UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

116 lines (115 loc) • 8.26 kB
import { type WorkflowRunListByScopeOptions, type WorkflowRunStore, type WorkflowRunSummary, type WorkflowRunUpdateExpect, type WorkflowRunUpdateOptions } from "../../core/workflow-run-store.js"; import type { WorkflowRun } from "../../orchestration/workflow.js"; import { type LedgerSpec } from "./shared-ledger.js"; import { type CorruptReadInfo } from "./corrupt-read-sink.js"; /** * design/97 S1b — the zero-dependency FILE backend for {@link WorkflowRunStore} (TOC-local `/workflows` * history). Behaviorally identical to {@link import("../../core/workflow-run-store.js").InMemoryWorkflowRunStore}, * built on the SAME crash-safety mechanics as {@link import("./checkpoint-store.js").FileCheckpointStore}: * * 1. **In-process async mutex per id** — a `Map<id, Promise>` serialization chain (the SAME shape as * `FileCheckpointStore.withLock` / `TtlSessionStore.pending`): `put`/`update`/`reap`-delete on a given id * chain behind one another, so no two interleaved async tasks both read+commit the same row. * 2. **Authoritative state = an in-memory `Map<id, WorkflowRun>`**, rebuilt by replaying `runs.jsonl` * (+ a compacted `snapshot`) at boot, last-writer-wins by event order (the latest `put`/`update`/`delete` * wins — the same "authoritative fields by event order" rule). * 3. **Commit ordering = appendLine the event + fsync BEFORE flipping the in-memory map** — so a crash can * never leave memory and disk disagreeing. The observability store is non-engine-critical, so `fsync` is * per-config (default on); a crash before the fsync'd append simply replays as the prior state. * 4. **A line the replay cannot read refuses the store** — anything but that unfinished last append, which is read as not having * happened: the fold is last-writer-wins, so folding past a damaged `update` served a finished run as still running * (`FileLedgerDamagedError`, `store.ledger_damaged`, in `shared-ledger.ts`). The refusal is this store's alone — the backend * factory never builds it, so a damaged run ledger leaves the other stores of the root opening; `inspectFileLedgers(root)` reads * it without opening it, and `setAsideLedgerDamage(root, "workflow-runs")` is the way out. * * The CAS predicate is byte-for-byte the in-memory one: `row && row.scope === scope` plus the `expect.rev` * OCC; the summary projection is the shared {@link summarizeWorkflowRun} (anti-drift). NO per-operation * flock — the fence is per DIRECTORY and taken at construction: the first instance over the run ledger * takes `<root>/workflow-runs/LOCK` and a second OS process is refused by name (`shared-ledger.ts`). * This doc used to credit "the coarse boot LOCK, owned by the backend factory" — which never applied to * this store at all: `FileStorageBackend` does not construct it, so every deployment wiring * `RunnerDeps.workflowRunStore` had an OCC ledger and a truncating compaction with no fence whatsoever. */ /** One persisted ledger event. The replay folds these in order into the authoritative map. */ type LedgerEvent = { t: "put"; id: string; run: WorkflowRun; } | { t: "update"; id: string; run: WorkflowRun; } | { t: "delete"; id: string; }; export interface FileWorkflowRunStoreOptions { /** When false, a ledger append is NOT fsync'd (the observability store is non-engine-critical). Default true. */ fsync?: boolean; /** Compact the ledger into a snapshot once it exceeds this many events (then truncate). Default 1000. */ compactEvery?: number; /** The observability ledger's seat; see {@link import("./shared-ledger.js").LedgerPaths.onCorruptRead}. */ onCorruptRead?: (info: CorruptReadInfo) => void; } /** The run ledger's files under a data root, and its fold ({@link import("./shared-ledger.js").LedgerSpec}). */ export declare const WORKFLOW_RUN_LEDGER: LedgerSpec<WorkflowRun, LedgerEvent>; export declare class FileWorkflowRunStore implements WorkflowRunStore { private readonly fsyncEnabled; private readonly compactEvery; /** RB-59: authoritative state is SHARED per canonical directory (see the note above the class). */ private readonly ledger; /** RB-145: this instance's own close latch — the refcount belongs to the DIRECTORY, not to callers. */ private closed; private readonly disclose; private get runs(); constructor(root: string, options?: FileWorkflowRunStoreOptions); /** * The open's pass over the finished records an older engine wrote: each is given its tree id as `workflowTreeIdStampOf` answers it * (the same rule, driven over the rows in hand), by the compare-and-set that answer names. A best-effort migration, never a * condition of the open: a row that does not read is left as it is (its listing says so), a record whose line does not read whole * stays without a tree id, and a write that fails or loses leaves that row without one — told on the store's disclosure seat * (`onCorruptRead`, naming the run), and once for the whole open on the process's default notice seat * (`store.tree_id_stamp_incomplete`, how many rows, how many stamps the closing compaction did not sync, and the first failure's * code) — and the next open tries again. Synchronous, * inside the construction: no other operation of this process runs between the read of a row and its write. The pass's appends are * not synced one by one and start no compaction; the pass ends with one compaction, the one write that makes them durable (a crash * before it loses only stamps, which the next open writes again — a stamp is the same on every pass). */ private stampTreeIds; /** Serialize an op behind any in-flight op on the same id (the in-process per-id async mutex). */ private withLock; /** Commit one ledger event (append + fsync) THEN flip the in-memory map (crash-safe ordering), then * the best-effort housekeeping compaction (RB-150/RB-167) — all three steps in the base. */ private commit; put(id: string, run: WorkflowRun): Promise<void>; get(id: string): Promise<WorkflowRun | null>; update(id: string, scope: string, run: WorkflowRun, expect?: WorkflowRunUpdateExpect, _opts?: WorkflowRunUpdateOptions): Promise<boolean>; listByScope(scope: string, opts?: WorkflowRunListByScopeOptions): Promise<WorkflowRunSummary[]>; reap(scope: string, now: number, opts?: { maxAgeMs?: number; keep?: number; }): Promise<number>; /** One terminal run of the scope, deleted under its id lock (interface: {@link WorkflowRunStore.deleteRun}) — one row of a batch: * its earlier events leave the disk when the batch ends ({@link settleErasure}). */ deleteRun(runId: string, scope: string): Promise<boolean>; /** The end of a batch of {@link deleteRun} calls (interface: {@link WorkflowRunStore.settleErasure}): the ledger compacted once. */ settleErasure(): Promise<void>; /** The session's terminal runs, deleted each under its own id lock with the selection re-checked against the live row (interface: * {@link WorkflowRunStore.deleteBySession}) — a run removed or replaced by a new running run is skipped, as `reap` skips one. */ deleteBySession(sessionId: string, scope: string): Promise<string[]>; /** Force a compaction now (test/inspection): rewrite the snapshot from the authoritative map and * truncate the live ledger (RB-167's closeForSwap recipe lives in the base). */ compactNow(): void; /** Test/inspection helper: number of stored runs. */ get size(): number; /** * Release the append handle (best-effort). The LAST holder over the directory also drops its * cross-process writer fence (`<dir>/LOCK`), so a successor process can open the same run ledger. * There is no OTHER door: this store is never constructed by `FileStorageBackend`, so nothing else * ever hands its fence back — the doc line that used to credit "the backend factory" here named a * release that could not happen under any assembly, for a lock this store did not hold in the first * place (see the class note above). */ close(): void; } export {};