Skip to content

livery.workshop._traces

livery.workshop._traces

The legs' traces: what a run cost, kept where no sync brings it.

A profiled job leaves two records, and the workspace contract prices them apart under [ci]. timing, on unless the contract says otherwise, runs every entry of every job profiled: each check leg writes a Chrome trace of every task, step and test it ran, and its timing row, kilobytes that fm ci.timings, the speed marks and fm ci.balance read, comes from that trace. profile, off unless asked, pushes the trace itself, megabytes a leg that only fm ci.profile reads, to a namespace of its own, outside the one refspec a sync mirrors. profile-window says how many runs the pushed channel keeps, profile-into where an assembled file lands, and profile-keep how many of those files stay there. A pushed trace is the one a profiled run writes, so profile = true beside timing = false refuses.

Off is zero cost rather than less. timing = false runs nothing profiled, writes no row and pushes nothing. With profile off the trace stays on the runner and goes with it, so a checkout pays nothing for traces nobody asked for, and the gate reads none of them. The file is a Chrome trace of that leg: every task, step and test it ran, and the wall-clock origin of its own clock, so one leg's timeline can be laid beside another's.

The push is observational. A trace that is not there and a push origin refuses are each one printed line, and none of them decides a job.

livery.workshop._traces.assemble reads the other way: one trace for a whole run, built from the forge's own job times and whatever traces the channel holds. The forge is asked for the skeleton and nothing else, so nothing here knows a forge.

Classes:

Name Description
Policy

What the contract says about the legs' traces.

Caused

One run about a commit.

Node

One commit of a chain, and the runs about it.

Walked

A chain of runs as one timeline.

Assembled

One run as a timeline, and where that timeline's zero sits.

Functions:

Name Description
policy

The contract's [ci] trace keys for root, and what it got wrong.

sweep

Keep the newest keep assembled files under at; what went.

this_leg

The leg this process belongs to, as the job runner named it.

push

Put trace on this leg's ref of the run; the line to print.

about

Record the commit this run ran on when the forge files it elsewhere; the line.

runs_about

Every run about commit, and a line per thing worth saying.

chain

Every run about commit, and the runs of what its merge produced.

assemble

One trace of a whole run: its jobs, their steps, and the legs' traces.

newest_run

The forge's newest run for head_sha, or empty when it lists none.

drop_run

Put the run of git's head in this command's own drop box; the line.

drop_chain

Put the chain from commit in this command's own drop box; the line.

write_chain

Write the chain from commit where a person can open it; and the lines.

write_run

Write a run's assembled trace where a person can open it; and the lines.

Attributes:

Name Type Description
TRACE_FILE
JOB_FILE
TIMING_KEY
PROFILE_KEY
WINDOW_KEY
INTO_KEY
KEEP_KEY
TIMING_DEFAULT
PROFILE_DEFAULT
WINDOW_DEFAULT
KEEP_DEFAULT
INTO_DEFAULT
TRACES
ABOUT
RUN_PID
LEG_PIDS

TRACE_FILE module-attribute

TRACE_FILE = 'trace.json'

JOB_FILE module-attribute

JOB_FILE = 'job.json'

TIMING_KEY module-attribute

TIMING_KEY = 'timing'

PROFILE_KEY module-attribute

PROFILE_KEY = 'profile'

WINDOW_KEY module-attribute

WINDOW_KEY = 'profile-window'

INTO_KEY module-attribute

INTO_KEY = 'profile-into'

KEEP_KEY module-attribute

KEEP_KEY = 'profile-keep'

TIMING_DEFAULT module-attribute

TIMING_DEFAULT = True

PROFILE_DEFAULT module-attribute

PROFILE_DEFAULT = False

WINDOW_DEFAULT module-attribute

WINDOW_DEFAULT = 100

KEEP_DEFAULT module-attribute

KEEP_DEFAULT = 50

INTO_DEFAULT module-attribute

INTO_DEFAULT = '.workshop/profiles'

TRACES module-attribute

TRACES = git.Keyed('run', ('run', 'leg'), namespace=git.TRACE_NAMESPACE, holds_rows=False, keep=_kept_runs)

ABOUT module-attribute

ABOUT = git.Keyed('about', ('commit',), namespace=git.TRACE_NAMESPACE, stale_after=timedelta(days=90))

RUN_PID module-attribute

RUN_PID = 1

LEG_PIDS module-attribute

LEG_PIDS = 1000

Policy dataclass

Policy(timing: bool, profile: bool, window: int, into: str, keep: int)

What the contract says about the legs' traces.

Attributes:

Name Type Description
timing bool

Whether every job runs its entries profiled. On, each check leg writes a trace of every task, step and test it ran, and its timing row is read from that trace. Off means zero cost: no entry runs profiled, nothing is written on a runner, no row, no push.

profile bool

Whether a job pushes the trace it wrote to the trace refs, for a run to be assembled from. Off, the trace stays on the runner and goes with it, and the timing row is unaffected. On needs timing on, and a contract saying otherwise refuses. A run from a period when it was off still assembles at the job level, because that shape comes from the forge.

window int

How many runs' traces the pushed channel keeps. This one governs what a later assembly can still read, so it decides how far back a chain can be built.

into str

Where an assembled file lands, relative to the workspace root unless it is absolute.

keep int

How many assembled files stay in that directory. This one governs this checkout's own disk and nothing else: the files here are output, never input, so sweeping them strands no chain.

timing instance-attribute

timing: bool

profile instance-attribute

profile: bool

window instance-attribute

window: int

into instance-attribute

into: str

keep instance-attribute

keep: int

Caused dataclass

Caused(run_id: str, event: str, recorded: bool = False)

One run about a commit.

Attributes:

Name Type Description
run_id str

The forge's own id for the run.

event str

What started it, as the forge or the run's own record spells it.

recorded bool

Whether the run said so itself, because the forge files it under another commit.

run_id instance-attribute

run_id: str

event instance-attribute

event: str

recorded class-attribute instance-attribute

recorded: bool = False

Node dataclass

Node(commit: str, runs: tuple[str, ...])

One commit of a chain, and the runs about it.

Attributes:

Name Type Description
commit str

The commit.

runs tuple[str, ...]

Every run about it that assembled to something, in the order they were walked.

commit instance-attribute

commit: str

runs instance-attribute

runs: tuple[str, ...]

Walked dataclass

Walked(events: list[dict[str, Any]], nodes: tuple[Node, ...], lines: list[str])

A chain of runs as one timeline.

Attributes:

Name Type Description
events list[dict[str, Any]]

Every run's events on one clock, in epoch microseconds, which is what a drop box takes and what a file records its zero against.

nodes tuple[Node, ...]

The commits walked, in order.

lines list[str]

A line per thing worth saying about the walking.

events instance-attribute

events: list[dict[str, Any]]

nodes instance-attribute

nodes: tuple[Node, ...]

lines instance-attribute

lines: list[str]

Assembled dataclass

Assembled(events: list[dict[str, Any]], origin: float, lines: list[str])

One run as a timeline, and where that timeline's zero sits.

Attributes:

Name Type Description
events list[dict[str, Any]]

The trace's events, every stamp relative to origin.

origin float

That zero, in wall-clock microseconds, which is what lets another timeline be laid on this one.

lines list[str]

A line per thing worth saying about the assembling.

events instance-attribute

events: list[dict[str, Any]]

origin instance-attribute

origin: float

lines instance-attribute

lines: list[str]

policy

policy(root: Path) -> tuple[Policy, str]

The contract's [ci] trace keys for root, and what it got wrong.

The contract's judge refuses a key of the wrong type. A count below zero or an empty path is named with what it must be, and the default stands for it.

Raises:

Type Description
Failed

when profile is true beside timing = false, naming both keys. A pushed trace is the one a profiled run writes, so the contradiction refuses here, where every reader of the policy meets it once, rather than as a line one reader prints and another never sees.

Source code in packages/workshop/src/livery/workshop/_traces.py
def policy(root: Path) -> tuple[Policy, str]:
    """The contract's ``[ci]`` trace keys for *root*, and what it got wrong.

    The contract's judge refuses a key of the wrong type. A count
    below zero or an empty path is named with what it must be, and the
    default stands for it.

    Raises:
        Failed: when ``profile`` is true beside ``timing = false``,
            naming both keys. A pushed trace is the one a profiled run
            writes, so the contradiction refuses here, where every
            reader of the policy meets it once, rather than as a line
            one reader prints and another never sees.
    """
    from livery.workshop._contract import load_contract

    contract = load_contract(root / "workshop.toml")
    found: dict[str, Any] = contract.get("ci") or {}
    timing = _flag(found, TIMING_KEY, TIMING_DEFAULT)
    profile = _flag(found, PROFILE_KEY, PROFILE_DEFAULT)
    if profile and not timing:
        fail(
            f"[ci] {PROFILE_KEY} is true and [ci] {TIMING_KEY} is false; the trace"
            f" pushed is the one a profiled run writes, so {PROFILE_KEY} = true"
            f" implies {TIMING_KEY} = true: drop {TIMING_KEY} = false or set"
            f" {PROFILE_KEY} = false"
        )
    window, why_window = _count(found, WINDOW_KEY, WINDOW_DEFAULT)
    into, why_into = _text(found, INTO_KEY, INTO_DEFAULT)
    keep, why_keep = _count(found, KEEP_KEY, KEEP_DEFAULT)
    return Policy(timing, profile, window, into, keep), "; ".join(
        why for why in (why_window, why_into, why_keep) if why
    )

sweep

sweep(at: Path, keep: int) -> list[str]

Keep the newest keep assembled files under at; what went.

Runs after each write, so a checkout that profiles often does not accumulate. Newest by modification time, because the name carries a run id or a commit and neither orders by age. A keep of zero keeps everything: the count is a ceiling, and no ceiling means no sweeping rather than sweeping all of it.

Every trace in the directory is a candidate, whichever writer made it. The directory belongs to the mechanism, so a new writer gets housekeeping and an ignore rule without either being taught about it; the cost is that a file put there by hand is swept like the rest, and a trace to keep belongs somewhere else.

Returns one line per file removed, for the caller to report beside whatever it wrote. A file that cannot be removed is named and the sweep goes on: this is housekeeping and never a verdict.

Source code in packages/workshop/src/livery/workshop/_traces.py
def sweep(at: Path, keep: int) -> list[str]:
    """Keep the newest *keep* assembled files under *at*; what went.

    Runs after each write, so a checkout that profiles often does not
    accumulate. Newest by modification time, because the name carries a
    run id or a commit and neither orders by age. A *keep* of zero
    keeps everything: the count is a ceiling, and no ceiling means no
    sweeping rather than sweeping all of it.

    Every trace in the directory is a candidate, whichever writer made
    it. The directory belongs to the mechanism, so a new writer gets
    housekeeping and an ignore rule without either being taught about
    it; the cost is that a file put there by hand is swept like the
    rest, and a trace to keep belongs somewhere else.

    Returns one line per file removed, for the caller to report beside
    whatever it wrote. A file that cannot be removed is named and the
    sweep goes on: this is housekeeping and never a verdict.
    """
    if keep <= 0:
        return []
    found = sorted(
        (path for path in at.glob("*.json") if path.is_file()),
        key=lambda path: path.stat().st_mtime,
        reverse=True,
    )
    lines = []
    for path in found[keep:]:
        try:
            path.unlink()
        except OSError as error:
            lines.append(f"profile: {path.name} stayed ({error})")
            continue
        lines.append(f"profile: swept {path.name}")
    return lines

this_leg

this_leg() -> str

The leg this process belongs to, as the job runner named it.

Source code in packages/workshop/src/livery/workshop/_traces.py
def this_leg() -> str:
    """The leg this process belongs to, as the job runner named it."""
    return os.environ.get(LEG_VARIABLE, "")

push

push(root: Path, trace: Path, *, job: str = '', leg: str = '', run: RunContext | None = None) -> str

Put trace on this leg's ref of the run; the line to print.

job is the job's name as the forge lists it, written down beside the trace: it is what an assembler joins the leg to its job by, and a matrix job's forge name cannot be derived from the leg's label.

leg is that label. The job runner gives it to the entries it spawns and pushes from its own process, which never had it in its environment, so the caller that knows the label says it; livery.workshop._traces.this_leg answers for a caller running inside a leg, where the environment is the only source.

Empty when the contract asks for no pushed traces ([ci] profile, off unless asked), so a workspace that wants none neither pushes nor says anything. Every other answer is a line: a trace that was never written, a leg nothing named, a run this is not, or origin's own refusal.

Source code in packages/workshop/src/livery/workshop/_traces.py
def push(
    root: Path,
    trace: Path,
    *,
    job: str = "",
    leg: str = "",
    run: RunContext | None = None,
) -> str:
    """Put *trace* on this leg's ref of the run; the line to print.

    *job* is the job's name as the forge lists it, written down beside
    the trace: it is what an assembler joins the leg to its job by, and
    a matrix job's forge name cannot be derived from the leg's label.

    *leg* is that label. The job runner gives it to the entries it
    spawns and pushes from its own process, which never had it in its
    environment, so the caller that knows the label says it;
    `livery.workshop._traces.this_leg` answers for a caller running
    inside a leg, where the environment is the only source.

    Empty when the contract asks for no pushed traces (``[ci] profile``,
    off unless asked), so a workspace that wants none neither pushes nor
    says anything. Every other answer is a line: a trace that was never
    written, a leg nothing named, a run this is not, or origin's own
    refusal.
    """
    kept, why = policy(root)
    if not kept.profile:
        return ""
    if why:
        return f"profile: {why}"
    found = run or run_context()
    if found is None:
        return "profile: not a CI run; the trace stays on this machine"
    named = leg or this_leg()
    if not named:
        return f"profile: {LEG_VARIABLE} names no leg; the trace is not pushed"
    if not trace.is_file():
        return f"profile: no trace at {trace}; nothing to push"
    series = TRACES.series(found.run_id, named)
    files = {TRACE_FILE: trace.read_text(encoding="utf-8")}
    if job:
        files[JOB_FILE] = json.dumps({"job": job}, sort_keys=True)
    refused = git.put(
        state_store(root),
        series.ref,
        files,
        message=f"trace: {named} of run {found.run_id}",
        ci_only=True,
    )
    if refused:
        return f"profile: the trace was not pushed ({refused})"
    size = trace.stat().st_size
    return f"profile: {size // 1024} KiB pushed to {series.ref}"

about

about(root: Path, *, run: RunContext | None = None) -> str

Record the commit this run ran on when the forge files it elsewhere; the line.

A push run and a pull request run are filed under the commit they ran on, so nothing needs writing down. A dispatched run is filed under the tip of the ref it was dispatched on, and another merge landing between the dispatch and the run moves that tip past the commit the dispatch named. Then the forge's listing for the commit the run is about does not hold it, and only the run itself knows.

Written whatever the contract says about traces. The record is one row, and more than the assembler reads it: the merge point asks livery.workshop._traces.runs_about for the wave of a squash the forge filed under a tip that moved on, so a workspace that keeps no trace still keeps this. Empty outside a run, and on every run whose own head is the commit it checked out, which is most of them. Every other answer is a line.

Source code in packages/workshop/src/livery/workshop/_traces.py
def about(root: Path, *, run: RunContext | None = None) -> str:
    """Record the commit this run ran on when the forge files it elsewhere; the line.

    A push run and a pull request run are filed under the commit they
    ran on, so nothing needs writing down. A dispatched run is filed
    under the tip of the ref it was dispatched on, and another merge
    landing between the dispatch and the run moves that tip past the
    commit the dispatch named. Then the forge's listing for the commit
    the run is about does not hold it, and only the run itself knows.

    Written whatever the contract says about traces. The record is one
    row, and more than the assembler reads it: the merge point asks
    [livery.workshop._traces.runs_about][] for the wave of a squash the
    forge filed under a tip that moved on, so a workspace that keeps no
    trace still keeps this. Empty outside a run, and on every run whose
    own head is the commit it checked out, which is most of them. Every
    other answer is a line.
    """
    found = run or run_context()
    if found is None:
        return ""
    head = git.head_sha(root)
    if not head or head == found.head_sha:
        return ""  # the forge already files it here
    refused = ABOUT.series(head).put(
        state_store(root),
        {found.run_id: {"run": found.run_id, "event": found.event, "ref": found.ref}},
        message=f"about: run {found.run_id} ran on {head[:12]}",
    )
    if refused:
        return f"profile: what this run ran on was not recorded ({refused})"
    return f"profile: run {found.run_id} recorded as the run of {head[:12]}"

runs_about

runs_about(root: Path, repo: Repository, commit: str) -> tuple[tuple[Caused, ...], list[str]]

Every run about commit, and a line per thing worth saying.

Two sources in one answer. The forge's listing for the commit holds the push run, the pull request runs and every dispatched run it filed under it. Beside that, the runs that recorded themselves, because the forge filed them under a commit that had moved on. A run both sources name appears once, from the forge.

Source code in packages/workshop/src/livery/workshop/_traces.py
def runs_about(
    root: Path, repo: Repository, commit: str
) -> tuple[tuple[Caused, ...], list[str]]:
    """Every run about *commit*, and a line per thing worth saying.

    Two sources in one answer. The forge's listing for the commit holds
    the push run, the pull request runs and every dispatched run it
    filed under it. Beside that, the runs that recorded themselves,
    because the forge filed them under a commit that had moved on. A run
    both sources name appears once, from the forge.
    """
    found = [
        Caused(str(run.id), run.event) for run in repo.checks.runs(head_sha=commit)
    ]
    known = {caused.run_id for caused in found}
    with git.remote_snapshot(state_store(root), fetch=(ABOUT.series(commit).ref,)):
        rows = ABOUT.series(commit).rows(state_store(root))
    lines = [f"{commit[:12]}: {rows.reason}"] if rows.reason else []
    for row in rows.rows:
        run_id = str(row.data.get("run") or "")
        if run_id and run_id not in known:
            found.append(Caused(run_id, str(row.data.get("event") or ""), True))
            known.add(run_id)
    return tuple(found), lines

chain

chain(root: Path, repo: Repository, commit: str, *, depth: int = 2, now: datetime | None = None) -> Walked

Every run about commit, and the runs of what its merge produced.

Three recorded facts and no guesses: what the forge lists for a commit, what a run wrote down about the commit it ran on, and the merge commit a pull request names. So a chain followed while it happens and one walked from the same commit weeks later are the same tree, which is the property this exists for.

A release is two commits and one hop. The branch commit carries the pull request's run; the merge commit carries the base's own run and the wave dispatched at it, which is filed under the base's tip and found through the commit it recorded rather than through a time.

Parameters:

Name Type Description Default
root Path

The workspace root, whose channel the traces are read from.

required
repo Repository

The repository the runs belong to.

required
commit str

Where the walk starts.

required
depth int

How many merges to follow. Zero walks the one commit.

2
now datetime | None

The moment a job still running is measured to.

None

Returns:

Type Description
Walked

The events, the commits walked with the runs about each, and a

Walked

line per thing worth saying. A commit with no run and no merge

Walked

is a node with nothing under it, never a guess.

Source code in packages/workshop/src/livery/workshop/_traces.py
def chain(
    root: Path,
    repo: Repository,
    commit: str,
    *,
    depth: int = 2,
    now: datetime | None = None,
) -> Walked:
    """Every run about *commit*, and the runs of what its merge produced.

    Three recorded facts and no guesses: what the forge lists for a
    commit, what a run wrote down about the commit it ran on, and the
    merge commit a pull request names. So a chain followed while it
    happens and one walked from the same commit weeks later are the same
    tree, which is the property this exists for.

    A release is two commits and one hop. The branch commit carries the
    pull request's run; the merge commit carries the base's own run and
    the wave dispatched at it, which is filed under the base's tip and
    found through the commit it recorded rather than through a time.

    Args:
        root: The workspace root, whose channel the traces are read from.
        repo: The repository the runs belong to.
        commit: Where the walk starts.
        depth: How many merges to follow. Zero walks the one commit.
        now: The moment a job still running is measured to.

    Returns:
        The events, the commits walked with the runs about each, and a
        line per thing worth saying. A commit with no run and no merge
        is a node with nothing under it, never a guess.
    """
    moment = now or datetime.now(UTC)
    events: list[dict[str, Any]] = []
    lines: list[str] = []
    nodes: list[Node] = []
    walked: set[str] = set()
    taken: set[str] = set()
    ceiling = 0
    ahead = [(commit, depth)]
    while ahead:
        at, left = ahead.pop(0)
        if not at or at in walked:
            continue
        walked.add(at)
        caused, why = runs_about(root, repo, at)
        lines += why
        kept: list[str] = []
        said: list[str] = []
        for run in caused:
            if run.run_id in taken:
                continue
            taken.add(run.run_id)
            made = assemble(root, repo, run.run_id, head_sha=at, clock=0.0, now=moment)
            lines += [f"run {run.run_id}: {line}" for line in made.lines]
            if not made.events:
                continue
            moved, ceiling = _renumbered(made.events, by=ceiling, about=at, run=run)
            events += moved
            kept.append(run.run_id)
            said.append(
                f"run {run.run_id} ({run.event}"
                + (", recorded)" if run.recorded else ")")
            )
        nodes.append(Node(at, tuple(kept)))
        lines.append(f"{at[:12]}: {', '.join(said) if said else 'no run assembled'}")
        if left <= 0:
            continue
        found = repo.pr.find_by_head_sha(at)
        if found is None or not found.merged_sha:
            continue
        lines.append(f"{at[:12]} merged as {found.merged_sha[:12]} by #{found.number}")
        ahead.append((found.merged_sha, left - 1))
    return Walked(events, tuple(nodes), lines)

assemble

assemble(root: Path, repo: Repository, run_id: str, *, head_sha: str = '', clock: float | None = None, now: datetime | None = None) -> Assembled

One trace of a whole run: its jobs, their steps, and the legs' traces.

The forge answers the skeleton: every job with its status, its conclusion, its start and end, and its own steps. Each job is a track of the run's process, so jobs that ran at once read as the parallel work they were. Where the channel holds that job's trace, its events are laid on the run's clock through the origin the trace recorded, in process groups of their own: the alignment is what nests them, and it comes from two clocks that were written down independently rather than from the order anything arrived in.

A job with no trace keeps its slice and its steps. A job the forge gives no times at all, a skip, is an instant event carrying its conclusion, because a thing with no duration is an event and not a span. A job still running is a slice up to the moment of assembly.

Parameters:

Name Type Description Default
root Path

The workspace root, which the traces are read through.

required
repo Repository

The repository whose run this is.

required
run_id str

The forge's own id for the run.

required
head_sha str

The commit the run checked, when the caller knows it. With it the run's own row is read too, so the wait before each job can be drawn; without it the jobs' own times are the whole skeleton.

''
clock float | None

The wall-clock moment, in microseconds, every stamp is measured from. The run's own first moment by default, which is a file that starts at zero; 0.0 leaves the stamps on the wall clock itself, which is what a drop box takes.

None
now datetime | None

The moment a running job's slice ends; the present by default.

None

Returns:

Type Description
Assembled

The events, the wall-clock moment they are measured from, and a line

Assembled

per thing worth saying. No events at all means the forge listed no

Assembled

job for the run.

Source code in packages/workshop/src/livery/workshop/_traces.py
def assemble(
    root: Path,
    repo: Repository,
    run_id: str,
    *,
    head_sha: str = "",
    clock: float | None = None,
    now: datetime | None = None,
) -> Assembled:
    """One trace of a whole run: its jobs, their steps, and the legs' traces.

    The forge answers the skeleton: every job with its status, its
    conclusion, its start and end, and its own steps. Each job is a
    track of the run's process, so jobs that ran at once read as the
    parallel work they were. Where the channel holds that job's trace,
    its events are laid on the run's clock through the origin the
    trace recorded, in process groups of their own: the alignment is
    what nests them, and it comes from two clocks that were written
    down independently rather than from the order anything arrived in.

    A job with no trace keeps its slice and its steps. A job the forge
    gives no times at all, a skip, is an instant event carrying its
    conclusion, because a thing with no duration is an event and not a
    span. A job still running is a slice up to the moment of assembly.

    Args:
        root: The workspace root, which the traces are read through.
        repo: The repository whose run this is.
        run_id: The forge's own id for the run.
        head_sha: The commit the run checked, when the caller knows
            it. With it the run's own row is read too, so the wait
            before each job can be drawn; without it the jobs' own
            times are the whole skeleton.
        clock: The wall-clock moment, in microseconds, every stamp is
            measured from. The run's own first moment by default, which
            is a file that starts at zero; ``0.0`` leaves the stamps on
            the wall clock itself, which is what a drop box takes.
        now: The moment a running job's slice ends; the present by
            default.

    Returns:
        The events, the wall-clock moment they are measured from, and a line
        per thing worth saying. No events at all means the forge listed no
        job for the run.
    """
    # The plugin lays one trace on another's clock, and is optional: an
    # ordinary run of any verb must not import it, and importing this
    # module is how the submit reaches `drop_run`.
    from livery.footman.profile import laid_on

    moment = now or datetime.now(UTC)
    lines: list[str] = []
    jobs = repo.checks.jobs(int(run_id)) if run_id.isdigit() else ()
    if not run_id.isdigit():
        lines.append(f"run {run_id}: not a number, so the forge cannot be asked")
        return Assembled([], 0.0, lines)
    if not jobs:
        lines.append(f"run {run_id}: the forge lists no job for it")
        return Assembled([], 0.0, lines)
    created = _run_created(repo, run_id, head_sha, lines) if head_sha else None
    zero = _zero_of(jobs, created, moment) if clock is None else clock
    events: list[dict[str, Any]] = [
        {
            "ph": "M",
            "name": "process_name",
            "pid": RUN_PID,
            "args": {"name": f"run {run_id}"},
        }
    ]
    # One listing and one fetch for every leg's trace of the run.
    with git.remote_snapshot(state_store(root), fetch=(f"{TRACES.prefix}{run_id}/",)):
        traced, refusals = _legs_of(root, run_id)
    lines += refusals
    pids = itertools.count(LEG_PIDS)
    ordered = sorted(jobs, key=_job_order)
    for tid, job in enumerate(ordered, start=1):
        events += _job_events(job, tid=tid, zero=zero, created=created, now=moment)
        text = traced.get(job.name) or traced.get(git.slug(job.name))
        if text is None:
            continue
        found, why = laid_on(text, zero=zero, pids=pids, label=job.name)
        if why:
            lines.append(f"{job.name}: {why}")
            continue
        events += found
        drawn, said = _residue(
            job, found, tid=tid, total=len(ordered), zero=zero, now=moment
        )
        events += drawn
        own = f"{job.name}: {len(found)} event(s) of its own"
        lines.append(f"{own}, {said}" if said else own)
    return Assembled(events, zero, lines)

newest_run

newest_run(repo: Repository, head_sha: str) -> str

The forge's newest run for head_sha, or empty when it lists none.

Source code in packages/workshop/src/livery/workshop/_traces.py
def newest_run(repo: Repository, head_sha: str) -> str:
    """The forge's newest run for *head_sha*, or empty when it lists none."""
    runs = repo.checks.runs(head_sha=head_sha)
    return str(runs[0].id) if runs else ""

drop_run

drop_run(repo: Repository, root: Path, *, run_id: str = '') -> str

Put the run of git's head in this command's own drop box; the line.

For a verb that followed a run to its end. With a trace being kept, the run it watched goes into the same box its own children drop into, so one file holds the local command, the run it caused, every job of that run, and every leg's tasks and tests underneath. The stamps are the wall clock's, which is what a box takes, and this run's writer lays the whole thing on its own clock.

Empty when no trace is being kept, which is the ordinary case: the verb calls this whatever its line asked for and pays one environment read.

Never raises. A trace is something noticed about a run, so nothing here may change what the run decided: every failure, git's and the forge's alike, comes back as the line to print. A CI leg proved the point by running its own tests under a profile, where a rig with no repository turned a watched merge into a failure.

Source code in packages/workshop/src/livery/workshop/_traces.py
def drop_run(repo: Repository, root: Path, *, run_id: str = "") -> str:
    """Put the run of *git*'s head in this command's own drop box; the line.

    For a verb that followed a run to its end. With a trace being kept, the
    run it watched goes into the same box its own children drop into, so one
    file holds the local command, the run it caused, every job of that run,
    and every leg's tasks and tests underneath. The stamps are the wall
    clock's, which is what a box takes, and this run's writer lays the whole
    thing on its own clock.

    Empty when no trace is being kept, which is the ordinary case: the verb
    calls this whatever its line asked for and pays one environment read.

    Never raises. A trace is something noticed about a run, so nothing here
    may change what the run decided: every failure, git's and the forge's
    alike, comes back as the line to print. A CI leg proved the point by
    running its own tests under a profile, where a rig with no repository
    turned a watched merge into a failure.
    """
    from livery.footman.profile import dropped, keeping

    # Assembling a run costs forge calls, so the cheap question comes first.
    if not keeping():
        return ""
    try:
        head_sha = git.head_sha(root)
        found = run_id or newest_run(repo, head_sha)
        if not found:
            return f"profile: the forge lists no run for {head_sha[:12]}"
        made = assemble(root, repo, found, head_sha=head_sha, clock=0.0)
        if not made.events:
            why = made.lines[0] if made.lines else f"run {found} assembled to nothing"
            return f"profile: {why}"
        if dropped(made.events) is None:
            return ""
    except Exception as error:
        return f"profile: the run was not traced ({error})"
    jobs = len({e["tid"] for e in made.events if e.get("cat") == "job"})
    return f"profile: run {found} joins this trace, {jobs} job(s)"

drop_chain

drop_chain(repo: Repository, root: Path, *, commit: str = '', depth: int = 2) -> str

Put the chain from commit in this command's own drop box; the line.

For a verb that followed its work to the end of everything it caused: a release, whose pull request run, base run and wave are one story. The stamps are the wall clock's, which is what a box takes, and this box's writer lays the whole thing on its own clock.

HEAD by default. Empty when no trace is being kept, which is the ordinary case, so the verb pays one environment read.

Never raises. A trace is something noticed about work that is already done, so nothing here may change what that work decided: every failure, git's and the forge's alike, comes back as the line to print.

Source code in packages/workshop/src/livery/workshop/_traces.py
def drop_chain(
    repo: Repository, root: Path, *, commit: str = "", depth: int = 2
) -> str:
    """Put the chain from *commit* in this command's own drop box; the line.

    For a verb that followed its work to the end of everything it
    caused: a release, whose pull request run, base run and wave are one
    story. The stamps are the wall clock's, which is what a box takes,
    and this box's writer lays the whole thing on its own clock.

    ``HEAD`` by default. Empty when no trace is being kept, which is the
    ordinary case, so the verb pays one environment read.

    Never raises. A trace is something noticed about work that is
    already done, so nothing here may change what that work decided:
    every failure, git's and the forge's alike, comes back as the line
    to print.
    """
    from livery.footman.profile import dropped, keeping

    if not keeping():
        return ""
    try:
        at = commit or git.head_sha(root)
        walked = chain(root, repo, at, depth=depth, now=None)
        if not walked.events:
            why = walked.lines[-1] if walked.lines else f"nothing about {at[:12]}"
            return f"profile: {why}"
        if dropped(walked.events) is None:
            return ""
    except Exception as error:
        return f"profile: the chain was not traced ({error})"
    runs = sum(len(node.runs) for node in walked.nodes)
    return f"profile: {runs} run(s) of {len(walked.nodes)} commit(s) join this trace"

write_chain

write_chain(root: Path, repo: Repository, commit: str, *, depth: int = 2, into: Path | None = None) -> tuple[Path | None, list[str]]

Write the chain from commit where a person can open it; and the lines.

The same walk the release command drops into its own trace, asked for from a commit instead. The directory is the contract's [ci] profile-into unless the caller names another.

Source code in packages/workshop/src/livery/workshop/_traces.py
def write_chain(
    root: Path,
    repo: Repository,
    commit: str,
    *,
    depth: int = 2,
    into: Path | None = None,
) -> tuple[Path | None, list[str]]:
    """Write the chain from *commit* where a person can open it; and the lines.

    The same walk the release command drops into its own trace, asked
    for from a commit instead. The directory is the contract's
    ``[ci] profile-into`` unless the caller names another.
    """
    from livery.footman.profile import as_trace

    kept, why = policy(root)
    if why:
        return None, [f"profile: {why}"]
    walked = chain(root, repo, commit, depth=depth)
    if not walked.events:
        return None, walked.lines
    where = into or Path(kept.into)
    at = where if where.is_absolute() else root / where
    at.mkdir(parents=True, exist_ok=True)
    path = at / f"chain-{commit[:12]}.json"
    stamps = [
        float(event["ts"])
        for event in walked.events
        if isinstance(event.get("ts"), (int, float))
    ]
    origin = min(stamps) if stamps else 0.0
    shifted = [
        {**event, "ts": round(float(event["ts"]) - origin, 1)}
        if isinstance(event.get("ts"), (int, float))
        else event
        for event in walked.events
    ]
    path.write_text(as_trace(shifted, origin=origin), encoding="utf-8")
    return path, [*walked.lines, *sweep(at, kept.keep)]

write_run

write_run(root: Path, repo: Repository, *, run_id: str = '', head_sha: str = '', into: Path | None = None) -> tuple[Path | None, list[str]]

Write a run's assembled trace where a person can open it; and the lines.

For investigating a run that has already ended, which is what the traces are kept for. Without a run_id the forge's newest run for head_sha is the one. The directory is the contract's [ci] profile-into unless the caller names another.

Source code in packages/workshop/src/livery/workshop/_traces.py
def write_run(
    root: Path,
    repo: Repository,
    *,
    run_id: str = "",
    head_sha: str = "",
    into: Path | None = None,
) -> tuple[Path | None, list[str]]:
    """Write a run's assembled trace where a person can open it; and the lines.

    For investigating a run that has already ended, which is what the traces
    are kept for. Without a *run_id* the forge's newest run for *head_sha* is
    the one. The directory is the contract's ``[ci] profile-into`` unless the
    caller names another.
    """
    from livery.footman.profile import as_trace

    kept, why = policy(root)
    if why:
        return None, [f"profile: {why}"]
    found = run_id or (newest_run(repo, head_sha) if head_sha else "")
    if not found:
        return None, [f"profile: the forge lists no run for {head_sha[:12]}"]
    made = assemble(root, repo, found, head_sha=head_sha)
    if not made.events:
        return None, made.lines
    where = into or Path(kept.into)
    at = where if where.is_absolute() else root / where
    at.mkdir(parents=True, exist_ok=True)
    path = at / f"run-{found}.json"
    # The stamps are relative to the run's own first moment, so the file says
    # where that sits: another timeline can be laid on this one.
    path.write_text(as_trace(made.events, origin=made.origin), encoding="utf-8")
    return path, [*made.lines, *sweep(at, kept.keep)]