Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
3 changes: 3 additions & 0 deletions skills/analysis-workflow/references/repos.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +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.
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.
13 changes: 11 additions & 2 deletions src/analysis_workflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path>` in a notebook
74 changes: 73 additions & 1 deletion src/analysis_workflow/provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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"])


Expand Down Expand Up @@ -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 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:
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["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:
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
Expand Down
58 changes: 57 additions & 1 deletion tests/test_provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
consolidated metadata.
"""

import datetime
import json
import shutil
import subprocess
Expand All @@ -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
Expand Down Expand Up @@ -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, 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)

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"): # 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"
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"
Expand Down
21 changes: 20 additions & 1 deletion tests/test_trace.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Tracing an artifact back through store records and declared inputs."""

import datetime
import os
import shutil
import time
Expand All @@ -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

Expand Down Expand Up @@ -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")
Expand Down
Loading