Skip to content

Caching and the scratch#

Analysis over a CaptureGraph dataset is longitudinal: the dataset grows, and the naive "process everything" script redoes nearly all of its work on every run. The scratch fixes that. You write decomposed pure functions over loaded values — recipes — and pretend the filesystem doesn't exist: intermediates are stored for you in a managed, content-addressed directory, keyed by content hash, and reused whenever the same inputs recur. Because the captured data on disk is durable, every memoized result the scratch holds is recomputable, so the cache is pure speedup; the one exception is ImpureState, which is durable state the scratch is asked to keep.

A recipe takes and returns the values cg.load hands back. Loading Captures loads a Survey whose sessions is a cg.Map[cg.Date, Session] and whose sessions carry a photo: cg.Image; survey.sessions.photo is then an Array of images, and a recipe over one image maps over all of them:

import capturegraph as cg

survey = cg.load("/path/to/MySurvey", Survey)


@cg.pure_function("thumbnail/1")
def thumbnail(image: cg.Image) -> cg.Thumbnail:
    thumb = cg.Thumbnail.new()  # a fresh path in this call's workspace; no file yet
    small = image.pil()
    small.thumbnail((256, 256))
    small.save(thumb)
    return thumb


thumbs = survey.sessions.photo.pmap(thumbnail)  # first run computes; later runs hit

Every value a recipe takes or returns is a CGType: a cg.Struct subclass, a cg.Array or cg.Map of them, or a scalar — a JSON scalar such as cg.Number (cg.Number(3).value == 3), or a file scalar such as cg.Image, whose value is the file's path. Each knows how to store and load itself as a directory tree, and that tree is what the scratch hashes. Types and Nodes is the vocabulary; Containers is how Array and Map broadcast, map and pmap.

The unit of reuse is the function call: thumbnail(photo) is memoized on ("thumbnail/1", hash(photo)). Edit one stage of a pipeline and only that stage and its dependents recompute; add new captures and only the new ones are processed. That is the whole point — recompute only what's new. A recipe is an ordinary function: you call it, and there is no event loop, no await, no runtime to spin up.

Where recipes run#

The same function runs in two places, and nothing about it changes between them:

  • Outside the server — a script or notebook over a target you copied off a phone or pulled with sync. cg.load the target and call your recipes; re-run the script as the dataset grows and only the new captures compute.
  • Inside the server — an interceptor. The server opens the machine's shared scratch at startup and exports CG_SCRATCH to every process it starts, so an interceptor just calls the recipe, and a script on the same machine hits what the server computed. Pure functions memoize expensive work across requests; ImpureState holds the coordination state a crowd needs, such as a reservation book. From Zero to a Scheduled Target builds one.

Tests get an isolated, auto-deleted scratch from the cg_scratch pytest fixture.

The scratch#

Every file-producing recipe operation runs against a scratch: a garbage-collected, content-addressed directory the library manages. One scratch serves every process on the machine — scripts, notebooks, the server and its workers — so work any of them computed is a hit for the rest. A process opens its scratch on first use, by precedence:

  1. an explicit cg.scratch.configure(path),
  2. the CG_SCRATCH environment variable,
  3. ~/.cache/capturegraph (cg.scratch.default_root() names the one in effect).

Leave configure out to share; set CG_SCRATCH to move the shared scratch. configure() without a path opens the shared one with size settings:

cg.scratch.configure(max_size_gb=50)

Setting overrides (max_size_gb, free_space_ratio) persist into the scratch's settings.toml, which is read fail-soft on later opens. The index carries a layout version: a scratch written by an older layout is migrated in place on open where the change allows, and otherwise emptied and rebuilt — objects/ deleted with it — so an upgrade never refuses a scratch or waits for someone to delete one.

For tests, cg.scratch.temporary() is a context manager that installs a throwaway scratch and deletes its tree on exit; the shipped cg_scratch pytest fixture wraps it. Analysis code and notebooks always run against a durable configured scratch: a throwaway one defeats the caching model and hides state from the store's bookkeeping, and per-run isolation comes from an ImpureState key, never from a throwaway scratch. configure sets the default every thread shares; temporary overrides it for the calling thread or task only, so a throwaway scratch in one thread never redirects the work another is doing. A thread you start yourself begins without the override; pmap carries it into its workers.

A scratch is four ideas and nothing else: objects exist, names reference them, a pin keeps an object alive while a running process holds it, and a lock serializes the writers of one state, the computation of one call, or the users of one machine-wide resource.

Concept Where it lives What it means
object objects/<hash>/ an immutable value tree, named by its own merkle hash; its files are write-protected on disk
name names row a name resolving to one object; kept names are never evicted
pin pins row one living process's hold on an object
lock locks/state/<key> the flock serializing writers of one ImpureState key
lock locks/call/<key> the flock held by whoever is computing one memoized call
lock locks/resource/<name> the flock held by whoever is using one machine-wide resource (gpu)
<root>/
  .gitignore             "*" — the root ignores itself
  objects/<hash>/        immutable value trees
  live/<owner>/<n>/      that process's in-progress workspaces, one per call
  locks/<owner>          the process liveness flock
  locks/state/<key>      one flock per ImpureState key
  locks/call/<key>       one flock per memoized call being computed
  locks/resource/<name>  one flock per machine-wide resource in use
  settings.toml
  index.sqlite           tables: objects, names, pins
  hashes.sqlite          file_hashes: leaf hashes remembered by path and stat
  open.lock              the flock one process at a time opens the scratch under

An <owner> is <pid hex>-<boot nonce hex>, one per process that has the scratch open. A cached call result is one name per declared return position, call:<call_key>/<position>: call:<key>/0 for a single return, /0 and /1 for a tuple[A, B], and a hit needs every position present — one evicted is no hit. An ImpureState is the name state:<class identity>\x1f<key>, which is kept; the name carries the class's identity (module.QualName@<schema digest>) as well as the key, so two states with the same key never meet. Eviction ranks objects rows and never takes one a kept name holds or a living process pins. live/<owner>/ is owned by construction — the process that made it is the only one that writes it — and is reclaimed by the next process that opens the scratch, whose reconcile deletes every live/ directory whose liveness flock is free, so a crash leaves nothing to reason about, only something to sweep.

One filesystem underlies all of it, so sealing a result from live/ into objects/ is an atomic rename (an object that already exists — from any call — dedups to the one copy), and any number of processes sharing a scratch path co-operate through the index and file locks — a shared cache across every analysis job and server on the machine.

The index admits one writer at a time, so no write transaction walks the filesystem: a tree is hashed, measured, and moved into objects/ first, and one short transaction then indexes, names, and pins it. Reads take a snapshot and never wait. A writer waits up to two minutes for the index before the call fails with a ScratchError naming it. The hash cache lives in its own file, so hashing a large tree never holds the index. Opening is serialized by open.lock, so an index of an older layout is migrated or rebuilt by exactly one process before any other reads it.

You never name a path in objects/ or move a file there yourself. A body that produces a new file asks its type for one — cg.Image.new("jpeg"), cg.Thumbnail.new(), cg.ManagedDir.new() — writes to it, and returns it, as thumbnail above does. The extension names one of the type's declared extensions and is inferred when the type declares exactly one. Every call runs with one live workspace, and new allocates inside it, so what the body writes seals with its result; the framework hashes the file and files it flat into objects/ on the way out. The same new works outside any call too — in a script or a test — where the value gets a workspace of its own for as long as it is held. That is what "pretend the filesystem doesn't exist" means in practice: inputs are values, outputs come from new, and nothing else touches a path.

Eviction: utility density#

The cache is bounded by budget = min(max_size_gb, free_space_ratio × (available + current cache)) — free_space_ratio defaults to 0.5 and max_size_gb to no cap — and the scratch keeps it under budget by evicting entries. Which entries matters, and the choice is the research-relevant part.

Each entry carries a use score: a leaky integrator over its access times (score = prev·e^(−Δt/decay) + (1 − e^(−Δt/recharge)), with a decay of 7 days and a recharge of 1 hour), which estimates the entry's future use rate. Eviction does not rank by score alone. It ranks candidates ascending by utility density:

$$ \text{density} = \frac{\text{effective_score}(now) \times \text{compute_seconds}}{\text{size_bytes}} $$

Read the units: (uses/second) × (compute-seconds/use) ÷ bytes = compute-seconds saved per second, per byte. It is a value density — how much recomputation each stored byte spares the machine per unit time. Evicting the lowest-density entries first is exactly the greedy knapsack heuristic, near-optimal while individual entries are small against the budget. An object's compute_seconds is the measured body wall-time of the costliest call that ever produced it, so a result several recipes share is priced at what losing it would really cost; a floor of 1 ms and 1 byte keeps a free, empty result from dividing by zero.

With multiple processes sharing one scratch, every job's usage aggregates into one ranking: the scratch becomes a global allocator of disk to compute, continuously maximizing total compute-time saved per byte across the whole machine, with no per-process tuning.

The honest boundaries: this is single-machine only — flock, statvfs, and SQLite WAL are unreliable on network filesystems, so put the scratch on a local disk. And because cross-process access bumps interleave, the scores are order-approximate (elapsed time is clamped to ≥ 0 so a stale bump can never inflate a score); the reordering that causes is bounded and acceptable for a heuristic.

pure_function#

@cg.pure_function(identity=None) memoizes a function over CGType values.

Identity and the stale-serve contract. The identity keys every cache entry, and its two forms have sharply different invalidation behavior:

  • A versioned identity — @cg.pure_function("thumbnail/1") — means you own invalidation. The identity never changes with the code, so editing the body without bumping the version keeps serving the old cached result, deliberately. Bump to "thumbnail/2" to invalidate. This is the contract, not a bug — version-pin a stable stage and you control exactly when its cache resets.
  • The bare form — @cg.pure_function — digests the compiled body: its bytecode, its constants, and the global names it references. A change to the code itself invalidates; a comment or a local rename does not, and neither does editing a function it calls. Convenient while iterating; use a versioned identity for anything long-lived.

The return annotation is required and load-bearing: it is the schema the result is stored and loaded with. A tuple[A, B] return is stored one position per element and hits only when every position is present.

Hashability of arguments is crisp. An argument hashes by its structure, in one walk: a struct by its field names and their values' hashes, a map by its encoded keys and theirs, an array by its elements in order; a file by its extension and bytes, a directory by its tree, a JSON scalar by the bytes it stores as, and a Missing by its reason. The class holding a value never enters the hash, and neither does the type its parameter declares, so a value loaded from disk, an equal one built in memory and one built from a re-executed target module all hit the same key. File bytes are hashed once: the scratch remembers each file's hash for as long as its size, mtime and inode are unchanged.

A loaded struct, map or array is read-only (Loaded values are read-only), so it remembers its hash after the first walk; an in-memory one is walked again on every call, its loaded parts answering from memory. A file rewritten after the load leaves the loaded container keyed by the bytes it was first hashed with; the next load keys the new ones. A file or directory on its own is hashed on every call, so a directory a workspace refines in place keys by what it holds now.

A result's files are stored as cheaply as the filesystem allows: a file already in the scratch (made by the call with T.new(), or a cached result passed through) is hard-linked, since nothing there is written in place; any other file is cloned copy-on-write where the filesystem can (btrfs, XFS) and copied where it cannot (ext4). A capture file is never linked, so editing it cannot change a cached result.

A result the scratch hands back is cg.held(value), and so is every part of it (result.sessions, one session's photo): its files exist only while a value holding them does, pinned against eviction. Plain int/float/bool/str/bytes/None, datetime/date/timedelta, and tuples, lists, dicts, and frozensets of those get canonical tagged encodings (so 1, 1.0, and True never collide; dicts are key-sorted). Each plain type is one registered encoder in the scratch's plain module. Anything else — a raw NumPy array, say — raises UnhashableArgumentError naming the parameter; wrap it as a CGType first.

Plain and typed values hash apart. cg.Array([1.0]) and cg.Array[cg.Number]([cg.Number(1.0)]) are different keys: one holds a plain float, the other a JSON scalar. Pass a value the same way each time to share an entry; the worst a mismatch costs is a recompute, never a wrong hit.

Every result is cached. There is no admission threshold: the output is already in live/, so sealing it is an atomic rename plus one index row, and utility-density eviction flushes whatever fails to earn its bytes back. A hit costs one index read, a pin, and a metadata-weight load (about a millisecond), so wrapping even a fast stage is fine; a function that must not be cached is a plain function.

A Missing argument yields Missing. A call with a Missing anywhere in its arguments returns Missing without running or caching, so absence chains through a recipe the way it chains through attribute access: thumbnail(session.photo) is Missing for a session with no photo.

A Missing result is never cached. A body that returns Missing (in any position of a tuple return) gets its result back but nothing is sealed, so the next call runs the body again. A container result with Missing elements is cached: each such element stores as its <entry>.cg-missing marker and loads back as Missing, so images.map(step, on_error="missing") seals with a gap where step raised.

Calling is just calling. A decorated function is an ordinary synchronous callable:

result = thumbnail(image)

That holds everywhere — a script, a server request handler running in a worker thread, a notebook cell. There is nothing to await and no loop to drive.

Claiming a miss. However many callers reach the same miss together — worker threads, uvicorn workers, separate jobs on one machine — the body runs once. A caller that finds no sealed result takes an exclusive flock on locks/call/<key>, looks the key up again under it, and only then runs the body; everyone else blocks on that lock until the first caller seals, then finds the result and hits. The kernel drops the lock on any death, so a crashed claimant frees the key and the next waiter computes. Callers block for as long as the body takes: the call lock has no timeout, and there is no duplicate work. Whether a call is in flight somewhere is a separate question with a separate answer: the scratch's memo(key) — key from thumbnail.key(image) — reports computing while anyone holds the key's call lock, in this process or another, and results once it has sealed.

Progress, and the exec log#

A body that runs for minutes is visible while it runs, through cg.logging: a memoized call is a log scope named after its function, a map or pmap a count of its elements, a cache hit one line saying so, and a body of its own says more with cg.logging.info and cg.logging.progress. Nothing is recorded unless a cg.logging.to() block is listening — a terminal, a notebook, or the server computing a page.

with cg.logging.to(cg.logging.Terminal()):
    thumbs = survey.sessions.photo.pmap(thumbnail)

On a terminal that block redraws the open entries in place, indented two spaces per level, and prints each one once more as it closes. Midway through the pmap above it shows something like:

thumbnail  [########------------] 8/20  3.1s
  worker 1  4  3.1s
    thumbnail  identity=thumbnail/1  0.4s  (iteration 5)
  worker 2  4  3.0s
    thumbnail: cached  (iteration 5)

The count is named after the mapped function, each pool thread is a worker count beneath it showing the elements it has finished, and each element is one turn of its worker, so what an element logs is tagged with its turn: a miss opens a thumbnail scope carrying the identity, a hit is the one cached line. A map or pmap a body makes sits beneath that body's scope the same way, and a pmap inside a worker runs sequentially as a plain count.

The other record is the exec log. A tool a body runs through exec (below) streams its combined stdout and stderr, as they arrive, into exec.log at the root of the call's workspace — outside every result, so it never seals into the object — and the last 40 lines into one tail entry beneath the command's $ <command> log scope, rewritten in place as output arrives, so a page or terminal shows what the tool is saying. When a call raises, its workspace is released, and the exception carries those last 40 lines as a note, so the failure explains itself wherever it is reported: the call's scope ends failed with that text.

Global locks#

Some work must not overlap: two models training at once exhaust the GPU. A resource of the machine gets a named lock, and a body that needs it holds the lock for the block:

@cg.pure_function("train_model/1")
def train_model(dataset: cg.ManagedDir) -> cg.ManagedDir:
    work = cg.ManagedDir.new()
    work.stage(dataset, "data")
    with cg.lock("gpu"):
        work.exec(["ns-train", "splatfacto", "--data", "data", "--output-dir", "outputs"])
    return work / "outputs"

The lock is an exclusive flock on locks/resource/<name>, so holders serialize across every thread, uvicorn worker and script sharing the scratch, and the kernel frees it on any kind of death: a crashed trainer never wedges the GPU. "gpu" is the one conventional name; any other string is a lock of its own.

The wait is visible. lock opens a log scope <name> lock. On acquiring, the holder writes a note into the lock file — <purpose> (pid <pid>) since <epoch seconds>, where the purpose is the innermost open log scope's message (inside a memoized call, its name) or, outside any scope, the calling function's name. A waiter reads that note back once a second and updates its scope's message from it: gpu lock: waiting for train_model (pid 4242), held 5m12s. Once acquired the message becomes gpu lock: held and the scope stays open for the block, so a computing page or a terminal shows a run waiting for the GPU as exactly that, and shows what is holding it while it does.

Nesting passes through. The names a context holds live in a context variable, so a lock of a name the context already holds runs its block at once, and a pmap worker of a held block, running in a copy of the caller's context, does the same: holding the GPU and mapping a recipe that also locks it never waits on itself. A thread you start yourself begins without the hold and waits like any other caller.

A lock is scoped to the scratch, which is what the machine's jobs share; two scratch roots on one machine do not exclude each other.

ImpureState — keyed persistent state#

Some state persists and changes between calls: a reservation ledger a fleet of server workers bumps, a COLMAP reconstruction refined by every new batch of images. cg.ImpureState gives them exactly one home. Subclass it like a cg.Struct — the annotated fields ARE the persistent state — and declare the operations as ordinary methods. open(key) names one state and returns a handle, not a loaded value: every method call on it is a whole serialized read-modify-write, and reading a field off it raises a TypeError pointing at peek().

from datetime import UTC, datetime


class ReservationBook(cg.ImpureState):
    held: cg.Map[cg.UserID, cg.Time]  # granted slots, keyed by user

    def reserve(self, user_id: str, slot: datetime) -> bool:
        held: dict[str, cg.Time] = {}
        if not cg.is_missing(self.held):
            held = {user.identifier: when for user, when in self.held.items()}
        if any(when.value == slot for when in held.values()):
            return False
        held[user_id] = cg.Time(slot)
        self.held = cg.Map(held)
        return True


book = ReservationBook.open("MySurvey")
granted = book.reserve("alice", datetime(2026, 9, 14, 9, tzinfo=UTC))

Inside a method, self IS the current state: read its fields, assign its fields. The framework loads the committed state before the method runs and atomically commits self after it returns; the first call for a key seeds the state from the class's field defaults, and a field without a default starts Missing (test with cg.is_missing, as reserve does). Because operations are methods over one class, several operations naturally share one state — a book with reserve and release is one class with two methods, not two functions with two disjoint states.

State is a name over objects/, not a mutable file. Every committed version is a sealed immutable object named by its own merkle; an update seals the new version and atomically repoints the state: name at it. Two consequences fall out for free:

  • Crash safety. A crash anywhere mid-call — even between sealing the new object and repointing — leaves the name on the previous version; the half-committed object is just an unreferenced tree the sweeper ranks like any other. Sealing fsyncs every file and directory of the tree before the rename into objects/, and the rename before the index names it, so a power loss never leaves a name over files the disk lost.
  • Free history. Only the object the state: name currently holds is eviction-exempt. A superseded version loses the hold and becomes evictable history — still loadable by hash until density eviction takes it, with ReservationBook.load(root / "objects" / hash) and root the path configure returned. You get versioned state without a versioning system.

One writer per key. The whole load → method → commit runs under an exclusive flock on locks/state/<key>, so concurrent callers — worker threads, uvicorn workers, separate jobs — serialize their read-modify-writes and never lose an update (this is what lets counters and reservations retire ad-hoc persistence layers). The kernel drops that lock on any death, orderly or not, so a crashed holder's key is simply free. Unlike the call lock, the state lock has a deadline: a method call, and peek(), waits up to 30 seconds for the key and then raises ScratchError — which is why a long-running method, such as a COLMAP pass, must not be called concurrently on one key.

Never cached. Every method call runs against the latest state; arguments are not hashed and results are never memoized. Mutability lives only where it is honest — the state — and the pure cache stays immutable (its pins and dedup depend on that).

Reading without writing. open(key).peek() loads the committed state as a read-only value — a snapshot, not a live view — whose file and directory fields point into objects/<hash>/.

Progressive external tools. Decomposition covers everything decomposable: per-item pure_functions plus cheap pure assembly, where the cache itself is the progressive state. For the rest — sequential/stochastic cores like the COLMAP mapper or a training loop, which refine one artifact in place — the artifact IS the state, and holding it is what the class is for:

class SparseModel(cg.ImpureState):
    model: cg.ManagedDir  # the whole COLMAP model tree
    passes: cg.Number = cg.Number(0)

    def advance(self, database: cg.Blob) -> cg.Number:
        if cg.is_missing(self.model):
            self.model = cg.ManagedDir.new()
        self.model.exec(["colmap", "mapper", "--database_path", database, "--output_path", "."])
        self.passes = cg.Number(self.passes.value + 1)
        return self.passes


passes = SparseModel.open("MySurvey").advance(database)
model = SparseModel.open("MySurvey").peek().model  # objects/<hash>/model

Inside a method, self is a private working copy: the committed tree is copied into the call's workspace before the method runs, so a directory or file field is the method's own to write in place — the tool refines self.model where it stands — and the commit afterwards snapshots whatever the method left there. The sealed object is never touched. The workspace is released at commit, so a method must never return a value that lives in it — advance returns the pass count, not self.model — and committed fields are read through peek().

Each SparseModel.open(target_id).advance(...) call refines that target's model; the identity of the evolving artifact is declared by the key ("the reconstruction of target X"), never inferred from input hashes. No folds, no warm-start hints, no mutable cache entries — those were considered and rejected.

Identity and invalidation. State survives editing a method — the identity is the class's qualified name plus a digest of its schema, not a source digest. The schema is the field names and each field's wire type (for a nested struct, its fields in turn), key-sorted, so defaults, declaration order, method bodies and docstrings are outside the identity. Changing a field's name or type (or renaming/moving the class) starts an empty state: the struct IS the format, and a format change is a new identity, not a migration.

Durability equals the scratch's. State lives in the scratch's object store, so a durable cg.scratch.configure root means durable state, and cg.scratch.temporary state is ephemeral by definition. One caveat: a scratch whose index layout cannot be migrated is emptied on open, current state: versions included, so ImpureState is durable against crashes and restarts, not against a scratch format change.

Damaged objects are dropped, not repaired. Scratch.verify() re-hashes every object (through the stat cache, so only changed files are re-read) and drops each one whose files no longer hash to its name — truncated by a power loss, or edited in place. Each name pointing at it goes with it: the call computes again, and the state starts again from its seed. Run it once against the shared root with cg.scratch.Scratch(cg.scratch.default_root()).verify().

Mapping and parallelism#

A recipe applies to one value; to run it over a collection, map it. There are two ways, and the choice is explicit — recipes never parallelize behind your back:

  • Array.map(fn) / Map.map(fn) run fn over every element (or value, keys preserved) sequentially, results in order. They fail fast: the first element that raises stops the map and its exception propagates, so a long run never continues past a broken step. Pass on_error="missing" to run every element anyway, keeping each failure as a reasoned Missing (a map where every element failed for a non-data reason still raises):
thumbs = images.map(thumbnail)
sparse = images.map(cgr.sfm.keypoints, on_error="missing")
  • Array.pmap(fn) / Map.pmap(fn) are the same but across the process's one thread pool, sized to the CPU count; the first element to raise propagates as soon as it finishes, and elements not yet started never start; with cg.parallelism(n): caps how many elements a pmap has in flight at once. The cap is a context variable, like temporary and a held lock: it applies to the calling thread or task, pmap copies it into its workers, and a thread you start yourself begins at the default. They parallelize for real only when the bodies release the GIL — NumPy/PyTorch/PIL/ffmpeg/CUDA kernels or a subprocess, which is the dominant analysis workload. A pure-Python CPU body serializes on the interpreter lock, so pmap buys nothing there. A pmap inside a worker runs sequentially: the outer pool is the parallelism, so nested fan-out never oversubscribes.
thumbs = images.pmap(thumbnail)

Beyond that, hashing runs multithreaded inside blake3 for large files, and an external tool run in a directory (below) parallelizes itself however it does. There is deliberately no framework-level fan-out primitive: the mental model stays "a recipe is a function you call," and the parallelism you get is the parallelism you asked for.

Blackbox tools#

Some stages are external tools — colmap, ffmpeg — that write an opaque directory of files. A blackbox recipe gets a fresh directory with cg.ManagedDir.new(), stages its inputs into it, runs the tool there, and returns the result tree (or a subdirectory of it) as a first-class cached cg.ManagedDir:

import capturegraph as cg


@cg.pure_function("colmap_sfm/1")
def colmap_sfm(images: cg.Array[cg.Image]) -> cg.ManagedDir:
    work = cg.ManagedDir.new()                        # a fresh directory in this call
    for index, image in enumerate(images):
        work.stage(image, f"images/{index}.jpg")      # typed value straight in, parents made
    work.exec(["colmap", "automatic_reconstructor", "--workspace_path", "."])
    return work / "sparse"                            # the tree the tool wrote

A ManagedDir is a pathlib.Path, so you join and read it as one. The blackbox vocabulary is two methods of cg.DirScalar, and ManagedDir is that class under an opaque wire name:

  • work.stage(source, rel) — copy a file or tree to rel, creating rel's parents: source is any path or CGType file value. The copy is this directory's own, so a tool may overwrite it in place.
  • work.exec(argv, *, env=None, timeout=None, check=True, capture_output=False) — subprocess.run with work as the working directory; path values in argv pass straight through, and a non-zero exit raises CalledProcessError.

A sub-path of a ManagedDir — work / "sparse", work / "outputs" — is a ManagedDir sharing the workspace hold, and returning one seals only that subtree: the object's hash is computed from the subtree's content at seal, so a subdirectory has no identity of its own until it is returned.

Inputs are read-only: a value handed to a recipe lives in the object store or the data root, and stage is what gives the tool a copy it may write.

cg.ManagedDir (an unannotated managed folder) and cg.Blob (a file scalar accepting any extension) are analysis-only types: they let a recipe hold arbitrary tool output, including as fields of an ImpureState — a whole tool directory persists beside its progress counters, no archiving. They never appear in a procedure or target schema (no captured-data or iOS obligation); @cg.procedure rejects a schema holding one, naming the offending position.

See also: Recipes, the shipped recipe library built on this page, and Adding a type, which joins a type of your own to hashing, caching, new and stage by declaring its on-disk form.