@sema-agent/core
Version:
Stateless, task-oriented AI agent core
249 lines (248 loc) • 10.2 kB
JavaScript
import { statSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { acquireStoreDirLock, AppendLog, atomicWriteFile, canonicalStoreKey, ensureDir, judgeJsonlFile, } from "./fs-atomic.js";
export class FileLedgerDamagedError extends Error {
dir;
damaged;
rowsInReach;
snapshotRowsLost;
name = "FileLedgerDamagedError";
code = "store.ledger_damaged";
constructor(message, dir, damaged, rowsInReach, snapshotRowsLost) {
super(message);
this.dir = dir;
this.damaged = damaged;
this.rowsInReach = rowsInReach;
this.snapshotRowsLost = snapshotRowsLost;
}
}
export function foldLedger(paths, model) {
const rows = new Map();
const damaged = [];
const judge = (accepts, what) => ({ accepts, what: `a ${what} carries none of this ${model.label}'s own members` });
for (const read of judgeJsonlFile(paths.snapshotPath, "whole", judge(model.judgeRow, "snapshot row"))) {
if (read.verdict === "record")
rows.set(model.keyOf(read.record), read.record);
else if (read.verdict !== "uncommitted-tail")
damaged.push({ file: "snapshot", path: paths.snapshotPath, ...damageOf(read) });
}
const establishedAt = new Map();
let events = 0;
let lastDamagedLedgerLine = 0;
let uncommittedTail;
for (const read of judgeJsonlFile(paths.ledgerPath, "appended", judge(model.judgeEvent, "ledger event"))) {
if (read.verdict === "record") {
if (filesForeignRow(model, read.record)) {
damaged.push({ file: "ledger", path: paths.ledgerPath, line: read.line, form: "missing-required", what: FOREIGN_ROW });
lastDamagedLedgerLine = read.line;
continue;
}
model.apply(rows, read.record);
events++;
if (model.settles(read.record) !== undefined)
establishedAt.set(model.eventKey(read.record), read.line);
}
else if (read.verdict === "uncommitted-tail")
uncommittedTail = { line: read.line, bytes: read.bytes };
else {
damaged.push({ file: "ledger", path: paths.ledgerPath, ...damageOf(read) });
lastDamagedLedgerLine = read.line;
}
}
const reach = lastDamagedLedgerLine === 0 ? [] : [...rows.keys()].filter((key) => (establishedAt.get(key) ?? 0) < lastDamagedLedgerLine);
return { rows, events, damaged, reach, ...(uncommittedTail !== undefined ? { uncommittedTail } : {}) };
}
const FOREIGN_ROW = "a ledger event that files a row under a key other than the row's own (no writer of this ledger appends one)";
function filesForeignRow(model, ev) {
const row = model.settles(ev);
return row !== undefined && row !== null && model.keyOf(row) !== model.eventKey(ev);
}
function damageOf(read) {
return read.verdict === "blank" ? { line: read.line, form: "torn-json", what: "an empty line (no writer of this ledger leaves one)" } : { line: read.line, form: read.form, what: read.what };
}
function ledgerDamagedError(label, ledgerPath, fold) {
const dir = dirname(ledgerPath);
const lost = fold.damaged.filter((d) => d.file === "snapshot").length;
const lines = fold.damaged.map((d) => `${d.file} ${basename(d.path)} line ${d.line} (${d.form})`).join(", ");
const message = `[sema] file store: the ${label} at ${dir} is damaged — ${lines}: not one of its records, and not an append that never finished. ` +
`Refused rather than served: last-writer-wins would read what those lines held as never written, and serve a row's earlier state as its current one. ` +
`Reach: ${fold.reach.length} row(s) whose newest state may have been on a damaged ledger line, ${lost} snapshot row(s) lost, plus any row whose only line was damaged. ` +
`Set it aside with setAsideLedgerDamage(${JSON.stringify(dirname(dir))}, ${JSON.stringify(basename(dir))}): it keeps a verbatim copy of both files and rewrites the ledger with only the rows the damage cannot have moved.`;
return new FileLedgerDamagedError(message, dir, fold.damaged, fold.reach.length, lost);
}
export function replayLedger(paths, model) {
const fold = foldLedger(paths, model);
const disclose = paths.onCorruptRead;
if (fold.damaged.length > 0) {
for (const d of fold.damaged)
disclose?.({ kind: "record", path: d.path, reason: `${d.form}: ${d.what} at line ${d.line} (the ${model.label} is refused)`, line: d.line, form: d.form });
const refusal = ledgerDamagedError(model.label, paths.ledgerPath, fold);
disclose?.({ kind: "file", path: paths.ledgerPath, reason: refusal.message });
throw refusal;
}
if (fold.uncommittedTail !== undefined) {
const { line, bytes } = fold.uncommittedTail;
disclose?.({
kind: "file",
path: paths.ledgerPath,
reason: `uncommitted tail: ${bytes} byte(s) at line ${line} with no newline — an append that never returned — read as not having happened; an append log opening this ledger cuts them`,
});
}
return { rows: fold.rows, events: fold.events };
}
export function writeLedgerPair(paths, rows, beforeLedger) {
const lines = [...rows].map((r) => JSON.stringify(r)).join("\n");
atomicWriteFile(paths.tmpDir, paths.snapshotPath, lines.length ? `${lines}\n` : "");
beforeLedger?.();
atomicWriteFile(paths.tmpDir, paths.ledgerPath, "");
}
export function ledgerPathsOf(root, spec) {
const dir = join(root, spec.name);
return { dir, tmpDir: join(root, "tmp"), ledgerPath: join(dir, spec.ledgerFile), snapshotPath: join(dir, spec.snapshotFile) };
}
function snapshotVersion(snapshotPath) {
try {
const st = statSync(snapshotPath, { bigint: true });
return `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}`;
}
catch (e) {
if (e.code === "ENOENT")
return "absent";
throw e;
}
}
const SETTLED_READ_ATTEMPTS = 3;
export function readLedgerSettled(paths, model) {
const read = readSettled(paths.snapshotPath, () => replayLedger(paths, model));
return read === undefined ? { settled: false } : { settled: true, ...read };
}
export function readSettled(snapshotPath, read) {
for (let attempt = 0; attempt < SETTLED_READ_ATTEMPTS; attempt++) {
const before = snapshotVersion(snapshotPath);
const answer = read();
if (snapshotVersion(snapshotPath) === before)
return answer;
}
return undefined;
}
export class LedgerCore {
key;
paths;
model;
table;
rows = new Map();
refs = 1;
locks = new Map();
events = 0;
handle;
fence;
released = false;
constructor(key, paths, model, table) {
this.key = key;
this.paths = paths;
this.model = model;
this.table = table;
}
bootstrap() {
this.fence = acquireStoreDirLock(this.paths.dir, { label: this.model.label });
try {
const replayed = replayLedger(this.paths, this.model);
for (const [key, row] of replayed.rows)
this.rows.set(key, row);
this.events = replayed.events;
this.handle = new AppendLog(this.paths.ledgerPath);
}
catch (e) {
this.fence.release();
this.fence = undefined;
throw e;
}
}
withLock(key, fn) {
const prev = this.locks.get(key) ?? Promise.resolve();
const run = prev.then(() => fn(), () => fn());
const tail = run.then(() => { }, () => { });
this.locks.set(key, tail);
void tail.then(() => {
if (this.locks.get(key) === tail)
this.locks.delete(key);
});
return run;
}
commit(ev, fsync, compactEvery) {
if (!this.model.judgeEvent(ev) || filesForeignRow(this.model, ev)) {
throw new Error(`file ledger: refusing to write a ${this.model.label} event its own replay would not read as one of its records (its members, or a row filed under a key other than its own) — nothing was written`);
}
this.log.append(ev, fsync);
this.model.apply(this.rows, ev);
this.events++;
if (this.events >= compactEvery) {
try {
this.compact();
}
catch {
}
}
}
compact() {
if (this.released) {
throw new Error("file ledger: this authority was released (its store was closed) — refusing to compact a directory it no longer owns");
}
writeLedgerPair(this.paths, this.rows.values(), () => this.log.closeForSwap());
this.events = 0;
}
settleErasure() {
if (this.events > 0)
this.compact();
}
release() {
this.refs -= 1;
if (this.refs > 0)
return;
if (this.table.get(this.key) === this)
this.table.delete(this.key);
this.released = true;
this.handle?.close();
this.fence?.release();
this.fence = undefined;
}
get pendingEvents() {
return this.events;
}
get log() {
if (this.handle === undefined)
throw new Error("file ledger: used before bootstrap");
return this.handle;
}
}
export class SharedLedgerTable {
model;
live = new Map();
constructor(model) {
this.model = model;
}
isLive(dir) {
return this.live.has(canonicalStoreKey(dir));
}
acquire(paths) {
ensureDir(paths.dir);
ensureDir(paths.tmpDir);
const key = canonicalStoreKey(paths.dir);
const existing = this.live.get(key);
if (existing !== undefined) {
existing.refs += 1;
return existing;
}
const core = new LedgerCore(key, paths, this.model, this.live);
this.live.set(key, core);
try {
core.bootstrap();
}
catch (e) {
if (this.live.get(key) === core)
this.live.delete(key);
throw e;
}
return core;
}
}