Repository navigation
refactor: split db.ts under 400 lines - #14979
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughAdds 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)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
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 valueAlias the UNION column so the row type matches the query.
The
UNIONresult takes its column name from the firstSELECT, sofrom_handlevalues arrive under theto_handlekey. 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:
UNIONalready removes duplicates, so the extraSetis redundant.src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.ts (1)
89-109: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winConsider guarding the completion update on the
pendingstate.The
UPDATEmatches any row with the same caller, request, method, and payload hash. A second call for an alreadycompletedreceipt overwrites the storedreceiptbody. A retried request would then observe a different response than the first completion returned. AddingAND state = 'pending'keeps the first recorded receipt authoritative, and the existingchanges !== 1check converts the repeat call intorequest_mismatch.If callers already short-circuit on the
completeddisposition frombeginMutationReceipt, 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 winGate lifecycle transitions write multiple tables without a transaction. Both functions update
decision_gatesandtasks(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 ascreateQuestioninsrc/main/runtime/orchestration/db/questions/question-threads.ts, wrap the same class of transition inBEGIN IMMEDIATEwith aROLLBACKhandler.
src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts#L8-L30: wrap the gate insert,completeActiveDispatchForTask, and theblockedtask update in oneBEGIN IMMEDIATEblock.src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts#L32-L56: wrap theresolvedgate update and thereadytask update in oneBEGIN IMMEDIATEblock.Confirm first that
completeActiveDispatchForTaskand the callers of these functions do not already hold a transaction, because SQLite rejects nestedBEGIN.src/main/runtime/orchestration/db/legacy/legacy-lifecycle-operation.ts (1)
143-152: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueFlatten 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' + : undefinedsrc/main/runtime/orchestration/db/legacy/legacy-question-lookup.ts (1)
71-97: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueReuse the fetched message and hoist the acknowledgement statement.
row.source_message_idandrow.message_idhold the same value, because the join condition ism.id = q.message_id. Each surviving row therefore callsgetMessageByIdtwice. The acknowledgement probe also callsprepareonce 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 winPreserve the original payload when it is not a JSON object.
src/main/runtime/orchestration/db/messages/message-inbox.tsLines 36-59 writes this result back intomessages.payload. For an array payload, a scalar payload, or invalid JSON,parsedstays 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 liftUnconditional
ROLLBACKin the catch block can discard a caller's transaction. Four methods open a transaction withthis.db.exec('BEGIN IMMEDIATE')and roll back unconditionally in the catch block. SQLite rejects a nestedBEGIN, so a call made inside an existing transaction throws at theBEGINline, 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 theBEGIN IMMEDIATEincommitLegacyCompatibilityPrincipal, 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 inacknowledgeLegacyMail, 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 inacknowledgeLegacyQuestionAnswer, whose catch block rolls back at line 87.src/main/runtime/orchestration/db/runs/run-binding.ts#L23-L23: apply the same ownership guard inbindRun, 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 winAlign the module and function name with the highest handled version.
The gate at line 146 handles version 28, but the function is named
applySchemaMigrationsV13ToV27and the file ismigrate-v13-v27.ts. The name states the range contract for the next migration author. Rename both to cover v28, or move themutation_caller_identitiesgate 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 winStream 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 nativeStatementSync, which providesiterate().src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts (1)
54-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove 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 winExtract the shared active-dispatch lookup.
completeActiveDispatchForTaskandfailActiveDispatchForTaskrun 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) : undefinedsrc/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts (1)
44-52: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAvoid the parse and re-stringify round trip for
effectsandresidual_resources.When
params.effectsis 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.parsealso throws if the column holds malformed JSON, which aborts an otherwise valid reconcile.Use
COALESCEin SQL and bindnullinstead.♻️ 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 winRemove 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 winAdd a state guard to the worker update.
This update matches on
dispatch_idalone. 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 winWrap the read-then-write stage update in a transaction.
recordRemoteAttachmentStagereads 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 changesstate,last_error, oreffectsbetween the read and the write loses that change.updateRemoteAttachmentSetupEvidenceat Lines 139-156 has the same shape.Two options exist. Run both statements inside
BEGIN IMMEDIATElikecreateRemoteDispatchAttachmentdoes, 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 winReuse
WORKER_SETTLED_STATESand drop the unused JOIN.Two points apply here.
The settled-state list at Lines 49-50 duplicates
WORKER_SETTLED_STATES, whichworker-terminal-release.tsimports from../../worker-terminal-ownership. The literal can drift from the shared constant. Import the constant instead.The JOIN on
worker_dispatchesat Line 22 selects no column fromwand applies no predicate onw. The eligibility check at Line 50 already loads the owning dispatch. If more than oneworker_dispatchesrow shares anowner_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
📒 Files selected for processing (85)
config/max-lines-baseline.txtsrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/db/attach-orchestration-db-methods.tssrc/main/runtime/orchestration/db/contract-constants.tssrc/main/runtime/orchestration/db/coordinator-runs/coordinator-run-store.tssrc/main/runtime/orchestration/db/database-file-permissions.tssrc/main/runtime/orchestration/db/decision-gates/decision-gate-store.tssrc/main/runtime/orchestration/db/dispatch-capability-hash.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-capability.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-completion.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.tssrc/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.tssrc/main/runtime/orchestration/db/federated-worker-report-outcome.test.tssrc/main/runtime/orchestration/db/federated-worker-report-outcome.tssrc/main/runtime/orchestration/db/federation/federated-dispatch-store.tssrc/main/runtime/orchestration/db/federation/federation-relay-ack.tssrc/main/runtime/orchestration/db/federation/federation-relay-enqueue.tssrc/main/runtime/orchestration/db/federation/federation-relay-import.tssrc/main/runtime/orchestration/db/federation/federation-relay-item.tssrc/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.tssrc/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.tssrc/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.tssrc/main/runtime/orchestration/db/federation/remote-question-store.tssrc/main/runtime/orchestration/db/generated-id.tssrc/main/runtime/orchestration/db/legacy-question-identity.test.tssrc/main/runtime/orchestration/db/legacy-question-identity.tssrc/main/runtime/orchestration/db/legacy/legacy-ask-operation.tssrc/main/runtime/orchestration/db/legacy/legacy-compatibility-candidates.tssrc/main/runtime/orchestration/db/legacy/legacy-compatibility-principals.tssrc/main/runtime/orchestration/db/legacy/legacy-lifecycle-operation.tssrc/main/runtime/orchestration/db/legacy/legacy-mail-acknowledge.tssrc/main/runtime/orchestration/db/legacy/legacy-question-acknowledge.tssrc/main/runtime/orchestration/db/legacy/legacy-question-lookup.tssrc/main/runtime/orchestration/db/legacy/legacy-recovery-cohort.tssrc/main/runtime/orchestration/db/legacy/legacy-reply-operation.tssrc/main/runtime/orchestration/db/legacy/legacy-worker-completion.tssrc/main/runtime/orchestration/db/lifecycle-rejection-marker.test.tssrc/main/runtime/orchestration/db/lifecycle-rejection-marker.tssrc/main/runtime/orchestration/db/messages/direct-mailbox-routing.tssrc/main/runtime/orchestration/db/messages/foreign-direct-mailbox-routing.tssrc/main/runtime/orchestration/db/messages/mailbox-routing-page.tssrc/main/runtime/orchestration/db/messages/message-inbox.tssrc/main/runtime/orchestration/db/messages/message-insert.tssrc/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.tssrc/main/runtime/orchestration/db/orchestration-db-methods.tssrc/main/runtime/orchestration/db/orchestration-db.tssrc/main/runtime/orchestration/db/pane-key-match.test.tssrc/main/runtime/orchestration/db/pane-key-match.tssrc/main/runtime/orchestration/db/questions/question-threads.tssrc/main/runtime/orchestration/db/reset/orchestration-reset.tssrc/main/runtime/orchestration/db/run-list-cursor.test.tssrc/main/runtime/orchestration/db/run-list-cursor.tssrc/main/runtime/orchestration/db/run-list-page.tssrc/main/runtime/orchestration/db/runs/legacy-coordinator-mail-takeover.tssrc/main/runtime/orchestration/db/runs/run-binding.tssrc/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.tssrc/main/runtime/orchestration/db/runs/run-create.tssrc/main/runtime/orchestration/db/runs/run-delivery.tssrc/main/runtime/orchestration/db/runs/run-lookup.tssrc/main/runtime/orchestration/db/schema/adopt-legacy-run.tssrc/main/runtime/orchestration/db/schema/backfill-legacy-question-threads.tssrc/main/runtime/orchestration/db/schema/create-core-tables-sql.tssrc/main/runtime/orchestration/db/schema/create-graph-tables-sql.tssrc/main/runtime/orchestration/db/schema/create-tables.tssrc/main/runtime/orchestration/db/schema/migrate-legacy-contract-storage.tssrc/main/runtime/orchestration/db/schema/migrate-v13-v27.tssrc/main/runtime/orchestration/db/schema/migrate-v2-v12.tssrc/main/runtime/orchestration/db/schema/migrate.tssrc/main/runtime/orchestration/db/schema/schema-column-probes.tssrc/main/runtime/orchestration/db/tasks/task-store.tssrc/main/runtime/orchestration/db/utc-timestamp.tssrc/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-authority.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-outcome.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stage.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stop.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.tssrc/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.
|
@coderabbitai Fixing. Will be in the next commit |
|
Tip For best results, initiate chat on the files or code changes.
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
54d4117 to
a2c03c3
Compare
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
src/main/runtime/orchestration/db/reset/orchestration-reset.ts (1)
6-15: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winGuard the
ROLLBACKso it cannot mask the original error.If
COMMITfails, SQLite may already have rolled the transaction back.this.db.exec('ROLLBACK')then throwscannot rollback - no transaction is active, and that error replaces the real failure. Wrap the rollback in its owntry.♻️ 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 winStream rows without adding a nested transaction. Replace
.all(runId)with.iterate(runId)to avoid loading all payloads into memory. The enclosingBEGIN IMMEDIATEalready batches the updates.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 069deed2-3dd6-42c7-8d9b-eb263a303e02
📒 Files selected for processing (88)
config/max-lines-baseline.txtsrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/db/attach-orchestration-db-methods.tssrc/main/runtime/orchestration/db/contract-constants.tssrc/main/runtime/orchestration/db/coordinator-runs/coordinator-run-store.tssrc/main/runtime/orchestration/db/database-file-permissions.tssrc/main/runtime/orchestration/db/decision-gates/decision-gate-store.tssrc/main/runtime/orchestration/db/dispatch-capability-hash.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-capability.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-circuit-breaker.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-completion.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.tssrc/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.tssrc/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.tssrc/main/runtime/orchestration/db/federated-worker-report-outcome.test.tssrc/main/runtime/orchestration/db/federated-worker-report-outcome.tssrc/main/runtime/orchestration/db/federation/federated-dispatch-store.tssrc/main/runtime/orchestration/db/federation/federation-relay-ack.tssrc/main/runtime/orchestration/db/federation/federation-relay-enqueue.tssrc/main/runtime/orchestration/db/federation/federation-relay-import.tssrc/main/runtime/orchestration/db/federation/federation-relay-item.tssrc/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.tssrc/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.tssrc/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.tssrc/main/runtime/orchestration/db/federation/remote-question-store.tssrc/main/runtime/orchestration/db/generated-id.tssrc/main/runtime/orchestration/db/legacy-question-identity.test.tssrc/main/runtime/orchestration/db/legacy-question-identity.tssrc/main/runtime/orchestration/db/legacy/legacy-ask-operation.tssrc/main/runtime/orchestration/db/legacy/legacy-compatibility-candidates.tssrc/main/runtime/orchestration/db/legacy/legacy-compatibility-principals.tssrc/main/runtime/orchestration/db/legacy/legacy-lifecycle-operation.tssrc/main/runtime/orchestration/db/legacy/legacy-mail-acknowledge.tssrc/main/runtime/orchestration/db/legacy/legacy-question-acknowledge.tssrc/main/runtime/orchestration/db/legacy/legacy-question-lookup.tssrc/main/runtime/orchestration/db/legacy/legacy-recovery-cohort.tssrc/main/runtime/orchestration/db/legacy/legacy-reply-operation.tssrc/main/runtime/orchestration/db/legacy/legacy-worker-completion.tssrc/main/runtime/orchestration/db/lifecycle-rejection-marker.test.tssrc/main/runtime/orchestration/db/lifecycle-rejection-marker.tssrc/main/runtime/orchestration/db/messages/direct-mailbox-routing.tssrc/main/runtime/orchestration/db/messages/foreign-direct-mailbox-routing.tssrc/main/runtime/orchestration/db/messages/mailbox-routing-page.tssrc/main/runtime/orchestration/db/messages/message-inbox.tssrc/main/runtime/orchestration/db/messages/message-insert.tssrc/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.tssrc/main/runtime/orchestration/db/orchestration-db-methods.tssrc/main/runtime/orchestration/db/orchestration-db.tssrc/main/runtime/orchestration/db/pane-key-match.test.tssrc/main/runtime/orchestration/db/pane-key-match.tssrc/main/runtime/orchestration/db/questions/question-threads.tssrc/main/runtime/orchestration/db/reset/orchestration-reset.tssrc/main/runtime/orchestration/db/run-list-cursor.test.tssrc/main/runtime/orchestration/db/run-list-cursor.tssrc/main/runtime/orchestration/db/run-list-page.tssrc/main/runtime/orchestration/db/runs/legacy-coordinator-mail-takeover.tssrc/main/runtime/orchestration/db/runs/run-binding.tssrc/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.tssrc/main/runtime/orchestration/db/runs/run-create.tssrc/main/runtime/orchestration/db/runs/run-delivery.tssrc/main/runtime/orchestration/db/runs/run-lookup.tssrc/main/runtime/orchestration/db/schema/adopt-legacy-run.tssrc/main/runtime/orchestration/db/schema/backfill-legacy-question-threads.tssrc/main/runtime/orchestration/db/schema/create-core-tables-sql.tssrc/main/runtime/orchestration/db/schema/create-graph-tables-sql.tssrc/main/runtime/orchestration/db/schema/create-tables.tssrc/main/runtime/orchestration/db/schema/migrate-legacy-contract-storage.tssrc/main/runtime/orchestration/db/schema/migrate-v13-v28.tssrc/main/runtime/orchestration/db/schema/migrate-v2-v12.tssrc/main/runtime/orchestration/db/schema/migrate.tssrc/main/runtime/orchestration/db/schema/schema-column-probes.tssrc/main/runtime/orchestration/db/tasks/task-store.tssrc/main/runtime/orchestration/db/utc-timestamp.tssrc/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-authority.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-outcome.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stage.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-stop.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.tssrc/main/runtime/orchestration/dispatch-failure-idempotency.test.tssrc/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.
|
@coderabbitai Fixing. Will be in the next commit |
|
Tip For best results, initiate chat on the files or code changes.
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.
* 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.
* 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.
Problem
The orchestration database module in
db.tsexceeded 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:
Main
orchestration-db.tsis now 48 lines. Methods attach via mixin pattern inattach-orchestration-db-methods.ts. Transactional invariants and behavior unchanged.Testing