Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): #6712 PR 4b fix 3, a level looks up a file name's parser once per suffix

garrytanc221ceea0048
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 4baaf4a05d..48f71cb692 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -1061,6 +1061,30 @@ export function syncImportParserFor(path: string, schemaPack: string | null): Sy
return syncImportParser(schemaPack);
}
+/**
+ * One parser per importer kind (`syncImportParserFor`) for a whole level, not one object per path. The kind is a test on
+ * the suffix from the path's last dot (every image and code extension is a dot and a dot-free suffix), so a file name's
+ * suffix is looked up once per level. A path whose last dot sits in a directory name asks `syncImportKind` itself, so the
+ * lookup holds file-name suffixes only, never one entry per path.
+ */
+export function syncImportParsers(schemaPack: string | null): (path: string) => SyncImportParser {
+ const parsers = new Map<string, SyncImportParser>(), bySuffix = new Map<string, SyncImportParser>();
+ const ofKind = (path: string) => {
+ const kind = syncImportKind(path);
+ let parser = parsers.get(kind);
+ if (!parser) parsers.set(kind, parser = syncImportParserFor(path, schemaPack));
+ return parser;
+ };
+ return path => {
+ const dot = path.lastIndexOf('.');
+ if (dot < 0 || path.indexOf('/', dot) >= 0) return ofKind(path);
+ const suffix = path.slice(dot);
+ let parser = bySuffix.get(suffix);
+ if (!parser) bySuffix.set(suffix, parser = ofKind(path));
+ return parser;
+ };
+}
+
const provenanceFingerprint = (sourceId: string, incarnation: string, pageId: number) => `${sourceId}:${incarnation}:${pageId}`;
export async function recordSyncImportProvenance(tx: Exec, value: Omit<SyncImportProvenance, 'recorded_at' | 'validated'>): Promise<void> {
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 4977fc0766..facf2c17bc 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -31,7 +31,7 @@ import { sourceMirrorReadOnly } from './mirror-read-only.ts';
import { colonFileRefusal, COLON_REFUSAL_MESSAGES, readSyncFile, resolveManagedSyncContext, syncExcludePatterns, syncGit, type ManagedSyncContext, type SyncFileRefusal } from './sync-discovery.ts';
import { isWindowsColonTarget } from './native-file-target.ts';
import { confirmedSyncDelta } from '../sync-rename-identity.ts';
-import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, syncImportKind, syncImportParser, syncImportParserFor,
+import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, syncImportParser, syncImportParsers,
type GitHoldRecord, type SyncImportParser, type SyncImportProvenance } from './sync-holds.ts';
import { movedDriftHolds, sameParser } from './sync-prescreen.ts';
import { sameSyncOrigin, selectOriginClaimant, syncOriginPath } from './sync-origin.ts';
@@ -712,7 +712,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
return level === baselineOf(path);
});
- const parserFor = parserByKind(pack?.identity ?? null);
+ const parserFor = syncImportParsers(pack?.identity ?? null);
const fp = (path: string) => parserFor(sourceRelative(path));
// The page's fields come straight from `pages` (no `PageRow` per path); `at` is its slot, undefined for a page-less path.
const stateOf = (path: string, dirty: SyncPathState['dirty'], probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): { state: SyncPathState; at?: number; legacyPageless?: true } => {
@@ -980,7 +980,7 @@ export async function passWritesMatched(exec: Exec, input: { kind: 'postgres' |
if (!read || read.pages.length !== input.ids.length) return false;
const writers = new Map((await exec.executeRaw<{ id: string; level: string | null; path: string | null }>(`SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path
FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])`, [input.sourceId, input.ids])).map(row => [row.id, row]));
- const pages = read.pages, parserFor = parserByKind(input.pack);
+ const pages = read.pages, parserFor = syncImportParsers(input.pack);
for (let i = 0; i < pages.length; i++) {
const writer = writers.get(String(pages.id[i])), level = writer?.level ?? null, sourcePath = pages.sourcePath[i]!;
if (!writer?.path || level === null || pages.deleted(i) || !pages.hasRecord(i)) return false;
@@ -1005,17 +1005,6 @@ async function readLevelHolds(engine: BrainEngine, sourceId: string, incarnation
return { holds, retry: new Set(retryPaths.filter(path => !retryConsumed?.has(path))), moved: [...basisMoved, ...driftMoved] };
}
-/** One parser per importer kind (`syncImportParserFor`) for a whole level, not one object per path. */
-function parserByKind(schemaPack: string | null): (path: string) => SyncImportParser {
- const parsers = new Map<string, SyncImportParser>();
- return path => {
- const kind = syncImportKind(path);
- let parser = parsers.get(kind);
- if (!parser) parsers.set(kind, parser = syncImportParserFor(path, schemaPack));
- return parser;
- };
-}
-
/**
* Master refuses a spelling only among the files its sync claims (sync-discovery.ts:538-541): the live page's origin and the
* page-less spellings that changed since the cursor. A page-less spelling unchanged since the baseline was never claimed
diff --git a/test/sync-import-parsers-6712.test.ts b/test/sync-import-parsers-6712.test.ts
new file mode 100644
index 0000000000..f2e3886e6f
--- /dev/null
+++ b/test/sync-import-parsers-6712.test.ts
@@ -0,0 +1,31 @@
+/**
+ * #6712 PR 4b fix 3: a level asks for the parser a page at each path records (sync-holds.ts `syncImportParsers`), and
+ * looks a file name's suffix up once per level instead of testing every image and code extension per path.
+ *
+ * Protects: the per-level lookup returns, for every path, the parser `syncImportParserFor` returns, and one object per
+ * kind: for every image and code extension in either case, Markdown, no dot, a dot in a directory name, several dots,
+ * a dotted directory followed by an extension, and with or without a schema pack; a suffix seen first under one path
+ * answers alike for every later path that shares it.
+ */
+import { expect, test } from 'bun:test';
+import { syncImportParserFor, syncImportParsers } from '../src/core/persistence/sync-holds.ts';
+import { CODE_EXTENSIONS } from '../src/core/sync.ts';
+
+const IMAGES = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.heic', '.heif', '.avif'];
+
+test('the per-level lookup returns the parser syncImportParserFor returns, one object per kind', () => {
+ const paths = ['', '.', 'README', 'a.', 'notes/a.md', 'notes/a.MD', 'dir.ts/file', 'dir.png/file.md', 'dir.md/file.ts', 'x.d.ts', 'a.tar.gz', '.ts', 'v1.2/notes', 'x.\u212At'];
+ for (const ext of [...CODE_EXTENSIONS, ...IMAGES, '.md', '.mdx']) for (const stem of ['a', 'dir/a', 'dir.v2/a.b'])
+ paths.push(stem + ext, stem + ext.toUpperCase(), `${stem}${ext}/inner`, stem + ext.slice(0, -1));
+ for (const pack of [null, 'pack-a']) {
+ const lookup = syncImportParsers(pack), seen = new Map<string, ReturnType<typeof syncImportParserFor>>();
+ for (const order of [paths, [...paths].reverse()]) for (const path of order) {
+ const got = lookup(path), want = syncImportParserFor(path, pack);
+ expect({ path, got }).toEqual({ path, got: want });
+ const key = JSON.stringify(want);
+ if (!seen.has(key)) seen.set(key, got);
+ expect(got).toBe(seen.get(key)!);
+ }
+ expect(seen.size).toBe(3);
+ }
+});