Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(rpc-proxy,hcc): guard doomed wake retriggers and derive fresh-read outcome

Alfredo Lopez7b703875a5ca
diff --git a/desktop-app/src/__tests__/appService.wakeScopeMatrix.issue791.test.ts b/desktop-app/src/__tests__/appService.wakeScopeMatrix.issue791.test.ts
index 75133e673..d2945c91b 100644
--- a/desktop-app/src/__tests__/appService.wakeScopeMatrix.issue791.test.ts
+++ b/desktop-app/src/__tests__/appService.wakeScopeMatrix.issue791.test.ts
@@ -81,7 +81,15 @@ function firstScope(issueRpcTokenForHostRefs: ReturnType<typeof vi.fn>): unknown
// ── POSITIVE: the nine finite operations that must request host:wake:write ──
//
-// Each entry is one of the exactly-nine on-demand operations from plan §11.4.
+// Plan §11.4 makes TWELVE routes wake-capable. NINE of them map to operations
+// whose scope arrays THIS PR changes, and those nine are the cases below
+// (session ×4, model ×1, artifact ×2, approval ×2). The remaining three —
+// invokeHostMessage, getTaskResult, cancelTask — ride
+// HOST_FINITE_OPERATION_SCOPES.message, which already carried the wake scope on
+// origin/dev, so this PR adds no scope for them and there is nothing here to
+// pin. 9 + 3 = 12: the two counts describe different nouns (operations changed
+// vs routes wake-capable), not an inconsistency.
+//
// The assertion is the FULL exact scope array, wake scope included — a widening
// that dropped or reordered a scope would fail loudly here.
@@ -158,8 +166,21 @@ describe('issue #791 — finite operations request host:wake:write in addition t
// ── NEGATIVE: observability reads and every SSE stream must NEVER request wake ──
//
// A suspended stateless Host must stay suspended under polling and streaming, or
-// observability would defeat scale-to-zero. These assert the EXACT non-wake
-// scope AND that no issued token on these surfaces carries host:wake:write.
+// observability would defeat scale-to-zero.
+//
+// SCOPE OF THIS ASSERTION — read carefully before strengthening it. The harness
+// stubs issueRpcTokenForHostRefs and inspects mock.calls[n][0], so these tests
+// prove that no stream/observability surface REQUESTS the wake scope. They do
+// NOT — and cannot — prove anything about the token actually DELIVERED:
+// RpcTokenManager reuses a cached token whose scopes are a superset of the
+// request (pinned in test/rpcTokenManager.test.ts), so a stream may legitimately
+// run on a token that already carries host:wake:write.
+//
+// That is safe because possessing the scope is not what wakes a Host: rpc-proxy
+// triggers a wake only from its explicit per-route allowlist plus the positive
+// isWakeCapable gate (wakeAndHold.ts). The no-wake-on-streams invariant is
+// therefore enforced SERVER-SIDE and survives a maximally-scoped token; these
+// client-side tests pin the request shape, which is the half the client owns.
// (The status-stream reconnect lifecycle is additionally guarded by
// appService.prewarm.test.ts.)
diff --git a/desktop-app/test/rpcTokenManager.test.ts b/desktop-app/test/rpcTokenManager.test.ts
index c5df4f1e7..4126151c4 100644
--- a/desktop-app/test/rpcTokenManager.test.ts
+++ b/desktop-app/test/rpcTokenManager.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { describe, it, expect, vi } from "vitest";
vi.mock("../src/config.js", () => ({
config: { requestTimeoutMs: 5000, externalRestApiBaseUrl: "http://localhost:8091" },
@@ -86,6 +86,7 @@ describe("RpcTokenManager — getOrIssue()", () => {
// Override to return fresh token
vi.mocked(authClient.issueRpcToken).mockResolvedValueOnce({
token: "rpc-fresh-2",
+ accessScope: "team",
teamId: "team-1",
scopes: ["host:message:invoke"],
hostRefs: ["chatllm"],
@@ -107,3 +108,50 @@ describe("RpcTokenManager — getOrIssue()", () => {
expect(meta.hostRefs).toContain("chatllm");
});
});
+
+// ── Subset-scope reuse: INTENTIONAL, pinned on purpose ────────────────────────
+//
+// A narrower request is satisfied from a cached SUPERSET token, so the token a
+// caller receives can carry scopes it did not ask for — including
+// host:wake:write on a stream/observability surface. That is deliberate: it
+// keeps issuance to one round trip instead of one per distinct scope set, and
+// it is NOT a wake risk, because possessing the scope never wakes a Host —
+// rpc-proxy triggers a wake only from its explicit per-route allowlist plus the
+// isWakeCapable gate (wakeAndHold.ts).
+//
+// This test exists so the behavior is a pinned contract rather than an
+// undocumented side effect: if someone later makes stream open a wake-capable
+// route, or narrows this cache to exact-scope keying, one of these two
+// assertions turns red and forces the decision to be made explicitly.
+describe("RpcTokenManager — subset scope reuse", () => {
+ it("serves a narrower request from the cached superset token, which still carries host:wake:write", async () => {
+ const authClient = {
+ issueRpcToken: vi.fn().mockResolvedValue({
+ token: "rpc-token-superset",
+ accessScope: "team",
+ teamId: "team-1",
+ scopes: ["host:activity:read", "host:task:read", "host:wake:write"],
+ hostRefs: ["chatllm"],
+ expiresInSeconds: 60,
+ }),
+ } as unknown as AuthClient;
+ const manager = new RpcTokenManager(authClient);
+
+ // Broad issuance (e.g. a finite operation that legitimately needs wake).
+ await manager.getOrIssue(
+ "sess-token",
+ ["host:activity:read", "host:task:read", "host:wake:write"],
+ ["chatllm"]
+ );
+ expect(authClient.issueRpcToken).toHaveBeenCalledOnce();
+
+ // Narrower request (e.g. an observability read) — served from cache.
+ const reused = await manager.getOrIssue("sess-token", ["host:activity:read"], ["chatllm"]);
+
+ // 1. Exactly ONE issuance: the subset did not trigger a second round trip.
+ expect(authClient.issueRpcToken).toHaveBeenCalledOnce();
+ // 2. The DELIVERED token is the cached superset — it still carries wake.
+ expect(reused.token).toBe("rpc-token-superset");
+ expect(reused.scopes).toContain("host:wake:write");
+ });
+});
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index aa17fbbd2..57c6f56ae 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -3919,7 +3919,16 @@ export class HostReconciler {
capturedWatchGeneration: capturedAuthority.generation,
currentWatchGeneration: this.hostWatchAuthority().generation,
currentCacheOmitsHost: !cacheHasHost(hostName),
- freshAuthoritativeRead: 'confirmed404',
+ // Derived, not hardcoded. `presence` is provably 'absent' here (the
+ // 'present' and 'error' branches returned above), so this evaluates
+ // to the identical literal and the runtime behavior is unchanged.
+ // Deriving it makes the mapping total: if readHostPresence ever
+ // grows a fourth outcome, the else-branch type stops satisfying
+ // freshAuthoritativeRead's union and the compiler rejects it —
+ // instead of silently labelling a non-404 read as 'confirmed404'
+ // in a value that is DECISIONAL (a conjunct of
+ // destructiveCleanupAllowed, :94-95), not telemetry.
+ freshAuthoritativeRead: presence === 'absent' ? 'confirmed404' : presence,
})
) {
hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })
diff --git a/host-context-controller/src/statelessDeployment.ts b/host-context-controller/src/statelessDeployment.ts
index c7c52df60..a21f3c573 100644
--- a/host-context-controller/src/statelessDeployment.ts
+++ b/host-context-controller/src/statelessDeployment.ts
@@ -126,6 +126,11 @@ fi
# state/state.db. Preserve the older destination as state/<db>.pre-<ts>.bak
# (NOTHING is ever deleted), then let the fresher root source migrate in via the
# normal path below. The destination is proven non-symlink above.
+# WHY positional implies temporal: every stateless boot MOVES the SQLite set out
+# of root into state/ (the mv loops below), so root is left with no state.db. A
+# root state.db can therefore only have been (re)created by a STATEFUL life that
+# ran strictly AFTER the last stateless life — which is what makes "root source"
+# equivalent to "newer source" here, with no timestamp read required.
root_dest_collision=0
if [ "$root_sqlite_source" -eq 1 ]; then
for db in state.db state.db-wal state.db-shm; do
diff --git a/rpc-proxy/src/services/__tests__/wakeAndHold.test.ts b/rpc-proxy/src/services/__tests__/wakeAndHold.test.ts
index 9fbdd5b2c..61a32b2a9 100644
--- a/rpc-proxy/src/services/__tests__/wakeAndHold.test.ts
+++ b/rpc-proxy/src/services/__tests__/wakeAndHold.test.ts
@@ -304,6 +304,38 @@ describe('kill-switch and poll-source failure while held', () => {
await pending
})
+ it('skips a retrigger whose wake authorization has expired, keeps holding, and does not settle', async () => {
+ // Drive the guard through the class's OWN injectable clock (deps.now, read
+ // via this.now()) rather than mutating global time. That is how the rest of
+ // this suite controls time, and it keeps the guard's predicate observable
+ // without a wall-clock side effect.
+ let clockMs = Date.now()
+ const { coordinator, requestWake, probeReady } = makeCoordinator({ now: () => clockMs })
+ requestWake.mockResolvedValue({ kind: 'wake-requested', wakeGeneration: 1 })
+ probeReady.mockResolvedValue(false)
+
+ const tokenExpMs = clockMs + 60_000
+ const pending = coordinator.hold(holdParams({ tokenExpMs }))
+ expect(requestWake).toHaveBeenCalledTimes(1) // initial wake only
+
+ // Drive the guard's precondition: the retrigger tick lands AFTER the wake
+ // authorization expired. Advancing the injected clock without advancing the
+ // timer queue models a blocked event loop / scheduler delay — the entry is
+ // still unsettled and holding, but its token is now inside the safety margin.
+ clockMs = tokenExpMs - 1_000
+ await vi.advanceTimersByTimeAsync(RETRIGGER_MS)
+
+ // The doomed POST is NOT spent...
+ expect(requestWake).toHaveBeenCalledTimes(1)
+ // ...and the hold survives: the entry is still tracked, not settled, so the
+ // readiness poll can still release this waiter.
+ expect(coordinator.trackedHostCount()).toBe(1)
+
+ // Drain: let the hold reach its deadline so the pending promise resolves.
+ await vi.advanceTimersByTimeAsync(MAX_HOLD_MS)
+ await pending
+ })
+
it('releases held requests via the legacy path when the wake endpoint turns 409 mid-hold', async () => {
const { coordinator, requestWake, probeReady } = makeCoordinator()
requestWake
diff --git a/rpc-proxy/src/services/wakeAndHold.ts b/rpc-proxy/src/services/wakeAndHold.ts
index c65f804cf..8deb30309 100644
--- a/rpc-proxy/src/services/wakeAndHold.ts
+++ b/rpc-proxy/src/services/wakeAndHold.ts
@@ -400,6 +400,21 @@ export class WakeAndHoldCoordinator {
}
const scheduleRetrigger = () => {
entry.retriggerTimer = setTimeout(async () => {
+ // Hygiene: a retrigger whose wake authorization has already expired is
+ // doomed — control-api would reject it — so skip the call rather than
+ // spend it. We deliberately KEEP HOLDING: the readiness poll runs on its
+ // own timer and the entry still has TTL left, so a host that wakes via
+ // any other path still resolves this waiter. Rescheduling matters
+ // because a later waiter can adopt this entry and upgrade
+ // `wakeAuthorization` to a longer-lived token, after which retriggers
+ // resume. Same predicate as the adopt path above.
+ if (entry.wakeAuthorization.tokenExpMs - TOKEN_EXP_SAFETY_MARGIN_MS <= this.now()) {
+ console.debug(
+ `[RPC_PROXY] wake retrigger skipped (wake authorization expired) host=${entry.hostRef}`
+ )
+ if (!entry.settled) scheduleRetrigger()
+ return
+ }
await this.issueWake(entry, { initial: false })
if (entry.settled) {
console.debug(