From ec5fc151181f05ea75d94ae1bb3c91c2f957118f Mon Sep 17 00:00:00 2001 From: Rishabh Bafna Date: Fri, 20 Nov 2026 15:37:14 +0530 Subject: [PATCH] fix(artifacts): ensure monotonic versioning and isolate extensions in LocalArtifactStore - Parse numeric versions monotonically to avoid collisions when earlier versions are pruned - Check for existing version numbers across all file extensions before writing - Add unit test verifying version isolation when prior versions are removed --- lib/crewai/src/crewai/artifacts.py | 9 ++++++++- lib/crewai/tests/test_artifacts.py | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/crewai/src/crewai/artifacts.py b/lib/crewai/src/crewai/artifacts.py index 455268d639..da27fb0f41 100644 --- a/lib/crewai/src/crewai/artifacts.py +++ b/lib/crewai/src/crewai/artifacts.py @@ -225,8 +225,15 @@ def save( ) -> SavedArtifact: directory = self.root / execution_id / artifact.identifier directory.mkdir(parents=True, exist_ok=True) - version = len(list(directory.glob("v*.*"))) + 1 + existing_versions = [ + int(path.stem[1:]) + for path in directory.glob("v*.*") + if path.is_file() and path.stem[1:].isdigit() + ] + version = max(existing_versions, default=0) + 1 while True: + while any(directory.glob(f"v{version}.*")): + version += 1 path = directory / f"v{version}.{extension}" try: with path.open("xb") as file: diff --git a/lib/crewai/tests/test_artifacts.py b/lib/crewai/tests/test_artifacts.py index 1f1f3a304d..58f070308e 100644 --- a/lib/crewai/tests/test_artifacts.py +++ b/lib/crewai/tests/test_artifacts.py @@ -151,6 +151,32 @@ def test_tool_refuses_hidden_files(store, tmp_path, file_path): assert not (store.root / "exec-1" / "secret").exists() +def test_local_store_version_isolation_with_pruned_versions_and_extension_changes( + store, tmp_path +): + directory = tmp_path / "artifacts" / "exec-1" / "report" + directory.mkdir(parents=True, exist_ok=True) + (directory / "v1.html").write_text("

v1

") + (directory / "v2.svg").write_text("v2") + + # Simulate v1 being deleted/pruned + (directory / "v1.html").unlink() + + # Save artifact with different extension (png) + report = Artifact(identifier="report", title="Report", kind="image") + saved = save_artifact(report, content=b"\x89PNG\r\n\x1a\n") + + # Version must monotonically increment to 3 rather than colliding on 2 + assert saved.version == 3 + assert (directory / "v3.png").exists() + assert not (directory / "v2.png").exists() + + # Both surviving versions must load correctly + assert store.load("exec-1", "report", version=2) == b"v2" + assert store.load("exec-1", "report", version=3) == b"\x89PNG\r\n\x1a\n" + assert store.load("exec-1", "report") == b"\x89PNG\r\n\x1a\n" + + def test_rejects_bad_identifier(): with pytest.raises(ValueError): Artifact(identifier="Bad Id", title="x", kind="text")