Skip to content

Logging and progress#

A pipeline that runs for minutes should say what it is doing, and a pipeline that fails should say where. cg.logging is how CaptureGraph does both: a tree of log entries that every memoized call, map, pmap, lock and tool run writes into on its own, routed by context to wherever it should show — a terminal, a notebook cell, or the page a server is computing. Nothing is recorded unless something is listening: an unheard call grabs its call site, reads one context variable and returns an inert entry — a couple of hundred nanoseconds — so a recipe logs the same way whether or not anyone is watching.

cg.logging is the capturegraph.logging package of the core library (import capturegraph as cg). It imports nothing from the type system or the scratch, so a script that never touches a cg.pure_function can still use it; the dependency runs the other way, and What logs on its own lists it. The two other imports on this page are separate packages built on the core (Installation lists all three): capturegraph_ui (cgui, the capturegraph-ui package) adds the notebook sink and the HTML renderer, and capturegraph_recipes (cgr, the capturegraph-recipes package) holds the reconstruction stages whose lines the table quotes.

The model in three steps#

1. Routing. A context variable holds the entry new entries sit beneath. cg.logging.to(*sinks) opens a fresh Log for its block, makes the log's root that ambient entry, and sends every entry to the sinks. It takes nothing but sinks; with none at all (cg.logging.to()) the log still collects, which is how a test reads what a recipe logged. Outside every to() block the verbs return an inert entry that accepts every call and records nothing.

import capturegraph as cg
import capturegraph_ui as cgui

with cg.logging.to(cg.logging.Terminal()) as log:
    thumbnails = journal.sessions.photo.pmap(cgui.thumbnail)

print(len(log.entries()), "entries")

Several sinks receive every entry, each in turn. Terminal writes to the stream it is given, so appending to a file is the caller's open mode:

with (
    open("build.log", "a") as file,
    cg.logging.to(cg.logging.Terminal(), cg.logging.Terminal(file)),
):
    ...

to() blocks nest: an inner block opens a log of its own with its own sinks, and the outer log hears nothing from inside it until the inner block ends. cg.logging.current() is the log being written and current_entry() the innermost open entry; both are None when nothing is listening.

Threads inherit the context variable or they do not. A pmap worker runs in a copy of the caller's context and logs beneath the caller's entry; a thread you start yourself starts with none, so what it logs is inert. To give it a place, start it under a copy of the context — threading.Thread(target=contextvars.copy_context().run, args=(work,)) — or hand it an entry the caller made: an entry accepts update and advance from any thread that holds it, which is how the splat trainer's watcher thread reports its steps.

2. Entries. info, warning and error — info(message, *, key=None, **fields) — log a line: a level, a message and named JSON-able fields. A plain line is complete as it stands and is born done. with on the line makes it a scope: entering sets the context variable to the entry, exactly as to() sets it to the log's root, so everything logged in the block sits beneath it; the entry is open for the block and ends done, or failed carrying the exception's text and notes.

with cg.logging.info("Decoding frames", count=len(frames)):
    for frame in frames:
        ...
        cg.logging.warning("no depth", frame=frame.index)

progress logs a count, a Progress: progress(iterable=None, *, total=None, label=None, key=None), where total defaults to the iterable's length when it has one and label to progress. Iterate it, or hold it and advance it by hand; update(message=None, *, done=None, **fields) changes the message, the count and the fields in one revision, from any thread.

for batch in cg.logging.progress(batches, label="Training"):
    loss = train(batch)
    cg.logging.info(f"loss {loss:.3f}", loss=loss)

with cg.logging.progress(total=len(jobs), label="Rendering") as bar:
    for job in jobs:
        render(job)
        bar.advance()

3. Sinks. A Sink has one required method. emit(entry) is called once when an entry is made and once per change after that, in order, synchronously on the thread that logged and under the log's lock — a slow sink slows the computation, and an exception from emit is caught and reported through the standard library's logging rather than raised into the recipe. The Entry carries its id, parent, revision and status, so a sink that keeps a tree upserts by id and a sink that prints decides from the revision and the status. start(log) and finish() bracket the block for sinks that need the whole log or a last flush; the base class makes both no-ops.

class Collect(cg.logging.Sink):
    def __init__(self) -> None:
        self.messages: list[str] = []

    def emit(self, entry: cg.logging.Entry) -> None:
        if entry.revision == 0:
            self.messages.append(entry.message)

Three sinks ship. cg.logging.Terminal(stream=None) prints to sys.stderr by default, or to any open text stream: on a terminal the open entries are redrawn in place ten times a second beneath the lines already printed; on anything else — a file, a CI log — each entry is one line as it is made, one more as a scope or an iterated count closes, and a revised line at most once a second, since a stream cannot take a line back. That last rule matters to anyone tailing the file: a scope or an iterated count always prints its closing line, but a plain line revised inside the one-second window keeps the text last printed — finish flushes the stream and prints no catch-up. cgui.Notebook(), from capturegraph-ui, shows the tree as one HTML output in the running cell and redraws it in place (install that package's notebook extra for IPython). The server's page runner has a sink of its own that streams the tree to the browser.

import capturegraph as cg
import capturegraph_recipes as cgr
import capturegraph_ui as cgui

with cg.logging.to(cgui.Notebook()):
    splat = cgr.splats.train(frames, seed)

Writing a sink of your own is three methods, one of them required.

Loops: the same line is the same entry#

A training loop that logs its loss every step would bury everything else under thousands of lines. Inside an iterated progress, it does not:

  • Every entry logged beneath the loop — at any depth — is keyed by its call site: the code location that logged it, and how many times that location has logged in the current iteration. The same line logging again next iteration revises its entry in place instead of appending one; a sink sees a change, not a new entry.
  • An entry the loop stops logging stays, carrying the iteration it was last logged in. A renderer tags it iteration 3 once the loop has moved on, so a warning from one iteration never disappears and never hides the current state.
  • An entry logged again is logged anew: its clock restarts, a past failure clears, and what was logged beneath it in its earlier run is dropped. A scope entered every iteration therefore times and shows only its latest run, never a past run's children or error beneath the current one.
  • key="…" names a slot by hand, anywhere — inside a loop or not — and replaces the call-site rule for that call: two calls with the same key beneath the same parent are one entry. A tool's output tail is one: cg.logging.info(tail, key="tail"), pumped from a thread running under a copy of the context, revises the same entry with every chunk.
for step in cg.logging.progress(range(10_000), label="Training"):
    loss = train_step()
    cg.logging.info(f"loss {loss:.4f}", loss=loss)  # one entry, revised 10 000 times
    if loss > 10:
        cg.logging.error("diverging", loss=loss)  # stays, tagged with its iteration

Iterating is what starts iterations; turn() is one iteration as a block, for elements that arrive one at a time. A count advanced by hand (advance, update(done=…)) has none, so beneath it every call appends. A progress nested in the loop is the loop for everything beneath it, and the slot rule reuses it: its count starts over each outer iteration. map iterates its count, so it reads exactly like the loop above; pmap gives each pool thread a worker count beneath its own and runs every element as one turn of its worker, so the tree shows how many threads are working, how many elements each has done, and what each is doing right now (a pmap of one element, or one inside a worker, runs sequentially as a plain count).

What logs on its own#

Nothing in a recipe needs annotating to be visible. The four names in the first rows belong to the scratch:

What Logs
a memoized call, on a miss a scope named after the function, with its identity as a field; failed with the exception text and the exec.log tail if the body raises
a memoized call, on a hit one line, <function>: cached
map / pmap a count named after the function (or label=) with the element count as its total; map runs each element as an iteration of it, pmap as a turn of a worker <n> count per pool thread beneath it
cg.lock("gpu") a scope gpu lock: waiting for train (pid 4242), held 5m12s while it waits, gpu lock: held once it has the resource
a tool run through exec (work.exec(argv) on a cg.ManagedDir) a scope $ <command> with a tail entry beneath it holding the last forty lines of output
an ImpureState method a scope Class.method
a reconstruction stage (cgr.sfm, cgr.depth, cgr.splats) one info line naming its result, the numbers as fields: Matched with candidates and inliers, Adjusted with the reprojection before and after, Fitted to measured depth with scale and shift; Reconstruction lists each stage's line
a stage reading its inputs one by one a count over them — Reading keypoints, Decoding frames, Seeding frames, Reading EXIF — with the element count as its total
cgr.sfm.tracks a Matching pairs count over the pairs, every pair's Matched line a turn of a pool worker
cgr.sfm.reconstruct a Registering images count, one turn per image, its registered, points and reprojection_px fields revised as the model grows
cgr.splats.train a Training count whose step, loss and gaussian count a watcher thread reads from the trainer's report file and updates

The wire shape#

Entry.json() is what every renderer reads, and Log.json() is the whole tree, parents before children:

{"id": "3", "parent": "1", "level": "info", "message": "loss 0.0312",
 "fields": {"loss": 0.0312}, "done": null, "total": null, "iteration": 41,
 "started": 1757600000.1, "ended": 1757600000.1, "status": "done",
 "error": null, "revision": 41}

iteration counts from zero — the shipped renderers show iteration + 1 — and is null outside a loop; status is done for a plain line, open inside a with block or an iteration, and failed after an exception, with error holding its text. What emit sees walks every key.

The core package renders nothing. cgui.log.html(log) renders the same tree as a self-contained fragment of nested <details>, which is what cgui.Notebook shows and what the server stores as a page's build log. The browser renderer that draws the tree live from a stream of these entries is cgui.log.script(), with cgui.log.stylesheet() beside it, so a frontend of your own needs the JSON alone.