Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#7112): portable gbrain_try_jsonb replaces Postgres 16+ IS JSON / pg_input_is_valid

garrytan9be5c33371fa
diff --git a/src/commands/doctor/checks/core-health.ts b/src/commands/doctor/checks/core-health.ts
index a43bc9eb46..06722dd68c 100644
--- a/src/commands/doctor/checks/core-health.ts
+++ b/src/commands/doctor/checks/core-health.ts
@@ -273,7 +273,7 @@ export async function jsonbIntegrityCheck(
);
if (!existsRows[0]?.exists) continue;
const damage = jsonPayloadOnly
- ? `jsonb_typeof(${col}) = 'string' AND (${col} #>> '{}') ~ '^[[:space:]]*[\\[{]' AND pg_input_is_valid(${col} #>> '{}', 'jsonb')`
+ ? `jsonb_typeof(${col}) = 'string' AND (${col} #>> '{}') ~ '^[[:space:]]*[\\[{]' AND gbrain_try_jsonb(${col} #>> '{}') IS NOT NULL`
: `jsonb_typeof(${col}) = 'string'`;
const rows = await engine.executeRaw<{ n: number }>(
`SELECT count(*)::int AS n FROM ${table} WHERE ${damage}`,
diff --git a/src/commands/repair-jsonb.ts b/src/commands/repair-jsonb.ts
index d343c869e9..49bb70f364 100644
--- a/src/commands/repair-jsonb.ts
+++ b/src/commands/repair-jsonb.ts
@@ -77,10 +77,10 @@ function damagePredicate(t: RepairTarget): string {
const base = `jsonb_typeof(${t.column}) = 'string'`;
// Container-looking is not enough: '[INFO] fetch complete' matches the
// shape probe but is NOT valid JSON — the repair cast would throw and
- // abort the run. pg_input_is_valid (PG16+, same floor as the IS JSON
- // predicate updateSourceConfig already relies on) gates on parseability.
+ // abort the run. gbrain_try_jsonb (NULL on unparseable text; Postgres 15+,
+ // #7112) gates on parseability.
return t.jsonPayloadOnly
- ? `${base} AND (${t.column} #>> '{}') ~ '^[[:space:]]*[\\[{]' AND pg_input_is_valid(${t.column} #>> '{}', 'jsonb')`
+ ? `${base} AND (${t.column} #>> '{}') ~ '^[[:space:]]*[\\[{]' AND gbrain_try_jsonb(${t.column} #>> '{}') IS NOT NULL`
: base;
}
diff --git a/src/core/cycle/dream-breaker.ts b/src/core/cycle/dream-breaker.ts
index c3c26e1476..184c1d1675 100644
--- a/src/core/cycle/dream-breaker.ts
+++ b/src/core/cycle/dream-breaker.ts
@@ -216,7 +216,7 @@ export async function resetDreamBreakerKey(engine: BrainEngine, baseKey: string)
VALUES ($1, jsonb_build_object($2::text, to_char((now() + interval '1 millisecond') AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))::text)
ON CONFLICT (key) DO UPDATE SET value = ((
SELECT COALESCE(jsonb_object_agg(entry.key, entry.value), '{}'::jsonb)
- FROM jsonb_each_text(CASE WHEN config.value IS JSON OBJECT THEN config.value::jsonb ELSE '{}'::jsonb END) entry
+ FROM jsonb_each_text(CASE WHEN jsonb_typeof(gbrain_try_jsonb(config.value)) = 'object' THEN gbrain_try_jsonb(config.value) ELSE '{}'::jsonb END) entry
WHERE entry.key <> $2::text AND entry.value ~ '^[0-9]{4}-' AND entry.value::timestamptz > now() - interval '24 hours'
) || EXCLUDED.value::jsonb)::text`,
[DREAM_BREAKER_RESETS_KEY, dreamBreakerBaseKey(baseKey)],
diff --git a/src/core/engine-sql/sources.ts b/src/core/engine-sql/sources.ts
index 9657bd7d3d..d81d904675 100644
--- a/src/core/engine-sql/sources.ts
+++ b/src/core/engine-sql/sources.ts
@@ -57,9 +57,10 @@ export async function updateSourceConfig(exec: SqlExecutor, sourceId: string, pa
// String branch guard: a JSONB string whose inner text is NOT itself valid
// JSON (one of the historical bad shapes this path repairs) would make the
// bare `::jsonb` cast raise `invalid input syntax for type json`, failing
- // the whole UPDATE. Postgres has no `try_cast`, so we gate the cast with
- // the SQL `IS JSON` predicate (Postgres 16+): parseable inner text is
- // double-encoded config and gets parsed; unparseable text falls back to `{}`.
+ // the whole UPDATE. Postgres has no `try_cast`, so the cast goes through
+ // gbrain_try_jsonb (NULL on unparseable text; Postgres 15+, unlike IS JSON,
+ // #7112): parseable inner text is double-encoded config and gets parsed;
+ // unparseable text falls back to `{}`.
// The guard keeps the merge a single atomic statement (no extra round-trip,
// no lost-update race).
//
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 95d55d02c0..cc64b743b7 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -31,6 +31,14 @@ CREATE TABLE IF NOT EXISTS sources (
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb
+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS \$fn\$
+BEGIN
+ RETURN input::jsonb;
+EXCEPTION WHEN data_exception THEN
+ RETURN NULL;
+END \$fn\$;
+
INSERT INTO sources (id, name, config)
SELECT 'default', 'default', '{"federated": true}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM sources WHERE id = 'default')
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 5d8ab18c74..b901b4a438 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -61,6 +61,18 @@ CREATE TABLE IF NOT EXISTS sources (
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+-- #7112: text -> jsonb, NULL when the text is not valid jsonb. The portable
+-- (Postgres 15+) guard for casting a double-encoded config or payload string;
+-- IS JSON and pg_input_is_valid() are Postgres 16+. Migration v263 installs it
+-- on existing brains.
+CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb
+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS \$fn\$
+BEGIN
+ RETURN input::jsonb;
+EXCEPTION WHEN data_exception THEN
+ RETURN NULL;
+END \$fn\$;
+
-- Seed the default source. 'default' is federated=true for backward compat
-- (pre-v0.17 brains behave exactly as before — every page appears in search).
-- Pre-existing sync.repo_path / sync.last_commit are copied in by the v16
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 59b7090582..7c10d71c56 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 262;
+export const LATEST_SCHEMA_VERSION = 263;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index a86757a665..4d376fcd12 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -263,6 +263,7 @@ import { v259 } from './v259-ingest-log-marked-index.ts';
import { v260 } from './v260-segmented-page-size-index.ts';
import { v261 } from './v261-persistence-request-transient-retries.ts';
import { v262 } from './v262-commit-notifier.ts';
+import { v263 } from './v263-try-jsonb-function.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -524,4 +525,5 @@ export const MIGRATIONS: Migration[] = [
v260,
v261,
v262,
+ v263,
];
diff --git a/src/core/schema-migrations/v263-try-jsonb-function.ts b/src/core/schema-migrations/v263-try-jsonb-function.ts
new file mode 100644
index 0000000000..c6c7c245a3
--- /dev/null
+++ b/src/core/schema-migrations/v263-try-jsonb-function.ts
@@ -0,0 +1,26 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); src/schema.sql
+// carries the same function for fresh installs.
+//
+// #7112: gbrain_try_jsonb(text) parses text as jsonb and returns NULL when it
+// is not valid jsonb, instead of raising. It replaces the SQL/JSON `IS JSON`
+// predicate and pg_input_is_valid(), both Postgres 16+, which made every
+// statement that normalizes sources.config a syntax error (42601) on
+// Postgres 15. It also refuses what IS JSON let through and the jsonb cast
+// then rejected (a \u0000 escape), so the guarded cast can no longer raise.
+// DDL only, nothing to backfill.
+export const v263: Migration = {
+ version: 263,
+ name: 'try_jsonb_function',
+ idempotent: true,
+ sql: `
+ CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb
+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS $fn$
+ BEGIN
+ RETURN input::jsonb;
+ EXCEPTION WHEN data_exception THEN
+ RETURN NULL;
+ END $fn$;
+ `,
+};
diff --git a/src/core/source-config-sql.ts b/src/core/source-config-sql.ts
index 644ffeddf1..7b17ef093f 100644
--- a/src/core/source-config-sql.ts
+++ b/src/core/source-config-sql.ts
@@ -5,7 +5,9 @@
* strings or arrays of config fragments. The recursive CTE unwraps strings up
* to the same depth as the application reader, then merges recoverable array
* fragments left-to-right. Invalid fragments are ignored instead of making a
- * repair or archive operation fail.
+ * repair or archive operation fail: gbrain_try_jsonb (schema.sql, v263) parses
+ * a string layer or returns NULL, which works on Postgres 15 where the IS JSON
+ * predicate does not parse (#7112).
*
* This expression is static SQL: it contains no user input.
*/
@@ -14,11 +16,11 @@ export const SOURCE_CONFIG_OBJECT_SQL = `(
root_layers(value, depth) AS (
SELECT COALESCE(config, '{}'::jsonb), 0
UNION ALL
- SELECT (value #>> '{}')::jsonb, depth + 1
+ SELECT gbrain_try_jsonb(value #>> '{}'), depth + 1
FROM root_layers
WHERE depth < 10
AND jsonb_typeof(value) = 'string'
- AND (value #>> '{}') IS JSON
+ AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL
),
root(value) AS (
SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1
@@ -35,11 +37,11 @@ export const SOURCE_CONFIG_OBJECT_SQL = `(
fragment_layers(ordinality, value, depth) AS (
SELECT ordinality, value, 0 FROM fragment_seeds
UNION ALL
- SELECT ordinality, (value #>> '{}')::jsonb, depth + 1
+ SELECT ordinality, gbrain_try_jsonb(value #>> '{}'), depth + 1
FROM fragment_layers
WHERE depth < 10
AND jsonb_typeof(value) = 'string'
- AND (value #>> '{}') IS JSON
+ AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL
),
fragments AS (
SELECT DISTINCT ON (ordinality) ordinality, value
diff --git a/src/schema.sql b/src/schema.sql
index ffe35742a0..bb1456367d 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -57,6 +57,18 @@ CREATE TABLE IF NOT EXISTS sources (
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+-- #7112: text -> jsonb, NULL when the text is not valid jsonb. The portable
+-- (Postgres 15+) guard for casting a double-encoded config or payload string;
+-- IS JSON and pg_input_is_valid() are Postgres 16+. Migration v263 installs it
+-- on existing brains.
+CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb
+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS $fn$
+BEGIN
+ RETURN input::jsonb;
+EXCEPTION WHEN data_exception THEN
+ RETURN NULL;
+END $fn$;
+
-- Seed the default source. 'default' is federated=true for backward compat
-- (pre-v0.17 brains behave exactly as before — every page appears in search).
-- Pre-existing sync.repo_path / sync.last_commit are copied in by the v16
diff --git a/test/doctor-source-config-shape.test.ts b/test/doctor-source-config-shape.test.ts
index 52bf602602..3191dfc130 100644
--- a/test/doctor-source-config-shape.test.ts
+++ b/test/doctor-source-config-shape.test.ts
@@ -40,7 +40,8 @@ describe('checkSourceConfigShape (#2829)', () => {
// Paste-ready repair SQL is part of the hint.
expect(result.message).toContain('UPDATE sources SET config');
expect(result.message).toContain('jsonb_array_elements');
- expect(result.message).toContain('IS JSON');
+ expect(result.message).toContain('gbrain_try_jsonb');
+ expect(result.message).not.toContain('IS JSON');
// #5002: name commands that actually rewrite the config column — never the
// "any 'gbrain sources' config write" category (set-cr-mode writes another
// column and leaves the check red).
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index 74615fca66..e4fdacb4aa 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -438,7 +438,7 @@ describe('doctor command', () => {
VALUES (990001, 1, 'assistant', to_jsonb('plain text payload, not JSON'::text))`,
);
// Container-LOOKING but invalid JSON — matches the shape probe but
- // pg_input_is_valid must exclude it (repairing it would throw).
+ // gbrain_try_jsonb must exclude it (repairing it would throw).
await engine.executeRaw(
`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)
VALUES (990001, 2, 'assistant', to_jsonb('[INFO] fetch complete'::text))`,