mlua_swarm/store/run/mod.rs
1//! `RunStore` — persistence for `Run` records (one kick of a `Task`).
2//!
3//! Part of the issue #13 ID-hierarchy reconciliation: Blueprint -> Task ->
4//! Run -> Step -> Attempt. A [`RunId`](crate::types::RunId) is minted
5//! server-side each time a [`crate::store::task::TaskRecord`] is kicked; it
6//! carries a lightweight trace of the steps dispatched during that kick
7//! ([`StepEntry`]) for observability, plus its own outcome status
8//! independent of the owning Task's coarser status. A single Task can have
9//! N `Run`s over its lifetime (`list_by_task`).
10//!
11//! Current scope:
12//!
13//! - [`InMemoryRunStore`] — process-volatile default.
14//! - [`SqliteRunStore`] — file-backed persistence via `rusqlite-isle`.
15//! `step_entries` is a JSON column, not normalized into its own table —
16//! this is a trace/observability artifact, not something queried
17//! relationally.
18//! - Other persistent backends (Git / mini-app / …) are future carries.
19
20use crate::blueprint::BindingDigest;
21use crate::store::replay::{ReplayCursor, ReplayStore};
22use crate::types::{RunId, StepId, TaskId};
23use async_trait::async_trait;
24use serde::{Deserialize, Serialize};
25use std::collections::{BTreeMap, HashMap};
26use std::sync::{Arc, Mutex};
27use thiserror::Error;
28
29pub mod inmemory;
30pub mod sqlite;
31pub use inmemory::InMemoryRunStore;
32pub use sqlite::SqliteRunStore;
33
34// ──────────────────────────────────────────────────────────────────────────
35// RunStatus / StepEntry / RunRecord
36// ──────────────────────────────────────────────────────────────────────────
37
38/// Lifecycle status of a [`RunRecord`] — the outcome of one specific kick
39/// of a Task.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
41#[serde(rename_all = "snake_case")]
42pub enum RunStatus {
43 /// Minted, not yet dispatched.
44 Pending,
45 /// Steps are currently being dispatched for this Run.
46 Running,
47 /// The Run completed successfully.
48 Done,
49 /// The Run failed.
50 Failed,
51 /// The Run was still `Running` when the server process restarted
52 /// (issue #35 ST2 boot-time recovery sweep). Terminal — in-flight
53 /// `EngineState` is process-local and unrecoverable; this variant
54 /// records the fact without attempting to reconstruct or resume it.
55 Interrupted,
56 /// A cancel request landed on the Run (via `POST /v1/runs/:id/cancel`
57 /// / `mse_cancel` / `swarm_cancel`). Terminal — the current wiring
58 /// records the intent + trace event; live in-flight abort of the
59 /// still-dispatching flow remains a v3 carry, so a Run that reaches
60 /// its Ok outcome after this marker keeps its terminal `result_ref`,
61 /// but the Cancelled marker itself is observable via
62 /// `swarm_status.cancel_requested` and `core.cancel_requested` on
63 /// the trace stream.
64 Cancelled,
65}
66
67/// One worker-reported degradation entry — a worker fell back to a
68/// substitute behavior instead of failing outright (e.g. a tool call errored
69/// and the worker used a cached/default value). Independent channel from
70/// [`StepEntry`]/`result_ref`: degradations never flow through step OUTPUT
71/// or the fold path (GH #32; sibling of the GH #34 audit sidecar — both
72/// keep observational signal off the BP-chain value). Reported via `POST
73/// /v1/worker/degradation`; the server injects `step_ref`/`attempt`/`at`
74/// before persisting.
75#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
76pub struct DegradationEntry {
77 /// The tool (or capability) the worker attempted to use.
78 pub tool: String,
79 /// The error that triggered the fallback, in the worker's own words.
80 pub error: String,
81 /// What the worker substituted instead of failing.
82 pub fallback: String,
83 /// Optional free-form context from the worker.
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub note: Option<String>,
86 /// The Blueprint step ref (`Step.ref`) this degradation was reported
87 /// under, if known. Server-injected metadata, not worker-supplied.
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub step_ref: Option<String>,
90 /// The attempt number this degradation was reported under, if known.
91 /// Server-injected metadata, not worker-supplied.
92 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub attempt: Option<u32>,
94 /// Unix epoch seconds — when this entry was recorded. Server-injected.
95 pub at: u64,
96}
97
98/// One entry in a Run's step trace — appended as the engine dispatches
99/// (and finishes) each step. Purely observational: no field here is
100/// consulted for flow control.
101///
102/// The per-step stats extension (started/completed timestamps, duration,
103/// token usage, model, worker kind, variant-specific `adapter_data`) is
104/// additive: every field is `Option` + `#[serde(default)]` so rows
105/// written before the extension deserialize unchanged, and a dispatch
106/// where no boundary reported stats still appends a valid entry. The
107/// entry stays **write-once** — in-flight visibility belongs to the
108/// sibling [`crate::store::trace::TraceEvent`] stream, never to
109/// in-place updates here.
110#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
111pub struct StepEntry {
112 /// The step this entry traces.
113 #[schemars(with = "String")]
114 pub step_id: StepId,
115 /// The Blueprint step ref (`Step.ref`) that was dispatched, if known.
116 pub step_ref: Option<String>,
117 /// Free-form status label for this step at the time the entry was
118 /// recorded (e.g. `"dispatched"`, `"passed"`, `"blocked"`).
119 pub status: Option<String>,
120 /// Immutable Runner/Agent/Context snapshot digest used for this step.
121 /// `None` for rows created before BoundAgent launch wiring.
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub binding_digest: Option<BindingDigest>,
124 /// Unix epoch seconds — when this entry was recorded.
125 pub at: u64,
126 /// The attempt number the stats below describe (the LAST attempt the
127 /// dispatch ran), when a worker boundary reported one.
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub attempt: Option<u32>,
130 /// Unix epoch milliseconds — when the dispatcher began this step.
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub started_at_ms: Option<i64>,
133 /// Unix epoch milliseconds — when the step reached its outcome.
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub completed_at_ms: Option<i64>,
136 /// Wall-clock dispatch duration in milliseconds (dispatcher-measured,
137 /// worker-kind independent).
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub duration_ms: Option<u64>,
140 /// Worker kind label (`"agent_block"` / `"subprocess"` / `"operator"`
141 /// / …) as reported by the worker boundary.
142 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub worker_kind: Option<String>,
144 /// The model that served the attempt, when known.
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub model: Option<String>,
147 /// Normalized token usage, when a worker boundary reported one.
148 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub usage: Option<crate::store::trace::TokenUsage>,
150 /// Number of LLM turns the attempt ran, when reported.
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub num_turns: Option<u32>,
153 /// Worker-kind-specific raw payload (size-capped, engine-opaque).
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub adapter_data: Option<serde_json::Value>,
156}
157
158impl StepEntry {
159 /// Construct an entry with only the pre-stats fields set — the shape
160 /// every pre-extension writer produced. Stats fields default to
161 /// `None`; the dispatcher's fold fills them when available.
162 pub fn basic(
163 step_id: StepId,
164 step_ref: Option<String>,
165 status: Option<String>,
166 binding_digest: Option<BindingDigest>,
167 at: u64,
168 ) -> Self {
169 Self {
170 step_id,
171 step_ref,
172 status,
173 binding_digest,
174 at,
175 attempt: None,
176 started_at_ms: None,
177 completed_at_ms: None,
178 duration_ms: None,
179 worker_kind: None,
180 model: None,
181 usage: None,
182 num_turns: None,
183 adapter_data: None,
184 }
185 }
186
187 /// Fold a boundary-reported [`crate::store::trace::WorkerStats`]
188 /// into this entry (the dispatcher's outcome-time fold). `None`
189 /// fields in `stats` leave the entry untouched; `adapter_data` is
190 /// size-capped via [`crate::store::trace::cap_payload`].
191 pub fn with_worker_stats(mut self, stats: crate::store::trace::WorkerStats) -> Self {
192 self.worker_kind = stats.worker_kind.or(self.worker_kind);
193 self.model = stats.model.or(self.model);
194 self.usage = stats.usage.or(self.usage);
195 self.num_turns = stats.num_turns.or(self.num_turns);
196 self.adapter_data = stats
197 .adapter_data
198 .map(crate::store::trace::cap_payload)
199 .or(self.adapter_data);
200 self
201 }
202}
203
204/// Who currently holds one **slot** of a Run — the model's `Assignee`
205/// (`{ op, desc, gen }`), persisted as one value of the
206/// [`RunRecord::current`] map.
207///
208/// A "slot" is a Blueprint-declared Operator seat: the `operator_ref` an
209/// agent names (`Blueprint.operators[].name`). A Blueprint may declare
210/// several, so a Run has as many slots as its Blueprint declares, each
211/// with its own holder over time.
212///
213/// Invariants this type carries (model §4.3):
214///
215/// - **A1** `|Run.current| ≤ 1` **per slot** — expressed as the map keyed
216/// by slot on [`RunRecord::current`]: one key cannot hold two values, so
217/// a seat cannot have two holders. The slot is the map key, never a
218/// field of this struct.
219/// - **A3** [`Self::gen`] is immutable for the lifetime of an instance.
220/// Re-assignment never mutates an existing `Assignee`; the store mints a
221/// fresh instance with the next generation (**Q3**). Nothing in this
222/// crate takes `&mut Assignee`.
223/// - **A9** [`Self::desc`] is mandatory. The store rejects an empty (or
224/// whitespace-only) `desc` with
225/// [`RunStoreError::AssigneeDescRequired`]; the HTTP layer maps that to
226/// `400`. The store itself never decides a status code.
227/// - **A10** this is the one place a slot's current holder is recorded and
228/// the one place it is read from — the destination is not baked into any
229/// sibling field.
230///
231/// The `Assignee` does not cross the SAP boundary (model §4.7 T1): the
232/// primitives below the boundary carry an `operator`, never an assignee or
233/// a generation.
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
235pub struct Assignee {
236 /// Who holds the slot — the model's `OperatorId`, which is the key
237 /// space of the engine's operator registry. Session ids (`S-<hex>`)
238 /// and role aliases (`main-ai`) share that one key space (the WS login
239 /// path registers both), so this stays a plain `String` rather than
240 /// narrowing to a session id.
241 pub op: String,
242 /// Why this holder was assigned — the human-readable record of the
243 /// assignment. Required (**A9**); an empty value is rejected at the
244 /// store boundary rather than stored as `""`.
245 pub desc: String,
246 /// The generation stamped on this holder at acquire time (**A4**:
247 /// `G` after the increment). Immutable for the lifetime of the
248 /// instance (**A3**) — a later acquire produces a NEW `Assignee` with
249 /// a higher `gen` instead of rewriting this one.
250 ///
251 /// `G` is a single counter per **Run**, not per slot: an assignment to
252 /// any slot advances the one counter, so two holders of different
253 /// slots can be ordered against each other by `gen` alone.
254 pub gen: u64,
255}
256
257/// What [`RunStore::vacate_assignee`] did — it releases a seat only while
258/// that seat still holds the generation the caller observed, so "released"
259/// and "someone else got there first" are two answers, not one.
260///
261/// # Why a release has to name a generation
262///
263/// A release is issued by a caller that *read* the holder earlier and then
264/// decided it should go: **A7** reads a holder, asks its adapter for
265/// `T-ALIVE`, and releases on `Disconnected`; **O8**'s cascade reads a
266/// holder, matches it against a deleted operator's names, and releases.
267/// Both decisions are about the `Assignee` that was read, and both have
268/// `.await` points between the read and the write, during which an
269/// `acquire` (which never excludes — **A8**) can seat somebody else.
270///
271/// Addressed at `(run, slot)` alone, such a release would delete whatever
272/// holder happened to be there — a holder whose liveness was never asked
273/// for and whose deletion no premise in the model supports. That is a lost
274/// update, not **A8**: the acquirer was answered `200` with its generation
275/// (**Q4**) and has no channel to learn it was undone. Carrying the
276/// observed generation turns the write back into the decision that was
277/// actually made.
278///
279/// `gen` alone identifies the holder because `G` is Run-wide and advances
280/// on every assignment event, so a generation is never reused — a seat
281/// holding `expected_gen` is holding the very instance the caller read,
282/// including when a re-acquire put the *same* operator back (**A8**).
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub enum VacateOutcome {
285 /// The seat still held the observed generation, so it was released and
286 /// the slot is now `Vacant`.
287 Released {
288 /// The Run-wide counter `G` after this event (**A4**: a `Vacant`
289 /// advances it exactly like an `Assign` does).
290 generation: u64,
291 /// The holder that was released — the instance the caller read.
292 released: Assignee,
293 },
294 /// The seat did not hold the observed generation, so **nothing was
295 /// written**: no holder removed, `G` not advanced, `updated_at`
296 /// untouched.
297 ///
298 /// The caller's reading is stale — either an `acquire` moved the seat
299 /// on (**A8** already decided that contest, and the newer holder
300 /// stands) or the seat was released by someone else in between. Either
301 /// way the release is not re-issued against the new state: the
302 /// decision behind it was made about a holder that is no longer there.
303 Stale {
304 /// Who holds the seat now, for the message the caller reports.
305 /// `None` = the slot is already `Vacant`.
306 current: Option<Assignee>,
307 },
308}
309
310/// One persisted `Run` row — one kick of a [`crate::store::task::TaskRecord`].
311#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
312pub struct RunRecord {
313 /// Run identifier.
314 #[schemars(with = "String")]
315 pub id: RunId,
316 /// The Task this Run was kicked from.
317 #[schemars(with = "String")]
318 pub task_id: TaskId,
319 /// Current lifecycle status.
320 pub status: RunStatus,
321 /// Trace of dispatched steps, in append order.
322 pub step_entries: Vec<StepEntry>,
323 /// Worker-reported degradations, in append order (GH #32). Independent
324 /// channel from [`Self::step_entries`]/[`Self::result_ref`] — see
325 /// [`DegradationEntry`]'s doc for the invariant. `[]` (the default) =
326 /// no degradations reported — every pre-#32 Run is unaffected.
327 #[serde(default, skip_serializing_if = "Vec::is_empty")]
328 pub degradations: Vec<DegradationEntry>,
329 /// Operator session id bound to this Run, if any (WS operator
330 /// correlation).
331 ///
332 /// This is the **launch-time snapshot** of who was pinned when the Run
333 /// was kicked — not the live holder. The live holder is
334 /// [`Self::current`]; nothing resolves a dispatch destination from this
335 /// field, so the two are not competing destinations (**A10**).
336 pub operator_sid: Option<String>,
337 /// The Run's live holders, keyed by **slot** — the model's
338 /// `Run.current` (§4.3).
339 ///
340 /// A slot is a Blueprint-declared Operator seat (`operator_ref` =
341 /// `Blueprint.operators[].name`): a Blueprint may declare several, and
342 /// each agent picks the one it dispatches through. The cardinality is
343 /// therefore `Run 1 : N Operator` and `Operator 1 : 1 Assignee` (at a
344 /// time), hence `Run 1 : N Assignee` — with **A1** reading "at most one
345 /// holder **per slot**", which is exactly what a map expresses. An
346 /// absent key is that slot's `Vacant`; an empty map is a Run with no
347 /// slot held at all.
348 ///
349 /// **R2** — a `Vacant` slot does not stop the Run; only a dispatch that
350 /// needs *that* slot's holder is affected, and dispatches through other
351 /// slots are untouched. **R6** — this travels with the Run row, so a
352 /// restart does not drop the assignments.
353 ///
354 /// Only [`RunStore::acquire_assignee`] / [`RunStore::vacate_assignee`]
355 /// write it, both scoped to one slot, and both mint a fresh
356 /// [`Assignee`] rather than mutating a stored one (**Q3**).
357 ///
358 /// [`BTreeMap`](std::collections::BTreeMap) rather than `HashMap`: the
359 /// map is serialized into a persisted column and into observation
360 /// payloads, and key-sorted output keeps those bytes stable across
361 /// processes. Additive with `#[serde(default)]` so rows serialized
362 /// before the assignment axis existed decode unchanged (as an empty
363 /// map = every slot Vacant).
364 ///
365 /// # An empty map is written out, not skipped
366 ///
367 /// This field used to carry `skip_serializing_if =
368 /// "BTreeMap::is_empty"`, so a Run holding nothing had no `current`
369 /// key on the wire at all. That made "nobody holds anything on this
370 /// Run" and "this response does not report holders" the same bytes,
371 /// and §4.3 asks for the opposite (*居なければ居ないと分かる* — when
372 /// nobody is there, it must be possible to tell that nobody is there).
373 /// `"current": {}` says it. The per-seat form of the same answer, which
374 /// also names the seats nobody holds, is
375 /// [`crate::handover::run_assignees`].
376 #[serde(default)]
377 pub current: BTreeMap<String, Assignee>,
378 /// The Run's generation counter — the model's `G` (**A4**).
379 ///
380 /// `0` at launch. Every assignment event (`Assign` **or** `Vacant`)
381 /// increments it by one **before** stamping, so the first `Assign`
382 /// yields `gen == 1`; the counter therefore holds the generation of
383 /// the most recent event, and the next event will use this value `+ 1`.
384 /// The bump is unconditional — re-acquiring for the SAME `op` still
385 /// increments, because the counter counts events, not state changes.
386 ///
387 /// **One counter per Run, shared by every slot.** An `Assign` to slot
388 /// `b` advances the same `G` that a preceding `Assign` to slot `a`
389 /// advanced, so any two holders — of the same slot or of different
390 /// ones — can be ordered by `gen`. Per-slot counters would buy nothing
391 /// and would make that comparison meaningless.
392 ///
393 /// **A2** (`current = Assigned(a) ⟹ a.gen ≤ G`) holds on two legs, not
394 /// one. On the write path it holds by construction: every `current`
395 /// value's `gen` is stamped from this counter at the moment it is
396 /// bumped, so an acquire can never leave a holder above it. On the way
397 /// **in** it is checked — [`RunStore::create`] takes a caller-supplied
398 /// record with both fields public, so a record that arrives already
399 /// violating A2 is refused with
400 /// [`RunStoreError::AssigneeGenerationAhead`] rather than stored (see
401 /// [`RunRecord::validate_assignment_generations`]). Left unchecked, that
402 /// record would stay violated: the next acquire stamps generation 1,
403 /// below the seeded incumbent, and ordering two holders by `gen` — the
404 /// whole reason `G` is Run-wide — would silently invert.
405 ///
406 /// Additive with `#[serde(default)]` (pre-existing rows read back `0`).
407 #[serde(default)]
408 pub next_generation: u64,
409 /// The Run's terminal result payload, set once by
410 /// [`RunStore::set_result`]. `None` while the Run is in flight.
411 #[schemars(with = "Option<serde_json::Value>")]
412 pub result_ref: Option<serde_json::Value>,
413 /// Opaque JSON snapshot of the launch input this Run was kicked with
414 /// (blueprint / init_ctx / operator injection / ttl / …). The server
415 /// serializes its own launch-input struct into this string at Run
416 /// creation time so an `Interrupted` Run can be resumed under the SAME
417 /// `run_id` without re-deriving the input from a since-stale request
418 /// body. The store treats it as an opaque blob — the schema is owned by
419 /// the caller (the server crate). `None` = no snapshot recorded (older
420 /// rows predating resume support, or a caller that never opts in); such
421 /// a Run cannot be resumed. Additive with `#[serde(default)]` so
422 /// pre-existing serialized rows deserialize unchanged.
423 #[serde(default, skip_serializing_if = "Option::is_none")]
424 pub input_json: Option<String>,
425 /// Unix epoch seconds — creation time.
426 pub created_at: u64,
427 /// Unix epoch seconds — last update time.
428 pub updated_at: u64,
429}
430
431impl RunRecord {
432 /// **A2** as a check: every holder in [`Self::current`] must have been
433 /// stamped at or below [`Self::next_generation`]
434 /// (`current = Assigned(a) ⟹ a.gen ≤ G`).
435 ///
436 /// [`RunStore::create`] calls this on the record it is handed, and every
437 /// [`RunStore`] implementation is expected to — an out-of-tree backend
438 /// that skips it accepts records the two in-tree backends refuse.
439 /// Nothing else needs it: `acquire_assignee` stamps `gen` from the
440 /// counter it has just bumped, so no write path in this crate can
441 /// produce a record this rejects.
442 ///
443 /// Reports the first offending seat in [`Self::current`]'s key order,
444 /// which is stable (`BTreeMap`), so the same bad record always names the
445 /// same seat.
446 pub fn validate_assignment_generations(&self) -> Result<(), RunStoreError> {
447 for (slot, assignee) in &self.current {
448 if assignee.gen > self.next_generation {
449 return Err(RunStoreError::AssigneeGenerationAhead {
450 slot: slot.clone(),
451 gen: assignee.gen,
452 next_generation: self.next_generation,
453 });
454 }
455 }
456 Ok(())
457 }
458}
459
460/// Filter/paging parameters for [`RunStore::list`] — the `GET /v1/runs`
461/// collection query. All filters AND together; results are newest-first
462/// (`created_at` descending, ties broken by insertion order where the
463/// backend tracks one).
464#[derive(Debug, Clone, Default)]
465pub struct RunListFilter {
466 /// Only Runs kicked from this Task.
467 pub task_id: Option<TaskId>,
468 /// Only Runs currently in this status.
469 pub status: Option<RunStatus>,
470 /// Page size cap. `None` = no cap.
471 pub limit: Option<usize>,
472 /// Skip the first N matching rows (after ordering).
473 pub offset: Option<usize>,
474}
475
476/// Errors surfaced by a [`RunStore`] implementation.
477#[derive(Debug, Error)]
478pub enum RunStoreError {
479 /// No Run exists for the given id.
480 #[error("run not found: {0}")]
481 NotFound(RunId),
482
483 /// `create` was called with an id that is already stored.
484 #[error("run already exists: {0}")]
485 Duplicate(RunId),
486
487 /// **A9**: [`RunStore::acquire_assignee`] was called without a `desc`.
488 /// The record is mandatory, so the acquire is refused rather than
489 /// stored with an empty one. The store deliberately does not name an
490 /// HTTP status — the caller maps this to `400`.
491 #[error("assignee desc is required")]
492 AssigneeDescRequired,
493
494 /// **A2**: a record handed to [`RunStore::create`] carries a holder
495 /// whose generation is above the Run's counter `G`
496 /// (`current[slot].gen > next_generation`), so it would be stored
497 /// already violating `current = Assigned(a) ⟹ a.gen ≤ G`.
498 ///
499 /// The acquire path cannot produce this — it stamps `gen` from the
500 /// counter it just bumped — but `create` accepts a caller-built
501 /// [`RunRecord`] with both fields public, and that is a published
502 /// surface. Refused rather than stored: the violation is permanent
503 /// (the next acquire stamps a *lower* generation than the incumbent's,
504 /// inverting the ordering `G` being Run-wide exists to provide) and
505 /// invisible afterwards. Callers map this to `400`, same as
506 /// [`Self::AssigneeDescRequired`].
507 #[error(
508 "assignee generation is ahead of the run's counter: current['{slot}'].gen = {gen} > \
509 next_generation = {next_generation}"
510 )]
511 AssigneeGenerationAhead {
512 /// The seat whose holder is ahead of the counter.
513 slot: String,
514 /// That holder's generation.
515 gen: u64,
516 /// The Run counter `G` it was measured against.
517 next_generation: u64,
518 },
519
520 /// An assignment event named no slot. `Run.current` is keyed by slot,
521 /// so an `Assign` (or a `Vacant`) with an empty slot names no seat to
522 /// write — it is refused rather than collapsed onto a `""` key that
523 /// no `operator_ref` can ever resolve to. Callers map this to `400`,
524 /// same as [`Self::AssigneeDescRequired`].
525 #[error("assignee slot is required")]
526 AssigneeSlotRequired,
527
528 /// Backend-specific failure not covered by the other variants.
529 #[error("other: {0}")]
530 Other(String),
531}
532
533/// The provenance of a Run snapshot's `bound_agents` array.
534///
535/// Persisted as the [`BOUND_AGENTS_ORIGIN_KEY`] sibling of `bound_agents`
536/// inside the opaque [`RunRecord::input_json`] blob. This is Run-store
537/// metadata, **not** a schema-crate Blueprint wire type: it never enters
538/// [`crate::blueprint::BoundAgent`], `BoundAgentDigestInput`, or any digest
539/// computation. It lives here beside [`RunContext`] — rather than in
540/// `crate::service::task_launch` — because both the domain launch service
541/// (which writes it) and the server crate's bindings-explain handler (which
542/// reads it) consume it, and both already depend on this module; parking it
543/// in the service module would force the server crate to reach into a
544/// service-private type.
545#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
546#[serde(rename_all = "snake_case")]
547pub enum SnapshotOrigin {
548 /// `bound_agents` were resolved and pinned at the Run's initial launch —
549 /// the binding identity is the launch-time pin.
550 Launch,
551 /// `bound_agents` were backfilled from the current Blueprint when a
552 /// pre-binding-snapshot Run was resumed or reran. The binding identity
553 /// carries no launch-time pin guarantee.
554 ResumeBackfill,
555}
556
557/// JSON key the [`SnapshotOrigin`] is persisted under, beside `bound_agents`,
558/// in [`RunRecord::input_json`].
559pub const BOUND_AGENTS_ORIGIN_KEY: &str = "bound_agents_origin";
560
561impl SnapshotOrigin {
562 /// Read the origin marker from a decoded launch snapshot. An absent (or
563 /// unparseable) [`BOUND_AGENTS_ORIGIN_KEY`] maps to
564 /// [`SnapshotOrigin::ResumeBackfill`] — the safe side: a snapshot whose
565 /// `bound_agents` were persisted before this marker existed cannot prove
566 /// they were pinned at launch, so it must not be reported as a launch pin
567 /// and (on the replay axis) must not have binding digests mixed into its
568 /// replay keys. Only test artifacts hit this case in practice — the
569 /// strict-binding series is unreleased, so no real snapshot predates the
570 /// marker.
571 pub fn from_snapshot(snapshot: &serde_json::Value) -> Self {
572 snapshot
573 .get(BOUND_AGENTS_ORIGIN_KEY)
574 .and_then(|v| serde_json::from_value::<SnapshotOrigin>(v.clone()).ok())
575 .unwrap_or(SnapshotOrigin::ResumeBackfill)
576 }
577}
578
579/// GH #76 error surface: single-slot breadcrumb the dispatcher writes when a step
580/// aborts the flow (currently: [`crate::core::state::DispatchOutcome::Blocked`]),
581/// so the surrounding [`crate::service::task_launch::TaskLaunchService::launch`]
582/// `map_err` closure can lift `failed_step` + `verdict_value` off the eval
583/// boundary into the structured [`crate::service::task_launch::TaskLaunchError::FlowEval`]
584/// variant. Sibling to `step_entries` (append-only per-step trace) — this
585/// slot is last-write-wins because only ONE aborting step matters for the
586/// eval's terminal error envelope, and flow-ir stops dispatching further
587/// steps after `EvalError::DispatcherError`.
588#[derive(Debug, Clone)]
589pub struct LastFailure {
590 /// The `StepId` (dispatch-time tid) the dispatcher assigned to the
591 /// aborting step.
592 pub step_id: StepId,
593 /// The Blueprint `Step.ref` that dispatched the aborting step, if
594 /// known (dispatcher fills this from its own `ref_` param — never `None`
595 /// on the current write path, but modeled `Option` because the
596 /// `LastFailure` shape is a public read surface and future breadcrumb
597 /// writers may not have a ref in hand).
598 pub step_ref: Option<String>,
599 /// The verdict value the aborting step carried
600 /// (e.g. `DispatchOutcome::Blocked(v)`'s `v`, cloned by the dispatcher
601 /// before mapping the outcome to `EvalError::DispatcherError`).
602 pub verdict_value: serde_json::Value,
603}
604
605/// Pairs a [`RunId`] with the [`RunStore`] used to persist its trace.
606///
607/// Threaded from the server entry points (`POST /v1/tasks`, `POST
608/// /v1/tasks/:id/runs`) down through `TaskApplication::handle_with_run` /
609/// `TaskLaunchService::launch` / `EngineDispatcher` (issue #13 run_id
610/// propagation) so every step the dispatcher runs can be appended to
611/// `RunRecord.step_entries` and the run's id exposed to workers via
612/// `Ctx.meta.runtime["run_id"]`. Kept as a distinct type — rather than a
613/// new field on `TaskApplicationInput` — so the pre-existing exhaustive
614/// struct literal in `mlua-swarm-cli`'s MCP adapter (`TaskApplicationInput
615/// { .. }`, no `run_ctx`) keeps compiling unchanged: callers that don't
616/// care about run tracing keep calling `TaskApplication::handle` /
617/// `TaskLaunchService::launch`, which pass `None` through internally.
618#[derive(Clone)]
619pub struct RunContext {
620 /// The Run this dispatch's steps should be traced into.
621 pub run_id: RunId,
622 /// Where to append [`StepEntry`] rows as steps are dispatched.
623 pub run_store: Arc<dyn RunStore>,
624 /// Optional [`ReplayStore`] the engine will append a Ctx-snapshot +
625 /// step-output row to after every completed step (see
626 /// [`crate::store::replay`] for the primitive). `None` (the default)
627 /// disables logging entirely — pre-replay callers keep their behavior
628 /// byte-for-byte.
629 pub replay_store: Option<Arc<dyn ReplayStore>>,
630 /// Optional [`ReplayCursor`] the engine consults BEFORE dispatching
631 /// each step. When present and the cursor has a matching row for
632 /// `(step_ref, input_hash, occurrence)`, the engine returns the
633 /// stored `DispatchOutcome::Pass(value)` verbatim and skips the
634 /// Adapter spawn — this is the replay-hit path. `None` (the default)
635 /// disables replay entirely.
636 pub replay_cursor: Option<Arc<Mutex<ReplayCursor>>>,
637 /// Run-pinned replay identity component, keyed by logical agent name.
638 pub binding_digests: Arc<HashMap<String, BindingDigest>>,
639 /// Whether this dispatch is a resume / rerun-from of an existing Run
640 /// rather than an initial launch. `false` (the default) marks an initial
641 /// launch. Set to `true` ONLY by the server's resume and rerun-from
642 /// handlers — it is the sole, explicit signal that decides a backfilled
643 /// snapshot's [`SnapshotOrigin`] (never inferred from replay-cursor or
644 /// step-entry state, whose wiring is free to change).
645 pub resume: bool,
646 /// GH #76 error surface: shared single-slot breadcrumb the dispatcher writes when
647 /// a step aborts the flow (`DispatchOutcome::Blocked` → `EvalError`).
648 /// Read by the enclosing [`crate::service::task_launch::TaskLaunchService::launch`]
649 /// `map_err` closure to populate the structured
650 /// [`crate::service::task_launch::TaskLaunchError::FlowEval`] variant's
651 /// `failed_step` / `verdict_value` fields. `None` (the default) means
652 /// no aborting step was recorded — either the run succeeded, or an
653 /// error path fired that does not go through the dispatcher's Blocked
654 /// arm (e.g. `EvalError` raised by flow-ir itself before dispatch).
655 /// Behind `std::sync::Mutex` to match the `replay_cursor` sibling
656 /// (same crate-level convention — dispatcher writes are short critical
657 /// sections, no `.await` held across).
658 pub last_failure: Arc<Mutex<Option<LastFailure>>>,
659 /// Optional [`crate::store::trace::TraceHandle`] bound to this Run —
660 /// the write port for the per-Run [`crate::store::trace::TraceEvent`]
661 /// stream. When present the dispatcher appends `core.*` events
662 /// around every step and registers the handle with the engine
663 /// (`Engine::trace_handle`) so middlewares/workers can append their
664 /// own kinds. `None` (the default) disables the trace rail entirely
665 /// — pre-trace callers keep their behavior byte-for-byte.
666 pub trace: Option<crate::store::trace::TraceHandle>,
667}
668
669impl RunContext {
670 /// Construct a `RunContext` with just the RunStore wired — the same
671 /// shape all pre-replay callers use (`replay_store` / `replay_cursor`
672 /// both `None`). Preserved as a convenience so a caller that never
673 /// opts into replay can keep constructing `RunContext` positionally.
674 pub fn new(run_id: RunId, run_store: Arc<dyn RunStore>) -> Self {
675 Self {
676 run_id,
677 run_store,
678 replay_store: None,
679 replay_cursor: None,
680 binding_digests: Arc::new(HashMap::new()),
681 resume: false,
682 last_failure: Arc::new(Mutex::new(None)),
683 trace: None,
684 }
685 }
686
687 /// Builder-style setter: attach a
688 /// [`crate::store::trace::TraceHandle`] so the dispatcher appends
689 /// `core.*` trace events around every step and exposes the handle
690 /// to middlewares/workers via the engine.
691 pub fn with_trace(mut self, trace: crate::store::trace::TraceHandle) -> Self {
692 self.trace = Some(trace);
693 self
694 }
695
696 /// GH #76 error surface: write the aborting-step breadcrumb (last-write-wins).
697 /// Called by [`crate::blueprint::EngineDispatcher::dispatch`]'s Blocked
698 /// arm BEFORE it maps the outcome to `EvalError::DispatcherError`.
699 /// Silently succeeds if the mutex is poisoned — this is an
700 /// observability breadcrumb, not a load-bearing invariant, and a
701 /// poisoned mutex here must never prevent the primary abort error
702 /// from propagating (same fail-open convention as the sibling
703 /// `append_step_entry` warn-and-swallow at
704 /// `EngineDispatcher::dispatch`).
705 pub fn set_last_failure(&self, failure: LastFailure) {
706 if let Ok(mut slot) = self.last_failure.lock() {
707 *slot = Some(failure);
708 }
709 }
710
711 /// GH #76 error surface: reconstruct a partial-ctx snapshot from the step-entry
712 /// trace persisted so far — the in-tree substitute for a full
713 /// `storage.snapshot()` from flow-ir (upstream carry).
714 ///
715 /// Shape: `{ "steps": { "<step_id>": { "step_ref": ..., "status": ...,
716 /// "binding_digest": ..., "at": ... } } }` — a JSON object keyed by
717 /// each dispatched `StepId` with its recorded [`StepEntry`] metadata.
718 /// This is metadata-level, NOT value-level (no `StepEntry` carries the
719 /// step's actual OUTPUT value; that requires upstream mlua-flow-ir
720 /// support to expose `storage.snapshot()` on error). Consumers who
721 /// need value-level partial ctx must wait for the upstream carry —
722 /// see the FlowEval `partial_ctx` field rustdoc.
723 ///
724 /// Returns `Value::Null` if the store lookup fails (e.g. the row was
725 /// deleted between dispatch and error surfacing) — the caller's
726 /// `partial_ctx: Option<Value>` field wraps this so `Null` is
727 /// distinguishable from "no snapshot attempt at all".
728 pub async fn snapshot_partial_ctx(&self) -> serde_json::Value {
729 let record = match self.run_store.get(&self.run_id).await {
730 Ok(r) => r,
731 Err(_) => return serde_json::Value::Null,
732 };
733 let mut steps = serde_json::Map::new();
734 for entry in &record.step_entries {
735 let mut fields = serde_json::Map::new();
736 if let Some(ref_) = &entry.step_ref {
737 fields.insert(
738 "step_ref".to_string(),
739 serde_json::Value::String(ref_.clone()),
740 );
741 }
742 if let Some(status) = &entry.status {
743 fields.insert(
744 "status".to_string(),
745 serde_json::Value::String(status.clone()),
746 );
747 }
748 if let Some(digest) = &entry.binding_digest {
749 fields.insert(
750 "binding_digest".to_string(),
751 serde_json::Value::String(digest.to_string()),
752 );
753 }
754 fields.insert("at".to_string(), serde_json::Value::Number(entry.at.into()));
755 steps.insert(entry.step_id.to_string(), serde_json::Value::Object(fields));
756 }
757 let mut out = serde_json::Map::new();
758 out.insert("steps".to_string(), serde_json::Value::Object(steps));
759 serde_json::Value::Object(out)
760 }
761
762 /// Builder-style setter: attach a [`ReplayStore`] to log every
763 /// completed step's Ctx snapshot + output into.
764 pub fn with_replay_store(mut self, store: Arc<dyn ReplayStore>) -> Self {
765 self.replay_store = Some(store);
766 self
767 }
768
769 /// Builder-style setter: attach a [`ReplayCursor`] the dispatcher
770 /// consults for a hit before dispatching each step.
771 pub fn with_replay_cursor(mut self, cursor: Arc<Mutex<ReplayCursor>>) -> Self {
772 self.replay_cursor = Some(cursor);
773 self
774 }
775
776 /// Attach immutable binding digests so replay keys distinguish the same
777 /// step/input executed under different Runner/Agent/Context snapshots.
778 pub fn with_binding_digests(mut self, digests: HashMap<String, BindingDigest>) -> Self {
779 self.binding_digests = Arc::new(digests);
780 self
781 }
782
783 /// Builder-style setter: mark this dispatch as a resume / rerun-from of
784 /// an existing Run (see [`Self::resume`]). Called only by the server's
785 /// resume and rerun-from handlers; every other construction site leaves
786 /// the default `false` (initial launch).
787 pub fn with_resume(mut self) -> Self {
788 self.resume = true;
789 self
790 }
791}
792
793impl std::fmt::Debug for RunContext {
794 // `dyn RunStore` carries no `Debug` bound (backend implementations
795 // shouldn't be forced to derive it just to satisfy this struct's
796 // `Debug`); render `run_store` as its `name()` instead, same idiom as
797 // `WorkerInvocation`'s manual `Debug` for its `Arc<dyn OutputSink>`
798 // field.
799 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800 f.debug_struct("RunContext")
801 .field("run_id", &self.run_id)
802 .field("run_store", &self.run_store.name())
803 .field(
804 "replay_store",
805 &self.replay_store.as_ref().map(|s| s.name()),
806 )
807 .field("replay_cursor", &self.replay_cursor.is_some())
808 .field("binding_digests", &self.binding_digests.len())
809 .field("resume", &self.resume)
810 .field(
811 "last_failure",
812 &self.last_failure.lock().ok().and_then(|slot| slot.clone()),
813 )
814 .field("trace", &self.trace.is_some())
815 .finish()
816 }
817}
818
819// ──────────────────────────────────────────────────────────────────────────
820// RunStore trait
821// ──────────────────────────────────────────────────────────────────────────
822
823/// Persistence interface for `Run` records — one kick of a Task, in the
824/// issue #13 ID hierarchy.
825#[async_trait]
826pub trait RunStore: Send + Sync {
827 /// Backend name — for diagnostics/logging.
828 fn name(&self) -> &str;
829
830 /// Create a new Run row. Returns `Duplicate` if `record.id` is already
831 /// stored.
832 ///
833 /// This is the one door into the store that carries a caller-built
834 /// [`RunRecord`], so it is where the assignment axis is checked rather
835 /// than assumed: a record whose `current` holds a generation above
836 /// `next_generation` is refused with
837 /// [`RunStoreError::AssigneeGenerationAhead`] (**A2**, see
838 /// [`RunRecord::validate_assignment_generations`]). Implementations must
839 /// run that check before persisting anything. The rest of the record —
840 /// `step_entries`, `status`, timestamps — is still trusted as given.
841 async fn create(&self, record: RunRecord) -> Result<(), RunStoreError>;
842
843 /// Fetch a Run by id.
844 async fn get(&self, id: &RunId) -> Result<RunRecord, RunStoreError>;
845
846 /// List every Run kicked from `task_id`, ascending by `created_at`
847 /// (oldest kick first).
848 async fn list_by_task(&self, task_id: &TaskId) -> Result<Vec<RunRecord>, RunStoreError>;
849
850 /// Append one step-trace entry to a Run's `step_entries`, bumping
851 /// `updated_at` to now.
852 async fn append_step_entry(&self, id: &RunId, entry: StepEntry) -> Result<(), RunStoreError>;
853
854 /// Append one worker-reported degradation to a Run's `degradations`
855 /// (GH #32), bumping `updated_at` to now. Independent of
856 /// [`Self::append_step_entry`] — degradations never flow through step
857 /// OUTPUT/fold.
858 async fn append_degradation(
859 &self,
860 id: &RunId,
861 entry: DegradationEntry,
862 ) -> Result<(), RunStoreError>;
863
864 /// Update a Run's status, bumping `updated_at` to now.
865 async fn update_status(&self, id: &RunId, status: RunStatus) -> Result<(), RunStoreError>;
866
867 /// Atomically transition a Run's status from `from` to `to`, bumping
868 /// `updated_at` to now — the compare-and-set primitive the resume path
869 /// (`POST /v1/runs/:id/resume`) uses to guard against a double resume
870 /// racing the same `Interrupted` Run into `Running` twice.
871 ///
872 /// Returns `Ok(true)` when a row with this `id` AND current status
873 /// `from` was found and flipped to `to`; `Ok(false)` when the row's
874 /// current status was not `from` (a concurrent transition already won,
875 /// or the Run is absent). Never a hard error for the status-mismatch /
876 /// absent case — the boolean is the caller's race signal.
877 async fn try_transition(
878 &self,
879 id: &RunId,
880 from: RunStatus,
881 to: RunStatus,
882 ) -> Result<bool, RunStoreError>;
883
884 /// Assign this Run's `slot` to `op` — the model's `Assign` event
885 /// (§4.3).
886 ///
887 /// `slot` is the Blueprint-declared Operator seat (`operator_ref`) the
888 /// assignment applies to; only that key of
889 /// [`RunRecord::current`] is touched, so assigning one seat never
890 /// disturbs another's holder.
891 ///
892 /// Bumps the Run's generation counter `G` by one and stamps the new
893 /// value onto a **freshly minted** [`Assignee`], which replaces
894 /// `current[slot]` (**A4** / **Q3**: the previously stored `Assignee`
895 /// is returned untouched, never rewritten in place). `G` is Run-wide,
896 /// so this advances the same counter every other slot's events advance.
897 /// `updated_at` is bumped to now.
898 ///
899 /// **A8**: this succeeds regardless of who holds the slot — a live
900 /// holder is displaced (last writer wins); there is no exclusion and
901 /// no rejection path for a contended slot. The only refusals are
902 /// **A9** (an empty or whitespace-only `desc` returns
903 /// [`RunStoreError::AssigneeDescRequired`]) and an empty `slot`
904 /// (returns [`RunStoreError::AssigneeSlotRequired`]); an unknown `id`
905 /// returns [`RunStoreError::NotFound`].
906 ///
907 /// The read of `G` and the write of both columns happen atomically, so
908 /// two concurrent acquires can never read the same `G` and hand out a
909 /// duplicate generation — including when they name different slots.
910 ///
911 /// Returns `(new generation, the holder this call displaced from this
912 /// slot)` — the caller needs both to tell whether it took over from
913 /// someone and under which generation it now dispatches.
914 async fn acquire_assignee(
915 &self,
916 id: &RunId,
917 slot: &str,
918 op: &str,
919 desc: &str,
920 ) -> Result<(u64, Option<Assignee>), RunStoreError>;
921
922 /// Release the holder of this Run's `slot` — the model's `Vacant`
923 /// event (§4.3) — **but only while that seat still holds the
924 /// generation the caller observed**. Other slots keep their holders.
925 ///
926 /// `expected_gen` is the `gen` of the [`Assignee`] the caller read and
927 /// decided about. The comparison and the write happen in one critical
928 /// section (the same transaction / lock `acquire_assignee` uses), so a
929 /// concurrent `acquire` either lands before the check — and the
930 /// release becomes a no-op — or after the write, which is an ordinary
931 /// **A8** takeover of an already-Vacant seat. There is no window in
932 /// which a stale reader deletes a newer holder. See [`VacateOutcome`]
933 /// for why the generation has to travel with the call at all; this is
934 /// the only release verb, because both production callers (**A7** at
935 /// `AssigneeRouter::execute` and **O8**'s cascade) are stale readers,
936 /// and an unconditional sibling would exist only to be picked by
937 /// mistake.
938 ///
939 /// **A4**: a release that actually happens bumps the Run-wide
940 /// generation counter exactly like `Assign` does; it just mints no
941 /// [`Assignee`]. A subsequent [`Self::acquire_assignee`] — on this slot
942 /// or any other — therefore continues from the bumped value rather than
943 /// reusing the generation the released holder had. `updated_at` is
944 /// bumped to now. A [`VacateOutcome::Stale`] result is **not** an
945 /// assignment event and writes nothing at all: the counter counts
946 /// events, and a release that did not release is not one.
947 ///
948 /// An already-Vacant slot therefore answers
949 /// `Stale { current: None }` rather than burning a generation — no
950 /// generation can match an absent holder. An empty `slot` returns
951 /// [`RunStoreError::AssigneeSlotRequired`] and an unknown `id` returns
952 /// [`RunStoreError::NotFound`].
953 async fn vacate_assignee(
954 &self,
955 id: &RunId,
956 slot: &str,
957 expected_gen: u64,
958 ) -> Result<VacateOutcome, RunStoreError>;
959
960 /// Set a Run's terminal `result_ref`, bumping `updated_at` to now.
961 async fn set_result(
962 &self,
963 id: &RunId,
964 result_ref: serde_json::Value,
965 ) -> Result<(), RunStoreError>;
966
967 /// Replace the opaque launch snapshot after pre-dispatch binding has
968 /// enriched it (for example with immutable `bound_agents`).
969 async fn set_input_json(&self, id: &RunId, input_json: String) -> Result<(), RunStoreError>;
970
971 /// List every Run currently `Running` (issue #35 ST2 boot sweep +
972 /// ST4 occupancy check reuse this). No ordering guarantee.
973 async fn list_running(&self) -> Result<Vec<RunRecord>, RunStoreError>;
974
975 /// List Runs matching `filter`, newest-first (`created_at`
976 /// descending) — the `GET /v1/runs` collection read.
977 async fn list(&self, filter: &RunListFilter) -> Result<Vec<RunRecord>, RunStoreError>;
978
979 /// Delete a Run row (the `DELETE /v1/runs/:id` retention operation).
980 /// The caller is responsible for pruning the sibling trace stream
981 /// ([`crate::store::trace::RunTraceStore::delete_run`]) — the two
982 /// stores are deliberately uncoupled at the trait level.
983 async fn delete(&self, id: &RunId) -> Result<(), RunStoreError>;
984}
985
986// ──────────────────────────────────────────────────────────────────────────
987// Shared inner state used by the InMemory backend.
988// ──────────────────────────────────────────────────────────────────────────
989
990#[derive(Default)]
991pub(crate) struct Inner {
992 /// Insertion order — used as a stable tie-break under `list_by_task()`.
993 pub(crate) order: Vec<RunId>,
994 pub(crate) records: HashMap<RunId, RunRecord>,
995}
996
997pub(crate) type SharedInner = Mutex<Inner>;