sparkles:build-primitives task DAG — Specification
Abstract
The task DAG runs a set of typed tasks with dependencies, and reports them. A command plans its work as a validated graph of tasks. Each task has a stable identity, a weighted resource claim and a typed action, and each edge a condition such as "on success" or "on failure". One executor runs the graph on Event Horizon fibers under a single job budget, with structured cancellation. One reporter turns its event stream into deterministic transcripts, live terminal views or streamed logs. The result is the same whichever order the work completes in: the outcome, its primary cause and the plain transcript.
Introduction
Repository tooling runs many independent jobs: package builds and tests, documentation examples, link checks, statistics fetches. Run one at a time, they waste the machine. Run with ad hoc thread pools and polling loops, they produce logs that change from run to run, failures that depend on timing, and child processes that outlive an interrupted command.
The hard part is not concurrency itself. Fallback work must run only after a failure, and summaries even after one. Fail-fast must stop new work, kill process trees and still drain their output. Heavy jobs must not starve behind a stream of light ones. And the report must name one primary failure, the same one on every run.
This package models every unit of work as a task node in a directed acyclic graph whose edges carry conditions. A single executor fiber owns all graph state: it admits ready tasks by their longest chain to the end of the graph against a weighted capacity, a thread budget and a memory budget, resolves edges as prerequisites finish, and publishes typed events. Task actions run on any scheduler worker and report back over bounded cross-worker channels. Because decisions are made by one owner, and outcomes and the primary failure are decided by presentation order, neither depends on completion order.
The task DAG does not know any particular command. Commands, their graphs, and the CLI belong to the consumer; the reference consumer is apps/ci, specified in the apps/ci command specification. Compiling packages is the build graph's job: it lowers builds into task nodes for this executor. The interactive terminal reporter is supplied by the consumer, because it needs a UI library this package does not depend on. Distributed admission across several executor fibers, persistent scheduler state and a workflow file format are out of scope.
Section 1 states the invariants. Section 2 defines package discovery and focused selection, §3 the core model, and §4 the execution environment. Then come §5 cancellation, §6 determinism, §7 reporting, including CI-provider integration, §8 the dry-run projection and §9 the module layout. Delivery history lives in PLAN.md, and the choices behind the design in decisions.md.
1. Invariants
- One owner. A single executor fiber owns admission, edge resolution, outcomes and event sequence numbers. Action fibers report observations and never change graph state.
- Order-independent results. Outcomes, the primary failure, the exit status and the plain transcript (with timings off) are functions of the graph and the actions' results, not of completion order.
- No polling. Waiting is parking on Event Horizon: timers, channels, process completions. No task path sleeps, polls or spins.
- Nothing outlives the run. When the executor returns, no task fiber, child process, pipe or channel user remains.
- Bounded memory. Event channels, output buffers and replay storage are bounded; overflow spills to the task's directory or is counted, never silently dropped.
- One writer. The reporter fiber is the only writer to the user-facing output streams.
2. Package discovery and focused selection
2.1 Package graph
Discovery reads the root dub.sdl, each sub-package manifest, and the selected configuration's in-tree dependencies. Each package has:
struct Package
{
PackageId id; // stable qualified package name
string shortName; // e.g. "base"
string path; // e.g. "libs/base"
string configuration; // the active configuration
PackageId[] dependencies;
PlatformSet platforms;
}TDS1: Graph validation. Discovery must reject duplicate ids, unknown in-tree dependencies, self-edges and cycles before execution. An edge A -> B means B depends on A. Lists are normalized by PackageId, never by associative-array iteration order.
TDS2: The active configuration. A test mode must activate the unittest configuration when the recipe declares one. Otherwise, and for build modes, it activates the first configuration whose platforms allow the host, as dub does. A package's edges are its top-level in-tree dependencies plus those of its active configuration. A dependency on the root package adds no edge, and neither does an optional dependency that is not on by default.
TDS3: Package edges are selection data. Package edges must drive only the --dependencies and --dependents closures (TDS7). A consumer decides which of them become task edges.
Rationale: a package's test never waits for another package's test. It waits only for the build actions its own binary needs, which the build graph derives from these same edges.
2.2 --from
TDS4: Selector matching. --from may be repeated, and each occurrence may take one or more selectors. A selector must match any of:
- a short package name, such as
base; - a qualified name, such as
sparkles:base; - a repository-relative directory, such as
libs/base; - a git-style glob over any of those forms, such as
sparkles:ui-*orlibs/ui*.*and?stop at/,**crosses it, and\escapes the next character. There are no[...]classes.
Matches from all --from selectors are unioned. A selector, glob or not, that matches nothing must be an error, so a misspelled CI selector cannot become a green no-op.
2.3 --since
TDS5: The base revision. --since REF must compute changes from merge-base(REF, HEAD) through the working tree, including staged, unstaged and untracked paths. --since with no value resolves the current branch's upstream, and origin/main when there is none. Failure to resolve a base is an actionable selection error.
TDS6: Changed paths select by claims. A changed path must seed the root of each request whose closure holds a package and configuration whose input set claims it, and the root of every request when a workspace input holds it (BGW12). A request whose reads are not all stated, because its resolution failed or its closure reaches an opaque entry, must be seeded by any change. A request is the package's test root for a test selection and its default configuration for a build.
Where a path lies does not decide what it selects: a path in no package's directory selects the packages that read it, and documentation beside a recipe selects none. A removed path is judged like any other, without the file and without the base revision's packages, and a rename counts as a removal plus a creation. A path that no request claims and no workspace input holds selects nothing. The workspace inputs are derived (the files planning read and the planner's closure) except the toolchain's definition, which the consumer states; the repository's statement is part of the apps/ci command specification.
2.4 Selection algebra
TDS7: Evaluation order. Selection must be evaluated in this order:
- Discover and validate the full package graph.
- If neither
--fromnor--sinceis present, seed all packages. - If only
--fromis present, seed its union of matches. - If only
--sinceis present, seed the packages TDS6 selects. - If both are present, seed the union of both match sets.
- If
--dependenciesis present, add the transitive dependency closure. - If
--dependentsis present, add the transitive reverse-dependency closure. - If both closure flags are present, compute both to a fixed point from the original seed. The result is the union, not an order-dependent expansion.
- Apply platform eligibility. Ineligible packages remain visible as skipped nodes rather than disappearing.
- Sort by stable package id and induce the package edges among the selected packages.
TDS8: Empty selections. An empty final selection must be an error unless every seed is represented by an explicit platform-skipped node.
3. Core model
3.1 Task nodes
struct TaskNode
{
TaskId id; // stable, unique, printable
TaskKind kind;
string label;
PresentationKey order;
ResourceClaim resources;
TaskAction action;
FailurePolicy failurePolicy;
OutputPolicy outputPolicy;
}TDM1: Stable ids. A TaskId must be derived from semantic identity, for example test:sparkles.base:unittest or docs:verify:README.md:readme_versions. It must not contain a memory address, random number, temporary path or discovery index.
TDM2: Presentation keys. A PresentationKey is a tuple of command phase, package or file key, work-kind key, and within-owner ordinal. It must define the order of dry-run output, buffered output replay, failure replay and summaries.
TDM3: Closed actions. A TaskAction must be a closed sum type for known work, not an arbitrary shell string. A process action carries its argument vector, environment, working directory, stdin policy, timeout and task-directory policy as data. Its environment is either a delta over the command's own environment or complete, replacing it. A build-graph action's is always complete (BGA4). An in-process action names a typed handler.
TDM4: Redaction. An environment value marked redacted must be passed to the child and must never appear in an event or a dry run. Every occurrence of it in a line the child prints is masked as <redacted> before the line reaches an event or a spool. A multiline value is also masked line by line, because the child's output is framed into lines before masking (T11): each of its lines of at least 8 bytes, as a shorter one would mask unrelated output and hides too little to matter (T14).
3.2 Edges
enum EdgeCondition { onSuccess, onFailure, onCompletion, always }
struct TaskEdge
{
TaskId prerequisite;
TaskId dependent;
EdgeCondition condition;
EdgeReason reason;
}Normal dependency edges use onSuccess. Reducers that summarize failed work use onCompletion. Cleanup uses always. A fallback uses onFailure on its prerequisite, which has a provisional failure policy (TDC4).
TDM5: Edge satisfaction. A prerequisite's terminal outcome must satisfy an edge as follows:
| Condition | Satisfied by |
|---|---|
onSuccess | Succeeded, Degraded, Skipped |
onFailure | Failed, provisional Blocked |
onCompletion | every outcome except Cancelled |
always | every outcome |
A skipped prerequisite satisfies onSuccess: a skip is an eligibility rule, not a broken contract. A provisional block is a Blocked outcome whose root cause is a failure under a provisional policy (TDC4). It satisfies onFailure, so a fallback attached to the last node of a provisional chain still fires when an earlier node of that chain failed.
TDM6: Blocked and unneeded nodes. A node is decided only once every prerequisite is terminal, so its outcome never depends on completion order. When one of its edge conditions is impossible, the first of these rules that applies decides it:
- Unneeded: if every impossible edge is an
onFailureedge whose prerequisite endedSucceeded,DegradedorSkipped, or comes from a node that is itself unneeded, the node isBlocked(conditionUnmet): a fallback's later nodes are unneeded with its first. That outcome never fails the command, and summaries count it apart from other blocks: a fallback that was not needed. - Blocked by a failure: if any impossible prerequisite failed or is a block that descends from a failure, the node is
Blockedand names the lowest-index such prerequisite. A failure outranks a cancellation beside it (TDC2 item 4). A block whose root cause is a provisional failure is a provisional block, which does not fail the command. - Cancelled: if every impossible prerequisite was cancelled, apart from unneeded
onFailureedges as in rule 1, the node isCancelled(notAdmitted). - Blocked: otherwise the node is
Blockedand names its lowest-index impossible prerequisite that is itself blocked.
Cleanup nodes are idempotent and run under a cancellation protection region.
3.3 Resource claims
struct ResourceClaim
{
uint jobsWeight; // >= 1 for runnable work
ulong memoryBytes; // the predicted peak: the second dimension under a memory budget (TDM18)
string[] exclusiveKeys;
Duration predictedDuration; // what the node's chain is measured in (TDM8)
uint threads; // the threads it runs, which may exceed its tokens (TDM10)
ulong coldBytes; // a conservative charge while it runs, on a default prediction (TDM18)
bool lookupFirst; // looks a stored result up before it is charged (TDM7)
}TDM7: Weighted admission. The executor must own --jobs N weighted tokens. A node starts only when all its exclusive keys are free, no node whose file claims conflict with its own is running (TDM15), jobsWeight tokens are available, under a memory budget its memoryBytes fit (TDM18), and under a thread budget its threads fit (TDM10). A claim larger than total capacity, or than either budget, is clamped to it, so it runs alone rather than deadlocking. A node whose fiber cannot be spawned fails at once as Failed(spawnFailed), releasing what it claimed (T12).
A node that looks up first (lookupFirst) is admitted twice. Its lookup starts once its exclusive keys are free and no conflicting node runs, holding those but none of its tokens, threads or memory, with at most lookupSlots such nodes between their start and their charge; a lookup takes no key or file the reserved node needs (TDM8), and starts under the gate's hold but not its cancel (TDM19). Only when its driver says it executes (TaskContext.execute), after a lookup that found no stored result, is its claim considered, as a ready node's is, in admission order with the same backfill and reservation (TDM8), and charged (TaskCharged) before its action runs; a cancellation meanwhile, or while the charge is delivered, ends it cancelled, unexecuted, and a charged node is timed from its charge. So a run whose lookups hit charges nothing, and a lookup never waits for memory or tokens an execution would need.
TDM8: Admission order. Ready nodes must be considered in admission order: by the longest chain of predicted durations from the node to the end of the graph, its own included, longest first, then in presentation order. The chain follows every edge but a fallback's (onFailure), which a run that goes well never takes. A node with no prediction (predictedDuration) counts as one second, so a graph without predictions is ordered by depth. A node that does not fit the tokens, the threads or the memory left must not hold back a later node that fits: that one starts past it (backfilling). A node is aged once the starvation bound, 30 seconds unless the run sets another, has passed since a later node first started past it. Each admission pass considers the aged nodes first, in admission order, skipping one that waits for a key or a conflicting writer. The first that does not fit is reserved: until twice the bound has passed, another node starts only if it fits, shares no key or file with it, and is predicted to end before the reserved one could start, were the running nodes to end as predicted (a node without a prediction counting a second); after it, no other node starts while it does not fit. So a heavy node waits at most twice the bound and then until enough running nodes end, however many light ones keep arriving. The longest chain is a heuristic under the tokens, the threads and the memory, not an optimum. A node that waits only for an exclusive key or a conflicting writer holds back nothing (decision T17).
TDM9: Default weights. Default weights are declared by work kind. A planner may override them for documented packages:
| Work kind | Default weight |
|---|---|
| Pure scan, parse, reduce, or git query | 1 |
| Build-graph actions | per the build graph's BGA8 |
| One standalone or markdown example run | 2 |
| Known DMD-frontend-heavy package task | 4 |
| Mutating docs rewrite | 1, writing its file (TDM15) |
TDM10: Capacity. Without --jobs, capacity must be sparkles.base.hw_caps.hwParallelism(), which already folds in CPU quotas, available memory, load and swap, or, for a run with a memory budget, the CPU count under its quotas and load, cut by the memory the budget is capped by (a small container's, a --memory-max), never by the memory free at the start nor by swap, read once: the budget follows the host's memory as the run goes (TDM18), and a capacity cut by the memory free at the start would not. Tokens count parallelism only: memory is admitted by its own dimension (TDM18), never by a unit per GiB. Explicit --jobs sets capacity exactly. Work that starts its own threads, such as the test runner's -t N or a linker, takes its thread count from its claim, or, when it uses its threads in bursts, states more threads than tokens (ResourceClaim.threads): its tokens are what it uses on average. Under a thread budget the running nodes' admitted threads, each node's threads or else its weight, clamped to the budget, must add up to at most the budget, so task-level parallelism does not multiply into unbounded threads; a node whose threads exceed the budget is charged the whole budget and so runs alone, and with nothing running the first ready node starts whatever its threads. A single LDC compile is single-threaded and needs no cap.
TDM18: Admission by memory. When the run has a memory budget, a node must be charged only when its memoryBytes fits beside what the charged nodes hold, at its start or, for one that looks up first, when it executes (TDM7). A claim above the budget runs alone: it starts only when no node is charged, and nothing else is charged while it runs, a claim of zero included. With nothing charged, the first node waiting for its claim is charged whatever its memory, subject to the gate (TDM19), so a wrong prediction costs time and never stalls the run. A running node holds the larger of its charge at its start and the largest resident set it has reported (TaskUsage), at most the budget, so a node that outgrows its prediction keeps later ones waiting rather than sharing memory it already uses. A node's charge at its start is the larger of its prediction and its coldBytes, a conservative charge its planner gives a node on a kind's default, and it holds that charge while it runs, whatever it reports below it: a compile grows for most of its life, and an early sample says little of its peak. So a burst of nodes on low defaults does not start together, nor fill the budget again once each reports its first resident set. A report of no resident set counts for nothing. Without a budget the dimension is off. The run's memoryBudget is a cap: each time the executor asks the gate (TDM19), the budget it fits charges in becomes the smaller of the cap and what the charged nodes hold now, by the resident sets they last reported as current, not their peaks, plus the gate's headroom, what the host has free beyond its reserve. Charges a node has not grown into yet are not credited twice: what it has not taken is still in the headroom; memory a node frees counts in both only until its next sample. The budget so rises as soon as the gate sees memory freed; when it shrinks below what the charged nodes hold, admission stops and nothing that runs is stopped. A claim runs alone by the cap, not by the budget of the moment. The predictions are the planner's: ci records each action's measured peak and predicts from it, but for a test leg its caller narrows with runner options of its own (CIC23).
TDM19: The admission gate. A run may have a gate the executor asks before it charges a node, and under a memory budget at every admission pass, which answers open, hold or cancel, with a headroom (TDM18); a lookup (TDM7) starts under a hold, and "runs" below means charged:
- Hold, bounded (memory pressure while memory runs short): no further node starts while one runs, for at most 30 seconds since the hold began or a node last finished; with nothing running, one node is admitted. Nothing running is stopped. The bound lifts the hold, not the budget: past it one more node starts only if its claim fits the memory budget of the moment (TDM18), which the gate's headroom keeps low while memory runs short, so under a hold that lasts a node waits for one to end as often as for the bound.
- Hold, unbounded (a file system under its reserve): no further node starts while one runs; with nothing running, the run is cancelled with the gate's message.
- Cancel (a file system under its floor): the run is cancelled with the gate's message, as
CancelCause.resources, which fails the command; running nodes are stopped as any cancellation stops them.
A cancellation by the gate, like any other, still starts each cleanup node once it is ready. The executor asks at most once per admission pass, and, while nodes run, at least four times a second whether or not a node is ready, so a file system that fills while every token is taken still cancels the run. Its timer is one fiber for the whole run, taken before any task's.
TDM20: A memory-limit failure. A process task killed at its own memory limit (Event Horizon §13.7) must end as Failed(memoryLimit), its output naming the limit and its peak, even when its leader exited zero, since the limit killed the rest of its tree. A kill by a limit above it, such as its run's scope, stays a signal failure. The limit is the task's prediction times the run's factor, saturating, at least a floor and at most a ceiling, when the prediction is measured (ResourceClaim.memoryMeasured); an unmeasured one, a kind's default, gets the ceiling alone. An in-process action that starts processes is told the same limit (TaskContext.memoryLimit) and runs them under it together; it reports their peak and a kill at it, and the kill fails it the same way.
Exclusive keys protect semantic resources, not implementation mutexes, and resources that are not files: coverage-publish and a publication slot. A file a node writes is a file claim (TDM15). stdout is not an exclusive task resource, because the reporter is its only writer.
3.4 Outcomes
alias TaskOutcome = SumType!(
Succeeded,
Failed,
Skipped,
Cancelled,
Blocked,
Degraded,
);| Outcome | Meaning | Fails command |
|---|---|---|
Succeeded | Authoritative work completed and its contract holds. | No |
Failed | Work ran, or could not start, and its authoritative contract does not hold. | Yes |
Skipped | A declared eligibility rule excluded the work, such as platform support. | No |
Cancelled | Work was admitted or pending but interrupted by fail-fast, signal, or shutdown. | No additional failure; the initiating cause controls exit. |
Blocked | A required predecessor did not succeed or its edge condition was impossible. | Yes if the block descends from failure; no for conditionUnmet; otherwise reported with the cancellation cause. |
Degraded | The authoritative contract passed, but optional evidence or measurement is unavailable. | No |
TDM11: Causes and observations. Every non-success outcome must carry a typed reason and, where applicable, its causal tasks. Outcomes and events name tasks by their index in the validated graph's presentation order, not by TaskId, so their members hold no pointers. Process status, timeout, signal, bounded output references, elapsed time and sampled usage are observations attached to an outcome, not booleans that replace it. A test action also attaches its passed, failed and skipped counts and its failed tests' names (CIC11).
Which measurements an observation carries, with their units and qualities, is specified by observability, which adds a measurement table that the executor fills and hands over at the run's end (OBA5), and keeps each run as a run record.
3.5 Events
alias TaskEvent = SumType!(
GraphPlanned,
TaskReady,
TaskStarted,
TaskOutput,
TaskUsage,
TaskFinished,
CancellationRequested,
RunFinished,
TaskFresh,
TaskStale,
TaskReused,
TaskNotice,
AdmissionState, // TDO10
TaskCharged, // TDM7
);TDM12: Event sequence. Every event must carry a run-local monotonic sequence number and a monotonic timestamp. Task output also carries task-local stream and chunk sequence numbers. Events reach the sink in sequence order: a number is drawn only by the producer about to deliver its event.
TDM13: Event producers. The executor must be the sole producer of lifecycle events. Process and CPU adapters send observations back to it through bounded Event Horizon channels that deliver across scheduler workers, preserving ownership and backpressure. Reporters consume events and cannot alter scheduling.
TDM14: Owned output. Events must not borrow child buffers. Event payloads hold no pointers. An output line travels in the event envelope's text field, beside the payload. Output is line-assembled at the boundary, with an explicit final unterminated line event. Per-task output is bounded in memory, each line counted with its terminator so that empty lines count too, and spills to its task directory when necessary. Distinct task ids have distinct task directories, all under the run's root (T10). A failed task's diagnostic tail and spill path remain available until final reporting.
3.6 File claims and freshness
struct WriteClaim
{
string path; // relative to the worktree root
bool tree; // the directory `path` and everything beneath it
}
struct FileClaims
{
Fileset reads; // a fileset of the graph's arena; `Fileset.init` states nothing
WriteClaim[] writes;
}TDM15: File claims. A node may state the files it reads, as a fileset of the arena its graph owns, and the files and directory trees it writes (BGW16). Validation must derive the conflicts:
- A read set conflicts with a write claim unless the set's verdict on the claimed path, taken with no facts about the entry, proves it cannot hold it:
rejectfor a file,skipfor a tree. A.gitignorescope that only a resolution reads counts as possibly holding the path, and so does a set holding a link the graph was told resolves to it. - Two write claims conflict when one path is the other or lies beneath a tree the other claims.
A node that reads what another writes must be ordered with it by a path of edges, in either direction; validation rejects a graph in which neither precedes the other, naming the reader, the path and the writer (T15). Nodes whose writes conflict never run at the same time (TDM7). A write claim's path is relative and normalized, or the graph is rejected. A node that states no claim conflicts with nothing.
TDM16: Freshness. An action driver may say, on the node's fiber and before its action, whether a result recorded for the same action and inputs is reused. A node's identity never holds a content id (invariant 6); the driver computes the input identity. A fresh node emits TaskFresh with that identity, runs nothing and ends Succeeded. A node it calls stale emits TaskStale with the reason and the path the reason names, in the envelope's text, then runs. The reasons are the build graph's miss reasons (OBA8), no recorded result, and a prerequisite that ran in this run, which makes stale a node the driver calls fresh. A node whose driver says nothing emits neither event. Reporters end the node's line with , fresh or , ran: and the reason, a path when there is one.
TDM17: Reuse. A driver that decides while it runs, rather than before, to adopt a stored result instead of executing the node's action may say so through its context, which emits TaskReused before the node's outcome. The build graph's store hit is the case (BGK3). The event changes no outcome and no line of the plain transcript; a live view counts the node as reused rather than executed.
TDM21: Notices. A driver may report a line of its own, apart from the action's output, through its context, which emits TaskNotice with the line in the envelope's text. A notice says what the driver found that a reader must see whatever the node's outcome: a result that could not be published, a rebuild unlike its record, an input edited while the action ran. Reporters show every notice whatever the node's output policy (TDO3): a block holds its notices after the lines its policy shows, each prefixed [<label> notice] , and an interlaced transcript writes each as it arrives. A notice changes no outcome. The action's own output, and the driver's notes that only explain an outcome, such as a cache note, remain output lines.
TDM22: A thrown task. Whatever a driver throws while it runs a node, an Error such as a failed assertion or a range violation included, and any Error it throws saying whether the node is fresh, must end that node Failed(contract), with a notice (TDM21) naming what was thrown: its type, its source position and its message. The node never ends with another outcome or none, and the run goes on as after any failure: its dependents are blocked, fail-fast cancels, and a protected cleanup that throws fails the same way. A node the run had asked to stop when it threw ends cancelled, as TDC3 has it, its notice still written.
4. Event Horizon-only execution
TDE1: One runtime. sparkles:event-horizon must be the sole concurrency and asynchronous-I/O runtime inside a task-DAG consumer:
- The command starts one
LoopGroupand one root structured scope. - Scheduler tasks are Event Horizon fibers.
- Subprocesses use Event Horizon's supervised runs (
supervise), with piped stdio, asynchronous reap, and an owned POSIX process group or Windows Job Object. - Timers and timeouts use the Event Horizon clock.
- Executor communication uses bounded cross-worker Event Horizon channels.
- Blocking work, including a blocking HTTP client, runs on Event Horizon's scheduler-integrated
BlockingPool, never on a scheduler worker.
TDE2: Forbidden constructs. Command and executor modules must not use std.parallelism.TaskPool, detached core.thread.Thread workers, std.process.execute for task execution, sleep or poll loops, or ad hoc atomic status polling.
TDE3: No fallback executor. Anything represented as a TaskNode must execute through the Event Horizon executor. If loop creation fails, the command reports a structured setup failure. Small bounded planning reads may run synchronously before LoopGroup.run.
The executor is generic over the Event Horizon capability row where practical. Pure graph tests use a deterministic fake action driver and TestSched with a fake clock. Process integration tests use real short-lived children.
5. Structured cancellation and fail-fast
TDC1: Scope ownership. The root command scope must own all scheduler fibers, child processes, channels, task directories and the reporter. A task does not outlive it.
TDC2: Fail-fast. On an authoritative task failure with --fail-fast, the executor must:
- record
TaskFinished(Failed)completely; - emit
CancellationRequested(failFast, causalTaskId)exactly once; - close admission, so no newly ready ordinary node starts;
- turn pending nodes into
Cancelled(notAdmitted), unless TDM6 decides themBlocked, for a failed dependency or an unneeded fallback; - let running in-process tasks observe scope cancellation at defined yield points;
- send running child process groups
SIGTERMon POSIX, thenSIGKILLafter a bounded grace period; peer platforms use their owned-tree termination; - drain stdout and stderr through terminal completion and reap every child;
- run cleanup, task-directory removal and the final reporters inside a protected cleanup scope. A
cleanupnode still starts once ready, and its action runs underprotect.
TDC3: The primary cause. The primary cause must be the lowest-index authoritative failure among the completions the executor collects in one turn. A node the executor interrupted that then reports Failed is recorded as Cancelled(interrupted), because the interrupt, not the node, caused the failure. Conversely, a node that reports Cancelled while neither the run nor the executor's enclosing scope was cancelled is recorded as Failed(contract): no cause stands behind its cancellation to control the exit status (T13).
TDC4: Provisional failures. A failure of a node with a provisional failure policy, and a provisional block descending from one, must not initiate fail-fast, fail the command or become the primary cause. Its onFailure fallback classifies the authoritative result. A degraded result does not initiate fail-fast either.
TDC5: Signals and exit codes. SIGINT and SIGTERM must follow the fail-fast path with an external-interrupt cause. Exit codes are 130 for SIGINT, 143 for SIGTERM, and 1 for task or planning failure. Success, skips and degradations return 0. A second interrupt shortens the grace period but still reaps children and restores the terminal.
TDC6: Without fail-fast. Without --fail-fast, independent branches must continue. Nodes with unsuccessful required predecessors are blocked, and reducers connected by onCompletion still run and summarize the complete attempted set.
6. Determinism
TDD1: Deterministic results. For the same repository state, options and action results, these must be identical:
- node ids, the edge set, resource claims and the dry-run plan;
- package and file selection;
- ready-queue tie-breaking, by
PresentationKeythenTaskId; - buffered task-block replay, diagnostics within a block, failure replay and final summaries;
- reducer output order;
- the exit status and the primary cause (TDC3).
Task completion times are not deterministic. TTY animation reflects real completion order, and --interlaced exposes runtime output order. Neither affects final ordering or outcome selection.
TDD2: Order-independent planning. Graph construction must not depend on associative-array iteration, directory iteration, completion order, wall-clock timestamps, random ids or temporary paths. A graph cycle reports the stable shortest discovered cycle, with ids ordered from its lowest member.
7. Reporting and output
7.1 Single writer
TDO1: One writer. One reporter fiber must be the only writer to the user-facing stdout and stderr streams. Logger records that are part of task presentation enter the event channel rather than being written from workers. So every emitted line is atomic, and terminal control sequences have one owner. A live view's redraw between events (TDO8) runs on a fiber of the reporter's scheduler, so it never overlaps the handling of an event.
7.2 Interactive TTY
The TTY reporter is supplied by the consumer, because it depends on a UI library this package does not import. apps/ci's reporter adapts sparkles:ui's TaskReporter over task events.
TDO2: TTY behaviour. A TTY reporter must:
- register all planned nodes before execution, so totals do not move;
- show each running task's spinner, elapsed time and a bounded tail, a task that looks up first (TDM7) running from its charge, not its lookup;
- graduate terminal transitions into scrollback, in real event order;
- retain a bounded diagnostic tail per failure, and replay failures in presentation order after the live region finishes;
- end with a summary of succeeded, failed, degraded, skipped, blocked and cancelled counts, plus wall, CPU and RSS statistics when available;
- restore the terminal on success, failure or cancellation, as protected cleanup.
It may collapse pending tasks past a height limit, with visible counts.
TDO8: A live view beside the transcript. A command writing to a terminal may keep the plain transcript (TDO3, TDO4) and add a live view beneath it, instead of a TTY reporter of its own. Then:
- the transcript's lines must print above the view as the plain reporter releases them, unchanged, so the scrollback holds exactly what a run without a terminal writes;
- the view sees every event after the transcript has, and redraws between events at most every 100 ms, so running times move;
finishends the transcript first, then the view, which restores the terminal as protected cleanup.
The view is the consumer's, like the TTY reporter; this package defines only the seam (LiveView) and the reporter that drives both.
TDO9: A consumer's transcript. A command may draw its transcript itself (Transcript) in place of the plain reporter's: a person's account of the run rather than the ordered, deterministic one, written where the command chooses. Then the transcript sees every event first and ends first, and a live view, when there is one, sees each event after it and ends after it (TranscriptAndView). A command that draws its own transcript still owes what TDO7 asks of child output on a CI service: masked values, fenced lines.
TDO10: The admission trace. The executor must emit an AdmissionState event after every admission pass whose state differs from the last one it emitted: the ready and running counts, how many nodes the pass started, what the running nodes hold of the tokens, the threads and the memory against the capacity and the budgets (the memory budget of the moment and its cap, TDM18), the first ready node in admission order that waited for its claim, a lookup never one, and why (WaitReason: tokens, threads, memory, a claim above the budget, a key or a conflicting writer, the gate), and the reserved node (TDM8), which is that first node while it waits; a pass that starts nothing reports only a change of state. With TaskReady, TaskStarted, TaskCharged and TaskFinished, these events trace every decision (the ready count includes the nodes awaiting their charge, the running count only the charged ones); a reporter may consume them, and TracingReporter writes them one JSON object a line, naming tasks by id, beside another reporter's work.
TDO11: An observer of the run. A command may add an observer beside its reporter (the build graph's RunReporting.observer, a Transcript): it sees every event before the reporter does and ends before the reporter does, so what it gathers is complete when the reporter writes its last line; with the admission trace (TDO10), it sees each event before the trace does too. An observer that throws, or cannot be made, is let go: the run and its reporter go on and end without it. An observer writes nothing to the user-facing streams (TDO1); what it gathers is the command's to report, such as ci test's summary of a run (ci task-DAG CIC29).
TDO12: Quiet success. The plain reporter may be asked to write nothing for a task that succeeded with no notice that ran for no stale input: in block output neither its lines nor its terminal line; interlaced, whose lines are written as they come, held ones included, not its terminal line; every other task, the failure replay and the summary are written as without it. It is off by default, so a command shows each task unless it asks otherwise: a command whose graph holds a node per file asks, so that its transcript names what failed, not every file that passed.
7.3 Non-TTY default
TDO3: Deterministic blocks. Non-TTY output must contain no cursor movement, spinner frames or rewritten lines, and no colour when terminal capabilities disable it. Each task's output is buffered or spooled and emitted as one block in PresentationKey order, once all earlier blocks are terminal.
A block is the task's lines, each prefixed [<label> <stream>] , followed by exactly one <label>: <outcome> line, where <label> is the node's label, or its id when it has none. A line holding line breaks is written as that many lines, each prefixed. The summary names failed tasks by id, which commands take. The node's output policy decides which lines the block holds:
replay: all of them.tailOnFailure: the bounded tail, only when the task did not succeed.lastLineOnSuccess: the bounded tail when the task did not succeed, and its last line when it did, as a test run ends with its summary.none: none.
A block then holds the node's notices (TDM21), whatever its policy, after those lines and before its <label>: <outcome> line.
Elapsed times are the only part that varies with execution, and they are optional. With them off, the transcript is byte-identical for the same graph, outcomes, output and notices.
A heartbeat may report aggregate completed/total progress to stderr during a long silent run. It carries no task output, is disabled when stderr is not independently writable, and is omitted from machine-readable output.
7.4 --interlaced
TDO4: Interlaced lines. Interlaced mode must emit each assembled output line of a replay node as soon as the reporter receives it:
[test:sparkles.base:unittest stdout] ...
[test:sparkles.ui:unittest stderr] ...- Prefixes are mandatory even when one task runs.
- A line is never split by another task, and stdout and stderr identity is retained.
- An unterminated final fragment is emitted once.
- Ordering across tasks is nondeterministic.
- A node of another policy (TDO3) streams none of its output: the lines its policy shows depend on how it ended, so they come with the terminal lines, a failure's in the failure replay.
- A notice (TDM21) streams as it arrives, whatever the node's policy.
The terminal lines, the failure replay and the summary are written together at the end, sorted in presentation order. With a provider's groups, the terminal lines are one collapsed group and the failure replay one expanded group.
On a TTY, --interlaced disables per-task live tails and prints above a compact aggregate TaskReporter frame. With --jobs 1 it still prefixes output.
7.5 Machine output
TDO5: JSON documents. A command that owns a JSON mode must emit one JSON document and no human UI on stdout. Logs and warnings go to stderr. A command's report JSON is not a task-event stream, and a JSON-lines event stream is out of scope.
7.6 CI-provider integration
TDO6: One provider module. A reporter that runs under a CI service must use that service's log conventions through one provider module, never by testing environment variables itself. The module detects the provider and exposes these operations:
| Operation | GitHub Actions | GitLab CI | Buildkite | Azure Pipelines | CircleCI and others |
|---|---|---|---|---|---|
| Detect | GITHUB_ACTIONS=true | GITLAB_CI=true | BUILDKITE=true | TF_BUILD=True | CIRCLECI=true, else none |
| Open a group | ::group::<title> | \e[0Ksection_start:<unix-time>:<name>[collapsed=true]\r\e[0K<title> | --- <title> | ##[group]<title> | a plain heading line |
| Close a group | ::endgroup:: | \e[0Ksection_end:<unix-time>:<name>\r\e[0K | none | ##[endgroup] | none |
| Annotate a line | ::error file=…,line=…::<msg> | none | none | ##vso[task.logissue type=error;sourcepath=…;linenumber=…]<msg> | none |
| Mask a secret | ::add-mask::<value> | none (configured masking) | none | ##vso[task.setvariable variable=<name>;issecret=true]<value> | none |
| Step summary | append to $GITHUB_STEP_SUMMARY | none | buildkite-agent annotate | none | none |
| Set an output | append to $GITHUB_OUTPUT | none (dotenv artifacts) | buildkite-agent meta-data set | ##vso[task.setvariable variable=<name>;isOutput=true]<value> | none |
The provider module's golden tests are checked against each provider's published syntax, cited in its sources.
TDO7: Provider rules.
- A provider without an operation must degrade to plain output. It never emits another provider's syntax.
- A group never contains a partial line. Opening and closing a group are ordinary line-atomic writes by the single writer.
- In block mode, each replayed task block is wrapped in a group titled with the task id and outcome.
- In interlaced mode, interleaved lines are never grouped. The closing terminal lines and the failure replay are each wrapped in one group.
- A failure that carries a source location is annotated where the provider supports it.
- Redacted values (TDM4) are masked on the provider as well as in task output.
The provider module has no dependency on the task DAG, so other tools that report to a CI service, such as the test runner, can use it.
8. Dry-run contract
TDY1: What a dry run does. --dry-run must perform all side-effect-free discovery needed for a faithful plan: manifest reads, package graph construction, git change queries for --since, the planner's own extraction and scans, platform evaluation and graph validation.
TDY2: What a dry run does not do. A dry run must not:
- run task actions or make network requests;
- create build, temporary, coverage, cache or output directories;
- write any file;
- probe optional toolchains by executing them;
- report success for tasks.
TDY3: Dry-run output. The output must list selection reasons, nodes in presentation order, resource claims, the directories each node's read set starts from and the paths it writes, redacted action summaries, edges with their conditions and reasons, and the pairs of nodes that may not run at once (TDM15). It ends with counts by kind and the total weighted capacity. A planning error exits nonzero. A valid dry run exits zero and emits no TaskStarted events.
9. Module layout
| Module | Responsibility |
|---|---|
sparkles.build_primitives.task.action | The closed action vocabulary and its redacted summary. A leaf. |
sparkles.build_primitives.task.model | Task ids, presentation keys, claims, nodes, edges, outcomes and events. |
sparkles.build_primitives.task.graph | The graph builder, validation, stable topological order, edge resolution and the dry-run plan. |
sparkles.build_primitives.task.executor | Weighted admission, edge resolution, Event Horizon scopes and cancellation. No command knowledge. |
sparkles.build_primitives.task.admission_trace | The admission trace (TDO10): a reporter writing admission decisions as JSON lines. |
sparkles.build_primitives.task.output | The bounded per-task output spool. |
sparkles.build_primitives.task.process | The Event Horizon subprocess adapter. |
sparkles.build_primitives.task.reporter | The reporter interface, the event consumer and ordered block buffering. |
sparkles.build_primitives.task.reporter_plain | The deterministic non-TTY and interlaced reporter. |
sparkles.build_primitives.task.testing | The fake action driver for executor and reporter tests. |
sparkles.build_primitives.workspace.* | Package discovery and focused selection (§2). |
The CI-provider module is its own leaf package, sparkles:ci-provider (see decisions.md).
The pure modules — action, model, graph and workspace — import neither Event Horizon nor UI modules. No module in this package imports a UI library. Reporter modules know events, not commands, and the executor knows action drivers, not command-line parameters.