GeezerVison is showing github.com — perf(server): thread list reads no longer scan a long thread's runs a… · incognitojam/styal@3c7b846
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/FoundationPersistence.test.ts +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -4159,6 +4159,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { | 4159 | 4159 | }); | 4160 | 4160 | const afterUpdate = yield* projectionStore.getThreadProjection(threadId); | 4161 | 4161 | assert.equal(afterUpdate.turnItems[0]?.ordinal, ordinals[0]); | | 4162 | + assert.equal((yield* projectionStore.getThreadShell(threadId))?.itemCount, 151); | 4162 | 4163 | assert.equal((yield* maintenance.verify).valid, true); | 4163 | 4164 |
| 4164 | 4165 | yield* sql` | @@ -4173,6 +4174,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { | 4173 | 4174 | const rebuilt = yield* maintenance.rebuild; | 4174 | 4175 | assert.isTrue(rebuilt.valid); | 4175 | 4176 | assert.lengthOf((yield* projectionStore.getThreadProjection(threadId)).turnItems, 151); | | 4177 | + assert.equal((yield* projectionStore.getThreadShell(threadId))?.itemCount, 151); | 4176 | 4178 | }), | 4177 | 4179 | ); | 4178 | 4180 | }); | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/ProjectionStore.test.ts +96-40Lines changed: 96 additions & 40 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -5753,42 +5753,71 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { | 5753 | 5753 | }), | 5754 | 5754 | ); | 5755 | 5755 |
| 5756 | | - it.effect("looks up shell stop requests and report questions through partial indexes", () => | 5757 | | - Effect.gen(function* () { | 5758 | | - const projectionStore = yield* ProjectionStore.ProjectionStoreV2; | 5759 | | - const sql = yield* SqlClient.SqlClient; | 5760 | | - const { projectId } = yield* assertProjectScopedShells("sql-shell-stop-index"); | 5761 | | - const { statements, tracer } = traceSqlStatements(); | 5762 | | - yield* projectionStore | 5763 | | - .getShellSnapshot({ projectId, location: "active" }) | 5764 | | - .pipe(Effect.withTracer(tracer)); | | 5756 | + it.effect( | | 5757 | + "reads shell runs, item counts, and report questions without walking thread history", | | 5758 | + () => | | 5759 | + Effect.gen(function* () { | | 5760 | + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; | | 5761 | + const sql = yield* SqlClient.SqlClient; | | 5762 | + const { projectId } = yield* assertProjectScopedShells("sql-shell-stop-index"); | | 5763 | + const { statements, tracer } = traceSqlStatements(); | | 5764 | + yield* projectionStore | | 5765 | + .getShellSnapshot({ projectId, location: "active" }) | | 5766 | + .pipe(Effect.withTracer(tracer)); | | 5767 | + const planOf = (statement: string) => | | 5768 | + sql | | 5769 | + .unsafe<{ readonly detail: string }>(`EXPLAIN QUERY PLAN ${statement}`) | | 5770 | + .pipe(Effect.map((rows) => rows.map((row) => row.detail))); | 5765 | 5771 |
| 5766 | | - const threadQuery = statements.find((statement) => | 5767 | | - statement.includes("AS latest_run_stop_requested"), | 5768 | | - ); | 5769 | | - assert.isDefined(threadQuery); | 5770 | | - const plan = (yield* sql.unsafe<{ readonly detail: string }>( | 5771 | | - `EXPLAIN QUERY PLAN ${threadQuery}`, | 5772 | | - )).map((row) => row.detail); | 5773 | | - for (const [alias, index] of [ | 5774 | | - ["report", "report_key"], | 5775 | | - ["newer", "report_key"], | 5776 | | - ["answer", "report_answer"], | 5777 | | - ]) { | 5778 | | - const lookup = plan.find((detail) => detail.startsWith(`SEARCH ${alias} `)); | 5779 | | - assert.isDefined(lookup); | 5780 | | - assert.include(lookup, `orchestration_v2_projection_messages_${index}_idx`); | 5781 | | - } | 5782 | | - assert.include( | 5783 | | - plan.find((detail) => detail.startsWith("SEARCH newer ")), | 5784 | | - "(thread_id=? AND <expr>=? AND <expr>>?)", | 5785 | | - ); | 5786 | | - const stopRequestLookups = plan.filter((detail) => detail.startsWith("SEARCH stop_request ")); | 5787 | | - assert.lengthOf(stopRequestLookups, 2); | 5788 | | - for (const lookup of stopRequestLookups) { | 5789 | | - assert.include(lookup, "orchestration_v2_projection_turn_items_stop_request_idx"); | 5790 | | - } | 5791 | | - }), | | 5772 | + const threadQuery = statements.find((statement) => | | 5773 | + statement.includes("AS latest_run_stop_requested"), | | 5774 | + ); | | 5775 | + assert.isDefined(threadQuery); | | 5776 | + const plan = yield* planOf(threadQuery); | | 5777 | + for (const [alias, index] of [ | | 5778 | + ["report", "report_key"], | | 5779 | + ["newer", "report_key"], | | 5780 | + ["answer", "report_answer"], | | 5781 | + ]) { | | 5782 | + const lookup = plan.find((detail) => detail.startsWith(`SEARCH ${alias} `)); | | 5783 | + assert.isDefined(lookup); | | 5784 | + assert.include(lookup, `orchestration_v2_projection_messages_${index}_idx`); | | 5785 | + } | | 5786 | + assert.include( | | 5787 | + plan.find((detail) => detail.startsWith("SEARCH newer ")), | | 5788 | + "(thread_id=? AND <expr>=? AND <expr>>?)", | | 5789 | + ); | | 5790 | + const stopRequestLookups = plan.filter((detail) => | | 5791 | + detail.startsWith("SEARCH stop_request "), | | 5792 | + ); | | 5793 | + assert.lengthOf(stopRequestLookups, 2); | | 5794 | + for (const lookup of stopRequestLookups) { | | 5795 | + assert.include(lookup, "orchestration_v2_projection_turn_items_stop_request_idx"); | | 5796 | + } | | 5797 | + // The active, activity, and pending-secret lookups; walking the ordinal index instead | | 5798 | + // reads every run of an idle thread. | | 5799 | + const activeRunLookups = plan.filter( | | 5800 | + (detail) => detail.startsWith("SEARCH r ") && detail.includes("(thread_id=?"), | | 5801 | + ); | | 5802 | + assert.lengthOf(activeRunLookups, 4); | | 5803 | + for (const lookup of activeRunLookups) { | | 5804 | + assert.include(lookup, "orchestration_v2_projection_runs_thread_status_idx"); | | 5805 | + } | | 5806 | + const lastExecutedIndex = plan.findIndex((detail) => | | 5807 | + detail.includes("orchestration_v2_projection_runs_last_executed_idx"), | | 5808 | + ); | | 5809 | + assert.notStrictEqual(lastExecutedIndex, -1); | | 5810 | + // The lookup that follows the search is the sort it no longer needs. | | 5811 | + assert.notInclude(plan[lastExecutedIndex + 1] ?? "", "USE TEMP B-TREE"); | | 5812 | + | | 5813 | + const countQueries = statements.filter((statement) => statement.includes("item_count")); | | 5814 | + assert.isNotEmpty(countQueries); | | 5815 | + for (const countQuery of countQueries) { | | 5816 | + for (const detail of yield* planOf(countQuery)) { | | 5817 | + assert.notInclude(detail, "orchestration_v2_projection_turn_items"); | | 5818 | + } | | 5819 | + } | | 5820 | + }), | 5792 | 5821 | ); | 5793 | 5822 |
| 5794 | 5823 | it.effect("reads a run's turn-start items by thread and run, not by walking thread history", () => | @@ -6042,6 +6071,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { | 6042 | 6071 | }, | 6043 | 6072 | }); | 6044 | 6073 | } | | 6074 | + let runWrites = 0; | 6045 | 6075 | const applyRun = ( | 6046 | 6076 | threadId: ThreadId, | 6047 | 6077 | suffix: string, | @@ -6050,9 +6080,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { | 6050 | 6080 | ) => { | 6051 | 6081 | const runId = RunId.make(`run:shell-item-counts:${suffix}`); | 6052 | 6082 | const rootNodeId = NodeId.make(`node:shell-item-counts:${suffix}`); | | 6083 | + runWrites += 1; | 6053 | 6084 | return projectionStore | 6054 | 6085 | .apply({ | 6055 | | - id: EventId.make(`event:shell-item-counts:${suffix}:run`), | | 6086 | + id: EventId.make(`event:shell-item-counts:${suffix}:run:${runWrites}`), | 6056 | 6087 | type: "run.created", | 6057 | 6088 | threadId, | 6058 | 6089 | runId, | @@ -6079,11 +6110,14 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { | 6079 | 6110 | }) | 6080 | 6111 | .pipe(Effect.as(runId)); | 6081 | 6112 | }; | 6082 | | - let ordinal = 0; | 6083 | | - const applyItem = (threadId: ThreadId, runId: RunId | null) => { | 6084 | | - ordinal += 1; | | 6113 | + let items = 0; | | 6114 | + let writes = 0; | | 6115 | + // Passing `rewrite` writes that earlier item again, possibly under another run. | | 6116 | + const applyItem = (threadId: ThreadId, runId: RunId | null, rewrite?: number) => { | | 6117 | + const ordinal = rewrite ?? (items += 1); | | 6118 | + writes += 1; | 6085 | 6119 | return projectionStore.apply({ | 6086 | | - id: EventId.make(`event:shell-item-counts:item:${ordinal}`), | | 6120 | + id: EventId.make(`event:shell-item-counts:write:${writes}`), | 6087 | 6121 | type: "turn-item.updated", | 6088 | 6122 | threadId, | 6089 | 6123 | ...(runId === null ? {} : { runId }), | @@ -6136,6 +6170,28 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { | 6136 | 6170 | ); | 6137 | 6171 | assert.equal(shell?.itemCount, itemCount); | 6138 | 6172 | } | | 6173 | + | | 6174 | + // Writing an item again keeps its count; moving it to another run moves the count. | | 6175 | + const itemCountOf = (threadId: ThreadId) => | | 6176 | + projectionStore.getThreadShell(threadId).pipe(Effect.map((shell) => shell?.itemCount)); | | 6177 | + yield* applyItem(busyThreadId, completedRunId, 3); | | 6178 | + assert.equal(yield* itemCountOf(busyThreadId), 4); | | 6179 | + yield* applyItem(busyThreadId, rolledBackRunId, 3); | | 6180 | + assert.equal(yield* itemCountOf(busyThreadId), 3); | | 6181 | + yield* applyItem(busyThreadId, null, 3); | | 6182 | + assert.equal(yield* itemCountOf(busyThreadId), 4); | | 6183 | + | | 6184 | + // A run's rollback uncounts its items, and writing the run again counts them back. | | 6185 | + yield* applyRun(busyThreadId, "busy-completed", 1, true); | | 6186 | + assert.equal(yield* itemCountOf(busyThreadId), 3); | | 6187 | + yield* applyRun(busyThreadId, "busy-completed", 1, false); | | 6188 | + assert.equal(yield* itemCountOf(busyThreadId), 4); | | 6189 | + // Items written before their run exist count once it does. | | 6190 | + const lateRunId = RunId.make("run:shell-item-counts:late"); | | 6191 | + yield* applyItem(otherThreadId, lateRunId); | | 6192 | + assert.equal(yield* itemCountOf(otherThreadId), 1); | | 6193 | + yield* applyRun(otherThreadId, "late", 2, false); | | 6194 | + assert.equal(yield* itemCountOf(otherThreadId), 2); | 6139 | 6195 | }), | 6140 | 6196 | ); | 6141 | 6197 |
| |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/ProjectionStore.ts +14-14Lines changed: 14 additions & 14 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -7296,7 +7296,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> = | 7296 | 7296 | active.status AS active_run_status, | 7297 | 7297 | ( | 7298 | 7298 | SELECT r.status | | 7299 | + -- Read active runs by status. Walking the ordinal index to skip this sort | | 7300 | + -- reads every run of a thread with none active. | 7299 | 7301 | FROM orchestration_v2_projection_runs r | | 7302 | + INDEXED BY orchestration_v2_projection_runs_thread_status_idx | 7300 | 7303 | WHERE r.thread_id = t.thread_id | 7301 | 7304 | AND r.status IN ('preparing', 'starting', 'running', 'waiting') | 7302 | 7305 | AND NOT ${isSilentShellRun("r")} | @@ -7311,6 +7314,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> = | 7311 | 7314 | r.requested_at | 7312 | 7315 | ) | 7313 | 7316 | FROM orchestration_v2_projection_runs r | | 7317 | + INDEXED BY orchestration_v2_projection_runs_thread_status_idx | 7314 | 7318 | WHERE r.thread_id = t.thread_id | 7315 | 7319 | AND r.status IN ('preparing', 'starting', 'running', 'waiting') | 7316 | 7320 | AND NOT ${isSilentShellRun("r")} | @@ -7374,6 +7378,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> = | 7374 | 7378 | SELECT secret.payload_json | 7375 | 7379 | -- Keep runs outermost so completed history is never scanned for a pending secret. | 7376 | 7380 | FROM orchestration_v2_projection_runs r | | 7381 | + INDEXED BY orchestration_v2_projection_runs_thread_status_idx | 7377 | 7382 | CROSS JOIN orchestration_v2_projection_turn_items secret | 7378 | 7383 | INDEXED BY orchestration_v2_projection_turn_items_thread_run_idx | 7379 | 7384 | WHERE r.thread_id = t.thread_id | @@ -7425,6 +7430,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> = | 7425 | 7430 | LEFT JOIN orchestration_v2_projection_runs active ON active.run_id = ( | 7426 | 7431 | SELECT r.run_id | 7427 | 7432 | FROM orchestration_v2_projection_runs r | | 7433 | + INDEXED BY orchestration_v2_projection_runs_thread_status_idx | 7428 | 7434 | WHERE r.thread_id = t.thread_id | 7429 | 7435 | AND r.status IN ('preparing', 'starting', 'running') | 7430 | 7436 | AND NOT ${isSilentShellRun("r")} | @@ -7528,27 +7534,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> = | 7528 | 7534 |
| 7529 | 7535 | const selectShellRunItemCounts = (threadIds: ReadonlyArray<ThreadId>) => | 7530 | 7536 | sql<ShellRunItemCountRow>` | 7531 | | - SELECT thread_id, run_id, COUNT(*) AS item_count | 7532 | | - FROM orchestration_v2_projection_turn_items | 7533 | | - WHERE run_id IS NOT NULL AND thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) | 7534 | | - GROUP BY thread_id, run_id | | 7537 | + SELECT thread_id, run_key AS run_id, item_count | | 7538 | + FROM orchestration_v2_projection_turn_item_counts | | 7539 | + WHERE run_key <> '' AND thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) | 7535 | 7540 | `; | 7536 | 7541 |
| 7537 | | - // Count all selected threads in one index walk; fork sources still need per-run counts. | 7538 | 7542 | const selectShellItemCounts = (threadIds: ReadonlyArray<ThreadId>) => | 7539 | 7543 | sql<ShellItemCountRow>` | 7540 | 7544 | SELECT counts.thread_id, | 7541 | | - SUM(CASE WHEN counts.run_id IS NULL OR r.status <> 'rolled_back' | | 7545 | + SUM(CASE WHEN counts.run_key = '' OR r.status <> 'rolled_back' | 7542 | 7546 | THEN counts.item_count ELSE 0 END) AS item_count, | 7543 | | - SUM(CASE WHEN counts.run_id IS NULL THEN counts.item_count ELSE 0 END) | | 7547 | + SUM(CASE WHEN counts.run_key = '' THEN counts.item_count ELSE 0 END) | 7544 | 7548 | AS runless_item_count | 7545 | | - FROM ( | 7546 | | - SELECT thread_id, run_id, COUNT(*) AS item_count | 7547 | | - FROM orchestration_v2_projection_turn_items | 7548 | | - WHERE thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) | 7549 | | - GROUP BY thread_id, run_id | 7550 | | - ) counts | 7551 | | - LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = counts.run_id | | 7549 | + FROM orchestration_v2_projection_turn_item_counts counts | | 7550 | + LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = counts.run_key | | 7551 | + WHERE counts.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) | 7552 | 7552 | GROUP BY counts.thread_id | 7553 | 7553 | `; | 7554 | 7554 |
| |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/persistence/ForkMigrations.test.ts +7-11Lines changed: 7 additions & 11 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -14,7 +14,6 @@ import { migrationManifest, runMigrations } from "./Migrations.ts"; | 14 | 14 | import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; | 15 | 15 |
| 16 | 16 | import dropWorktreeSetupState from "./ForkMigrations/014_DropWorktreeSetupState.ts"; | 17 | | -import { createMessageSearchTriggers } from "../orchestration-v2/messageSearchIndex.ts"; | 18 | 17 |
| 19 | 18 | const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); | 20 | 19 | const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); | @@ -81,16 +80,11 @@ organizedLayer("ForkMigrations project pins from fork migration 11", (it) => { | 81 | 80 | const sql = yield* SqlClient.SqlClient; | 82 | 81 | const pinnedAt = "2026-10-01T00:00:00.000Z"; | 83 | 82 | // An earlier build's history: fork migration 11 ran, upstream stops at 75. | 84 | | - yield* runAllMigrations(); | 85 | | - yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id >= 76`; | 86 | | - yield* sql`DROP INDEX orchestration_v2_projection_threads_subagent_result_idx`; | 87 | | - yield* sql`DROP INDEX orchestration_v2_projection_runs_delegated_delivery_idx`; | 88 | | - yield* sql`ALTER TABLE scheduled_tasks DROP COLUMN thread_mode`; | 89 | | - yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`; | 90 | | - yield* sql`DROP TRIGGER orchestration_v2_message_search_update`; | 91 | | - yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`; | 92 | | - yield* sql`ALTER TABLE orchestration_v2_projection_messages DROP COLUMN search_text`; | 93 | | - yield* createMessageSearchTriggers(sql); | | 83 | + yield* runMigrations({ toMigrationInclusive: 62 }); | | 84 | + yield* sql`ALTER TABLE projection_thread_activities RENAME TO styal_legacy_v1_thread_activities`; | | 85 | + yield* sql`ALTER TABLE projection_turns RENAME TO styal_legacy_v1_turns`; | | 86 | + yield* runMigrations({ toMigrationInclusive: 75 }); | | 87 | + yield* runForkMigrations({ toMigrationInclusive: 11 }); | 94 | 88 | yield* sql` | 95 | 89 | INSERT INTO projection_projects ( | 96 | 90 | project_id, title, workspace_root, scripts_json, created_at, updated_at, | @@ -111,6 +105,8 @@ organizedLayer("ForkMigrations project pins from fork migration 11", (it) => { | 111 | 105 | [81, "ProjectionMessageSearchText"], | 112 | 106 | [82, "TurnItemConversationIndex"], | 113 | 107 | [83, "CommandReadIndexes"], | | 108 | + [84, "LastExecutedRunIndex"], | | 109 | + [85, "TurnItemCounts"], | 114 | 110 | ]); | 115 | 111 | assert.deepStrictEqual( | 116 | 112 | yield* sql` | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/persistence/Migrations.ts +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -86,6 +86,8 @@ import Migration0080 from "./Migrations/080_ScheduledTaskThreadMode.ts"; | 86 | 86 | import Migration0081 from "./Migrations/081_ProjectionMessageSearchText.ts"; | 87 | 87 | import Migration0082 from "./Migrations/082_TurnItemConversationIndex.ts"; | 88 | 88 | import Migration0083 from "./Migrations/083_CommandReadIndexes.ts"; | | 89 | +import Migration0084 from "./Migrations/084_LastExecutedRunIndex.ts"; | | 90 | +import Migration0085 from "./Migrations/085_TurnItemCounts.ts"; | 89 | 91 |
| 90 | 92 | const migrationEntries = [ | 91 | 93 | [1, "OrchestrationEvents", Migration0001], | @@ -172,6 +174,8 @@ const migrationEntries = [ | 172 | 174 | [81, "ProjectionMessageSearchText", Migration0081], | 173 | 175 | [82, "TurnItemConversationIndex", Migration0082], | 174 | 176 | [83, "CommandReadIndexes", Migration0083], | | 177 | + [84, "LastExecutedRunIndex", Migration0084], | | 178 | + [85, "TurnItemCounts", Migration0085], | 175 | 179 | ] as const; | 176 | 180 |
| 177 | 181 | export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); | |
Collapse file Copy file name to clipboard +18Lines changed: 18 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import * as Effect from "effect/Effect"; | | 2 | +import * as SqlClient from "effect/sql/SqlClient"; | | 3 | + | | 4 | +export default Effect.gen(function* () { | | 5 | + const sql = yield* SqlClient.SqlClient; | | 6 | + | | 7 | + // The shell's last executed run lookup sorts every run of the thread. This index carries | | 8 | + // that order and the same predicate the lookup filters on. A database that already has | | 9 | + // the index keeps it, so a hand-applied one does not fail the migration. | | 10 | + yield* sql` | | 11 | + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_runs_last_executed_idx | | 12 | + ON orchestration_v2_projection_runs( | | 13 | + thread_id, (completed_at IS NULL) DESC, completed_at DESC, ordinal DESC, run_id DESC | | 14 | + ) | | 15 | + WHERE status <> 'queued' | | 16 | + AND NOT (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL) | | 17 | + `; | | 18 | +}); |
Collapse file Copy file name to clipboard +60Lines changed: 60 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import { assert, it } from "@effect/vitest"; | | 2 | +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; | | 3 | +import * as Effect from "effect/Effect"; | | 4 | +import * as SqlClient from "effect/sql/SqlClient"; | | 5 | + | | 6 | +import { runMigrations } from "../Migrations.ts"; | | 7 | + | | 8 | +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); | | 9 | + | | 10 | +layer("085_TurnItemCounts", (it) => { | | 11 | + it.effect("backfills item counts, then follows upserts, moves, and deletes", () => | | 12 | + Effect.gen(function* () { | | 13 | + const sql = yield* SqlClient.SqlClient; | | 14 | + yield* runMigrations({ toMigrationInclusive: 84 }); | | 15 | + const upsert = (id: string, threadId: string, runId: string | null) => sql` | | 16 | + INSERT INTO orchestration_v2_projection_turn_items ( | | 17 | + turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json | | 18 | + ) | | 19 | + VALUES ( | | 20 | + ${id}, ${threadId}, ${runId}, 1, 'assistant_message', 'completed', | | 21 | + '2026-10-29T00:00:00.000Z', '{}' | | 22 | + ) | | 23 | + ON CONFLICT(turn_item_id) DO UPDATE SET | | 24 | + thread_id = excluded.thread_id, | | 25 | + run_id = excluded.run_id, | | 26 | + status = excluded.status | | 27 | + `; | | 28 | + yield* upsert("runless-1", "thread-1", null); | | 29 | + yield* upsert("runless-2", "thread-1", null); | | 30 | + yield* upsert("run-1", "thread-1", "run-1"); | | 31 | + | | 32 | + yield* runMigrations(); | | 33 | + | | 34 | + const counts = () => | | 35 | + sql<{ readonly thread_id: string; readonly run_key: string; readonly item_count: number }>` | | 36 | + SELECT thread_id, run_key, item_count | | 37 | + FROM orchestration_v2_projection_turn_item_counts | | 38 | + ORDER BY thread_id, run_key | | 39 | + `; | | 40 | + assert.deepEqual(yield* counts(), [ | | 41 | + { thread_id: "thread-1", run_key: "", item_count: 2 }, | | 42 | + { thread_id: "thread-1", run_key: "run-1", item_count: 1 }, | | 43 | + ]); | | 44 | + | | 45 | + yield* upsert("run-1", "thread-1", "run-1"); | | 46 | + yield* upsert("run-2", "thread-2", "run-2"); | | 47 | + yield* upsert("runless-2", "thread-1", "run-1"); | | 48 | + assert.deepEqual(yield* counts(), [ | | 49 | + { thread_id: "thread-1", run_key: "", item_count: 1 }, | | 50 | + { thread_id: "thread-1", run_key: "run-1", item_count: 2 }, | | 51 | + { thread_id: "thread-2", run_key: "run-2", item_count: 1 }, | | 52 | + ]); | | 53 | + | | 54 | + yield* sql`DELETE FROM orchestration_v2_projection_turn_items WHERE thread_id = 'thread-1'`; | | 55 | + assert.deepEqual(yield* counts(), [ | | 56 | + { thread_id: "thread-2", run_key: "run-2", item_count: 1 }, | | 57 | + ]); | | 58 | + }), | | 59 | + ); | | 60 | +}); |
|