@sema-agent/core
Version:
Stateless, task-oriented AI agent core
234 lines (233 loc) • 9.96 kB
JavaScript
import { receiveRetentionPolicy } from "../../core/retention-policy.js";
import { assertDeletionSessionId } from "../../core/retention.js";
import { WorkflowRunStoreError, admitWorkflowRun, isTerminalWorkflowStatus, nextWorkflowRunOnUpdate, queryWorkflowRuns, readStoredWorkflowRun, workflowRunReapCandidates, workflowRunsDoomed, WORKFLOW_RUN_REAP_KNOBS, WORKFLOW_RUN_ROW_SHAPE, } from "../../core/workflow-run-store.js";
import { workflowTreeIdStampInHand } from "../../orchestration/workflow-tree-id.js";
import { readMember, thrownName } from "../../core/thrown-value.js";
import { deliverEngineNotice } from "../../core/engine-notice.js";
function failureCodeOf(err) {
const code = readMember(err, "code");
if (typeof code === "string" && /^[A-Za-z0-9_.-]{1,40}$/.test(code))
return code;
return thrownName(err) ?? typeof err;
}
import { ledgerPathsOf, SharedLedgerTable } from "./shared-ledger.js";
import { guardCorruptSink } from "./corrupt-read-sink.js";
import { assertAdoptionBootGate } from "./adoption/marker.js";
import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js";
import { readLedgerTuning } from "./ledger-tuning.js";
const FILE_WORKFLOW_RUN_STORE_OPTION_KEYS = optionKeys()({ fsync: 0, compactEvery: 0, onCorruptRead: 0 });
const isRunRow = (x) => WORKFLOW_RUN_ROW_SHAPE.rowKey(x);
const runLedgerModel = {
label: "workflow-run ledger",
keyOf: (run) => run.id,
apply: (runs, ev) => {
if (ev.t === "delete") {
runs.delete(ev.id);
return;
}
runs.set(ev.id, ev.run);
},
judgeRow: isRunRow,
judgeEvent: (x) => {
const ev = x;
if (typeof ev.id !== "string")
return false;
return ev.t === "delete" ? true : isRunRow(ev.run);
},
eventKey: (ev) => ev.id,
settles: (ev) => (ev.t === "delete" ? null : ev.run),
nameOf: (run) => `workflow run ${run.id}`,
};
const runLedgers = new SharedLedgerTable(runLedgerModel);
export const WORKFLOW_RUN_LEDGER = Object.freeze({
name: "workflow-runs",
ledgerFile: "runs.jsonl",
snapshotFile: "runs.snapshot.jsonl",
model: runLedgerModel,
table: runLedgers,
});
export class FileWorkflowRunStore {
fsyncEnabled;
compactEvery;
ledger;
closed = false;
disclose;
get runs() {
return this.ledger.rows;
}
constructor(root, options) {
const opts = receiveOptions(options, "FileWorkflowRunStore", FILE_WORKFLOW_RUN_STORE_OPTION_KEYS);
assertAdoptionBootGate(root, "FileWorkflowRunStore");
const tuning = readLedgerTuning(opts, "FileWorkflowRunStore", "FileWorkflowRunStore options");
this.fsyncEnabled = tuning.fsync;
this.compactEvery = tuning.compactEvery;
const paths = ledgerPathsOf(root, WORKFLOW_RUN_LEDGER);
const sink = guardCorruptSink(opts.onCorruptRead);
this.disclose = sink === undefined ? undefined : (reason) => sink({ kind: "file", path: paths.ledgerPath, reason });
this.ledger = runLedgers.acquire({ ...paths, ...(sink !== undefined ? { onCorruptRead: sink } : {}) });
this.stampTreeIds(paths.ledgerPath);
}
stampTreeIds(ledgerPath) {
let stamped = 0;
let notStamped = 0;
let firstCode;
const failed = (err) => {
notStamped += 1;
firstCode ??= failureCodeOf(err);
};
for (const [id, raw] of [...this.runs]) {
let row;
try {
row = readStoredWorkflowRun(raw, { key: id });
}
catch {
continue;
}
const scope = row.scope;
const answer = workflowTreeIdStampInHand(row, (up) => {
const r = this.runs.get(up);
if (r === undefined)
return null;
try {
const got = readStoredWorkflowRun(r, { key: up });
return got.scope === scope ? got : null;
}
catch {
return "unreadable";
}
});
if (typeof answer === "string" || answer.kind !== "stamp")
continue;
try {
const next = nextWorkflowRunOnUpdate(this.runs.get(id), id, scope, { ...row, treeId: answer.treeId }, answer.expect);
if (next === null)
throw new Error("the row moved before its write");
this.ledger.commit({ t: "update", id, run: next }, false, Number.POSITIVE_INFINITY);
stamped += 1;
}
catch (err) {
failed(err);
this.disclose?.(`workflow run ${JSON.stringify(id)}: its tree id was not written at the store's open (${failureCodeOf(err)}) — the record stays without one, and the next open tries again`);
}
}
let notSynced = 0;
if (stamped > 0) {
try {
this.ledger.compact();
}
catch (err) {
firstCode ??= failureCodeOf(err);
notSynced = stamped;
}
}
if (notStamped > 0 || notSynced > 0) {
const code = firstCode ?? "unknown";
const said = [
...(notStamped > 0 ? [`${notStamped} finished workflow run record(s) were not given their tree id (the records read as before; the next open of this store tries again)`] : []),
...(notSynced > 0 ? [`the tree ids given to ${notSynced} record(s) are written but not synced (a crash before the store's next synced write loses them, and the open after it writes them again)`] : []),
];
deliverEngineNotice(undefined, {
code: "store.tree_id_stamp_incomplete",
message: `[sema] file store at ${ledgerPath}, at its open: ${said.join("; ")} — first failure: ${code}.`,
detail: { path: ledgerPath, notStamped, notSynced, code },
});
}
}
withLock(id, fn) {
return this.ledger.withLock(id, fn);
}
commit(ev, fsync) {
this.ledger.commit(ev, fsync, this.compactEvery);
}
async put(id, run) {
return this.withLock(id, () => {
if (this.runs.has(id)) {
throw new WorkflowRunStoreError("workflow_run.already_exists", `workflow run id already exists`);
}
const stored = structuredClone(run);
stored.id = id;
stored.rev = run.rev ?? 0;
this.commit({ t: "put", id, run: admitWorkflowRun(stored, id) }, this.fsyncEnabled);
});
}
async get(id) {
const run = this.runs.get(id);
return run ? structuredClone(readStoredWorkflowRun(run, { key: id }, this.disclose)) : null;
}
async update(id, scope, run, expect, _opts) {
return this.withLock(id, () => {
const next = nextWorkflowRunOnUpdate(this.runs.get(id), id, scope, run, expect, this.disclose);
if (!next)
return false;
this.commit({ t: "update", id, run: next }, this.fsyncEnabled);
return true;
});
}
async listByScope(scope, opts) {
return queryWorkflowRuns(this.runs.entries(), scope, opts, this.disclose);
}
async reap(scope, now, opts) {
const policy = receiveRetentionPolicy("WorkflowRunStore.reap", opts, WORKFLOW_RUN_REAP_KNOBS);
if (policy.maxAgeMs === undefined && policy.keep === undefined)
return 0;
const doomed = workflowRunsDoomed(workflowRunReapCandidates(this.runs.entries(), scope, this.disclose), now, policy);
let n = 0;
for (const { id, byAge } of doomed) {
const deleted = await this.withLock(id, () => {
const live = this.runs.get(id);
if (!live || live.scope !== scope || !isTerminalWorkflowStatus(live.status))
return false;
if (byAge && policy.maxAgeMs !== undefined && (live.endedAt ?? live.createdAt) >= now - policy.maxAgeMs) {
return false;
}
this.ledger.commit({ t: "delete", id }, this.fsyncEnabled, Number.POSITIVE_INFINITY);
return true;
});
if (deleted)
n++;
}
this.ledger.settleErasure();
return n;
}
async deleteRun(runId, scope) {
return this.withLock(runId, () => {
const live = this.runs.get(runId);
if (live === undefined || live.scope !== scope || !isTerminalWorkflowStatus(live.status))
return false;
this.ledger.commit({ t: "delete", id: runId }, this.fsyncEnabled, Number.POSITIVE_INFINITY);
return true;
});
}
async settleErasure() {
this.ledger.settleErasure();
}
async deleteBySession(sessionId, scope) {
assertDeletionSessionId(sessionId, "WorkflowRunStore.deleteBySession");
const selected = (r) => r !== undefined && r.scope === scope && r.originatingSessionId === sessionId && isTerminalWorkflowStatus(r.status);
const deleted = [];
for (const id of [...this.runs.values()].filter(selected).map((r) => r.id)) {
const gone = await this.withLock(id, () => {
if (!selected(this.runs.get(id)))
return false;
this.ledger.commit({ t: "delete", id }, this.fsyncEnabled, Number.POSITIVE_INFINITY);
return true;
});
if (gone)
deleted.push(id);
}
this.ledger.settleErasure();
return deleted;
}
compactNow() {
this.ledger.compact();
}
get size() {
return this.runs.size;
}
close() {
if (this.closed)
return;
this.closed = true;
this.ledger.release();
}
}