OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: pi extension handlers exceed the host's 30s budget — unbounded recall fallback ladder (35s reproduced) and 28s takeover overview poll

Open taonos opened this issue 2 months ago • 0 comments

Issue Origin

Observed or reproduced in a real environment (host-side error observed 25 times; the recall over-budget chain reproduced directly, the takeover chain measured at 28s of its 30s budget).

Bug Description

examples/pi-coding-agent-extension runs multi-step OpenViking work inline inside host event handlers whose worst cases are sized against a 60s allowance, while the pi host (@oh-my-pi/pi-coding-agent, omp) caps every extension handler except tool_call at a hard-coded 30s. When the server is slow enough to push a chain past that cap, the host logs

Extension "…/extensions/openviking/index.ts" error: handler timed out after 30000ms

and discards the handler's return value. It does not cancel the handler, so the chain keeps running and its side effects land after the host has moved on.

The sizing assumption is written down in shared/recall-core.mjs:163-175:

Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with a quarter to spare.

That allowance does not exist on this host. In @oh-my-pi/pi-coding-agent (18.2.8, dist/cli.js) the budget is K5 = 30000, returned by the per-event resolver for every event except session_shutdown, and only extensionHandlers.toolCallTimeoutMs is configurable — non-tool handlers have no knob.

Two handler bodies are affected.

1. context → recall ladder (reproduced over budget: 35,009 ms). index.ts awaits recall.searchPending() → buildRecallBlock, whose fallback ladder is three sequential requests, each with its own independent fuse:

rung code fuse
context face /api/v1/search/search shared/recall-core.mjs:174, :188-193 (EXPANSION_REQUEST_TIMEOUT_MS) 15s (45s when rewrite is requested)
/recall fallback shared/recall-core.mjs:591-601 10s
find per source + per-item content reads searchAllSources, resolveItemContent 10s each

No overall deadline spans the ladder, so a stalled server walks all three rungs and the handler cannot finish inside 30s. With rewrite on, rung 1 alone (45s) exceeds the cap.

2. turn_end / session_before_compact → takeover commit + overview poll (28,006 ms of the 30,000 ms budget, before any real work). lib/takeover-core.mjs commitAndAdvance() does flush → commit (client fuse 30s in client.ts) → pollOverview(), and pollOverview is takeoverOverviewPollMax × takeoverOverviewPollMs = 15 × 2000ms by default (lib/takeover-core.mjs:8-10, :385-397). Measured with an instant stub server and the overview never ready, the sleeps alone consume 28.0s, leaving ~2s for the commit and 15 overview round trips. I did not reproduce this one past 30s; it is a margin that any real latency closes.

Why the timeout is not merely cosmetic. The host aborts only its own signal; the extension never observes it and runs to completion:

  • context: after searchPending() eventually resolves, injectRecall still runs and still records to the recall ledger (lib/recall-ledger.mjs) — for a block the host already threw away. The ledger then claims an injection the provider never received and re-applies it on the next turn, which is exactly the prompt-prefix divergence the ledger exists to prevent.
  • turn_end: once polling finally returns an overview, lib/takeover-core.mjs:288-296 advances coveredUserTurns and calls persist() — after the handler was declared timed out.

Consequently a bare Promise.race guard at the handler boundary is not a sufficient fix: it satisfies the host but leaves both late side effects intact. A fix needs either a cancellation signal threaded into the chain, or an expiry check before the ledger write and the boundary advance.

Steps to Reproduce

  1. Install examples/pi-coding-agent-extension into an omp/pi host (~/.omp/agent/extensions/openviking), pointed at an OpenViking server, with takeoverEnabled: true and defaults elsewhere.
  2. Make the server slow to answer /api/v1/search/search (the reproduction below substitutes a stub that never answers inside the fuse).
  3. Send any prompt long enough to pass minQueryLength, so the context handler runs recall.
  4. Host log shows Extension handler timed out … "event":"context","timeoutMs":30000, and the turn's provider request carries no recall block.
  5. For the takeover path: let a turn cross takeoverTokenThreshold while the archive overview is not yet ready, and time commitAndAdvance().

Expected Behavior

Each handler body finishes inside the host's per-handler budget, degrading gracefully when the server is slow: recall is skipped for that turn, or the takeover commit is deferred to the next one — with no host-level error, and no state written after the host has discarded the handler's result.

Actual Behavior

The host logs handler timed out after 30000ms and drops the handler's return value while the chain continues in the background. In one day of logs on a single machine: 25 occurrences — 15 context, 9 turn_end, 1 session_before_compact. The bursts track subagent fan-out (9 subagent sessions launched together; 6 context handlers expired in the same 70ms window 30s later).

Note on attribution: the specific trigger for each logged event is inferred, not observed — the extension's debugLogPath was unset for those turns, so I cannot prove which rung of the ladder each one reached. Live probes taken now are fast (health 32ms, recall 181-1206ms, 9 concurrent recalls 1.2s total) and say nothing about server behaviour at the time. What is demonstrated is the vulnerability and its size, not a per-event cause.

Minimal Reproducible Example

// Bun. Points the shipped modules at a stub server that never answers in time,
// then times the two handler chains against the host's 30,000ms cap.
const dir = "<install>/extensions/openviking";
const { loadConfig } = await import(`${dir}/config.ts`);
const { OVClient } = await import(`${dir}/client.ts`);
const rc = await import(`${dir}/shared/recall-core.mjs`);
const { TakeoverCore } = await import(`${dir}/lib/takeover-core.mjs`);

const server = Bun.serve({
  port: 0,
  async fetch(req) {
    if (new URL(req.url).pathname === "/health") return Response.json({ status: "ok", result: {} });
    await Bun.sleep(60000);                     // never answers inside the fuse
    return Response.json({ status: "ok", result: {} });
  },
});
const cfg = { ...loadConfig(dir), endpoint: `http://127.0.0.1:${server.port}` };
const client = new OVClient(cfg);
const fj = (p, i, o) => client.fetchJSON(p, i, o);

// 1. the `context` handler's recall chain
let t = Date.now();
const stages = [];
await rc.buildRecallBlockDetailed(fj, cfg, "why does the handler time out", {
  actorPeerId: cfg.peerId, legacyPeerId: cfg.legacyPeerId, sessionId: "repro",
  legacyCachePath: "/tmp/ov-repro-face.json",
  log: (ev) => stages.push(`${ev}@${Date.now() - t}ms`),
});
console.log("context recall chain:", Date.now() - t, "ms", stages.join(" "));

// 2. the `turn_end` handler's takeover chain (sleeps only, instant server)
t = Date.now();
const core = new TakeoverCore({
  config: { ...cfg, takeoverEnabled: true },
  io: {
    flush: async () => true,
    commit: async () => ({ task_id: "t" }),
    fetchOverview: async () => "",              // overview not ready yet
    persistEntry: () => {}, getWatermark: () => 0, log: () => {},
  },
});
core.lastSeenUserTurns = 99;
await core.onTurnSynced(cfg.takeoverTokenThreshold + 1);
console.log("turn_end takeover commit+poll:", Date.now() - t, "ms");
server.stop(true);

Output:

context recall chain: 35009 ms
  recall_context_face_error@15005ms recall_endpoint_fallback@25007ms recall_search_summary@35009ms
turn_end takeover commit+poll: 28006 ms

Error Logs

{"timestamp":"2026-09-21T18:39:46.499-07:00","level":"warn","message":"Extension handler timed out","extensionPath":"/home/hxucaa/.omp/agent/extensions/openviking/index.ts","event":"context","timeoutMs":30000}
{"timestamp":"2026-09-21T18:39:46.499-07:00","level":"error","message":"Extension error","path":"/home/hxucaa/.omp/agent/extensions/openviking/index.ts","error":"handler timed out after 30000ms"}
{"timestamp":"2026-09-21T18:39:46.512-07:00","level":"warn","message":"Extension handler timed out","extensionPath":"…/openviking/index.ts","event":"context","timeoutMs":30000}
{"timestamp":"2026-09-21T10:15:09.382-07:00","level":"warn","message":"Extension handler timed out","extensionPath":"…/openviking/index.ts","event":"turn_end","timeoutMs":30000}
{"timestamp":"2026-09-21T18:50:41.546-07:00","level":"warn","message":"Extension handler timed out","extensionPath":"…/openviking/index.ts","event":"session_before_compact","timeoutMs":30000}

OpenViking Version

Server v0.4.20; openviking-pi-extension 0.3.2

Python Version

N/A — the defect is in the TypeScript/JS extension (server is 0.4.20 on Python 3.12)

Operating System

Linux

Model Backend

Other

Additional Context

Suggested direction

  1. Give the recall ladder one overall deadline, well under the tightest host budget, and skip rungs 2-3 once it is spent — the per-request fuses currently sum without any cap.
  2. Bring pollOverview's worst case under the same budget (smaller takeoverOverviewPollMax/Ms defaults, or resume polling on a later turn instead of blocking the current handler).
  3. Make late completion harmless: on expiry, skip the ledger write and the coveredUserTurns advance rather than letting them land after the host discarded the result.
  4. Consider making the harness budget a config value per harness adapter, since the 60s assumption in shared/recall-core.mjs:163-175 is host-specific and wrong for at least this one.

Test gap

tests/takeover-core.test.mjs exercises pollOverview with takeoverOverviewPollMs: 1, takeoverOverviewPollMax: 3, so the shipped 2000 × 15 worst case is never measured, and nothing in tests/ asserts any handler-level budget. Worth a case that bounds the shipped defaults, plus one that an expired handler produces no ledger write and no boundary advance.

Scope

shared/recall-core.mjs is generated from examples/memory-plugin-shared/lib, and lib/takeover-core.mjs is vendored the same way, so downstream ports that vendor those cores inherit both budgets. Whether other harnesses are affected depends on their own handler caps; the 60s assumption should be verified per harness rather than assumed.

taonos avatar Sep 22 '26 02:09 taonos