aien-dev has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
GitHub aien-dev/interplane-mv#46 (code only)
Apply it
git checkout -b patch-e148d1c5bf3155da 1d9f317e0b6d22c9f6ca72a8a2444ee827caf3f3 curl -fsSL https://interplane.io/drakestapleton/interplane-mv/patches/e148d1c5bf3155da.patch | git am
Provenance
github-import 1
aien-dev/interplane-mv
46
4a241f4a5379875c2ed165896dd5e5031c8ba0c9
{"kind":"github-import","owner":"aien-dev","repo":"interplane-mv","number":46,"url":"https://github.com/aien-dev/interplane-mv/pull/46","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:04Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/CHANGELOG.md b/CHANGELOG.md index 85c0e48..db42f83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ - Trust run tooling (plan cut R1a): both conformance runners write `<case>.inputs.json` (full input ledger) next to `<case>.results.json` under `--dump`, byte-identical across Rust and Python (the Rust results dump now nulls `duration_ms` like Python). `bench/tools/trust_run.py` runs every offline leg of PROTOCOL-0.3 (T1, T2, both negative-control matrices, validator, TRUST-DIGEST, T3, T4) and computes gates P, X, I, E, A, N from the raw files. The dev run found a spec-versus-protocol conflict: results the pipeline synthesizes after a raising or foreign-result `execute` carried null `content_kind` and `trust` (CORE.md said so), which gate P2 counts as missing. Both pipelines now label them `tool_result` + `unknown`, the schema reading of a null label, so behaviour is unchanged. - Streamed responses (plan 19.7 item 6, streaming half): Lenshift dialect `openai_stream` in Rust and Python takes a streamed `/v1/chat/completions` body (Server-Sent Events) exactly as sent, assembles the fragments into one assistant message and parses it with the `openai` rules (`spec/LENSHIFT.md`). A stream without `finish_reason` `stop`, `tool_calls` or `function_call` rejects every call as "truncated tool call"; malformed streams (conflicting id or name, second choice, fragment without index, data after `[DONE]`, non-JSON chunk) are rejected whole. 23 dialect fixtures, six of them the real Ollama, llama.cpp and SGLang stream captures byte for byte. Both dialect fixture runners now also compare every digest a fixture records. - Lenshift `openai` cross-language fix: Rust accepted an already-decoded `arguments` object and reported a non-string value as "arguments is not an object"; it now rejects every non-string `arguments` as "arguments is not valid JSON", as Python and `spec/LENSHIFT.md` do. Only Ollama's own `/api/chat` sends decoded objects (capture `05e`); all 29 OpenAI-compatible captured calls send strings. Fixtures `openai/arguments_decoded_object` and `openai/arguments_not_string` fail on the old Rust code. +- Session state limits (plan 19.7 item 6b): host-set `max_traces` (1024), `max_messages_per_trace`, `max_requests_per_trace` and `max_inputs_per_trace` (4096 each) bound the pipeline's per-trace state in Rust and Python. A message or request over a limit is refused at the replay and duplicate stage with the new `ErrorCode` `session_limit_exceeded` (`session limit exceeded: <limit name>`), after the replay and duplicate checks and before any runtime contact; `register_input` over its limit fails like a duplicate `input_id`. New host-only `Pipeline.close_trace` drops a trace's ledger ids, inputs, approval entries, event sequence and events and refuses later messages, requests, inputs and approval continuations with the new `session_closed` (`session closed: <trace_id>`). Unit tests with the same scenarios in both SDKs (the 0.3 corpus stays frozen). Python: the trace flag `_pending` is renamed `_awaiting`. ## Unreleased (0.2, CrossAxis lane) diff --git a/STATUS.md b/STATUS.md index fc10f5f..8bfe803 100644 --- a/STATUS.md +++ b/STATUS.md @@ -40,4 +40,5 @@ byte-identical) ยท `qualified` (measured against a real model/backend). | Odysseus adapter reads exposure (0.3 cut E2) | - | tested | adapters/odysseus/tests/test_injection_exposure.py (21) | gate armed from `CallContext.exposure` (floor below user_supplied, or absent) plus Odysseus's own result observation; caller trust hints removed; hosts register the user turn (demo, bench runner); 18 injected effects held, 0 executed; red check: 15 host-registered cases fail without it | | AIEN adapter passes exposure, honest labels (0.3 cut E4) | tested | - | adapters/aien/tests/exposure.rs (4) | re-pinned sovereign-core 0c1d249 (#207); `CallContext.exposure` reaches `EffectClassAuthority` and the approval path; 11 injected effects held, 0 executed, nothing written; results labelled per capability (read_file workspace_content, list_dir tool_result, write_file tool_result trusted_runtime); red check: base-rule test fails without the passthrough | | Adapter subset runners T3 and T4 (0.3 cut R0) | - | tested (T3: 43 fixtures, vs odysseus@2992bf6) | T4 in Rust: 32 fixtures (A15 included, 0.3 cut R0b) vs sovereign-core 0c1d249; violations 0, content-derived 0 | subset rule in spec/CORE.md, frozen in TRUST-DIGEST.txt (`t3_subset`, `t4_subset`); red check: gate off gives 32 T3 violations, mis-enrolled write_file fails 18 of 18 T4 injection cases; A15 has no corpus fixture | +| Session state limits and `close_trace` (plan 19.7 item 6b) | tested | tested | unit tests (corpus frozen) | `max_traces`, `max_messages_per_trace`, `max_requests_per_trace`, `max_inputs_per_trace` refuse at the replay and duplicate stage with `session_limit_exceeded`; host-only `close_trace` drops a trace's state and refuses it with `session_closed`; same 7 scenarios and strings in both languages; fixtures follow the next corpus revision | | CI | running | running | - | github.com/aien-dev/interplane: schemas, rust, python, cross-language identity, both adapters | diff --git a/python/interplane/core.py b/python/interplane/core.py index 2726c3c..1bd69e0 100644 --- a/python/interplane/core.py +++ b/python/interplane/core.py @@ -103,6 +103,8 @@ class ErrorCode: UNKNOWN_DECISION = "unknown_decision" RUNTIME_UNAVAILABLE = "runtime_unavailable" STALE_CAPABILITY = "stale_capability" + SESSION_LIMIT_EXCEEDED = "session_limit_exceeded" + SESSION_CLOSED = "session_closed" ALL = frozenset(v for k, v in list(vars().items()) if k.isupper() and isinstance(v, str)) @@ -845,6 +847,10 @@ class Limits: max_argument_bytes: int = 65536 max_requests_per_turn: int = 32 max_text_length: int = 4096 + max_traces: int = 1024 + max_messages_per_trace: int = 4096 + max_requests_per_trace: int = 4096 + max_inputs_per_trace: int = 4096 @classmethod def from_dict(cls, data: Optional[dict]) -> "Limits": @@ -893,6 +899,32 @@ class RequestLedger: requests.add(request_id) return None + # Read-only views and cleanup used by the session state limits (CORE.md). + def has_message(self, trace_id: str, message_id: str) -> bool: + return message_id in self._messages.get(trace_id, ()) + + def has_request_id(self, trace_id: str, request_id: str) -> bool: + return request_id in self._requests.get(trace_id, ()) + + def message_count(self, trace_id: str) -> int: + return len(self._messages.get(trace_id, ())) + + def request_count(self, trace_id: str) -> int: + return len(self._requests.get(trace_id, ())) + + def holds(self, trace_id: str) -> bool: + return bool(self._messages.get(trace_id) or self._requests.get(trace_id)) + + def traces(self) -> set: + """Every trace that holds at least one recorded id.""" + return {t for t, v in self._messages.items() if v} | { + t for t, v in self._requests.items() if v + } + + def forget(self, trace_id: str) -> None: + self._messages.pop(trace_id, None) + self._requests.pop(trace_id, None) + # --------------------------------------------------------------------------- # Lifecycle diff --git a/python/interplane/crossveil.py b/python/interplane/crossveil.py index 95256b1..42701ad 100644 --- a/python/interplane/crossveil.py +++ b/python/interplane/crossveil.py @@ -308,21 +308,87 @@ class Pipeline: self.ledger = ledger or RequestLedger() self.events: list = [] self._seq: dict = {} - self._pending: dict = {} # trace_id -> True while results await a model continuation + self._awaiting: dict = {} # trace_id -> True while results await a model continuation self._inputs: dict = {} # trace_id -> [InputRecord, ...] in order (0.3 cut P3) # (trace_id, request_id) -> _PendingEntry. Host-only: only continue_approval and # cancel_approval read or change it; a new pipeline starts empty (0.3 cut A1/A2). self._pending: dict = {} + self._closed: set = set() # trace ids closed by the host (session state limits) + + # -- session state limits (CORE.md) --------------------------------------------- + def _holds(self, trace_id: str) -> bool: + """A trace is held when the pipeline keeps any state for it.""" + return ( + self.ledger.holds(trace_id) + or bool(self._inputs.get(trace_id)) + or trace_id in self._seq + or trace_id in self._awaiting + or any(k[0] == trace_id for k in self._pending) + ) + + def _held_count(self) -> int: + held = set(self.ledger.traces()) | {t for t, v in self._inputs.items() if v} + held |= set(self._seq) | set(self._awaiting) | {k[0] for k in self._pending} + return len(held) + + def _can_hold(self, trace_id: str) -> bool: + """False for a closed trace, and for a new trace while ``max_traces`` are held.""" + if trace_id in self._closed: + return False + return self._holds(trace_id) or self._held_count() < self.limits.max_traces + + def _message_refusal(self, trace_id: str) -> Optional[tuple]: + """``(code, message)`` when a further message on the trace is refused, else None.""" + if trace_id in self._closed: + return ErrorCode.SESSION_CLOSED, f"session closed: {trace_id}" + if not self._holds(trace_id) and self._held_count() >= self.limits.max_traces: + return ErrorCode.SESSION_LIMIT_EXCEEDED, "session limit exceeded: max_traces" + if self.ledger.message_count(trace_id) >= self.limits.max_messages_per_trace: + msg = "session limit exceeded: max_messages_per_trace" + return ErrorCode.SESSION_LIMIT_EXCEEDED, msg + return None + + def _request_refusal(self, trace_id: str) -> Optional[tuple]: + if trace_id in self._closed: + return ErrorCode.SESSION_CLOSED, f"session closed: {trace_id}" + if self.ledger.request_count(trace_id) >= self.limits.max_requests_per_trace: + msg = "session limit exceeded: max_requests_per_trace" + return ErrorCode.SESSION_LIMIT_EXCEEDED, msg + return None + + def close_trace(self, trace_id: str) -> None: + """Host-only: drop everything the pipeline keeps for the trace (ledger ids, inputs, + approval entries, event sequence, events) and refuse any later message, request, input or + continuation on it with ``session_closed``. Closing an unknown or closed trace is a no-op. + Never called from model output or an admitted envelope.""" + if trace_id in self._closed: + return + self._closed.add(trace_id) + self.ledger.forget(trace_id) + self._inputs.pop(trace_id, None) + self._seq.pop(trace_id, None) + self._awaiting.pop(trace_id, None) + for key in [k for k in self._pending if k[0] == trace_id]: + del self._pending[key] + self.events = [e for e in self.events if e.extra.get("trace_id") != trace_id] # -- input ledger and exposure (0.3 cut P3) ----------------------------------- def register_input(self, record: Any) -> InputRecord: """Host-only: register an input placed in front of the model on ``record.trace_id``, before the turn that can see it. Never called from model output or an admitted envelope. Raises - ``ValueError`` on a duplicate ``input_id`` for the trace.""" + ``ValueError`` on a duplicate ``input_id`` for the trace, past ``max_inputs_per_trace``, + on a new trace while ``max_traces`` are held, or on a closed trace; nothing is recorded then.""" rec = record if isinstance(record, InputRecord) else InputRecord.from_dict(record) - ledger = self._inputs.setdefault(rec.trace_id, []) + if rec.trace_id in self._closed: + raise ValueError(f"session closed: {rec.trace_id}") + ledger = self._inputs.get(rec.trace_id, []) if any(r.input_id == rec.input_id for r in ledger): raise ValueError(f"duplicate input_id: {rec.input_id}") + if len(ledger) >= self.limits.max_inputs_per_trace: + raise ValueError("session limit exceeded: max_inputs_per_trace") + if not self._holds(rec.trace_id) and self._held_count() >= self.limits.max_traces: + raise ValueError("session limit exceeded: max_traces") + ledger = self._inputs.setdefault(rec.trace_id, []) ledger.append(copy.deepcopy(rec)) return rec @@ -353,6 +419,8 @@ class Pipeline: self._push_result_input(trace_id, result, digest(rendered)) def _push_result_input(self, trace_id: str, result: ToolResult, content_digest: str) -> None: + if not self._can_hold(trace_id): + return # closed, or refused as a further trace: no state may grow for it prov = result.provenance or {} ledger = self._inputs.setdefault(trace_id, []) n = sum(1 for r in ledger if r.input_id.startswith("in-auto-")) @@ -377,6 +445,8 @@ class Pipeline: # -- events (RelayLine) ------------------------------------------------- def _emit(self, trace_id: str, name: str, request_id=None, turn=None, payload=None) -> None: + if not self._can_hold(trace_id): + return # closed, or refused as a further trace: nothing is recorded for it seq = self._seq.get(trace_id, 0) self._seq[trace_id] = seq + 1 ev = Event(event=name, seq=seq, request_id=request_id, turn=turn, payload=payload) @@ -440,13 +510,21 @@ class Pipeline: "malformed envelope: payload.kind", turn, ) - replay = self.ledger.admit_message(trace_id, env["message_id"]) - if replay is not None: + if self.ledger.has_message(trace_id, env["message_id"]): msg = f"replayed message_id: {env['message_id']}" - return self._rejected(rid, replay, trace_id, msg, turn) - dup = self.ledger.admit_request_id(trace_id, rid) - if dup is not None: - return self._rejected(rid, dup, trace_id, f"duplicate request_id: {rid}", turn) + return self._rejected(rid, ErrorCode.REPLAYED_MESSAGE, trace_id, msg, turn) + refusal = self._message_refusal(trace_id) + if refusal is not None: + return self._rejected(rid, refusal[0], trace_id, refusal[1], turn) + self.ledger.admit_message(trace_id, env["message_id"]) + if self.ledger.has_request_id(trace_id, rid): + return self._rejected( + rid, ErrorCode.DUPLICATE_REQUEST_ID, trace_id, f"duplicate request_id: {rid}", turn + ) + refusal = self._request_refusal(trace_id) + if refusal is not None: + return self._rejected(rid, refusal[0], trace_id, refusal[1], turn) + self.ledger.admit_request_id(trace_id, rid) self._emit(trace_id, "tool_request", rid, turn, {"tool": copy.deepcopy(payload["tool"])}) if self.limits.arguments_oversized(payload["arguments"]): msg = f"arguments exceed {self.limits.max_argument_bytes} bytes" @@ -614,6 +692,8 @@ class Pipeline: ) def _live_pending(self, trace_id: str, request_id: str) -> _PendingEntry: + if trace_id in self._closed: + raise ContinuationRefused("session_closed") p = self._pending.get((trace_id, request_id)) if p is None or p.life.state is not State.REQUIRES_APPROVAL: raise ContinuationRefused("no_pending_approval") @@ -787,7 +867,7 @@ class Pipeline: ) -> TurnOutcome: """Parse one model turn and run every call it contains through the pipeline.""" out = TurnOutcome(turn=turn, outcome="no_tool") - if self._pending.pop(trace_id, None): + if self._awaiting.pop(trace_id, None): self._emit(trace_id, "continue", None, turn) try: module = self.registry.get(dialect) @@ -860,7 +940,8 @@ class Pipeline: elif out.rejected: out.outcome = "rejected" if pairs: - self._pending[trace_id] = True + if self._can_hold(trace_id): + self._awaiting[trace_id] = True else: self._emit(trace_id, "complete", None, turn) out.events = [ diff --git a/python/tests/test_session_limits.py b/python/tests/test_session_limits.py new file mode 100644 index 0000000..6a00756 --- /dev/null +++ b/python/tests/test_session_limits.py @@ -0,0 +1,220 @@ +"""Session state limits and close_trace (spec/CORE.md, "Session state limits"). + +The same scenarios, code strings and message strings are tested in +rust/crates/interplane-crossveil/tests/session_limits.rs. +""" + +import pytest + +from interplane import lenshift +from interplane.core import Decision, ErrorCode, InputRecord, Limits +from interplane.crossveil import ( + ContinuationRefused, + MockRuntime, + Pipeline, + mock_mapping_table, +) + +NOW = "2026-01-01T00:00:00Z" + + +def pipe(**limits): + return Pipeline(lenshift, mock_mapping_table(), MockRuntime(), Limits(**limits)) + + +def env(trace, message_id, request_id): + return { + "interplane_version": "0.1", + "message_id": message_id, + "trace_id": trace, + "parent_id": None, + "timestamp": NOW, + "source": {"kind": "model", "id": "m"}, + "destination": {"kind": "runtime", "id": "mock"}, + "payload": { + "kind": "tool_request", + "request_id": request_id, + "tool": {"namespace": None, "name": "read_file"}, + "arguments": {"path": "/tmp/a"}, + "provenance": {"dialect": "openai", "parser_version": "1.0.0"}, + }, + } + + +def admit(p, trace, message_id, request_id): + """``(status, code, message)`` of one admitted envelope.""" + res, _ = p.admit_envelope(env(trace, message_id, request_id)) + if res.error is None: + return res.status, None, None + return res.status, res.error.code, res.error.message + + +def input_rec(input_id, trace): + return InputRecord.from_dict( + { + "input_id": input_id, + "content_kind": "user_request", + "trust": "user_supplied", + "source": {"kind": "operator", "id": "op"}, + "origin": "user:prompt", + "content_digest": "sha256:" + "a" * 64, + "trace_id": trace, + "parent_id": None, + "derived_from": [], + } + ) + + +def continuation(request_id, approval_id): + return Decision.from_dict( + { + "kind": "decision", + "request_id": request_id, + "decision": "authorized", + "capability": "delete_file", + "authority": {"runtime": "mock", "policy_engine": "mock.policy"}, + "approval": {"approval_id": approval_id}, + } + ) + + +OK = ("ok", None, None) +LIMIT = "session_limit_exceeded" + + +def test_defaults(): + lim = Limits() + assert (lim.max_traces, lim.max_messages_per_trace) == (1024, 4096) + assert (lim.max_requests_per_trace, lim.max_inputs_per_trace) == (4096, 4096) + assert Limits.from_dict({"max_traces": 7}).max_traces == 7 + assert ErrorCode.SESSION_LIMIT_EXCEEDED == "session_limit_exceeded" + assert ErrorCode.SESSION_CLOSED == "session_closed" + + +def test_request_limit_rejects_before_runtime_contact(): + p = pipe(max_requests_per_trace=2) + assert admit(p, "t", "m1", "r1") == OK + assert admit(p, "t", "m2", "r2") == OK + calls = p.runtime.decide_calls + got = admit(p, "t", "m3", "r3") + assert got == ("rejected", LIMIT, "session limit exceeded: max_requests_per_trace") + assert p.runtime.decide_calls == calls + # the request id was not recorded: the same id is not a duplicate on a later try elsewhere + assert not p.ledger.has_request_id("t", "r3") + # a duplicate is still reported as a duplicate, ahead of the limit + assert admit(p, "t", "m4", "r1")[1] == "duplicate_request_id" + + +def test_replay_is_still_reported_at_the_message_limit(): + p = pipe(max_messages_per_trace=2) + assert admit(p, "t", "m1", "r1") == OK + assert admit(p, "t", "m2", "r2") == OK + got = admit(p, "t", "m1", "r9") + assert got == ("rejected", "replayed_message", "replayed message_id: m1") + + +def test_message_limit(): + p = pipe(max_messages_per_trace=2) + assert admit(p, "t", "m1", "r1") == OK + assert admit(p, "t", "m2", "r2") == OK + got = admit(p, "t", "m3", "r3") + assert got == ("rejected", LIMIT, "session limit exceeded: max_messages_per_trace") + assert not p.ledger.has_message("t", "m3") + assert admit(p, "u", "m1", "r1") == OK # other traces are not affected + + +def test_trace_limit_and_close_frees_a_slot(): + p = pipe(max_traces=2) + assert admit(p, "a", "m1", "r1") == OK + assert admit(p, "b", "m1", "r1") == OK + got = admit(p, "c", "m1", "r1") + assert got == ("rejected", LIMIT, "session limit exceeded: max_traces") + assert not p.ledger.holds("c") and not [e for e in p.events if e.extra["trace_id"] == "c"] + assert admit(p, "a", "m2", "r2") == OK # a held trace keeps working + with pytest.raises(ValueError, match="^session limit exceeded: max_traces$"): + p.register_input(input_rec("i1", "c")) # inputs cannot open a further trace either + assert p.inputs("c") == [] + p.close_trace("a") + assert admit(p, "c", "m1", "r1") == OK + + +def test_input_limit_records_nothing(): + p = pipe(max_inputs_per_trace=1) + p.register_input(input_rec("i1", "t")) + with pytest.raises(ValueError, match="^session limit exceeded: max_inputs_per_trace$"): + p.register_input(input_rec("i2", "t")) + assert [r["input_id"] for r in p.inputs("t")] == ["i1"] + with pytest.raises(ValueError, match="^duplicate input_id: i1$"): + p.register_input(input_rec("i1", "t")) + + +def test_close_trace(): + p = pipe() + assert admit(p, "t", "m1", "r1") == OK + p.register_input(input_rec("i1", "t")) + p.run_turn( + "openai", + "m", + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "c1", + "type": "function", + "function": {"name": "delete_file", "arguments": '{"path": "/tmp/x"}'}, + } + ], + }, + "t", + 0, + ) + pa = p.pending_approval("t", "c1") + assert pa is not None + assert admit(p, "u", "m1", "r1") == OK + n_t = len([e for e in p.events if e.extra["trace_id"] == "t"]) + n_u = len([e for e in p.events if e.extra["trace_id"] == "u"]) + assert n_t > 0 and n_u > 0 + + p.close_trace("t") + p.close_trace("t") # closing twice is a no-op + p.close_trace("never-seen") # so is closing an unknown trace + assert len(p.events) == n_u and all(e.extra["trace_id"] == "u" for e in p.events) + assert p.inputs("t") == [] and p.pending_approval("t", "c1") is None + + closed = ("rejected", "session_closed", "session closed: t") + assert admit(p, "t", "m9", "r9") == closed + assert admit(p, "t", "m1", "r1") == closed # a former replay is refused as closed too + with pytest.raises(ValueError, match="^session closed: t$"): + p.register_input(input_rec("i2", "t")) + d = continuation("c1", pa.approval_id) + with pytest.raises(ContinuationRefused) as e1: + p.continue_approval("t", "c1", d, pa.request_digest, NOW) + assert e1.value.reason == "session_closed" + with pytest.raises(ContinuationRefused) as e2: + p.cancel_approval("t", "c1") + assert e2.value.reason == "session_closed" + assert p.inputs("t") == [] and len(p.events) == n_u # a refusal leaves no state behind + assert admit(p, "u", "m2", "r2") == OK # other traces keep working + # a model turn on the closed trace is refused per call and recorded nowhere + out = p.run_turn( + "openai", + "m", + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "c2", + "type": "function", + "function": {"name": "read_file", "arguments": '{"path": "/tmp/x"}'}, + } + ], + }, + "t", + 1, + ) + assert out.results[0].error.code == "session_closed" + assert out.results[0].error.message == "session closed: t" + assert not p.ledger.holds("t") and p.inputs("t") == [] + assert all(e.extra["trace_id"] != "t" for e in p.events) diff --git a/rust/crates/interplane-core/src/ledger.rs b/rust/crates/interplane-core/src/ledger.rs index c11b437..c58eb66 100644 --- a/rust/crates/interplane-core/src/ledger.rs +++ b/rust/crates/interplane-core/src/ledger.rs @@ -10,6 +10,21 @@ pub struct Limits { pub max_argument_bytes: usize, #[serde(default = "default_reqs")] pub max_requests_per_turn: usize, + /// Session state limits (CORE.md): traces held at once. + #[serde(default = "default_traces")] + pub max_traces: usize, + #[serde(default = "default_session")] + pub max_messages_per_trace: usize, + #[serde(default = "default_session")] + pub max_requests_per_trace: usize, + #[serde(default = "default_session")] + pub max_inputs_per_trace: usize, +} +fn default_traces() -> usize { + 1024 +} +fn default_session() -> usize { + 4096 } fn default_arg_bytes() -> usize { 65536 @@ -22,6 +37,10 @@ impl Default for Limits { Self { max_argument_bytes: 65536, max_requests_per_turn: 32, + max_traces: 1024, + max_messages_per_trace: 4096, + max_requests_per_trace: 4096, + max_inputs_per_trace: 4096, } } } @@ -54,6 +73,37 @@ impl RequestLedger { Err(ErrorCode::DuplicateRequestId) } } + /// Read-only views and cleanup used by the session state limits (CORE.md). + pub fn has_message(&self, trace: &str, message_id: &str) -> bool { + self.seen + .get(trace) + .is_some_and(|e| e.0.contains(message_id)) + } + pub fn has_request(&self, trace: &str, request_id: &str) -> bool { + self.seen + .get(trace) + .is_some_and(|e| e.1.contains(request_id)) + } + pub fn message_count(&self, trace: &str) -> usize { + self.seen.get(trace).map_or(0, |e| e.0.len()) + } + pub fn request_count(&self, trace: &str) -> usize { + self.seen.get(trace).map_or(0, |e| e.1.len()) + } + /// True when the trace holds at least one recorded id. + pub fn holds(&self, trace: &str) -> bool { + self.message_count(trace) + self.request_count(trace) > 0 + } + /// Every trace that holds at least one recorded id. + pub fn traces(&self) -> impl Iterator<Item = &String> { + self.seen + .iter() + .filter(|(_, e)| !e.0.is_empty() || !e.1.is_empty()) + .map(|(t, _)| t) + } + pub fn forget(&mut self, trace: &str) { + self.seen.remove(trace); + } } #[cfg(test)] diff --git a/rust/crates/interplane-core/src/types.rs b/rust/crates/interplane-core/src/types.rs index 469e280..ebd1b70 100644 --- a/rust/crates/interplane-core/src/types.rs +++ b/rust/crates/interplane-core/src/types.rs @@ -25,6 +25,8 @@ string_enum! { UnknownDecision => "unknown_decision", RuntimeUnavailable => "runtime_unavailable", StaleCapability => "stale_capability", + SessionLimitExceeded => "session_limit_exceeded", + SessionClosed => "session_closed", } } diff --git a/rust/crates/interplane-crossveil/src/pipeline.rs b/rust/crates/interplane-crossveil/src/pipeline.rs index 218a067..a926f5c 100644 --- a/rust/crates/interplane-crossveil/src/pipeline.rs +++ b/rust/crates/interplane-crossveil/src/pipeline.rs @@ -1,5 +1,5 @@ //! The reference pipeline: admit -> map -> decide -> execute -> render. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::panic::{catch_unwind, AssertUnwindSafe}; use interplane_core::*; @@ -46,6 +46,8 @@ pub enum Refusal { /// No pending approval for the call: unknown request, already executed, denied or /// cancelled, a second continuation, or a pipeline created after a restart. NoPendingApproval, + /// The trace was closed by the host (`close_trace`). + SessionClosed, } impl Refusal { @@ -53,6 +55,7 @@ impl Refusal { pub fn as_str(self) -> &'static str { match self { Refusal::NoPendingApproval => "no_pending_approval", + Refusal::SessionClosed => "session_closed", } } } @@ -144,6 +147,10 @@ pub struct Pipeline<'a> { /// Approval entries by `(trace_id, request_id)` (cut A1/A2). Host-only: only the continuation /// and cancel calls below read or change them, and a new pipeline starts empty. pending: HashMap<(String, String), PendingEntry>, + /// The trace each entry of `events` belongs to (same length as `events`). + event_traces: Vec<String>, + /// Traces closed by the host (session state limits); they stay refused for the pipeline's life. + closed: HashSet<String>, } /// Position in the trust order; `unknown` and anything unrecognized rank as `external_untrusted`. @@ -278,6 +285,101 @@ impl<'a> Pipeline<'a> { turn: None, inputs: HashMap::new(), pending: HashMap::new(), + event_traces: vec![], + closed: HashSet::new(), + } + } + + // -- session state limits (CORE.md) ---------------------------------------------- + /// A trace is held when the pipeline keeps any state for it. + fn holds(&self, trace: &str) -> bool { + self.ledger.holds(trace) + || self.inputs.get(trace).is_some_and(|v| !v.is_empty()) + || self.seq.contains_key(trace) + || self.pending.keys().any(|(t, _)| t == trace) + } + + fn held_count(&self) -> usize { + let mut held: HashSet<&str> = self.ledger.traces().map(String::as_str).collect(); + held.extend( + self.inputs + .iter() + .filter(|(_, v)| !v.is_empty()) + .map(|(t, _)| t.as_str()), + ); + held.extend(self.seq.keys().map(String::as_str)); + held.extend(self.pending.keys().map(|(t, _)| t.as_str())); + held.len() + } + + /// False for a closed trace, and for a new trace while `max_traces` are held. + fn can_hold(&self, trace: &str) -> bool { + if self.closed.contains(trace) { + return false; + } + self.holds(trace) || self.held_count() < self.limits.max_traces + } + + fn closed_refusal(trace: &str) -> (ErrorCode, String) { + (ErrorCode::SessionClosed, format!("session closed: {trace}")) + } + + /// `(code, message)` when a further message on the trace is refused. + fn message_refusal(&self, trace: &str) -> Option<(ErrorCode, String)> { + if self.closed.contains(trace) { + return Some(Self::closed_refusal(trace)); + } + let limit = if !self.holds(trace) && self.held_count() >= self.limits.max_traces { + "max_traces" + } else if self.ledger.message_count(trace) >= self.limits.max_messages_per_trace { + "max_messages_per_trace" + } else { + return None; + }; + Some(( + ErrorCode::SessionLimitExceeded, + format!("session limit exceeded: {limit}"), + )) + } + + /// `(code, message)` when a further request id on the trace is refused. + fn request_refusal(&self, trace: &str) -> Option<(ErrorCode, String)> { + if self.closed.contains(trace) { + return Some(Self::closed_refusal(trace)); + } + if self.ledger.request_count(trace) >= self.limits.max_requests_per_trace { + return Some(( + ErrorCode::SessionLimitExceeded, + "session limit exceeded: max_requests_per_trace".to_string(), + )); + } + None + } + + /// Record a request id for a call that is already refused (`run_turn`'s malformed and + /// over-the-turn-limit calls), unless that would break a session limit. + fn note_refused_request(&mut self, trace: &str, request_id: &str) { + if self.request_refusal(trace).is_none() && self.can_hold(trace) { + let _ = self.ledger.note_request(trace, request_id); + } + } + + /// Host-only: drop everything the pipeline keeps for the trace (ledger ids, inputs, approval + /// entries, event sequence, events) and refuse any later message, request, input or + /// continuation on it with `session_closed`. Closing an unknown or closed trace is a no-op. + /// Not reachable from model output or an admitted envelope. + pub fn close_trace(&mut self, trace: &str) { + if !self.closed.insert(trace.to_string()) { + return; + } + self.ledger.forget(trace); + self.inputs.remove(trace); + self.seq.remove(trace); + self.pending.retain(|(t, _), _| t != trace); + if self.event_traces.len() == self.events.len() { + let mut keep = self.event_traces.iter().map(|t| t != trace); + self.events.retain(|_| keep.next().unwrap_or(true)); + self.event_traces.retain(|t| t != trace); } } @@ -286,11 +388,27 @@ impl<'a> Pipeline<'a> { /// reachable from model output or from an admitted envelope: those paths never call it. /// Refuses a duplicate `input_id` on the trace. pub fn register_input(&mut self, rec: InputRecord) -> Result<(), String> { - let ledger = self.inputs.entry(rec.trace_id.clone()).or_default(); - if ledger.iter().any(|r| r.input_id == rec.input_id) { + if self.closed.contains(&rec.trace_id) { + return Err(format!("session closed: {}", rec.trace_id)); + } + let held = self.inputs.get(&rec.trace_id).map_or(0, Vec::len); + if self + .inputs + .get(&rec.trace_id) + .is_some_and(|l| l.iter().any(|r| r.input_id == rec.input_id)) + { return Err(format!("duplicate input_id: {}", rec.input_id)); } - ledger.push(rec); + if held >= self.limits.max_inputs_per_trace { + return Err("session limit exceeded: max_inputs_per_trace".to_string()); + } + if !self.holds(&rec.trace_id) && self.held_count() >= self.limits.max_traces { + return Err("session limit exceeded: max_traces".to_string()); + } + self.inputs + .entry(rec.trace_id.clone()) + .or_default() + .push(rec); Ok(()) } @@ -326,6 +444,9 @@ impl<'a> Pipeline<'a> { } fn push_result_input(&mut self, trace: &str, r: &ToolResult, content_digest: String) { + if !self.can_hold(trace) { + return; // closed, or refused as a further trace: no state may grow for it + } let prov = r.provenance.as_ref(); let ledger = self.inputs.entry(trace.to_string()).or_default(); let mut n = ledger @@ -354,6 +475,10 @@ impl<'a> Pipeline<'a> { } fn emit(&mut self, trace: &str, event: EventKind, request_id: Option<&str>) { + if !self.can_hold(trace) { + return; // closed, or refused as a further trace: nothing is recorded for it + } + self.event_traces.push(trace.to_string()); let s = self.seq.entry(trace.to_string()).or_insert(0); let seq = *s; *s += 1; @@ -472,10 +597,14 @@ impl<'a> Pipeline<'a> { }; return self.reject(&trace, peek.as_deref(), code, &msg); } - if self.ledger.note_message(&trace, &env.message_id).is_err() { + if self.ledger.has_message(&trace, &env.message_id) { let msg = format!("replayed message_id: {}", env.message_id); return self.reject(&trace, peek.as_deref(), ErrorCode::ReplayedMessage, &msg); } + if let Some((code, msg)) = self.message_refusal(&trace) { + return self.reject(&trace, peek.as_deref(), code, &msg); + } + let _ = self.ledger.note_message(&trace, &env.message_id); let mut req = match env.parse_payload() { Ok(Payload::ToolRequest(t)) => t, _ => { @@ -489,10 +618,14 @@ impl<'a> Pipeline<'a> { }; let rid = req.request_id.clone(); self.emit(&trace, EventKind::ToolRequest, Some(&rid)); - if self.ledger.note_request(&trace, &rid).is_err() { + if self.ledger.has_request(&trace, &rid) { let msg = format!("duplicate request_id: {rid}"); return self.reject(&trace, Some(&rid), ErrorCode::DuplicateRequestId, &msg); } + if let Some((code, msg)) = self.request_refusal(&trace) { + return self.reject(&trace, Some(&rid), code, &msg); + } + let _ = self.ledger.note_request(&trace, &rid); let size = canonicalize(&Value::Object(req.arguments.clone())).len(); if size > self.limits.max_argument_bytes { let msg = format!("arguments exceed {} bytes", self.limits.max_argument_bytes); @@ -825,6 +958,9 @@ impl<'a> Pipeline<'a> { request_digest: &str, now: &str, ) -> Result<(ToolResult, ObservedRecord), Refusal> { + if self.closed.contains(trace) { + return Err(Refusal::SessionClosed); + } let key = (trace.to_string(), request_id.to_string()); let mut p = match self.pending.remove(&key) { Some(p) if p.lc.state() == State::RequiresApproval => p, @@ -916,6 +1052,9 @@ impl<'a> Pipeline<'a> { trace: &str, request_id: &str, ) -> Result<(ToolResult, ObservedRecord), Refusal> { + if self.closed.contains(trace) { + return Err(Refusal::SessionClosed); + } let key = (trace.to_string(), request_id.to_string()); let mut p = match self.pending.remove(&key) { Some(p) if p.lc.state() == State::RequiresApproval => p, @@ -1052,7 +1191,7 @@ impl<'a> Pipeline<'a> { match item { Item::Rejected(i) => { let r = &parsed.rejected[i]; - let _ = self.ledger.note_request(trace_id, &r.request_id); + self.note_refused_request(trace_id, &r.request_id); let (res, o) = self.reject(trace_id, Some(&r.request_id), r.code.clone(), &r.message); out.rendered.push(self.render(dialect, &res, None)); @@ -1062,7 +1201,7 @@ impl<'a> Pipeline<'a> { Item::Intent(i) => { let intent = &parsed.intents[i]; let (res, o) = if n >= self.limits.max_requests_per_turn { - let _ = self.ledger.note_request(trace_id, &intent.request_id); + self.note_refused_request(trace_id, &intent.request_id); self.reject( trace_id, Some(&intent.request_id), diff --git a/rust/crates/interplane-crossveil/tests/session_limits.rs b/rust/crates/interplane-crossveil/tests/session_limits.rs new file mode 100644 index 0000000..6a84841 --- /dev/null +++ b/rust/crates/interplane-crossveil/tests/session_limits.rs @@ -0,0 +1,278 @@ +//! Session state limits and close_trace (spec/CORE.md, "Session state limits"). +//! +//! The same scenarios, code strings and message strings are tested in +//! python/tests/test_session_limits.py. +use interplane_core::*; +use interplane_crossveil::*; +use interplane_lenshift::DialectRegistry; +use serde_json::{json, Value}; + +const NOW: &str = "2026-01-01T00:00:00Z"; +const LIMIT: &str = "session_limit_exceeded"; + +fn pipe<'a>(rt: &'a mut dyn RuntimeAuthority, limits: Limits) -> Pipeline<'a> { + Pipeline::new( + DialectRegistry::with_defaults(), + mock_mapping_table(), + rt, + limits, + RequestLedger::new(), + ) +} + +fn env(trace: &str, message_id: &str, request_id: &str) -> Value { + json!({ + "interplane_version": "0.1", "message_id": message_id, "trace_id": trace, + "parent_id": null, "timestamp": NOW, + "source": {"kind": "model", "id": "m"}, "destination": {"kind": "runtime", "id": "mock"}, + "payload": { + "kind": "tool_request", "request_id": request_id, + "tool": {"namespace": null, "name": "read_file"}, + "arguments": {"path": "/tmp/a"}, + "provenance": {"dialect": "openai", "parser_version": "1.0.0"} + } + }) +} + +/// `(status, code, message)` of one admitted envelope. +fn admit( + p: &mut Pipeline<'_>, + trace: &str, + message_id: &str, + request_id: &str, +) -> (String, Option<String>, Option<String>) { + let (res, _) = p.admit_value(&env(trace, message_id, request_id)); + let status = res.status.as_str().to_string(); + match res.error { + None => (status, None, None), + Some(e) => (status, Some(e.code.as_str().to_string()), Some(e.message)), + } +} + +fn refused(code: &str, message: &str) -> (String, Option<String>, Option<String>) { + ( + "rejected".to_string(), + Some(code.to_string()), + Some(message.to_string()), + ) +} + +fn ok() -> (String, Option<String>, Option<String>) { + ("ok".to_string(), None, None) +} + +fn input_rec(id: &str, trace: &str) -> InputRecord { + serde_json::from_value(json!({ + "input_id": id, "content_kind": "user_request", "trust": "user_supplied", + "source": {"kind": "operator", "id": "op"}, "origin": "user:prompt", + "content_digest": format!("sha256:{}", "a".repeat(64)), + "trace_id": trace, "parent_id": null, "derived_from": [] + })) + .unwrap() +} + +fn call(id: &str, name: &str, args: Value) -> Value { + json!({"id": id, "type": "function", "function": {"name": name, "arguments": args.to_string()}}) +} +fn turn(calls: Vec<Value>) -> Value { + json!({"role": "assistant", "content": null, "tool_calls": calls}) +} + +fn continuation(rid: &str, aid: &str) -> Decision { + serde_json::from_value(json!({ + "kind": "decision", "request_id": rid, "decision": "authorized", + "capability": "delete_file", + "authority": {"runtime": "mock", "policy_engine": "mock.policy"}, + "approval": {"approval_id": aid} + })) + .expect("decision") +} + +#[test] +fn defaults() { + let l = Limits::default(); + assert_eq!((l.max_traces, l.max_messages_per_trace), (1024, 4096)); + assert_eq!( + (l.max_requests_per_trace, l.max_inputs_per_trace), + (4096, 4096) + ); + let l: Limits = serde_json::from_str(r#"{"max_traces": 7}"#).unwrap(); + assert_eq!((l.max_traces, l.max_inputs_per_trace), (7, 4096)); + assert_eq!(ErrorCode::SessionLimitExceeded.as_str(), LIMIT); + assert_eq!(ErrorCode::SessionClosed.as_str(), "session_closed"); +} + +#[test] +fn request_limit_rejects_before_runtime_contact() { + let mut rt = MockRuntime::new(); + let mut p = pipe( + &mut rt, + Limits { + max_requests_per_trace: 2, + ..Limits::default() + }, + ); + assert_eq!(admit(&mut p, "t", "m1", "r1"), ok()); + assert_eq!(admit(&mut p, "t", "m2", "r2"), ok()); + let got = admit(&mut p, "t", "m3", "r3"); + assert_eq!( + got, + refused(LIMIT, "session limit exceeded: max_requests_per_trace") + ); + assert!(!p.ledger.has_request("t", "r3")); + assert_eq!( + admit(&mut p, "t", "m4", "r1").1.as_deref(), + Some("duplicate_request_id") + ); + drop(p); + assert_eq!(rt.decide_calls, 2); +} + +#[test] +fn replay_is_still_reported_at_the_message_limit() { + let mut rt = MockRuntime::new(); + let mut p = pipe( + &mut rt, + Limits { + max_messages_per_trace: 2, + ..Limits::default() + }, + ); + assert_eq!(admit(&mut p, "t", "m1", "r1"), ok()); + assert_eq!(admit(&mut p, "t", "m2", "r2"), ok()); + assert_eq!( + admit(&mut p, "t", "m1", "r9"), + refused("replayed_message", "replayed message_id: m1") + ); +} + +#[test] +fn message_limit() { + let mut rt = MockRuntime::new(); + let mut p = pipe( + &mut rt, + Limits { + max_messages_per_trace: 2, + ..Limits::default() + }, + ); + assert_eq!(admit(&mut p, "t", "m1", "r1"), ok()); + assert_eq!(admit(&mut p, "t", "m2", "r2"), ok()); + assert_eq!( + admit(&mut p, "t", "m3", "r3"), + refused(LIMIT, "session limit exceeded: max_messages_per_trace") + ); + assert!(!p.ledger.has_message("t", "m3")); + assert_eq!(admit(&mut p, "u", "m1", "r1"), ok()); +} + +#[test] +fn trace_limit_and_close_frees_a_slot() { + let mut rt = MockRuntime::new(); + let mut p = pipe( + &mut rt, + Limits { + max_traces: 2, + ..Limits::default() + }, + ); + assert_eq!(admit(&mut p, "a", "m1", "r1"), ok()); + assert_eq!(admit(&mut p, "b", "m1", "r1"), ok()); + let n = p.events.len(); + assert_eq!( + admit(&mut p, "c", "m1", "r1"), + refused(LIMIT, "session limit exceeded: max_traces") + ); + assert!(!p.ledger.holds("c") && p.events.len() == n); + assert_eq!(admit(&mut p, "a", "m2", "r2"), ok()); + // Inputs cannot open a further trace either. + assert_eq!( + p.register_input(input_rec("i1", "c")), + Err("session limit exceeded: max_traces".to_string()) + ); + assert!(p.inputs("c").is_empty()); + p.close_trace("a"); + assert_eq!(admit(&mut p, "c", "m1", "r1"), ok()); +} + +#[test] +fn input_limit_records_nothing() { + let mut rt = MockRuntime::new(); + let mut p = pipe( + &mut rt, + Limits { + max_inputs_per_trace: 1, + ..Limits::default() + }, + ); + p.register_input(input_rec("i1", "t")).unwrap(); + assert_eq!( + p.register_input(input_rec("i2", "t")).unwrap_err(), + "session limit exceeded: max_inputs_per_trace" + ); + let ids: Vec<&str> = p.inputs("t").iter().map(|r| r.input_id.as_str()).collect(); + assert_eq!(ids, ["i1"]); + assert_eq!( + p.register_input(input_rec("i1", "t")).unwrap_err(), + "duplicate input_id: i1" + ); +} + +#[test] +fn close_trace() { + let mut rt = MockRuntime::new(); + let mut p = pipe(&mut rt, Limits::default()); + assert_eq!(admit(&mut p, "t", "m1", "r1"), ok()); + p.register_input(input_rec("i1", "t")).unwrap(); + p.run_turn( + "openai", + "m", + &turn(vec![call("c1", "delete_file", json!({"path": "/tmp/x"}))]), + "t", + 0, + ); + let pa = p.pending_approval("t", "c1").expect("pending"); + let n_t = p.events.len(); + assert_eq!(admit(&mut p, "u", "m1", "r1"), ok()); + let n_u = p.events.len() - n_t; + assert!(n_t > 0 && n_u > 0); + + p.close_trace("t"); + p.close_trace("t"); + p.close_trace("never-seen"); + assert_eq!(p.events.len(), n_u); + assert!(p.inputs("t").is_empty() && p.pending_approval("t", "c1").is_none()); + assert_eq!(p.events[0].seq, 0, "only u's events remain"); + + let closed = refused("session_closed", "session closed: t"); + assert_eq!(admit(&mut p, "t", "m9", "r9"), closed); + assert_eq!(admit(&mut p, "t", "m1", "r1"), closed); + assert_eq!( + p.register_input(input_rec("i2", "t")).unwrap_err(), + "session closed: t" + ); + let d = continuation("c1", &pa.approval_id); + let err = p + .continue_approval("t", "c1", &d, &pa.request_digest, NOW) + .unwrap_err(); + assert_eq!(err.as_str(), "session_closed"); + assert_eq!( + p.cancel_approval("t", "c1").unwrap_err().as_str(), + "session_closed" + ); + assert!(p.inputs("t").is_empty() && p.events.len() == n_u); + assert_eq!(admit(&mut p, "u", "m2", "r2"), ok()); + assert_eq!(p.events.len(), 2 * n_u); + let out = p.run_turn( + "openai", + "m", + &turn(vec![call("c2", "read_file", json!({"path": "/tmp/x"}))]), + "t", + 1, + ); + let e = out.results[0].error.as_ref().expect("error"); + assert_eq!(e.code.as_str(), "session_closed"); + assert_eq!(e.message, "session closed: t"); + assert!(!p.ledger.holds("t") && p.inputs("t").is_empty()); + assert_eq!(p.events.len(), 2 * n_u, "the closed trace added no events"); +} diff --git a/spec/CORE.md b/spec/CORE.md index 9636af0..b172b83 100644 --- a/spec/CORE.md +++ b/spec/CORE.md @@ -36,6 +36,42 @@ when the extension exists, proves origin, never authority. | tool requests per turn | 32 | `malformed_tool_call` on the 33rd and later | | `reason` / `message` length | 4096 | truncated by the producer | +## Session state limits + +A pipeline keeps state per trace: seen `message_id`s (replay), seen `request_id`s (duplicates), the +input ledger, approval entries (terminal ones are kept so a second continuation is refused), the +event sequence and the trace's events. Without bounds a long-lived host grows without limit, so +these limits apply. Like the limits above they are set by the host, default as listed, and never +raised by a model. + +| Limit | Default | Violation | +|---|---|---| +| `max_traces`: traces held at once | 1024 | the first message of a further trace is refused `session_limit_exceeded`; nothing is recorded for it | +| `max_messages_per_trace`: `message_id`s recorded on one trace | 4096 | the further message is refused `session_limit_exceeded` and not recorded | +| `max_requests_per_trace`: `request_id`s recorded on one trace | 4096 | the further request is rejected `session_limit_exceeded` before any runtime contact and not recorded | +| `max_inputs_per_trace`: InputRecords registered on one trace | 4096 | `register_input` fails (host error, as for a duplicate `input_id`); nothing is recorded. `register_input` on a trace that holds no state while `max_traces` are held fails the same way (`session limit exceeded: max_traces`) | + +A message or request is refused at exactly the stage, and in exactly the form, at which +`replayed_message` and `duplicate_request_id` are refused, with the code `session_limit_exceeded` +and the message `session limit exceeded: <limit name>`. The checks run after the replay and +duplicate checks (a replay is still reported as `replayed_message`). The trace check applies to the +first message of a trace that holds no state yet. + +**Closing a trace.** `close_trace(trace_id)` is host-only (never reachable from model output or an +admitted envelope). It drops every piece of the trace's state listed above, including its events, +which frees a slot for `max_traces`. Without its ledger a closed trace could not detect replays, so +the pipeline remembers the closed id for its own lifetime, and any later message, request, +registered input or approval continuation on that trace is refused with `session_closed` (message +`session closed: <trace_id>`), at the same stages as above; continuations are refused like a +continuation with no pending entry. Closing an unknown or already-closed trace is a no-op. The set +of closed ids is the one piece of state that grows with closed traces; a host reclaims it by +starting a new pipeline (approvals pending in the old one are then refused, case A12). + +`session_limit_exceeded` and `session_closed` are `ErrorCode` values (a MINOR addition, +`VERSIONING.md`). The 0.3 trust corpus is frozen (`conformance/TRUST-DIGEST.txt`), so these limits +are covered by unit tests in both SDKs with the same scenarios; conformance fixtures follow with the +next corpus revision. + ## Processing stages (the Crossveil lifecycle) ``` @@ -228,6 +264,8 @@ Error messages (pinned; `<x>` substituted; no other text): | replayed_message | `replayed message_id: <id>` | | unknown_capability | `no mapping for tool: <namespace.name or name>` | | stale_capability | `mapping table catalog digest does not match runtime catalog`, or `capability is advertised more than once with different definitions` | +| session_limit_exceeded | `session limit exceeded: <limit name>` | +| session_closed | `session closed: <trace_id>` | | capability_not_found | `unknown capability: <capability>` | | invalid_arguments | mock: `missing required argument: <key>` or `argument <key> must be <type>`; runtime-said-invalid uses the decision's `reason` | | policy_denied | the decision's `reason` | diff --git a/spec/schemas/common.schema.json b/spec/schemas/common.schema.json index daad053..0edf1d8 100644 --- a/spec/schemas/common.schema.json +++ b/spec/schemas/common.schema.json @@ -108,7 +108,9 @@ "execution_timeout", "unknown_decision", "runtime_unavailable", - "stale_capability" + "stale_capability", + "session_limit_exceeded", + "session_closed" ] }, "Error": {