mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 09:22:18 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d98e6b507f | ||
|
|
d4bbf6eeae |
@@ -1743,15 +1743,7 @@ async function extractStaleFromDB(
|
||||
// `page.updated_at.toISOString()` — the JS Date is ms-truncated, so the
|
||||
// µs-precision DB updated_at stayed strictly greater and the page never
|
||||
// cleared on Postgres. Stamping the exact value makes them equal.
|
||||
//
|
||||
// Version-arm floor: a page last edited BEFORE LINK_EXTRACTOR_VERSION_TS
|
||||
// would otherwise be stamped below the version watermark and stay
|
||||
// permanently stale (`links_extracted_at < versionTs` re-fires every run).
|
||||
// Stamp max(updated_at, versionTs) — versionTs is always a past release
|
||||
// date, so a concurrent edit's now() still exceeds the stamp and D4 holds.
|
||||
// Tie at ms precision picks updated_at_iso (its µs ≥ versionTs's .000000).
|
||||
const stampTs = new Date(page.updated_at_iso) >= new Date(versionTs) ? page.updated_at_iso : versionTs;
|
||||
processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: stampTs });
|
||||
processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: page.updated_at_iso });
|
||||
}
|
||||
|
||||
// Flush NON-swallowing (CDX-4): a throw here propagates out of the sweep so
|
||||
|
||||
@@ -28,7 +28,7 @@ import { ensureWellFormed } from './text-safe.ts';
|
||||
* OR updated_at > links_extracted_at`. It is an ISO-8601 string (NOT a number) —
|
||||
* the column is TIMESTAMPTZ and the predicate binds it as `::timestamptz`.
|
||||
*/
|
||||
export const LINK_EXTRACTOR_VERSION_TS = '2026-07-21T00:00:00Z';
|
||||
export const LINK_EXTRACTOR_VERSION_TS = '2026-05-31T00:00:00Z';
|
||||
|
||||
// ─── Entity references ──────────────────────────────────────────
|
||||
|
||||
@@ -80,10 +80,10 @@ export type LinkResolutionType = 'qualified' | 'unqualified';
|
||||
* Directory prefix whitelist. These are the top-level slug dirs the extractor
|
||||
* recognizes as entity references. Upstream canonical + our extensions:
|
||||
* - Gbrain canonical: people, companies, meetings, concepts, deal, civic, project, source, media, yc, projects
|
||||
* - Our domain extensions: tech, finance, personal, openclaw, ops (domain-organized wikis)
|
||||
* - Our domain extensions: tech, finance, personal, openclaw (domain-organized wikis)
|
||||
* - Our entity prefix: entities (we kept some legacy entities/projects/ pages)
|
||||
*/
|
||||
const DIR_PATTERN = '(?:people|companies|meetings|concepts|deal|civic|project|projects|source|media|yc|tech|finance|personal|openclaw|entities|ops)';
|
||||
const DIR_PATTERN = '(?:people|companies|meetings|concepts|deal|civic|project|projects|source|media|yc|tech|finance|personal|openclaw|entities)';
|
||||
|
||||
/**
|
||||
* Match `[Name](path)` markdown links pointing to entity directories.
|
||||
@@ -865,16 +865,7 @@ export function queryBasenameIndex(idx: Map<string, string[]>, name: string): st
|
||||
if (!name || typeof name !== 'string') return [];
|
||||
const trimmed = name.trim();
|
||||
if (!trimmed) return [];
|
||||
let hit = idx.get(trimmed) ?? idx.get(trimmed.toLowerCase()) ?? idx.get(normalizeBasename(trimmed));
|
||||
// Issue #2576 bug 2: path-style refs (`runbooks/2026-05-01-x`) from dirs
|
||||
// outside DIR_PATTERN reach here, but normalizeBasename strips slashes
|
||||
// into a garbage key (`runbooks2026-05-01-x`) that can never hit the
|
||||
// tail-keyed index. Fall back to the path tail so qualified refs resolve
|
||||
// by basename like everything else.
|
||||
if (!hit && trimmed.includes('/')) {
|
||||
const tail = trimmed.slice(trimmed.lastIndexOf('/') + 1).trim();
|
||||
if (tail) hit = idx.get(tail) ?? idx.get(tail.toLowerCase()) ?? idx.get(normalizeBasename(tail));
|
||||
}
|
||||
const hit = idx.get(trimmed) ?? idx.get(trimmed.toLowerCase()) ?? idx.get(normalizeBasename(trimmed));
|
||||
return hit ? [...hit].sort(basenameSort) : [];
|
||||
}
|
||||
|
||||
|
||||
@@ -5565,30 +5565,78 @@ export class PostgresEngine implements BrainEngine {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* perf (#1694 by @Omerbahari): process-lifetime config cache. A single
|
||||
* search fires ~85 getConfig() reads (loadConfigWithEngine x2, plus
|
||||
* mode/cache/intent/rerank/graph-signals resolvers). On a remote pooler
|
||||
* each read is a round-trip; serial they dominate query latency and can
|
||||
* push the op handler past cli.ts's 10s disconnect force-exit, truncating
|
||||
* stdout. First read batch-loads the whole `config` table into this Map
|
||||
* (inside the same connRetry posture as the per-key read — #1603/#1891);
|
||||
* setConfig/unsetConfig write through. TTL bounds staleness for
|
||||
* multi-writer processes; GBRAIN_CONFIG_CACHE_TTL_MS=0 disables.
|
||||
* Only present keys are stored — Map.has() distinguishes known-absent.
|
||||
*/
|
||||
private _configCache: Map<string, string> | null = null;
|
||||
private _configCacheLoadedAt = 0;
|
||||
private _configCacheLoad: Promise<void> | null = null;
|
||||
private get _configCacheTtlMs(): number {
|
||||
const raw = process.env.GBRAIN_CONFIG_CACHE_TTL_MS;
|
||||
if (raw !== undefined) {
|
||||
const n = parseInt(raw, 10);
|
||||
if (Number.isFinite(n) && n >= 0) return n;
|
||||
}
|
||||
return 30_000;
|
||||
}
|
||||
|
||||
async getConfig(key: string): Promise<string | null> {
|
||||
// #1603: a transient pooler drop on this read used to throw / fall through
|
||||
// to defaults silently — which on remote Postgres surfaces as the wrong
|
||||
// search mode/knobs and empty-stdout queries.
|
||||
return this.connRetry(async () => {
|
||||
const rows = await this.sql`SELECT value FROM config WHERE key = ${key}`;
|
||||
return rows.length > 0 ? (rows[0].value as string) : null;
|
||||
});
|
||||
// search mode/knobs and empty-stdout queries. Both the batch load and the
|
||||
// cache-off per-key read keep the connRetry reconnect posture.
|
||||
const ttl = this._configCacheTtlMs;
|
||||
if (ttl === 0) {
|
||||
return this.connRetry(async () => {
|
||||
const rows = await this.sql`SELECT value FROM config WHERE key = ${key}`;
|
||||
return rows.length > 0 ? (rows[0].value as string) : null;
|
||||
});
|
||||
}
|
||||
if (this._configCache === null || Date.now() - this._configCacheLoadedAt >= ttl) {
|
||||
// Single-flight: concurrent cold reads share one batch load.
|
||||
this._configCacheLoad ??= this.connRetry(async () => {
|
||||
const rows = await this.sql`SELECT key, value FROM config` as unknown as
|
||||
Array<{ key: string; value: string | null }>;
|
||||
const map = new Map<string, string>();
|
||||
for (const r of rows) if (r.value != null) map.set(r.key, r.value);
|
||||
this._configCache = map;
|
||||
this._configCacheLoadedAt = Date.now();
|
||||
}).finally(() => {
|
||||
this._configCacheLoad = null;
|
||||
});
|
||||
await this._configCacheLoad;
|
||||
}
|
||||
return this._configCache!.has(key) ? this._configCache!.get(key)! : null;
|
||||
}
|
||||
|
||||
async setConfig(key: string, value: string): Promise<void> {
|
||||
return this.connRetry(async () => {
|
||||
await this.connRetry(async () => {
|
||||
await this.sql`
|
||||
INSERT INTO config (key, value) VALUES (${key}, ${value})
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value
|
||||
`;
|
||||
});
|
||||
// Write-through so a long-lived process never serves stale config.
|
||||
this._configCache?.set(key, value);
|
||||
}
|
||||
|
||||
async unsetConfig(key: string): Promise<number> {
|
||||
return this.connRetry(async () => {
|
||||
const count = await this.connRetry(async () => {
|
||||
const result = await this.sql`DELETE FROM config WHERE key = ${key}` as unknown as { count: number };
|
||||
return result.count ?? 0;
|
||||
});
|
||||
// Write-through: known-absent, so the cache doesn't serve a stale value.
|
||||
this._configCache?.delete(key);
|
||||
return count;
|
||||
}
|
||||
|
||||
async listConfigKeys(prefix: string): Promise<string[]> {
|
||||
|
||||
@@ -29,6 +29,13 @@ if (existsSync(envPath)) {
|
||||
}
|
||||
}
|
||||
|
||||
// E2E suites seed/rewrite the config table via raw SQL and expect engine
|
||||
// reads to see it immediately; disable the process-lifetime config cache
|
||||
// (#1694) so read semantics match pre-cache behavior. Spawned CLI
|
||||
// subprocesses inherit this. Cache semantics are pinned by
|
||||
// test/postgres-engine-config-cache.test.ts.
|
||||
process.env.GBRAIN_CONFIG_CACHE_TTL_MS ??= '0';
|
||||
|
||||
const DATABASE_URL = process.env.DATABASE_URL;
|
||||
const FIXTURES_DIR = resolve(import.meta.dir, 'fixtures');
|
||||
|
||||
|
||||
@@ -209,24 +209,6 @@ describe('gbrain extract --stale', () => {
|
||||
expect(usRows[0]?.eq).toBe(true);
|
||||
});
|
||||
|
||||
test('version-arm floor: page edited BEFORE LINK_EXTRACTOR_VERSION_TS clears after --stale (issue #2576 bug 3)', async () => {
|
||||
// A page whose updated_at predates the version watermark used to be
|
||||
// stamped at its updated_at (< versionTs), so the version arm re-fired
|
||||
// every run — permanently stale. The sweep now floors the stamp at
|
||||
// versionTs. (The #1768 test above also covers this since the v0.42.x
|
||||
// VERSION_TS bump moved its date below the watermark, but this pins the
|
||||
// behavior explicitly so a date "repair" there can't drop coverage.)
|
||||
await engine.putPage('people/alice', personPage('Alice'));
|
||||
await engine.executeRaw(`UPDATE pages SET updated_at = '2000-01-01T00:00:00Z' WHERE slug = 'people/alice'`);
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(1);
|
||||
|
||||
await runExtract(engine, ['--stale']);
|
||||
// Pre-floor this stayed 1 forever (stamp < versionTs → version arm re-fires).
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);
|
||||
await runExtract(engine, ['--stale']);
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);
|
||||
});
|
||||
|
||||
test('CDX-4 (D2): a link-flush throw aborts the sweep and leaves pages UNSTAMPED', async () => {
|
||||
await engine.putPage('people/alice', personPage('Alice'));
|
||||
await engine.putPage('companies/acme', companyPage('Acme', '[Alice](people/alice) founded [Acme](companies/acme).'));
|
||||
|
||||
@@ -140,15 +140,6 @@ describe('extractEntityRefs', () => {
|
||||
expect(wikiRefs[0].needsResolution).toBe(true);
|
||||
});
|
||||
|
||||
test('recognizes ops/ qualified wikilinks (issue #2576 bug 2)', () => {
|
||||
// `ops` was missing from DIR_PATTERN, so [[ops/...]] fell through to
|
||||
// the generic 2c pass (needsResolution) instead of being a real ref.
|
||||
const refs = extractEntityRefs('Deployed via [[ops/services/pointer-agent]].');
|
||||
expect(refs.length).toBe(1);
|
||||
expect(refs[0].slug).toBe('ops/services/pointer-agent');
|
||||
expect(refs[0].needsResolution).toBeUndefined();
|
||||
});
|
||||
|
||||
test('skips qualified-syntax tokens (those belong to 2a)', () => {
|
||||
// [[wiki:topics/ai]] looks like 2a's qualified shape — even though
|
||||
// it wouldn't satisfy DIR_PATTERN, 2c must not claim it either
|
||||
@@ -1078,15 +1069,6 @@ describe('makeResolver — fallback chain', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('resolveBasenameMatches: path-style ref falls back to the tail (issue #2576 bug 2)', async () => {
|
||||
// normalizeBasename strips slashes, so `runbooks/2026-05-01-pointer-agent`
|
||||
// used to normalize to a garbage key that never hit the tail-keyed index.
|
||||
const engine = makeFakeEngineWithSlugs(['ops/changes/2026-05-01-pointer-agent']);
|
||||
const r = makeResolver(engine);
|
||||
expect(await r.resolveBasenameMatches!('runbooks/2026-05-01-pointer-agent'))
|
||||
.toEqual(['ops/changes/2026-05-01-pointer-agent']);
|
||||
});
|
||||
|
||||
test('resolveBasenameMatches: case-insensitive fallback', async () => {
|
||||
const engine = makeFakeEngineWithSlugs(['companies/fast-weigh']);
|
||||
const r = makeResolver(engine);
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Process-lifetime config cache (#1694 takeover, by @Omerbahari).
|
||||
*
|
||||
* A single search fires ~85 getConfig() reads; on a remote pooler each is a
|
||||
* round-trip. The first read now batch-loads the whole `config` table into a
|
||||
* Map; setConfig/unsetConfig write through; TTL bounds multi-writer
|
||||
* staleness; GBRAIN_CONFIG_CACHE_TTL_MS=0 restores per-key reads.
|
||||
*
|
||||
* Pure: stubs `_sql` with a call-counting fake; no real DB.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'bun:test';
|
||||
import { PostgresEngine } from '../src/core/postgres-engine.ts';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
|
||||
const FAST_RETRY = { maxRetries: 3, delayMs: 1, delayMaxMs: 1, jitter: 'none' as const };
|
||||
|
||||
/** Engine whose `sql` records every query's template strings and returns `rows`. */
|
||||
function makeEngine(rows: unknown[]) {
|
||||
const e = new PostgresEngine();
|
||||
const calls: string[] = [];
|
||||
(e as unknown as { _connectionStyle: string })._connectionStyle = 'instance';
|
||||
(e as unknown as { _bulkRetryOptsCache: unknown })._bulkRetryOptsCache = FAST_RETRY;
|
||||
(e as unknown as { _sql: unknown })._sql = (strings: TemplateStringsArray) => {
|
||||
calls.push(strings.join('?'));
|
||||
return Promise.resolve(rows);
|
||||
};
|
||||
return { engine: e, calls };
|
||||
}
|
||||
|
||||
/** Run `fn` with GBRAIN_CONFIG_CACHE_TTL_MS set (or cleared when undefined). */
|
||||
const withTtl = (ttl: string | undefined, fn: () => Promise<void>) =>
|
||||
withEnv({ GBRAIN_CONFIG_CACHE_TTL_MS: ttl }, fn);
|
||||
|
||||
describe('PostgresEngine config cache (#1694)', () => {
|
||||
it('batch-loads once and serves repeat reads from the cache', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([
|
||||
{ key: 'search.mode', value: 'balanced' },
|
||||
{ key: 'embedding_multimodal', value: 'true' },
|
||||
]);
|
||||
expect(await engine.getConfig('search.mode')).toBe('balanced');
|
||||
expect(await engine.getConfig('embedding_multimodal')).toBe('true');
|
||||
expect(await engine.getConfig('search.mode')).toBe('balanced');
|
||||
// One SELECT total — this is the whole point of the fix.
|
||||
expect(calls.length).toBe(1);
|
||||
expect(calls[0]).toContain('SELECT key, value FROM config');
|
||||
}));
|
||||
|
||||
it('returns null for a known-absent key without an extra round-trip', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'a', value: '1' }]);
|
||||
expect(await engine.getConfig('missing.key')).toBeNull();
|
||||
expect(await engine.getConfig('missing.key')).toBeNull();
|
||||
expect(calls.length).toBe(1);
|
||||
}));
|
||||
|
||||
it('setConfig writes through so subsequent reads see the new value', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'k', value: 'old' }]);
|
||||
expect(await engine.getConfig('k')).toBe('old');
|
||||
await engine.setConfig('k', 'new');
|
||||
expect(await engine.getConfig('k')).toBe('new');
|
||||
expect(calls.length).toBe(2); // batch load + upsert; no re-read
|
||||
}));
|
||||
|
||||
it('unsetConfig writes through so subsequent reads see absence', () => withTtl(undefined, async () => {
|
||||
const { engine } = makeEngine([{ key: 'k', value: 'v' }]);
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
await engine.unsetConfig('k');
|
||||
expect(await engine.getConfig('k')).toBeNull();
|
||||
}));
|
||||
|
||||
it('concurrent cold reads share a single batch load (single-flight)', () => withTtl(undefined, async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'k', value: 'v' }]);
|
||||
const [a, b, c] = await Promise.all([
|
||||
engine.getConfig('k'),
|
||||
engine.getConfig('k'),
|
||||
engine.getConfig('other'),
|
||||
]);
|
||||
expect([a, b, c]).toEqual(['v', 'v', null]);
|
||||
expect(calls.length).toBe(1);
|
||||
}));
|
||||
|
||||
it('GBRAIN_CONFIG_CACHE_TTL_MS=0 disables the cache (per-key reads)', () => withTtl('0', async () => {
|
||||
const { engine, calls } = makeEngine([{ value: 'v' }]);
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
expect(calls.length).toBe(2);
|
||||
expect(calls[0]).toContain('SELECT value FROM config WHERE key =');
|
||||
}));
|
||||
|
||||
it('an expired TTL reloads from the database', () => withTtl('1', async () => {
|
||||
const { engine, calls } = makeEngine([{ key: 'k', value: 'v' }]);
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
expect(await engine.getConfig('k')).toBe('v');
|
||||
expect(calls.length).toBe(2); // two batch loads
|
||||
}));
|
||||
|
||||
it('the batch load keeps the connRetry reconnect posture (#1603/#1891)', () => withTtl(undefined, async () => {
|
||||
const e = new PostgresEngine();
|
||||
(e as unknown as { _connectionStyle: string })._connectionStyle = 'instance';
|
||||
(e as unknown as { _sql: unknown })._sql = null; // torn-down pool → retryable
|
||||
(e as unknown as { _bulkRetryOptsCache: unknown })._bulkRetryOptsCache = FAST_RETRY;
|
||||
let reconnects = 0;
|
||||
(e as unknown as { reconnect: () => Promise<void> }).reconnect = async () => {
|
||||
reconnects++;
|
||||
(e as unknown as { _sql: unknown })._sql = () =>
|
||||
Promise.resolve([{ key: 'k', value: 'v' }]);
|
||||
};
|
||||
expect(await e.getConfig('k')).toBe('v');
|
||||
expect(reconnects).toBe(1);
|
||||
}));
|
||||
});
|
||||
@@ -43,7 +43,9 @@ function makeTornDownEngine(poolResult: unknown): { engine: PostgresEngine; reco
|
||||
|
||||
describe('PostgresEngine non-batch config accessors self-heal (PR #1891 takeover)', () => {
|
||||
it('getConfig reconnects + retries a null instance pool, then returns the value', async () => {
|
||||
const { engine, reconnects } = makeTornDownEngine([{ value: 'live-value' }]);
|
||||
// Rows carry `key` too: getConfig's default cached path batch-loads
|
||||
// `SELECT key, value FROM config` (#1694) through the same connRetry.
|
||||
const { engine, reconnects } = makeTornDownEngine([{ key: 'some.key', value: 'live-value' }]);
|
||||
expect(await engine.getConfig('some.key')).toBe('live-value');
|
||||
expect(reconnects()).toBe(1); // exactly one reconnect closed the gap
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user