Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#7112): owner-exception redaction tokenizes the statement and keeps message names only from catalog templates; repair-jsonb refuses before v263

garrytanecb4243a604e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec0e92d830..fb64f4caaf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,7 +21,7 @@ identifiers and attribution are available in the pre-removal Git revision
| Managed sync, put_page with a slug-root mode, source config updates, archive/restore and the shared-skills opt-out on Postgres 15 | every statement that merges `sources.config` failed to parse (42601); the managed sync checkpoint never committed | the merge uses `gbrain_try_jsonb(text)` (migration v263), which parses on Postgres 15, 16 and 17 and PGLite |
| Doctor `jsonb_integrity` and `gbrain repair-jsonb` on Postgres 15 | `pg_input_is_valid` (Postgres 16+) failed the check | the same `gbrain_try_jsonb` guard |
| A double-encoded config or dream-breaker map whose text is JSON but not jsonb (a `\u0000` escape) | passed `IS JSON`, then the cast raised and the whole update failed, on every server | reads as an empty object, like other unparseable text |
-| A write that failed on an unexpected database error | the receipt named the class and SQLSTATE only | owner-side the receipt also keeps `error_text` (the server message, quoted values replaced by `…`), `statement` (the first line of the SQL, literals replaced, never parameters) and `position`; `gbrain write-request <id> --json` on the brain host prints `error_detail`, and the consumer log line carries the same fields |
+| A write that failed on an unexpected database error | the receipt named the class and SQLSTATE only | owner-side the receipt also keeps `error_text` (the server message; object names survive only in known catalog messages or when the statement names them, any other quoted run is replaced by `…`), `statement` (the SQL's keywords, identifiers and operators, every literal, number and comment replaced, never parameters) and `position`; `gbrain write-request <id> --json` on the brain host prints `error_detail`, and the consumer log line carries the same fields |
### What to watch for after you upgrade
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 02cdef892e..64744c0580 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -6,7 +6,7 @@
- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).
-- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never an application error's message), so `withAttempt` stamps the build; #7112: a server-generated database error (a five-character SQLSTATE and a severity, never a PL/pgSQL RAISE) also keeps `error_text` (its primary message, first line, at most 240 characters, a double-quoted token kept only after an object word such as `near`, `column` or `relation`, every other quoted run replaced by `…`), `statement` (the first line of the failing SQL, literals and dollar-quoted bodies replaced, at most 160 characters, never the parameters) and `position`, all owner-only; a trusted local `gbrain write-request <id>` returns the full `error_detail`; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`/`error_text`/`statement`/`position`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).
+- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never an application error's message), so `withAttempt` stamps the build; #7112: a server-generated database error (a five-character SQLSTATE, a severity and a routine; never a PL/pgSQL RAISE or ASSERT or another class P0 error) also keeps `error_text` (its primary message, at most 240 characters; object names survive only in a known catalog message such as a not-null violation, or a syntax-error or does-not-exist message whose name the statement holds as an identifier; any other message loses everything from its first quote to its last, because Postgres does not escape quotes inside a value) and `statement` (the failing SQL tokenized: keywords, identifiers, parameter markers and operators, with every literal, E-string, dollar-quoted body, number and comment replaced or dropped, cut at anything unrecognized, at most 160 characters, never the parameters) and `position`, all owner-only; a trusted local `gbrain write-request <id>` returns the full `error_detail`; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`/`error_text`/`statement`/`position`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).
- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Atom item completion still waits for all atoms and provenance links; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.
diff --git a/src/commands/repair-jsonb.ts b/src/commands/repair-jsonb.ts
index 49bb70f364..e762c4346f 100644
--- a/src/commands/repair-jsonb.ts
+++ b/src/commands/repair-jsonb.ts
@@ -133,6 +133,12 @@ export async function repairJsonb(opts: RepairOpts = { dryRun: false }): Promise
await db.connect(engineCfg);
const sql = db.getConnection();
+ // #7112: the jsonPayloadOnly predicate calls gbrain_try_jsonb (migration v263). This pre-connect command does not run
+ // migrations, and the per-target catch below would turn its absence into "0 rows" while damaged rows stay.
+ const [helper] = await sql.unsafe(`SELECT to_regprocedure('gbrain_try_jsonb(text)') IS NOT NULL AS installed`) as Array<{ installed: boolean }>;
+ if (!helper?.installed) {
+ throw new Error('repair-jsonb needs the gbrain_try_jsonb function from schema migration v263, which this database does not have yet. Run: gbrain apply-migrations --yes --no-autopilot-install');
+ }
// Progress on stderr only. Stdout is reserved for the JSON summary that
// migrations/v0_12_2.ts parses via JSON.parse — stray progress lines on
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 6c855ad60a..4e797abd7d 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -45,7 +45,7 @@ export type FenceRefusalDetail = FenceFailureDetail & Pick<PublicationFailureDet
* #5929: an unexpected exception in the owner. Fixed identifiers only, never
* application error text or values: the error class, its errno and the top gbrain
* source frame (repo-relative). #7112: a database server error also keeps its
- * redacted primary message, the first line of the failing statement and the
+ * redacted primary message, the failing statement with every literal replaced and the
* error position (`databaseErrorText`). All of it is owner-only.
*/
export interface OwnerExceptionDetail extends Pick<PublicationFailureDetail, 'stage' | 'attempt'> {
@@ -178,47 +178,126 @@ export const OWNER_EXCEPTION_MESSAGE = 'Publication failed on an unexpected owne
const ERROR_TEXT_MAX = 240;
const STATEMENT_MAX = 160;
-/** The words after which a server message's double-quoted token names an object (or the token a syntax error stopped at), not a value. */
-const IDENTIFIER_CONTEXT = /\b(?:near|column|relation|constraint|table|index|type|schema|function|sequence|role|database|extension|trigger|view|parameter|operator|policy|cursor|savepoint|prepared statement|portal)\s*$/i;
+const SQL_NAME = /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/;
+const SQL_TOKEN = {
+ space: /\s+/y,
+ lineComment: /--[^\n]*(?:\n|$)/y,
+ param: /\$[0-9]+/y,
+ dollar: /\$(?:[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/y,
+ number: /(?:[0-9]|\.[0-9])[0-9A-Za-z_.]*/y,
+ word: /[A-Za-z_\u0080-\uffff][A-Za-z0-9_$\u0080-\uffff]*/y,
+ punct: /[(),;.*=<>!+\-/%:[\]|&~^@#?{}]/y,
+};
/**
- * The first non-blank line with every quoted run replaced: a single-quoted literal or dollar-quoted body becomes `'…'`
- * or `$…$`, a double-quoted token stays only when `keepQuoted` says it names an object, and an unterminated quote ends
- * the text. Control characters become spaces; at most `max` characters.
+ * #7112: a SQL statement reduced to its keywords, identifiers, parameter markers and operators. Every string literal,
+ * dollar-quoted body and number becomes a placeholder, comments drop, and anything unrecognized or unterminated ends
+ * the text, so no literal value survives. `names` holds the statement's identifiers, lower-cased.
*/
-function redactLine(text: string, max: number, keepQuoted: (inner: string, before: string) => boolean): string | undefined {
- const line = text.split('\n').map(part => part.trim()).find(part => part.length > 0);
- if (!line) return undefined;
+function sqlShape(query: string): { text: string; names: Set<string> } {
+ const names = new Set<string>();
let out = '';
- for (let i = 0; i < line.length;) {
- const ch = line[i]!;
- const tag = ch === '$' ? /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(line.slice(i))?.[0] : undefined;
- if (ch !== "'" && ch !== '"' && !tag) { out += ch; i++; continue; }
- const open = tag ?? ch;
- let close = line.indexOf(open, i + open.length);
- while (!tag && close >= 0 && line[close + 1] === ch) close = line.indexOf(ch, close + 2);
- if (close < 0) { out += '…'; break; }
- const inner = line.slice(i + open.length, close);
- out += ch === '"' && keepQuoted(inner, out) ? `"${inner}"` : tag ? '$…$' : `${ch}…${ch}`;
- i = close + open.length;
+ let space = false;
+ const emit = (token: string) => { out += (space && out ? ' ' : '') + token; space = false; };
+ const at = (re: RegExp, i: number) => { re.lastIndex = i; return re.exec(query)?.[0]; };
+ let i = 0;
+ scan: while (i < query.length) {
+ const ch = query[i]!;
+ let token: string | undefined;
+ if ((token = at(SQL_TOKEN.space, i)) || (token = at(SQL_TOKEN.lineComment, i))) { space = true; i += token.length; continue; }
+ if (query.startsWith('/*', i)) {
+ let depth = 0;
+ for (let j = i; j < query.length; j++) {
+ if (query.startsWith('/*', j)) { depth++; j++; } else if (query.startsWith('*/', j)) { depth--; j++; if (depth === 0) { i = j + 1; space = true; continue scan; } }
+ }
+ break;
+ }
+ if (ch === "'") {
+ const backslash = /(?:^|[^A-Za-z0-9_$\u0080-\uffff])[eE]$/.test(query.slice(Math.max(0, i - 2), i));
+ for (let j = i + 1; j < query.length; j++) {
+ if (backslash && query[j] === '\\') { j++; continue; }
+ if (query[j] !== "'") continue;
+ if (query[j + 1] === "'") { j++; continue; }
+ emit("'…'"); i = j + 1; continue scan;
+ }
+ out += '…'; break;
+ }
+ if (ch === '"') {
+ for (let j = i + 1; j < query.length; j++) {
+ if (query[j] !== '"') continue;
+ if (query[j + 1] === '"') { j++; continue; }
+ const name = query.slice(i + 1, j).replace(/""/g, '"');
+ if (SQL_NAME.test(name)) { names.add(name.toLowerCase()); emit(`"${name}"`); } else emit('"…"');
+ i = j + 1; continue scan;
+ }
+ out += '…'; break;
+ }
+ if ((token = at(SQL_TOKEN.param, i))) { emit(token); i += token.length; continue; }
+ if ((token = at(SQL_TOKEN.dollar, i))) {
+ const close = query.indexOf(token, i + token.length);
+ if (close < 0) { out += '…'; break; }
+ emit('$…$'); i = close + token.length; continue;
+ }
+ if ((token = at(SQL_TOKEN.number, i))) { emit('?'); i += token.length; continue; }
+ if ((token = at(SQL_TOKEN.word, i))) { names.add(token.toLowerCase()); emit(token); i += token.length; continue; }
+ if ((token = at(SQL_TOKEN.punct, i))) { emit(token); i += token.length; continue; }
+ out += '…'; break;
+ }
+ return { text: out.length > STATEMENT_MAX ? `${out.slice(0, STATEMENT_MAX - 1)}…` : out, names };
+}
+
+const quotedName = (template: string) => new RegExp(`^${template.replace(/"N"/g, '"([A-Za-z_][A-Za-z0-9_$]{0,62})"')}$`);
+/** Server messages whose every double-quoted token is a catalog name: a bound or literal value cannot appear in them. */
+const CATALOG_NAMED = [
+ 'null value in column "N" of relation "N" violates not-null constraint',
+ 'duplicate key value violates unique constraint "N"',
+ 'new row for relation "N" violates check constraint "N"',
+ 'insert or update on table "N" violates foreign key constraint "N"',
+ 'update or delete on table "N" violates foreign key constraint "N" on table "N"',
+].map(quotedName);
+/**
+ * Server messages whose quoted token is a name from the statement text, kept only when the statement holds it as an
+ * identifier: a bound value cast to regclass or regtype yields the same message with the value in it.
+ */
+const STATEMENT_NAMED = [
+ 'syntax error at or near "N"',
+ '(?:relation|column|type|function|schema|index|constraint|table) "N" does not exist',
+ 'column "N" of relation "N" does not exist',
+].map(quotedName);
+
+/**
+ * #7112: a server message without the values it can carry. A message that matches a known template keeps its object
+ * names; any other message loses everything from its first quote to its last (Postgres does not escape a quote inside
+ * a quoted value, so the value's own quotes cannot be told apart) and every hexadecimal byte run.
+ */
+function serverMessageText(message: string, statementNames: Set<string>): string {
+ const line = message.replace(/[\x00-\x1f\x7f]+/g, ' ').trim();
+ const kept = CATALOG_NAMED.some(re => re.test(line))
+ || STATEMENT_NAMED.some(re => { const m = re.exec(line); return !!m && m.slice(1).every(name => statementNames.has(name.toLowerCase())); });
+ let text = line;
+ if (!kept) {
+ const first = line.search(/["']/);
+ const last = Math.max(line.lastIndexOf('"'), line.lastIndexOf("'"));
+ if (first >= 0) text = first === last ? `${line.slice(0, first)}"…` : `${line.slice(0, first)}"…"${line.slice(last + 1)}`;
+ text = text.replace(/\b0x[0-9a-f]+/gi, '0x…');
}
- const clean = out.replace(/[\x00-\x1f\x7f]/g, ' ');
- return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
+ return text.length > ERROR_TEXT_MAX ? `${text.slice(0, ERROR_TEXT_MAX - 1)}…` : text;
}
/**
- * #7112: what a database server error says, without the values it can carry. Only a server-generated error qualifies
- * (a five-character SQLSTATE and a severity); a PL/pgSQL RAISE carries caller text and is skipped, like `databaseRefusal`.
- * The message keeps a double-quoted token only where the server names an object or the token a syntax error stopped at;
- * the statement keeps its first line with literals replaced, never its parameters.
+ * #7112: what a database server error says, without the values it can carry. Only an error the server itself generated
+ * qualifies: a five-character SQLSTATE, a severity and a C routine that is neither a PL/pgSQL RAISE nor ASSERT (their
+ * text is the caller's) nor any other class P0 condition. The message goes through `serverMessageText`; the statement
+ * keeps its tokens with every literal replaced, never its parameters.
*/
function databaseErrorText(e: Record<string, unknown>): Pick<OwnerExceptionDetail, 'error_text' | 'statement' | 'position'> {
- if (typeof e.code !== 'string' || !/^[0-9A-Z]{5}$/.test(e.code) || typeof e.severity !== 'string' || e.routine === 'exec_stmt_raise') return {};
- const errorText = typeof e.message === 'string'
- ? redactLine(e.message, ERROR_TEXT_MAX, (inner, before) => IDENT.test(inner) && IDENTIFIER_CONTEXT.test(before.trimEnd())) : undefined;
- const statement = typeof e.query === 'string' ? redactLine(e.query, STATEMENT_MAX, inner => IDENT.test(inner)) : undefined;
+ if (typeof e.code !== 'string' || !/^[0-9A-Z]{5}$/.test(e.code) || e.code.startsWith('P0') || typeof e.severity !== 'string'
+ || typeof e.routine !== 'string' || /^exec_stmt_(?:raise|assert)$/.test(e.routine)) return {};
+ const shape = typeof e.query === 'string' ? sqlShape(e.query) : undefined;
+ const errorText = typeof e.message === 'string' ? serverMessageText(e.message, shape?.names ?? new Set()) : undefined;
const position = Number(e.position);
- return { ...(errorText ? { error_text: errorText } : {}), ...(statement ? { statement } : {}), ...(Number.isInteger(position) && position > 0 ? { position } : {}) };
+ return { ...(errorText ? { error_text: errorText } : {}), ...(shape?.text ? { statement: shape.text } : {}),
+ ...(Number.isInteger(position) && position > 0 ? { position } : {}) };
}
/** #5929: the bounded identity of an unexpected owner exception (class, errno, frame, and a database error's redacted text), kept owner-only. */
diff --git a/test/postgres15-sql-compat-7112.test.ts b/test/postgres15-sql-compat-7112.test.ts
index 0806729461..7a6aaf2d31 100644
--- a/test/postgres15-sql-compat-7112.test.ts
+++ b/test/postgres15-sql-compat-7112.test.ts
@@ -13,6 +13,8 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { resetDreamBreakerKey, DREAM_BREAKER_RESETS_KEY } from '../src/core/cycle/dream-breaker.ts';
import { testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { repairJsonb } from '../src/commands/repair-jsonb.ts';
+import * as db from '../src/core/db.ts';
const SOURCE = 'cfg-7112';
const NUL_OBJECT = '{"label":"\\u0000"}';
@@ -20,8 +22,9 @@ const NUL_OBJECT = '{"label":"\\u0000"}';
for (const kind of testBackends()) describe(`portable jsonb guard (${kind})`, () => {
let engine: BrainEngine;
let close: (() => Promise<void>) | undefined;
+ let databaseUrl = '';
beforeAll(async () => {
- if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ if (kind === 'postgres') ({ engine, close, databaseUrl } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }
await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT (id) DO NOTHING', [SOURCE]);
}, 120_000);
@@ -61,6 +64,17 @@ for (const kind of testBackends()) describe(`portable jsonb guard (${kind})`, ()
const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [DREAM_BREAKER_RESETS_KEY]);
expect(Object.keys(JSON.parse(row!.value))).toEqual(['synthesize:cfg-7112']);
});
+
+ if (kind === 'postgres') test('repair-jsonb refuses on a database without gbrain_try_jsonb instead of reporting 0 rows', async () => {
+ const engineConfig = { engine: 'postgres' as const, database_url: databaseUrl };
+ try {
+ expect((await repairJsonb({ dryRun: true, engineConfig })).total_repaired).toBe(0);
+ await engine.executeRaw('DROP FUNCTION gbrain_try_jsonb(text)');
+ await expect(repairJsonb({ dryRun: true, engineConfig })).rejects.toThrow(/gbrain_try_jsonb[\s\S]*gbrain apply-migrations/);
+ } finally {
+ await db.disconnect();
+ }
+ });
});
describe('#7112: shipped SQL parses on every supported Postgres (15+)', () => {
diff --git a/test/publication-failure-owner-exception.test.ts b/test/publication-failure-owner-exception.test.ts
index 48049b50da..b3680bedfc 100644
--- a/test/publication-failure-owner-exception.test.ts
+++ b/test/publication-failure-owner-exception.test.ts
@@ -168,20 +168,20 @@ describe('#7112 a database error keeps its redacted server text and statement, o
throw new Error('expected the statement to fail');
};
- test('a syntax error names the token, the first statement line with literals replaced and the position; parameters never appear', async () => {
+ test('a syntax error names the token, the statement with literals replaced and the position; parameters never appear', async () => {
const error = await serverError("SELECT id FROM sources\n WHERE name = $1 AND config->>'k' = 'secret-literal' AND (config #>> '{}') IS JSONX", ['secret-param']);
const { row } = await failingWrite(error);
expect(row.error_message).toBe(OWNER_EXCEPTION_MESSAGE);
const detail = row.error_detail as Record<string, any>;
- expect(detail).toMatchObject({ origin: 'owner_exception', errno: '42601', statement: 'SELECT id FROM sources' });
- expect(detail.error_text).toMatch(/^syntax error at or near "[A-Z]+"$/);
+ expect(detail).toMatchObject({ origin: 'owner_exception', errno: '42601', error_text: 'syntax error at or near "JSONX"',
+ statement: "SELECT id FROM sources WHERE name = $1 AND config->>'…' = '…' AND (config #>> '…') IS JSONX" });
expect(detail.position).toBeGreaterThan(0);
expect(JSON.stringify(row)).not.toContain('secret-literal');
expect(JSON.stringify(row)).not.toContain('secret-param');
expect((receiptFor(row) as Record<string, any>).write_error_detail).toEqual({ origin: 'owner_exception', stage: 'publication' });
const receipt = await withEnv({ GBRAIN_HOME: join(dir, 'home') }, () =>
operationsByName.get_write_request.handler(ctx(), { request_id: row.request_id })) as Record<string, any>;
- expect(receipt.error_detail).toMatchObject({ errno: '42601', error_text: detail.error_text, statement: 'SELECT id FROM sources', position: detail.position });
+ expect(receipt.error_detail).toMatchObject({ errno: '42601', error_text: detail.error_text, statement: detail.statement, position: detail.position });
});
test('a value the server quotes into its message is replaced, an object it names is kept', async () => {
@@ -192,6 +192,43 @@ describe('#7112 a database error keeps its redacted server text and statement, o
expect(notNull.row.error_detail).toMatchObject({ errno: '23502', error_text: 'null value in column "id" of relation "sources" violates not-null constraint' });
});
+ test('a bound value with its own quotes is replaced whole: Postgres does not escape them', async () => {
+ const { row } = await failingWrite(await serverError('SELECT $1::uuid', ['prefix"PRIVATE_SECRET"suffix']));
+ expect(row.error_detail).toMatchObject({ errno: '22P02', error_text: 'invalid input syntax for type uuid: "…"', statement: 'SELECT $1::uuid' });
+ expect(JSON.stringify(row)).not.toContain('PRIVATE_SECRET');
+ });
+
+ test('a bound value the server reports as an object name is replaced: the statement does not name it', async () => {
+ const value = await failingWrite(await serverError('SELECT $1::regtype', ['PRIVATE_SECRET']));
+ expect(value.row.error_detail).toMatchObject({ error_text: 'type "…" does not exist', statement: 'SELECT $1::regtype' });
+ expect(JSON.stringify(value.row).toLowerCase()).not.toContain('private_secret');
+ });
+
+ test('escape strings, Unicode dollar tags, numbers and comments never reach the statement', async () => {
+ const statements = [
+ "SELECT E'prefix\\'PRIVATE_SECRET'::uuid",
+ 'SELECT $é$PRIVATE-SECRET$é$::uuid',
+ 'SELECT 4111111111111111 AS PRIVATE_x, $1::uuid -- PRIVATE_SECRET',
+ "SELECT /* PRIVATE_SECRET /* nested */ still */ $1::uuid, U&'PRIVATE_SECRET'",
+ ];
+ const shapes = [];
+ for (const sql of statements) {
+ const { row } = await failingWrite(await serverError(sql, sql.includes('$1') ? ['x'] : []));
+ expect(JSON.stringify(row)).not.toContain('PRIVATE_SECRET');
+ expect(JSON.stringify(row)).not.toContain('PRIVATE-SECRET');
+ expect(JSON.stringify(row)).not.toContain('4111');
+ shapes.push((row.error_detail as Record<string, unknown>).statement);
+ }
+ expect(shapes).toEqual(["SELECT E'…'::uuid", 'SELECT $…$::uuid', 'SELECT ? AS PRIVATE_x, $1::uuid', "SELECT $1::uuid, U&'…'"]);
+ });
+
+ test('a PL/pgSQL ASSERT keeps no text: its message is the caller\'s', async () => {
+ const { row } = await failingWrite(await serverError("DO $$ BEGIN ASSERT false, 'PRIVATE_SECRET'; END $$"));
+ expect(row.error_detail).toMatchObject({ origin: 'owner_exception', errno: 'P0004' });
+ expect((row.error_detail as Record<string, unknown>).error_text).toBeUndefined();
+ expect(JSON.stringify(row)).not.toContain('PRIVATE_SECRET');
+ });
+
test('a PL/pgSQL RAISE keeps no text: it carries caller values', async () => {
const { row } = await failingWrite(await serverError("DO $$ BEGIN RAISE EXCEPTION USING ERRCODE = '22023', MESSAGE = 'secret-title of a page'; END $$"));
const detail = row.error_detail as Record<string, any>;
diff --git a/test/snapshot-inputs-closure.test.ts b/test/snapshot-inputs-closure.test.ts
index 5eb454042d..7ba16fa505 100644
--- a/test/snapshot-inputs-closure.test.ts
+++ b/test/snapshot-inputs-closure.test.ts
@@ -142,9 +142,9 @@ describe('snapshot schema hash inputs (EO7)', () => {
describe('pglite-snapshot CI cache keys (DX O7)', () => {
const keys = discoverCacheKeys();
- test('discovers every key: 14 across e2e.yml, test.yml and stress.yml, two profiles', () => {
- expect(keys.length).toBe(14);
- expect(keys.filter((k) => k.file.endsWith('e2e.yml')).length).toBe(6);
+ test('discovers every key: 15 across e2e.yml, test.yml and stress.yml, two profiles', () => {
+ expect(keys.length).toBe(15);
+ expect(keys.filter((k) => k.file.endsWith('e2e.yml')).length).toBe(7);
expect(keys.filter((k) => k.file.endsWith('test.yml')).length).toBe(7);
expect(keys.filter((k) => k.file.endsWith('stress.yml')).length).toBe(1);
expect([...new Set(keys.map((k) => k.namespace))].sort()).toEqual(['pglite-snapshot', 'pglite-snapshot-default']);