Background sessions on Mongo control plane (Main + Worker topology)
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|workerenv 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_queueis replaced;EventBroadcasteris 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:
findOneAndUpdateCAS onsessions.lease. TTL = 30 s, renew every 10 s. Lease loss triggersrequeue_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), manualPOST /api/session/{id}/background, and Main lifespan shutdown for active turns. Each emits amigratingsession_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)
- 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.
- 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 aninterruptedevent.
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 onPyMongoError, subscriber counter attach/detach - [x]
tests/test_lifespan_grace_sweep.py(8) โrelease_session_to_backgroundevent emission, grace-sweep predicate matrix,/backgroundroute 200/404 - [x]
tests/test_worker_idle_eviction.py(13) โ idle predicate matrix,claim_dormant_sessionuser-bypass + lease-taken paths, claim-tick skips already-held
- [x]
- [x] Pre-existing unit suite still green (248 passing; two unrelated pre-existing
test_doom_loopfailures verified viagit stash) - [x]
ruff checkclean on every file modified by this PR (pre-existing E402/F401/F841 inmain.pyandroutes/agent.pypredate 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)
- Roll Workers first with the new code. They start consuming
pending_submissionsagainst any session whose lease has expired, but won't see anything new until Main also rolls. - Then roll Main.
MongoSessionStore.init()runs an idempotent backfill: sessions withlast_active_at > now-1hand no lease get an empty lease so the next CAS succeeds; older sessions flip toruntime_state: idle(still recoverable, neverended). - 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:
- Heartbeat misleading-WARN guard when session drops mid-iteration
delete_sessionrequeue ordering (race window for clean-delete UI)claim_dormant_sessionlease release on rebuild failure (TTL recovers in 30 s)pending_submissionspayload size guard (16 MB BSON ceiling)- 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_looprenewals on outage โ heartbeat returnsNone,_on_lease_lostcleans 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)
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
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
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_leaseinsession_persistence.py - Full reconnect path from
_check_session_accessโensure_session_loadedโ_sse_response _on_lease_lostscope and which submissionsrequeue_claimed_fortouches- Heartbeat error handling (
renew_leaseonPyMongoError) - SSE holder/non-holder branching in
_sse_responseand whether the non-holder path is reachable via HTTP - Worker claim tick:
_worker_claim_tickquery and session discovery - Lifespan shutdown sweep: active-turn handover to Workers
shutdown_sessionlock scope with external I/O inside- New
/backgroundroute auth guard _backfill_lease_statemigration 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.
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 requeuerenew_leaseerror handling (session_persistence.py:628โ630) โ PyMongoError sentinelrelease_leaseupdate (session_persistence.py:638โ641) โ whether holder_id is clearedshutdown_sessionlock 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.
PR Review: Background sessions on Mongo control plane 
Tasks
- [x] Gather context (CLAUDE.md, REVIEW.md)
- [ ] Check P0 #1:
ensure_session_loadedreconnect path for Worker-held sessions - [ ] Check P0 #2:
_on_lease_lost/requeue_claimed_forscope - [ ] Check P1 fixes (renew_lease sentinel, release_lease holder_id, shutdown_session lock)
- [ ] Post findings
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_loadedreconnect path for Worker-held sessions - [x] Check P0 #2:
_on_lease_lost/requeue_claimed_forscope - [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_loadedstub construction (session_manager.py:892โ933) โ lease-claim failure path, stub fields, insertion guard_check_session_access+_enforce_gated_model_quotainteraction (routes/agent.py:179โ196,139โ157) โ what stub flows trigger withsession=None_sse_responseis_holderbranch (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 fixrenew_leasePyMongoError propagation (session_persistence.py:615โ633) + heartbeat catch (session_manager.py:265โ270)release_leaseholder_id clear (session_persistence.py:635โ652)shutdown_sessionlock 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_loadednow returns a stubAgentSessionwithholder_id=foreign_holderandbroadcaster=Noneinstead ofNone._sse_responsecorrectly takes the non-holder change-stream slow path becauseis_holderevaluates toFalse(broadcaster is None). SSE reconnect now works. โ - P0 #2 (
_on_lease_lostrequeues all sessions):_on_lease_lostnow passessession_id=session_idtorequeue_claimed_for(session_manager.py:292โ293);requeue_claimed_forfilters on that field when provided (session_persistence.py:737โ738). Double-execution vector is closed. โ - P1 (
renew_leasePyMongoError):renew_leasenow propagatesPyMongoError; the heartbeat loop catches it atsession_manager.py:265and skips withcontinue, never calling_on_lease_lost. โ - P1 (
release_leaseholder_id not cleared):release_leasenow setslease.holder_id: Nonealongsidelease.expires_at: now(session_persistence.py:649), closing the heartbeat re-acquire window. โ - P1 (
shutdown_sessionlock scope): Only thesessions.getlookup runs insideself._lock;release_leaseandwait_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 turnPOST /api/chat/{session_id}(routes/agent.py:641โ654) โ combined submit+streamPOST /api/approvereaches_check_session_accessbut does not call_enforce_gated_model_quota, so it is not affected by this specific crash โ but it would still return a stub thatsubmit_approvalwould 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 โ
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_quotacrash withsession=Nonestub - [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
AgentSessionconstruction inensure_session_loaded(session_manager.py:896โ933) โsession=None,claude_counteddefault POST /submitandPOST /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 sessionPOST /api/chat/{session_id}(routes/agent.py:653โ654) โ whentext 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 โ
PR Review: Background sessions on Mongo control plane 
Tasks
- [ ] Gather context (CLAUDE.md, REVIEW.md)
- [ ] Check prior P0:
_enforce_gated_model_quotacrash withsession=Nonestub - [ ] 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
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_quotacrash withsession=Nonestub - [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 558cc03agent/core/token_crypto.pyโ Fernet wrapper, fail-closed semantics, key-rotation/missing-key pathssession_persistence.upsert_session(agent/core/session_persistence.py:269โ319) โencrypted_credential/credential_set_atwrite semantics (None = leave-alone),credential_set_atonly 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 + bumpcredential_set_atonly whenhf_tokenactually rotates_rebuild_agent_session_from_store(backend/session_manager.py:806โ890) โ restored-session construction,created_athandling_idle_eviction_loop(backend/session_manager.py:444โ510) โ predicate that consumescreated_at.timestamp()change_stream_pending_submissions/change_stream_events(agent/core/session_persistence.py:776โ820) โasync with await collection.watch(...)fix from drill 1create_session(backend/session_manager.py:1082โ1194) โ persist-before-CAS reorder- No new hf_token leak vectors in logs (grepped
backend/session_manager.pyforhf_tokenlog sites)
Acknowledged fixes from prior reviews
- P0 stub crash on
_enforce_gated_model_quotaโ fixed in 558cc03. Theif agent_session.session is None: returnguard atbackend/routes/agent.py:156โ158correctly short-circuits before the.config.model_namederef.POST /api/submitandPOST /api/chat/{session_id}against Worker-held sessions now return 200 instead of 500. โ - Drill 1 #1 (create_session ordering) โ
persist_session_snapshotruns beforeclaim_leaseatbackend/session_manager.py:1163โ1170. โ - Drill 1 #2 (unawaited
collection.watch()) โ both stream consumers now useasync with await self.db.X.watch(...). โ - Drill 1 #3 (naive
created_atdefault) โAgentSession.created_atdefault factory is nowdatetime.now(UTC)atbackend/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_atis 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 withtz_aware=True, andAsyncMongoClient(uri, serverSelectionTimeoutMS=3000)atagent/core/session_persistence.py:172does 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:
- Main restart โ user reconnects to Main:
ensure_session_loadedrebuilds session, claims lease, sets naivecreated_at.last_submission_at = 0.0until the user submits something. If the user just reads chat history (no submission), the eviction tick at 60s cadence seesnow - created_at.timestamp() > IDLE_TTL_Sand releases the lease. User submits โ re-restore โ re-evict cycle. - 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 bylast_submission_atgetting set quickly, but ifclaim_pending_submissionreturns no doc (or errors), the Worker sits withlast_submission_at=0.0and naivecreated_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