Skip to content

The agent that grows with you

docs: define stable local lineage and paused fork recovery

Teknium757f19f4b44e
diff --git a/docs/gateway-local-sessions.md b/docs/gateway-local-sessions.md
index 2247a3e053e..15f35e4bea4 100644
--- a/docs/gateway-local-sessions.md
+++ b/docs/gateway-local-sessions.md
@@ -12,7 +12,9 @@ A server-authenticated identity with `session:create` can call:
The result preserves `session_id`, `stored_session_id`, `messages`, `message_count`, and
`info`, and includes the authority's normal resume snapshot fields. Both session IDs are
-the same persisted ID. Creation is lazy with respect to the agent, but reserves the real
+the same stable persisted **logical** ID. Compression and reset may rotate the private
+physical transcript target without changing either client ID. Creation is lazy with respect
+to the agent, but reserves the real
SessionDB/SessionStore identity before returning. One canonical SQLite transaction commits
the session row, route, and private `gateway.local_policy.v1:<stored-id>` creation receipt.
Repeating the request ID for the same principal and profile reuses that identity and frozen
@@ -63,9 +65,21 @@ pending approval alive. A new viewer can resume the same identity and answer thr
- Never-started queued local inputs resume through the same authority FIFO after bootstrap
readiness. Interrupted started inputs become `unknown`, are never replayed, and pause
their followers. Reattachment can inspect the unknown snapshot without running it.
-- Reset/compression identity migration remains separate integration work. A creation receipt
- cannot authorize a different compression successor; recovery currently pauses that route
- instead of silently selecting a different stored session or inheriting a default policy.
+- Compression publication atomically advances the receipt's private `entry.session_id` and
+ route alongside the child transcript. The receipt retains its creation `session_id`, policy,
+ principal/profile binding, and explicit approved `lineage`. Recovery validates compression
+ steps with the existing canonical child selector and reset steps with the existing
+ `_reset_from` boundary; it never adopts arbitrary forks or copied foreign receipts.
+- The canonical SessionStore local reset commits the new row, old-row closure, receipt and
+ route before changing the in-memory entry. Reset deliberately starts empty history while
+ preserving the frozen launch policy and queued admission owner. It does not replay an
+ interrupted execution or cancel later accepted inputs. Creating an independent conversation
+ still uses `session.create` with a new request ID; this is not a new revision-fenced reset RPC
+ or a change to the multi-view `/new` contract.
+- Admission targets, digests, claim generations, subscriber identity and uncertain outcomes
+ remain on the stable logical row. Thus lost-ACK retries keep their existing receipts after
+ either transition, and shared controls/stream callbacks keep the same execution owner.
+ Clients continue resuming the creation ID, not an internal physical continuation ID.
## Verification
@@ -95,3 +109,14 @@ held after its real claim. Fresh daemons execute only the authorized queued inpu
history/source/model/toolsets despite changed defaults, and refuse unknown, foreign,
missing and corrupt policy cases. A further restart executes nothing twice. All inference
is loopback-only; this is not native launcher or compression-transfer evidence.
+
+`tests/gateway/test_local_session_lineage.py` adds rollback and isolation invariants, plus
+three separate ordinary daemon processes. Its first-process fixture invokes the production
+agent rotation publication on the real cached AIAgent and the production SessionStore reset,
+then kills the daemon after a durable queued admission. Cold unmodified daemons preserve
+compressed history, reset's empty-history boundary, policy/cwd, admission identities and
+unknown-state blocking. Unrelated fork work and foreign receipts stay unclaimed. The model
+peer verifies recovered cwd in the actual prompt and frozen model/toolsets; this fixture does
+not execute a post-restart cwd tool effect, generate a compression summary, or exercise a
+native launcher. It proves the production publication/recovery boundary, not those separate
+surfaces.
diff --git a/tests/gateway/fixtures/local_lineage_probe.py b/tests/gateway/fixtures/local_lineage_probe.py
index 12383b0f00f..a71f459f42c 100644
--- a/tests/gateway/fixtures/local_lineage_probe.py
+++ b/tests/gateway/fixtures/local_lineage_probe.py
@@ -77,7 +77,9 @@ def probe(tmp_path):
snapshot = await rpc(ws, 'session.resume', session_id=sessions[name])
assert 'result' in snapshot, snapshot
history = json.dumps(snapshot['result']['messages'])
- assert 'RECOVERY_ACK_RECOVER_' + name.upper() in history, history
+ assert any(m['role'] == 'assistant' and m.get('content', '').startswith('RECOVERY_ACK_')
+ and m['content'].endswith('RECOVER_' + name.upper())
+ for m in snapshot['result']['messages']), history
assert ('RECOVERY_ACK_WARM_HISTORY' in history) == (name == 'safe'), history
assert 'RESET_OLD' not in history, history
same = await rpc(ws, 'session.create', **params[name])
@@ -115,10 +117,18 @@ def probe(tmp_path):
# A same-origin fork and a copied receipt do not gain the root's authority.
sessions['fork'] = 'unrelated-fork'
db.execute("""INSERT INTO sessions(id,source,parent_session_id,model_config,chat_id,user_id,session_key,started_at)
- SELECT ?,source,id,'{"_branch":true}',chat_id,user_id,session_key,started_at FROM sessions WHERE id=?""",
+ SELECT ?,source,id,'{"_branched_from":"fixture-parent"}',chat_id,user_id,session_key,started_at FROM sessions WHERE id=?""",
(sessions['fork'], targets['safe']))
db.execute('INSERT INTO state_meta(key,value) SELECT ?,value FROM state_meta WHERE key=?',
('gateway.local_policy.v1:' + sessions['fork'], 'gateway.local_policy.v1:' + sessions['safe']))
+ from gateway.session_admission import admission_fingerprint
+ payload = {'text': 'FORK_QUEUE'}
+ digest = admission_fingerprint(canonical_target=sessions['fork'], payload={'input': payload, 'intent': 'queue'})
+ db.execute('''INSERT INTO session_admissions(admission_id,request_id,principal_id,target_session_id,
+ lineage_json,payload_json,payload_digest,intent,status,owner_epoch)
+ SELECT 'fork-admission','fork',principal_id,?,?,?,?,intent,'queued',owner_epoch
+ FROM session_admissions WHERE request_id='safe' ''',
+ (sessions['fork'], json.dumps([sessions['fork']]), json.dumps(payload), digest))
cfg['model']['default'] = 'changed-default'
cfg['platform_toolsets']['cli'] = ['terminal']
(home / 'config.yaml').write_text(json.dumps(cfg))
@@ -127,17 +137,19 @@ def probe(tmp_path):
pids.append(proc.pid); epochs.append(desc['authority_epoch'])
asyncio.run(recovered(desc))
assert db_rows() == {'warm-safe': 'terminal', 'warm-reset': 'terminal', 'started': 'unknown',
- 'follower': 'queued', 'reset': 'terminal', 'foreign': 'queued', 'safe': 'terminal'}
+ 'follower': 'queued', 'reset': 'terminal', 'foreign': 'queued', 'fork': 'queued', 'safe': 'terminal'}
assert all(route_targets[name] == targets[name] for name in ('safe', 'reset', 'unknown')), route_targets
assert all(targets[name] != sessions[name] for name in ('safe', 'reset', 'unknown')), targets
- texts = [next((m.get('content') for m in reversed(r['messages']) if m['role'] == 'user'), '') for r in peer.requests]
+ raw_texts = [next((m.get('content') for m in reversed(r['messages']) if m['role'] == 'user'), '') for r in peer.requests]
+ # The production restart note may precede the newly admitted text; retain it in the receipt.
+ texts = [text.rsplit('\n\n', 1)[-1] for text in raw_texts]
assert sorted(texts) == sorted(['WARM_HISTORY', 'RESET_OLD', 'BLOCK_STARTED', 'RECOVER_SAFE', 'RECOVER_RESET']), texts
for name in ('safe', 'reset'):
- request = next(r for r in peer.requests if any(m.get('content') == 'RECOVER_' + name.upper() for m in r['messages']))
+ request = next(r for r in peer.requests if any(isinstance(m.get('content'), str) and m['content'].endswith('RECOVER_' + name.upper()) for m in r['messages']))
assert request['model'] == params[name]['model'] and not request.get('tools')
assert params[name]['cwd'] in json.dumps(request['messages']), request['messages']
return {'pids': pids, 'epochs': epochs, 'logical_ids': sessions, 'physical_targets': targets,
- 'inference_texts': texts, 'stable_receipts': True, 'policy_cwd_history_retained': True,
+ 'inference_texts': texts, 'raw_inference_texts': raw_texts, 'stable_receipts': True, 'policy_cwd_history_retained': True,
'unknown_not_replayed': True, 'foreign_and_fork_refused': True}
finally:
peer.release.set()
diff --git a/tests/gateway/test_local_session_lineage.py b/tests/gateway/test_local_session_lineage.py
index d7df84bfe97..c7b6d32140b 100644
--- a/tests/gateway/test_local_session_lineage.py
+++ b/tests/gateway/test_local_session_lineage.py
@@ -107,8 +107,11 @@ async def test_local_lineage_transitions_preserve_owner_or_roll_back(tmp_path, m
foreign = Principal('foreign', 'fixture', actor.capabilities, 'foreign')
with pytest.raises(RuntimeStoreError, match='permission_denied'):
await restarted.attach(foreign, ref)
+ wrong_profile = Principal('owner', 'other-profile', actor.capabilities, 'other-profile')
+ with pytest.raises(RuntimeStoreError, match='profile_mismatch'):
+ await restarted.attach(wrong_profile, ref)
db.create_session('unrelated-fork', source='gui', parent_session_id='compressed-again',
- model_config={'_branch': True}, chat_id=live.source.chat_id,
+ model_config={'_branched_from': 'compressed-again'}, chat_id=live.source.chat_id,
user_id=actor.subject, session_key=live.route)
with pytest.raises(RuntimeStoreError, match='storage_unavailable'):
await restarted.attach(actor, SessionRef('fixture', 'unrelated-fork'))