mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 09:22:18 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97ddee0548 |
@@ -21,17 +21,14 @@ GBrain is tuned for the Supabase **Transaction pooler** (port 6543): it
|
||||
auto-disables prepared statements there and routes `engine.transaction()`
|
||||
(migrations, DDL, sync imports) to a derived **direct** connection
|
||||
(`db.<ref>.supabase.co:5432`). That direct host is IPv6-only, so on an
|
||||
IPv4-only host it is unreachable. When that happens gbrain now falls back to
|
||||
the pooler automatically (one stderr warning, then single-pool mode for the
|
||||
rest of the process) — but the pooler's ~2-min statement timeout can truncate
|
||||
very long migrations or bulk imports.
|
||||
IPv4-only host, reads work but sync **silently skips most pages**. This is the
|
||||
number one cause of "sync ran but nothing happened."
|
||||
|
||||
Fix: make the direct connection reachable over IPv4. Either set
|
||||
`GBRAIN_DIRECT_DATABASE_URL` to the **Session pooler** string (port 5432 on the
|
||||
`pooler.supabase.com` host, IPv4), or enable Supabase's IPv4 add-on.
|
||||
`GBRAIN_DISABLE_DIRECT_POOL=1` skips the direct pool (and the fallback warning)
|
||||
entirely. Verify by running `gbrain sync` and checking that the page count in
|
||||
`gbrain stats` matches the syncable file count in the repo.
|
||||
`pooler.supabase.com` host, IPv4), or enable Supabase's IPv4 add-on. Verify by
|
||||
running `gbrain sync` and checking that the page count in `gbrain stats` matches
|
||||
the syncable file count in the repo.
|
||||
|
||||
### The Primitives
|
||||
|
||||
|
||||
+5
-8
@@ -2720,17 +2720,14 @@ GBrain is tuned for the Supabase **Transaction pooler** (port 6543): it
|
||||
auto-disables prepared statements there and routes `engine.transaction()`
|
||||
(migrations, DDL, sync imports) to a derived **direct** connection
|
||||
(`db.<ref>.supabase.co:5432`). That direct host is IPv6-only, so on an
|
||||
IPv4-only host it is unreachable. When that happens gbrain now falls back to
|
||||
the pooler automatically (one stderr warning, then single-pool mode for the
|
||||
rest of the process) — but the pooler's ~2-min statement timeout can truncate
|
||||
very long migrations or bulk imports.
|
||||
IPv4-only host, reads work but sync **silently skips most pages**. This is the
|
||||
number one cause of "sync ran but nothing happened."
|
||||
|
||||
Fix: make the direct connection reachable over IPv4. Either set
|
||||
`GBRAIN_DIRECT_DATABASE_URL` to the **Session pooler** string (port 5432 on the
|
||||
`pooler.supabase.com` host, IPv4), or enable Supabase's IPv4 add-on.
|
||||
`GBRAIN_DISABLE_DIRECT_POOL=1` skips the direct pool (and the fallback warning)
|
||||
entirely. Verify by running `gbrain sync` and checking that the page count in
|
||||
`gbrain stats` matches the syncable file count in the repo.
|
||||
`pooler.supabase.com` host, IPv4), or enable Supabase's IPv4 add-on. Verify by
|
||||
running `gbrain sync` and checking that the page count in `gbrain stats` matches
|
||||
the syncable file count in the repo.
|
||||
|
||||
### The Primitives
|
||||
|
||||
|
||||
@@ -1078,9 +1078,6 @@ async function initPostgres(opts: {
|
||||
console.warn(' Direct connections are IPv6 only and fail in many environments.');
|
||||
console.warn(' Use the Transaction pooler connection string instead (port 6543):');
|
||||
console.warn(' Supabase Dashboard > Connect (top bar) > Connection String > Transaction pooler');
|
||||
console.warn(' (With a pooler URL, gbrain derives a direct connection for DDL and falls back');
|
||||
console.warn(' to the pooler automatically if that host is unreachable. Power users:');
|
||||
console.warn(' GBRAIN_DIRECT_DATABASE_URL overrides the derived URL; GBRAIN_DISABLE_DIRECT_POOL=1 disables it.)');
|
||||
console.warn('');
|
||||
}
|
||||
|
||||
@@ -1094,9 +1091,6 @@ async function initPostgres(opts: {
|
||||
if (databaseUrl.includes('supabase.co') && (msg.includes('ECONNREFUSED') || msg.includes('ETIMEDOUT'))) {
|
||||
console.error('Connection failed. Supabase direct connections (db.*.supabase.co:5432) are IPv6 only.');
|
||||
console.error('Use the Transaction pooler connection string instead (port 6543).');
|
||||
console.error('(gbrain derives its own direct connection from pooler URLs for DDL; if that host is');
|
||||
console.error('unreachable it falls back to the pooler. GBRAIN_DIRECT_DATABASE_URL overrides the');
|
||||
console.error('derived URL; GBRAIN_DISABLE_DIRECT_POOL=1 disables the direct pool entirely.)');
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
@@ -167,25 +167,6 @@ export function deriveDirectUrl(url: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error codes that mean "the direct host is unreachable from this network"
|
||||
* (#1641). The auto-derived db.<ref>.supabase.co host is IPv6-only without
|
||||
* the paid IPv4 add-on, so ENOTFOUND/ECONNREFUSED here is expected on
|
||||
* IPv4-only networks — we fall back to the pooler instead of failing init.
|
||||
*/
|
||||
const NETWORK_UNREACHABLE_CODES = [
|
||||
'ENOTFOUND', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH',
|
||||
'ETIMEDOUT', 'CONNECT_TIMEOUT',
|
||||
];
|
||||
|
||||
/** True when err looks like a network-unreachable failure (not auth/SQL). */
|
||||
export function isNetworkUnreachableError(err: unknown): boolean {
|
||||
const code = (err as { code?: unknown } | null)?.code;
|
||||
if (typeof code === 'string' && NETWORK_UNREACHABLE_CODES.includes(code)) return true;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return NETWORK_UNREACHABLE_CODES.some(c => msg.includes(c));
|
||||
}
|
||||
|
||||
/**
|
||||
* Read kill-switch state from env. Subordinate to parent manager's state
|
||||
* when present (A2 inheritance).
|
||||
@@ -338,30 +319,7 @@ export class ConnectionManager {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
let pool: Sql | null;
|
||||
try {
|
||||
pool = await this._directInit;
|
||||
} catch (err) {
|
||||
// #1641: the derived direct host (db.<ref>.supabase.co) is IPv6-only
|
||||
// without Supabase's IPv4 add-on. On IPv4-only networks the direct
|
||||
// pool can never connect — permanently fall back to the read pool
|
||||
// (self-activating kill-switch) instead of failing init/migrations.
|
||||
// Non-network errors (auth, SQL) still throw: they mean misconfig,
|
||||
// not unreachability.
|
||||
if (isNetworkUnreachableError(err)) {
|
||||
const alreadyWarned = this._killSwitch;
|
||||
this._killSwitch = true;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
if (!alreadyWarned) console.error(
|
||||
`gbrain: direct connection to ${this._directUrl ? this.hostOnly(this._directUrl) : 'unknown host'} unreachable (${msg}); ` +
|
||||
'falling back to the pooler for DDL/bulk (long migrations may hit the pooler statement timeout). ' +
|
||||
'Set GBRAIN_DIRECT_DATABASE_URL to a reachable direct URL (e.g. the Session pooler, port 5432) or enable the Supabase IPv4 add-on; ' +
|
||||
'GBRAIN_DISABLE_DIRECT_POOL=1 silences this.',
|
||||
);
|
||||
return this.getReadPool();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const pool = await this._directInit;
|
||||
if (!pool) {
|
||||
// Defensive — initDirectPool should have thrown.
|
||||
throw new Error('connection-manager: direct pool init returned null');
|
||||
@@ -392,9 +350,8 @@ export class ConnectionManager {
|
||||
},
|
||||
};
|
||||
const t0 = Date.now();
|
||||
let pool: Sql | null = null;
|
||||
try {
|
||||
pool = postgres(this._directUrl, opts);
|
||||
const pool = postgres(this._directUrl, opts);
|
||||
// Probe to validate connectivity early.
|
||||
await pool`SELECT 1`;
|
||||
logConnectionEvent({
|
||||
@@ -405,9 +362,6 @@ export class ConnectionManager {
|
||||
});
|
||||
return pool;
|
||||
} catch (err) {
|
||||
// Don't leak the failed pool's sockets/timers (#1641 fallback keeps
|
||||
// the process running afterward).
|
||||
if (pool) await endPoolBounded(pool);
|
||||
logConnectionEvent({
|
||||
pool: 'ddl',
|
||||
op: 'error',
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
import type { BrainEngine } from '../engine.ts';
|
||||
import { loadActivePackBestEffort } from './best-effort.ts';
|
||||
import type { OperationContext } from '../operations.ts';
|
||||
import { isUndefinedTableError } from '../utils.ts';
|
||||
|
||||
export interface StatsOpts {
|
||||
/** Single source scope. Omit + omit sourceIds for whole-brain aggregate. */
|
||||
@@ -164,9 +165,17 @@ async function fetchCountRows(engine: BrainEngine, opts: StatsOpts): Promise<Raw
|
||||
`;
|
||||
try {
|
||||
return await engine.executeRaw<RawCountRow>(sql, params);
|
||||
} catch {
|
||||
// Empty / pre-init brain: pages table may not exist yet.
|
||||
return [];
|
||||
} catch (err) {
|
||||
// ONLY swallow the genuine "pages table doesn't exist yet" case
|
||||
// (empty / pre-init brain). #2466: the old bare `catch {}` masked
|
||||
// EVERY error — so any engine-level failure (connection, version
|
||||
// skew, a query incompatibility) was silently converted to 0 rows,
|
||||
// printing "Total pages: 0" on a populated brain and cascading into
|
||||
// false "100% coverage" + a starved `schema suggest`. Surface
|
||||
// everything that is not a missing-table error so the real failure
|
||||
// is visible instead of hidden behind a fake zero.
|
||||
if (isUndefinedTableError(err)) return [];
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,9 +213,11 @@ async function detectDeadPrefixes(
|
||||
if (cnt === 0) {
|
||||
hints.push({ type: t.name, prefix });
|
||||
}
|
||||
} catch {
|
||||
// Skip on engine error (no pages table yet, etc.).
|
||||
continue;
|
||||
} catch (err) {
|
||||
// #2466: only skip on the genuine "no pages table yet" case;
|
||||
// rethrow any other engine error so it isn't silently masked.
|
||||
if (isUndefinedTableError(err)) continue;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
isSupabasePoolerUrl,
|
||||
deriveDirectUrl,
|
||||
readKillSwitchEnv,
|
||||
isNetworkUnreachableError,
|
||||
resolveDirectPoolSize,
|
||||
ConnectionManager,
|
||||
DEFAULT_DIRECT_POOL_SIZE,
|
||||
@@ -239,65 +238,3 @@ describe('ConnectionManager — parent inheritance (A2)', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('isNetworkUnreachableError (#1641)', () => {
|
||||
test('classifies network codes as unreachable', () => {
|
||||
for (const code of ['ENOTFOUND', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'ETIMEDOUT', 'CONNECT_TIMEOUT']) {
|
||||
const err = Object.assign(new Error('connect failed'), { code });
|
||||
expect(isNetworkUnreachableError(err)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('classifies by message when code absent', () => {
|
||||
expect(isNetworkUnreachableError(new Error('getaddrinfo ENOTFOUND db.abc.supabase.co'))).toBe(true);
|
||||
});
|
||||
|
||||
test('auth/SQL errors are NOT unreachable', () => {
|
||||
expect(isNetworkUnreachableError(new Error('password authentication failed for user "postgres"'))).toBe(false);
|
||||
expect(isNetworkUnreachableError(new Error('syntax error at or near "SELEC"'))).toBe(false);
|
||||
expect(isNetworkUnreachableError(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ConnectionManager — direct-pool fallback on unreachable host (#1641)', () => {
|
||||
let originalKillSwitch: string | undefined;
|
||||
let originalError: typeof console.error;
|
||||
let errLines: string[];
|
||||
beforeEach(() => {
|
||||
originalKillSwitch = process.env.GBRAIN_DISABLE_DIRECT_POOL;
|
||||
delete process.env.GBRAIN_DISABLE_DIRECT_POOL;
|
||||
originalError = console.error;
|
||||
errLines = [];
|
||||
console.error = (...args: unknown[]) => { errLines.push(args.join(' ')); };
|
||||
});
|
||||
afterEach(() => {
|
||||
console.error = originalError;
|
||||
if (originalKillSwitch === undefined) delete process.env.GBRAIN_DISABLE_DIRECT_POOL;
|
||||
else process.env.GBRAIN_DISABLE_DIRECT_POOL = originalKillSwitch;
|
||||
});
|
||||
|
||||
test('ddl() falls back to the read pool when the direct host is unreachable', async () => {
|
||||
const cm = new ConnectionManager({
|
||||
url: 'postgresql://postgres.abc:p@aws.pooler.supabase.com:6543/db',
|
||||
// 127.0.0.1:9 (discard) → instant ECONNREFUSED, the IPv4-only-network shape.
|
||||
directUrl: 'postgresql://postgres:p@127.0.0.1:9/db',
|
||||
});
|
||||
const fakeReadPool = {} as ReturnType<typeof ConnectionManager.prototype.read>;
|
||||
cm.setReadPool(fakeReadPool);
|
||||
expect(cm.isDualPoolActive()).toBe(true);
|
||||
|
||||
const pool = await cm.ddl(); // without the fix this throws ECONNREFUSED
|
||||
expect(pool).toBe(fakeReadPool);
|
||||
// Self-activating kill-switch: subsequent calls skip the direct pool.
|
||||
expect(cm.isKillSwitchActive()).toBe(true);
|
||||
expect(cm.isDualPoolActive()).toBe(false);
|
||||
expect(cm.describeMode().mode).toBe('single (kill-switch)');
|
||||
// One stderr line mentioning the power-user override.
|
||||
const warning = errLines.filter(l => l.includes('GBRAIN_DIRECT_DATABASE_URL'));
|
||||
expect(warning.length).toBe(1);
|
||||
|
||||
const again = await cm.ddl();
|
||||
expect(again).toBe(fakeReadPool);
|
||||
expect(errLines.filter(l => l.includes('GBRAIN_DIRECT_DATABASE_URL')).length).toBe(1);
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
@@ -222,6 +222,89 @@ describe('runStatsCore — JSON envelope shape', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('runStatsCore — #2466 catch-narrowing (real count + error surfacing)', () => {
|
||||
// #2466: `gbrain schema stats` reported "Total pages: 0" on a populated
|
||||
// PGLite brain. The bug was a bare `catch {}` in fetchCountRows (and a
|
||||
// sibling in detectDeadPrefixes) that converted ANY engine error into 0
|
||||
// rows. The COUNT query itself is valid on PGLite (proven below), so the
|
||||
// regression pins two things: (a) a populated brain reports the real,
|
||||
// non-zero count through the full runStatsCore path; (b) a non-missing-
|
||||
// table engine error is rethrown, not masked into a fake zero.
|
||||
|
||||
it('reports the real non-zero count on a populated PGLite brain (no false 0)', async () => {
|
||||
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
|
||||
// Seed a realistic mix: typed, untyped, multiple types — like the
|
||||
// 169-page brain in the bug report (scaled down).
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const type = i % 3 === 0 ? '' : (i % 3 === 1 ? 'person' : 'company');
|
||||
await seedPage(`notes/p${i}`, { type, sourcePath: `notes/p${i}.md` });
|
||||
}
|
||||
const result = await runStatsCore(ctxOf());
|
||||
// The core regression: NOT zero.
|
||||
expect(result.aggregate.total_pages).toBe(12);
|
||||
expect(result.aggregate.typed_pages).toBe(8);
|
||||
expect(result.aggregate.untyped_pages).toBe(4);
|
||||
// And coverage is the honest ratio, not the vacuous 1.0 a 0/0 prints.
|
||||
expect(result.aggregate.coverage).not.toBe(1.0);
|
||||
});
|
||||
});
|
||||
|
||||
it('fetchCountRows rethrows a non-missing-table engine error instead of masking it as 0 pages', async () => {
|
||||
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
|
||||
// No pack → detectDeadPrefixes is skipped, isolating the throw to the
|
||||
// fetchCountRows catch we narrowed. The count query (the GROUP BY one)
|
||||
// throws a column-level error (SQLSTATE 42703) — the exact class the
|
||||
// old bare `catch {}` swallowed into 0 rows; everything else succeeds.
|
||||
__setPackLocatorForTests(() => null);
|
||||
const boom = Object.assign(new Error('column "type" does not exist'), { code: '42703' });
|
||||
const stubEngine = {
|
||||
executeRaw: async (sql: string) => {
|
||||
if (/GROUP BY source_id/.test(sql)) throw boom; // the fetchCountRows query
|
||||
return [];
|
||||
},
|
||||
} as unknown as PGLiteEngine;
|
||||
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
|
||||
await expect(runStatsCore(ctx)).rejects.toThrow('column "type" does not exist');
|
||||
});
|
||||
});
|
||||
|
||||
it('fetchCountRows still degrades to empty (no throw) on a genuine missing pages table', async () => {
|
||||
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
|
||||
// Pre-init brain shape: the count query hits a missing pages table
|
||||
// (SQLSTATE 42P01). This is the ONLY case the narrowed catch swallows.
|
||||
__setPackLocatorForTests(() => null);
|
||||
const missing = Object.assign(new Error('relation "pages" does not exist'), { code: '42P01' });
|
||||
const stubEngine = {
|
||||
executeRaw: async (sql: string) => {
|
||||
if (/GROUP BY source_id/.test(sql)) throw missing;
|
||||
return [];
|
||||
},
|
||||
} as unknown as PGLiteEngine;
|
||||
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
|
||||
const result = await runStatsCore(ctx);
|
||||
expect(result.aggregate.total_pages).toBe(0);
|
||||
expect(result.per_source).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('detectDeadPrefixes rethrows a non-missing-table error (sibling catch)', async () => {
|
||||
await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: 'tiny' }, async () => {
|
||||
seedTinyPack('tiny', [{ name: 'person', prefix: 'people/' }]);
|
||||
// fetchCountRows (the GROUP BY query) succeeds → []; the per-prefix
|
||||
// dead-prefix LIKE query then throws a non-missing-table error, which
|
||||
// must surface through the narrowed sibling catch.
|
||||
const stubEngine = {
|
||||
executeRaw: async (sql: string) => {
|
||||
if (/GROUP BY source_id/.test(sql)) return []; // count query: empty brain, fine
|
||||
throw Object.assign(new Error('division by zero'), { code: '22012' }); // the LIKE query
|
||||
},
|
||||
} as unknown as PGLiteEngine;
|
||||
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
|
||||
await expect(runStatsCore(ctx)).rejects.toThrow('division by zero');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('runStatsCore — type/untyped split', () => {
|
||||
it('treats empty-string type as untyped (not its own bucket)', async () => {
|
||||
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
|
||||
|
||||
Reference in New Issue
Block a user