Skip to content

refactor: split db.ts under 400 lines - #14979

Merged
AmethystLiang merged 6 commits into
mainfrom
split-orchestration-db
Aug 17, 2026
Merged

AmethystLiang merged 6 commits into
mainfrom
split-orchestration-db

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​372 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​370
Prod 81 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​9730 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7749 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1981

Problem

The orchestration database module in db.ts exceeded the max-lines budget (~1300 lines), mixing schema creation, dispatch context, federation, legacy compatibility, messages, runs, tasks, and worker dispatch all in one file. Hard to navigate and maintain.

Solution

Split into focused modules organized by feature area:

  • dispatch-context: capability, completion, lookup, worker settlement
  • federation: relay ack/enqueue/import, remote attachments and questions
  • legacy: ask/reply operations, compatibility principals, recovery
  • messages: direct/foreign mailbox routing, inbox, insertion
  • runs: creation, lookup, delivery, binding, coordinator routing
  • tasks: task store, status, lineage
  • worker-dispatch: start/stop, authority, outcome, recovery
  • worker-terminal: archive, listing, release, transfer
  • schema: table creation, v2–v27 migrations
  • utilities: ID generation, capability hashing, pane matching, timestamps

Main orchestration-db.ts is now 48 lines. Methods attach via mixin pattern in attach-orchestration-db-methods.ts. Transactional invariants and behavior unchanged.

Testing

  • No semantic changes to orchestration logic
  • Type safety maintained via exported method interface types
  • Schema and migration logic unchanged
  • Existing tests pass

@coderabbitai

coderabbitai Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4437d3b7-c2b0-4869-aad5-e8dcc6972f96

📥 Commits

Reviewing files that changed from the base of the PR and between a2c03c3 and d06add6.

📒 Files selected for processing (4)
  • src/main/runtime/orchestration/db/federation/remote-question-store.ts
  • src/main/runtime/orchestration/db/reset/orchestration-reset.ts
  • src/main/runtime/orchestration/federation-acknowledgment-integrity.test.ts
  • src/main/runtime/orchestration/orchestration-reset-db.test.ts

📝 Walkthrough

Walkthrough

Adds a complete SQLite-backed orchestration database. The change introduces schema creation and migrations, typed prototype method assembly, run and task management, message routing, legacy compatibility, dispatch and worker lifecycle handling, federation relay support, remote attachments, decision gates, mutation receipts, and worker-terminal resource management. It also adds focused tests for parsing, cursor handling, lifecycle markers, failure idempotency, and transactional message updates.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.73% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the problem, solution, and testing, but it omits most required template sections, including the linked issue, visual proof, checklist, and author details. Complete the required template sections, add the linked issue, provide N/A visual proof if applicable, and complete the testing and checklist items.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the main refactor: splitting the oversized database module and reducing its size.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 20

🧹 Nitpick comments (16)
src/main/runtime/orchestration/db/coordinator-runs/coordinator-run-store.ts (1)

66-71: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Alias the UNION column so the row type matches the query.

The UNION result takes its column name from the first SELECT, so from_handle values arrive under the to_handle key. The cast { to_handle: string }[] therefore describes both sides with a misleading name. An explicit alias makes the shape intentional and stops a later column reorder from breaking the mapping.

♻️ Proposed alias
   const allHandles = this.db
     .prepare(
-      'SELECT DISTINCT to_handle FROM messages UNION SELECT DISTINCT from_handle FROM messages'
+      'SELECT DISTINCT to_handle AS handle FROM messages UNION SELECT DISTINCT from_handle AS handle FROM messages'
     )
-    .all() as { to_handle: string }[]
-  return [...new Set(allHandles.map((r) => r.to_handle))].filter((h) => !busyHandles.has(h))
+    .all() as { handle: string }[]
+  return allHandles.map((r) => r.handle).filter((h) => !busyHandles.has(h))
 }

Note: UNION already removes duplicates, so the extra Set is redundant.

src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.ts (1)

89-109: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Consider guarding the completion update on the pending state.

The UPDATE matches any row with the same caller, request, method, and payload hash. A second call for an already completed receipt overwrites the stored receipt body. A retried request would then observe a different response than the first completion returned. Adding AND state = 'pending' keeps the first recorded receipt authoritative, and the existing changes !== 1 check converts the repeat call into request_mismatch.

If callers already short-circuit on the completed disposition from beginMutationReceipt, this is defensive only.

♻️ Proposed state guard
       `UPDATE mutation_receipts
        SET state = 'completed', receipt = ?, updated_at = datetime('now')
        WHERE caller_fingerprint = ? AND request_id = ? AND method = ?
-         AND payload_hash = ?`
+         AND payload_hash = ? AND state = 'pending'`
src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts (1)

8-30: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Gate lifecycle transitions write multiple tables without a transaction. Both functions update decision_gates and tasks (and, on creation, the active dispatch) as separate statements. A failure between the statements leaves the gate state and the task state inconsistent. Sibling stores in this cohort, such as createQuestion in src/main/runtime/orchestration/db/questions/question-threads.ts, wrap the same class of transition in BEGIN IMMEDIATE with a ROLLBACK handler.

  • src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts#L8-L30: wrap the gate insert, completeActiveDispatchForTask, and the blocked task update in one BEGIN IMMEDIATE block.
  • src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts#L32-L56: wrap the resolved gate update and the ready task update in one BEGIN IMMEDIATE block.

Confirm first that completeActiveDispatchForTask and the callers of these functions do not already hold a transaction, because SQLite rejects nested BEGIN.

src/main/runtime/orchestration/db/legacy/legacy-lifecycle-operation.ts (1)

143-152: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Flatten the nested ternary that derives persistedOutcome.

The nested conditional repeats two of the three operands. A small helper makes the reconstruction rule explicit.

♻️ Optional refactor
-      const persistedOutcome =
-        params.message.existingId &&
-        dispatch.task_id === params.lifecycle.taskId &&
-        dispatch.status === 'completed'
-          ? 'succeeded'
-          : params.message.existingId &&
-              dispatch.task_id === params.lifecycle.taskId &&
-              dispatch.status === 'failed'
-            ? 'failed'
-            : undefined
+      const reconstructsSettledDispatch =
+        Boolean(params.message.existingId) && dispatch.task_id === params.lifecycle.taskId
+      const persistedOutcome = !reconstructsSettledDispatch
+        ? undefined
+        : dispatch.status === 'completed'
+          ? 'succeeded'
+          : dispatch.status === 'failed'
+            ? 'failed'
+            : undefined
src/main/runtime/orchestration/db/legacy/legacy-question-lookup.ts (1)

71-97: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Reuse the fetched message and hoist the acknowledgement statement.

row.source_message_id and row.message_id hold the same value, because the join condition is m.id = q.message_id. Each surviving row therefore calls getMessageById twice. The acknowledgement probe also calls prepare once per row. Row count is capped at 500, so this is a hygiene improvement rather than a hot-path defect.

♻️ Optional refactor
+  const acknowledged = this.db.prepare(
+    `SELECT 1 FROM legacy_mail_receipts
+     WHERE principal_id = ? AND message_id = ?
+       AND acknowledged_at IS NOT NULL`
+  )
   return rows
-    .filter((row) => {
-      const message = this.getMessageById(row.source_message_id)
-      return Boolean(
-        message &&
-        legacyMessageMatchesQuestion(message, params.question, params.options ?? [], [
-          params.recipientHandle,
-          runAddress
-        ])
-      )
-    })
-    .map((row) => ({
+    .flatMap((row) => {
+      const message = this.getMessageById(row.message_id)
+      if (
+        !message ||
+        !legacyMessageMatchesQuestion(message, params.question, params.options ?? [], [
+          params.recipientHandle,
+          runAddress
+        ])
+      ) {
+        return []
+      }
+      return [{
         question: exposeQuestionTimestamps(row),
-      message: this.getMessageById(row.message_id) as MessageRow,
+        message,
         claimedByOperation: row.claimed_by_operation === 1,
         answerAcknowledged: row.answer_message_id
-        ? Boolean(
-            this.db
-              .prepare(
-                `SELECT 1 FROM legacy_mail_receipts
-                 WHERE principal_id = ? AND message_id = ?
-                   AND acknowledged_at IS NOT NULL`
-              )
-              .get(principal.id, row.answer_message_id)
-          )
-        : false
-    }))
+          ? Boolean(acknowledged.get(principal.id, row.answer_message_id))
+          : false
+      }]
+    })
src/main/runtime/orchestration/db/lifecycle-rejection-marker.ts (1)

6-19: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Preserve the original payload when it is not a JSON object.

src/main/runtime/orchestration/db/messages/message-inbox.ts Lines 36-59 writes this result back into messages.payload. For an array payload, a scalar payload, or invalid JSON, parsed stays empty and the original content is lost from the audit record. Keep the raw value under a separate key.

♻️ Proposed refactor
   let parsed: Record<string, unknown> = {}
+  let unstructured: string | undefined
   try {
     const value: unknown = payload ? JSON.parse(payload) : {}
     if (value && typeof value === 'object' && !Array.isArray(value)) {
       parsed = value as Record<string, unknown>
+    } else if (payload) {
+      unstructured = payload
     }
   } catch {
-    // Authority reconciliation only reaches this path with object payloads.
+    unstructured = payload ?? undefined
   }
   return JSON.stringify({
     ...parsed,
+    ...(unstructured === undefined ? {} : { _orcaOriginalPayload: unstructured }),
     _orcaLifecycleRejection: { code, reason }
   })
src/main/runtime/orchestration/db/legacy/legacy-compatibility-principals.ts (1)

32-34: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Unconditional ROLLBACK in the catch block can discard a caller's transaction. Four methods open a transaction with this.db.exec('BEGIN IMMEDIATE') and roll back unconditionally in the catch block. SQLite rejects a nested BEGIN, so a call made inside an existing transaction throws at the BEGIN line, and the catch block then rolls back the outer transaction. The shared fix is to track transaction ownership, or to use the driver's transaction wrapper, which nests through savepoints.

  • src/main/runtime/orchestration/db/legacy/legacy-compatibility-principals.ts#L32-L34: guard the BEGIN IMMEDIATE in commitLegacyCompatibilityPrincipal, and roll back at line 134 only when this call opened the transaction.
  • src/main/runtime/orchestration/db/legacy/legacy-mail-acknowledge.ts#L19-L20: apply the same ownership guard in acknowledgeLegacyMail, whose catch block rolls back at line 100.
  • src/main/runtime/orchestration/db/legacy/legacy-question-acknowledge.ts#L14-L15: apply the same ownership guard in acknowledgeLegacyQuestionAnswer, whose catch block rolls back at line 87.
  • src/main/runtime/orchestration/db/runs/run-binding.ts#L23-L23: apply the same ownership guard in bindRun, which also rolls back at lines 27 and 152.
src/main/runtime/orchestration/db/schema/migrate-v13-v27.ts (1)

5-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align the module and function name with the highest handled version.

The gate at line 146 handles version 28, but the function is named applySchemaMigrationsV13ToV27 and the file is migrate-v13-v27.ts. The name states the range contract for the next migration author. Rename both to cover v28, or move the mutation_caller_identities gate into a follow-on module.

Also applies to: 146-153

src/main/runtime/orchestration/db/schema/migrate-legacy-contract-storage.ts (1)

108-118: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Stream message rows with StatementSync.iterate().

.all(runId) materializes every payload during startup migration. Use .iterate(runId) to keep memory usage bounded. SyncDatabase.prepare() returns the native StatementSync, which provides iterate().

src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts (1)

54-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the duplicate comments.

Line 56 duplicates Line 54. Lines 127-128 duplicate Lines 124-125. Keep one concise comment for each operation.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”

Also applies to: 124-128

Source: Coding guidelines

src/main/runtime/orchestration/db/dispatch-context/dispatch-completion.ts (1)

12-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared active-dispatch lookup.

completeActiveDispatchForTask and failActiveDispatchForTask run the identical SELECT. Extract one local helper so the active-dispatch predicate stays consistent if the status set changes.

♻️ Proposed refactor
+function activeDispatchForTask(
+  db: OrchestrationDb,
+  taskId: string
+): DispatchContextRow | undefined {
+  return db.db
+    .prepare(
+      "SELECT * FROM dispatch_contexts WHERE task_id = ? AND status IN ('pending', 'dispatched') ORDER BY rowid DESC LIMIT 1"
+    )
+    .get(taskId) as DispatchContextRow | undefined
+}
+
 export function completeActiveDispatchForTask(this: OrchestrationDb, taskId: string): void {
-  const active = this.db
-    .prepare(
-      "SELECT * FROM dispatch_contexts WHERE task_id = ? AND status IN ('pending', 'dispatched') ORDER BY rowid DESC LIMIT 1"
-    )
-    .get(taskId) as DispatchContextRow | undefined
+  const active = activeDispatchForTask(this, taskId)
   if (active) {
     this.completeDispatch(active.id)
   }
 }
@@
-  const active = this.db
-    .prepare(
-      "SELECT * FROM dispatch_contexts WHERE task_id = ? AND status IN ('pending', 'dispatched') ORDER BY rowid DESC LIMIT 1"
-    )
-    .get(taskId) as DispatchContextRow | undefined
+  const active = activeDispatchForTask(this, taskId)
   return active ? this.failDispatch(active.id, error) : undefined
src/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts (1)

44-52: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Avoid the parse and re-stringify round trip for effects and residual_resources.

When params.effects is undefined, line 49 parses the stored column and stringifies it again. The write is semantically a no-op but can reformat the stored text. JSON.parse also throws if the column holds malformed JSON, which aborts an otherwise valid reconcile.

Use COALESCE in SQL and bind null instead.

♻️ Proposed refactor
-               effects = ?, residual_resources = ?, last_error = NULL,
+               effects = COALESCE(?, effects),
+               residual_resources = COALESCE(?, residual_resources), last_error = NULL,
@@
-          JSON.stringify(params.effects ?? JSON.parse(worker.effects)),
-          JSON.stringify(params.residualResources ?? JSON.parse(worker.residual_resources)),
+          params.effects ? JSON.stringify(params.effects) : null,
+          params.residualResources ? JSON.stringify(params.residualResources) : null,
src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts (1)

81-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the orphaned comments.

The section header on line 81 and the note on line 83 describe worker-terminal-resource behavior. No code in this file implements that behavior; the logic now lives in src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts. Move the note next to the code it explains, or delete it.

🧹 Proposed cleanup
-// --- Worker terminal resources (schema v23) ---------------------------------------------------
-
-// Historical renderer input and reuse cannot be proven, so pre-v23 terminals stay external.
-
 export type WorkerDispatchAbandonMethods = {
src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts (1)

70-76: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add a state guard to the worker update.

This update matches on dispatch_id alone. Every other update in this function constrains the current state, for example line 55 and line 64. The early return at line 39 excludes settled workers, and the statement runs inside the transaction, so the current in-process behavior is correct. Add the guard so a concurrently settled worker cannot be reopened and so the statement matches the file convention.

♻️ Proposed refactor
         `UPDATE worker_dispatches
          SET state = ?, stage = 'terminal_missing', last_error = ?, updated_at = datetime('now')
-         WHERE dispatch_id = ?`
+         WHERE dispatch_id = ?
+           AND state IN ('starting', 'ready', 'start_unknown', 'stopping', 'stop_unknown')`
src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.ts (1)

101-127: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Wrap the read-then-write stage update in a transaction.

recordRemoteAttachmentStage reads the row at Line 101 and then writes every column back, using the snapshot values as fallbacks. The UPDATE has no predicate on the observed state. A concurrent writer that changes state, last_error, or effects between the read and the write loses that change. updateRemoteAttachmentSetupEvidence at Lines 139-156 has the same shape.

Two options exist. Run both statements inside BEGIN IMMEDIATE like createRemoteDispatchAttachment does, or build the UPDATE from only the supplied fields so unspecified columns are never rewritten.

src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts (1)

19-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse WORKER_SETTLED_STATES and drop the unused JOIN.

Two points apply here.

The settled-state list at Lines 49-50 duplicates WORKER_SETTLED_STATES, which worker-terminal-release.ts imports from ../../worker-terminal-ownership. The literal can drift from the shared constant. Import the constant instead.

The JOIN on worker_dispatches at Line 22 selects no column from w and applies no predicate on w. The eligibility check at Line 50 already loads the owning dispatch. If more than one worker_dispatches row shares an owner_dispatch_id, the JOIN also duplicates candidate rows.

♻️ Proposed refactor
+import { WORKER_SETTLED_STATES } from '../../worker-terminal-ownership'
 import type { WorkerTerminalResourceRow } from '../../worker-terminal-ownership'
@@
   const candidates = this.db
     .prepare(
       `SELECT r.* FROM worker_terminal_resources r
-         JOIN worker_dispatches w ON w.dispatch_id = r.owner_dispatch_id
         WHERE r.process_incarnation = ? AND r.host_scope IS ?
           AND r.ownership_state != 'released'`
     )
@@
   return exact.find(
     (candidate) =>
       candidate.ownership_state === 'owned' &&
       ['not_requested', 'retained'].includes(candidate.release_state) &&
-      ['succeeded', 'failed', 'stopped', 'abandoned'].includes(
-        this.getWorkerDispatch(candidate.owner_dispatch_id)?.state ?? ''
-      )
+      WORKER_SETTLED_STATES.includes(
+        this.getWorkerDispatch(candidate.owner_dispatch_id)?.state as never
+      )
   )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 29cefc18-7437-49e7-ae72-b8106c634a62

📥 Commits

Reviewing files that changed from the base of the PR and between c73e5a2 and 54d4117.

📒 Files selected for processing (85)
  • config/max-lines-baseline.txt
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/contract-constants.ts
  • src/main/runtime/orchestration/db/coordinator-runs/coordinator-run-store.ts
  • src/main/runtime/orchestration/db/database-file-permissions.ts
  • src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts
  • src/main/runtime/orchestration/db/dispatch-capability-hash.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-capability.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-completion.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts
  • src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts
  • src/main/runtime/orchestration/db/federated-worker-report-outcome.test.ts
  • src/main/runtime/orchestration/db/federated-worker-report-outcome.ts
  • src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-ack.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-import.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-item.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts
  • src/main/runtime/orchestration/db/federation/remote-question-store.ts
  • src/main/runtime/orchestration/db/generated-id.ts
  • src/main/runtime/orchestration/db/legacy-question-identity.test.ts
  • src/main/runtime/orchestration/db/legacy-question-identity.ts
  • src/main/runtime/orchestration/db/legacy/legacy-ask-operation.ts
  • src/main/runtime/orchestration/db/legacy/legacy-compatibility-candidates.ts
  • src/main/runtime/orchestration/db/legacy/legacy-compatibility-principals.ts
  • src/main/runtime/orchestration/db/legacy/legacy-lifecycle-operation.ts
  • src/main/runtime/orchestration/db/legacy/legacy-mail-acknowledge.ts
  • src/main/runtime/orchestration/db/legacy/legacy-question-acknowledge.ts
  • src/main/runtime/orchestration/db/legacy/legacy-question-lookup.ts
  • src/main/runtime/orchestration/db/legacy/legacy-recovery-cohort.ts
  • src/main/runtime/orchestration/db/legacy/legacy-reply-operation.ts
  • src/main/runtime/orchestration/db/legacy/legacy-worker-completion.ts
  • src/main/runtime/orchestration/db/lifecycle-rejection-marker.test.ts
  • src/main/runtime/orchestration/db/lifecycle-rejection-marker.ts
  • src/main/runtime/orchestration/db/messages/direct-mailbox-routing.ts
  • src/main/runtime/orchestration/db/messages/foreign-direct-mailbox-routing.ts
  • src/main/runtime/orchestration/db/messages/mailbox-routing-page.ts
  • src/main/runtime/orchestration/db/messages/message-inbox.ts
  • src/main/runtime/orchestration/db/messages/message-insert.ts
  • src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.ts
  • src/main/runtime/orchestration/db/orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/orchestration-db.ts
  • src/main/runtime/orchestration/db/pane-key-match.test.ts
  • src/main/runtime/orchestration/db/pane-key-match.ts
  • src/main/runtime/orchestration/db/questions/question-threads.ts
  • src/main/runtime/orchestration/db/reset/orchestration-reset.ts
  • src/main/runtime/orchestration/db/run-list-cursor.test.ts
  • src/main/runtime/orchestration/db/run-list-cursor.ts
  • src/main/runtime/orchestration/db/run-list-page.ts
  • src/main/runtime/orchestration/db/runs/legacy-coordinator-mail-takeover.ts
  • src/main/runtime/orchestration/db/runs/run-binding.ts
  • src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts
  • src/main/runtime/orchestration/db/runs/run-create.ts
  • src/main/runtime/orchestration/db/runs/run-delivery.ts
  • src/main/runtime/orchestration/db/runs/run-lookup.ts
  • src/main/runtime/orchestration/db/schema/adopt-legacy-run.ts
  • src/main/runtime/orchestration/db/schema/backfill-legacy-question-threads.ts
  • src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts
  • src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts
  • src/main/runtime/orchestration/db/schema/create-tables.ts
  • src/main/runtime/orchestration/db/schema/migrate-legacy-contract-storage.ts
  • src/main/runtime/orchestration/db/schema/migrate-v13-v27.ts
  • src/main/runtime/orchestration/db/schema/migrate-v2-v12.ts
  • src/main/runtime/orchestration/db/schema/migrate.ts
  • src/main/runtime/orchestration/db/schema/schema-column-probes.ts
  • src/main/runtime/orchestration/db/tasks/task-store.ts
  • src/main/runtime/orchestration/db/utc-timestamp.ts
  • src/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-authority.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-outcome.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stage.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stop.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts
💤 Files with no reviewable changes (1)
  • config/max-lines-baseline.txt

Included review availability: Your plan includes up to 10 reviews per rolling hour; 4 remain after this review.

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai Fixing. Will be in the next commit

@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Thanks. I will check the update after the next commit.

You are interacting with an AI system.

Add status guards to UPDATE statements to prevent late operations from
overwriting changes made by concurrent requests. Validate mutation results
to surface silent no-ops. Extract circuit-break threshold, add transaction
wrapping, and sanitize untrusted input. Bump schema version to v28.
Wrap dispatch failures and batched message updates with SAVEPOINTs to
ensure atomicity and idempotency:
- Dispatch failures now check status guards and roll back if the
  related task update fails, preventing partial state corruption
- Message batches (across multiple 500-id chunks) roll back entirely
  if any batch fails, avoiding partial mutations
- Add tests verifying idempotency and atomicity under failure conditions
@AmethystLiang
AmethystLiang force-pushed the split-orchestration-db branch from 54d4117 to a2c03c3 Compare August 17, 2026 04:38
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/main/runtime/orchestration/db/reset/orchestration-reset.ts (1)

6-15: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Guard the ROLLBACK so it cannot mask the original error.

If COMMIT fails, SQLite may already have rolled the transaction back. this.db.exec('ROLLBACK') then throws cannot rollback - no transaction is active, and that error replaces the real failure. Wrap the rollback in its own try.

♻️ Proposed hardening
   } catch (error) {
-    this.db.exec('ROLLBACK')
+    try {
+      this.db.exec('ROLLBACK')
+    } catch {
+      // transaction already rolled back by SQLite
+    }
     throw error
   }
src/main/runtime/orchestration/db/schema/migrate-legacy-contract-storage.ts (1)

108-118: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Stream rows without adding a nested transaction. Replace .all(runId) with .iterate(runId) to avoid loading all payloads into memory. The enclosing BEGIN IMMEDIATE already batches the updates.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 069deed2-3dd6-42c7-8d9b-eb263a303e02

📥 Commits

Reviewing files that changed from the base of the PR and between 71bbab7 and a2c03c3.

📒 Files selected for processing (88)
  • config/max-lines-baseline.txt
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/contract-constants.ts
  • src/main/runtime/orchestration/db/coordinator-runs/coordinator-run-store.ts
  • src/main/runtime/orchestration/db/database-file-permissions.ts
  • src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts
  • src/main/runtime/orchestration/db/dispatch-capability-hash.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-capability.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-circuit-breaker.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-completion.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts
  • src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts
  • src/main/runtime/orchestration/db/federated-worker-report-outcome.test.ts
  • src/main/runtime/orchestration/db/federated-worker-report-outcome.ts
  • src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-ack.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-import.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-item.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts
  • src/main/runtime/orchestration/db/federation/remote-question-store.ts
  • src/main/runtime/orchestration/db/generated-id.ts
  • src/main/runtime/orchestration/db/legacy-question-identity.test.ts
  • src/main/runtime/orchestration/db/legacy-question-identity.ts
  • src/main/runtime/orchestration/db/legacy/legacy-ask-operation.ts
  • src/main/runtime/orchestration/db/legacy/legacy-compatibility-candidates.ts
  • src/main/runtime/orchestration/db/legacy/legacy-compatibility-principals.ts
  • src/main/runtime/orchestration/db/legacy/legacy-lifecycle-operation.ts
  • src/main/runtime/orchestration/db/legacy/legacy-mail-acknowledge.ts
  • src/main/runtime/orchestration/db/legacy/legacy-question-acknowledge.ts
  • src/main/runtime/orchestration/db/legacy/legacy-question-lookup.ts
  • src/main/runtime/orchestration/db/legacy/legacy-recovery-cohort.ts
  • src/main/runtime/orchestration/db/legacy/legacy-reply-operation.ts
  • src/main/runtime/orchestration/db/legacy/legacy-worker-completion.ts
  • src/main/runtime/orchestration/db/lifecycle-rejection-marker.test.ts
  • src/main/runtime/orchestration/db/lifecycle-rejection-marker.ts
  • src/main/runtime/orchestration/db/messages/direct-mailbox-routing.ts
  • src/main/runtime/orchestration/db/messages/foreign-direct-mailbox-routing.ts
  • src/main/runtime/orchestration/db/messages/mailbox-routing-page.ts
  • src/main/runtime/orchestration/db/messages/message-inbox.ts
  • src/main/runtime/orchestration/db/messages/message-insert.ts
  • src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.ts
  • src/main/runtime/orchestration/db/orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/orchestration-db.ts
  • src/main/runtime/orchestration/db/pane-key-match.test.ts
  • src/main/runtime/orchestration/db/pane-key-match.ts
  • src/main/runtime/orchestration/db/questions/question-threads.ts
  • src/main/runtime/orchestration/db/reset/orchestration-reset.ts
  • src/main/runtime/orchestration/db/run-list-cursor.test.ts
  • src/main/runtime/orchestration/db/run-list-cursor.ts
  • src/main/runtime/orchestration/db/run-list-page.ts
  • src/main/runtime/orchestration/db/runs/legacy-coordinator-mail-takeover.ts
  • src/main/runtime/orchestration/db/runs/run-binding.ts
  • src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts
  • src/main/runtime/orchestration/db/runs/run-create.ts
  • src/main/runtime/orchestration/db/runs/run-delivery.ts
  • src/main/runtime/orchestration/db/runs/run-lookup.ts
  • src/main/runtime/orchestration/db/schema/adopt-legacy-run.ts
  • src/main/runtime/orchestration/db/schema/backfill-legacy-question-threads.ts
  • src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts
  • src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts
  • src/main/runtime/orchestration/db/schema/create-tables.ts
  • src/main/runtime/orchestration/db/schema/migrate-legacy-contract-storage.ts
  • src/main/runtime/orchestration/db/schema/migrate-v13-v28.ts
  • src/main/runtime/orchestration/db/schema/migrate-v2-v12.ts
  • src/main/runtime/orchestration/db/schema/migrate.ts
  • src/main/runtime/orchestration/db/schema/schema-column-probes.ts
  • src/main/runtime/orchestration/db/tasks/task-store.ts
  • src/main/runtime/orchestration/db/utc-timestamp.ts
  • src/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-authority.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-outcome.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stage.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stop.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts
  • src/main/runtime/orchestration/dispatch-failure-idempotency.test.ts
  • src/main/runtime/orchestration/message-batch-atomicity.test.ts
💤 Files with no reviewable changes (1)
  • config/max-lines-baseline.txt
🚧 Files skipped from review as they are similar to previous changes (74)
  • src/main/runtime/orchestration/db/federated-worker-report-outcome.ts
  • src/main/runtime/orchestration/db/legacy-question-identity.test.ts
  • src/main/runtime/orchestration/db/dispatch-capability-hash.ts
  • src/main/runtime/orchestration/db/generated-id.ts
  • src/main/runtime/orchestration/db/lifecycle-rejection-marker.test.ts
  • src/main/runtime/orchestration/db/pane-key-match.ts
  • src/main/runtime/orchestration/db/messages/mailbox-routing-page.ts
  • src/main/runtime/orchestration/db/run-list-cursor.ts
  • src/main/runtime/orchestration/db/database-file-permissions.ts
  • src/main/runtime/orchestration/db/messages/message-insert.ts
  • src/main/runtime/orchestration/db/contract-constants.ts
  • src/main/runtime/orchestration/db/federated-worker-report-outcome.test.ts
  • src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts
  • src/main/runtime/orchestration/db/run-list-page.ts
  • src/main/runtime/orchestration/db/orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/pane-key-match.test.ts
  • src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts
  • src/main/runtime/orchestration/db/coordinator-runs/coordinator-run-store.ts
  • src/main/runtime/orchestration/db/legacy/legacy-worker-completion.ts
  • src/main/runtime/orchestration/db/legacy/legacy-lifecycle-operation.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-outcome.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-import.ts
  • src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/runs/legacy-coordinator-mail-takeover.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-capability.ts
  • src/main/runtime/orchestration/db/legacy-question-identity.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts
  • src/main/runtime/orchestration/db/runs/run-create.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts
  • src/main/runtime/orchestration/db/legacy/legacy-recovery-cohort.ts
  • src/main/runtime/orchestration/db/orchestration-db.ts
  • src/main/runtime/orchestration/db/messages/foreign-direct-mailbox-routing.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts
  • src/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts
  • src/main/runtime/orchestration/db/utc-timestamp.ts
  • src/main/runtime/orchestration/db/legacy/legacy-ask-operation.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts
  • src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.ts
  • src/main/runtime/orchestration/db/schema/backfill-legacy-question-threads.ts
  • src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-ack.ts
  • src/main/runtime/orchestration/db/runs/run-binding.ts
  • src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts
  • src/main/runtime/orchestration/db/runs/run-delivery.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts
  • src/main/runtime/orchestration/db/schema/adopt-legacy-run.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts
  • src/main/runtime/orchestration/db/lifecycle-rejection-marker.ts
  • src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.ts
  • src/main/runtime/orchestration/db/legacy/legacy-reply-operation.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stage.ts
  • src/main/runtime/orchestration/db/schema/schema-column-probes.ts
  • src/main/runtime/orchestration/db/tasks/task-store.ts
  • src/main/runtime/orchestration/db/messages/message-inbox.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts
  • src/main/runtime/orchestration/db/runs/run-lookup.ts
  • src/main/runtime/orchestration/db/legacy/legacy-question-lookup.ts
  • src/main/runtime/orchestration/db/run-list-cursor.test.ts
  • src/main/runtime/orchestration/db/legacy/legacy-mail-acknowledge.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts
  • src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts
  • src/main/runtime/orchestration/db/messages/direct-mailbox-routing.ts
  • src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts
  • src/main/runtime/orchestration/db/questions/question-threads.ts
  • src/main/runtime/orchestration/db/schema/migrate.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stop.ts
  • src/main/runtime/orchestration/db/federation/federation-relay-item.ts
  • src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.ts
  • src/main/runtime/orchestration/db/legacy/legacy-compatibility-candidates.ts
  • src/main/runtime/orchestration/db/legacy/legacy-compatibility-principals.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai Fixing. Will be in the next commit

@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Thanks. I will review the fix after the next commit.

You are interacting with an AI system.

- Remote question answering: add classification check before and after UPDATE to safely detect concurrent modifications. Prevents false success when the UPDATE loses a race.
- Transaction rollback: wrap in try-catch to prevent errors from masking the original failure.
- Question thread reset: use status update instead of deletion to preserve message references.
Add test cases for answer replay idempotency, conflict detection, and a race condition between concurrent answer updates in federation relay. Also verify local question state transitions during orchestration reset.
@AmethystLiang
AmethystLiang merged commit 81d7f9b into main Aug 17, 2026
2 of 45 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
* refactor: split db.ts under 400 lines

* rm plan

* fix(orchestration-db): add safety guards to database operations

Add status guards to UPDATE statements to prevent late operations from
overwriting changes made by concurrent requests. Validate mutation results
to surface silent no-ops. Extract circuit-break threshold, add transaction
wrapping, and sanitize untrusted input. Bump schema version to v28.

* Add transactional safety to dispatch and message operations

Wrap dispatch failures and batched message updates with SAVEPOINTs to
ensure atomicity and idempotency:
- Dispatch failures now check status guards and roll back if the
  related task update fails, preventing partial state corruption
- Message batches (across multiple 500-id chunks) roll back entirely
  if any batch fails, avoiding partial mutations
- Add tests verifying idempotency and atomicity under failure conditions

* Handle concurrent writes and improve transactional safety

- Remote question answering: add classification check before and after UPDATE to safely detect concurrent modifications. Prevents false success when the UPDATE loses a race.
- Transaction rollback: wrap in try-catch to prevent errors from masking the original failure.
- Question thread reset: use status update instead of deletion to preserve message references.

* test: add answer replay and race condition edge case coverage

Add test cases for answer replay idempotency, conflict detection, and a race condition between concurrent answer updates in federation relay. Also verify local question state transitions during orchestration reset.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* refactor: split db.ts under 400 lines

* rm plan

* fix(orchestration-db): add safety guards to database operations

Add status guards to UPDATE statements to prevent late operations from
overwriting changes made by concurrent requests. Validate mutation results
to surface silent no-ops. Extract circuit-break threshold, add transaction
wrapping, and sanitize untrusted input. Bump schema version to v28.

* Add transactional safety to dispatch and message operations

Wrap dispatch failures and batched message updates with SAVEPOINTs to
ensure atomicity and idempotency:
- Dispatch failures now check status guards and roll back if the
  related task update fails, preventing partial state corruption
- Message batches (across multiple 500-id chunks) roll back entirely
  if any batch fails, avoiding partial mutations
- Add tests verifying idempotency and atomicity under failure conditions

* Handle concurrent writes and improve transactional safety

- Remote question answering: add classification check before and after UPDATE to safely detect concurrent modifications. Prevents false success when the UPDATE loses a race.
- Transaction rollback: wrap in try-catch to prevent errors from masking the original failure.
- Question thread reset: use status update instead of deletion to preserve message references.

* test: add answer replay and race condition edge case coverage

Add test cases for answer replay idempotency, conflict detection, and a race condition between concurrent answer updates in federation relay. Also verify local question state transitions during orchestration reset.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant