Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): surface the cause behind a persistence SQL error #4837

ClosedSy-D(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/4837/headopened View on GitHub

What Changed

toPersistenceSqlError no longer restates the operation as the detail. It carries a payload-safe description of the actual cause instead.

Why

Reported in #4818. The screenshot there reads:

SQL error in OrchestrationCommandReceiptRepository.upsert:query: Failed to execute OrchestrationCommandReceiptRepository.upsert:query

The operation name twice, and nothing else. PersistenceSqlError.message composes SQL error in ${operation}: ${detail}, and the mapper set detail to Failed to execute ${operation}. The real failure was captured in cause and never rendered.

Errors.test.ts already asserts this intent, in a test named "keeps SQL operation context without a tautological detail" — it builds the error without a detail and expects SQL error in AuthSessionRepository.list:query. toPersistenceSqlError was the path that did not honour it.

Notes For Review

This does not fix the SQL failure in #4818. It makes it identifiable. The upsert that failed there runs inside withTransaction in OrchestrationEngine.ts:190, so SQLITE_BUSY is plausible — and so is a Request schema encode failure, which this mapper would have labelled a "SQL error" despite not being one. Those want opposite fixes and today's message cannot tell them apart, which is presumably why the issue is filed as not reproducible.

On the payload rule. The neighbouring test "maps schema errors without copying rejected payloads into diagnostics" establishes that rejected values must not reach diagnostics, so the cause is not copied blindly:

  • a schema failure contributes summarizeSchemaIssue, which emits issue tags only,
  • a driver failure contributes its own message, which names the SQLite condition and at most the constraint it violated, never a bound value,
  • anything else leaves the detail unset, which message already renders cleanly.

A new test asserts a rejected value cannot appear in the message.

Blast radius. This mapper shapes every persistence error message that goes through it. The diff is small, the effect is broad — that is the point, but it is worth a deliberate look.

Follow-up, deliberately not in this PR. Newer call sites (AuthPairingLinks.ts:112) route a schema cause to PersistenceDecodeError rather than labelling it a SQL error, which is the better shape. The comment above toPersistenceDecodeError notes these call sites are "being revamped separately", so I left the routing alone and only fixed the message.

Validation

  • vp run --filter t3 test — 1690 passed, 7 skipped. No existing test depended on the old tautological detail.
  • vp run --filter t3 typecheck — no errors
  • vp lint / vp fmt --check on the changed files — clean

New cases in Errors.test.ts:

causeresulting message
Error("SQLITE_BUSY: database is locked")SQL error in …upsert:query: SQLITE_BUSY: database is locked
schema errorissue tags only; asserts the rejected value is absent
a value with no messageSQL error in …list:query (unchanged)

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • No UI change, so no screenshots

Note

Medium Risk The mapper shapes every persistence SQL error message site-wide; behavior changes are intentional but broad, with privacy-sensitive formatting rules that must stay correct.

Overview Fixes tautological persistence SQL error messages (operation repeated twice with no real failure hint) by changing how toPersistenceSqlError sets detail.

Instead of always using Failed to execute <operation>, it now derives detail from the cause when it can do so safely: SQLite failures get a normalized SQLITE(<errcode>) <errstr> string by walking up to four levels of the cause chain (so wrapped driver errors still work), without copying the driver’s unbounded constraint text into message. Schema causes routed through this mapper get issue tags via summarizeSchemaIssue, not rejected values. Unrecognized causes leave detail unset so message stays SQL error in <operation>.

New tests in Errors.test.ts lock in normalized SQLite details, nested causes, omission of column/table prose from messages, and schema paths that must not leak sentinel payload strings.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 7b41332e5771f9f6d88351aa2d2411a044bd01d7. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Surface SQLite condition and schema issue details in toPersistenceSqlError

  • toPersistenceSqlError in Errors.ts now derives detail from the error cause instead of always setting 'Failed to execute <operation>'.
  • A new sqliteCondition helper walks up to four levels of the cause chain to find errcode/errstr properties and returns a normalized string like 'SQLITE(1555) constraint failed'.
  • A new describeSqlCause helper categorizes the cause: SQLite errors get the normalized condition string; Schema errors get a summary via issue tag; uncategorizable causes result in detail being omitted entirely.
  • Behavioral Change: detail on persistence SQL errors changes from the fixed string 'Failed to execute <operation>' to a normalized SQLite condition, a schema issue tag, or undefined.
Macroscope summarized 7b41332.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 209783da-9274-4582-a73b-01c07ae5ab05

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      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.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. Reviewed against the Effect service conventions. One violation found in apps/server/src/persistence/Errors.ts (with a test that locks in the behavior): the mapper now copies cause.message into the structural detail attribute, and PersistenceSqlError.message is built from that detail.

      Posted via Macroscope — Effect Service Conventions
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Approved 9ff106f

      This PR improves error message content in persistence SQL errors by surfacing SQLite error codes and schema issue summaries. The changes are limited to diagnostic output with no control flow impact, and include thorough test coverage.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. Both points taken, fixed in 9ff106f2d — and the second suggestion turned out to be the better design, so I took that rather than dropping the SQL side entirely.

      Limiting detail to the schema summary alone would have left a real SQLite failure with an operation-only message, which is the state #4818 is stuck in. Your alternative — a bounded normalized code — keeps the diagnosis without the unbounded text.

      SQLite names its condition through a fixed result-code table, and node:sqlite exposes it as errcode / errstr. Both are bounded and carry no query data, unlike the message. Checked against a real failure:

      message : UNIQUE constraint failed: t.a          <- driver prose, names the column
      errcode : 1555
      errstr  : constraint failed                       <- fixed table, value-free

      So describeSqlCause now contributes:

      • schema failure → summarizeSchemaIssue, issue tags only, unchanged
      • driver failure → SQLITE(<errcode>) <errstr>, read through the wrapping error since the mapper receives the SqlError
      • anything else → nothing, leaving the operation-only message

      Verified end to end against a genuine node:sqlite constraint violation on a table holding a sentinel value:

      message : SQL error in OrchestrationCommandReceiptRepository.upsert:query: SQLITE(1555) constraint failed
      detail  : SQLITE(1555) constraint failed
      sentinel present in message? false
      cause preserved? true

      On the test comment: the assertion on spliced driver text is gone. The suite now asserts structural attributes — the exact detail, the preserved cause, that the driver's column name cannot reach the message, and that an uncategorizable cause leaves detail unset.

      vp run --filter t3 test — 1692 passed, 7 skipped. Typecheck and lint clean.

    6. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fbb2ec7ddb1afb87928a859a92bddc6a70b45396. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -73,3 +73,19 @@
      7373 const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
      7474
      7575 // Kept for orchestration/projection call sites, which are being revamped separately.
      76+/**
      77+ * SQLite names its condition through a fixed result-code table, so the code and
      78+ * its canonical string are bounded and carry no query data. The driver message
      79+ * is not bounded: a constraint failure spells out the table and column it hit.
      80+ * Only the normalized pair is carried here; `cause` keeps everything else.
      81+ */
      82+function sqliteCondition(cause: unknown): string | undefined {
      83+ let value: unknown = cause;
      84+ for (let depth = 0; depth < 4 && typeof value === "object" && value !== null; depth += 1) {
      85+ const { errcode, errstr } = value as { errcode?: unknown; errstr?: unknown };
      86+ if (typeof errcode === "number" && typeof errstr === "string") {
      87+ return `SQLITE(${errcode}) ${errstr}`;
      88+ }
      89+ value = (value as { cause?: unknown }).cause;
      90+ }
      91+ return undefined;

      SqlError reason not traversed

      High Severity

      sqliteCondition only walks the .cause chain, but the Node SQLite client wraps driver failures as SqlError with reason: classifySqliteError(...) and does not pass the raw driver as cause. When PersistenceSqlError is built from that SqlError, describeSqlCause may find no errcode/errstr, leave detail unset, and #4818-style upsert failures can still show an operation-only message.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fbb2ec7ddb1afb87928a859a92bddc6a70b45396. Configure [here](https://www.cursor.com/dashboard/bugbot).
    7. Checked this against the real construction, and the conclusion does not hold — though the premise is a fair read of the code.

      NodeSqliteClient does build the error as described, with only a reason:

      catch: (cause) => new SqlError({ reason: classifySqliteError(cause, { message: "...", operation: "prepare" }) })

      But Effect's SqlError exposes a cause derived from that reason, and the classified reason keeps the driver error as its cause. So the chain SqlError → reason → driver error is walkable, which is what sqliteCondition does.

      Built that exact shape and ran it through the mapper:

      classifySqliteError exportiert? function
      hat .cause?               true
      hat .reason?              true
      reason.cause vorhanden?   true
      detail : SQLITE(1555) constraint failed

      Across the failure kinds an upsert can realistically hit:

      failuredetaildriver prose leaked?
      UNIQUE violationSQLITE(1555) constraint failedno
      NOT NULL violationSQLITE(1299) constraint failedno
      syntax errorSQLITE(1) SQL logic errorno
      missing tableSQLITE(1) SQL logic errorno
      missing columnSQLITE(1) SQL logic errorno

      So a #4818-style upsert failure does get a categorized detail rather than an operation-only message, which is the outcome the review was worried about.

      The walk is bounded at four levels of cause. If a future client wraps more deeply than that, the detail would fall back to unset — that is the intended failure mode, not silence about a value.

    8. Note

      🤖 GPT-6 Astra (preview) responding on behalf of Theo

      Merged replacement #9536. It retains the original fix, adds the missing Bun SQLite error codes, and tests the real SQL client. The squash commit credits @Sy-D and preserves the original co-author trailer.

      Verified database-lock and schema failures through the receipt repository in Node and Bun. CI passed and review findings are resolved. This improves diagnosis. It does not fix the underlying failure in issue #4818.

Sign in to join this conversation.