happier icon indicating copy to clipboard operation
happier copied to clipboard

CLI pending queue pump retries forever on 401, causing server unresponsiveness

Open danljungstrom opened this issue 7 months ago • 1 comments

Summary

The CLI daemon's pending queue polling loop does not distinguish between "nothing to materialize" and "auth failure (401)". When a daemon holds a stale/expired token, the pending pump retries POST /v2/sessions/:id/pending/materialize-next every ~1 second indefinitely, generating millions of failed requests that eventually cause the server (especially SQLite-backed light deployments) to become unresponsive.

Root Cause

In apps/cli/src/api/session/pendingQueueV2Transport.ts:79-106, tryMaterializeNextViaHttp has a catch-all that swallows all errors (including 401 Unauthorized) and returns { ok: false }:

// Line 103
} catch {
    return { ok: false };
}

The caller (materializeNextPendingQueueV2Message at line 108) treats { ok: false } as "try HTTP fallback" or "nothing happened", and the upstream pending pump loop (createAcpRuntime.ts:232-314) interprets this as "no pending messages right now, poll again after pollIntervalMs".

The result: a 401 response is indistinguishable from a transient network error, and the pump never stops.

Impact (observed on production light server)

  • 1.6 million failed 401 requests to a single session's materialize-next endpoint
  • 1.2 GB log file (happier-stack.out.log) — 22M lines, mostly these 401s
  • SQLite write contention: the constant request volume causes legitimate DB operations (usageReport.upsert, session.update during session-end) to hit "Socket timeout" errors
  • Server becomes unresponsive to real client requests, requiring an LXC container reboot to recover

Reproduction

  1. Start a Happier light server (SQLite-backed)
  2. Start a CLI daemon that connects and begins polling pending queue for a session
  3. Invalidate the daemon's auth token (e.g., restart the server so tokens rotate, or let the token expire)
  4. Observe: materialize-next returns 401 every ~1 second indefinitely
  5. After hours/days, server responsiveness degrades due to log I/O and SQLite contention

Suggested Fix

Primary fix (CLI — pending queue transport)

In apps/cli/src/api/session/pendingQueueV2Transport.ts, the HTTP fallback should distinguish 401/403 from other errors:

// tryMaterializeNextViaHttp — instead of catch-all:
} catch (error: unknown) {
    if (axios.isAxiosError(error) && (error.response?.status === 401 || error.response?.status === 403)) {
        // Signal auth failure distinctly so the pump can stop or re-auth
        return { ok: false, authFailed: true };
    }
    return { ok: false };
}

The pending pump in createAcpRuntime.ts should then check authFailed and abort the loop rather than retrying.

Secondary fix (CLI — socket RPC path)

The same pattern exists in tryMaterializeNextViaSocket (line 62-77) — socket disconnection or auth rejection is also swallowed into { ok: false }.

Tertiary fix (Server — defense in depth)

The materialize-next HTTP route (pendingRoutes.ts:378-440) has a rate limit of 120/min, but this only applies after auth succeeds. The 401 responses bypass it since app.authenticate rejects before the handler runs. Consider rate-limiting at the auth middleware level for repeated 401s from the same source.

Minor fix (Server — shutdown race)

The session-end handler in sessionUpdateHandler.ts:322-363 performs DB writes (session.findUnique + session.update) that are not wrapped in keepAlive(). During shutdown, these race with onShutdown('db') (Prisma disconnect), causing "Socket timeout" errors. While non-fatal (caught by try/catch), wrapping in keepAlive() or checking isShutdown() would eliminate the noise.

Files to Modify

File Change
apps/cli/src/api/session/pendingQueueV2Transport.ts Distinguish 401/403 from transient errors in both HTTP and socket paths
apps/cli/src/agent/acp/runtime/createAcpRuntime.ts Stop pending pump on auth failure instead of retrying
apps/server/sources/app/api/socket/sessionUpdateHandler.ts (Optional) Wrap session-end DB ops in keepAlive()

Diagnostic Commands

# Check if the polling is happening on your server:
grep -c "materialize-next" /path/to/happier-stack.out.log

# Check if all calls are failing auth:
grep "materialize-next" /path/to/happier-stack.out.log | grep -c "Auth failed"

# Check log file size:
du -sh /path/to/happier-stack.out.log

# Find the offending daemon (on the machine running the CLI):
ps aux | grep happier | grep daemon

Immediate Workaround

  1. Find and kill the rogue daemon process on the machine that's polling
  2. Truncate the bloated log file: truncate -s 0 /path/to/happier-stack.out.log
  3. The server will recover without a reboot

danljungstrom avatar Apr 16 '26 08:04 danljungstrom

Created prematurely — will re-file after proper review.

danljungstrom avatar Apr 16 '26 08:04 danljungstrom