@parcha/agentrun-serve 0.1.0-beta.49 → 0.1.0-beta.51
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 +173 -9
- package/README.md +246 -39
- package/dist/agent-delete.d.ts +3 -2
- package/dist/agent-delete.js +29 -4
- package/dist/agents-store.js +7 -3
- package/dist/api-only.d.ts +8 -10
- package/dist/api-only.js +11 -12
- package/dist/capacity.d.ts +50 -0
- package/dist/capacity.js +49 -0
- package/dist/cli-learning/claude-wire.d.ts +41 -0
- package/dist/cli-learning/claude-wire.js +258 -0
- package/dist/cli-learning/cli.d.ts +11 -0
- package/dist/cli-learning/cli.js +241 -0
- package/dist/cli-learning/codex-worktree.d.ts +10 -0
- package/dist/cli-learning/codex-worktree.js +119 -0
- package/dist/cli-learning/connections.d.ts +62 -0
- package/dist/cli-learning/connections.js +87 -0
- package/dist/cli-learning/entry.d.ts +1 -0
- package/dist/cli-learning/entry.js +4 -0
- package/dist/cli-learning/evidence.d.ts +78 -0
- package/dist/cli-learning/evidence.js +492 -0
- package/dist/cli-learning/hook.d.ts +33 -0
- package/dist/cli-learning/hook.js +544 -0
- package/dist/cli-learning/install.d.ts +33 -0
- package/dist/cli-learning/install.js +335 -0
- package/dist/cli-learning/observation-proof.d.ts +14 -0
- package/dist/cli-learning/observation-proof.js +10 -0
- package/dist/cli-learning/policy.d.ts +48 -0
- package/dist/cli-learning/policy.js +363 -0
- package/dist/cli-learning/schema.d.ts +16 -0
- package/dist/cli-learning/schema.js +27 -0
- package/dist/cli-learning/state.d.ts +23 -0
- package/dist/cli-learning/state.js +61 -0
- package/dist/cli.js +24 -2
- package/dist/compute-cost.d.ts +101 -0
- package/dist/compute-cost.js +250 -0
- package/dist/console/assets/index-Bt1B51b7.js +733 -0
- package/dist/console/assets/index-sVftE9Ht.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/email/email-faux.d.ts +3 -1
- package/dist/email/email-faux.js +3 -2
- package/dist/email/routes.js +22 -12
- package/dist/eval-previous.d.ts +52 -0
- package/dist/eval-previous.js +164 -0
- package/dist/file-types.d.ts +2 -0
- package/dist/file-types.js +3 -1
- package/dist/harness-install.d.ts +6 -2
- package/dist/harness-install.js +40 -8
- package/dist/harness.d.ts +1 -1
- package/dist/harness.js +3 -2
- package/dist/learn/check.d.ts +8 -5
- package/dist/learn/check.js +25 -24
- package/dist/learn/repick.d.ts +22 -13
- package/dist/learn/repick.js +57 -56
- package/dist/learn/secrets.js +14 -3
- package/dist/learn/workflow-draft.d.ts +4 -0
- package/dist/learn/workflow-draft.js +10 -7
- package/dist/learned-workflow.js +8 -8
- package/dist/learning-setting.js +2 -2
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +1 -1
- package/dist/mcp-pin-first.js +2 -1
- package/dist/mcp-private-hosts.d.ts +24 -3
- package/dist/mcp-private-hosts.js +53 -3
- package/dist/model-gateway.d.ts +2 -0
- package/dist/model-gateway.js +3 -1
- package/dist/native/runtimes.d.ts +2 -0
- package/dist/native/runtimes.js +2 -0
- package/dist/observation/learning.d.ts +32 -0
- package/dist/observation/learning.js +66 -0
- package/dist/observation/observer.d.ts +8 -1
- package/dist/observation/observer.js +89 -9
- package/dist/observation/schema.js +12 -4
- package/dist/observation/usage-identity.d.ts +9 -0
- package/dist/observation/usage-identity.js +11 -0
- package/dist/openapi.js +113 -29
- package/dist/paid-calls.d.ts +13 -6
- package/dist/paid-calls.js +14 -8
- package/dist/run-launch.d.ts +16 -2
- package/dist/run-launch.js +6 -1
- package/dist/run-timeline-served.js +5 -3
- package/dist/run-usage.d.ts +23 -8
- package/dist/run-usage.js +100 -18
- package/dist/run-view.d.ts +2 -0
- package/dist/run-view.js +12 -7
- package/dist/runner/adapter-loop.d.ts +4 -0
- package/dist/runner/adapter-loop.js +44 -27
- package/dist/runner/adapter-run-spec.d.ts +8 -3
- package/dist/runner/adapter-run-spec.js +15 -8
- package/dist/runner/beside.d.ts +13 -0
- package/dist/runner/beside.js +27 -8
- package/dist/runner/big-writes.d.ts +33 -0
- package/dist/runner/big-writes.js +105 -0
- package/dist/runner/cli-run-spec.js +16 -8
- package/dist/runner/disk-free.d.ts +44 -0
- package/dist/runner/disk-free.js +96 -0
- package/dist/runner/feedback-round.d.ts +12 -8
- package/dist/runner/feedback-round.js +16 -30
- package/dist/runner/harness-loops.js +3 -1
- package/dist/runner/held.d.ts +4 -1
- package/dist/runner/journal-kinds.d.ts +1 -1
- package/dist/runner/learning-end.js +13 -4
- package/dist/runner/main.d.ts +17 -6
- package/dist/runner/main.js +187 -45
- package/dist/runner/metrics.d.ts +4 -0
- package/dist/runner/metrics.js +9 -0
- package/dist/runner/presence.d.ts +11 -2
- package/dist/runner/presence.js +31 -3
- package/dist/runner/run-child-host.d.ts +27 -17
- package/dist/runner/run-child-host.js +70 -116
- package/dist/runner/run-child.js +3 -0
- package/dist/runner/run-errors.js +2 -0
- package/dist/runner/runner-check.d.ts +51 -0
- package/dist/runner/runner-check.js +206 -0
- package/dist/runner/runner-metrics.d.ts +19 -0
- package/dist/runner/runner-metrics.js +49 -0
- package/dist/runner/runner.d.ts +37 -0
- package/dist/runner/runner.js +43 -3
- package/dist/runner/save-slots.d.ts +9 -0
- package/dist/runner/save-slots.js +91 -0
- package/dist/runner/sdk-loop.js +34 -22
- package/dist/runs-over-store.d.ts +8 -1
- package/dist/runs-over-store.js +57 -9
- package/dist/sdk/runs.d.ts +25 -6
- package/dist/sdk/runs.js +107 -35
- package/dist/sdk/runtimes.d.ts +19 -0
- package/dist/sdk/runtimes.js +23 -0
- package/dist/sdk/schema.d.ts +14 -8
- package/dist/sdk/schema.js +18 -6
- package/dist/server.d.ts +7 -0
- package/dist/server.js +151 -28
- package/dist/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/start-switches.js +2 -0
- package/dist/stats.d.ts +4 -0
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.d.ts +13 -2
- package/dist/store/agent-body.js +19 -4
- package/dist/store/dialect.d.ts +2 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/postgres/connection.d.ts +5 -2
- package/dist/store/postgres/connection.js +19 -7
- package/dist/store/postgres/dialect.js +1 -0
- package/dist/store/postgres/migrate.d.ts +30 -0
- package/dist/store/postgres/migrate.js +72 -5
- package/dist/store/postgres/migration-lint.d.ts +8 -0
- package/dist/store/postgres/migration-lint.js +119 -0
- package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
- package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
- package/dist/store/postgres/store.d.ts +8 -3
- package/dist/store/postgres/store.js +31 -11
- package/dist/store/schema.d.ts +26 -4
- package/dist/store/schema.js +45 -4
- package/dist/store/sqlite/connection.d.ts +3 -3
- package/dist/store/sqlite/connection.js +3 -3
- package/dist/store/sqlite/run-launch.d.ts +9 -1
- package/dist/store/sqlite/run-launch.js +44 -0
- package/dist/store/sqlite/store.d.ts +19 -4
- package/dist/store/sqlite/store.js +180 -93
- package/dist/store/store-schema.d.ts +34 -0
- package/dist/store/store-schema.js +125 -0
- package/dist/store/store.d.ts +61 -2
- package/dist/store/store.js +13 -0
- package/dist/store-reads/analytics.d.ts +3 -2
- package/dist/store-reads/analytics.js +20 -8
- package/dist/store-reads/cap.d.ts +9 -5
- package/dist/store-reads/cap.js +28 -2
- package/dist/store-reads/decisions.d.ts +21 -0
- package/dist/store-reads/decisions.js +22 -0
- package/dist/store-reads/journal.d.ts +8 -2
- package/dist/store-reads/journal.js +27 -8
- package/dist/store-view.d.ts +9 -4
- package/dist/store-view.js +48 -25
- package/dist/template-eval.d.ts +15 -1
- package/dist/template-eval.js +92 -13
- package/dist/templates.d.ts +4 -3
- package/dist/templates.js +4 -3
- package/dist/timeline/labels.js +17 -0
- package/dist/tool-gate.d.ts +4 -2
- package/dist/tool-list.js +1 -0
- package/dist/tools.d.ts +6 -2
- package/dist/tools.js +13 -1
- package/dist/trigger-targets.d.ts +21 -5
- package/dist/trigger-targets.js +13 -10
- package/dist/unified-usage.d.ts +24 -0
- package/dist/unified-usage.js +400 -0
- package/dist/uploads-archil.d.ts +100 -0
- package/dist/uploads-archil.js +430 -0
- package/dist/uploads.d.ts +55 -1
- package/dist/uploads.js +185 -98
- package/dist/validate.js +1 -1
- package/dist/web-fake.d.ts +25 -0
- package/dist/web-fake.js +38 -1
- package/dist/web-save.d.ts +75 -0
- package/dist/web-save.js +235 -0
- package/dist/workspace/archil-claim.d.ts +5 -2
- package/dist/workspace/archil-claim.js +5 -2
- package/dist/workspace/archil-disk.d.ts +11 -1
- package/dist/workspace/archil-disk.js +43 -10
- package/dist/workspace/archil.d.ts +3 -0
- package/dist/workspace/archil.js +102 -16
- package/dist/workspace/computer-for-claim.d.ts +14 -0
- package/dist/workspace/computer-for-claim.js +46 -7
- package/dist/workspace/computer-intervals.d.ts +9 -3
- package/dist/workspace/computer-intervals.js +17 -8
- package/dist/workspace/pieced.d.ts +14 -0
- package/dist/workspace/pieced.js +23 -0
- package/dist/workspace/run-disk.js +32 -12
- package/dist/workspace/run-workspace.d.ts +1 -1
- package/dist/workspace/run-workspace.js +11 -6
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +52 -7
- package/templates/README.md +36 -7
- package/dist/console/assets/index-Bzn4eUYF.js +0 -715
- package/dist/console/assets/index-CR2ZGei1.css +0 -1
|
@@ -12,7 +12,7 @@ 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, 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";
|
|
15
|
+
import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNNERS_ADDED, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
16
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
17
|
/** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
|
|
18
18
|
const madeOf = (body) => {
|
|
@@ -33,7 +33,7 @@ import { cleanText, settledBody } from "../dialect.js";
|
|
|
33
33
|
import { inMemory } from "./memory.js";
|
|
34
34
|
import { Connection, DEFAULT_BUSY_TIMEOUT_MS } from "./connection.js";
|
|
35
35
|
import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
|
|
36
|
-
import { readLaunch, readLearningStarts, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
36
|
+
import { readLaunch, readLearningStarts, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
37
37
|
import { canonical } from "../agent-body.js";
|
|
38
38
|
import { aadOf, sealedAt } from "../seal.js";
|
|
39
39
|
/** A claim's length when the caller names none. */
|
|
@@ -171,12 +171,12 @@ const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), u
|
|
|
171
171
|
const orNull = (value) => (value === null ? null : Number(value));
|
|
172
172
|
const intervalOf = (r) => ({
|
|
173
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),
|
|
174
|
+
memoryMb: orNull(r.memory_mb), diskGb: orNull(r.disk_gb), startedAt: Number(r.started_at), kept: Number(r.kept) === 1, endedAt: orNull(r.ended_at), bookedMs: Number(r.booked_ms),
|
|
175
175
|
});
|
|
176
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 });
|
|
177
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 });
|
|
178
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 });
|
|
179
|
-
const runnerOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, refused: r.refused, host: r.host, port: r.port === null ? null : Number(r.port), seenAt: Number(r.seen_at) });
|
|
179
|
+
const runnerOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, refused: r.refused, host: r.host, port: r.port === null ? null : Number(r.port), seenAt: Number(r.seen_at), version: r.version, slots: r.slots === null ? null : Number(r.slots) });
|
|
180
180
|
const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
|
|
181
181
|
const mcpOauthOf = (r) => ({ state: r.state, server: r.server, sealed: Uint8Array.from(r.sealed), working: r.working === null ? null : JSON.parse(r.working), expiresAt: r.expires_at });
|
|
182
182
|
const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
|
|
@@ -198,12 +198,35 @@ async function versionOf(db) {
|
|
|
198
198
|
* (webhook.json, webhook-outbox.json) do not refuse the directory either: nothing reads them, and the webhook, now in
|
|
199
199
|
* the store, is set again. */
|
|
200
200
|
const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json", "trigger-secrets.json", ".door-token"];
|
|
201
|
+
/** The columns a runner of this build needs that an earlier build of this same version may not have: the server adds each
|
|
202
|
+
* at its start (openSqliteStore), and a runner on a file without one waits for that server (StoreAwaitsServer, in `why`'s
|
|
203
|
+
* words; exit 3). store-schema reads the same list, so its report says "waits" where the runner would. */
|
|
204
|
+
export const SQLITE_RUNNER_NEEDS = [
|
|
205
|
+
{ table: "revisions", columns: ["mcp_pin", "monid_pin"], why: "install MCP and Monid revision metadata" },
|
|
206
|
+
{ table: "settings", columns: ["connector_id"], why: "add native command ownership metadata" },
|
|
207
|
+
{ table: "runs", columns: ["cost_upper_bound"], why: "add the bound beside each run's cost" },
|
|
208
|
+
{ table: "runs", columns: ["labels"], why: "add each run's labels" },
|
|
209
|
+
{ table: "triggers", columns: ["template_id"], why: "add each trigger's package mark" },
|
|
210
|
+
{ table: "runners", columns: ["host"], why: "keep each runner's word that it is there and its relay in one table (runners)" },
|
|
211
|
+
{ table: "runners", columns: Object.keys(RUNNERS_ADDED), why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
|
|
212
|
+
{ table: "hand_backs", columns: ["run_id"], why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
|
|
213
|
+
];
|
|
214
|
+
/** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
|
|
215
|
+
* or undefined when it opens; `columnsOf` reads a table's columns. */
|
|
216
|
+
export async function runnerWaitsFor(columnsOf) {
|
|
217
|
+
for (const need of SQLITE_RUNNER_NEEDS) {
|
|
218
|
+
const present = await columnsOf(need.table);
|
|
219
|
+
if (need.columns.some((column) => !present.has(column)))
|
|
220
|
+
return need.why;
|
|
221
|
+
}
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
201
224
|
/** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
|
|
202
225
|
* store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
|
|
203
226
|
* disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
|
|
204
227
|
* (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. The store is read before
|
|
205
228
|
* this server holds its owner lock, so it waits `busyTimeoutMs` for another process's lock on it (isThisVersionsStore). */
|
|
206
|
-
function earlierVersionIn(dataDir, busyTimeoutMs) {
|
|
229
|
+
export function earlierVersionIn(dataDir, busyTimeoutMs) {
|
|
207
230
|
if (!existsSync(dataDir))
|
|
208
231
|
return [];
|
|
209
232
|
const found = [];
|
|
@@ -329,6 +352,13 @@ export async function openSqliteStore(options) {
|
|
|
329
352
|
if (found !== SCHEMA_VERSION && !upgrading)
|
|
330
353
|
throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
|
|
331
354
|
const columns = new Set((await connection.all("SELECT name FROM pragma_table_info('revisions')")).map((column) => column.name));
|
|
355
|
+
// Every column a runner of this build needs that an earlier build of this version may lack (SQLITE_RUNNER_NEEDS), read
|
|
356
|
+
// at once: the same list store-schema reports from. Each check below says the same, where the server adds it.
|
|
357
|
+
if (role === "runner") {
|
|
358
|
+
const waits = await runnerWaitsFor(async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name)));
|
|
359
|
+
if (waits !== undefined)
|
|
360
|
+
throw new StoreAwaitsServer(waits);
|
|
361
|
+
}
|
|
332
362
|
if (role === "runner" && (!columns.has("mcp_pin") || !columns.has("monid_pin")))
|
|
333
363
|
throw new StoreAwaitsServer("install MCP and Monid revision metadata");
|
|
334
364
|
const nativeOwners = (await connection.all("PRAGMA table_info(settings)")).some(column => column.name === 'connector_id');
|
|
@@ -363,9 +393,15 @@ export async function openSqliteStore(options) {
|
|
|
363
393
|
// An earlier build of version 13 kept each runner's relay in a table of its own (runner_relays), which the server's
|
|
364
394
|
// open below drops for runners (schema.ts RUNNERS). A runner says it is there, and where its relay answers, through
|
|
365
395
|
// runners alone, so it waits for that server.
|
|
366
|
-
|
|
396
|
+
const runnerColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('runners')")).map((column) => column.name));
|
|
397
|
+
if (role === "runner" && !runnerColumns.has("host")) {
|
|
367
398
|
throw new StoreAwaitsServer("keep each runner's word that it is there and its relay in one table (runners)");
|
|
368
399
|
}
|
|
400
|
+
// An earlier build of this version kept no runner's version and slots (schema.ts RUNNERS_ADDED) and no hand-backs
|
|
401
|
+
// (HAND_BACKS): a runner writes both (its presence, its releases), so it waits for the server that adds them below.
|
|
402
|
+
if (role === "runner" && (Object.keys(RUNNERS_ADDED).some((column) => !runnerColumns.has(column)) || (await connection.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'hand_backs'")).length === 0)) {
|
|
403
|
+
throw new StoreAwaitsServer("keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)");
|
|
404
|
+
}
|
|
369
405
|
// The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
|
|
370
406
|
// migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
|
|
371
407
|
// An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
|
|
@@ -393,11 +429,27 @@ export async function openSqliteStore(options) {
|
|
|
393
429
|
// dropped, its rows heartbeats that each relay's runner writes again within its renewal, so none is copied.
|
|
394
430
|
{ sql: "DROP TABLE IF EXISTS runner_relays" },
|
|
395
431
|
{ sql: RUNNERS },
|
|
432
|
+
// Nor any hand-back (schema.ts HAND_BACKS): a release before it kept none.
|
|
433
|
+
{ sql: HAND_BACKS },
|
|
434
|
+
{ sql: HAND_BACKS_AT },
|
|
435
|
+
{ sql: HAND_BACKS_RUN },
|
|
396
436
|
// Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
|
|
397
437
|
{ sql: COMPUTER_INTERVALS },
|
|
398
438
|
{ sql: COMPUTER_INTERVALS_RUN },
|
|
399
439
|
{ sql: NATIVE_COMMANDS_INDEX },
|
|
400
440
|
], { full: true });
|
|
441
|
+
// A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
|
|
442
|
+
// COMPUTER_INTERVALS_ADDED): each column added where missing, its rows' disk unknown (null) and booked time none.
|
|
443
|
+
const intervalColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('computer_intervals')")).map((column) => column.name));
|
|
444
|
+
const missing = Object.entries(COMPUTER_INTERVALS_ADDED).filter(([column]) => !intervalColumns.has(column)).map(([, sql]) => ({ sql }));
|
|
445
|
+
if (missing.length > 0)
|
|
446
|
+
await connection.write(missing, { full: true });
|
|
447
|
+
// A runners table an earlier build of this version made has no version or slots (schema.ts RUNNERS_ADDED): each added
|
|
448
|
+
// where missing, every row's unknown (null) until its runner's next put.
|
|
449
|
+
const runnersNow = new Set((await connection.all("SELECT name FROM pragma_table_info('runners')")).map((column) => column.name));
|
|
450
|
+
const runnersMissing = Object.entries(RUNNERS_ADDED).filter(([column]) => !runnersNow.has(column)).map(([, sql]) => ({ sql }));
|
|
451
|
+
if (runnersMissing.length > 0)
|
|
452
|
+
await connection.write(runnersMissing, { full: true });
|
|
401
453
|
await backfillNativeCommandOwners(connection);
|
|
402
454
|
if (found === 11) {
|
|
403
455
|
const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
|
|
@@ -417,7 +469,14 @@ export async function openSqliteStore(options) {
|
|
|
417
469
|
await connection.close().catch(() => undefined);
|
|
418
470
|
throw error;
|
|
419
471
|
}
|
|
420
|
-
|
|
472
|
+
const store = storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
|
|
473
|
+
// A SQLite runner opens only its own version (the server upgrades the file in place at its start, never beside a
|
|
474
|
+
// runner on another build): its floor is the version itself.
|
|
475
|
+
const schemaState = async () => {
|
|
476
|
+
const version = await versionOf(connection);
|
|
477
|
+
return { version, runnerFloor: version, known: SCHEMA_VERSION };
|
|
478
|
+
};
|
|
479
|
+
return Object.assign(store, { schemaState });
|
|
421
480
|
}
|
|
422
481
|
/** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
|
|
423
482
|
const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
|
|
@@ -478,27 +537,49 @@ function readOnly(tx) {
|
|
|
478
537
|
/** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
|
|
479
538
|
* clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
|
|
480
539
|
* `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
|
|
481
|
-
* purge checkpoints.
|
|
482
|
-
export function storeOver(connection, now, file
|
|
483
|
-
return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}
|
|
540
|
+
* purge checkpoints. */
|
|
541
|
+
export function storeOver(connection, now, file) {
|
|
542
|
+
return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`);
|
|
484
543
|
}
|
|
485
|
-
|
|
486
|
-
|
|
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. */
|
|
544
|
+
/** How long a purge's checkpoint waits for another connection's reader or writer before it leaves the log to the next
|
|
545
|
+
* start's scrub: short, since every other request of the store's connection queues behind it. */
|
|
491
546
|
const PURGE_CHECKPOINT_BUSY_MS = 20;
|
|
492
|
-
/**
|
|
493
|
-
*
|
|
547
|
+
/** A run's content in every table that keeps it by the run's id, gone: what a run's purge (Runs.purge) and its delete
|
|
548
|
+
* (Runs.remove) both drop. A table added for a run's content goes here, so neither path leaves it behind. */
|
|
549
|
+
async function dropRunContent(tx, runId) {
|
|
550
|
+
for (const table of PI_TABLES)
|
|
551
|
+
await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
|
|
552
|
+
await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
|
|
553
|
+
await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
|
|
554
|
+
await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
|
|
555
|
+
await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
|
|
556
|
+
await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
|
|
557
|
+
await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
|
|
558
|
+
await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
|
|
559
|
+
await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
|
|
560
|
+
await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
|
|
561
|
+
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
562
|
+
await tx.run("DELETE FROM hand_backs WHERE run_id = ?", runId);
|
|
563
|
+
}
|
|
564
|
+
/** An agent's own rows no tombstone keeps (its learning, its saved sign-ins and their tombstones), gone: what an agent's
|
|
565
|
+
* purge (Agents.purge) and its delete (Agents.remove) both drop. */
|
|
566
|
+
async function dropAgentPrivate(tx, agentId) {
|
|
567
|
+
await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
|
|
568
|
+
await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
|
|
569
|
+
await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
|
|
570
|
+
}
|
|
571
|
+
/** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite (and a purge, when its
|
|
572
|
+
* checkpoint could not truncate the log) and removes once no file of the store keeps the bytes they replaced: a start
|
|
573
|
+
* that finds it finishes the scrub. */
|
|
494
574
|
const SCRUB_SUFFIX = ".scrub";
|
|
495
575
|
/** How long the scrub's VACUUM waits, once its busy wait ran out on another connection's write, before its one retry. */
|
|
496
576
|
const VACUUM_RETRY_MS = 400;
|
|
497
|
-
/** The marker at `path`, written and synced (its directory too) before the rewrite it marks changes a byte
|
|
577
|
+
/** The marker at `path`, written and synced (its directory too): before the rewrite it marks changes a byte, or once a
|
|
578
|
+
* purge's checkpoint left the log. */
|
|
498
579
|
function markScrub(path) {
|
|
499
580
|
const fd = openSync(path, "w", 0o600);
|
|
500
581
|
try {
|
|
501
|
-
writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear may have left
|
|
582
|
+
writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear, or a purge, may have left old bytes in the store's free pages or its WAL; the next start scrubs them and removes this file.\n");
|
|
502
583
|
fsyncSync(fd);
|
|
503
584
|
}
|
|
504
585
|
finally {
|
|
@@ -554,12 +635,13 @@ class SqliteStore {
|
|
|
554
635
|
#released = new Map();
|
|
555
636
|
/** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
|
|
556
637
|
#scrubMarker;
|
|
557
|
-
/**
|
|
558
|
-
|
|
559
|
-
|
|
638
|
+
/** How many times a purge left the marker (#purged). The marker has two owners: secureRewrite removes it only when no
|
|
639
|
+
* purge left it since the step that covers that purge's log (its own start, or the checkpoint it asked), so a marker a
|
|
640
|
+
* purge left is never removed without a checkpoint that truncated the purge's frames. */
|
|
641
|
+
#purgeMarks = 0;
|
|
642
|
+
constructor(db, now, origin, scrubMarker) {
|
|
560
643
|
this.#db = db;
|
|
561
644
|
this.#scrubMarker = scrubMarker;
|
|
562
|
-
this.#warn = warn;
|
|
563
645
|
this.#now = now;
|
|
564
646
|
this.origin = origin ?? this;
|
|
565
647
|
this.where = db.where;
|
|
@@ -732,9 +814,7 @@ class SqliteStore {
|
|
|
732
814
|
if (left.length)
|
|
733
815
|
throw new TriggersLeft(agentId, left.map((one) => one.id));
|
|
734
816
|
await tx.run("DELETE FROM learning_proposals WHERE agent_id = ?", agentId);
|
|
735
|
-
await tx
|
|
736
|
-
await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
|
|
737
|
-
await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
|
|
817
|
+
await dropAgentPrivate(tx, agentId);
|
|
738
818
|
// Its revisions in one statement (a revision's parent is the same agent's, checked at the statement's end), the
|
|
739
819
|
// agent's pointer at its current one cleared first.
|
|
740
820
|
await tx.run("UPDATE agents SET current_revision = NULL WHERE id = ?", agentId);
|
|
@@ -755,9 +835,7 @@ class SqliteStore {
|
|
|
755
835
|
const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
|
|
756
836
|
if (triggersLeft.length)
|
|
757
837
|
throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
|
|
758
|
-
await tx
|
|
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);
|
|
838
|
+
await dropAgentPrivate(tx, agentId);
|
|
761
839
|
// The answer a template apply kept under its key, which holds the agent as it was made.
|
|
762
840
|
await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
|
|
763
841
|
// Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
|
|
@@ -767,7 +845,7 @@ class SqliteStore {
|
|
|
767
845
|
return true;
|
|
768
846
|
});
|
|
769
847
|
if (purged)
|
|
770
|
-
await this.#purged(
|
|
848
|
+
await this.#purged();
|
|
771
849
|
},
|
|
772
850
|
};
|
|
773
851
|
this.templates = {
|
|
@@ -1113,6 +1191,7 @@ class SqliteStore {
|
|
|
1113
1191
|
return row && runOf(row);
|
|
1114
1192
|
},
|
|
1115
1193
|
launch: (runId) => readLaunch(db, runId),
|
|
1194
|
+
usageMetadata: (runId, options) => readUsageMetadata(db, runId, options),
|
|
1116
1195
|
learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
|
|
1117
1196
|
list: async ({ agentId, revisionId, state, archived, labels, limit, purged = false }) => {
|
|
1118
1197
|
// 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,
|
|
@@ -1279,18 +1358,7 @@ class SqliteStore {
|
|
|
1279
1358
|
}
|
|
1280
1359
|
if (left.length)
|
|
1281
1360
|
throw new RunsMadeFromLeft(runId, left);
|
|
1282
|
-
|
|
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);
|
|
1361
|
+
await dropRunContent(tx, runId);
|
|
1294
1362
|
// What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
|
|
1295
1363
|
// fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
|
|
1296
1364
|
// trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
|
|
@@ -1313,7 +1381,7 @@ class SqliteStore {
|
|
|
1313
1381
|
return true;
|
|
1314
1382
|
});
|
|
1315
1383
|
if (purged)
|
|
1316
|
-
await this.#purged(
|
|
1384
|
+
await this.#purged();
|
|
1317
1385
|
},
|
|
1318
1386
|
remove: async (runId) => {
|
|
1319
1387
|
await db.transaction(async (tx) => {
|
|
@@ -1324,19 +1392,9 @@ class SqliteStore {
|
|
|
1324
1392
|
return;
|
|
1325
1393
|
if (!FINAL_STATES.includes(run.state))
|
|
1326
1394
|
throw new StoreConstraint(`run ${runId} is ${run.state}: only a final run is removed`);
|
|
1327
|
-
|
|
1328
|
-
await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
|
|
1329
|
-
await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
|
|
1330
|
-
await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
|
|
1331
|
-
await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
|
|
1332
|
-
await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
|
|
1333
|
-
await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
|
|
1334
|
-
await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
|
|
1335
|
-
await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
|
|
1336
|
-
await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
|
|
1395
|
+
await dropRunContent(tx, runId);
|
|
1337
1396
|
await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
|
|
1338
|
-
|
|
1339
|
-
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
1397
|
+
// Its computers' usage, which a purge keeps (figures, no words).
|
|
1340
1398
|
await tx.run("DELETE FROM computer_intervals WHERE run_id = ?", runId);
|
|
1341
1399
|
await tx.run("DELETE FROM runs WHERE id = ?", runId);
|
|
1342
1400
|
});
|
|
@@ -1811,8 +1869,8 @@ class SqliteStore {
|
|
|
1811
1869
|
this.computerIntervals = {
|
|
1812
1870
|
opened: async (row) => {
|
|
1813
1871
|
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],
|
|
1872
|
+
sql: "INSERT INTO computer_intervals (provider, provider_id, run_id, kind, gpu_type, gpu_count, cpus, memory_mb, disk_gb, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (provider, provider_id) DO NOTHING",
|
|
1873
|
+
params: [row.provider, row.providerId, row.runId, row.kind, row.gpuType, row.gpuCount, row.cpus, row.memoryMb, row.diskGb, row.startedAt],
|
|
1816
1874
|
}]);
|
|
1817
1875
|
},
|
|
1818
1876
|
kept: async (provider, providerId) => {
|
|
@@ -1821,7 +1879,12 @@ class SqliteStore {
|
|
|
1821
1879
|
ended: async (provider, providerId, at) => {
|
|
1822
1880
|
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
1881
|
},
|
|
1824
|
-
|
|
1882
|
+
booked: async (provider, providerId, ms) => {
|
|
1883
|
+
if (!Number.isSafeInteger(ms) || ms <= 0)
|
|
1884
|
+
return;
|
|
1885
|
+
await db.write([{ sql: "UPDATE computer_intervals SET booked_ms = booked_ms + ? WHERE provider = ? AND provider_id = ?", params: [ms, provider, providerId] }]);
|
|
1886
|
+
},
|
|
1887
|
+
forRun: async (runId) => (await db.all("SELECT run_id, provider, provider_id, kind, gpu_type, gpu_count, cpus, memory_mb, disk_gb, started_at, kept, ended_at, booked_ms FROM computer_intervals WHERE run_id = ? ORDER BY started_at, provider, provider_id", runId)).map(intervalOf),
|
|
1825
1888
|
};
|
|
1826
1889
|
const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
|
|
1827
1890
|
this.pairedComputers = {
|
|
@@ -1888,9 +1951,9 @@ class SqliteStore {
|
|
|
1888
1951
|
};
|
|
1889
1952
|
// Stamped and judged on the deadlines' clock (fence.ts storeNow: the database's on Postgres), the one a claim's lease
|
|
1890
1953
|
// runs on, so a runner on another host whose own clock is behind the server's never reads as gone (nor its relay).
|
|
1891
|
-
const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at FROM runners";
|
|
1954
|
+
const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at, version, slots FROM runners";
|
|
1892
1955
|
this.runners = {
|
|
1893
|
-
put: async ({ runner, incarnation, refused, host = null, port = null }, { unlessLiveMs } = {}) => {
|
|
1956
|
+
put: async ({ runner, incarnation, refused, host = null, port = null, version = null, slots = null }, { unlessLiveMs } = {}) => {
|
|
1894
1957
|
const n = clock();
|
|
1895
1958
|
// With unlessLiveMs, the upsert's WHERE leaves a row another incarnation renewed within it as it is, in the same
|
|
1896
1959
|
// statement: no read between, so a later process's put can never land between a look and this write.
|
|
@@ -1898,8 +1961,8 @@ class SqliteStore {
|
|
|
1898
1961
|
const [, result] = await db.write([
|
|
1899
1962
|
{ sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
|
|
1900
1963
|
{
|
|
1901
|
-
sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at${unlessLive}`,
|
|
1902
|
-
params: [runner, incarnation, refused, host, port, ...n.params, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
|
|
1964
|
+
sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at, version, slots) VALUES (?, ?, ?, ?, ?, ${n.sql}, ?, ?) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at, version = excluded.version, slots = excluded.slots${unlessLive}`,
|
|
1965
|
+
params: [runner, incarnation, refused, host, port, ...n.params, version, slots, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
|
|
1903
1966
|
},
|
|
1904
1967
|
]);
|
|
1905
1968
|
return (result?.changes ?? 0) === 1;
|
|
@@ -1917,6 +1980,22 @@ class SqliteStore {
|
|
|
1917
1980
|
remove: async (runner, incarnation) => {
|
|
1918
1981
|
await db.write([{ sql: "DELETE FROM runners WHERE runner = ? AND incarnation = ?", params: [runner, incarnation] }]);
|
|
1919
1982
|
},
|
|
1983
|
+
capacity: async (windowMs) => {
|
|
1984
|
+
// One read snapshot (Postgres: REPEATABLE READ READ ONLY; SQLite: one read transaction), so a claim or a release
|
|
1985
|
+
// that lands meanwhile never counts a run as both waiting and held, or as neither. The deadlines' clock is read
|
|
1986
|
+
// once in it, then bound into every count, so the counts judge one "now".
|
|
1987
|
+
return db.transaction(async (tx) => {
|
|
1988
|
+
const now = clock();
|
|
1989
|
+
const [read] = await tx.all(`SELECT ${now.sql} AS at`, ...now.params);
|
|
1990
|
+
const at = Number(read.at);
|
|
1991
|
+
const n = { sql: d.bigintParam, params: [at] };
|
|
1992
|
+
const claimable = claimableIn(d, n);
|
|
1993
|
+
const [queued] = await tx.all(`SELECT count(*) AS count FROM runs WHERE ${claimable.sql}`, ...claimable.params);
|
|
1994
|
+
const held = await tx.all(`SELECT runner, count(*) AS count FROM runs WHERE state IN ('running', 'parked') AND runner IS NOT NULL AND claimed_until >= ${n.sql} GROUP BY runner ORDER BY runner`, ...n.params);
|
|
1995
|
+
const [handBacks] = await tx.all(`SELECT count(*) AS count FROM hand_backs WHERE at >= ${n.sql} - ${d.bigintParam}`, ...n.params, windowMs);
|
|
1996
|
+
return { at, queued: Number(queued?.count ?? 0), held: new Map(held.map((row) => [row.runner, Number(row.count)])), handBacks: Number(handBacks?.count ?? 0) };
|
|
1997
|
+
}, { read: true });
|
|
1998
|
+
},
|
|
1920
1999
|
};
|
|
1921
2000
|
this.importedTemplates = {
|
|
1922
2001
|
list: async () => (await db.all("SELECT id, source, sha, publisher, files, imported_at FROM imported_templates ORDER BY id")).map((row) => ({
|
|
@@ -2122,46 +2201,46 @@ class SqliteStore {
|
|
|
2122
2201
|
handedAny: async () => (await handedAnyIn(db))?.id,
|
|
2123
2202
|
};
|
|
2124
2203
|
}
|
|
2125
|
-
/** After a purge
|
|
2126
|
-
*
|
|
2127
|
-
*
|
|
2128
|
-
*
|
|
2129
|
-
*
|
|
2130
|
-
*
|
|
2131
|
-
*
|
|
2132
|
-
*
|
|
2133
|
-
*
|
|
2134
|
-
async #purged(
|
|
2204
|
+
/** After a purge committed (runs.purge, agents.purge), on a SQLite store with a file: a WAL checkpoint (TRUNCATE).
|
|
2205
|
+
* secure_delete (worker.ts open) zeroed the purged bytes in the pages the purge wrote, but those pages are new frames
|
|
2206
|
+
* in the WAL: the file keeps its earlier images of them, and the WAL its earlier frames, until a checkpoint copies the
|
|
2207
|
+
* zeroed pages into the file and truncates the log. A reader in another connection (a runner's read, a backup) may hold
|
|
2208
|
+
* the log back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy wait, since every
|
|
2209
|
+
* request of the store's one connection queues behind it (the purge already committed). One it held back (or that
|
|
2210
|
+
* failed) leaves secureRewrite's marker, so the next start's scrub truncates the log, a crash between included. A marker
|
|
2211
|
+
* that cannot be written (a full disk) throws, the purge committed: its caller answers it as the fault it is (a 500 the
|
|
2212
|
+
* server logs), and drops what it served of the purged run all the same (agent-delete.ts purgeOneOrRefuse). */
|
|
2213
|
+
async #purged() {
|
|
2214
|
+
const marker = this.#scrubMarker;
|
|
2135
2215
|
const db = this.#db;
|
|
2136
|
-
if (
|
|
2216
|
+
if (marker === undefined || !(db instanceof Connection))
|
|
2137
2217
|
return;
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
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));
|
|
2218
|
+
const checkpoint = await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS).catch(() => undefined);
|
|
2219
|
+
if (checkpoint?.busy === 0)
|
|
2220
|
+
return;
|
|
2221
|
+
this.#purgeMarks++;
|
|
2222
|
+
try {
|
|
2223
|
+
markScrub(marker);
|
|
2224
|
+
}
|
|
2225
|
+
catch (error) {
|
|
2226
|
+
throw new Error(`The purge committed, but its WAL checkpoint was held back and the scrub's marker could not be written (${error.message}): the log may keep the purged bytes until a later checkpoint truncates it.`, { cause: error });
|
|
2151
2227
|
}
|
|
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
2228
|
}
|
|
2154
2229
|
async secureRewrite(work, options = {}) {
|
|
2155
2230
|
const marker = this.#scrubMarker;
|
|
2156
|
-
|
|
2231
|
+
const db = this.#db;
|
|
2232
|
+
if (marker === undefined || !(db instanceof Connection))
|
|
2157
2233
|
return { rewritten: await work() };
|
|
2158
2234
|
// Written before any byte changes: a server that dies after the rewrite committed, and before the scrub below is done,
|
|
2159
2235
|
// leaves it, and its next start scrubs though no row is left in the clear.
|
|
2160
2236
|
const pending = existsSync(marker);
|
|
2237
|
+
const purgesBefore = this.#purgeMarks;
|
|
2161
2238
|
markScrub(marker);
|
|
2162
2239
|
// 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
2240
|
const rewritten = await work();
|
|
2164
|
-
|
|
2241
|
+
// Nothing rewritten, and the marker is this call's alone: no purge left it while the work ran (#purgeMarks). One that
|
|
2242
|
+
// did needs the checkpoint below, or the next start's scrub.
|
|
2243
|
+
if (rewritten === 0 && !pending && this.#purgeMarks === purgesBefore) {
|
|
2165
2244
|
rmSync(marker, { force: true });
|
|
2166
2245
|
return { rewritten };
|
|
2167
2246
|
}
|
|
@@ -2179,10 +2258,12 @@ class SqliteStore {
|
|
|
2179
2258
|
await new Promise((resolve) => setTimeout(resolve, VACUUM_RETRY_MS));
|
|
2180
2259
|
await this.#db.all("VACUUM");
|
|
2181
2260
|
});
|
|
2182
|
-
const
|
|
2261
|
+
const purgesBefore = this.#purgeMarks;
|
|
2262
|
+
const checkpoint = await db.checkpoint();
|
|
2183
2263
|
// A reader in another connection (a runner, a backup) held the log back: the old frames are there until a
|
|
2184
|
-
// checkpoint is done, so the marker stays.
|
|
2185
|
-
|
|
2264
|
+
// checkpoint is done, so the marker stays. So does one a purge left after this checkpoint was asked: its frames may
|
|
2265
|
+
// be past it.
|
|
2266
|
+
if (checkpoint?.busy !== 0 || this.#purgeMarks !== purgesBefore)
|
|
2186
2267
|
return { rewritten, left: "busy" };
|
|
2187
2268
|
}
|
|
2188
2269
|
catch (error) {
|
|
@@ -2301,6 +2382,12 @@ class SqliteStore {
|
|
|
2301
2382
|
// never live until the next claim. A claim whose lease ran out releases nothing: the run, running with its lease run
|
|
2302
2383
|
// out, is claimable at once, never stuck.
|
|
2303
2384
|
`UPDATE runs SET epoch = epoch + 1, runner = NULL, claimed_until = NULL, wake_at = ?, backoff_until = ?, state = coalesce(?, state)${leaving ? `, left_running_at = ${now.sql}` : ""} WHERE ${fence.where} AND runner = ?`, [wakeAt, backoffUntil, state ?? null, ...(leaving ? now.params : []), ...fence.params, claim.runner]));
|
|
2385
|
+
// A release that leaves the run running is a hand-back (schema.ts HAND_BACKS): kept in this same write for the
|
|
2386
|
+
// capacity read, with the rows past HAND_BACKS_KEPT_MS removed. A park, or a release of a parked run, is none.
|
|
2387
|
+
if ((state ?? final?.state) === "running") {
|
|
2388
|
+
await tx.run(`DELETE FROM hand_backs WHERE at < ${now.sql} - ${this.#db.dialect.bigintParam}`, ...now.params, HAND_BACKS_KEPT_MS);
|
|
2389
|
+
await tx.run(`INSERT INTO hand_backs (run_id, runner, epoch, at) VALUES (?, ?, ?, ${now.sql})`, claim.runId, claim.runner, claim.epoch, ...now.params);
|
|
2390
|
+
}
|
|
2304
2391
|
}, { full: true });
|
|
2305
2392
|
// The released claim's journal is dead (its epoch moved on): the store keeps it no longer, and refuses it from now.
|
|
2306
2393
|
this.#journals.delete(journalKey(claim));
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type SchemaState } from "./postgres/migrate.js";
|
|
2
|
+
import { type StoreTarget } from "./open.js";
|
|
3
|
+
/** The line `agentrun-serve store-schema` prints. */
|
|
4
|
+
export interface StoreSchemaReport {
|
|
5
|
+
readonly store: StoreTarget["kind"];
|
|
6
|
+
/** Where the store is, in words: the SQLite file, or the Postgres schema (never its URL). */
|
|
7
|
+
readonly where: string;
|
|
8
|
+
readonly schema: number | null;
|
|
9
|
+
readonly runnerFloor: number | null;
|
|
10
|
+
readonly build: number;
|
|
11
|
+
readonly server: "sets up" | "opens" | "migrates" | "refuses";
|
|
12
|
+
readonly runner: "opens" | "waits" | "refused";
|
|
13
|
+
}
|
|
14
|
+
/** What a build that knows `build` does with a store at `state`, on `kind`. `earlier`: the data directory holds an earlier
|
|
15
|
+
* version's files (SQLite only), which this build's server refuses to start beside (StoreFromEarlierVersion). `awaits`:
|
|
16
|
+
* on SQLite at this build's version, a column this build's runner needs that the file lacks (SQLITE_RUNNER_NEEDS), which
|
|
17
|
+
* its server adds at its start: the runner waits for it, as openSqliteStore makes it. */
|
|
18
|
+
export declare function storeSchemaReport(target: StoreTarget, state: SchemaState, build: number, earlier?: boolean, awaits?: boolean): StoreSchemaReport;
|
|
19
|
+
/** How long the read waits on Postgres (ms): for a lock (a server migrating holds the ledger's), for its one statement, and
|
|
20
|
+
* for any answer at all (a database that took the connection and went silent). Past one, the read fails: exit 1. */
|
|
21
|
+
export declare const STORE_SCHEMA_LOCK_MS = 2000;
|
|
22
|
+
export declare const STORE_SCHEMA_STATEMENT_MS = 5000;
|
|
23
|
+
export declare const STORE_SCHEMA_ANSWER_MS = 6000;
|
|
24
|
+
/** Reads the store `dataDir` and `env` name (and the URL, this process's AGENTRUN_STORE_URL secret unless given). */
|
|
25
|
+
export declare function readStoreSchema(dataDir: string, env?: NodeJS.ProcessEnv, url?: string): Promise<StoreSchemaReport>;
|
|
26
|
+
/** The versions this build knows, read from its own files, with no store: `postgres`, its newest migration; `sqlite`,
|
|
27
|
+
* SCHEMA_VERSION. */
|
|
28
|
+
export declare const buildSchema: () => {
|
|
29
|
+
readonly postgres: number;
|
|
30
|
+
readonly sqlite: number;
|
|
31
|
+
};
|
|
32
|
+
/** `agentrun-serve store-schema [--data DIR]`, or `--build` (this build's versions, no store read): the exit code (the
|
|
33
|
+
* file's head). */
|
|
34
|
+
export declare function storeSchemaMain(argv: readonly string[], defaultDataDir: string, usage: string): Promise<number>;
|