Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(engine-scope): an entry point inside its own engine scope never re-enters it

garrytan8a1ed0a10dc4
diff --git a/src/core/engine-scope.ts b/src/core/engine-scope.ts
index ff584ab583..3d76dfda59 100644
--- a/src/core/engine-scope.ts
+++ b/src/core/engine-scope.ts
@@ -24,7 +24,7 @@ export function withEngineScope<T>(engine: object, fn: () => T): T {
/** True in a process that opened an embedded engine when the call does not run in `engine`'s scope yet: the entry point re-enters itself in it. */
export function needsEngineScope(engine: object): boolean {
const current = scope.getStore();
- return processHasEmbeddedEngines() && (current === undefined || engineKey(current) !== engineKey(engine));
+ return processHasEmbeddedEngines() && (current === undefined || (current !== engine && engineKey(current) !== engineKey(engine)));
}
/** The engine scope the current call runs in, for deferred work to resume in with runInEngineScope. */
diff --git a/test/engine-scope-identity.test.ts b/test/engine-scope-identity.test.ts
new file mode 100644
index 0000000000..7cf1d2b273
--- /dev/null
+++ b/test/engine-scope-identity.test.ts
@@ -0,0 +1,26 @@
+/**
+ * An entry point that re-enters itself in its engine's scope (importFromFile, hybridSearch: needsEngineScope) must see
+ * that scope as its own once inside it, whatever the engine object returns for its root key. A Proxy engine that
+ * answers every property with a fresh value (the mock engines the import tests use) made engineKey differ on every
+ * read, so importFromFile re-entered itself until the stack overflowed in any process that had opened an embedded
+ * engine earlier (test/engine-scope-required.test.ts then test/import-file.test.ts in one shard).
+ */
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { openEngine, withEngineScope } from '../src/core/engine-open.ts';
+import { needsEngineScope } from '../src/core/engine-scope.ts';
+
+test('inside withEngineScope(engine), needsEngineScope(engine) is false even when engineKey is unstable', async () => {
+ const embedded = await openEngine({
+ embedded_core: true, engine: 'pglite', database: {}, host: { id: randomUUID() },
+ embedding: { model: 'openai:text-embedding-3-small', dimensions: 1536 }, ai: { providers: {} },
+ });
+ try {
+ const unstable = new Proxy({}, { get: () => () => undefined });
+ expect(needsEngineScope(unstable)).toBe(true);
+ expect(withEngineScope(unstable, () => needsEngineScope(unstable))).toBe(false);
+ expect(withEngineScope(embedded, () => needsEngineScope(embedded))).toBe(false);
+ } finally {
+ await embedded.disconnect();
+ }
+});