grove · engine

The engine

One driver task per declared root (crates/grove-daemon/src/engine/), owning that root's status cache, its single background slot, and its warm-pool hint. engine::RootSet owns the map from declared slug to running engine and reconciles it on every roots_changed.

Status is a cache, never persisted, re-derived from disk on restart; a running engine adds only the transients cloning and degraded, which disk cannot say.

Status

grove_api::RootStatus, pinned in contracts/wire-vocab.json as root_status:

statusmeans
readythe bare clone and the trunk checkout are both on disk, no failure recorded
cloninga reconcile has been dispatched for a root not yet on disk
degradeda terminal failure stopped the engine; it waits for an operator or a change
missingdeclared, nothing on disk yet
unknownno engine has run for this root yet — the cache has nothing to say
unavailablea reader's verdict, never a state an engine enters

unavailable is what a reader says when the engine or the lane did not answer inside the reader's budget. Three readers produce it:

  • stream::view — a root whose one lane job of git reads missed SNAPSHOT_BUDGET (3 s), or whose read the lane shed. The row stands but reports unavailable rather than the engine's status, since "ready" beside an empty worktree list is a lie a client cannot detect.
  • engine::set — a status read that did not answer inside STATUS_BUDGET (5 s). A driver only ever awaits its mailbox, so this should never fire; it keeps a whole-home doctor from hanging on one bad engine.
  • the CLI — grove tree list reads an unavailable row as no answer and falls through to the disk (commands::tree_list).

The transition table

Every status change goes through one function, engine::status::next_status(current, transition). The question it answers is always the same: preserve the transient the driver owns, or trust disk? Trust disk too eagerly and a root mid-clone reads missing, so the next event dispatches a second clone; preserve too eagerly and a finished clone stays cloning forever.

disk_status(home, slug) is the engine's one filesystem read: Ready when the root's bare (roots::bare_dir, roots/<slug>/bare) and the trunk checkout (roots::trunk_dir, so whichever directory under code/<slug> this root's trunk branch names) are both directories, else Missing: a bare with no trunk checkout is the half-realized state reconcile finishes.

current ↓ / transition →ReconcileDispatchedDerive(Ready)Derive(Missing)ReconcileError(Ready)ReconcileError(Missing)
unknowncloningreadymissingreadymissing
missingcloningreadymissingreadymissing
cloningcloningreadycloningreadymissing
readyreadyreadymissingreadymissing
degradedcloningreadydegradedreadymissing
unavailableunavailablereadymissingreadymissing
  • ReconcileDispatched — a root not yet on disk (missing, unknown, or a degraded root retrying its clone) surfaces cloning; anything else is unchanged. Disk is not consulted: the dispatch precedes any read and surfaces the intent to clone.
  • Derive — disk ready always wins upward, because a completed clone is authoritative. Otherwise a driver-owned transient (cloning, degraded) is preserved rather than masked as missing, and everything else takes the honest disk verdict.
  • ReconcileError — the attempt is over, so trust disk plainly. cloning is not preserved here, unlike under Derive — the reason there are two events — since nothing would clear it.

Properties the tests pin (engine/status.rs): the table is total over the whole cross product and never leaves the published vocabulary; it never returns unknown (an entry state only); it never invents unavailable; and re-deriving against an unchanged disk is a fixed point, which is what makes a burst of manifest events cost nothing.

One background slot

At most one of reconcile / sync / fill is in flight per root, chosen in that priority order. Every condition is level-triggered state, re-evaluated on each completion (Driver::drive):

  1. a background op is in flight ⇒ do nothing; the next op is picked when this one lands;
  2. reconcile_pending ⇒ mark ReconcileDispatched and dispatch reconcile;
  3. sync_pending and status is ready ⇒ dispatch sync;
  4. status is ready and the pool hint is off the declared target ⇒ dispatch fill, which adds a slot below target and reclaims the highest one above it. A converge that fails latches (fill_blocked) until the next real event, because the level condition it failed on is still true — without the latch the root re-dispatches into the same failure as fast as git can run.

The slot is taken synchronously in dispatch, before the task that will do the work exists, so a second trigger one line later already sees it occupied: a double clone is unrepresentable.

reconcile_pending is set at start and on every roots_changed, and a reconcile is re-dispatched on every manifest change even for a realized root — the op is idempotent and worktrees may have changed out of band. sync_pending waits for a drive that finds the root ready.

A reconcile folds the pool read — the declared pool.size and the observed slot count — into the same lane job as roots::reconcile_one, so the manifest read never queues separately behind the clone it follows. The Applied outcome and the pool read are applied separately, so a read that succeeded still lands when the reconcile beside it errored. The observed count is taken as truth rather than adjusted by a delta: a reconcile is where a declared worktree claims a slot (worktrees::create/reconcile promote one when the pool has any), so a hint that only ever counted fills would sit stale-high and starve the refill that should follow.

task_started is published from inside the lane job, once the work actually begins — so neither a reconcile queued behind its own root's lane nor one deferred for want of a clone permit is reported as running. The signal that a queued reconcile exists is the root's own cloning status. task_finished is published by the driver when the outcome lands. Both name one of the three background kinds (reconcile | sync | fill) and a coarse outcome (ok | failed); foreground work — remove, doctor — answers on its own request and produces no frame.

No timers

Convergence is push-based. A failure degrades one root, logs, and waits — the next event is the retry. There is no retry timer, no poll, and no periodic sweep in the engine. The only deadlines in the daemon are the lane's idle reap and the watcher's debounce, and both are budgets on an event rather than a cadence.

One failure's next event is not a manifest change. A reconcile that backs off another realizer's clone in flight (an offline CLI's, holding the cloning marker's lock through the clone and the worktree and share passes after it) degrades the root, and the end of that clone touches nothing the watcher sees. So the driver waits on the marker itself (roots::await_clone, on a detached thread, since the wait spans the whole clone and its passes) and re-runs roots_changed once the lock is released or the marker is gone. A marker nobody holds is a holder gone — a CLI that crashed before the wait opened it — and wakes the retry too, which claims the free leftover rather than refusing it. No spin follows: every in-flight refusal comes from a held lock, and a marker that cannot be locked at all answers false.

grove doctor prints non-ready engine statuses and under-filled pools because a failed background refill retries on the next event, not on a clock.

Terminal vs transient

An op failure carries one of seven stable codes from grove_ops::Error::code (stele:landmark wire-error-codes): not_declared, not_ready, invalid_input, conflict, network, git, io. grove_api::policy::classify_error partitions them:

  • Terminal — conflict, invalid_input. Retrying cannot help: a would-clobber conflict or a malformed declaration is stuck until a human edits the manifest, and that edit is itself the event that re-drives the engine. So the root goes degraded, where doctor can see it, instead of re-deriving to cloning and retrying forever.
  • Transient — not_declared, not_ready, network, git, io. The attempt is over, so the engine takes ReconcileError(disk) — trusting disk plainly rather than stranding a stale cloning — and waits for the next event.

The classifier is a total match on the Error enum, so a new category stops the build until it is classified. policy::terminal_error_codes() reads its wire strings off real Error values, so a rename in Error::code travels rather than leaving a stale literal.

invalid_input/conflict are the engine's terminal pair, while the CLI's exit-code map groups invalid_input with network/git/io and pairs conflict with not_ready. Two unrelated partitions over one taxonomy; both are contract.

A genuine clone failure does not arrive as an Err at all — it arrives as Applied { status: Failed }, which policy::classify_reconcile maps to degraded (cloned/present map to ready). That partition is total by construction: the match has no catch-all, so a new ReconcileStatus stops the build.

A background task that returns nothing at all (BgOutcome::Crashed) is a third case: a reconcile crash degrades that root only, a sync crash leaves a failed sync note, a fill crash is logged and forgotten.

The clone bound

Deps::clones is a global ClonePermits with DEFAULT_CLONE_LIMIT = 4 permits (GROVE_CLONE_LIMIT), bounding how many roots may hold a clone at once. Without it a daemon booting a home with N declared roots fans out N concurrent network fetches.

Only a reconcile of a root disk says is unrealized takes a permit, read under the root's lane: a realized root's reconcile cannot clone, and since every manifest event re-arms reconcile on every root ahead of sync and fill, a ready root that needed a permit would starve its syncs and fills behind other roots' clones. a_ready_roots_reconcile_and_sync_run_while_other_clones_hold_every_permit pins that.

The permit is tried at the head of the root's own lane, and never waited for there; only this ordering avoids both failure modes below.

Acquiring dispatch-side and then awaiting lane admission inverts the bound: a reconcile doing nothing at all — merely waiting out a foreground op on its own root — would hold one of the four permits against roots whose lanes are completely free. A whole-home doctor takes every root's foreground lane at once, so four such reconciles would stall home-wide convergence for the length of the pass. a_reconcile_parked_on_a_busy_lane_holds_no_clone_permit pins that.

Blocking for a permit inside the lane job is worse, because the job holds the lane while it waits. Once the permits are all held by clones that have stalled — a peer that accepts the connection and then goes silent, a dropped VPN, a slept laptop's half-open socket — every other root's reconcile parks on the bound holding its own lane, and those roots' snapshot reads shed as unavailable. The whole home then reports unavailable and converges nothing while /api/health still answers ready: damage meant to be local to a busy root becomes the daemon's.

So the lane job only tries for a permit and, failing, returns immediately — the lane is released, reads answer again, and the reconcile is re-armed. The driver, having freed its slot, parks its mailbox in ClonePermits' one shared registry, holding nothing. No timer, and no permit is ever held by something that is not cloning. a_reconcile_without_a_clone_permit_frees_its_lane_and_resumes_when_one_lands pins it.

A freed permit pokes the driver at the front of the registry, and the driver re-dispatches into the same try carrying the poke. The poke is a wake-up, not a claim, so a re-dispatched reconcile still waiting out its own lane holds no permit. Each poke ends exactly once — consumed by that try, or declined by being dropped (the driver is gone, busy, or its root no longer needs a clone) — and a decline pokes the next parked driver. Pokes in flight never fall below free permits while a driver is parked, so a release wakes exactly one driver rather than every waiter. In general a release costs one poke and each steal (below) one more. slow_a_cold_boot_contending_for_one_permit_pokes_once_per_release pins the bound for its own scenario: forty missing roots against one permit converge with at most 2×ROOTS pokes in total. a_poke_a_driver_cannot_use_is_declined_to_the_next_parked_root pins the decline path: a poke dropped unused, in the lane job or after the re-drive, wakes the next parked root.

The registry is not a fair queue. A fresh dispatch, one not poked, may take a free permit ahead of the poked driver it was freed for; that driver's try then fails and it parks again at the back — one re-park per steal. The driver parks when the deferral lands rather than inside the lane job, so a poke can never reach it while its slot still reads busy and be declined as unwanted, and a permit freed between the failed try and the park is poked for by the park itself. A driver already parked keeps its one entry: a re-dispatch that defers again while it is still queued adds none.

Wake-up order can also lag the permit. A poked reconcile queued behind foreground work on its own lane carries its poke until the lane admits it, so while that op runs the next parked root is not woken — even though the permit is free for any fresh try meanwhile.

The permit travels back to the driver with the result and is dropped after task_finished is published, so a cloning reconcile's started/finished pair brackets a held permit exactly, and the bound is observable from the event stream.

The root's status stays honest while it waits: cloning is set when the reconcile is dispatched, not when it reaches a permit.

Sync

Engine::sync is accept-only: it returns as soon as the request is recorded, never when the fetch finishes, and a re-request while one is pending or in flight coalesces into it. root_sync_changed is broadcast on accept, so every attached view shows the in-flight state immediately — not only the client that asked — and again on completion.

The driver runs it only from ready, so a degraded root holds syncing: true until a dispatched reconcile recovers it: syncing means "holds a sync request", not "is fetching". POST /api/roots/sync is the one caller (api.html § Sync).

roots::sync fetches the trunk branch (bounded, single-refspec), fast-forwards the trunk checkout onto the tracking ref, and prunes any warm-pool slot stranded at a pre-sync tip. It never forces. Uncommitted edits ride across the fast-forward; a trunk carrying local commits, or an edit an incoming commit would overwrite, is reported: SyncNote::of maps git::FastForward to the note the snapshot publishes beside syncing — diverged, dirty, or nothing for updated/already_current. SyncNote::Failed is the synthetic member: a sync that errored, or whose task never returned, leaves it. The next clean sync clears the note.

Pruned slots leave the pool hint stale-high, which would starve the refill guard, so the driver decrements it by what the report says was pruned.

Promote

There is no promote route and no engine-level promote call. Claiming a warm slot is a step inside realizing a declared worktree, so it lives in the realizer that every path reaches: worktrees::create (the offline grove tree add) and worktrees::reconcile (what the engine runs after a declare-and-nudge, and after a hand-edited manifest). A promote wired to one caller is a pool that is filled and never redeemed — paid for on every clone, reported as pool n/n readiness, and claimed by nothing.

A Promotion::Cold is not a failure — it is the signal to cold-create, distinguishing an empty pool (Empty) from a name collision (Conflict) — so the warm and cold paths are interchangeable and the caller does not choose between them. The engine learns what the claim cost from the next reconcile's pool read, and refills toward the target from there.

Nothing blocking runs in the driver

Every grove-ops call leaves the driver as a task, runs on the root's lane, and comes back as a message. The driver's loop only awaits its mailbox, so status keeps answering while a clone drags on for minutes.

Engine::stop is explicit rather than "drop the last handle": a background task holds a sender so it can report its outcome, so an undeclared root would otherwise stay alive for the length of its in-flight clone. stop also raises a flag a queued reconcile reads at the head of the lane, so one that has not begun never does: it takes no clone permit and never reaches realize. grove-ops work already running cannot be cancelled — a clone mid-transfer runs to completion and reports to a mailbox nobody reads.

The engine set

RootSet is one task owning the slug → engine map, so "start the declared-minus-running, stop the running-minus-declared" is an ordinary set difference rather than a concurrency problem. That single ownership is also what closes the undeclare → redeclare race: a slug stopped in one pass is already out of the map before the next pass reads it, because both passes are the same task.

It cold-boots by reading the declared set itself rather than waiting for the first broadcast — the boot-time announcement can be published before the task subscribes, and a set that waited for it would sit empty until the next manifest change. It is driven by the event bus, never by the watcher directly.

Tests

crates/grove-daemon/tests/engine.rs is the behavioural gate, one named test per behaviour on this page; the HTTP half of sync is tests/observe.rs and tests/http_contract.rs.

The transition table's own tests live beside it in engine/status.rs, and the whole-flow scenario — declare → realize → claim a warm slot → sync → remove — is crates/grove-daemon/tests/scenario.rs.