@swirls/looms 0.19.1 → 0.20.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.
@@ -7,6 +7,39 @@ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").LocalE
7
7
  readonly definitionVersion?: string | undefined;
8
8
  readonly input?: Schema.Json | undefined;
9
9
  }, EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
10
+ readonly type: "evaluator.evaluated";
11
+ readonly payload: {
12
+ readonly evaluationId: string;
13
+ readonly definitionName?: string | undefined;
14
+ readonly answers: {
15
+ readonly [x: string]: {
16
+ readonly type: "boolean";
17
+ readonly value: boolean;
18
+ readonly probability: number;
19
+ } | {
20
+ readonly type: "choice";
21
+ readonly value: string;
22
+ } | {
23
+ readonly type: "score";
24
+ readonly value: number;
25
+ };
26
+ };
27
+ readonly route: string;
28
+ readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
29
+ readonly usage?: {
30
+ readonly input: number;
31
+ readonly output: number;
32
+ } | undefined;
33
+ };
34
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
35
+ readonly type: "evaluator.requested";
36
+ readonly payload: {
37
+ readonly evaluationId: string;
38
+ readonly definitionName?: string | undefined;
39
+ readonly state: string;
40
+ readonly model?: string | undefined;
41
+ };
42
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
10
43
  readonly type: "runtime.child.close.requested";
11
44
  readonly payload: {
12
45
  readonly policy: "terminate" | "wait";
@@ -252,37 +285,4 @@ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").LocalE
252
285
  readonly payload: Schema.Json;
253
286
  };
254
287
  };
255
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
256
- readonly type: "evaluator.evaluated";
257
- readonly payload: {
258
- readonly evaluationId: string;
259
- readonly definitionName?: string | undefined;
260
- readonly answers: {
261
- readonly [x: string]: {
262
- readonly type: "boolean";
263
- readonly value: boolean;
264
- readonly probability: number;
265
- } | {
266
- readonly type: "choice";
267
- readonly value: string;
268
- } | {
269
- readonly type: "score";
270
- readonly value: number;
271
- };
272
- };
273
- readonly route: string;
274
- readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
275
- readonly usage?: {
276
- readonly input: number;
277
- readonly output: number;
278
- } | undefined;
279
- };
280
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
281
- readonly type: "evaluator.requested";
282
- readonly payload: {
283
- readonly evaluationId: string;
284
- readonly definitionName?: string | undefined;
285
- readonly state: string;
286
- readonly model?: string | undefined;
287
- };
288
288
  })>>;
@@ -43,6 +43,39 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
43
43
  readonly definitionVersion?: string | undefined;
44
44
  readonly input?: import("effect/Schema").Json | undefined;
45
45
  }, import("./definitions-store").EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
46
+ readonly type: "evaluator.evaluated";
47
+ readonly payload: {
48
+ readonly evaluationId: string;
49
+ readonly definitionName?: string | undefined;
50
+ readonly answers: {
51
+ readonly [x: string]: {
52
+ readonly type: "boolean";
53
+ readonly value: boolean;
54
+ readonly probability: number;
55
+ } | {
56
+ readonly type: "choice";
57
+ readonly value: string;
58
+ } | {
59
+ readonly type: "score";
60
+ readonly value: number;
61
+ };
62
+ };
63
+ readonly route: string;
64
+ readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
65
+ readonly usage?: {
66
+ readonly input: number;
67
+ readonly output: number;
68
+ } | undefined;
69
+ };
70
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
71
+ readonly type: "evaluator.requested";
72
+ readonly payload: {
73
+ readonly evaluationId: string;
74
+ readonly definitionName?: string | undefined;
75
+ readonly state: string;
76
+ readonly model?: string | undefined;
77
+ };
78
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
46
79
  readonly type: "runtime.child.close.requested";
47
80
  readonly payload: {
48
81
  readonly policy: "terminate" | "wait";
@@ -288,39 +321,6 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
288
321
  readonly payload: import("effect/Schema").Json;
289
322
  };
290
323
  };
291
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
292
- readonly type: "evaluator.evaluated";
293
- readonly payload: {
294
- readonly evaluationId: string;
295
- readonly definitionName?: string | undefined;
296
- readonly answers: {
297
- readonly [x: string]: {
298
- readonly type: "boolean";
299
- readonly value: boolean;
300
- readonly probability: number;
301
- } | {
302
- readonly type: "choice";
303
- readonly value: string;
304
- } | {
305
- readonly type: "score";
306
- readonly value: number;
307
- };
308
- };
309
- readonly route: string;
310
- readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
311
- readonly usage?: {
312
- readonly input: number;
313
- readonly output: number;
314
- } | undefined;
315
- };
316
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
317
- readonly type: "evaluator.requested";
318
- readonly payload: {
319
- readonly evaluationId: string;
320
- readonly definitionName?: string | undefined;
321
- readonly state: string;
322
- readonly model?: string | undefined;
323
- };
324
324
  })>;
325
325
  }, {
326
326
  evaluator: import("@swirls/looms/core").ThreadDefinition<{
@@ -391,6 +391,39 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
391
391
  readonly definitionVersion?: string | undefined;
392
392
  readonly input?: import("effect/Schema").Json | undefined;
393
393
  }, import("./definitions-store").EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
394
+ readonly type: "evaluator.evaluated";
395
+ readonly payload: {
396
+ readonly evaluationId: string;
397
+ readonly definitionName?: string | undefined;
398
+ readonly answers: {
399
+ readonly [x: string]: {
400
+ readonly type: "boolean";
401
+ readonly value: boolean;
402
+ readonly probability: number;
403
+ } | {
404
+ readonly type: "choice";
405
+ readonly value: string;
406
+ } | {
407
+ readonly type: "score";
408
+ readonly value: number;
409
+ };
410
+ };
411
+ readonly route: string;
412
+ readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
413
+ readonly usage?: {
414
+ readonly input: number;
415
+ readonly output: number;
416
+ } | undefined;
417
+ };
418
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
419
+ readonly type: "evaluator.requested";
420
+ readonly payload: {
421
+ readonly evaluationId: string;
422
+ readonly definitionName?: string | undefined;
423
+ readonly state: string;
424
+ readonly model?: string | undefined;
425
+ };
426
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
394
427
  readonly type: "runtime.child.close.requested";
395
428
  readonly payload: {
396
429
  readonly policy: "terminate" | "wait";
@@ -636,39 +669,6 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
636
669
  readonly payload: import("effect/Schema").Json;
637
670
  };
638
671
  };
639
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
640
- readonly type: "evaluator.evaluated";
641
- readonly payload: {
642
- readonly evaluationId: string;
643
- readonly definitionName?: string | undefined;
644
- readonly answers: {
645
- readonly [x: string]: {
646
- readonly type: "boolean";
647
- readonly value: boolean;
648
- readonly probability: number;
649
- } | {
650
- readonly type: "choice";
651
- readonly value: string;
652
- } | {
653
- readonly type: "score";
654
- readonly value: number;
655
- };
656
- };
657
- readonly route: string;
658
- readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
659
- readonly usage?: {
660
- readonly input: number;
661
- readonly output: number;
662
- } | undefined;
663
- };
664
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
665
- readonly type: "evaluator.requested";
666
- readonly payload: {
667
- readonly evaluationId: string;
668
- readonly definitionName?: string | undefined;
669
- readonly state: string;
670
- readonly model?: string | undefined;
671
- };
672
672
  })>;
673
673
  };
674
674
  readonly threads: {
@@ -23,7 +23,7 @@ export type PostgresEventLogOptions = ({
23
23
  } | {
24
24
  sql: Sql;
25
25
  }) & {
26
- /** Declared run attributes. Each one is a `looms_run_index` column. */
26
+ /** Declared run attributes. Each one is a column on `looms_run_index` and on `looms_run_events`. */
27
27
  readonly additionalFields?: RunAttributeFields;
28
28
  /**
29
29
  * Schema ownership on init. Default `auto` applies pending versioned migrations
@@ -36,5 +36,9 @@ export declare function postgresEventLog(options: PostgresEventLogOptions): Even
36
36
  export declare function applySqlOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
37
37
  /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
38
38
  export declare function applyRunIndexOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
39
- /** Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered. */
40
- export declare function insertRunEvents(sql: TransactionSql, events: readonly EventEnvelope[]): Promise<void>;
39
+ /**
40
+ * Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered.
41
+ * Each declared attribute column is filled from the run's attributes: the started event when it is in
42
+ * `events`, otherwise the run's `looms_run_index` row, which an earlier batch wrote.
43
+ */
44
+ export declare function insertRunEvents(sql: TransactionSql, events: readonly EventEnvelope[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
@@ -1,6 +1,6 @@
1
1
  import { DateTime, Effect } from 'effect';
2
2
  import createPostgresClient, {} from 'postgres';
3
- import {} from '@swirls/looms/core';
3
+ import { isJsonObject, readAttributes, } from '@swirls/looms/core';
4
4
  import { eventLogOps } from './event-log-ops.js';
5
5
  import { runProjectorPromise } from './projector.js';
6
6
  import { columnValues, resolveReplicaColumns } from './replica/columns.js';
@@ -172,7 +172,10 @@ function postgresStore(sql, ownsClient, additionalFields, migrate) {
172
172
  : Promise.resolve(),
173
173
  };
174
174
  }
175
- /** Keeps each statement under Postgres's 65,535 bind parameters (13 per event row). */
175
+ /** Postgres allows 65,535 bind parameters per statement. */
176
+ const MAX_BIND_PARAMETERS = 65_535;
177
+ /** Bind parameters per event row before declared attribute columns. */
178
+ const EVENT_ROW_PARAMETERS = 14;
176
179
  const INSERT_CHUNK_ROWS = 1_000;
177
180
  function runIndexPatches(ops) {
178
181
  const patches = new Map();
@@ -201,7 +204,10 @@ function runIndexPatches(ops) {
201
204
  }
202
205
  export function applySqlOps(sql, ops, columns = []) {
203
206
  const events = ops.flatMap((op) => (op.type === 'insert' ? [envelopeFromEntry(op.entry)] : []));
204
- return Promise.all([insertRunEvents(sql, events), applyRunIndexOps(sql, ops, columns)]).then(() => undefined);
207
+ return Promise.all([
208
+ insertRunEvents(sql, events, columns),
209
+ applyRunIndexOps(sql, ops, columns),
210
+ ]).then(() => undefined);
205
211
  }
206
212
  /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
207
213
  export function applyRunIndexOps(sql, ops, columns = []) {
@@ -217,13 +223,39 @@ export function applyRunIndexOps(sql, ops, columns = []) {
217
223
  }
218
224
  return Promise.all(statements).then(() => undefined);
219
225
  }
220
- /** Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered. */
221
- export function insertRunEvents(sql, events) {
226
+ /**
227
+ * Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered.
228
+ * Each declared attribute column is filled from the run's attributes: the started event when it is in
229
+ * `events`, otherwise the run's `looms_run_index` row, which an earlier batch wrote.
230
+ */
231
+ export async function insertRunEvents(sql, events, columns = []) {
232
+ const attributes = columns.length === 0 ? new Map() : await runAttributes(sql, events);
233
+ const chunkRows = Math.min(INSERT_CHUNK_ROWS, Math.floor(MAX_BIND_PARAMETERS / (EVENT_ROW_PARAMETERS + columns.length)));
222
234
  const statements = [];
223
- for (let index = 0; index < events.length; index += INSERT_CHUNK_ROWS) {
224
- statements.push(insertEventChunk(sql, events.slice(index, index + INSERT_CHUNK_ROWS)));
235
+ for (let index = 0; index < events.length; index += chunkRows) {
236
+ statements.push(insertEventChunk(sql, events.slice(index, index + chunkRows), columns, attributes));
225
237
  }
226
- return Promise.all(statements).then(() => undefined);
238
+ await Promise.all(statements);
239
+ }
240
+ /** Attributes for each run in `events`. They are immutable, so any source for a run agrees. */
241
+ async function runAttributes(sql, events) {
242
+ const found = new Map();
243
+ for (const event of events) {
244
+ if (event.type === 'runtime.run.started' && !event.ephemeral && !found.has(event.runId)) {
245
+ const payload = isJsonObject(event.payload) ? event.payload : {};
246
+ found.set(event.runId, readAttributes(payload.attributes));
247
+ }
248
+ }
249
+ const missing = [...new Set(events.map((event) => event.runId))].filter((id) => !found.has(id));
250
+ if (missing.length > 0) {
251
+ const rows = await sql `
252
+ SELECT run_id, attributes FROM looms_run_index WHERE run_id IN ${sql(missing)}
253
+ `;
254
+ for (const row of rows) {
255
+ found.set(row.run_id, row.attributes);
256
+ }
257
+ }
258
+ return found;
227
259
  }
228
260
  function envelopeFromEntry(entry) {
229
261
  return {
@@ -242,8 +274,9 @@ function envelopeFromEntry(entry) {
242
274
  idempotencyKey: entry.idempotencyKey,
243
275
  };
244
276
  }
245
- function insertEventChunk(sql, events) {
277
+ function insertEventChunk(sql, events, columns, attributes) {
246
278
  const rows = events.map((event) => ({
279
+ ...hostColumnRow(columns, attributes.get(event.runId)),
247
280
  run_id: event.runId,
248
281
  seq: event.seq,
249
282
  event_id: event.id,
@@ -11,7 +11,7 @@ export interface ReplicaPurgeOptions<Fields extends RunAttributeFields = RunAttr
11
11
  readonly [Key in keyof Fields & string]?: string;
12
12
  };
13
13
  }
14
- /** A declared attribute and the `looms_run_index` column that stores it. */
14
+ /** A declared attribute and the column that stores it on `looms_run_index` and `looms_run_events`. */
15
15
  export interface ResolvedReplicaColumn {
16
16
  /** Attribute name, and the property name on the Drizzle table. */
17
17
  readonly key: string;
@@ -34,8 +34,15 @@ export interface ReplicaMigration {
34
34
  readonly id: string;
35
35
  readonly sql: string;
36
36
  }
37
+ export interface ColumnMigrationSql {
38
+ readonly runIndexColumn: (column: ResolvedReplicaColumn) => string;
39
+ readonly runIndexIndex: (column: ResolvedReplicaColumn) => string;
40
+ readonly eventColumn: (column: ResolvedReplicaColumn) => string;
41
+ readonly eventIndex: (column: ResolvedReplicaColumn) => string;
42
+ }
37
43
  /**
38
44
  * Migrations for declared attribute columns, after the Looms tables.
39
- * Each column and each index is its own migration, so declaring one later only adds that file.
45
+ * Each column and each index is its own migration, so declaring one later only adds those files.
46
+ * The `looms_run_index` column comes first; the `looms_run_events` column backfills from that table.
40
47
  */
41
- export declare function columnMigrations(fields: RunAttributeFields | undefined, migration: (id: string, sql: string) => ReplicaMigration, columnSql: (column: ResolvedReplicaColumn) => string, indexSql: (column: ResolvedReplicaColumn) => string): readonly ReplicaMigration[];
48
+ export declare function columnMigrations(fields: RunAttributeFields | undefined, migration: (id: string, sql: string) => ReplicaMigration, sql: ColumnMigrationSql): readonly ReplicaMigration[];
@@ -1,4 +1,4 @@
1
- /** Postgres caps identifiers at 63 bytes, and the index name adds `looms_run_index_`. */
1
+ /** Postgres caps identifiers at 63 bytes, and index names add `looms_run_index_` or `looms_run_event_`. */
2
2
  const COLUMN_NAME = /^[a-z_][a-z0-9_]{0,46}$/;
3
3
  const LOOMS_COLUMNS = new Set([
4
4
  'run_id',
@@ -16,6 +16,18 @@ const LOOMS_COLUMNS = new Set([
16
16
  'completed_at',
17
17
  'replicated_seq',
18
18
  'purged_at',
19
+ 'seq',
20
+ 'event_id',
21
+ 'ts',
22
+ 'type',
23
+ 'payload',
24
+ 'thread_id',
25
+ 'parent_thread_id',
26
+ 'causation_id',
27
+ 'effect_id',
28
+ 'origin',
29
+ 'idempotency_key',
30
+ 'ephemeral',
19
31
  ]);
20
32
  function snakeCase(key) {
21
33
  return key
@@ -67,11 +79,14 @@ export function sqlStringLiteral(value) {
67
79
  }
68
80
  /**
69
81
  * Migrations for declared attribute columns, after the Looms tables.
70
- * Each column and each index is its own migration, so declaring one later only adds that file.
82
+ * Each column and each index is its own migration, so declaring one later only adds those files.
83
+ * The `looms_run_index` column comes first; the `looms_run_events` column backfills from that table.
71
84
  */
72
- export function columnMigrations(fields, migration, columnSql, indexSql) {
73
- return resolveReplicaColumns(fields).flatMap((column) => {
74
- const added = migration(`column_${column.name}`, columnSql(column));
75
- return column.index ? [added, migration(`index_${column.name}`, indexSql(column))] : [added];
76
- });
85
+ export function columnMigrations(fields, migration, sql) {
86
+ return resolveReplicaColumns(fields).flatMap((column) => [
87
+ migration(`column_${column.name}`, sql.runIndexColumn(column)),
88
+ ...(column.index ? [migration(`index_${column.name}`, sql.runIndexIndex(column))] : []),
89
+ migration(`event_column_${column.name}`, sql.eventColumn(column)),
90
+ ...(column.index ? [migration(`event_index_${column.name}`, sql.eventIndex(column))] : []),
91
+ ]);
77
92
  }