Blog ·

Know when a file your agent depends on is stale

Record which version of an input a report was made from, and one field on the report tells every later reader that the input has since changed.

The problem

One agent builds a report from an export. The next day the export is replaced, and the report is still there, with the same name and yesterday’s numbers. Nothing about it says it is out of date, so the next agent that picks it up trusts it.

At the end of this guide you have one Python file that stores an input and a report on Artefaktum, records which version of the input the report was made from, and shows the check a consumer makes before it trusts the report. You see the check answer “current”, then “stale” after the input changes, then a rebuilt report that is current. All output is from our own run against production on 16 November 2026, with the ids shortened.

What you need

Python 3.10 or newer, the Python SDK and an API key from the console:

pip install artefaktum==0.3.0
export ARTEFAKTUM_API_KEY=ak_...

The guide builds one file, stale.py, block by block. Paste the blocks in order and run the file at the end. It starts with the imports, two versions of a small export, and a list of what the run stores:

import sys
import tempfile

import httpx  # installed with the SDK, which sends its requests through it
from artefaktum import Artefaktum, MissingApiKey, NotFound

TAGS = ["blog-guide", "stale-inputs"]

MONDAY = "name,plan\nada,free\nbo,pro\n"
TUESDAY = MONDAY + "cy,pro\ndee,free\n"

# Every artifact this run stores, so the end of the run can delete them all.
created = []

An artifact is a stored file with a title, a description and tags. The input is one:

def store_input(client, text):
    """Store the input file the report will be made from."""
    signups = client.artifacts.push(
        text.encode(),
        filename="signups.csv",
        title="Signups export",
        description="One row per signup: name and plan.",
        tags=TAGS,
    )
    created.append(signups.id)
    return signups

Record where the report came from

The report builder downloads the input, counts the rows and stores the count as a second artifact. Then it adds a relation, a typed link from one artifact to another. derived_from says “this file was made from that one”:

def build_report(client, input_id, replaces=None):
    """Make a report from the input and record which version it was made from."""
    source = client.artifacts.get(input_id)
    with tempfile.TemporaryDirectory() as workdir:
        path = client.artifacts.pull(source.id, workdir)
        count = len(path.read_text().splitlines()) - 1

    report = client.artifacts.push(
        f"{count} signups\n".encode(),
        filename="signups-report.txt",
        title="Signups report",
        description=f"Number of signups in the export: {count}.",
        tags=TAGS,
    )
    created.append(report.id)

    # Where this file came from: the input, pinned to the version that was its
    # latest when this build looked it up. Without to_version_id a new version
    # of the input would go unnoticed.
    client.artifacts.add_relation(
        report.id, source.id, "derived_from", to_version_id=source.latest_version.id
    )
    if replaces:
        # A rebuilt report is a new artifact that takes the old one's place.
        client.artifacts.add_relation(report.id, replaces, "supersedes")
    return report

The add_relation call with to_version_id is the whole mechanism. Every upload to an artifact is a version, and versions are never overwritten. The relation pins the report to the version of the input that was the latest when the report was built. When the input’s latest version is no longer that one, the report is stale.

to_version_id is optional in the SDK, and it is easy to leave out. We tried that first: the relation was stored, the input got a new version, and the report’s stale_upstream stayed False. A relation without a version has nothing to compare against. Pass the version.

In the TypeScript SDK the same call is client.artifacts.addRelation(report.id, source.id, "derived_from", { to_version_id }); see the TypeScript SDK page.

The second relation, supersedes, belongs to the rebuild and is explained below.

The check a consumer makes

A consumer does not compare dates or hashes. It reads the report’s record and looks at two fields:

def check(client, report_id):
    """What a consumer does before it trusts a report: read two fields."""
    report = client.artifacts.get(report_id)
    print(f"  report {report.id}  {report.description}")
    print(f"    stale_upstream: {report.stale_upstream}")
    print(f"    superseded:     {report.superseded}")
    if report.superseded:
        print(f"    superseded_by:  {report.superseded_by}")
    return report

stale_upstream is True when something the artifact was derived from has moved on. superseded is True when another artifact has replaced this one, and superseded_by is that artifact’s id. The server works both out from the relations each time the record is read, so there is nothing to refresh.

The flag does not say which input moved. The relations do, because each one carries the version that was read. explain also says so when the input has been deleted, and when the relation names no version or one that is no longer listed:

def explain(client, report):
    """Say which input moved on: compare the version read with the latest one."""
    for relation in client.artifacts.relations(report.id):
        if relation.relation_type != "derived_from" or relation.direction != "outgoing":
            continue
        try:
            source = client.artifacts.get(relation.to_artifact_id)
        except NotFound:
            source = None
        if source is None or source.latest_version is None:
            print(f"    made from artifact {relation.to_artifact_id}, which has been deleted")
            continue
        latest = source.latest_version
        if relation.to_version_id is None:
            # The relation names no version, so there is nothing to compare.
            print(f"    made from {latest.filename}, version not recorded")
            continue
        numbers = {v.id: v.version_number for v in client.artifacts.versions(relation.to_artifact_id)}
        if relation.to_version_id not in numbers:
            print(
                f"    made from a version of {latest.filename} that is no longer listed, "
                f"the latest is version {latest.version_number}"
            )
            continue
        print(
            f"    made from version {numbers[relation.to_version_id]} of "
            f"{latest.filename}, the latest is version {latest.version_number}"
        )

Search results carry the same two fields, so a consumer that finds the report by search sees them without a second call:

def find_reports(client, exclude_superseded):
    """Search the way a consumer would, by tag and title."""
    hits = client.artifacts.search(
        "signups report", mode="text", tags_all=TAGS, exclude_superseded=exclude_superseded
    )
    for hit in hits.items:
        found = hit.artifact
        if found.title == "Signups report":
            print(
                f"  report {found.id}  stale_upstream: {found.stale_upstream}"
                f"  superseded: {found.superseded}"
            )

The three moments, and the rebuild

run plays the story in order: make the report, change the input, check, rebuild, check again, search.

def run(client):
    print("1. A report is made from the input")
    signups = store_input(client, MONDAY)
    report = build_report(client, signups.id)
    check(client, report.id)

    print("2. The input changes")
    signups = client.artifacts.create_version(
        signups.id, TUESDAY.encode(), filename="signups.csv"
    )
    print(f"  signups.csv is now at version {signups.latest_version.version_number}")

    print("3. A consumer checks the report before trusting it")
    stale = check(client, report.id)
    if stale.stale_upstream:
        explain(client, stale)

    print("4. The report is rebuilt, and the consumer checks again")
    rebuilt = build_report(client, signups.id, replaces=report.id)
    old = check(client, report.id)
    if old.superseded_by != rebuilt.id:
        raise SystemExit("the old report does not point to the rebuilt one")
    check(client, old.superseded_by)

    print("5. What search returns")
    find_reports(client, exclude_superseded=True)
    print("   and with exclude_superseded=False")
    find_reports(client, exclude_superseded=False)

The last block deletes everything the run stored, also when a step fails, and one failed delete does not stop the others. main creates the client, which reads ARTEFAKTUM_API_KEY from the environment. A network failure ends the run with one line that starts with failed: and status 1:

def delete_created(client):
    """Delete what this run stored. One failed delete does not stop the others."""
    failed = 0
    for artifact_id in created:
        try:
            client.artifacts.delete(artifact_id)
        except Exception as error:
            failed += 1
            print(f"could not delete {artifact_id}: {error}", file=sys.stderr)
    print(f"deleted {len(created) - failed} of {len(created)} artifacts")


def main():
    try:
        client = Artefaktum()
    except MissingApiKey:
        print("usage: ARTEFAKTUM_API_KEY=ak_... python stale.py", file=sys.stderr)
        return 2
    try:
        run(client)
    except httpx.TransportError as error:
        # The SDK does not wrap a network failure: httpx's own error reaches the caller.
        print(f"failed: {error}", file=sys.stderr)
        return 1
    finally:
        # Runs even when a step above fails, so nothing is left behind.
        delete_created(client)
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run it:

python stale.py

The first two moments. The report is current, then the input gets its second version:

1. A report is made from the input
  report 01a1e3bb-ee35-…  Number of signups in the export: 2.
    stale_upstream: False
    superseded:     False
2. The input changes
  signups.csv is now at version 2

The third moment. Nobody touched the report, and its record now says so:

3. A consumer checks the report before trusting it
  report 01a1e3bb-ee35-…  Number of signups in the export: 2.
    stale_upstream: True
    superseded:     False
    made from version 1 of signups.csv, the latest is version 2

There was no delay to wait out: the program reads the report right after create_version returns, and the flag is already True.

Rebuild as a new artifact

The obvious rebuild is a new version of the same report with a new relation. We tried it, and the report stayed stale: the relation to version 1 of the input is still on the artifact, and neither the SDK nor the REST API removes a relation. So a rebuilt report is a new artifact, with one derived_from relation to the input version it read and a supersedes relation to the report it replaces. The new artifact cannot take over the old report’s external_key, because a key belongs to one artifact in a project, so a consumer that finds reports by key needs another convention, such as following superseded_by. That is what build_report(..., replaces=report.id) does:

4. The report is rebuilt, and the consumer checks again
  report 01a1e3bb-ee35-…  Number of signups in the export: 2.
    stale_upstream: True
    superseded:     True
    superseded_by:  01a1e3bc-0095-…
  report 01a1e3bc-0095-…  Number of signups in the export: 4.
    stale_upstream: False
    superseded:     False

A consumer that still holds the old id is not stranded. The old record says it was replaced and by what, and the new report is current.

Search leaves superseded artifacts out unless you ask for them:

5. What search returns
  report 01a1e3bc-0095-…  stale_upstream: False  superseded: False
   and with exclude_superseded=False
  report 01a1e3bc-0095-…  stale_upstream: False  superseded: False
  report 01a1e3bb-ee35-…  stale_upstream: True  superseded: True
deleted 3 of 3 artifacts

A stale report that has not been superseded stays in search results, with stale_upstream: True on the hit. Search hides what was replaced, not what is out of date, so the consumer still has to read the flag.

What stale means here, and what it does not

We saw stale_upstream turn True on a report in four cases:

  • the input got a new version, and the relation named the version that was read;
  • the input was deleted (the flag followed about a second later);
  • the input passed its expires_at;
  • another artifact was marked as superseding the input.

The last three also worked for a relation without to_version_id. Only the new-version case needs it.

The limits are as plain:

  • The flag is computed from relations you recorded. A report stored without a derived_from relation is never stale, whatever happens to its input.
  • It compares version ids, not file contents.
  • A new version of an artifact does not make that artifact superseded. Only a supersedes relation from another artifact does.
  • Once the input has a new version, the flag does not clear on that report. Rebuild as a new one.
  • The server can also infer derived_from when a download and a later upload name the same run id. pull in version 0.3.0 of the Python SDK takes no run id, so from Python you record the relation yourself, as this program does.

To use the store with no account at all, see pay per request from Python.

This page as Markdown: /blog/know-when-a-file-your-agent-depends-on-is-stale.md