ml-intern icon indicating copy to clipboard operation
ml-intern copied to clipboard

Background sessions on Mongo control plane (Main + Worker topology)

Open akseljoonas opened this issue 7 months ago โ€ข 9 comments

Summary

v1 of "background-running ml-intern": agent sessions survive SSE drops, browser close, and Main Space restarts. Frontend is unchanged โ€” backend-only refactor.

  • Topology: 1 Main Space + N Worker Spaces, same Docker image, MODE=main|worker env var differentiates. Worker Spaces have no public HTTP โ€” they consume a Mongo-backed work queue.
  • Universal control plane: All inter-process comms go through MongoDB. The in-memory submission_queue is replaced; EventBroadcaster is kept as an opt-in read-side cache attached only when this process holds the lease (so foreground SSE skips the change-stream round-trip).
  • Lease + heartbeat ownership: findOneAndUpdate CAS on sessions.lease. TTL = 30 s, renew every 10 s. Lease loss triggers requeue_claimed_for(holder_id) and drops the session locally so a Worker can pick up orphaned submissions.
  • Three migration triggers all converge on release_session_to_background(reason): SSE-drop grace period (default 180 s), manual POST /api/session/{id}/background, and Main lifespan shutdown for active turns. Each emits a migrating session_event the frontend can render as "reconnecting".
  • Worker idle eviction: 30-minute default; predicate is not is_in_tool_call AND not is_processing AND no pending_submissions in Mongo.

Acceptance drills (manual, post-deploy)

  1. Close laptop, come back: Start a session that launches a long-running tool (HF Job training), close the tab, wait 3+ minutes, reopen 30 minutes later. Frontend replays the missed events; pending approval is visible; approve and the session resumes.
  2. Main restart with active turn: Start a session mid-tool-call, force-restart Main (or docker restart). A Worker claims the lease within 30 s; the user reconnects to a fresh Main and sees the turn continuing without an interrupted event.

Both drills are runnable locally against docker run mongo:7 --replSet rs0 + 2 processes (MODE=main and MODE=worker). See the new "Background sessions deployment" section in AGENTS.md.

Test plan

  • [x] 83 new unit tests added across 6 files, all passing
    • [x] tests/test_session_persistence_lease.py (12) โ€” atomic CAS, FIFO, requeue ordering preservation, idempotent backfill
    • [x] tests/test_session_manager_lease.py (12) โ€” holder identity, claim wiring, heartbeat renewal + loss handling, lease release in finally
    • [x] tests/test_session_manager_submissions.py (18) โ€” enqueue paths, holder/non-holder interrupt, FIFO drain, inline interrupt/shutdown handling, poison containment
    • [x] tests/test_sse_holder_overlay.py (7) โ€” holder fast path, non-holder change stream, polling fallback on PyMongoError, subscriber counter attach/detach
    • [x] tests/test_lifespan_grace_sweep.py (8) โ€” release_session_to_background event emission, grace-sweep predicate matrix, /background route 200/404
    • [x] tests/test_worker_idle_eviction.py (13) โ€” idle predicate matrix, claim_dormant_session user-bypass + lease-taken paths, claim-tick skips already-held
  • [x] Pre-existing unit suite still green (248 passing; two unrelated pre-existing test_doom_loop failures verified via git stash)
  • [x] ruff check clean on every file modified by this PR (pre-existing E402/F401/F841 in main.py and routes/agent.py predate this branch)
  • [ ] Manual: drill 1 (close laptop) on the deployed Spaces
  • [ ] Manual: drill 2 (Main restart with active turn) on the deployed Spaces
  • [ ] Manual: pre-deploy baseline db.sessions.count({runtime_state: "processing"}) to capture blast-radius

Deployment notes (see AGENTS.md for the full runbook)

  1. Roll Workers first with the new code. They start consuming pending_submissions against any session whose lease has expired, but won't see anything new until Main also rolls.
  2. Then roll Main. MongoSessionStore.init() runs an idempotent backfill: sessions with last_active_at > now-1h and no lease get an empty lease so the next CAS succeeds; older sessions flip to runtime_state: idle (still recoverable, never ended).
  3. The lifespan shutdown sweep on the OLD Main releases active-turn leases via release_session_to_background(reason="main_shutdown"); Workers pick them up within 30 s.

Required env vars:

Var Default Effect
MODE main worker flips to the worker-loop entrypoint
MONGODB_URI unset Required for the control plane; without it falls back to NoopSessionStore (CLI compatibility)
GRACE_PERIOD_SECONDS 180 SSE-drop grace before background migration
IDLE_EVICTION_SECONDS 1800 Worker idle eviction TTL

MONGODB_URI must point at a replica set (Atlas works out of the box) for change-stream support. Single-node Mongo falls back to 500 ms polling.

Process & follow-ups

  • Design produced via /deep-dive (8 interview rounds + 3-lane causal trace) and refined via /plan --consensus --direct (Architect + Critic over 2 iterations, both APPROVED). Spec, trace, and consensus plan are committed under .omc/specs/ and .omc/plans/ for posterity.
  • Final architect verification: APPROVE WITH MINOR CLEANUP. Five LOW-severity follow-ups deferred to v1.1:
    1. Heartbeat misleading-WARN guard when session drops mid-iteration
    2. delete_session requeue ordering (race window for clean-delete UI)
    3. claim_dormant_session lease release on rebuild failure (TTL recovers in 30 s)
    4. pending_submissions payload size guard (16 MB BSON ceiling)
    5. Mongo-outage chaos test in CI

Risks

  • Mongo replica set is now a hard production requirement (was advisory). Single-node deployments degrade to polling and break _lease_heartbeat_loop renewals on outage โ€” heartbeat returns None, _on_lease_lost cleans up gracefully, clients reconnect.
  • Latency: foreground SSE consumers stay at today's profile (broadcaster fast path). Cross-process consumers see 50โ€“200 ms p50 from the change-stream tail.
  • Worker capacity at v1: MAX_SESSIONS_PER_WORKER ร— N Workers. Scaling is operational (deploy more Workers); the lease design supports it without code changes.

Out of scope (deferred)

  • Push notifications when away (NotificationGateway stays opt-in, only Slack provider wired)
  • Async-dashboard UX rebuild
  • 10k concurrent simultaneous load test (design accommodates it; v1 ships at 1 Main + 2 Workers)
  • Tool-call double-execution / Worker-crash idempotency (Workers assumed stable in v1)

akseljoonas avatar May 01 '26 18:05 akseljoonas

PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [ ] Read git diff and key changed files
  • [ ] Review session persistence / lease logic
  • [ ] Review session manager changes
  • [ ] Review routes / main.py changes
  • [ ] Review worker entrypoint and start.sh
  • [ ] Review test coverage
  • [ ] Post findings

View job run

github-actions[bot] avatar May 01 '26 18:05 github-actions[bot]

PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [ ] Read git diff and key changed files
  • [ ] Review session persistence / lease logic
  • [ ] Review session manager changes
  • [ ] Review routes / main.py changes
  • [ ] Review worker entrypoint and start.sh
  • [ ] Review test coverage
  • [ ] Post findings

View job run

github-actions[bot] avatar May 01 '26 18:05 github-actions[bot]

Claude finished @akseljoonas's task in 6m 36s โ€”โ€” View job


PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [x] Read git diff and key changed files
  • [x] Review session persistence / lease logic
  • [x] Review session manager changes
  • [x] Review routes / main.py changes
  • [x] Review worker entrypoint and start.sh
  • [x] Review test coverage
  • [x] Post findings

2 P0, 3 P1 Verdict: changes requested

What I checked

  • Lease CAS logic: claim_lease / renew_lease / release_lease in session_persistence.py
  • Full reconnect path from _check_session_access โ†’ ensure_session_loaded โ†’ _sse_response
  • _on_lease_lost scope and which submissions requeue_claimed_for touches
  • Heartbeat error handling (renew_lease on PyMongoError)
  • SSE holder/non-holder branching in _sse_response and whether the non-holder path is reachable via HTTP
  • Worker claim tick: _worker_claim_tick query and session discovery
  • Lifespan shutdown sweep: active-turn handover to Workers
  • shutdown_session lock scope with external I/O inside
  • New /background route auth guard
  • _backfill_lease_state migration safety
  • Unit test coverage (read test stubs for test_sse_holder_overlay.py, test_session_manager_lease.py)

P0 โ€” Reconnect to Worker-held session returns 404 (acceptance drill 2 is broken)

ensure_session_loaded requires claiming the lease before returning a session object. When a Worker holds the session's lease, claim_lease returns None (filter lease.expires_at < now OR holder_id IS NULL doesn't match a fresh Worker-held lease). ensure_session_loaded returns None at session_manager.py:843โ€“847, and _check_session_access raises HTTP 404 at routes/agent.py:190โ€“192.

This blocks every endpoint โ€” including GET /api/events/{session_id} (the SSE reconnect endpoint) and POST /api/chat/{session_id}. The non-holder Mongo change-stream slow path in _sse_response (routes/agent.py:799โ€“861) is unreachable via HTTP for Worker-held sessions: _check_session_access raises 404 before _sse_response is ever called.

The unit tests in test_sse_holder_overlay.py call _sse_response directly with a pre-constructed AgentSession(holder_id="other:host:zzz") that is already in manager.sessions, so they bypass _check_session_access entirely and do not catch this gap.

Acceptance drill 2 states: "A Worker claims the lease within 30 s; the user reconnects to a fresh Main and sees the turn continuing." This cannot happen because Main returns 404 for any session whose lease is currently held by a Worker.

Fix direction: ensure_session_loaded (and/or _check_session_access) needs a read-only path for sessions where the lease is held by another process. When claim_lease fails because another holder owns an unexpired lease, the function could return a lightweight stub AgentSession with holder_id set to the current holder's ID (read from the Mongo doc) and broadcaster=None. _sse_response already branches correctly on is_holder and handles agent_session with a foreign holder_id via the Mongo change-stream path โ€” the non-holder code path works as designed; the problem is only that it is never reached. Fix this โ†’


P0 โ€” _on_lease_lost requeues in-flight submissions for ALL held sessions, not just the one that lost its lease

_on_lease_lost(session_id) at session_manager.py:270 calls:

requeued = await store.requeue_claimed_for(self._holder_id)

requeue_claimed_for (session_persistence.py:707โ€“710) runs:

await self.db.pending_submissions.update_many(
    {"status": "claimed", "claimed_by": holder_id},
    ...
)

This flips every claimed submission for this holder back to pending โ€” across all sessions this process holds, not just session_id.

Concrete double-execution scenario: Main holds sessions A and B. B is mid-tool-call: claim_pending_submission has already set its submission to claimed. A's renew_lease returns None (either because another process took it, or because of a transient PyMongoError โ€” see P1 below). _on_lease_lost(A) fires, calls requeue_claimed_for(Main._holder_id), and resets B's in-flight submission to pending. A Worker claims B's submission and starts executing it. Main's _drain_and_process finishes processing the same submission and calls mark_submission_done. Two processes have now executed the same submission against the same session context.

Fix direction: Pass session_id to requeue_claimed_for and filter on it: {"status": "claimed", "claimed_by": holder_id, "session_id": session_id}. Fix this โ†’


P1 โ€” renew_lease returns None on PyMongoError, which the heartbeat loop treats identically to "lease stolen"

session_persistence.py:614โ€“617:

except PyMongoError as e:
    logger.warning(...)
    return None

session_manager.py:249โ€“254:

renewed = await store.renew_lease(session_id, self._holder_id, ttl_s=30)
if renewed is None:
    # Lease lost โ€” someone else holds it now.
    await self._on_lease_lost(session_id)

A transient Mongo network error fires _on_lease_lost, cancels the session's task, and (because of P0 #2) requeues in-flight submissions for all concurrently held sessions โ€” on a temporary outage, not an actual lease theft.

Fix: renew_lease should raise (or return a sentinel distinct from None) on PyMongoError so the heartbeat loop can skip and retry rather than treating it as a lost lease. Fix this โ†’

P1 โ€” release_lease leaves holder_id intact; heartbeat can re-acquire a just-released lease

release_lease (session_persistence.py:624โ€“630) sets lease.expires_at = now but does NOT clear lease.holder_id. After release_session_to_background releases the lease and pops the session from self.sessions (session_manager.py:332โ€“333), the heartbeat loop may have already snapshotted session_ids (between lines 246โ€“248) before the pop. The heartbeat then calls renew_lease(session_id, holder_id), whose filter matches {"_id": session_id, "lease.holder_id": holder_id} โ€” the holder_id was not cleared. This re-extends the lease by 30 s, blocking the Worker from claiming the session for up to one full TTL after the intended handover. Fix this โ†’

P1 โ€” shutdown_session holds _lock for up to 5 seconds while awaiting task completion

session_manager.py:1446โ€“1462 acquires self._lock and then calls both await self._store().release_lease(...) (external I/O) and await asyncio.wait_for(agent_session.task, timeout=5.0) inside the locked region. The lock is held for up to 5 seconds, serializing every other lock-requiring operation (heartbeat snapshot, release_session_to_background, grace-period sweep). Fix: release the lock before awaiting the task โ€” move release_lease and wait_for outside async with self._lock. Fix this โ†’


Overall: the core data-plane primitives (CAS lease, FIFO claim, change-stream tail, requeue) are well-designed and the test suite is thorough. The P0s are both in the boundary between the persistence layer and the session/route layer โ€” they are fixable with targeted changes. The non-holder SSE path is fully implemented and just needs to be made reachable.

github-actions[bot] avatar May 01 '26 18:05 github-actions[bot]

Claude finished @akseljoonas's task in 1m 47s โ€”โ€” View job


PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [x] Check P0 #1: reconnect-to-Worker-held session (ensure_session_loaded)
  • [x] Check P0 #2: _on_lease_lost requeues all sessions (requeue_claimed_for scope)
  • [x] Check P1 fixes (renew_lease sentinel, release_lease holder_id, shutdown_session lock)
  • [x] Post findings

2 P0 still open (unchanged from prior review), 3 P1 not yet addressed Verdict: changes requested

What I checked

  • ensure_session_loaded (session_manager.py:828โ€“878) โ€” lease-claim path when another holder owns the session
  • _on_lease_lost + requeue_claimed_for (session_manager.py:263โ€“284, session_persistence.py:710โ€“729) โ€” scope of submission requeue
  • renew_lease error handling (session_persistence.py:628โ€“630) โ€” PyMongoError sentinel
  • release_lease update (session_persistence.py:638โ€“641) โ€” whether holder_id is cleared
  • shutdown_session lock scope (session_manager.py:1478โ€“1491) โ€” I/O inside lock
  • Heartbeat snapshot/iteration loop (session_manager.py:240โ€“261) โ€” no changes

P0 โ€” Reconnect to Worker-held session returns 404 (unchanged)

ensure_session_loaded (session_manager.py:874โ€“878) still returns None when claim_lease returns None:

if claimed is None:
    logger.info(
        f"Refusing restore of {session_id}: lease held by another process"
    )
    return None

_check_session_access in routes/agent.py raises HTTP 404 on None. The non-holder change-stream slow path in _sse_response remains unreachable via HTTP for any session currently held by a Worker. Acceptance drill 2 is still broken. Fix this โ†’

P0 โ€” _on_lease_lost requeues in-flight submissions for ALL held sessions (unchanged)

_on_lease_lost (session_manager.py:272) still calls:

requeued = await store.requeue_claimed_for(self._holder_id)

requeue_claimed_for (session_persistence.py:719โ€“724) still filters only on {"status": "claimed", "claimed_by": holder_id} โ€” no session_id predicate. A single lease loss triggers a broad requeue across every session this holder owns, enabling the double-execution scenario described in the prior review. Fix this โ†’


The three P1s from the prior review (renew_lease PyMongoError sentinel, release_lease holder_id clear, shutdown_session lock scope) are also still open but not re-flagged here per re-review policy.

github-actions[bot] avatar May 01 '26 18:05 github-actions[bot]

PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [ ] Check P0 #1: ensure_session_loaded reconnect path for Worker-held sessions
  • [ ] Check P0 #2: _on_lease_lost / requeue_claimed_for scope
  • [ ] Check P1 fixes (renew_lease sentinel, release_lease holder_id, shutdown_session lock)
  • [ ] Post findings

View job run

github-actions[bot] avatar May 01 '26 18:05 github-actions[bot]

Claude finished @akseljoonas's task in 5m 21s โ€”โ€” View job


Claude finished @akseljoonas's task โ€”โ€” View job


PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [x] Check P0 #1: ensure_session_loaded reconnect path for Worker-held sessions
  • [x] Check P0 #2: _on_lease_lost / requeue_claimed_for scope
  • [x] Check P1 fixes (renew_lease sentinel, release_lease holder_id, shutdown_session lock)
  • [x] Post findings

1 P0 Verdict: changes requested

What I checked

  • ensure_session_loaded stub construction (session_manager.py:892โ€“933) โ€” lease-claim failure path, stub fields, insertion guard
  • _check_session_access + _enforce_gated_model_quota interaction (routes/agent.py:179โ€“196, 139โ€“157) โ€” what stub flows trigger with session=None
  • _sse_response is_holder branch (routes/agent.py:790โ€“794) โ€” whether stub reaches the non-holder change-stream path
  • _on_lease_lost + requeue_claimed_for (session_manager.py:281โ€“307, session_persistence.py:719โ€“750) โ€” session_id scope fix
  • renew_lease PyMongoError propagation (session_persistence.py:615โ€“633) + heartbeat catch (session_manager.py:265โ€“270)
  • release_lease holder_id clear (session_persistence.py:635โ€“652)
  • shutdown_session lock scope (session_manager.py:1521โ€“1555)

Acknowledged fixes from prior review

All five prior findings are addressed:

  • P0 #1 (reconnect to Worker-held session): ensure_session_loaded now returns a stub AgentSession with holder_id=foreign_holder and broadcaster=None instead of None. _sse_response correctly takes the non-holder change-stream slow path because is_holder evaluates to False (broadcaster is None). SSE reconnect now works. โœ“
  • P0 #2 (_on_lease_lost requeues all sessions): _on_lease_lost now passes session_id=session_id to requeue_claimed_for (session_manager.py:292โ€“293); requeue_claimed_for filters on that field when provided (session_persistence.py:737โ€“738). Double-execution vector is closed. โœ“
  • P1 (renew_lease PyMongoError): renew_lease now propagates PyMongoError; the heartbeat loop catches it at session_manager.py:265 and skips with continue, never calling _on_lease_lost. โœ“
  • P1 (release_lease holder_id not cleared): release_lease now sets lease.holder_id: None alongside lease.expires_at: now (session_persistence.py:649), closing the heartbeat re-acquire window. โœ“
  • P1 (shutdown_session lock scope): Only the sessions.get lookup runs inside self._lock; release_lease and wait_for(task) run outside it (session_manager.py:1538โ€“1553). โœ“

P0 โ€” Stub with session=None crashes _enforce_gated_model_quota on submit/chat endpoints

The stub returned by ensure_session_loaded for Worker-held sessions is constructed with session=None (session_manager.py:922). _enforce_gated_model_quota (routes/agent.py:156) unconditionally dereferences agent_session.session.config.model_name:

# routes/agent.py:154-156
if agent_session.claude_counted:
    return
model_name = agent_session.session.config.model_name  # AttributeError if session is None

The stub's claude_counted defaults to False (not read from the Mongo doc), so the early-return guard does not fire. Every invocation of _enforce_gated_model_quota against a stub raises AttributeError, which FastAPI surfaces as HTTP 500.

Affected paths (all call _check_session_access then _enforce_gated_model_quota):

  • POST /api/submit (routes/agent.py:598โ€“599) โ€” user submitting text to an ongoing Worker turn
  • POST /api/chat/{session_id} (routes/agent.py:641โ€“654) โ€” combined submit+stream
  • POST /api/approve reaches _check_session_access but does not call _enforce_gated_model_quota, so it is not affected by this specific crash โ€” but it would still return a stub that submit_approval would then handle correctly via the Mongo queue.

Scenario (post-drill-2): Worker holds session S. User reconnects from a fresh Main โ€” SSE works. User then sends a new message: POST /api/submit โ†’ ensure_session_loaded returns stub (session=None) โ†’ _enforce_gated_model_quota crashes โ†’ HTTP 500.

Fix direction: In _enforce_gated_model_quota, add a guard for session=None โ€” stubs represent sessions executing on a remote Worker and do not need local quota enforcement (the Worker already enforced quota when it built the real session). A one-line guard suffices:

if agent_session.session is None:
    return  # stub for remotely-held session; quota enforced by holder

Alternatively, read claude_counted from the loaded Mongo doc in the stub constructor so the guard at line 154 fires for already-charged sessions. Fix this โ†’

github-actions[bot] avatar May 01 '26 18:05 github-actions[bot]

Claude finished @akseljoonas's task in 1m 39s โ€”โ€” View job


PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [x] Check P0: _enforce_gated_model_quota crash with session=None stub
  • [x] Check for any new issues in the latest commit
  • [x] Post findings

1 P0 Verdict: changes requested

What I checked

  • _enforce_gated_model_quota (routes/agent.py:139โ€“170) โ€” session null guard
  • Stub AgentSession construction in ensure_session_loaded (session_manager.py:896โ€“933) โ€” session=None, claude_counted default
  • POST /submit and POST /chat/{session_id} call sites (routes/agent.py:598โ€“599, 653โ€“654)
  • Latest commit cd65715 (frontend-only: "Run-in-background button") โ€” no new backend changes

Acknowledged fixes from prior review

The prior P0 finding from the last review round (the _enforce_gated_model_quota crash) is not yet addressed. Commit 07f0a85 ("Fix P0/P1 lease-handover correctness issues") touched session_persistence.py, session_manager.py, and tests โ€” but not routes/agent.py.


P0 โ€” _enforce_gated_model_quota crashes on stub session (unchanged from prior review)

ensure_session_loaded still returns a stub with session=None at session_manager.py:922. _enforce_gated_model_quota at routes/agent.py:156 unconditionally dereferences agent_session.session.config.model_name:

# routes/agent.py:154-156
if agent_session.claude_counted:
    return
model_name = agent_session.session.config.model_name  # AttributeError when session=None

The stub's claude_counted is not set in the constructor (session_manager.py:920โ€“933), so it defaults to False (session_manager.py:112), and the early-return guard at line 154 does not fire.

Affected paths:

  • POST /api/submit (routes/agent.py:598โ€“599) โ€” user sending text while a Worker holds the session
  • POST /api/chat/{session_id} (routes/agent.py:653โ€“654) โ€” when text is not None and not approvals

Both raise AttributeError โ†’ HTTP 500 for any submit to a Worker-held session.

Fix: add a session=None guard at the top of _enforce_gated_model_quota, before line 154:

if agent_session.session is None:
    return  # stub for remotely-held session; quota enforced by holder

Alternatively, populate claude_counted=bool(meta.get("claude_counted")) in the stub constructor at session_manager.py:920โ€“933 so already-charged sessions hit the existing guard. The one-line guard is the safer and more self-documenting fix. Fix this โ†’

github-actions[bot] avatar May 02 '26 09:05 github-actions[bot]

PR Review: Background sessions on Mongo control plane

Tasks

  • [ ] Gather context (CLAUDE.md, REVIEW.md)
  • [ ] Check prior P0: _enforce_gated_model_quota crash with session=None stub
  • [ ] Review new commits (token_crypto.py, credential encryption, drill 1 fixes)
  • [ ] Spot-check correctness of credential encryption / session resume
  • [ ] Look for new agent-loop / streaming regressions
  • [ ] Post findings

View job run

github-actions[bot] avatar May 15 '26 13:05 github-actions[bot]

Claude finished @akseljoonas's task in 6m 12s โ€”โ€” View job


PR Review: Background sessions on Mongo control plane

Tasks

  • [x] Gather context (CLAUDE.md, REVIEW.md)
  • [x] Check prior P0: _enforce_gated_model_quota crash with session=None stub
  • [x] Review new commits (token_crypto.py, credential encryption, drill 1 fixes)
  • [x] Spot-check correctness of credential encryption / session resume
  • [x] Look for new agent-loop / streaming regressions
  • [x] Post findings

1 P0 Verdict: changes requested

What I checked

  • _enforce_gated_model_quota (backend/routes/agent.py:154โ€“158) โ€” verified the stub-session guard added in 558cc03
  • agent/core/token_crypto.py โ€” Fernet wrapper, fail-closed semantics, key-rotation/missing-key paths
  • session_persistence.upsert_session (agent/core/session_persistence.py:269โ€“319) โ€” encrypted_credential / credential_set_at write semantics (None = leave-alone), credential_set_at only updated on explicit caller intent (the 0f7a30e fix)
  • session_manager.claim_dormant_session (backend/session_manager.py:988โ€“1080) โ€” TTL gate, decrypt fail-closed, ciphertext + cred_set_at preserved across rebuild
  • _update_hf_identity (backend/session_manager.py:725โ€“745) โ€” re-encrypt + bump credential_set_at only when hf_token actually rotates
  • _rebuild_agent_session_from_store (backend/session_manager.py:806โ€“890) โ€” restored-session construction, created_at handling
  • _idle_eviction_loop (backend/session_manager.py:444โ€“510) โ€” predicate that consumes created_at.timestamp()
  • change_stream_pending_submissions / change_stream_events (agent/core/session_persistence.py:776โ€“820) โ€” async with await collection.watch(...) fix from drill 1
  • create_session (backend/session_manager.py:1082โ€“1194) โ€” persist-before-CAS reorder
  • No new hf_token leak vectors in logs (grepped backend/session_manager.py for hf_token log sites)

Acknowledged fixes from prior reviews

  • P0 stub crash on _enforce_gated_model_quota โ€” fixed in 558cc03. The if agent_session.session is None: return guard at backend/routes/agent.py:156โ€“158 correctly short-circuits before the .config.model_name deref. POST /api/submit and POST /api/chat/{session_id} against Worker-held sessions now return 200 instead of 500. โœ“
  • Drill 1 #1 (create_session ordering) โ€” persist_session_snapshot runs before claim_lease at backend/session_manager.py:1163โ€“1170. โœ“
  • Drill 1 #2 (unawaited collection.watch()) โ€” both stream consumers now use async with await self.db.X.watch(...). โœ“
  • Drill 1 #3 (naive created_at default) โ€” AgentSession.created_at default factory is now datetime.now(UTC) at backend/session_manager.py:113. โœ“ (but see below for the rebuild path that wasn't covered)
  • Credential encryption โ€” Fernet wrapper fails closed on missing/malformed key; ciphertext is leave-alone on snapshot saves; credential_set_at is preserved across rebuilds so the TTL clock tracks real token age. โœ“

P0 โ€” _rebuild_agent_session_from_store re-introduces the naive-datetime eviction bug on every restored session

The drill 1 commit (47d6f81) fixed the default_factory for AgentSession.created_at to use datetime.now(UTC) so freshly-created sessions are tz-aware. But every Worker- or Main-restored session goes through _rebuild_agent_session_from_store, which at backend/session_manager.py:860โ€“862 still produces a naive datetime:

created_at = meta.get("created_at")
if not isinstance(created_at, datetime):
    created_at = datetime.utcnow()  # naive

Both branches yield a naive datetime:

  • meta.get("created_at") from Mongo is naive UTC โ€” pymongo decodes BSON datetimes without tzinfo unless the client is constructed with tz_aware=True, and AsyncMongoClient(uri, serverSelectionTimeoutMS=3000) at agent/core/session_persistence.py:172 does not pass that flag.
  • The fallback uses datetime.utcnow() which is also naive.

The idle-eviction predicate at backend/session_manager.py:480โ€“484 then calls .timestamp() on this naive datetime:

if agent_session.last_submission_at == 0.0:
    last = (
        agent_session.created_at.timestamp()  # naive โ†’ interpreted as LOCAL time
        ...
    )

This is exactly the bug pattern the drill 1 fix described (10846s "idle" on a 46s-old session in UTC+3). On any non-UTC host, created_at.timestamp() returns an epoch offset by the host's tz offset; for UTC+3 the predicate computes now - last โ‰ˆ real_age + 10800s, which exceeds IDLE_TTL_S=1800 for every restored session.

The trigger surface that survives:

  1. Main restart โ†’ user reconnects to Main: ensure_session_loaded rebuilds session, claims lease, sets naive created_at. last_submission_at = 0.0 until the user submits something. If the user just reads chat history (no submission), the eviction tick at 60s cadence sees now - created_at.timestamp() > IDLE_TTL_S and releases the lease. User submits โ†’ re-restore โ†’ re-evict cycle.
  2. Worker claim_dormant_session: same path. The window before the first submission claim is short (sub-second under load) so Worker eviction is mostly masked by last_submission_at getting set quickly, but if claim_pending_submission returns no doc (or errors), the Worker sits with last_submission_at=0.0 and naive created_at โ†’ eviction on the next 60s tick.

The drill 1 commit recognised this as P0 for freshly-created sessions; it's equally P0 for restored ones, and restored sessions are the entire point of this PR. The other naive-datetime usage at the stub builder (backend/session_manager.py:957) is benign because stubs are never inserted into self.sessions and so don't reach the eviction loop.

Fix: mirror the pattern already used at backend/session_manager.py:1397โ€“1398 (in _consume_submissions) โ€” coerce naive datetimes to UTC-aware and use datetime.now(UTC) as the fallback:

created_at = meta.get("created_at")
if isinstance(created_at, datetime):
    if created_at.tzinfo is None:
        created_at = created_at.replace(tzinfo=UTC)
else:
    created_at = datetime.now(UTC)

Replace lines backend/session_manager.py:860โ€“862. The stub builder at line 957 can use the same pattern for consistency even though it's not load-bearing for eviction. Fix this โ†’


The credential-encryption layer is well-designed: ciphertext leave-alone semantics on snapshot saves, credential_set_at preserved across rebuilds, fail-closed decrypt path, env-key dependency documented in docs/deployment.md. The token never reaches Mongo in plaintext and the in-memory hf_token is only set from a successful decrypt or a live user reconnect. No new findings on that surface. ยท branch bg-sessions-mongo-control-plane

github-actions[bot] avatar May 15 '26 13:05 github-actions[bot]