From ec73453be3efc4e11f20f080fb5da03f23f98f3e Mon Sep 17 00:00:00 2001 From: Marius1311 Date: Wed, 18 Nov 2026 14:40:05 +0100 Subject: [PATCH 1/3] `credit`: records for keys a store held before records were kept; release 0.11.0 A `writes` block records only what appears while it is open, so a repo that adopts the conventions could not make its existing stores traceable. `credit(store, keys, task=, at=)` adds the record such a block would have written, for keys no record covers, with the time the task wrote them; dry run by default. The adoption steps say how existing tasks and stores are brought in. Co-Authored-By: Claude Fable 5.2 --- .claude-plugin/plugin.json | 2 +- skills/analysis-workflow/references/repos.md | 11 +++ src/analysis_workflow/__init__.py | 13 +++- src/analysis_workflow/provenance.py | 74 +++++++++++++++++++- tests/test_provenance.py | 58 ++++++++++++++- tests/test_trace.py | 21 +++++- 6 files changed, 173 insertions(+), 6 deletions(-) diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 0b32fac..477a22e 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "analysis-workflow", - "version": "0.10.0", + "version": "0.11.0", "description": "Conventions for analysis repos where humans and coding agents work side by side: versioned task directories for both, one session, worktree and PR per agent task; worktree-safe output paths; additive write-back to AnnData and SpatialData stores, which record which task wrote what. Ships a skill, guard hooks and the analysis_workflow Python package.", "author": { "name": "quadbio" diff --git a/skills/analysis-workflow/references/repos.md b/skills/analysis-workflow/references/repos.md index b63bced..f603251 100644 --- a/skills/analysis-workflow/references/repos.md +++ b/skills/analysis-workflow/references/repos.md @@ -36,3 +36,14 @@ beside their other repos). Then: `.github/pull_request_template.md`. 6. In `AGENTS.md`, one short section naming the plugin and where the working objects live; delete restated rules. 7. `uvx cruft link https://github.com/quadbio/analysis_template`, so the repo receives the template's updates. + +Task directories and shared stores that predate the conventions are then made traceable. This edits earlier task +directories and writes to shared storage, so the human approves it first and the PR notes it as an exception: + +1. Each task README gets the template's header lines: `**Author:**`, and `**Id:**` with a new + `secrets.token_hex(4)`. +2. The `declare-inputs` skill on each task. +3. For each store, work out from the code and the READMEs which task wrote which keys, and when. After the human's + sign-off on the dry run, `credit(store, keys, task=, at=, yes=True)` once per task and + store, until `analysis-workflow check provenance ` is clean. An AnnData store with consolidated + metadata is rewritten first (`write_zarr(..., consolidate_metadata=False)`). diff --git a/src/analysis_workflow/__init__.py b/src/analysis_workflow/__init__.py index c482594..44da93c 100644 --- a/src/analysis_workflow/__init__.py +++ b/src/analysis_workflow/__init__.py @@ -3,11 +3,20 @@ from importlib.metadata import version from analysis_workflow.paths import TaskPaths, main_checkout, task_paths -from analysis_workflow.provenance import register_magic, writes +from analysis_workflow.provenance import credit, register_magic, writes from analysis_workflow.size import analyze_anndata_size from analysis_workflow.working import commit_adata, keys_on_disk -__all__ = ["TaskPaths", "analyze_anndata_size", "commit_adata", "keys_on_disk", "main_checkout", "task_paths", "writes"] +__all__ = [ + "TaskPaths", + "analyze_anndata_size", + "commit_adata", + "credit", + "keys_on_disk", + "main_checkout", + "task_paths", + "writes", +] __version__ = version("analysis-workflow") register_magic() # `%%writes ` in a notebook diff --git a/src/analysis_workflow/provenance.py b/src/analysis_workflow/provenance.py index a4c5237..caed8d7 100644 --- a/src/analysis_workflow/provenance.py +++ b/src/analysis_workflow/provenance.py @@ -7,6 +7,9 @@ of them covers, so copying an object keeps each key with the task that made it. The block that writes a copy drops from those records the keys the copy did not keep. +A store older than its records gets them from `credit`, which adds the record a block would have written for keys +that are already there. + The stores are read as zarr groups, in format 2 or 3, so SpatialData is not imported. In an existing store only children are ever added under ``uns/provenance``: rewriting that group's metadata would replace the file another node is reading. @@ -100,7 +103,10 @@ def _named(path) -> dict[str, dict]: def records(path) -> list[dict]: - """The records in the store at ``path``, oldest first: ``{"task", "path", "branch", "keys", "at"}`` each.""" + """The records in the store at ``path``, oldest first: ``{"task", "path", "branch", "keys", "at"}`` each. + + One added by `credit` also holds ``recorded``, when it was added. + """ return sorted(_named(path).values(), key=lambda record: record["at"]) @@ -238,6 +244,72 @@ def writes(path, *, task: TaskPaths | str | Path | None = None): raise ValueError(problem) +def credit(path, keys, *, task: TaskPaths | str | Path, at: datetime.datetime, yes: bool = False) -> list[str]: + """Credit ``keys`` that are already in the store at ``path`` to the task that wrote them. + + For a store older than its records, in a repo that adopts these conventions: a `writes` block records only + what appears while it is open. Dry run by default: with ``yes=False`` the record is logged and nothing is + written. + + Parameters + ---------- + keys + The keys to credit, named as the store's records name them: ``obs/leiden``, ``X``, ``shapes/cells``. + task + The directory of the task that wrote them. + at + When it wrote them; without a time zone, in UTC. A trace of a whole store follows only the records + older than what was made from it. + + Returns + ------- + The keys credited (or that would be credited). + + Raises + ------ + KeyError + If a key is not in the store, or a record already covers it. + ValueError + If the task's README has no id, ``at`` is in the future, the store already holds a record of this task + at ``at``, ``path`` is no store, or it is an AnnData store with consolidated metadata. + """ + path, credited, wanted = Path(path).resolve(), _task(task), sorted(set(keys)) + if (identity := task_id(credited.task)) is None: + raise ValueError(f"{credited.task / 'README.md'} has no `**Id:**` line to record the keys under.") + if _kind(path) is None: + raise ValueError(f"{path} is not an AnnData or SpatialData store: it can hold no record.") + if _consolidated(path): + raise ValueError(CONSOLIDATED.format(path=path)) + at = at.replace(tzinfo=datetime.UTC) if at.tzinfo is None else at.astimezone(datetime.UTC) + now = datetime.datetime.now(datetime.UTC) + if at > now: + raise ValueError(f"{at.isoformat()} is in the future: `at` is when the task wrote the keys.") + found, bare = records(path), set(uncovered(path)) + if covered := sorted({k for record in found for k in record["keys"]} & set(wanted)): + raise KeyError(f"A record of {path} already covers: {', '.join(covered)}.") + if absent := [k for k in wanted if k not in bare]: + raise KeyError(f"Not in {path}: {', '.join(absent)}.") + checkout, _ = _checkouts_of(credited.task) + record = { + "task": identity, + "path": credited.task.relative_to(checkout).as_posix(), + "branch": None, + "keys": wanted, + "at": at.strftime(TIME), + "recorded": now.strftime(TIME), + } + if any((r["task"], r["at"]) == (record["task"], record["at"]) for r in found): + raise ValueError(f"{path} already holds a record of {record['path']} at {record['at']}.") + listed = "\n".join(f" {k}" for k in wanted) or " nothing to credit" + logger.info("Crediting to %s, as written %s, in %s:\n%s", record["path"], record["at"], path, listed) + if not yes or not wanted: + if not yes: + logger.info("Dry run (yes=False): %s unchanged. Re-run with yes=True to write.", path) + return wanted + _write(path, record) + return wanted + + def is_open(path) -> bool: """Whether a `writes` block for the store at ``path`` is open in this process.""" return Path(path).resolve() in _open diff --git a/tests/test_provenance.py b/tests/test_provenance.py index 3347964..235f360 100644 --- a/tests/test_provenance.py +++ b/tests/test_provenance.py @@ -5,6 +5,7 @@ consolidated metadata. """ +import datetime import json import shutil import subprocess @@ -17,7 +18,7 @@ import zarr from typer.testing import CliRunner -from analysis_workflow import commit_adata, writes +from analysis_workflow import commit_adata, credit, writes from analysis_workflow.cli import app from analysis_workflow.paths import task_id from analysis_workflow.provenance import keys, records, uncovered @@ -312,6 +313,61 @@ def test_check_provenance(store): assert "obsm/X_stray" in stray.output and "1 item(s) to look at." in stray.output +def test_credit_records_keys_older_than_the_records(tmp_path, adata, task, other): + """A store written before records were kept: each key goes to its task, at the time it was written.""" + path = tmp_path / "old.zarr" + adata.write_zarr(path, consolidate_metadata=False) # outside a block + assert records(path) == [] and uncovered(path) == ["X", "obs/a", "obsm/X_pca"] + then = datetime.datetime(2026, 1, 27, 12, tzinfo=datetime.UTC) + + assert credit(path, ["X", "obs/a"], task=task, at=then) == ["X", "obs/a"] # a dry run + assert records(path) == [] + + credit(path, ["X", "obs/a"], task=task, at=then, yes=True) + credit(path, ["obsm/X_pca"], task=other, at=then + datetime.timedelta(days=1), yes=True) + first, second = records(path) + assert (first["path"], first["keys"]) == ("analysis/topic/demo_v1", ["X", "obs/a"]) + assert first["at"] == "2026-01-27T12:00:00.000000Z" < first["recorded"] and first["branch"] is None + assert second["path"] == "analysis/topic/other_v1" and uncovered(path) == [] + assert len(ad.read_zarr(path).uns["provenance"]) == 2 + + adata.obsm["X_new"] = np.zeros((20, 2)) + with writes(path, task=other): # a later block records only what it adds + commit_adata(adata, path, keys={"obsm": ["X_new"]}, yes=True) + assert records(path)[-1]["keys"] == ["obsm/X_new"] + + +def test_credit_refuses_what_it_cannot_record(tmp_path, adata, task, store): + then = datetime.datetime(2026, 1, 27) + with pytest.raises(KeyError, match="already covers: X"): + credit(store, ["X"], task=task, at=then, yes=True) + + old = tmp_path / "old.zarr" + adata.write_zarr(old, consolidate_metadata=False) + with pytest.raises(KeyError, match="Not in .*: obs/absent"): + credit(old, ["obs/absent"], task=task, at=then, yes=True) + with pytest.raises(ValueError, match="in the future"): + credit(old, ["X"], task=task, at=datetime.datetime.now(datetime.UTC) + datetime.timedelta(days=1)) + credit(old, ["X"], task=task, at=then, yes=True) + with pytest.raises(ValueError, match="already holds a record"): + credit(old, ["obs/a"], task=task, at=then, yes=True) + assert [r["keys"] for r in records(old)] == [["X"]] + + consolidated = tmp_path / "cons.zarr" + adata.write_zarr(consolidated, consolidate_metadata=True) + with pytest.raises(ValueError, match="consolidated metadata"): + credit(consolidated, ["X"], task=task, at=then, yes=True) + with pytest.raises(ValueError, match="not an AnnData or SpatialData store"): + credit(tmp_path / "registry.csv", ["X"], task=task, at=then, yes=True) + + +def test_credit_in_a_spatialdata_store(tmp_path, adata, task): + path = tmp_path / "section.zarr" + spatial_store(path, adata) + credit(path, uncovered(path), task=task, at=datetime.datetime(2026, 1, 27), yes=True) + assert uncovered(path) == [] and len(zarr.open_group(str(path), mode="r").attrs["provenance"]) == 1 + + def test_a_task_without_an_id_cannot_write(tmp_path, adata, task): """The id is in the README's header, from `analysis-workflow new`; without one nothing is written.""" assert task_id(task) == "0a1b2c3d" diff --git a/tests/test_trace.py b/tests/test_trace.py index 83dc5ed..a0ecdd0 100644 --- a/tests/test_trace.py +++ b/tests/test_trace.py @@ -1,5 +1,6 @@ """Tracing an artifact back through store records and declared inputs.""" +import datetime import os import shutil import time @@ -11,7 +12,7 @@ import yaml from typer.testing import CliRunner -from analysis_workflow import commit_adata, writes +from analysis_workflow import commit_adata, credit, writes from analysis_workflow.cli import app from analysis_workflow.trace import changed_since_declared, declared, missing_inputs, trace @@ -158,6 +159,24 @@ def write_backs_behind_the_figure(age): assert write_backs_behind_the_figure(age=3600) == 0 # older than both: the store is a leaf with no record +def test_a_credited_key_is_traced_at_the_time_it_was_written(project): + """A store older than its records: `credit` gives a key its task, and its time decides what a whole store held.""" + main, tasks = project + old = "data/ds/processed/working/old.zarr" + ad.AnnData(np.ones((3, 2), dtype="float32")).write_zarr(main / old, consolidate_metadata=False) # outside a block + bare = trace(main / old, "X", start=main) + assert bare.nodes[bare.target]["status"] == "no record" + + two_days_ago = datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=2) + credit(main / old, ["X"], task=tasks["agent_build_v1"], at=two_days_ago, yes=True) + found = trace(main / old, "X", start=main) + assert names(found) == ["agent_build_v1"] and found.nodes[RAW]["status"] == "source" + + declare(tasks["human_fig_v1"], [{"path": old, "keys": ["*"]}]) + os.utime(main / FIGURE, (time.time() - 86400,) * 2) # made a day ago: after the credited write, before now + assert "agent_build_v1" in names(trace(main / FIGURE, start=main)) + + def test_a_key_without_a_record_and_a_task_that_is_gone(project): main, tasks = project root = __import__("zarr").open_group(str(main / STORE), mode="a") From 94e8c3eb534d4db5ec78fd1e9308b23982c5aac1 Mon Sep 17 00:00:00 2001 From: Marius1311 Date: Wed, 18 Nov 2026 14:42:34 +0100 Subject: [PATCH 2/3] `credit`: refuse a time another record of the store already has A trace tells a store's records apart by their time, so two tasks credited at the same time would merge. Co-Authored-By: Claude Fable 5.2 --- src/analysis_workflow/provenance.py | 8 ++++---- tests/test_provenance.py | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/analysis_workflow/provenance.py b/src/analysis_workflow/provenance.py index caed8d7..9531b68 100644 --- a/src/analysis_workflow/provenance.py +++ b/src/analysis_workflow/provenance.py @@ -270,8 +270,8 @@ def credit(path, keys, *, task: TaskPaths | str | Path, at: datetime.datetime, y KeyError If a key is not in the store, or a record already covers it. ValueError - If the task's README has no id, ``at`` is in the future, the store already holds a record of this task - at ``at``, ``path`` is no store, or it is an AnnData store with consolidated metadata. + If the task's README has no id, ``at`` is in the future or the time of another record of the store, + ``path`` is no store, or it is an AnnData store with consolidated metadata. """ path, credited, wanted = Path(path).resolve(), _task(task), sorted(set(keys)) if (identity := task_id(credited.task)) is None: @@ -298,8 +298,8 @@ def credit(path, keys, *, task: TaskPaths | str | Path, at: datetime.datetime, y "at": at.strftime(TIME), "recorded": now.strftime(TIME), } - if any((r["task"], r["at"]) == (record["task"], record["at"]) for r in found): - raise ValueError(f"{path} already holds a record of {record['path']} at {record['at']}.") + if any(r["at"] == record["at"] for r in found): # a store's records are told apart by their time + raise ValueError(f"{path} already holds a record written {record['at']}: give this one another time.") listed = "\n".join(f" {k}" for k in wanted) or " nothing to credit" logger.info("Crediting to %s, as written %s, in %s:\n%s", record["path"], record["at"], path, listed) if not yes or not wanted: diff --git a/tests/test_provenance.py b/tests/test_provenance.py index 235f360..7d27729 100644 --- a/tests/test_provenance.py +++ b/tests/test_provenance.py @@ -337,7 +337,7 @@ def test_credit_records_keys_older_than_the_records(tmp_path, adata, task, other assert records(path)[-1]["keys"] == ["obsm/X_new"] -def test_credit_refuses_what_it_cannot_record(tmp_path, adata, task, store): +def test_credit_refuses_what_it_cannot_record(tmp_path, adata, task, other, store): then = datetime.datetime(2026, 1, 27) with pytest.raises(KeyError, match="already covers: X"): credit(store, ["X"], task=task, at=then, yes=True) @@ -349,8 +349,8 @@ def test_credit_refuses_what_it_cannot_record(tmp_path, adata, task, store): with pytest.raises(ValueError, match="in the future"): credit(old, ["X"], task=task, at=datetime.datetime.now(datetime.UTC) + datetime.timedelta(days=1)) credit(old, ["X"], task=task, at=then, yes=True) - with pytest.raises(ValueError, match="already holds a record"): - credit(old, ["obs/a"], task=task, at=then, yes=True) + with pytest.raises(ValueError, match="already holds a record"): # a trace tells a store's records apart by time + credit(old, ["obs/a"], task=other, at=then, yes=True) assert [r["keys"] for r in records(old)] == [["X"]] consolidated = tmp_path / "cons.zarr" From 8ae4755641c89fe58383086b86817625e148731e Mon Sep 17 00:00:00 2001 From: Marius1311 Date: Wed, 18 Nov 2026 15:08:27 +0100 Subject: [PATCH 3/3] Adopting: one generic step for stores without records; the migration-specific steps removed Co-Authored-By: Claude Fable 5.2 --- skills/analysis-workflow/references/repos.md | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/skills/analysis-workflow/references/repos.md b/skills/analysis-workflow/references/repos.md index f603251..07f15bd 100644 --- a/skills/analysis-workflow/references/repos.md +++ b/skills/analysis-workflow/references/repos.md @@ -36,14 +36,6 @@ beside their other repos). Then: `.github/pull_request_template.md`. 6. In `AGENTS.md`, one short section naming the plugin and where the working objects live; delete restated rules. 7. `uvx cruft link https://github.com/quadbio/analysis_template`, so the repo receives the template's updates. - -Task directories and shared stores that predate the conventions are then made traceable. This edits earlier task -directories and writes to shared storage, so the human approves it first and the PR notes it as an exception: - -1. Each task README gets the template's header lines: `**Author:**`, and `**Id:**` with a new - `secrets.token_hex(4)`. -2. The `declare-inputs` skill on each task. -3. For each store, work out from the code and the READMEs which task wrote which keys, and when. After the human's - sign-off on the dry run, `credit(store, keys, task=, at=, yes=True)` once per task and - store, until `analysis-workflow check provenance ` is clean. An AnnData store with consolidated - metadata is rewritten first (`write_zarr(..., consolidate_metadata=False)`). +8. The shared stores the repo already holds have no record of who wrote their keys, so a trace ends at them. Where + the code shows which task wrote which keys, and when, `credit` records it, after the human's sign-off on its + dry run.