@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +144 -16
- package/dist/agent-delete.d.ts +33 -10
- package/dist/agent-delete.js +184 -26
- package/dist/agents-store.d.ts +6 -2
- package/dist/agents-store.js +18 -5
- package/dist/agents.d.ts +8 -1
- package/dist/agents.js +14 -4
- package/dist/answer-json.d.ts +2 -2
- package/dist/answer-json.js +3 -4
- package/dist/archil-routes.d.ts +1 -1
- package/dist/archil-routes.js +4 -3
- package/dist/browser-sessions.d.ts +56 -0
- package/dist/browser-sessions.js +117 -0
- package/dist/computer-routes.d.ts +4 -15
- package/dist/computer-routes.js +6 -10
- package/dist/console/assets/index-Bzn4eUYF.js +715 -0
- package/dist/console/assets/index-CR2ZGei1.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +15 -5
- package/dist/import.js +4 -3
- package/dist/learn/check.d.ts +11 -2
- package/dist/learn/check.js +12 -9
- package/dist/learn/promote.d.ts +7 -1
- package/dist/learn/promote.js +47 -0
- package/dist/learn/repick.d.ts +34 -0
- package/dist/learn/repick.js +201 -0
- package/dist/learned-workflow.d.ts +2 -0
- package/dist/learned-workflow.js +18 -1
- package/dist/learning-setting.d.ts +13 -0
- package/dist/learning-setting.js +23 -1
- package/dist/llms.txt +1 -1
- package/dist/openapi.js +170 -12
- package/dist/paid-calls.d.ts +4 -1
- package/dist/paid-calls.js +1 -1
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/run-usage.d.ts +110 -0
- package/dist/run-usage.js +312 -0
- package/dist/runner/adapter-loop.js +51 -20
- package/dist/runner/conformance/harness.d.ts +2 -0
- package/dist/runner/conformance/harness.js +18 -4
- package/dist/runner/feedback-round.d.ts +29 -1
- package/dist/runner/feedback-round.js +54 -3
- package/dist/runner/journal-kinds.d.ts +3 -1
- package/dist/runner/learning-end.js +49 -18
- package/dist/runner/loop-contract.d.ts +3 -0
- package/dist/runner/monid-run.js +2 -2
- package/dist/runner/promotion.js +8 -2
- package/dist/runner/reflect-hook.js +3 -2
- package/dist/runs-over-store.d.ts +3 -2
- package/dist/runs-over-store.js +9 -7
- package/dist/server.d.ts +3 -3
- package/dist/server.js +221 -98
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/journal/storage.js +1 -1
- package/dist/store/open.d.ts +1 -1
- package/dist/store/open.js +1 -1
- package/dist/store/postgres/migrations/0021_purged.sql +13 -0
- package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
- package/dist/store/schema.d.ts +15 -1
- package/dist/store/schema.js +50 -5
- package/dist/store/sqlite/connection.d.ts +4 -1
- package/dist/store/sqlite/connection.js +5 -0
- package/dist/store/sqlite/run-patch.d.ts +8 -3
- package/dist/store/sqlite/run-patch.js +15 -7
- package/dist/store/sqlite/store.d.ts +5 -2
- package/dist/store/sqlite/store.js +249 -48
- package/dist/store/sqlite/worker.d.ts +9 -0
- package/dist/store/sqlite/worker.js +18 -1
- package/dist/store/store.d.ts +142 -9
- package/dist/store/store.js +63 -0
- package/dist/store-reads/analytics.js +2 -1
- package/dist/store-reads/cap.d.ts +8 -2
- package/dist/store-reads/cap.js +27 -3
- package/dist/store-reads/learning.d.ts +1 -1
- package/dist/store-reads/learning.js +5 -2
- package/dist/store-reads/runs.js +2 -0
- package/dist/store-reads/stats.js +4 -2
- package/dist/store-view.d.ts +7 -0
- package/dist/store-view.js +61 -20
- package/dist/tools.js +9 -0
- package/dist/trigger-targets.d.ts +7 -4
- package/dist/trigger-targets.js +6 -6
- package/dist/triggers.d.ts +2 -1
- package/dist/triggers.js +5 -2
- package/dist/validate.d.ts +4 -2
- package/dist/validate.js +13 -3
- package/dist/viewer-credential.d.ts +3 -4
- package/dist/viewer-credential.js +6 -4
- package/dist/workspace/computer-for-claim.d.ts +5 -1
- package/dist/workspace/computer-for-claim.js +47 -18
- package/dist/workspace/computer-intervals.d.ts +20 -0
- package/dist/workspace/computer-intervals.js +49 -0
- package/dist/workspace/computer-janitor.d.ts +7 -3
- package/dist/workspace/computer-janitor.js +14 -6
- package/dist/workspace/computer-kept.d.ts +7 -2
- package/dist/workspace/computer-kept.js +9 -2
- package/dist/workspace/resolve-computer.d.ts +7 -4
- package/dist/workspace/resolve-computer.js +21 -32
- package/dist/workspace/run-end-computers.d.ts +1 -0
- package/dist/workspace/run-end-computers.js +4 -1
- package/package.json +10 -10
- package/dist/console/assets/index-CTGegcKt.css +0 -1
- package/dist/console/assets/index-D1Se6mgG.js +0 -715
|
@@ -12,8 +12,17 @@ import { watchCommandsAt, wakeCommands } from "../command-wake.js";
|
|
|
12
12
|
import { claimFence, storeNow } from "../fence.js";
|
|
13
13
|
import { RunStorage } from "../journal/storage.js";
|
|
14
14
|
import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
|
|
15
|
-
import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
16
|
-
import { AgentArchived, AgentDeleting, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, } from "../store.js";
|
|
15
|
+
import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_RUN, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
16
|
+
import { AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
|
|
17
|
+
/** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
|
|
18
|
+
const madeOf = (body) => {
|
|
19
|
+
for (const link of ["replay", "audit"]) {
|
|
20
|
+
const of = body?.[link]?.of;
|
|
21
|
+
if (typeof of === "string")
|
|
22
|
+
return of;
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
};
|
|
17
26
|
/** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
|
|
18
27
|
const seqOf = (cursor) => {
|
|
19
28
|
if (!/^(0|[1-9][0-9]{0,15})$/.test(cursor))
|
|
@@ -68,7 +77,7 @@ function triggerSet(patch, at) {
|
|
|
68
77
|
pairs.push(["updated_at", at]);
|
|
69
78
|
return { set: pairs.map(([column]) => `${column} = ?`).join(", "), params: pairs.map(([, value]) => value) };
|
|
70
79
|
}
|
|
71
|
-
const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
|
|
80
|
+
const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref, purged_at";
|
|
72
81
|
const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version, mcp_pin, monid_pin";
|
|
73
82
|
const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
|
|
74
83
|
const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at, template_id";
|
|
@@ -111,7 +120,7 @@ async function underClaim(tx, claim, now) {
|
|
|
111
120
|
throw new Fenced(claim.runId, claim.epoch);
|
|
112
121
|
return at;
|
|
113
122
|
}
|
|
114
|
-
const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref });
|
|
123
|
+
const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref, purgedAt: r.purged_at ?? null });
|
|
115
124
|
const revisionOf = (r) => ({
|
|
116
125
|
id: r.id, agentId: r.agent_id, parent: r.parent_id, kind: r.kind, body: JSON.parse(r.body), skills: r.skills === null ? null : JSON.parse(r.skills),
|
|
117
126
|
note: r.note, package: r.package === null ? null : JSON.parse(r.package), createdAt: r.created_at, externalVersion: r.external_version,
|
|
@@ -159,6 +168,11 @@ const mcpServerOf = (r, at = Number(r.read_at)) => ({
|
|
|
159
168
|
const mcpPinOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.mcp_pin), pinnedAt: Number(r.created_at) });
|
|
160
169
|
const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r.updated_at });
|
|
161
170
|
const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
|
|
171
|
+
const orNull = (value) => (value === null ? null : Number(value));
|
|
172
|
+
const intervalOf = (r) => ({
|
|
173
|
+
runId: r.run_id, provider: r.provider, providerId: r.provider_id, kind: r.kind, gpuType: r.gpu_type, gpuCount: orNull(r.gpu_count), cpus: orNull(r.cpus),
|
|
174
|
+
memoryMb: orNull(r.memory_mb), startedAt: Number(r.started_at), kept: Number(r.kept) === 1, endedAt: orNull(r.ended_at),
|
|
175
|
+
});
|
|
162
176
|
const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
|
|
163
177
|
const pairedOf = (r) => ({ id: r.id, name: r.name, hello: JSON.parse(r.hello), driver: r.driver, labels: JSON.parse(r.labels), pairingId: r.pairing_id, createdAt: r.created_at, seenAt: r.seen_at, revokedAt: r.revoked_at });
|
|
164
178
|
const mintedOf = (r) => ({ machine: r.machine, kind: r.kind, os: r.os, arch: r.arch, expiresAt: r.expires_at, revokedAt: r.revoked_at, createdAt: r.created_at, runner: r.runner, incarnation: r.incarnation, run: r.run, refused: r.refused });
|
|
@@ -307,8 +321,9 @@ export async function openSqliteStore(options) {
|
|
|
307
321
|
// Version 11 (0.1.0-beta.44 and before) keeps no listing on a run's row: the server adds it (schema.ts listingUpgrade)
|
|
308
322
|
// in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
|
|
309
323
|
// it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
|
|
310
|
-
// (schema.ts relayUpgrade).
|
|
311
|
-
|
|
324
|
+
// (schema.ts relayUpgrade). Version 13 keeps no purge time on a run or an agent: the server adds them (schema.ts
|
|
325
|
+
// purgeUpgrade). A runner refuses 11, 12 and 13 until that server has.
|
|
326
|
+
const upgrading = found === 11 || found === 12 || found === 13;
|
|
312
327
|
if (upgrading && role === "runner")
|
|
313
328
|
throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
|
|
314
329
|
if (found !== SCHEMA_VERSION && !upgrading)
|
|
@@ -378,24 +393,31 @@ export async function openSqliteStore(options) {
|
|
|
378
393
|
// dropped, its rows heartbeats that each relay's runner writes again within its renewal, so none is copied.
|
|
379
394
|
{ sql: "DROP TABLE IF EXISTS runner_relays" },
|
|
380
395
|
{ sql: RUNNERS },
|
|
396
|
+
// Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
|
|
397
|
+
{ sql: COMPUTER_INTERVALS },
|
|
398
|
+
{ sql: COMPUTER_INTERVALS_RUN },
|
|
381
399
|
{ sql: NATIVE_COMMANDS_INDEX },
|
|
382
400
|
], { full: true });
|
|
383
401
|
await backfillNativeCommandOwners(connection);
|
|
384
|
-
if (found ===
|
|
402
|
+
if (found === 11) {
|
|
385
403
|
const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
|
|
386
404
|
await connection.write(listingUpgrade(present).map((sql) => ({ sql })), { full: true });
|
|
387
405
|
}
|
|
388
|
-
if (
|
|
406
|
+
if (found === 11 || found === 12) {
|
|
389
407
|
const minted = new Set((await connection.all("SELECT name FROM pragma_table_info('minted_tokens')")).map((column) => column.name));
|
|
390
408
|
await connection.write(relayUpgrade(minted).map((sql) => ({ sql })), { full: true });
|
|
391
409
|
}
|
|
410
|
+
if (upgrading) {
|
|
411
|
+
const named = async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name));
|
|
412
|
+
await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
|
|
413
|
+
}
|
|
392
414
|
}
|
|
393
415
|
}
|
|
394
416
|
catch (error) {
|
|
395
417
|
await connection.close().catch(() => undefined);
|
|
396
418
|
throw error;
|
|
397
419
|
}
|
|
398
|
-
return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
|
|
420
|
+
return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file, options.warn);
|
|
399
421
|
}
|
|
400
422
|
/** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
|
|
401
423
|
const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
|
|
@@ -455,10 +477,18 @@ function readOnly(tx) {
|
|
|
455
477
|
}
|
|
456
478
|
/** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
|
|
457
479
|
* clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
|
|
458
|
-
* `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX)
|
|
459
|
-
|
|
460
|
-
|
|
480
|
+
* `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
|
|
481
|
+
* purge checkpoints. `warn`: told when that checkpoint could not empty the WAL (stderr by default). */
|
|
482
|
+
export function storeOver(connection, now, file, warn = stderrWarn) {
|
|
483
|
+
return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`, warn);
|
|
461
484
|
}
|
|
485
|
+
const stderrWarn = (message) => void process.stderr.write(`agentrun-serve: ${message}\n`);
|
|
486
|
+
/** How long a purge's checkpoint waits, once SQLite's busy wait ran out on another connection's reader or writer, before
|
|
487
|
+
* its one retry. */
|
|
488
|
+
const PURGE_CHECKPOINT_RETRY_MS = 200;
|
|
489
|
+
/** How long a purge's checkpoint waits for another connection's reader or writer before it gives up (and is retried):
|
|
490
|
+
* short, since every other request of the store's connection queues behind it. */
|
|
491
|
+
const PURGE_CHECKPOINT_BUSY_MS = 20;
|
|
462
492
|
/** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite and removes once no
|
|
463
493
|
* file of the store keeps the bytes it replaced: a start that finds it finishes the scrub. */
|
|
464
494
|
const SCRUB_SUFFIX = ".scrub";
|
|
@@ -496,6 +526,7 @@ class SqliteStore {
|
|
|
496
526
|
settings;
|
|
497
527
|
sealedKeys;
|
|
498
528
|
computerLedger;
|
|
529
|
+
computerIntervals;
|
|
499
530
|
pairedComputers;
|
|
500
531
|
mintedTokens;
|
|
501
532
|
runners;
|
|
@@ -523,9 +554,12 @@ class SqliteStore {
|
|
|
523
554
|
#released = new Map();
|
|
524
555
|
/** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
|
|
525
556
|
#scrubMarker;
|
|
526
|
-
|
|
557
|
+
/** Told what a person should know that no caller is answered (a purge's checkpoint that left the WAL as it was). */
|
|
558
|
+
#warn;
|
|
559
|
+
constructor(db, now, origin, scrubMarker, warn = stderrWarn) {
|
|
527
560
|
this.#db = db;
|
|
528
561
|
this.#scrubMarker = scrubMarker;
|
|
562
|
+
this.#warn = warn;
|
|
529
563
|
this.#now = now;
|
|
530
564
|
this.origin = origin ?? this;
|
|
531
565
|
this.where = db.where;
|
|
@@ -533,13 +567,22 @@ class SqliteStore {
|
|
|
533
567
|
const clock = () => storeNow(d, now);
|
|
534
568
|
this.#clock = clock;
|
|
535
569
|
const insertAgent = (tx, agent, at) => tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?)", agent.id, agent.name, agent.description ?? null, at);
|
|
570
|
+
/** Agent `agentId`'s row, held (a writer's row lock, as its purge takes it), or undefined when there is none; refused
|
|
571
|
+
* (AgentPurged) once it is purged: a write that waited on the purge's lock reads its purge time, and one that took the
|
|
572
|
+
* lock first commits before the purge reads anything. */
|
|
573
|
+
const heldAgent = async (tx, agentId) => {
|
|
574
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
575
|
+
const agent = await tx.get("SELECT current_revision, archived_at, external_ref, purged_at FROM agents WHERE id = ?", agentId);
|
|
576
|
+
if (agent && agent.purged_at != null)
|
|
577
|
+
throw new AgentPurged(agentId, agent.archived_at, agent.purged_at);
|
|
578
|
+
return agent;
|
|
579
|
+
};
|
|
536
580
|
const insertRevision = async (tx, agentId, revision, at, ifCurrent) => {
|
|
537
581
|
// The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
|
|
538
582
|
// (create) and a later one (addRevision, upgrade) both guarantee before this. Held (a writer's row lock), so two
|
|
539
583
|
// revisions added at once, by this server or another on the same store, never both name the same parent, and
|
|
540
|
-
// `ifCurrent` is compared with what no other writer can move until this commits.
|
|
541
|
-
await
|
|
542
|
-
const agent = await tx.get("SELECT current_revision FROM agents WHERE id = ?", agentId);
|
|
584
|
+
// `ifCurrent` is compared with what no other writer can move until this commits. Never one of a purged agent.
|
|
585
|
+
const agent = await heldAgent(tx, agentId);
|
|
543
586
|
if (!agent)
|
|
544
587
|
throw new StoreConstraint(`no agent ${agentId}`);
|
|
545
588
|
if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
|
|
@@ -561,13 +604,16 @@ class SqliteStore {
|
|
|
561
604
|
/** Refused (AgentDeleting) when agent `agentId` is being deleted: another system's agent with an archive time, which
|
|
562
605
|
* only its delete writes (AgentDeleting). The agent's row is held first (a writer's row lock, as the archive's UPDATE
|
|
563
606
|
* takes it), so on Postgres a delete's archive that commits first is read here, and one that commits after waits for
|
|
564
|
-
* this run to be in the store, where the delete's listing of the agent's runs finds it.
|
|
607
|
+
* this run to be in the store, where the delete's listing of the agent's runs finds it. A purged agent is refused too
|
|
608
|
+
* (AgentPurged): it takes no run and no trigger. */
|
|
565
609
|
const refuseDeleting = async (tx, agentId) => {
|
|
566
|
-
await
|
|
567
|
-
const agent = await tx.get("SELECT archived_at, external_ref FROM agents WHERE id = ?", agentId);
|
|
610
|
+
const agent = await heldAgent(tx, agentId);
|
|
568
611
|
if (agent?.archived_at != null && agent.external_ref != null)
|
|
569
612
|
throw new AgentDeleting(agentId);
|
|
570
613
|
};
|
|
614
|
+
/** The runs whose launch is made from run `runId` (madeOf: a replay of its input, an audit's shadow), by id. Every
|
|
615
|
+
* launch is read (no index names its source): a purge's read, never a hot path. */
|
|
616
|
+
const launchedFrom = async (ex, runId) => (await ex.all(`SELECT run_id AS id FROM run_launch WHERE (${d.jsonText("body", ["replay", "of"])} = ? OR ${d.jsonText("body", ["audit", "of"])} = ?) AND run_id <> ? ORDER BY run_id`, runId, runId, runId)).map((row) => row.id);
|
|
571
617
|
/** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
|
|
572
618
|
* while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
|
|
573
619
|
* distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
|
|
@@ -595,7 +641,11 @@ class SqliteStore {
|
|
|
595
641
|
const handedAnyIn = (tx) => tx.get(`SELECT id FROM runs WHERE state = 'running' AND sign_in_handed IS NOT NULL AND ${d.jsonArrayLength("sign_in_handed")} > 0 LIMIT 1`);
|
|
596
642
|
this.agents = {
|
|
597
643
|
put: async ({ id, name, description = null }) => {
|
|
598
|
-
await db.
|
|
644
|
+
await db.transaction(async (tx) => {
|
|
645
|
+
// Never a purged agent's name or description written back.
|
|
646
|
+
await heldAgent(tx, id);
|
|
647
|
+
await tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, description = excluded.description", id, name, description, now());
|
|
648
|
+
});
|
|
599
649
|
},
|
|
600
650
|
create: async (agent, firstRevision) => {
|
|
601
651
|
await db.transaction(async (tx) => {
|
|
@@ -617,9 +667,11 @@ class SqliteStore {
|
|
|
617
667
|
const row = await db.get(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? AND external_version = ?`, agentId, version);
|
|
618
668
|
return row && revisionOf(row);
|
|
619
669
|
},
|
|
620
|
-
list: async ({ archived = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"} ORDER BY created_at, id`)).map(agentOf),
|
|
670
|
+
list: async ({ archived = false, purged = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"}${purged ? "" : " AND purged_at IS NULL"} ORDER BY created_at, id`)).map(agentOf),
|
|
621
671
|
archive: async (id, archived, why) => db.transaction(async (tx) => {
|
|
622
672
|
const at = now();
|
|
673
|
+
// A purged agent stays as its purge left it: archived, never unarchived.
|
|
674
|
+
await heldAgent(tx, id);
|
|
623
675
|
await tx.run("UPDATE agents SET archived_at = ? WHERE id = ?", archived ? at : null, id);
|
|
624
676
|
if (!archived)
|
|
625
677
|
return [];
|
|
@@ -638,7 +690,11 @@ class SqliteStore {
|
|
|
638
690
|
});
|
|
639
691
|
},
|
|
640
692
|
setCurrent: async (agentId, revisionId) => {
|
|
641
|
-
const changed = await db.transaction((tx) =>
|
|
693
|
+
const changed = await db.transaction(async (tx) => {
|
|
694
|
+
// Never a purged agent's: its current revision stays the one its runs' tombstones read.
|
|
695
|
+
await heldAgent(tx, agentId);
|
|
696
|
+
return tx.runCounted("UPDATE agents SET current_revision = ? WHERE id = ? AND EXISTS (SELECT 1 FROM revisions WHERE id = ? AND agent_id = ?)", revisionId, agentId, revisionId, agentId);
|
|
697
|
+
});
|
|
642
698
|
if (changed === 0)
|
|
643
699
|
throw new StoreConstraint(`${revisionId} is not a revision of agent ${agentId}`);
|
|
644
700
|
},
|
|
@@ -648,9 +704,16 @@ class SqliteStore {
|
|
|
648
704
|
},
|
|
649
705
|
revisions: async (agentId) => (await db.all(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? ORDER BY created_at, id`, agentId)).map(revisionOf),
|
|
650
706
|
// Written only while the revision has none (the one place a revision changes after its save), then read back in the
|
|
651
|
-
// same transaction: the pin that stood, this one or another first run's.
|
|
707
|
+
// same transaction: the pin that stood, this one or another first run's. Never on a purged agent's revision (its purge
|
|
708
|
+
// cleared every pin): its agent's row held first, as the purge holds it, and none written once it is purged.
|
|
652
709
|
pinOnce: async (revisionId, pin) => {
|
|
653
710
|
const row = await db.transaction(async (tx) => {
|
|
711
|
+
const of = await tx.get("SELECT agent_id FROM revisions WHERE id = ?", revisionId);
|
|
712
|
+
if (!of)
|
|
713
|
+
return undefined;
|
|
714
|
+
await d.lockRow(tx, "agents", "id", of.agent_id);
|
|
715
|
+
if ((await tx.get("SELECT purged_at FROM agents WHERE id = ?", of.agent_id))?.purged_at != null)
|
|
716
|
+
return undefined;
|
|
654
717
|
await tx.run("UPDATE revisions SET mcp_pin = ? WHERE id = ? AND mcp_pin IS NULL", pinText(pin), revisionId);
|
|
655
718
|
return tx.get("SELECT mcp_pin FROM revisions WHERE id = ?", revisionId);
|
|
656
719
|
});
|
|
@@ -679,6 +742,33 @@ class SqliteStore {
|
|
|
679
742
|
await tx.run("DELETE FROM agents WHERE id = ?", agentId);
|
|
680
743
|
});
|
|
681
744
|
},
|
|
745
|
+
purge: async (agentId) => {
|
|
746
|
+
const purged = await db.transaction(async (tx) => {
|
|
747
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
748
|
+
const agent = await tx.get("SELECT purged_at FROM agents WHERE id = ?", agentId);
|
|
749
|
+
if (!agent || agent.purged_at !== null)
|
|
750
|
+
return false;
|
|
751
|
+
// Each run a tombstone first (Runs.purge): a run started past the delete's listing keeps the agent for the next one.
|
|
752
|
+
const left = await tx.get("SELECT id FROM runs WHERE agent_id = ? AND purged_at IS NULL LIMIT 1", agentId);
|
|
753
|
+
if (left)
|
|
754
|
+
throw new StoreConstraint(`agent ${agentId} still has run ${left.id} not purged: each is purged first (runs.purge)`);
|
|
755
|
+
const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
|
|
756
|
+
if (triggersLeft.length)
|
|
757
|
+
throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
|
|
758
|
+
await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
|
|
759
|
+
await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
|
|
760
|
+
await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
|
|
761
|
+
// The answer a template apply kept under its key, which holds the agent as it was made.
|
|
762
|
+
await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
|
|
763
|
+
// Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
|
|
764
|
+
await tx.run("UPDATE revisions SET body = '{}', skills = NULL, package = NULL, note = NULL, mcp_pin = NULL, monid_pin = NULL WHERE agent_id = ?", agentId);
|
|
765
|
+
// Its purge time last, in the same write as its name and description.
|
|
766
|
+
await tx.run("UPDATE agents SET name = '', description = NULL, purged_at = ? WHERE id = ?", now(), agentId);
|
|
767
|
+
return true;
|
|
768
|
+
});
|
|
769
|
+
if (purged)
|
|
770
|
+
await this.#purged(`agent ${agentId}`);
|
|
771
|
+
},
|
|
682
772
|
};
|
|
683
773
|
this.templates = {
|
|
684
774
|
apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
|
|
@@ -966,6 +1056,16 @@ class SqliteStore {
|
|
|
966
1056
|
return this.#queued(await db.transaction(async (tx) => {
|
|
967
1057
|
const at = now();
|
|
968
1058
|
await refuseDeleting(tx, agentId);
|
|
1059
|
+
// A run made from another (a replay of its input, an audit's shadow) never of a purged one: its source's row
|
|
1060
|
+
// held as its purge holds it, so either this commits first and the purge finds it (RunsMadeFromLeft), or the
|
|
1061
|
+
// purge does and this reads its purge time.
|
|
1062
|
+
const of = launch ? madeOf(launch.body) : undefined;
|
|
1063
|
+
if (of !== undefined) {
|
|
1064
|
+
await d.lockRow(tx, "runs", "id", of);
|
|
1065
|
+
const source = await tx.get("SELECT purged_at FROM runs WHERE id = ?", of);
|
|
1066
|
+
if (source && source.purged_at !== null)
|
|
1067
|
+
throw new RunPurged(of, id);
|
|
1068
|
+
}
|
|
969
1069
|
const row = await tx.get(insert, id, agentId, revisionId, labelled, at);
|
|
970
1070
|
if (origin)
|
|
971
1071
|
await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
|
|
@@ -1014,10 +1114,10 @@ class SqliteStore {
|
|
|
1014
1114
|
},
|
|
1015
1115
|
launch: (runId) => readLaunch(db, runId),
|
|
1016
1116
|
learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
|
|
1017
|
-
list: async ({ agentId, revisionId, state, archived, labels, limit }) => {
|
|
1117
|
+
list: async ({ agentId, revisionId, state, archived, labels, limit, purged = false }) => {
|
|
1018
1118
|
// A built-in learning run (a run's grade and merge, queued with its kept learning) is no run of a person's: no list,
|
|
1019
|
-
// count, stat or notice names it.
|
|
1020
|
-
const where = [NOT_A_LEARNING_RUN];
|
|
1119
|
+
// count, stat or notice names it. A purged run is a tombstone: only the readers that sum or count ask for it.
|
|
1120
|
+
const where = [NOT_A_LEARNING_RUN, ...(purged ? [] : ["purged_at IS NULL"])];
|
|
1021
1121
|
const params = [];
|
|
1022
1122
|
if (agentId !== undefined)
|
|
1023
1123
|
(where.push("agent_id = ?"), params.push(agentId));
|
|
@@ -1050,7 +1150,7 @@ class SqliteStore {
|
|
|
1050
1150
|
(where.push("runs.revision_id = ?"), params.push(revisionId));
|
|
1051
1151
|
for (const [key, value] of Object.entries(labels ?? {}))
|
|
1052
1152
|
(where.push(d.jsonObjectHas("runs.labels")), params.push(key, value));
|
|
1053
|
-
where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}
|
|
1153
|
+
where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}`, "runs.purged_at IS NULL");
|
|
1054
1154
|
if (status !== undefined)
|
|
1055
1155
|
(where.push("runs.list_status = ?"), params.push(status));
|
|
1056
1156
|
// A run still going (no settled status on its row) whose listing is behind: its list_status may say what it was.
|
|
@@ -1073,7 +1173,7 @@ class SqliteStore {
|
|
|
1073
1173
|
const [row] = await db.all(`SELECT COUNT(*) AS count, SUM(CASE WHEN runs.state IN ('queued', 'running', 'parked')
|
|
1074
1174
|
OR (runs.state = 'stopped' AND runs.outcome = 'stopped' AND runs.imported_from IS NULL AND revisions.kind = 'agentic') THEN 1 ELSE 0 END) AS live
|
|
1075
1175
|
FROM runs JOIN revisions ON revisions.id = runs.revision_id
|
|
1076
|
-
WHERE runs.agent_id = ? AND ${NOT_A_SHADOW_RUN} AND runs.${NOT_A_LEARNING_RUN}`, agentId);
|
|
1176
|
+
WHERE runs.agent_id = ? AND ${NOT_A_SHADOW_RUN} AND runs.${NOT_A_LEARNING_RUN} AND runs.purged_at IS NULL`, agentId);
|
|
1077
1177
|
return { count: Number(row?.count ?? 0), live: Number(row?.live ?? 0) };
|
|
1078
1178
|
},
|
|
1079
1179
|
// The rows whose listing is behind, by the three ways one falls behind, each over its own partial index.
|
|
@@ -1081,7 +1181,7 @@ class SqliteStore {
|
|
|
1081
1181
|
const n = clock();
|
|
1082
1182
|
const held = heldAt(n.sql);
|
|
1083
1183
|
const rows = await db.all(`SELECT id, list_mark AS mark, held FROM (
|
|
1084
|
-
SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_mark < list_mark
|
|
1184
|
+
SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_mark < list_mark AND purged_at IS NULL
|
|
1085
1185
|
UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_live = 1 AND NOT ${held}
|
|
1086
1186
|
UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_until IS NOT NULL AND listing_until <= ${n.sql}
|
|
1087
1187
|
) AS behind ORDER BY held, started_at DESC, id DESC LIMIT ? OFFSET ?`, ...n.params, ...n.params, ...n.params, ...n.params, ...n.params, limit, offset);
|
|
@@ -1155,7 +1255,66 @@ class SqliteStore {
|
|
|
1155
1255
|
// Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
|
|
1156
1256
|
await db.write([archived ? { sql: "UPDATE runs SET archived_at = COALESCE(archived_at, ?) WHERE id = ?", params: [now(), runId] } : { sql: "UPDATE runs SET archived_at = NULL WHERE id = ?", params: [runId] }]);
|
|
1157
1257
|
},
|
|
1158
|
-
every: async (agentId) => db.all("SELECT id, state FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId)
|
|
1258
|
+
every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
|
|
1259
|
+
.map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null })),
|
|
1260
|
+
madeFrom: async (runId) => {
|
|
1261
|
+
const learning = (await db.all("SELECT DISTINCT learning_run_id AS id FROM learning_proposals WHERE run_id = ? AND learning_run_id IS NOT NULL AND learning_run_id <> ?", runId, runId)).map((row) => row.id);
|
|
1262
|
+
return [...new Set([...(await launchedFrom(db, runId)), ...learning])].sort();
|
|
1263
|
+
},
|
|
1264
|
+
purge: async (runId, kept) => {
|
|
1265
|
+
const purged = await db.transaction(async (tx) => {
|
|
1266
|
+
// Held as a run's end holds it: a write under a claim of it is either in before this, or finds it final.
|
|
1267
|
+
await d.lockRow(tx, "runs", "id", runId, "update");
|
|
1268
|
+
const run = await tx.get("SELECT state, runner, metrics, purged_at FROM runs WHERE id = ?", runId);
|
|
1269
|
+
if (!run || run.purged_at !== null)
|
|
1270
|
+
return false;
|
|
1271
|
+
if (!FINAL_STATES.includes(run.state) || run.runner !== null)
|
|
1272
|
+
throw new StoreConstraint(`run ${runId} is ${run.state}${run.runner === null ? "" : ` under ${run.runner}'s claim`}: only a final run no runner holds is purged`);
|
|
1273
|
+
// A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
|
|
1274
|
+
// its input: each is purged first.
|
|
1275
|
+
const left = [];
|
|
1276
|
+
for (const id of await launchedFrom(tx, runId)) {
|
|
1277
|
+
if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
|
|
1278
|
+
left.push(id);
|
|
1279
|
+
}
|
|
1280
|
+
if (left.length)
|
|
1281
|
+
throw new RunsMadeFromLeft(runId, left);
|
|
1282
|
+
for (const table of PI_TABLES)
|
|
1283
|
+
await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
|
|
1284
|
+
await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
|
|
1285
|
+
await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
|
|
1286
|
+
await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
|
|
1287
|
+
await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
|
|
1288
|
+
await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
|
|
1289
|
+
await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
|
|
1290
|
+
await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
|
|
1291
|
+
await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
|
|
1292
|
+
await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
|
|
1293
|
+
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
1294
|
+
// What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
|
|
1295
|
+
// fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
|
|
1296
|
+
// trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
|
|
1297
|
+
await tx.run("UPDATE triggers SET last_run_id = NULL WHERE last_run_id = ?", runId);
|
|
1298
|
+
await tx.run("UPDATE trigger_firings SET run_id = NULL, payload = NULL, attrs = NULL WHERE run_id = ?", runId);
|
|
1299
|
+
await tx.run("UPDATE trigger_firings SET waits_on = NULL WHERE waits_on = ?", runId);
|
|
1300
|
+
await tx.run("UPDATE minted_tokens SET run = NULL WHERE run = ?", runId);
|
|
1301
|
+
// Its kept learning: what its turn asked and answered and the proposal go; each row stays, with the proposal's
|
|
1302
|
+
// state alone, as the learning meter (learning.spend) and the list's leaving out of learning runs read it.
|
|
1303
|
+
for (const row of await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ?", runId)) {
|
|
1304
|
+
const state = JSON.parse(row.proposal)?.state;
|
|
1305
|
+
await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
|
|
1306
|
+
}
|
|
1307
|
+
// Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
|
|
1308
|
+
// read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
|
|
1309
|
+
const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
|
|
1310
|
+
await tx.run("UPDATE runs SET summary = NULL, labels = NULL, sign_in_handed = NULL, metrics = ? WHERE id = ?", json(metrics), runId);
|
|
1311
|
+
// Its listing, and its purge time last: no list shows it, and no lister builds it again.
|
|
1312
|
+
await tx.run("UPDATE runs SET listing = NULL, list_status = NULL, listing_mark = list_mark, listing_live = 0, listing_until = NULL, listing_flags = 0, purged_at = ? WHERE id = ?", now(), runId);
|
|
1313
|
+
return true;
|
|
1314
|
+
});
|
|
1315
|
+
if (purged)
|
|
1316
|
+
await this.#purged(`run ${runId}`);
|
|
1317
|
+
},
|
|
1159
1318
|
remove: async (runId) => {
|
|
1160
1319
|
await db.transaction(async (tx) => {
|
|
1161
1320
|
// Held as a run's end holds it: a write under a claim of it is either in before this, or finds no row.
|
|
@@ -1178,10 +1337,11 @@ class SqliteStore {
|
|
|
1178
1337
|
await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
|
|
1179
1338
|
await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
|
|
1180
1339
|
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
1340
|
+
await tx.run("DELETE FROM computer_intervals WHERE run_id = ?", runId);
|
|
1181
1341
|
await tx.run("DELETE FROM runs WHERE id = ?", runId);
|
|
1182
1342
|
});
|
|
1183
1343
|
},
|
|
1184
|
-
reopen: async (runId, { kind, body = null }, { launchSealed } = {}) => {
|
|
1344
|
+
reopen: async (runId, { kind, body = null }, { launchSealed, endedAt } = {}) => {
|
|
1185
1345
|
const command = await db.transaction(async (tx) => {
|
|
1186
1346
|
// Never a run of an agent being deleted opened again (its mark, read in this transaction).
|
|
1187
1347
|
const of = await tx.get("SELECT agent_id FROM runs WHERE id = ?", runId);
|
|
@@ -1189,7 +1349,8 @@ class SqliteStore {
|
|
|
1189
1349
|
await refuseDeleting(tx, of.agent_id);
|
|
1190
1350
|
// Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
|
|
1191
1351
|
// spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
|
|
1192
|
-
const
|
|
1352
|
+
const at = endedAt === undefined ? { sql: "", params: [] } : { sql: " AND ended_at = ?", params: [endedAt] };
|
|
1353
|
+
const reopened = await tx.runCounted(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(d)}${at.sql}`, runId, ...at.params);
|
|
1193
1354
|
if (reopened === 0)
|
|
1194
1355
|
throw new RunFinal(runId);
|
|
1195
1356
|
// The message's launch secrets, with it: the claim that runs its turn reads them.
|
|
@@ -1264,7 +1425,7 @@ class SqliteStore {
|
|
|
1264
1425
|
}
|
|
1265
1426
|
}
|
|
1266
1427
|
// An update that made the run final: its other untaken rows are refused in this transaction, after its own takes.
|
|
1267
|
-
await refuseLeftovers(tx, claim.runId, patch.state, at, d);
|
|
1428
|
+
await refuseLeftovers(tx, claim.runId, patch.state, at, d, patch.keepsEnd === true);
|
|
1268
1429
|
// The bind's save lease, in this same transaction as the sign_in_handed write just made (applyRunPatch, under
|
|
1269
1430
|
// SIGN_IN_HANDED_LOCK): this run saves unless another run already holds one of the handed pointers (a running run,
|
|
1270
1431
|
// or — within signInSettleMs of leaving running, a vendor's settle window — one that left running less than that
|
|
@@ -1470,18 +1631,20 @@ class SqliteStore {
|
|
|
1470
1631
|
...(row.learning_run_id === null ? {} : { learningRunId: row.learning_run_id }), createdAt: row.created_at,
|
|
1471
1632
|
});
|
|
1472
1633
|
const PROPOSAL_COLUMNS = "run_id, round, agent_id, turn, proposal, learning_run_id, created_at";
|
|
1634
|
+
// A purged run's kept learning is its state alone (Runs.purge), for the learning meter: no reader of learning reads it.
|
|
1635
|
+
const NOT_PURGED = "NOT EXISTS (SELECT 1 FROM runs WHERE runs.id = learning_proposals.run_id AND runs.purged_at IS NOT NULL)";
|
|
1473
1636
|
this.learning = {
|
|
1474
1637
|
// A round asked for, else the run's newest.
|
|
1475
1638
|
proposal: async (runId, round) => {
|
|
1476
1639
|
const row = round === undefined
|
|
1477
|
-
? await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? ORDER BY round DESC LIMIT 1`, runId)
|
|
1478
|
-
: await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND round =
|
|
1640
|
+
? await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND ${NOT_PURGED} ORDER BY round DESC LIMIT 1`, runId)
|
|
1641
|
+
: await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND round = ? AND ${NOT_PURGED}`, runId, round);
|
|
1479
1642
|
return row ? proposalOf(row) : undefined;
|
|
1480
1643
|
},
|
|
1481
|
-
proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
|
|
1644
|
+
proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND ${NOT_PURGED} ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
|
|
1482
1645
|
kept: async (agentId) => {
|
|
1483
|
-
const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
|
|
1484
|
-
const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL)`, agentId)).map(runOf);
|
|
1646
|
+
const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND ${NOT_PURGED} ORDER BY run_id, round`, agentId)).map(proposalOf);
|
|
1647
|
+
const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL AND ${NOT_PURGED})`, agentId)).map(runOf);
|
|
1485
1648
|
return { proposals, learningRuns };
|
|
1486
1649
|
},
|
|
1487
1650
|
spend: async ({ from, to }) => {
|
|
@@ -1645,6 +1808,21 @@ class SqliteStore {
|
|
|
1645
1808
|
return (result?.changes ?? 0) === 1;
|
|
1646
1809
|
},
|
|
1647
1810
|
};
|
|
1811
|
+
this.computerIntervals = {
|
|
1812
|
+
opened: async (row) => {
|
|
1813
|
+
await db.write([{
|
|
1814
|
+
sql: "INSERT INTO computer_intervals (provider, provider_id, run_id, kind, gpu_type, gpu_count, cpus, memory_mb, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (provider, provider_id) DO NOTHING",
|
|
1815
|
+
params: [row.provider, row.providerId, row.runId, row.kind, row.gpuType, row.gpuCount, row.cpus, row.memoryMb, row.startedAt],
|
|
1816
|
+
}]);
|
|
1817
|
+
},
|
|
1818
|
+
kept: async (provider, providerId) => {
|
|
1819
|
+
await db.write([{ sql: "UPDATE computer_intervals SET kept = 1 WHERE provider = ? AND provider_id = ?", params: [provider, providerId] }]);
|
|
1820
|
+
},
|
|
1821
|
+
ended: async (provider, providerId, at) => {
|
|
1822
|
+
await db.write([{ sql: "UPDATE computer_intervals SET ended_at = ? WHERE provider = ? AND provider_id = ? AND ended_at IS NULL", params: [at, provider, providerId] }]);
|
|
1823
|
+
},
|
|
1824
|
+
forRun: async (runId) => (await db.all("SELECT run_id, provider, provider_id, kind, gpu_type, gpu_count, cpus, memory_mb, started_at, kept, ended_at FROM computer_intervals WHERE run_id = ? ORDER BY started_at, provider, provider_id", runId)).map(intervalOf),
|
|
1825
|
+
};
|
|
1648
1826
|
const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
|
|
1649
1827
|
this.pairedComputers = {
|
|
1650
1828
|
addCode: async (id, codeSha256, expiresAt) => {
|
|
@@ -1944,6 +2122,35 @@ class SqliteStore {
|
|
|
1944
2122
|
handedAny: async () => (await handedAnyIn(db))?.id,
|
|
1945
2123
|
};
|
|
1946
2124
|
}
|
|
2125
|
+
/** After a purge of `what` committed (runs.purge, agents.purge), on a SQLite store with a file: a WAL checkpoint
|
|
2126
|
+
* (TRUNCATE). secure_delete (worker.ts open) zeroed the purged bytes in the pages the purge wrote, but those pages are
|
|
2127
|
+
* new frames in the WAL: the file keeps its earlier images of them, and the WAL its earlier frames, until a checkpoint
|
|
2128
|
+
* copies the zeroed pages into the file and truncates the log. A reader in another connection (a runner's read, a
|
|
2129
|
+
* backup) may hold the log back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy
|
|
2130
|
+
* wait, since every request of the store's one connection queues behind it (the purge already committed). One retry
|
|
2131
|
+
* after a short pause, then a warning, and the old frames stay until the next purge's checkpoint (or the last
|
|
2132
|
+
* connection's close, which checkpoints and removes the log). An automatic checkpoint (PASSIVE) copies the zeroed
|
|
2133
|
+
* pages into the file but leaves the log's old frames in place. Never fails the purge, which committed. */
|
|
2134
|
+
async #purged(what) {
|
|
2135
|
+
const db = this.#db;
|
|
2136
|
+
if (this.#scrubMarker === undefined || !(db instanceof Connection))
|
|
2137
|
+
return;
|
|
2138
|
+
let why = "";
|
|
2139
|
+
for (let tries = 1; tries <= 2; tries++) {
|
|
2140
|
+
try {
|
|
2141
|
+
const checkpoint = await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS);
|
|
2142
|
+
if (checkpoint?.busy === 0)
|
|
2143
|
+
return;
|
|
2144
|
+
why = "another connection held the log";
|
|
2145
|
+
}
|
|
2146
|
+
catch (error) {
|
|
2147
|
+
why = error instanceof StoreBusy ? "another connection held the log" : `the checkpoint failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
2148
|
+
}
|
|
2149
|
+
if (tries === 1)
|
|
2150
|
+
await new Promise((resolve) => setTimeout(resolve, PURGE_CHECKPOINT_RETRY_MS));
|
|
2151
|
+
}
|
|
2152
|
+
this.#warn(`the purge of ${what} committed, but its WAL checkpoint did not finish (${why}): the purged content's earlier page images may stay in the store's file and its -wal until the next purge's checkpoint or the server's stop`);
|
|
2153
|
+
}
|
|
1947
2154
|
async secureRewrite(work, options = {}) {
|
|
1948
2155
|
const marker = this.#scrubMarker;
|
|
1949
2156
|
if (this.#db.dialect.name !== "sqlite" || marker === undefined)
|
|
@@ -1952,14 +2159,8 @@ class SqliteStore {
|
|
|
1952
2159
|
// leaves it, and its next start scrubs though no row is left in the clear.
|
|
1953
2160
|
const pending = existsSync(marker);
|
|
1954
2161
|
markScrub(marker);
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
try {
|
|
1958
|
-
rewritten = await work();
|
|
1959
|
-
}
|
|
1960
|
-
finally {
|
|
1961
|
-
await this.#db.all("PRAGMA secure_delete = OFF");
|
|
1962
|
-
}
|
|
2162
|
+
// secure_delete is on for the connection's whole life (worker.ts open): a rewritten row's old bytes are zeroed in its page.
|
|
2163
|
+
const rewritten = await work();
|
|
1963
2164
|
if (rewritten === 0 && !pending) {
|
|
1964
2165
|
rmSync(marker, { force: true });
|
|
1965
2166
|
return { rewritten };
|
|
@@ -1967,8 +2168,8 @@ class SqliteStore {
|
|
|
1967
2168
|
// Asked with no VACUUM (a server already serving): the marker stays, and the next start's scrub runs it before it serves.
|
|
1968
2169
|
if (options.vacuum === false)
|
|
1969
2170
|
return { rewritten, left: "deferred" };
|
|
1970
|
-
//
|
|
1971
|
-
//
|
|
2171
|
+
// A copy an update of the row left before secure_delete was on (a store an earlier server wrote: a pause, a rename, a
|
|
2172
|
+
// firing) is in a free block or page still. VACUUM rebuilds the file with neither, through the log; the
|
|
1972
2173
|
// checkpoint copies it into the file and truncates the log. Run outside any transaction.
|
|
1973
2174
|
try {
|
|
1974
2175
|
// Another connection's write (a runner's) may hold the lock past the busy wait: one retry after a short pause.
|
|
@@ -50,9 +50,18 @@ export type Request = {
|
|
|
50
50
|
op: "commit";
|
|
51
51
|
} | {
|
|
52
52
|
op: "rollback";
|
|
53
|
+
} | {
|
|
54
|
+
op: "checkpoint";
|
|
55
|
+
busyMs: number;
|
|
53
56
|
} | {
|
|
54
57
|
op: "close";
|
|
55
58
|
};
|
|
59
|
+
/** A WAL checkpoint's result: whether another connection held it back (`busy` 1), the log's frames, and those copied. */
|
|
60
|
+
export type CheckpointResult = {
|
|
61
|
+
busy: number;
|
|
62
|
+
log: number;
|
|
63
|
+
checkpointed: number;
|
|
64
|
+
};
|
|
56
65
|
/** An error as the worker reports it: busy (the lock outlasted busy_timeout), constraint, miss (an expectation), owned
|
|
57
66
|
* (another server holds the store), closed, or sql (anything else). */
|
|
58
67
|
export type WorkerError = {
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// the disk (a flush at FULL, or a write behind another process's lock) waits here, never on the event loop the runner's
|
|
3
3
|
// loops share. WAL with synchronous=NORMAL: a commit is durable against a process crash at once, and against a lost box
|
|
4
4
|
// only after the next FULL commit (flush). Every write starts BEGIN IMMEDIATE, so a write never upgrades a read lock and
|
|
5
|
-
// deadlocks another writer; busy_timeout covers another process's write in flight. Foreign keys are on.
|
|
5
|
+
// deadlocks another writer; busy_timeout covers another process's write in flight. Foreign keys and secure_delete are on.
|
|
6
6
|
//
|
|
7
7
|
// The messages (connection.ts sends them one at a time, in order):
|
|
8
8
|
// open {file, busyTimeoutMs, owner} the connection and its pragmas; `owner` also takes the store's owner lock (one
|
|
@@ -18,6 +18,9 @@
|
|
|
18
18
|
// an interactive transaction (connection.ts transaction()), its statements sent
|
|
19
19
|
// as stmt, or as step (one statement, its changes and rows, its `expect` checked)
|
|
20
20
|
// in between
|
|
21
|
+
// checkpoint {busyMs} a WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's
|
|
22
|
+
// reader or writer, not the connection's own busy wait: the requests queued behind
|
|
23
|
+
// it never wait on it longer. Its result row (busy, log, checkpointed)
|
|
21
24
|
// close
|
|
22
25
|
import { chmodSync, closeSync, openSync } from "node:fs";
|
|
23
26
|
import { parentPort } from "node:worker_threads";
|
|
@@ -207,6 +210,10 @@ function handle(request) {
|
|
|
207
210
|
keepPrivate(request.file, false);
|
|
208
211
|
db.exec(NORMAL);
|
|
209
212
|
db.exec("PRAGMA foreign_keys = ON");
|
|
213
|
+
// Every byte a write of this connection frees (a deleted row, an overwritten value, a freed page) is zeroed in the
|
|
214
|
+
// page it writes, so a purge (or any delete) leaves no copy in the file's free space once the WAL is checkpointed
|
|
215
|
+
// (sqlite/store.ts #purged). Per connection: the server's and each runner's, every one that writes, set here.
|
|
216
|
+
db.exec("PRAGMA secure_delete = ON");
|
|
210
217
|
return null;
|
|
211
218
|
}
|
|
212
219
|
case "exec":
|
|
@@ -247,6 +254,16 @@ function handle(request) {
|
|
|
247
254
|
if (inTx)
|
|
248
255
|
end(false);
|
|
249
256
|
return null;
|
|
257
|
+
case "checkpoint": {
|
|
258
|
+
const conn = opened();
|
|
259
|
+
conn.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(request.busyMs))}`);
|
|
260
|
+
try {
|
|
261
|
+
return conn.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get() ?? null;
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
conn.exec(`PRAGMA busy_timeout = ${busyTimeout}`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
250
267
|
case "close": {
|
|
251
268
|
if (inTx)
|
|
252
269
|
end(false);
|