Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(engine-migrate): add request timeout, stale-response guard, and invalidate cache on switch

Steven Enamakel98657c16dcb3
diff --git a/app/src/components/intelligence/useMemoryEngineCapabilities.ts b/app/src/components/intelligence/useMemoryEngineCapabilities.ts
index b314101559..445ad793e2 100644
--- a/app/src/components/intelligence/useMemoryEngineCapabilities.ts
+++ b/app/src/components/intelligence/useMemoryEngineCapabilities.ts
@@ -12,6 +12,7 @@ const log = debug('brain:memory-engine');
/** How long a fetched engine snapshot is reused by views mounting close together. */
export const MEMORY_ENGINE_CACHE_TTL_MS = 5000;
+const MEMORY_ENGINE_REQUEST_TIMEOUT_MS = 10_000;
export interface MemoryEngineView {
/** True until the first answer (or failure) arrives. */
@@ -44,6 +45,7 @@ const INITIAL: Snapshot = { loading: true, engines: [], current: null, error: nu
let snapshot: Snapshot = INITIAL;
let inflight: Promise<void> | null = null;
+let revision = 0;
const listeners = new Set<(s: Snapshot) => void>();
function publish(next: Snapshot) {
@@ -56,13 +58,24 @@ function publish(next: Snapshot) {
* in-flight request and callers within the TTL share its result.
*/
function fetchSnapshot(force: boolean): Promise<void> {
- if (inflight) return inflight;
+ if (inflight) {
+ return inflight.then(() =>
+ force && snapshot.fetchedAt === 0 ? fetchSnapshot(true) : undefined
+ );
+ }
const fresh =
snapshot.fetchedAt > 0 && Date.now() - snapshot.fetchedAt < MEMORY_ENGINE_CACHE_TTL_MS;
if (!force && fresh && snapshot.error === null) return Promise.resolve();
+ const requestedRevision = revision;
inflight = (async () => {
try {
- const [list, current] = await Promise.all([memoryEnginesList(), memoryEngineGet()]);
+ const [list, current] = await Promise.race([
+ Promise.all([memoryEnginesList(), memoryEngineGet()]),
+ new Promise<never>((_, reject) =>
+ setTimeout(() => reject(new Error("Memory engine status request timed out")), MEMORY_ENGINE_REQUEST_TIMEOUT_MS)
+ ),
+ ]);
+ if (requestedRevision !== revision) return;
log('loaded engines=%d active=%s', list.engines.length, current.driver);
publish({
loading: false,
@@ -73,7 +86,9 @@ function fetchSnapshot(force: boolean): Promise<void> {
});
} catch (err) {
log('unavailable: %o', err);
- publish({ ...snapshot, loading: false, error: err, fetchedAt: Date.now() });
+ if (requestedRevision === revision) {
+ publish({ ...snapshot, loading: false, error: err, fetchedAt: Date.now() });
+ }
} finally {
inflight = null;
}
@@ -83,13 +98,15 @@ function fetchSnapshot(force: boolean): Promise<void> {
/** Drop the cached snapshot (after a switch) so the next reader re-fetches. */
export function invalidateMemoryEngine(): void {
- snapshot = { ...snapshot, fetchedAt: 0 };
+ revision += 1;
+ publish({ ...snapshot, fetchedAt: 0 });
}
/** Test seam: forget everything, including subscribers' last value. */
export function resetMemoryEngineCacheForTests(): void {
snapshot = INITIAL;
inflight = null;
+ revision = 0;
}
/**
diff --git a/app/src/components/settings/panels/MemoryEnginePanel.tsx b/app/src/components/settings/panels/MemoryEnginePanel.tsx
index 5e8a79deb9..375bbdb818 100644
--- a/app/src/components/settings/panels/MemoryEnginePanel.tsx
+++ b/app/src/components/settings/panels/MemoryEnginePanel.tsx
@@ -26,7 +26,7 @@ import {
type MemoryEngineState,
type MemoryEngineTarget,
} from '../../../utils/tauriCommands/memoryEngine';
-import { useMemoryEngine } from '../../intelligence/useMemoryEngineCapabilities';
+import { invalidateMemoryEngine, useMemoryEngine } from '../../intelligence/useMemoryEngineCapabilities';
import { Alert, AlertDescription, Button, CenteredLoadingState } from '../../ui';
import { RadioGroupRoot } from '../../ui/RadioGroup';
import SettingsPanel from '../layout/SettingsPanel';
@@ -225,6 +225,8 @@ export default function MemoryEnginePanel() {
try {
await memoryEngineSet(target);
log('engine set driver=%s', target.driver);
+ invalidateMemoryEngine();
+ await refresh();
if (!mounted.current) return;
await finishSwitch(target.driver);
} catch (err) {
diff --git a/crates/openhuman-core/src/memory/ops/engine_migrate.rs b/crates/openhuman-core/src/memory/ops/engine_migrate.rs
index 0a4987cf39..c76bb62c6a 100644
--- a/crates/openhuman-core/src/memory/ops/engine_migrate.rs
+++ b/crates/openhuman-core/src/memory/ops/engine_migrate.rs
@@ -261,6 +261,9 @@ async fn run_job<F, Fut>(
);
}
CopyEnd::Finished(Ok(report)) => {
+ // The copy is past its cancellation point. Removing the signal
+ // makes concurrent cancel requests report `cancelled: false`.
+ cancels().remove(&job_id);
update_job(&job_id, |j| j.copied = report.records);
match commit().await {
Ok(()) => {
@@ -283,8 +286,7 @@ async fn run_job<F, Fut>(
/// Shown on a finished job: what the copy cannot promise.
const WRITES_DURING_COPY_NOTE: &str =
- "Memories written while the copy was running may not have been \
- copied. The previous engine still holds them; migrate again to copy any that are missing.";
+ "Memories written while the copy was running may not have been copied. The previous engine still holds them; this migration does not provide a second-pass delta copy.";
/// Spawn [`run_job`] under a supervisor so a panic fails the job instead of
/// leaving it "running" forever.
diff --git a/gitbooks/developing/engines.md b/gitbooks/developing/engines.md
index fc189289e4..f9d99b93bd 100644
--- a/gitbooks/developing/engines.md
+++ b/gitbooks/developing/engines.md
@@ -94,8 +94,7 @@ switches only after a clean copy; the source is never modified, and a failed
run leaves the active engine alone. A running copy can be cancelled (`engine_migrate_cancel`, between pages), is
bounded by `OPENHUMAN_MEMORY_MIGRATE_TIMEOUT_SECS` (default 2 hours) and fails, not
hangs, if its task panics. Records written while a copy runs may be missing from
-the new engine; the job result carries a `note` saying so, and migrating again
-copies them. `OPENHUMAN_MEMORY_DRIVER` pins the engine and makes the switch RPCs
+the new engine; the job result carries a `note` saying so, and this migration does not provide a second-pass delta copy. `OPENHUMAN_MEMORY_DRIVER` pins the engine and makes the switch RPCs
refuse.
`binding::admit` admits `tinymemory` (with `tinycortex` kept as a legacy
diff --git a/scripts/mock-api/routes/memory.mjs b/scripts/mock-api/routes/memory.mjs
index 3b4fa8cd29..286500e489 100644
--- a/scripts/mock-api/routes/memory.mjs
+++ b/scripts/mock-api/routes/memory.mjs
@@ -125,6 +125,11 @@ export async function handleMemory(ctx) {
const body = parsedBody && typeof parsedBody === "object" ? parsedBody : {};
if (route === "experience" && method === "POST") {
+ const key = String(body.idempotency_key || "").trim();
+ if (!key) {
+ fail(res, 400, "MISSING_IDEMPOTENCY_KEY", "idempotency_key is required");
+ return true;
+ }
const claim = req.headers?.["idempotency-key"];
if (claim) {
if (store.claims.has(claim)) {
@@ -133,7 +138,6 @@ export async function handleMemory(ctx) {
}
store.claims.add(claim);
}
- const key = String(body.idempotency_key || "");
const text = String(textOf(body) ?? "");
const seen = store.idempotency.get(key);
if (seen) {
@@ -201,10 +205,14 @@ export async function handleMemory(ctx) {
const ids = Array.isArray(body.selector?.memory_ids)
? body.selector.memory_ids.map(String)
: [];
- const narrowed = ["about_subject", "about_entity", "predicate"].some(
+ const unsupported = ["about_subject", "about_entity", "predicate"].some(
(f) => body.selector && body.selector[f] !== undefined,
);
- const selective = ids.length > 0 || narrowed;
+ if (unsupported) {
+ fail(res, 400, "UNSUPPORTED_SELECTOR", "the memory mock supports only memory_ids selectors");
+ return true;
+ }
+ const selective = ids.length > 0;
if (selective && body.confirm_all === true) {
fail(res, 400, "AMBIGUOUS_SELECTOR_CONFIRM_ALL");
return true;
@@ -214,8 +222,9 @@ export async function handleMemory(ctx) {
return true;
}
const before = store.events.length;
+ const requestedIds = new Set(ids);
store.events = selective
- ? store.events.filter((e) => !ids.includes(e.id))
+ ? store.events.filter((e) => e.scope !== scope || !requestedIds.has(e.id))
: store.events.filter((e) => e.scope !== scope);
const deleted = before - store.events.length;
ok(res, {