@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.40
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 +37 -0
- package/README.md +51 -1
- package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
- package/dist/console/assets/index-Jbxjcmdp.js +705 -0
- package/dist/console/index.html +2 -2
- package/dist/email/account.d.ts +0 -1
- package/dist/email/account.js +3 -3
- package/dist/email/answer.d.ts +5 -0
- package/dist/email/answer.js +35 -0
- package/dist/email/mail.js +19 -26
- package/dist/email/names.d.ts +30 -0
- package/dist/email/names.js +34 -0
- package/dist/email/routes.d.ts +1 -0
- package/dist/email/routes.js +1 -1
- package/dist/email/tools.d.ts +11 -4
- package/dist/email/tools.js +91 -46
- package/dist/eval-mailbox.d.ts +1 -1
- package/dist/eval-mailbox.js +3 -3
- package/dist/learn/compile.d.ts +3 -2
- package/dist/learn/compile.js +6 -5
- package/dist/learn/promote.d.ts +25 -14
- package/dist/learn/promote.js +32 -14
- package/dist/learning-cost.d.ts +17 -8
- package/dist/learning-cost.js +12 -4
- package/dist/local-models.d.ts +7 -1
- package/dist/local-models.js +11 -5
- package/dist/openapi.d.ts +1 -1
- package/dist/openapi.js +17 -15
- package/dist/port-models.d.ts +4 -1
- package/dist/port-models.js +1 -0
- package/dist/refusal-words.d.ts +3 -0
- package/dist/refusal-words.js +3 -0
- package/dist/run-launch.d.ts +2 -0
- package/dist/run-launch.js +2 -0
- package/dist/run-view.d.ts +3 -4
- package/dist/run-view.js +26 -24
- package/dist/runner/adapter-loop.d.ts +6 -2
- package/dist/runner/adapter-loop.js +45 -12
- package/dist/runner/adapter-run-spec.d.ts +1 -0
- package/dist/runner/adapter-run-spec.js +37 -1
- package/dist/runner/cli-run-spec.js +1 -0
- package/dist/runner/journal-kinds.d.ts +22 -0
- package/dist/runner/journal-kinds.js +39 -0
- package/dist/runner/model-route.d.ts +3 -1
- package/dist/runner/model-route.js +18 -3
- package/dist/runner/promotion.d.ts +8 -8
- package/dist/runner/promotion.js +135 -54
- package/dist/server.js +15 -8
- package/dist/store/dialect.d.ts +3 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/postgres/connection.d.ts +11 -5
- package/dist/store/postgres/connection.js +44 -17
- package/dist/store/postgres/dialect.js +5 -0
- package/dist/store/postgres/store.d.ts +7 -3
- package/dist/store/postgres/store.js +1 -0
- package/dist/store/sqlite/connection.js +72 -8
- package/dist/store/sqlite/run-launch.d.ts +11 -0
- package/dist/store/sqlite/run-launch.js +8 -0
- package/dist/store/sqlite/store.js +37 -16
- package/dist/store/sqlite/worker.d.ts +2 -0
- package/dist/store/sqlite/worker.js +13 -10
- package/dist/store/store.d.ts +15 -0
- package/dist/store-reads/learning.d.ts +30 -13
- package/dist/store-reads/learning.js +125 -51
- package/dist/template-eval.js +1 -1
- package/dist/templates.d.ts +14 -1
- package/dist/templates.js +67 -17
- package/dist/tool-gate.d.ts +5 -3
- package/dist/tool-gate.js +5 -2
- package/dist/tools.d.ts +13 -0
- package/dist/tools.js +15 -10
- package/dist/trigger-adapter.d.ts +3 -32
- package/dist/trigger-email.js +30 -77
- package/dist/triggers.d.ts +26 -14
- package/dist/triggers.js +99 -76
- package/dist/workflow/decision-recovery.js +5 -2
- package/dist/workflow/decisions.d.ts +7 -0
- package/package.json +9 -9
- package/templates/README.md +2 -2
- package/dist/console/assets/index-BNhZs-jp.css +0 -1
- package/dist/console/assets/index-BQv5aOGB.js +0 -700
|
@@ -8,7 +8,7 @@ import pg from "pg";
|
|
|
8
8
|
import { runnableDeadline } from "../deadline.js";
|
|
9
9
|
import { cleanText } from "../dialect.js";
|
|
10
10
|
import { ONE_ANSWER_INDEX } from "../schema.js";
|
|
11
|
-
import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned } from "../store.js";
|
|
11
|
+
import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned, STORE_WRITE_DEADLINE_MS } from "../store.js";
|
|
12
12
|
import { DEFAULT_TRANSACTION_DEADLINE_MS } from "../sqlite/connection.js";
|
|
13
13
|
import { postgresDialect } from "./dialect.js";
|
|
14
14
|
/** Which store this is, as two opens of the same data agree on it (StoreConnection.where): "postgres:" and the URL's host
|
|
@@ -26,7 +26,8 @@ export function postgresWhere(url, schema) {
|
|
|
26
26
|
}
|
|
27
27
|
/** A schema name the store takes: a plain lower-case identifier, so it is never quoted, and never input in SQL. */
|
|
28
28
|
export const SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
29
|
-
/** The default bound on
|
|
29
|
+
/** The default bound on a new connection's connect and startup to the store's Postgres (PgConnectionOptions.connectTimeoutMs),
|
|
30
|
+
* in ms; a wait for a busy pool's connection to come free has its own, longer bound (PgConnectionOptions.poolWaitMs). Below
|
|
30
31
|
* the runner's stop margin (runner.ts: lease 30 s, renew every 10 s, stop margin 5 s; a claim is let go when no renew has
|
|
31
32
|
* landed within lease - margin = 25 s of the last one's send, so two renew ticks, at +10 s and +20 s, fall inside it): a
|
|
32
33
|
* renew that cannot get a connection gives up within 4 s, inside the 5 s margin, and the next tick tries again. A renew
|
|
@@ -34,17 +35,20 @@ export const SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
|
34
35
|
* renew, connect to commit, is bounded from its call (LEASE_DEADLINE_MS), so one sent at +10 s whose connection went
|
|
35
36
|
* silent fails by +19 s and the +20 s tick renews on a fresh connection before +25 s. */
|
|
36
37
|
export const STORE_CONNECT_TIMEOUT_MS = 4_000;
|
|
37
|
-
/** pg's and pg-pool's words for a connection
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
/** pg's and pg-pool's words for a new connection's connect or startup that never finished in time. */
|
|
39
|
+
const CONNECT_TIMEOUT = /timeout expired|Connection terminated due to connection timeout/i;
|
|
40
|
+
/** pg-pool's words for a wait in its queue that no client came free for in time (every one in use). */
|
|
41
|
+
const POOL_WAIT_TIMEOUT = /timeout exceeded when trying to connect/i;
|
|
42
|
+
/** Whether `error`, or an error it was made from, says `words`. */
|
|
43
|
+
function says(error, words) {
|
|
42
44
|
for (let e = error, depth = 0; e && depth < 5; e = e.cause, depth++) {
|
|
43
|
-
if (
|
|
45
|
+
if (words.test(String(e.message ?? "")))
|
|
44
46
|
return true;
|
|
45
47
|
}
|
|
46
48
|
return false;
|
|
47
49
|
}
|
|
50
|
+
/** Whether `error`, or an error it was made from, is a new connection not had in time. */
|
|
51
|
+
const connectTimedOut = (error) => says(error, CONNECT_TIMEOUT);
|
|
48
52
|
/** A COMMIT is bounded by what is left of its transaction's deadline, never less than this (a commit sent at the deadline
|
|
49
53
|
* still gets an answer's time). Past it the connection is taken as silent and let go (destroyed); the commit's outcome is
|
|
50
54
|
* then unknown, and the caller is told so (Unanswered). STORE_WRITE_DEADLINE_MS's users keep 2 s spare for it. */
|
|
@@ -89,9 +93,14 @@ async function answered(query, ms, what) {
|
|
|
89
93
|
async function rollBackAndRelease(client) {
|
|
90
94
|
await answered(client.query("ROLLBACK"), ROLLBACK_ANSWER_MS, "its rollback").then(() => client.release(), (error) => client.release(error));
|
|
91
95
|
}
|
|
92
|
-
/** The refusal for a connection not
|
|
96
|
+
/** The refusal for a new connection not made within `ms` to the database at `where` (postgresWhere: no user or password). */
|
|
93
97
|
function connectDeadline(where, ms) {
|
|
94
|
-
return new StoreDeadline(ms, `no connection to the store's Postgres at ${where} within ${ms} ms: it does not answer
|
|
98
|
+
return new StoreDeadline(ms, `no connection to the store's Postgres at ${where} within ${ms} ms: it does not answer`);
|
|
99
|
+
}
|
|
100
|
+
/** The refusal for a call that waited `ms` for one of the `size` connections of the store's pool on the database at
|
|
101
|
+
* `where`, every one of them in use all that time: the store is busier than its pool, and the database answers. */
|
|
102
|
+
function poolBusy(where, ms, size) {
|
|
103
|
+
return new StoreDeadline(ms, `no connection of the store's Postgres at ${where} came free within ${ms} ms: all ${size} of this store's connections stayed in use, so the call was never sent`);
|
|
95
104
|
}
|
|
96
105
|
/** int8 as a JavaScript number: every integer the store keeps (ms, ids, epochs, counts) is one, and one outside the safe
|
|
97
106
|
* range is refused, as node:sqlite refuses it. */
|
|
@@ -277,8 +286,10 @@ export class PgConnection {
|
|
|
277
286
|
/** What taking the owner lock back needs. */
|
|
278
287
|
#ownerConfig;
|
|
279
288
|
#busyTimeoutMs;
|
|
280
|
-
/** The bound on
|
|
289
|
+
/** The bound on a new connection's connect and startup (PgConnectionOptions.connectTimeoutMs). */
|
|
281
290
|
#connectMs;
|
|
291
|
+
/** The bound on a wait for a busy pool's connection to come free (PgConnectionOptions.poolWaitMs), and the pool's size. */
|
|
292
|
+
#poolWait;
|
|
282
293
|
#closed = false;
|
|
283
294
|
/** Set while the owner lock is not held (its connection ended or failed, and it is being taken back), and for good once
|
|
284
295
|
* another server has the schema: every call is refused with it meanwhile. */
|
|
@@ -300,8 +311,9 @@ export class PgConnection {
|
|
|
300
311
|
}
|
|
301
312
|
return columns;
|
|
302
313
|
};
|
|
303
|
-
constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, ownerConfig) {
|
|
314
|
+
constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, poolWait, leasePool, ownerConfig) {
|
|
304
315
|
this.#connectMs = connectMs;
|
|
316
|
+
this.#poolWait = poolWait;
|
|
305
317
|
this.#pool = pool;
|
|
306
318
|
this.#leasePool = leasePool;
|
|
307
319
|
this.#owner = owner;
|
|
@@ -376,20 +388,31 @@ export class PgConnection {
|
|
|
376
388
|
this.#ownerConfig?.onLost?.(error);
|
|
377
389
|
}
|
|
378
390
|
/** The pool on `url` in `schema`, and (owner) the owner lock: StoreOwned when another server holds the schema. */
|
|
379
|
-
static async open({ url, schema, owner = false, busyTimeoutMs = 10_000, poolSize = 10, testClock = false, connectTimeoutMs = STORE_CONNECT_TIMEOUT_MS, ownerWaitMs = OWNER_WAIT_MS, onOwnerWait, onOwnerLost, ownerCheck }) {
|
|
391
|
+
static async open({ url, schema, owner = false, busyTimeoutMs = 10_000, poolSize = 10, testClock = false, connectTimeoutMs = STORE_CONNECT_TIMEOUT_MS, poolWaitMs = STORE_WRITE_DEADLINE_MS, ownerWaitMs = OWNER_WAIT_MS, onOwnerWait, onOwnerLost, ownerCheck }) {
|
|
380
392
|
if (!SCHEMA_NAME.test(schema))
|
|
381
393
|
throw new TypeError(`the store's schema is a lower-case name of letters, digits and underscores, not ${JSON.stringify(schema)}`);
|
|
382
394
|
// The database's end of the keepalives (KEEPALIVE_IDLE_S): a vanished client's session, and its locks, ended in ~25 s.
|
|
383
395
|
const keepalives = `-c tcp_keepalives_idle=${KEEPALIVE_IDLE_S} -c tcp_keepalives_interval=5 -c tcp_keepalives_count=3`;
|
|
384
396
|
const session = `-c search_path=${schema} -c lock_timeout=${Math.max(0, Math.floor(busyTimeoutMs))} -c synchronous_commit=on ${keepalives}`;
|
|
385
397
|
const connectMs = Math.max(1, Math.floor(connectTimeoutMs));
|
|
398
|
+
// Never below the connect's bound: pg-pool's one connectionTimeoutMillis also cuts a new client's connect, which must
|
|
399
|
+
// keep its own bound and its own words (StoreClient's).
|
|
400
|
+
const poolWait = Math.max(connectMs, Math.floor(poolWaitMs));
|
|
386
401
|
const where = postgresWhere(url, schema);
|
|
387
|
-
//
|
|
402
|
+
// Two bounds on getting a connection, each in one place. A new connection's connect and startup: connectMs, on the
|
|
403
|
+
// client itself (StoreClient), so a database that does not answer is refused fast. A wait in the pool's queue while
|
|
404
|
+
// every client is in use (a runner's loops' commits behind one another): pg-pool's connectionTimeoutMillis, poolWait,
|
|
405
|
+
// so a busy pool of a database that answers is waited out to a write's own deadline, never failed at connectMs.
|
|
406
|
+
class StoreClient extends pg.Client {
|
|
407
|
+
constructor(config) {
|
|
408
|
+
super({ ...(typeof config === "string" ? { connectionString: config } : config), connectionTimeoutMillis: connectMs });
|
|
409
|
+
}
|
|
410
|
+
}
|
|
388
411
|
// keepAlive: this end's TCP keepalives, from KEEPALIVE_IDLE_S (pg's default delay, 0, is the OS's 2 h).
|
|
389
412
|
const tcp = { keepAlive: true, keepAliveInitialDelayMillis: KEEPALIVE_IDLE_S * 1_000 };
|
|
390
413
|
// Every connection named for its schema, as the lease's and the owner lock's are: pg_stat_activity tells which
|
|
391
414
|
// store holds each one.
|
|
392
|
-
const config = { connectionString: url, options: session, types, max: poolSize, allowExitOnIdle: true, application_name: `agentrun-store:${schema}`, connectionTimeoutMillis:
|
|
415
|
+
const config = { connectionString: url, options: session, types, max: poolSize, allowExitOnIdle: true, application_name: `agentrun-store:${schema}`, Client: StoreClient, connectionTimeoutMillis: poolWait, ...tcp };
|
|
393
416
|
let lock;
|
|
394
417
|
const waitMs = Math.max(0, Math.floor(ownerWaitMs));
|
|
395
418
|
if (owner) {
|
|
@@ -428,7 +451,7 @@ export class PgConnection {
|
|
|
428
451
|
each.on("error", () => undefined);
|
|
429
452
|
each.on("connect", (fresh) => fresh.on("error", () => undefined));
|
|
430
453
|
}
|
|
431
|
-
return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, lock ? { url, waitMs, onLost: onOwnerLost, check: ownerCheck } : undefined);
|
|
454
|
+
return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, { ms: poolWait, size: poolSize }, leasePool, lock ? { url, waitMs, onLost: onOwnerLost, check: ownerCheck } : undefined);
|
|
432
455
|
}
|
|
433
456
|
/** `work`, counted in flight, refused after close. A connection it never got in time is StoreDeadline, naming the
|
|
434
457
|
* database's place. */
|
|
@@ -438,7 +461,11 @@ export class PgConnection {
|
|
|
438
461
|
if (this.#ownerLost)
|
|
439
462
|
return Promise.reject(this.#ownerLost);
|
|
440
463
|
const running = work().catch((error) => {
|
|
441
|
-
|
|
464
|
+
if (connectTimedOut(error))
|
|
465
|
+
throw connectDeadline(this.where, this.#connectMs);
|
|
466
|
+
if (says(error, POOL_WAIT_TIMEOUT))
|
|
467
|
+
throw poolBusy(this.where, this.#poolWait.ms, this.#poolWait.size);
|
|
468
|
+
throw error;
|
|
442
469
|
});
|
|
443
470
|
this.#inFlight.add(running);
|
|
444
471
|
const done = () => void this.#inFlight.delete(running);
|
|
@@ -36,6 +36,11 @@ export function postgresDialect(schema, { testClock = false } = {}) {
|
|
|
36
36
|
lockRow: async (tx, table, column, value, mode) => {
|
|
37
37
|
await tx.run(`SELECT 1 FROM ${table} WHERE ${column} = ? FOR ${mode === "update" ? "UPDATE" : "NO KEY UPDATE"}`, value);
|
|
38
38
|
},
|
|
39
|
+
lockRows: async (tx, table, column, values) => {
|
|
40
|
+
if (values.length === 0)
|
|
41
|
+
return;
|
|
42
|
+
await tx.run(`SELECT 1 FROM ${table} WHERE ${column} IN (${values.map(() => "?").join(", ")}) ORDER BY ${column} FOR NO KEY UPDATE`, ...values);
|
|
43
|
+
},
|
|
39
44
|
lockKey: async (tx, key) => {
|
|
40
45
|
await tx.run("SELECT pg_advisory_xact_lock(hashtext(?), hashtext(?))", schema, key);
|
|
41
46
|
},
|
|
@@ -23,10 +23,14 @@ export interface PostgresStoreOptions {
|
|
|
23
23
|
readonly busyTimeoutMs?: number;
|
|
24
24
|
/** Most connections the store holds at once (10 by default). */
|
|
25
25
|
readonly poolSize?: number;
|
|
26
|
-
/** How long
|
|
27
|
-
*
|
|
28
|
-
*
|
|
26
|
+
/** How long a new connection's connect and startup may take, in ms (STORE_CONNECT_TIMEOUT_MS, 4 s, by default). Past it
|
|
27
|
+
* the call, or the open, is refused (StoreDeadline, naming the database's host, database and schema, never the URL:
|
|
28
|
+
* it does not answer), never left hanging. */
|
|
29
29
|
readonly connectTimeoutMs?: number;
|
|
30
|
+
/** How long a call may wait for one of the pool's connections to come free while every one is in use, in ms
|
|
31
|
+
* (STORE_WRITE_DEADLINE_MS, 10 s, by default; never less than connectTimeoutMs). Past it the call is refused
|
|
32
|
+
* (StoreDeadline: every connection stayed in use), nothing of it sent. */
|
|
33
|
+
readonly poolWaitMs?: number;
|
|
30
34
|
/** Told, at a runner's open, when its clock is more than CLOCK_WARN_MS from the database's; at a server's, when it waits
|
|
31
35
|
* for another server to let the schema go. */
|
|
32
36
|
readonly warn?: (message: string) => void;
|
|
@@ -29,6 +29,7 @@ export async function openPostgresStore(options) {
|
|
|
29
29
|
...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }),
|
|
30
30
|
...(options.poolSize === undefined ? {} : { poolSize: options.poolSize }),
|
|
31
31
|
...(options.connectTimeoutMs === undefined ? {} : { connectTimeoutMs: options.connectTimeoutMs }),
|
|
32
|
+
...(options.poolWaitMs === undefined ? {} : { poolWaitMs: options.poolWaitMs }),
|
|
32
33
|
...(options.ownerWaitMs === undefined ? {} : { ownerWaitMs: options.ownerWaitMs }),
|
|
33
34
|
...(options.warn ? { onOwnerWait: options.warn } : {}),
|
|
34
35
|
...(options.onOwnerLost ? { onOwnerLost: options.onOwnerLost } : {}),
|
|
@@ -15,8 +15,14 @@ export const DEFAULT_TRANSACTION_DEADLINE_MS = 10_000;
|
|
|
15
15
|
/** The interactive transactions open in this process, on any of its connections: each with where it was opened and when
|
|
16
16
|
* it began. A transaction's StoreDeadline, and a begin's StoreBusy, name them in their stack (never their message, which
|
|
17
17
|
* an answer may carry), so a log says who held the store: the deadline's own transaction, or another of this process's
|
|
18
|
-
* (an in-process runner's) holding the lock a begin waited on.
|
|
18
|
+
* (an in-process runner's) holding the lock a begin waited on. `where`: its database (Connection.where), so a wait for
|
|
19
|
+
* the write lock knows a holder of this process on the same database (lockWait). */
|
|
19
20
|
const OPEN = new Set();
|
|
21
|
+
/** The interactive transactions of this process whose begin is with its worker, not yet answered: each on its database
|
|
22
|
+
* (`where`). Such a begin may hold the write lock already, its answer waiting for the event loop, and after a hold-up
|
|
23
|
+
* the answers of two workers come back in no set order, so a wait that ran out then can be read before that begin's
|
|
24
|
+
* answer adds it to OPEN (lockWait). */
|
|
25
|
+
const BEGINNING = new Set();
|
|
20
26
|
/** `opened`'s frames: where a transaction was asked for, without the Error line itself. */
|
|
21
27
|
const framesOf = (opened) => (opened.stack ?? "").split("\n").slice(1).join("\n");
|
|
22
28
|
/** `error` with its stack naming who held the store: `opened` (its own transaction's opener, when it has one), and every
|
|
@@ -198,8 +204,52 @@ export class Connection {
|
|
|
198
204
|
this.#tail = run.catch(() => undefined);
|
|
199
205
|
return run;
|
|
200
206
|
}
|
|
201
|
-
#stmt(sql, params, mode) {
|
|
202
|
-
return this.#send({ op: "stmt", statement: { sql, params: cleaned(params) }, mode });
|
|
207
|
+
#stmt(sql, params, mode, busyMs) {
|
|
208
|
+
return this.#send({ op: "stmt", statement: { sql, params: cleaned(params) }, mode, ...(busyMs !== undefined ? { busyMs } : {}) });
|
|
209
|
+
}
|
|
210
|
+
/** `send`, a request that takes the database's write lock (a transaction's begin, a write, a statement outside a
|
|
211
|
+
* transaction), given how long it may wait for it (`busyMs`; undefined, the connection's own busy wait). A wait that
|
|
212
|
+
* ran out on a transaction of this process on the same database (another of its connections: the server's and its
|
|
213
|
+
* in-process runner's) while this process was held up (its event loop held by other work, the machine holding it) is
|
|
214
|
+
* sent again, with the held-up time given back: that holder's statements wait for the same event loop, and its deadline
|
|
215
|
+
* counts only the time this process could run (store/deadline.ts runnableDeadline), so the wait for it counts the same
|
|
216
|
+
* way, and the holder, once it runs again, commits or meets its deadline. A wait on another process's write, or one
|
|
217
|
+
* this process could run through, ends StoreBusy as ever.
|
|
218
|
+
* Every wait is measured, and the holder looked for when it runs out, never when it is sent: a holder's begin posted
|
|
219
|
+
* in the same turn may take the lock before its answer makes it known. `self`: this request's own begin (BEGINNING),
|
|
220
|
+
* never its own holder. */
|
|
221
|
+
async #lockWait(send, self) {
|
|
222
|
+
let left = this.#busyTimeoutMs;
|
|
223
|
+
for (;;) {
|
|
224
|
+
const clock = runnableDeadline(left, () => { });
|
|
225
|
+
const sent = performance.now();
|
|
226
|
+
try {
|
|
227
|
+
return await send(left < this.#busyTimeoutMs ? left : undefined);
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
if (!(error instanceof StoreBusy))
|
|
231
|
+
throw error;
|
|
232
|
+
const held = clock.held();
|
|
233
|
+
if (held === 0 || !this.#heldHere(self))
|
|
234
|
+
throw error;
|
|
235
|
+
left -= performance.now() - sent - held;
|
|
236
|
+
if (left <= 0)
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
clock.clear();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/** A transaction of this process on this database is open, or its begin is with its worker (other than `self`). */
|
|
245
|
+
#heldHere(self) {
|
|
246
|
+
for (const open of OPEN)
|
|
247
|
+
if (open.where === this.#where)
|
|
248
|
+
return true;
|
|
249
|
+
for (const beginning of BEGINNING)
|
|
250
|
+
if (beginning !== self && beginning.where === this.#where)
|
|
251
|
+
return true;
|
|
252
|
+
return false;
|
|
203
253
|
}
|
|
204
254
|
/** The executor that sends straight to the worker: a transaction's handle, valid while `live()` says so. */
|
|
205
255
|
#executor(live) {
|
|
@@ -221,10 +271,10 @@ export class Connection {
|
|
|
221
271
|
return this.#queued(async () => void (await this.#send({ op: "exec", sql })));
|
|
222
272
|
}
|
|
223
273
|
run(sql, ...params) {
|
|
224
|
-
return this.#queued(async () => void (await this.#stmt(sql, params, "run")));
|
|
274
|
+
return this.#queued(async () => void (await this.#lockWait((busyMs) => this.#stmt(sql, params, "run", busyMs))));
|
|
225
275
|
}
|
|
226
276
|
runCounted(sql, ...params) {
|
|
227
|
-
return this.#queued(async () => (await this.#stmt(sql, params, "count")));
|
|
277
|
+
return this.#queued(async () => (await this.#lockWait((busyMs) => this.#stmt(sql, params, "count", busyMs))));
|
|
228
278
|
}
|
|
229
279
|
get(sql, ...params) {
|
|
230
280
|
return this.#queued(async () => ((await this.#stmt(sql, params, "get")) ?? undefined));
|
|
@@ -235,7 +285,10 @@ export class Connection {
|
|
|
235
285
|
/** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
|
|
236
286
|
* FULL commit, durable against a lost box together with every commit before it. */
|
|
237
287
|
write(statements, { full = false } = {}) {
|
|
238
|
-
return this.#queued(async () =>
|
|
288
|
+
return this.#queued(async () => {
|
|
289
|
+
const cleanedStatements = statements.map(cleanStatement);
|
|
290
|
+
return (await this.#lockWait((busyMs) => this.#send({ op: "write", statements: cleanedStatements, full, ...(busyMs !== undefined ? { busyMs } : {}) })));
|
|
291
|
+
});
|
|
239
292
|
}
|
|
240
293
|
/** A write transaction (BEGIN IMMEDIATE) the callback steps through its handle, deciding each statement from the ones
|
|
241
294
|
* before it. It commits when the callback resolves; when the callback rejects it rolls back and rejects with the same
|
|
@@ -259,15 +312,26 @@ export class Connection {
|
|
|
259
312
|
// Its wait for the database's lock (another process's write) bounded by what the deadline leaves: a lock still held
|
|
260
313
|
// when that runs out is the deadline's end, not the connection's own busy wait.
|
|
261
314
|
const busyMs = until !== undefined ? Math.max(0, until - Date.now()) : undefined;
|
|
315
|
+
// Until its begin is answered, it may hold the lock unknown to OPEN: another wait that runs out meanwhile finds it.
|
|
316
|
+
const beginning = { where: this.#where };
|
|
317
|
+
BEGINNING.add(beginning);
|
|
262
318
|
try {
|
|
263
|
-
|
|
319
|
+
// Counted from its call, its wait is the deadline's, the wall clock's; else its wait for a holder of this process
|
|
320
|
+
// gives back the time this process was held up (lockWait).
|
|
321
|
+
if (busyMs !== undefined)
|
|
322
|
+
await this.#send({ op: "begin", full, ...(read ? { read } : {}), busyMs });
|
|
323
|
+
else
|
|
324
|
+
await this.#lockWait((wait) => this.#send({ op: "begin", full, ...(read ? { read } : {}), ...(wait !== undefined ? { busyMs: wait } : {}) }), beginning);
|
|
264
325
|
}
|
|
265
326
|
catch (error) {
|
|
266
327
|
if (error instanceof StoreBusy && busyMs !== undefined && busyMs < this.#busyTimeoutMs)
|
|
267
328
|
throw holderNamed(new StoreDeadline(deadlineMs), { opened });
|
|
268
329
|
throw error instanceof StoreBusy ? holderNamed(error, { opened }) : error;
|
|
269
330
|
}
|
|
270
|
-
|
|
331
|
+
finally {
|
|
332
|
+
BEGINNING.delete(beginning);
|
|
333
|
+
}
|
|
334
|
+
const open = { opened, began: Date.now(), where: this.#where };
|
|
271
335
|
OPEN.add(open);
|
|
272
336
|
try {
|
|
273
337
|
let live = true;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type RunLaunchInput, type RunLaunchRow } from "../store.js";
|
|
2
|
+
import type { Dialect } from "../dialect.js";
|
|
2
3
|
import type { SqliteExecutor } from "./connection.js";
|
|
3
4
|
/** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
|
|
4
5
|
* trigger path both call it, so the row lands with its run or not at all. */
|
|
@@ -6,3 +7,13 @@ export declare function writeLaunch(tx: Pick<SqliteExecutor, "run">, runId: stri
|
|
|
6
7
|
/** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
|
|
7
8
|
* none, never a default. */
|
|
8
9
|
export declare function readLaunch(executor: Pick<SqliteExecutor, "get">, runId: string): Promise<RunLaunchRow>;
|
|
10
|
+
/** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
|
|
11
|
+
* the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
|
|
12
|
+
* and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
|
|
13
|
+
* is the member's JSON text, null when the run's body names none. */
|
|
14
|
+
export declare function readLearningStarts(executor: Pick<SqliteExecutor, "all"> & {
|
|
15
|
+
readonly dialect: Dialect;
|
|
16
|
+
}, agentId: string, where: string): Promise<{
|
|
17
|
+
runId: string;
|
|
18
|
+
learning: unknown;
|
|
19
|
+
}[]>;
|
|
@@ -18,3 +18,11 @@ export async function readLaunch(executor, runId) {
|
|
|
18
18
|
throw new StoreLaunchMissing(runId);
|
|
19
19
|
return runLaunchOf(row);
|
|
20
20
|
}
|
|
21
|
+
/** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
|
|
22
|
+
* the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
|
|
23
|
+
* and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
|
|
24
|
+
* is the member's JSON text, null when the run's body names none. */
|
|
25
|
+
export async function readLearningStarts(executor, agentId, where) {
|
|
26
|
+
const rows = await executor.all(`SELECT run_id, ${executor.dialect.jsonText("body", ["learning"])} AS learning FROM run_launch WHERE run_id IN (SELECT id FROM runs WHERE agent_id = ? AND ${where})`, agentId);
|
|
27
|
+
return rows.map((row) => ({ runId: row.run_id, learning: row.learning === null ? undefined : JSON.parse(row.learning) }));
|
|
28
|
+
}
|
|
@@ -19,10 +19,10 @@ const seqOf = (cursor) => {
|
|
|
19
19
|
throw new TypeError(`${JSON.stringify(cursor)} is not a run-change cursor this store gave`);
|
|
20
20
|
return Number(cursor);
|
|
21
21
|
};
|
|
22
|
-
import { settledBody } from "../dialect.js";
|
|
22
|
+
import { cleanText, settledBody } from "../dialect.js";
|
|
23
23
|
import { Connection } from "./connection.js";
|
|
24
24
|
import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
|
|
25
|
-
import { readLaunch, writeLaunch } from "./run-launch.js";
|
|
25
|
+
import { readLaunch, readLearningStarts, writeLaunch } from "./run-launch.js";
|
|
26
26
|
import { canonical } from "../agent-body.js";
|
|
27
27
|
import { aadOf, sealedAt } from "../seal.js";
|
|
28
28
|
/** A claim's length when the caller names none. */
|
|
@@ -302,6 +302,13 @@ const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at
|
|
|
302
302
|
AND id NOT IN (SELECT MIN(id) FROM commands WHERE kind IN ('approve', 'deny') AND refused IS NULL AND json_extract(body, '$.approval') IS NOT NULL GROUP BY run_id, json_extract(body, '$.approval'))`;
|
|
303
303
|
/** How many released claims a store remembers, to refuse their journals. */
|
|
304
304
|
const RELEASED_KEPT = 1024;
|
|
305
|
+
/** The most claims one statement of renewMany renews. Its WHERE joins each claim's fence with OR, and each OR is one more
|
|
306
|
+
* level of the expression tree, whose depth SQLite bounds at 1,000 (SQLITE_MAX_EXPR_DEPTH: 997 claims already fail). 250
|
|
307
|
+
* stays a quarter of that, and a runner's 300 claims are still two statements on a database a few ms away. */
|
|
308
|
+
const RENEW_CHUNK = 250;
|
|
309
|
+
/** A claim as renewMany matches it to the rows its update returned: its run, epoch and runner, each string as the store
|
|
310
|
+
* writes text (cleanText: a NUL as U+FFFD), so a claim and the row the database wrote for it make one key. */
|
|
311
|
+
const renewKey = (runId, epoch, runner) => `${cleanText(runId)}\u0000${epoch}\u0000${cleanText(runner)}`;
|
|
305
312
|
/** The key of a claim's one journal: its run and epoch. */
|
|
306
313
|
const journalKey = (claim) => `${claim.runId}\u0000${claim.epoch}`;
|
|
307
314
|
/** A statement under `claim`: one that changes no row means the run's epoch moved on, and the transaction rolls back. */
|
|
@@ -822,6 +829,7 @@ class SqliteStore {
|
|
|
822
829
|
return row && runOf(row);
|
|
823
830
|
},
|
|
824
831
|
launch: (runId) => readLaunch(db, runId),
|
|
832
|
+
learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
|
|
825
833
|
list: async ({ agentId, revisionId, state, archived, limit }) => {
|
|
826
834
|
// 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,
|
|
827
835
|
// count, stat or notice names it.
|
|
@@ -1131,6 +1139,11 @@ class SqliteStore {
|
|
|
1131
1139
|
return row ? proposalOf(row) : undefined;
|
|
1132
1140
|
},
|
|
1133
1141
|
proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
|
|
1142
|
+
kept: async (agentId) => {
|
|
1143
|
+
const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
|
|
1144
|
+
const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL)`, agentId)).map(runOf);
|
|
1145
|
+
return { proposals, learningRuns };
|
|
1146
|
+
},
|
|
1134
1147
|
spend: async ({ from, to }) => {
|
|
1135
1148
|
const rows = await db.all(`SELECT lp.agent_id, lp.proposal, lp.created_at, lp.learning_run_id, lr.state AS run_state, lr.ended_at AS run_ended_at, ${EXACT_COST_USD("lr")} AS run_cost_usd
|
|
1136
1149
|
FROM learning_proposals lp
|
|
@@ -1581,9 +1594,10 @@ class SqliteStore {
|
|
|
1581
1594
|
const rows = await tx.all(`UPDATE runs SET ${claimSet(stamp)} WHERE id IN (${picked.map(() => "?").join(", ")}) RETURNING id, epoch, claimed_until`, runner, ...stamp.params, leaseMs, ...picked.map((row) => row.id));
|
|
1582
1595
|
const epochs = new Map(rows.map((row) => [row.id, row.epoch]));
|
|
1583
1596
|
const untils = new Map(rows.map((row) => [row.id, Number(row.claimed_until)]));
|
|
1584
|
-
// A take or reclaim leaves no viewer of an older claim behind: its rows go in this transaction, every kind
|
|
1585
|
-
for (
|
|
1586
|
-
|
|
1597
|
+
// A take or reclaim leaves no viewer of an older claim behind: its rows go in this transaction, every kind, in one
|
|
1598
|
+
// statement for the whole batch (each run's epoch is the one just moved to), never one round trip a run.
|
|
1599
|
+
if (rows.length > 0)
|
|
1600
|
+
await tx.run(`DELETE FROM computer_viewers WHERE run_id IN (${rows.map(() => "?").join(", ")}) AND epoch < (SELECT epoch FROM runs WHERE runs.id = computer_viewers.run_id)`, ...rows.map((row) => row.id));
|
|
1587
1601
|
// A newer claim of a run supersedes its release here: journal() refuses by epoch, and the newer epoch passes.
|
|
1588
1602
|
for (const { id } of picked)
|
|
1589
1603
|
this.#released.delete(id);
|
|
@@ -1613,21 +1627,28 @@ class SqliteStore {
|
|
|
1613
1627
|
async renewMany(claims, { leaseMs = DEFAULT_LEASE_MS } = {}) {
|
|
1614
1628
|
if (claims.length === 0)
|
|
1615
1629
|
return [];
|
|
1616
|
-
// One transaction for every claim,
|
|
1617
|
-
//
|
|
1630
|
+
// One transaction for every claim, in a few statements whatever their count: the rows held in one, then one update
|
|
1631
|
+
// for each RENEW_CHUNK claims, each claim under its own fence. A runner's 300 claims are never 300 round trips with
|
|
1632
|
+
// their rows held, which on a database a few ms away outlast the lease's margin and lose every claim at once. A claim
|
|
1633
|
+
// another runner took changes no row and is answered Fenced, never rolling the others back.
|
|
1618
1634
|
return this.#db.transaction(async (tx) => {
|
|
1619
|
-
//
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
const
|
|
1623
|
-
for (
|
|
1635
|
+
// Every row held first, in one order (the dialect's, by run id), so two renews of overlapping runs never wait on
|
|
1636
|
+
// each other in a cycle, and the clock below is read once the rows are held.
|
|
1637
|
+
await this.#db.dialect.lockRows(tx, "runs", "id", [...new Set(claims.map((claim) => claim.runId))]);
|
|
1638
|
+
const renewed = new Map();
|
|
1639
|
+
for (let at = 0; at < claims.length; at += RENEW_CHUNK) {
|
|
1640
|
+
const chunk = claims.slice(at, at + RENEW_CHUNK);
|
|
1624
1641
|
// The deadlines' clock (the database's on Postgres) judges each lease and stamps the next one.
|
|
1625
1642
|
const now = this.#clock();
|
|
1626
|
-
const
|
|
1627
|
-
const
|
|
1628
|
-
|
|
1643
|
+
const fences = chunk.map((claim) => claimFence(claim, now));
|
|
1644
|
+
const rows = await tx.all(`UPDATE runs SET claimed_until = ${now.sql} + ? WHERE ${fences.map((fence) => `(${fence.where} AND runner = ?)`).join(" OR ")} RETURNING id, epoch, runner, claimed_until`, ...now.params, leaseMs, ...fences.flatMap((fence, i) => [...fence.params, chunk[i].runner]));
|
|
1645
|
+
for (const row of rows)
|
|
1646
|
+
renewed.set(renewKey(row.id, Number(row.epoch), row.runner), Number(row.claimed_until));
|
|
1629
1647
|
}
|
|
1630
|
-
return
|
|
1648
|
+
return claims.map((claim) => {
|
|
1649
|
+
const until = renewed.get(renewKey(claim.runId, claim.epoch, claim.runner));
|
|
1650
|
+
return until === undefined ? new Fenced(claim.runId, claim.epoch) : { ...claim, until };
|
|
1651
|
+
});
|
|
1631
1652
|
// On the lease connection (TransactionOptions.lease): a runner whose loops hold every pool client still renews.
|
|
1632
1653
|
}, { lease: true });
|
|
1633
1654
|
}
|
|
@@ -9,12 +9,13 @@
|
|
|
9
9
|
// server per store file): an exclusive lock on `<file>.owner`, held until close,
|
|
10
10
|
// let go by the OS when the process dies
|
|
11
11
|
// exec {sql} SQL text, maybe several statements, no bindings
|
|
12
|
-
// stmt {statement, mode}
|
|
12
|
+
// stmt {statement, mode, busyMs} one statement: run, count (its changes), get (first row) or all. Outside a
|
|
13
13
|
// transaction, a run or count is its own BEGIN IMMEDIATE transaction
|
|
14
|
-
// write {statements, full}
|
|
14
|
+
// write {statements, full, busyMs} one transaction: BEGIN IMMEDIATE, each statement in order, COMMIT; `full` makes it
|
|
15
15
|
// a FULL commit (flush). A statement's `expect` checks it changed a row; a miss
|
|
16
16
|
// rolls the whole transaction back with its `miss` (fenced, or a final run)
|
|
17
|
-
// begin {full} / commit / rollback
|
|
17
|
+
// begin {full, busyMs} / commit / rollback
|
|
18
|
+
// an interactive transaction (connection.ts transaction()), its statements sent
|
|
18
19
|
// as stmt, or as step (one statement, its changes and rows, its `expect` checked)
|
|
19
20
|
// in between
|
|
20
21
|
// close
|
|
@@ -65,8 +66,9 @@ function step(statement) {
|
|
|
65
66
|
/** The connection's own busy wait (its open's busyTimeoutMs): what a begin given a shorter one goes back to. */
|
|
66
67
|
let busyTimeout = 0;
|
|
67
68
|
/** A transaction: BEGIN IMMEDIATE for a write; for `read`, a deferred one that takes no writer lock (one snapshot).
|
|
68
|
-
* `busyMs`: the most this begin waits for the database's write lock, when the
|
|
69
|
-
*
|
|
69
|
+
* `busyMs`: the most this begin waits for the database's write lock, when less than the connection's own busy wait is
|
|
70
|
+
* left (a `fromCall` transaction's deadline, or a wait sent again with its held-up time given back: connection.ts
|
|
71
|
+
* lockWait); the connection's own is set back after it. */
|
|
70
72
|
function begin(full, read = false, busyMs) {
|
|
71
73
|
const conn = opened();
|
|
72
74
|
if (full)
|
|
@@ -114,11 +116,12 @@ function end(commit) {
|
|
|
114
116
|
txFull = false;
|
|
115
117
|
}
|
|
116
118
|
}
|
|
117
|
-
/** `work` inside its own BEGIN IMMEDIATE transaction when none is open
|
|
118
|
-
|
|
119
|
+
/** `work` inside its own BEGIN IMMEDIATE transaction when none is open (its begin waiting `busyMs` at most, as begin's);
|
|
120
|
+
* inside the open one otherwise. */
|
|
121
|
+
function written(work, busyMs) {
|
|
119
122
|
if (inTx)
|
|
120
123
|
return work();
|
|
121
|
-
begin(false);
|
|
124
|
+
begin(false, false, busyMs);
|
|
122
125
|
try {
|
|
123
126
|
const value = work();
|
|
124
127
|
end(true);
|
|
@@ -190,10 +193,10 @@ function handle(request) {
|
|
|
190
193
|
const prepared = opened().prepare(statement.sql);
|
|
191
194
|
return mode === "all" ? prepared.all(...(statement.params ?? [])) : (prepared.get(...(statement.params ?? [])) ?? null);
|
|
192
195
|
}
|
|
193
|
-
return written(() => step(statement).changes);
|
|
196
|
+
return written(() => step(statement).changes, request.busyMs);
|
|
194
197
|
}
|
|
195
198
|
case "write": {
|
|
196
|
-
begin(request.full === true);
|
|
199
|
+
begin(request.full === true, false, request.busyMs);
|
|
197
200
|
try {
|
|
198
201
|
const results = request.statements.map(step);
|
|
199
202
|
end(true);
|
package/dist/store/store.d.ts
CHANGED
|
@@ -292,6 +292,13 @@ export interface Learning {
|
|
|
292
292
|
proposals(agentId: string, options?: {
|
|
293
293
|
limit?: number;
|
|
294
294
|
}): Promise<LearningProposal[]>;
|
|
295
|
+
/** Everything agent `agentId`'s runs' learning kept, in two reads whatever the number of its runs: every round of every
|
|
296
|
+
* run's kept proposal (oldest round first within a run), and the rows of the learning runs they name (as runs.get
|
|
297
|
+
* reads one; a learning run named and never written has none). An agent-wide read's, never a read a run. */
|
|
298
|
+
kept(agentId: string): Promise<{
|
|
299
|
+
proposals: LearningProposal[];
|
|
300
|
+
learningRuns: RunRow[];
|
|
301
|
+
}>;
|
|
295
302
|
/** What learning spent outside any run, in one read: each run (not imported) whose learning ended in [from, to) (ms),
|
|
296
303
|
* its agent, when its learning ended and what its grade cost (null: unknown; 0: nothing graded). A learning dropped
|
|
297
304
|
* before it was proposed ended when it was kept; a proposal ended when its learning run ended (ended or failed), whose
|
|
@@ -801,6 +808,14 @@ export interface Runs {
|
|
|
801
808
|
/** The run's launch row (the runner reads it at its claim; the server for views). StoreLaunchMissing when the run has
|
|
802
809
|
* none (it was not started with one), never a default. */
|
|
803
810
|
launch(runId: string): Promise<RunLaunchRow>;
|
|
811
|
+
/** The learning start (the launch body's `learning` member, as stored: undefined when the body names none) of every run of
|
|
812
|
+
* agent `agentId` (no built-in learning run's) that has a launch row, in one read: what an agent-wide read (its cost per
|
|
813
|
+
* run, its learning view) needs of its runs at once, never a read a run. Only that member is read: no run's input, no
|
|
814
|
+
* sealed bytes. A run with no launch row has no entry. */
|
|
815
|
+
learningStarts(agentId: string): Promise<{
|
|
816
|
+
runId: string;
|
|
817
|
+
learning: unknown;
|
|
818
|
+
}[]>;
|
|
804
819
|
/** Newest first, at most `limit` (no limit: all). `archived` filters on the run's own archive time (true: archived,
|
|
805
820
|
* false: not); its agent's archive is read apart. A built-in learning run (one a kept learning names) is never listed. */
|
|
806
821
|
list(filter: {
|