spool-engine 0.0.0-stage → 0.2.0
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/LICENSE +202 -0
- package/README.md +12 -2
- package/dist/config.js +130 -0
- package/dist/config.js.map +1 -0
- package/dist/domain/errors.js +108 -0
- package/dist/domain/errors.js.map +1 -0
- package/dist/domain/journal.js +21 -0
- package/dist/domain/journal.js.map +1 -0
- package/dist/domain/json.js +55 -0
- package/dist/domain/json.js.map +1 -0
- package/dist/domain/llm.js +22 -0
- package/dist/domain/llm.js.map +1 -0
- package/dist/domain/retry.js +21 -0
- package/dist/domain/retry.js.map +1 -0
- package/dist/domain/run-status.js +40 -0
- package/dist/domain/run-status.js.map +1 -0
- package/dist/domain/sleep.js +7 -0
- package/dist/domain/sleep.js.map +1 -0
- package/dist/engine.js +131 -0
- package/dist/engine.js.map +1 -0
- package/dist/loops/every.js +32 -0
- package/dist/loops/every.js.map +1 -0
- package/dist/loops/listener.js +58 -0
- package/dist/loops/listener.js.map +1 -0
- package/dist/loops/live-runs.js +30 -0
- package/dist/loops/live-runs.js.map +1 -0
- package/dist/loops/queue-depth.js +28 -0
- package/dist/loops/queue-depth.js.map +1 -0
- package/dist/loops/reaper.js +71 -0
- package/dist/loops/reaper.js.map +1 -0
- package/dist/loops/waker.js +42 -0
- package/dist/loops/waker.js.map +1 -0
- package/dist/main.js +48 -0
- package/dist/main.js.map +1 -0
- package/dist/observability/logger.js +9 -0
- package/dist/observability/logger.js.map +1 -0
- package/dist/observability/metrics.js +97 -0
- package/dist/observability/metrics.js.map +1 -0
- package/dist/observability/tracing.js +146 -0
- package/dist/observability/tracing.js.map +1 -0
- package/dist/proto/limits_pb.d.ts +212 -0
- package/dist/proto/limits_pb.js +76 -0
- package/dist/proto/runs_pb.d.ts +740 -0
- package/dist/proto/runs_pb.js +147 -0
- package/dist/proto/workers_pb.d.ts +900 -0
- package/dist/proto/workers_pb.js +168 -0
- package/dist/services/admission.js +47 -0
- package/dist/services/admission.js.map +1 -0
- package/dist/services/cancel-run.js +43 -0
- package/dist/services/cancel-run.js.map +1 -0
- package/dist/services/claim-tasks.js +59 -0
- package/dist/services/claim-tasks.js.map +1 -0
- package/dist/services/complete-task.js +45 -0
- package/dist/services/complete-task.js.map +1 -0
- package/dist/services/fail-step.js +102 -0
- package/dist/services/fail-step.js.map +1 -0
- package/dist/services/group-commit.js +83 -0
- package/dist/services/group-commit.js.map +1 -0
- package/dist/services/live-tokens.js +90 -0
- package/dist/services/live-tokens.js.map +1 -0
- package/dist/services/next-step.js +33 -0
- package/dist/services/next-step.js.map +1 -0
- package/dist/services/notifier.js +54 -0
- package/dist/services/notifier.js.map +1 -0
- package/dist/services/query-runs.js +14 -0
- package/dist/services/query-runs.js.map +1 -0
- package/dist/services/replay-run.js +63 -0
- package/dist/services/replay-run.js.map +1 -0
- package/dist/services/report-step.js +129 -0
- package/dist/services/report-step.js.map +1 -0
- package/dist/services/run-watches.js +46 -0
- package/dist/services/run-watches.js.map +1 -0
- package/dist/services/send-event.js +16 -0
- package/dist/services/send-event.js.map +1 -0
- package/dist/services/sleep-run.js +47 -0
- package/dist/services/sleep-run.js.map +1 -0
- package/dist/services/throttle-step.js +76 -0
- package/dist/services/throttle-step.js.map +1 -0
- package/dist/services/trigger-run.js +38 -0
- package/dist/services/trigger-run.js.map +1 -0
- package/dist/services/wait-for-event.js +73 -0
- package/dist/services/wait-for-event.js.map +1 -0
- package/dist/services/wakeups.js +70 -0
- package/dist/services/wakeups.js.map +1 -0
- package/dist/services/watch-run.js +36 -0
- package/dist/services/watch-run.js.map +1 -0
- package/dist/services/worker-session.js +198 -0
- package/dist/services/worker-session.js.map +1 -0
- package/dist/store/errors.js +42 -0
- package/dist/store/errors.js.map +1 -0
- package/dist/store/events.js +96 -0
- package/dist/store/events.js.map +1 -0
- package/dist/store/idempotency.js +29 -0
- package/dist/store/idempotency.js.map +1 -0
- package/dist/store/json.js +9 -0
- package/dist/store/json.js.map +1 -0
- package/dist/store/limits.js +60 -0
- package/dist/store/limits.js.map +1 -0
- package/dist/store/migrate.js +20 -0
- package/dist/store/migrate.js.map +1 -0
- package/dist/store/run-views.js +96 -0
- package/dist/store/run-views.js.map +1 -0
- package/dist/store/runs.js +104 -0
- package/dist/store/runs.js.map +1 -0
- package/dist/store/schema.js +191 -0
- package/dist/store/schema.js.map +1 -0
- package/dist/store/steps.js +114 -0
- package/dist/store/steps.js.map +1 -0
- package/dist/store/tasks.js +463 -0
- package/dist/store/tasks.js.map +1 -0
- package/dist/store/transaction.js +23 -0
- package/dist/store/transaction.js.map +1 -0
- package/dist/store/waits.js +75 -0
- package/dist/store/waits.js.map +1 -0
- package/dist/store/watches.js +31 -0
- package/dist/store/watches.js.map +1 -0
- package/dist/transport/auth.js +26 -0
- package/dist/transport/auth.js.map +1 -0
- package/dist/transport/channel.js +46 -0
- package/dist/transport/channel.js.map +1 -0
- package/dist/transport/errors.js +74 -0
- package/dist/transport/errors.js.map +1 -0
- package/dist/transport/limits-service.js +60 -0
- package/dist/transport/limits-service.js.map +1 -0
- package/dist/transport/protocol.js +14 -0
- package/dist/transport/protocol.js.map +1 -0
- package/dist/transport/run-events.js +133 -0
- package/dist/transport/run-events.js.map +1 -0
- package/dist/transport/run-messages.js +78 -0
- package/dist/transport/run-messages.js.map +1 -0
- package/dist/transport/run-service.js +147 -0
- package/dist/transport/run-service.js.map +1 -0
- package/dist/transport/server.js +227 -0
- package/dist/transport/server.js.map +1 -0
- package/dist/transport/validation.js +61 -0
- package/dist/transport/validation.js.map +1 -0
- package/dist/transport/worker-service.js +396 -0
- package/dist/transport/worker-service.js.map +1 -0
- package/drizzle/0000_init.sql +95 -0
- package/drizzle/0001_tasks_storage.sql +2 -0
- package/drizzle/0002_waits_route.sql +3 -0
- package/drizzle/0003_event_waits.sql +8 -0
- package/drizzle/0004_llm_steps.sql +2 -0
- package/drizzle/0005_tasks_notify.sql +19 -0
- package/drizzle/0006_drop_tasks_notify.sql +8 -0
- package/drizzle/0007_tasks_fair.sql +5 -0
- package/drizzle/0008_concurrency_limits.sql +8 -0
- package/drizzle/0009_rate_limits.sql +12 -0
- package/drizzle/0010_run_listings.sql +2 -0
- package/drizzle/0011_run_replays.sql +7 -0
- package/drizzle/0012_run_watches.sql +8 -0
- package/drizzle/meta/0000_snapshot.json +668 -0
- package/drizzle/meta/0001_snapshot.json +668 -0
- package/drizzle/meta/0002_snapshot.json +680 -0
- package/drizzle/meta/0003_snapshot.json +723 -0
- package/drizzle/meta/0004_snapshot.json +733 -0
- package/drizzle/meta/0005_snapshot.json +733 -0
- package/drizzle/meta/0006_snapshot.json +733 -0
- package/drizzle/meta/0007_snapshot.json +739 -0
- package/drizzle/meta/0008_snapshot.json +791 -0
- package/drizzle/meta/0009_snapshot.json +843 -0
- package/drizzle/meta/0010_snapshot.json +881 -0
- package/drizzle/meta/0011_snapshot.json +903 -0
- package/drizzle/meta/0012_snapshot.json +958 -0
- package/drizzle/meta/_journal.json +97 -0
- package/package.json +58 -3
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sets the most runs with `key` that may run at once (F10), replacing any earlier limit.
|
|
3
|
+
* Applies to claims that start after it commits; runs already running are not stopped, so
|
|
4
|
+
* a lowered limit takes effect as they finish.
|
|
5
|
+
*/
|
|
6
|
+
export async function setConcurrencyLimit(sql, key, maxRunning) {
|
|
7
|
+
await sql `
|
|
8
|
+
INSERT INTO concurrency_slots (key, max_running) VALUES (${key}, ${maxRunning})
|
|
9
|
+
ON CONFLICT (key) DO UPDATE SET max_running = excluded.max_running`;
|
|
10
|
+
}
|
|
11
|
+
/** Removes a key's limit; returns false when it had none. */
|
|
12
|
+
export async function deleteConcurrencyLimit(sql, key) {
|
|
13
|
+
const rows = await sql `DELETE FROM concurrency_slots WHERE key = ${key}`;
|
|
14
|
+
return rows.count === 1;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Sets a key's token bucket (F11): `capacity` tokens at most, refilled at `refillPerSec`. A
|
|
18
|
+
* new bucket starts full; a changed one keeps its tokens, at most the new capacity, so
|
|
19
|
+
* reservations already made still count.
|
|
20
|
+
*/
|
|
21
|
+
export async function setRateLimit(sql, key, capacity, refillPerSec) {
|
|
22
|
+
await sql `
|
|
23
|
+
INSERT INTO rate_buckets (key, capacity, refill_per_sec, tokens, updated_at)
|
|
24
|
+
VALUES (${key}, ${capacity}, ${refillPerSec}, ${capacity}, now())
|
|
25
|
+
ON CONFLICT (key) DO UPDATE
|
|
26
|
+
SET capacity = excluded.capacity,
|
|
27
|
+
refill_per_sec = excluded.refill_per_sec,
|
|
28
|
+
tokens = least(rate_buckets.tokens, excluded.capacity)`;
|
|
29
|
+
}
|
|
30
|
+
/** Removes a key's bucket; returns false when it had none. */
|
|
31
|
+
export async function deleteRateLimit(sql, key) {
|
|
32
|
+
const rows = await sql `DELETE FROM rate_buckets WHERE key = ${key}`;
|
|
33
|
+
return rows.count === 1;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Takes `cost` tokens from a key's bucket and returns how long, in milliseconds, until
|
|
37
|
+
* they are due: 0 when the bucket had them. The bucket first refills for the time since
|
|
38
|
+
* it was last used, then may go below zero; that deficit is a reservation, and the
|
|
39
|
+
* returned wait is how long the refill takes to cover it, so callers that must wait are
|
|
40
|
+
* given distinct times in the order they asked. A key without a bucket is not
|
|
41
|
+
* limited. The row lock serialises takers of one key until the caller's transaction ends.
|
|
42
|
+
*
|
|
43
|
+
* Elapsed time never counts below zero: a transaction that began earlier but takes its
|
|
44
|
+
* token later must not roll the bucket's clock back.
|
|
45
|
+
*
|
|
46
|
+
* Plan: primary-key lookup on rate_buckets.
|
|
47
|
+
*/
|
|
48
|
+
export async function takeTokens(sql, key, cost) {
|
|
49
|
+
const [row] = await sql `
|
|
50
|
+
UPDATE rate_buckets
|
|
51
|
+
SET tokens = least(capacity::numeric,
|
|
52
|
+
tokens + refill_per_sec * greatest(0, extract(epoch FROM now() - updated_at)))
|
|
53
|
+
- ${cost},
|
|
54
|
+
updated_at = greatest(updated_at, now())
|
|
55
|
+
WHERE key = ${key}
|
|
56
|
+
RETURNING CASE WHEN tokens >= 0 THEN 0
|
|
57
|
+
ELSE ceil(-tokens / refill_per_sec * 1000) END::float8 AS "waitMs"`;
|
|
58
|
+
return row?.waitMs ?? 0;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=limits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"limits.js","sourceRoot":"","sources":["../../src/store/limits.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,GAAc,EACd,GAAW,EACX,UAAkB;IAElB,MAAM,GAAG,CAAA;+DACoD,GAAG,KAAK,UAAU;uEACV,CAAC;AACxE,CAAC;AAED,6DAA6D;AAC7D,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,GAAc,EAAE,GAAW;IACtE,MAAM,IAAI,GAAG,MAAM,GAAG,CAAA,6CAA6C,GAAG,EAAE,CAAC;IACzE,OAAO,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC;AAC1B,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,GAAc,EACd,GAAW,EACX,QAAgB,EAChB,YAAoB;IAEpB,MAAM,GAAG,CAAA;;cAEG,GAAG,KAAK,QAAQ,KAAK,YAAY,KAAK,QAAQ;;;;+DAIG,CAAC;AAChE,CAAC;AAED,8DAA8D;AAC9D,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,GAAc,EAAE,GAAW;IAC/D,MAAM,IAAI,GAAG,MAAM,GAAG,CAAA,wCAAwC,GAAG,EAAE,CAAC;IACpE,OAAO,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC;AAC1B,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,GAAc,EAAE,GAAW,EAAE,IAAY;IACxE,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,GAAG,CAAsB;;;;qBAI1B,IAAI;;kBAEP,GAAG;;sFAEiE,CAAC;IACrF,OAAO,GAAG,EAAE,MAAM,IAAI,CAAC,CAAC;AAC1B,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
2
|
+
import { drizzle } from "drizzle-orm/postgres-js";
|
|
3
|
+
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
|
4
|
+
import postgres from "postgres";
|
|
5
|
+
const migrationsFolder = fileURLToPath(new URL("../../drizzle", import.meta.url));
|
|
6
|
+
/** Arbitrary but fixed: every engine must contend for the same advisory lock. */
|
|
7
|
+
const MIGRATION_LOCK_ID = 7_365_001;
|
|
8
|
+
export async function applyMigrations(databaseUrl) {
|
|
9
|
+
const sql = postgres(databaseUrl, { max: 1, onnotice: () => undefined });
|
|
10
|
+
try {
|
|
11
|
+
// Engines may start together. A session lock on this single connection makes them take
|
|
12
|
+
// turns, and Postgres releases it when the connection closes, even after a crash.
|
|
13
|
+
await sql `SELECT pg_advisory_lock(${MIGRATION_LOCK_ID})`;
|
|
14
|
+
await migrate(drizzle(sql), { migrationsFolder });
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
await sql.end();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=migrate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate.js","sourceRoot":"","sources":["../../src/store/migrate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAC3D,OAAO,QAAQ,MAAM,UAAU,CAAC;AAEhC,MAAM,gBAAgB,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,eAAe,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAElF,iFAAiF;AACjF,MAAM,iBAAiB,GAAG,SAAS,CAAC;AAEpC,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,WAAmB;IACvD,MAAM,GAAG,GAAG,QAAQ,CAAC,WAAW,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,SAAS,EAAE,CAAC,CAAC;IACzE,IAAI,CAAC;QACH,uFAAuF;QACvF,kFAAkF;QAClF,MAAM,GAAG,CAAA,2BAA2B,iBAAiB,GAAG,CAAC;QACzD,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,gBAAgB,EAAE,CAAC,CAAC;IACpD,CAAC;YAAS,CAAC;QACT,MAAM,GAAG,CAAC,GAAG,EAAE,CAAC;IAClB,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** The most runs one page of a listing returns. */
|
|
2
|
+
export const MAX_RUNS_PAGE = 200;
|
|
3
|
+
/**
|
|
4
|
+
* Runs matching `filter`, newest first, a page at a time. Run ids are UUIDv7, so id order
|
|
5
|
+
* is creation order and a page continues from the last id of the one before, which stays
|
|
6
|
+
* correct while new runs arrive (keyset paging, never OFFSET).
|
|
7
|
+
*
|
|
8
|
+
* Each filter is added only when given, so every combination is planned for what it
|
|
9
|
+
* asks. Plans: with a tenant, an Index Scan on runs_tenant (tenant_id, id DESC); for
|
|
10
|
+
* failed runs, on the partial runs_failed (error IS NOT NULL), which holds only failed
|
|
11
|
+
* runs; otherwise a backward Index Scan on runs_pkey, the other filters checked per row
|
|
12
|
+
* and stopping at the page size.
|
|
13
|
+
*/
|
|
14
|
+
export async function listRuns(sql, filter) {
|
|
15
|
+
if (!Number.isInteger(filter.limit) || filter.limit < 1 || filter.limit > MAX_RUNS_PAGE) {
|
|
16
|
+
throw new RangeError(`limit must be an integer from 1 to ${String(MAX_RUNS_PAGE)}`);
|
|
17
|
+
}
|
|
18
|
+
const empty = sql ``;
|
|
19
|
+
const rows = await sql `
|
|
20
|
+
SELECT id, tenant_id AS "tenantId", workflow, status, created_at AS "createdAt",
|
|
21
|
+
updated_at AS "updatedAt", idempotency_key AS "idempotencyKey",
|
|
22
|
+
concurrency_key AS "concurrencyKey", queue, replay_of AS "replayOf",
|
|
23
|
+
replay_from AS "replayFrom"
|
|
24
|
+
FROM runs
|
|
25
|
+
WHERE true
|
|
26
|
+
${filter.tenantId === undefined ? empty : sql `AND tenant_id = ${filter.tenantId}`}
|
|
27
|
+
${filter.workflow === undefined ? empty : sql `AND workflow = ${filter.workflow}`}
|
|
28
|
+
${filter.status === undefined ? empty : sql `AND status = ${filter.status}`}
|
|
29
|
+
${filter.status === "failed" ? sql `AND error IS NOT NULL` : empty}
|
|
30
|
+
${filter.before === undefined ? empty : sql `AND id < ${filter.before}::uuid`}
|
|
31
|
+
ORDER BY id DESC
|
|
32
|
+
LIMIT ${filter.limit + 1}`;
|
|
33
|
+
return { runs: rows.slice(0, filter.limit), more: rows.length > filter.limit };
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* One run with its journal, failed attempts, and its task or wait, or undefined when no
|
|
37
|
+
* such run exists. One statement, so every part comes from the same snapshot: a step
|
|
38
|
+
* recorded meanwhile is either in the journal with the task that follows it, or neither.
|
|
39
|
+
* Timestamps inside the parts come back as ISO strings from json_build_object.
|
|
40
|
+
*
|
|
41
|
+
* Plan: a primary-key lookup on runs, then on steps, step_attempts, tasks (run_id unique)
|
|
42
|
+
* and waits by run id.
|
|
43
|
+
*/
|
|
44
|
+
export async function getRunDetail(sql, runId) {
|
|
45
|
+
const [row] = await sql `
|
|
46
|
+
SELECT r.id, r.tenant_id AS "tenantId", r.workflow, r.status, r.created_at AS "createdAt",
|
|
47
|
+
r.updated_at AS "updatedAt", r.idempotency_key AS "idempotencyKey",
|
|
48
|
+
r.concurrency_key AS "concurrencyKey", r.queue, r.replay_of AS "replayOf",
|
|
49
|
+
r.replay_from AS "replayFrom", r.input, r.output, r.error,
|
|
50
|
+
coalesce((
|
|
51
|
+
SELECT json_agg(json_build_object(
|
|
52
|
+
'seq', s.seq, 'name', s.name, 'kind', s.kind, 'output', s.output,
|
|
53
|
+
'attempts', s.attempts, 'startedAt', s.started_at,
|
|
54
|
+
'finishedAt', s.finished_at, 'model', s.model, 'tokensIn', s.tokens_in,
|
|
55
|
+
'tokensOut', s.tokens_out, 'costUsd', s.cost_usd::float8)
|
|
56
|
+
ORDER BY s.seq)
|
|
57
|
+
FROM steps s WHERE s.run_id = r.id), '[]'::json) AS steps,
|
|
58
|
+
coalesce((
|
|
59
|
+
SELECT json_agg(json_build_object(
|
|
60
|
+
'seq', a.seq, 'failure', a.failure, 'error', a.error,
|
|
61
|
+
'startedAt', a.started_at, 'finishedAt', a.finished_at)
|
|
62
|
+
ORDER BY a.seq, a.failure)
|
|
63
|
+
FROM step_attempts a WHERE a.run_id = r.id), '[]'::json) AS attempts,
|
|
64
|
+
(SELECT json_build_object(
|
|
65
|
+
'queue', t.queue, 'runAfter', t.run_after, 'attempt', t.attempt,
|
|
66
|
+
'stepFailures', t.step_failures,
|
|
67
|
+
'leaseExpiresAt', CASE WHEN t.lease_owner IS NOT NULL
|
|
68
|
+
THEN t.lease_expires_at END)
|
|
69
|
+
FROM tasks t WHERE t.run_id = r.id) AS task,
|
|
70
|
+
(SELECT json_build_object('kind', w.kind, 'wakeAt', w.wake_at,
|
|
71
|
+
'eventName', w.event_name)
|
|
72
|
+
FROM waits w WHERE w.run_id = r.id) AS wait
|
|
73
|
+
FROM runs r
|
|
74
|
+
WHERE r.id = ${runId}::uuid`;
|
|
75
|
+
return row;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A short text that changes whenever anything GetRun shows about the run changes: its
|
|
79
|
+
* status, a step recorded, an attempt failed, a claim, a backoff, a sleep or a wait. Cheap
|
|
80
|
+
* enough to poll per watcher; undefined when there is no such run.
|
|
81
|
+
*
|
|
82
|
+
* Plan: primary-key lookups on runs, tasks (run_id unique) and waits, and index-only
|
|
83
|
+
* counts on the steps and step_attempts primary keys.
|
|
84
|
+
*/
|
|
85
|
+
export async function runFingerprint(sql, runId) {
|
|
86
|
+
const [row] = await sql `
|
|
87
|
+
SELECT concat_ws('|', r.status, r.updated_at,
|
|
88
|
+
(SELECT count(*) FROM steps WHERE run_id = r.id),
|
|
89
|
+
(SELECT count(*) FROM step_attempts WHERE run_id = r.id),
|
|
90
|
+
(SELECT concat_ws(',', t.attempt, t.run_after, t.lease_owner IS NOT NULL)
|
|
91
|
+
FROM tasks t WHERE t.run_id = r.id),
|
|
92
|
+
(SELECT w.wake_at FROM waits w WHERE w.run_id = r.id)) AS fingerprint
|
|
93
|
+
FROM runs r WHERE r.id = ${runId}::uuid`;
|
|
94
|
+
return row?.fingerprint;
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=run-views.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-views.js","sourceRoot":"","sources":["../../src/store/run-views.ts"],"names":[],"mappings":"AAIA,mDAAmD;AACnD,MAAM,CAAC,MAAM,aAAa,GAAG,GAAG,CAAC;AA+BjC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,GAAc,EAAE,MAAiB;IAC9D,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,GAAG,CAAC,IAAI,MAAM,CAAC,KAAK,GAAG,aAAa,EAAE,CAAC;QACxF,MAAM,IAAI,UAAU,CAAC,sCAAsC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;IACtF,CAAC;IACD,MAAM,KAAK,GAAG,GAAG,CAAA,EAAE,CAAC;IACpB,MAAM,IAAI,GAAG,MAAM,GAAG,CAAiB;;;;;;;QAOjC,MAAM,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,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+1,104 @@
|
|
|
1
|
+
import { statusesThatCanBecome } from "../domain/run-status.js";
|
|
2
|
+
import { jsonb } from "./json.js";
|
|
3
|
+
export async function insertRun(tx, run) {
|
|
4
|
+
const [row] = await tx `
|
|
5
|
+
INSERT INTO runs (id, tenant_id, workflow, status, input, idempotency_key, concurrency_key,
|
|
6
|
+
queue, replay_of, replay_from)
|
|
7
|
+
VALUES (coalesce(${run.id ?? null}::uuid, uuidv7()), ${run.tenantId}, ${run.workflow},
|
|
8
|
+
'queued', ${jsonb(run.input)}::text::jsonb, ${run.idempotencyKey ?? null},
|
|
9
|
+
${run.concurrencyKey ?? null}, ${run.queue}, ${run.replay?.of ?? null}::uuid,
|
|
10
|
+
${run.replay?.from ?? null}::int)
|
|
11
|
+
RETURNING id`;
|
|
12
|
+
if (row === undefined)
|
|
13
|
+
throw new Error("INSERT ... RETURNING returned no row");
|
|
14
|
+
return row.id;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Inputs of the given runs, keyed by run id. Inputs never change after a trigger, so this
|
|
18
|
+
* read needs no transaction with the claim that preceded it.
|
|
19
|
+
*
|
|
20
|
+
* Plan: primary-key lookups on runs_pkey.
|
|
21
|
+
*/
|
|
22
|
+
export async function loadRunInputs(sql, runIds) {
|
|
23
|
+
if (runIds.length === 0)
|
|
24
|
+
return new Map();
|
|
25
|
+
const rows = await sql `
|
|
26
|
+
SELECT id, input FROM runs WHERE id = ANY(${[...runIds]}::uuid[])`;
|
|
27
|
+
return new Map(rows.map((row) => [row.id, row.input]));
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Marks a run succeeded with its output. Returns false, changing nothing, when the run's
|
|
31
|
+
* status does not allow it (domain/run-status.ts), so the database enforces the same
|
|
32
|
+
* transitions as the code.
|
|
33
|
+
*/
|
|
34
|
+
export async function succeedRun(tx, runId, output) {
|
|
35
|
+
const rows = await tx `
|
|
36
|
+
UPDATE runs
|
|
37
|
+
SET status = 'succeeded', output = ${jsonb(output)}::text::jsonb, updated_at = now()
|
|
38
|
+
WHERE id = ${runId} AND status = ANY(${statusesThatCanBecome("succeeded")}::text[])`;
|
|
39
|
+
return rows.count === 1;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Marks a run cancelled. Returns false, changing nothing, when the run's status does not
|
|
43
|
+
* allow it (it finished) or there is no such run.
|
|
44
|
+
*/
|
|
45
|
+
export async function cancelRun(tx, runId) {
|
|
46
|
+
const rows = await tx `
|
|
47
|
+
UPDATE runs SET status = 'cancelled', updated_at = now()
|
|
48
|
+
WHERE id = ${runId} AND status = ANY(${statusesThatCanBecome("cancelled")}::text[])`;
|
|
49
|
+
return rows.count === 1;
|
|
50
|
+
}
|
|
51
|
+
/** What a replay of a run starts from. Plan: primary-key lookups on runs and steps. */
|
|
52
|
+
export async function replaySource(tx, runId) {
|
|
53
|
+
const [row] = await tx `
|
|
54
|
+
SELECT tenant_id AS "tenantId", workflow, status, input,
|
|
55
|
+
concurrency_key AS "concurrencyKey", queue,
|
|
56
|
+
(SELECT count(*)::int FROM steps WHERE run_id = r.id) AS steps
|
|
57
|
+
FROM runs r WHERE id = ${runId}`;
|
|
58
|
+
return row;
|
|
59
|
+
}
|
|
60
|
+
/** A run's status, or undefined when there is no such run. */
|
|
61
|
+
export async function runStatus(tx, runId) {
|
|
62
|
+
const [row] = await tx `SELECT status FROM runs WHERE id = ${runId}`;
|
|
63
|
+
return row?.status;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Marks a run failed with a description of why: the dead-letter state. Returns false,
|
|
67
|
+
* changing nothing, when the run's status does not allow it.
|
|
68
|
+
*/
|
|
69
|
+
export async function failRun(tx, runId, error) {
|
|
70
|
+
const rows = await tx `
|
|
71
|
+
UPDATE runs
|
|
72
|
+
SET status = 'failed', error = ${jsonb(error)}::text::jsonb, updated_at = now()
|
|
73
|
+
WHERE id = ${runId} AND status = ANY(${statusesThatCanBecome("failed")}::text[])`;
|
|
74
|
+
return rows.count === 1;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Moves a run to running when its first step is recorded. Writes nothing once it is
|
|
78
|
+
* already running, so later steps add no write to runs.
|
|
79
|
+
*/
|
|
80
|
+
export async function markRunRunning(tx, runId) {
|
|
81
|
+
await tx `
|
|
82
|
+
UPDATE runs SET status = 'running', updated_at = now()
|
|
83
|
+
WHERE id = ${runId} AND status = ANY(${statusesThatCanBecome("running")}::text[])`;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Parks a run that has just started a sleep or a wait. Returns false, changing nothing,
|
|
87
|
+
* when the run's status does not allow it.
|
|
88
|
+
*/
|
|
89
|
+
export async function markRunParked(tx, runId, status) {
|
|
90
|
+
const rows = await tx `
|
|
91
|
+
UPDATE runs SET status = ${status}, updated_at = now()
|
|
92
|
+
WHERE id = ${runId} AND status = ANY(${statusesThatCanBecome(status)}::text[])`;
|
|
93
|
+
return rows.count === 1;
|
|
94
|
+
}
|
|
95
|
+
/** The batch form of markRunRunning: one statement for the runs that recorded a step. */
|
|
96
|
+
export async function markRunsRunning(tx, runIds) {
|
|
97
|
+
if (runIds.length === 0)
|
|
98
|
+
return;
|
|
99
|
+
await tx `
|
|
100
|
+
UPDATE runs SET status = 'running', updated_at = now()
|
|
101
|
+
WHERE id = ANY(${[...runIds]}::uuid[])
|
|
102
|
+
AND status = ANY(${statusesThatCanBecome("running")}::text[])`;
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=runs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runs.js","sourceRoot":"","sources":["../../src/store/runs.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAkB,MAAM,yBAAyB,CAAC;AAChF,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAgBlC,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,EAAa,EAAE,GAAW;IACxD,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE,CAA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;IAClF,OAAO,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC;AAC1B,CAAC;AAED,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,EAAa,EAAE,MAAyB;IAC5E,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAChC,MAAM,EAAE,CAAA;;qBAEW,CAAC,GAAG,MAAM,CAAC;yBACP,qBAAqB,CAAC,SAAS,CAAC,WAAW,CAAC;AACrE,CAAC"}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { bigint, check, customType, index, integer, jsonb, numeric, pgTable, primaryKey, smallint, text, timestamp, uuid, } from "drizzle-orm/pg-core";
|
|
3
|
+
const bytea = customType({ dataType: () => "bytea" });
|
|
4
|
+
const instant = (name) => timestamp(name, { withTimezone: true });
|
|
5
|
+
/** One row per workflow execution. */
|
|
6
|
+
export const runs = pgTable("runs", {
|
|
7
|
+
id: uuid("id").primaryKey(),
|
|
8
|
+
tenantId: text("tenant_id").notNull(),
|
|
9
|
+
workflow: text("workflow").notNull(),
|
|
10
|
+
status: text("status").notNull(),
|
|
11
|
+
input: jsonb("input").notNull(),
|
|
12
|
+
output: jsonb("output"),
|
|
13
|
+
error: jsonb("error"),
|
|
14
|
+
idempotencyKey: text("idempotency_key"),
|
|
15
|
+
/**
|
|
16
|
+
* Limits how many runs with this key run at once (F10); kept on the run so a woken
|
|
17
|
+
* run's task gets it again.
|
|
18
|
+
*/
|
|
19
|
+
concurrencyKey: text("concurrency_key"),
|
|
20
|
+
/** The queue the run was triggered on; null for runs from before it was kept. */
|
|
21
|
+
queue: text("queue"),
|
|
22
|
+
/** For a replay (F14): the run it copied its first steps from, and from which seq. */
|
|
23
|
+
replayOf: uuid("replay_of"),
|
|
24
|
+
replayFrom: integer("replay_from"),
|
|
25
|
+
createdAt: instant("created_at").notNull().defaultNow(),
|
|
26
|
+
updatedAt: instant("updated_at").notNull().defaultNow(),
|
|
27
|
+
}, (t) => [
|
|
28
|
+
check("runs_replay_check", sql `(${t.replayOf} IS NULL) = (${t.replayFrom} IS NULL)`),
|
|
29
|
+
check("runs_status_check", sql `${t.status} IN ('queued','running','sleeping','waiting','succeeded','failed','cancelled')`),
|
|
30
|
+
// Run listings, newest first (ids are UUIDv7). Neither index covers status, whose
|
|
31
|
+
// changes stay HOT updates: tenant_id never changes, and error is set only when a run
|
|
32
|
+
// fails, so the partial index is the dead-letter view without indexing status.
|
|
33
|
+
index("runs_tenant").on(t.tenantId, t.id.desc().nullsFirst()),
|
|
34
|
+
index("runs_failed")
|
|
35
|
+
.on(t.id.desc().nullsFirst())
|
|
36
|
+
.where(sql `${t.error} IS NOT NULL`),
|
|
37
|
+
]);
|
|
38
|
+
/** Separate from runs so uniqueness survives partitioning runs later. */
|
|
39
|
+
export const idempotencyKeys = pgTable("idempotency_keys", {
|
|
40
|
+
tenantId: text("tenant_id").notNull(),
|
|
41
|
+
workflow: text("workflow").notNull(),
|
|
42
|
+
key: text("key").notNull(),
|
|
43
|
+
runId: uuid("run_id").notNull(),
|
|
44
|
+
inputHash: bytea("input_hash").notNull(),
|
|
45
|
+
}, (t) => [primaryKey({ columns: [t.tenantId, t.workflow, t.key] })]);
|
|
46
|
+
/** The final result of each step. Replay reads this. */
|
|
47
|
+
export const steps = pgTable("steps", {
|
|
48
|
+
runId: uuid("run_id").notNull(),
|
|
49
|
+
seq: integer("seq").notNull(),
|
|
50
|
+
name: text("name").notNull(),
|
|
51
|
+
kind: text("kind").notNull(),
|
|
52
|
+
status: text("status").notNull(),
|
|
53
|
+
output: jsonb("output"),
|
|
54
|
+
error: jsonb("error"),
|
|
55
|
+
attempts: integer("attempts").notNull().default(1),
|
|
56
|
+
/** For kind llm: the model, as the provider names it. */
|
|
57
|
+
model: text("model"),
|
|
58
|
+
tokensIn: integer("tokens_in"),
|
|
59
|
+
tokensOut: integer("tokens_out"),
|
|
60
|
+
costUsd: numeric("cost_usd", { precision: 12, scale: 6 }),
|
|
61
|
+
startedAt: instant("started_at").notNull(),
|
|
62
|
+
finishedAt: instant("finished_at"),
|
|
63
|
+
}, (t) => [
|
|
64
|
+
primaryKey({ columns: [t.runId, t.seq] }),
|
|
65
|
+
// 'rate': a token taken from a rate limit's bucket before a step (F11).
|
|
66
|
+
check("steps_kind_check", sql `${t.kind} IN ('run','sleep','wait_event','llm','rate')`),
|
|
67
|
+
check("steps_status_check", sql `${t.status} IN ('succeeded','failed')`),
|
|
68
|
+
check("steps_llm_check", sql `(${t.kind} = 'llm') = (${t.model} IS NOT NULL) AND (${t.model} IS NULL) = (${t.tokensIn} IS NULL) AND (${t.model} IS NULL) = (${t.tokensOut} IS NULL)`),
|
|
69
|
+
]);
|
|
70
|
+
/** Append-only history of failed attempts. */
|
|
71
|
+
export const stepAttempts = pgTable("step_attempts", {
|
|
72
|
+
runId: uuid("run_id").notNull(),
|
|
73
|
+
seq: integer("seq").notNull(),
|
|
74
|
+
failure: integer("failure").notNull(),
|
|
75
|
+
error: jsonb("error").notNull(),
|
|
76
|
+
startedAt: instant("started_at").notNull(),
|
|
77
|
+
finishedAt: instant("finished_at").notNull(),
|
|
78
|
+
}, (t) => [primaryKey({ columns: [t.runId, t.seq, t.failure] })]);
|
|
79
|
+
/**
|
|
80
|
+
* Hot dispatch queue: at most one row per runnable or leased run.
|
|
81
|
+
* Storage parameters are set in a custom migration; Drizzle cannot express them.
|
|
82
|
+
*/
|
|
83
|
+
export const tasks = pgTable("tasks", {
|
|
84
|
+
id: bigint("id", { mode: "bigint" }).primaryKey().generatedAlwaysAsIdentity(),
|
|
85
|
+
runId: uuid("run_id").notNull().unique(),
|
|
86
|
+
queue: text("queue").notNull(),
|
|
87
|
+
tenantId: text("tenant_id").notNull(),
|
|
88
|
+
workflow: text("workflow").notNull(),
|
|
89
|
+
concurrencyKey: text("concurrency_key"),
|
|
90
|
+
priority: smallint("priority").notNull().default(0),
|
|
91
|
+
runAfter: instant("run_after").notNull().defaultNow(),
|
|
92
|
+
/** Fencing token: incremented by every claim and used for nothing else. */
|
|
93
|
+
attempt: integer("attempt").notNull().default(0),
|
|
94
|
+
stepFailures: integer("step_failures").notNull().default(0),
|
|
95
|
+
leaseExpiries: integer("lease_expiries").notNull().default(0),
|
|
96
|
+
leaseOwner: text("lease_owner"),
|
|
97
|
+
leaseExpiresAt: instant("lease_expires_at"),
|
|
98
|
+
}, (t) => [
|
|
99
|
+
// The claim takes turns across tenants: it steps from tenant to tenant on this
|
|
100
|
+
// index, then reads each tenant's runnable tasks in priority and age order.
|
|
101
|
+
index("tasks_fair")
|
|
102
|
+
.on(t.queue, t.tenantId, t.priority.desc().nullsFirst(), t.runAfter)
|
|
103
|
+
.where(sql `${t.leaseOwner} IS NULL`),
|
|
104
|
+
index("tasks_leases")
|
|
105
|
+
.on(t.leaseExpiresAt)
|
|
106
|
+
.where(sql `${t.leaseOwner} IS NOT NULL`),
|
|
107
|
+
// Counts a key's running runs, which are its leased tasks.
|
|
108
|
+
index("tasks_running_keys")
|
|
109
|
+
.on(t.concurrencyKey)
|
|
110
|
+
.where(sql `${t.leaseOwner} IS NOT NULL AND ${t.concurrencyKey} IS NOT NULL`),
|
|
111
|
+
check("tasks_lease_check", sql `(${t.leaseOwner} IS NULL) = (${t.leaseExpiresAt} IS NULL)`),
|
|
112
|
+
]);
|
|
113
|
+
/**
|
|
114
|
+
* Runs parked on a sleep or an event. wake_at is the wake time or the event timeout. A
|
|
115
|
+
* parked run has no task, so the wait keeps where its task goes when it wakes.
|
|
116
|
+
*/
|
|
117
|
+
export const waits = pgTable("waits", {
|
|
118
|
+
runId: uuid("run_id").primaryKey(),
|
|
119
|
+
seq: integer("seq").notNull(),
|
|
120
|
+
tenantId: text("tenant_id").notNull(),
|
|
121
|
+
queue: text("queue").notNull(),
|
|
122
|
+
workflow: text("workflow").notNull(),
|
|
123
|
+
/** The journal name an event wait is recorded under when it ends. */
|
|
124
|
+
stepName: text("step_name"),
|
|
125
|
+
kind: text("kind").notNull(),
|
|
126
|
+
wakeAt: instant("wake_at").notNull(),
|
|
127
|
+
eventName: text("event_name"),
|
|
128
|
+
match: jsonb("match"),
|
|
129
|
+
}, (t) => [
|
|
130
|
+
index("waits_wake").on(t.wakeAt),
|
|
131
|
+
index("waits_event")
|
|
132
|
+
.on(t.tenantId, t.eventName)
|
|
133
|
+
.where(sql `${t.kind} = 'event'`),
|
|
134
|
+
check("waits_kind_check", sql `${t.kind} IN ('sleep','event')`),
|
|
135
|
+
check("waits_event_check", sql `(${t.kind} = 'event') = (${t.eventName} IS NOT NULL) AND (${t.eventName} IS NULL) = (${t.match} IS NULL)`),
|
|
136
|
+
check("waits_step_name_check", sql `(${t.kind} = 'event') = (${t.stepName} IS NOT NULL)`),
|
|
137
|
+
]);
|
|
138
|
+
/** Received events, kept so one that arrives before its wait is not lost. */
|
|
139
|
+
export const events = pgTable("events", {
|
|
140
|
+
id: bigint("id", { mode: "bigint" }).primaryKey().generatedAlwaysAsIdentity(),
|
|
141
|
+
tenantId: text("tenant_id").notNull(),
|
|
142
|
+
name: text("name").notNull(),
|
|
143
|
+
payload: jsonb("payload").notNull(),
|
|
144
|
+
createdAt: instant("created_at").notNull().defaultNow(),
|
|
145
|
+
}, (t) => [index("events_lookup").on(t.tenantId, t.name, t.createdAt)]);
|
|
146
|
+
/**
|
|
147
|
+
* Which events each run has received, so a run never takes the same event twice: not for
|
|
148
|
+
* two waits, and not again on replay.
|
|
149
|
+
*/
|
|
150
|
+
export const eventDeliveries = pgTable("event_deliveries", {
|
|
151
|
+
runId: uuid("run_id").notNull(),
|
|
152
|
+
eventId: bigint("event_id", { mode: "bigint" }).notNull(),
|
|
153
|
+
}, (t) => [primaryKey({ columns: [t.runId, t.eventId] })]);
|
|
154
|
+
/**
|
|
155
|
+
* Concurrency limits (F10): at most `max_running` runs with this key run at once. What is
|
|
156
|
+
* running is not stored: it is the key's leased tasks, counted when a claim needs it, so
|
|
157
|
+
* there is no counter to drift.
|
|
158
|
+
*/
|
|
159
|
+
export const concurrencySlots = pgTable("concurrency_slots", {
|
|
160
|
+
key: text("key").primaryKey(),
|
|
161
|
+
maxRunning: integer("max_running").notNull(),
|
|
162
|
+
}, (t) => [check("concurrency_slots_max_running_check", sql `${t.maxRunning} >= 1`)]);
|
|
163
|
+
/**
|
|
164
|
+
* Rate limits (F11): a token bucket per key, refilled lazily on the database clock. Tokens
|
|
165
|
+
* may go below zero: a step that takes one then is a reservation, and waits until the
|
|
166
|
+
* bucket has refilled past it.
|
|
167
|
+
*/
|
|
168
|
+
export const rateBuckets = pgTable("rate_buckets", {
|
|
169
|
+
key: text("key").primaryKey(),
|
|
170
|
+
capacity: integer("capacity").notNull(),
|
|
171
|
+
refillPerSec: numeric("refill_per_sec").notNull(),
|
|
172
|
+
tokens: numeric("tokens").notNull(),
|
|
173
|
+
updatedAt: instant("updated_at").notNull(),
|
|
174
|
+
}, (t) => [
|
|
175
|
+
check("rate_buckets_capacity_check", sql `${t.capacity} >= 1`),
|
|
176
|
+
check("rate_buckets_refill_check", sql `${t.refillPerSec} > 0`),
|
|
177
|
+
]);
|
|
178
|
+
/**
|
|
179
|
+
* Runs someone is following live, by the engine serving them: engines forward a
|
|
180
|
+
* ctx.llm call's tokens only for runs in here. Each row expires unless its engine renews
|
|
181
|
+
* it, so an engine that died leaves nothing behind for long.
|
|
182
|
+
*/
|
|
183
|
+
export const runWatches = pgTable("run_watches", {
|
|
184
|
+
runId: uuid("run_id").notNull(),
|
|
185
|
+
engineId: text("engine_id").notNull(),
|
|
186
|
+
expiresAt: instant("expires_at").notNull(),
|
|
187
|
+
}, (t) => [
|
|
188
|
+
primaryKey({ columns: [t.runId, t.engineId] }),
|
|
189
|
+
index("run_watches_expiry").on(t.expiresAt),
|
|
190
|
+
]);
|
|
191
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/store/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,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IACrC,SAAS,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC,OAAO,EAAE;CAC3C,EACD,CAAC,CAAC,EAAE,EAAE,CAAC;IACL,UAAU,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;IAC9C,KAAK,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;CAC5C,CACF,CAAC"}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { jsonb } from "./json.js";
|
|
2
|
+
/**
|
|
3
|
+
* Where the journal stands for one reported seq. Steps are gap-free from 0, so the next
|
|
4
|
+
* seq is max + 1.
|
|
5
|
+
*
|
|
6
|
+
* Plan: two index scans on steps_pkey: a point lookup and a backward scan for the max.
|
|
7
|
+
*/
|
|
8
|
+
export async function journalPosition(tx, runId, seq) {
|
|
9
|
+
const [row] = await tx `
|
|
10
|
+
SELECT (SELECT coalesce(max(seq) + 1, 0) FROM steps WHERE run_id = ${runId})::int AS next,
|
|
11
|
+
(SELECT name FROM steps WHERE run_id = ${runId} AND seq = ${seq}) AS "nameAtSeq"`;
|
|
12
|
+
if (row === undefined)
|
|
13
|
+
throw new Error("journal position query returned no row");
|
|
14
|
+
return { next: row.next, nameAtSeq: row.nameAtSeq ?? undefined };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Appends a succeeded step. A sleep is recorded when it starts, with a null output, so a
|
|
18
|
+
* replay passes it at once; the wait itself lives in waits. Times come from the database clock; the start is derived from
|
|
19
|
+
* the worker's reported duration so worker clock skew cannot distort the timeline.
|
|
20
|
+
* Callers hold the task's row lock, so no other report for this run can race this insert;
|
|
21
|
+
* the primary key would reject one if it did.
|
|
22
|
+
*/
|
|
23
|
+
export async function insertStep(tx, step) {
|
|
24
|
+
const { llm } = step;
|
|
25
|
+
await tx `
|
|
26
|
+
INSERT INTO steps (run_id, seq, name, kind, status, output, attempts, model, tokens_in,
|
|
27
|
+
tokens_out, cost_usd, started_at, finished_at)
|
|
28
|
+
VALUES (${step.runId}, ${step.seq}, ${step.name}, ${step.kind}, 'succeeded',
|
|
29
|
+
${jsonb(step.output)}::text::jsonb, 1, ${llm?.model ?? null}, ${llm?.inputTokens ?? null},
|
|
30
|
+
${llm?.outputTokens ?? null}, ${llm?.costUsd ?? null}::numeric,
|
|
31
|
+
now() - make_interval(secs => ${step.durationMs / 1000}), now())`;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Keeps one failed attempt of a step, so a run's history shows every try, not only the one
|
|
35
|
+
* that finally worked. The primary key (run_id, seq, failure) rejects a second record of
|
|
36
|
+
* the same failure; callers hold the task's row lock, so none can race.
|
|
37
|
+
*/
|
|
38
|
+
export async function insertStepAttempt(tx, attempt) {
|
|
39
|
+
const error = { name: attempt.name, type: attempt.error.type, message: attempt.error.message };
|
|
40
|
+
await tx `
|
|
41
|
+
INSERT INTO step_attempts (run_id, seq, failure, error, started_at, finished_at)
|
|
42
|
+
VALUES (${attempt.runId}, ${attempt.seq}, ${attempt.failure}, ${jsonb(error)}::text::jsonb,
|
|
43
|
+
now() - make_interval(secs => ${attempt.durationMs / 1000}), now())`;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The recorded steps of each run, in seq order. Steps are append-only, so a journal read
|
|
47
|
+
* after a claim committed contains every step reported before it.
|
|
48
|
+
*
|
|
49
|
+
* Plan: index scan on steps_pkey for each run id.
|
|
50
|
+
*/
|
|
51
|
+
export async function loadJournals(sql, runIds) {
|
|
52
|
+
const journals = new Map(runIds.map((id) => [id, []]));
|
|
53
|
+
if (runIds.length === 0)
|
|
54
|
+
return journals;
|
|
55
|
+
const rows = await sql `
|
|
56
|
+
SELECT run_id AS "runId", seq, name, output FROM steps
|
|
57
|
+
WHERE run_id = ANY(${[...runIds]}::uuid[])
|
|
58
|
+
ORDER BY run_id, seq`;
|
|
59
|
+
for (const { runId, ...entry } of rows)
|
|
60
|
+
journals.get(runId)?.push(entry);
|
|
61
|
+
return journals;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The batch form of journalPosition: for each (run, seq), where the run's journal stands.
|
|
65
|
+
* One statement; positions come back in the order asked.
|
|
66
|
+
*
|
|
67
|
+
* Plan: per pair, an Index Only Scan Backward on steps_pkey for the max and a point lookup.
|
|
68
|
+
*/
|
|
69
|
+
export async function journalPositions(tx, asked) {
|
|
70
|
+
if (asked.length === 0)
|
|
71
|
+
return [];
|
|
72
|
+
const rows = await tx `
|
|
73
|
+
SELECT (SELECT coalesce(max(s.seq) + 1, 0) FROM steps s WHERE s.run_id = q.run_id)::int AS next,
|
|
74
|
+
(SELECT s.name FROM steps s WHERE s.run_id = q.run_id AND s.seq = q.seq) AS "nameAtSeq"
|
|
75
|
+
FROM unnest(${asked.map((a) => a.runId)}::uuid[], ${asked.map((a) => a.seq)}::int[])
|
|
76
|
+
WITH ORDINALITY AS q(run_id, seq, ord)
|
|
77
|
+
ORDER BY q.ord`;
|
|
78
|
+
return rows.map((row) => ({ next: row.next, nameAtSeq: row.nameAtSeq ?? undefined }));
|
|
79
|
+
}
|
|
80
|
+
/** The batch form of insertStep for succeeded `run` and `llm` steps: one statement. */
|
|
81
|
+
export async function insertSteps(tx, steps) {
|
|
82
|
+
if (steps.length === 0)
|
|
83
|
+
return;
|
|
84
|
+
await tx `
|
|
85
|
+
INSERT INTO steps (run_id, seq, name, kind, status, output, attempts, model, tokens_in,
|
|
86
|
+
tokens_out, cost_usd, started_at, finished_at)
|
|
87
|
+
SELECT run_id, seq, name, kind, 'succeeded', output::jsonb, 1, model, tokens_in, tokens_out,
|
|
88
|
+
cost_usd, now() - make_interval(secs => duration_ms / 1000.0), now()
|
|
89
|
+
FROM unnest(${steps.map((s) => s.runId)}::uuid[], ${steps.map((s) => s.seq)}::int[],
|
|
90
|
+
${steps.map((s) => s.name)}::text[], ${steps.map((s) => s.kind)}::text[],
|
|
91
|
+
${steps.map((s) => jsonb(s.output))}::text[],
|
|
92
|
+
${steps.map((s) => s.llm?.model ?? null)}::text[],
|
|
93
|
+
${steps.map((s) => s.llm?.inputTokens ?? null)}::int[],
|
|
94
|
+
${steps.map((s) => s.llm?.outputTokens ?? null)}::int[],
|
|
95
|
+
${steps.map((s) => s.llm?.costUsd ?? null)}::numeric[],
|
|
96
|
+
${steps.map((s) => s.durationMs)}::int[])
|
|
97
|
+
AS s(run_id, seq, name, kind, output, model, tokens_in, tokens_out, cost_usd, duration_ms)`;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Copies `from`'s recorded steps before `beforeSeq` into `to`'s journal, unchanged: a
|
|
101
|
+
* replay starts with them recorded, so a worker returns their outputs instead of running
|
|
102
|
+
* them. The copies keep their times, models, tokens and costs.
|
|
103
|
+
*
|
|
104
|
+
* Plan: Index Scan on steps_pkey (run_id, seq < beforeSeq).
|
|
105
|
+
*/
|
|
106
|
+
export async function copySteps(tx, from, to, beforeSeq) {
|
|
107
|
+
await tx `
|
|
108
|
+
INSERT INTO steps (run_id, seq, name, kind, status, output, error, attempts, model,
|
|
109
|
+
tokens_in, tokens_out, cost_usd, started_at, finished_at)
|
|
110
|
+
SELECT ${to}::uuid, seq, name, kind, status, output, error, attempts, model, tokens_in,
|
|
111
|
+
tokens_out, cost_usd, started_at, finished_at
|
|
112
|
+
FROM steps WHERE run_id = ${from} AND seq < ${beforeSeq}`;
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=steps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"steps.js","sourceRoot":"","sources":["../../src/store/steps.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AA8BlC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,EAAa,EACb,KAAa,EACb,GAAW;IAEX,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE,CAA8C;yEACG,KAAK;oDAC1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