interplane.Get Omega
Read in your language

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#49 (code only)

closed derived 344ad533172bb837 #49

Imported from GitHub aien-dev/interplane-mv#49 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base a6b039a99353e0d195fa496b284a27754c2db626 · Head 5f8327ddee853b69a1a01cfb646825dde371fcb8

greptile-apps[bot] reviewed (COMMENTED) on 2026-10-05 03:49 UTC

aien-dev has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

Apply it

git checkout -b patch-344ad533172bb837 a6b039a99353e0d195fa496b284a27754c2db626
curl -fsSL https://interplane.io/drakestapleton/interplane-mv/patches/344ad533172bb837.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/interplane-mv
49
5f8327ddee853b69a1a01cfb646825dde371fcb8
{"kind":"github-import","owner":"aien-dev","repo":"interplane-mv","number":49,"url":"https://github.com/aien-dev/interplane-mv/pull/49","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 a2e6c91..ecd52ce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@
 - 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`.
 - Refused calls use their request id (cross-language fix): Python `run_turn` did not record the `request_id` of a malformed or over-the-turn-limit call, Rust did, so a later call reusing that id was a duplicate in Rust and accepted in Python. Python now records it like Rust (within the session state limits); `spec/CORE.md` states the rule. Same test in both SDKs; it fails on the old Python.
 - Gate M and trust-run verdicts no longer pass vacuously. `bench/tools/live_injection.py`: `summarize([])` returned `gate_violations_zero: true` with zero cases, and a `--only` subset run printed "Gate: PASS" and exited 0. The summary now carries `verdict` (PASS, FAIL, EXPLORATORY, INCOMPLETE), `qualifying`, `completeness` (missing, duplicated, unexpected, errored cases) and `preregistered` (case count, `case_set_digest`, freeze match against `conformance/TRUST-DIGEST.txt`); PASS needs the whole preregistered C01-C08 + C11 set, run exactly once, no error, frozen corpus, 0 violations, and `gate_violations_zero` is true only then. Existing summary fields keep their names. Exit code 3 for EXPLORATORY or INCOMPLETE. `bench/tools/trust_run.py`: gate X passed on zero verdict rows and gate E on zero injection cases; X now needs exactly the corpus rows and E needs every system to cover its whole injection set, matched by case name, not count (T1, T2: all injection fixtures; T3, T4: the frozen subsets). New gate F fails the run unless the `trust_digest.py --check` and `validate_fixtures.py` legs recorded exit 0 in `exit-codes.json`, since the frozen subsets are read from `TRUST-DIGEST.txt`. `analyze.py` already reports INCOMPLETE on a partial or vacuous run (checked, unchanged). Tests in `test_live_injection.py` and `test_analyze.py`.
+- Closed-trace state is bounded and closing an unknown trace is a no-op (cross-language fix). Both SDKs recorded the id of an unknown trace on `close_trace` (10,000 unknown closes kept 10,000 ids, and each of those traces was then refused `session_closed`, against CORE.md), and both kept every closed id for the pipeline's life. Now a close of a trace holding no state records nothing; closed ids live in a window of the last `max_closed_traces` (4096) and older ones are retired into a fixed-size filter (`retired_filter_bits`, default 8388608 bits = 1 MiB, sha256 positions) that never forgets, so no closed or retired trace is admitted again; the filter can falsely refuse a never-used trace (fail closed; rate documented in CORE.md, about 5e-6 after 100,000 retirements). New `Limits` fields `max_closed_traces`, `retired_filter_bits` and `Pipeline.closed_trace_state()` in both SDKs; CORE.md "Closing a trace" rewritten. Same tests in `test_session_limits.py` and `session_limits.rs`, including 100,000 open/close cycles within the bound with every replay refused and shared vectors: filter refusals at 32 and 37 bits (37 is not a power of two, so a masking implementation fails) and exact filter positions at 1009 bits computed outside both SDKs. CORE.md states the bit layout and that closed-trace state is in memory only: a new pipeline forgets every closed id, so a host that restarts one must keep old trace ids out itself.
 
 ## Unreleased (0.2, CrossAxis lane)
 
diff --git a/STATUS.md b/STATUS.md
index 8bfe803..d96c955 100644
--- a/STATUS.md
+++ b/STATUS.md
@@ -40,5 +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 |
+| 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`; closing an unknown trace records nothing; closed ids live in a window of `max_closed_traces` (4096) plus a fixed retirement filter (`retired_filter_bits`, 1 MiB) so a retired trace stays refused and the state stays bounded (100,000 open/close cycles tested); same 16 scenarios, strings and filter positions 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 1bd69e0..d2345ad 100644
--- a/python/interplane/core.py
+++ b/python/interplane/core.py
@@ -851,6 +851,8 @@ class Limits:
     max_messages_per_trace: int = 4096
     max_requests_per_trace: int = 4096
     max_inputs_per_trace: int = 4096
+    max_closed_traces: int = 4096
+    retired_filter_bits: int = 8_388_608
 
     @classmethod
     def from_dict(cls, data: Optional[dict]) -> "Limits":
diff --git a/python/interplane/crossveil.py b/python/interplane/crossveil.py
index 6c2376f..521f88a 100644
--- a/python/interplane/crossveil.py
+++ b/python/interplane/crossveil.py
@@ -6,7 +6,9 @@ never fabricates or caches a decision, and fails closed on every adapter fault.
 """
 
 import copy
+import hashlib
 import re
+from collections import OrderedDict
 from dataclasses import dataclass, field
 from typing import Any, Optional, Protocol, runtime_checkable
 
@@ -290,6 +292,36 @@ def _approval_expired(expires_at: Any, now: Any) -> bool:
     return not _utc_shape(expires_at) or not _utc_shape(now) or now >= expires_at
 
 
+class _RetiredFilter:
+    """Fixed-size filter of retired closed-trace ids (CORE.md, "Closing a trace"). Positions: the
+    first four big-endian 32-bit words of sha256(trace_id as UTF-8), each modulo ``bits``. It never
+    forgets an added id; it can match an id never added (a false refusal, fail closed). With
+    ``bits`` 0 it matches every id once anything was added."""
+
+    def __init__(self, bits: int) -> None:
+        self.bits = max(0, bits)
+        self.data = bytearray((self.bits + 7) // 8)
+        self.count = 0
+
+    def _positions(self, trace_id: str) -> list:
+        h = hashlib.sha256(trace_id.encode("utf-8")).digest()
+        return [int.from_bytes(h[4 * i : 4 * i + 4], "big") % self.bits for i in range(4)]
+
+    def add(self, trace_id: str) -> None:
+        self.count += 1
+        if self.bits:
+            for pos in self._positions(trace_id):
+                self.data[pos >> 3] |= 1 << (pos & 7)
+
+    def matches(self, trace_id: str) -> bool:
+        if not self.bits:
+            return self.count > 0
+        return all(self.data[pos >> 3] & (1 << (pos & 7)) for pos in self._positions(trace_id))
+
+    def size_bytes(self) -> int:
+        return len(self.data)
+
+
 class Pipeline:
     """Reference pipeline: Lenshift.parse -> Core.admit -> CrossAxis.map -> decide -> execute."""
 
@@ -313,7 +345,10 @@ class Pipeline:
         # (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)
+        # Trace ids closed by the host (session state limits): the last ``max_closed_traces`` in
+        # close order, exactly; older ones are retired into a fixed-size filter (CORE.md).
+        self._closed: OrderedDict = OrderedDict()
+        self._retired: Optional[_RetiredFilter] = None
 
     # -- session state limits (CORE.md) ---------------------------------------------
     def _holds(self, trace_id: str) -> bool:
@@ -331,15 +366,27 @@ class Pipeline:
         held |= set(self._seq) | set(self._awaiting) | {k[0] for k in self._pending}
         return len(held)
 
+    def _is_closed(self, trace_id: str) -> bool:
+        """True for a closed trace: in the window of recent closed ids, or matched by the
+        retirement filter (which may also match a trace that was never used: refused, fail closed)."""
+        if trace_id in self._closed:
+            return True
+        return self._retired is not None and not self._holds(trace_id) and self._retired.matches(trace_id)
+
+    def closed_trace_state(self) -> tuple:
+        """``(closed ids held exactly, bytes of the retirement filter)``: the state closing traces
+        keeps. Bounded by ``(max_closed_traces, ceil(retired_filter_bits / 8))``."""
+        return len(self._closed), (self._retired.size_bytes() if self._retired is not None else 0)
+
     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:
+        if self._is_closed(trace_id):
             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:
+        if self._is_closed(trace_id):
             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"
@@ -349,7 +396,7 @@ class Pipeline:
         return None
 
     def _request_refusal(self, trace_id: str) -> Optional[tuple]:
-        if trace_id in self._closed:
+        if self._is_closed(trace_id):
             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"
@@ -366,11 +413,18 @@ class Pipeline:
     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:
+        continuation on it with ``session_closed``. Closing a trace that holds no state (unknown,
+        already closed or retired) is a no-op and records nothing. The id joins the window of the
+        last ``max_closed_traces`` closed ids; the oldest id leaving the window is retired into the
+        filter, so it stays refused. Never called from model output or an admitted envelope."""
+        if self._is_closed(trace_id) or not self._holds(trace_id):
             return
-        self._closed.add(trace_id)
+        self._closed[trace_id] = None
+        while len(self._closed) > self.limits.max_closed_traces:
+            oldest, _ = self._closed.popitem(last=False)
+            if self._retired is None:
+                self._retired = _RetiredFilter(self.limits.retired_filter_bits)
+            self._retired.add(oldest)
         self.ledger.forget(trace_id)
         self._inputs.pop(trace_id, None)
         self._seq.pop(trace_id, None)
@@ -386,7 +440,7 @@ class Pipeline:
         ``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)
-        if rec.trace_id in self._closed:
+        if self._is_closed(rec.trace_id):
             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):
@@ -699,7 +753,7 @@ class Pipeline:
         )
 
     def _live_pending(self, trace_id: str, request_id: str) -> _PendingEntry:
-        if trace_id in self._closed:
+        if self._is_closed(trace_id):
             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:
diff --git a/python/tests/test_session_limits.py b/python/tests/test_session_limits.py
index d0b9681..81f48b9 100644
--- a/python/tests/test_session_limits.py
+++ b/python/tests/test_session_limits.py
@@ -12,6 +12,7 @@ from interplane.crossveil import (
     ContinuationRefused,
     MockRuntime,
     Pipeline,
+    _RetiredFilter,
     mock_mapping_table,
 )
 
@@ -236,3 +237,153 @@ def test_refused_call_uses_its_request_id():
     out = p.run_turn("openai", "m", turn(call("c8", '{"path": "/tmp/a"}')), "t", 1)
     assert out.results[0].error.code == "duplicate_request_id"
     assert out.results[0].error.message == "duplicate request_id: c8"
+
+
+# -- closed-trace retirement (spec/CORE.md, "Closing a trace") ------------------------------------
+# Same scenarios and literals in rust/crates/interplane-crossveil/tests/session_limits.rs.
+
+CYCLES = 100_000
+# Fresh ids f0..f39 a 32-bit filter holding r0..r7 refuses (sha256 positions, CORE.md).
+RETIRED_FILTER_PARITY = [6, 18, 19, 28, 30, 31, 37, 38]
+# Fresh ids f0..f199 a 37-bit filter holding r0..r7 refuses. 37 is not a power of two, so an
+# implementation that masks instead of taking the modulo refuses a different set.
+RETIRED_FILTER_PARITY_37 = [0, 58, 61, 63, 70, 92, 102, 103, 111, 116, 121, 128, 147, 152, 154, 157, 159, 161, 183, 194]
+# Filter positions at 1009 bits, computed from the CORE.md rule with sha256sum, outside both SDKs.
+RETIRED_FILTER_POSITIONS_1009 = [("r0", [20, 106, 629, 750]), ("f6", [278, 703, 321, 847]),
+                                 ("trace-\u00e9", [733, 695, 298, 954])]
+
+
+def open_and_close(p, trace):
+    assert admit(p, trace, "m1", "r1") == OK
+    p.close_trace(trace)
+
+
+def closed(trace):
+    return ("rejected", "session_closed", f"session closed: {trace}")
+
+
+def test_retirement_defaults():
+    lim = Limits()
+    assert (lim.max_closed_traces, lim.retired_filter_bits) == (4096, 8_388_608)
+    assert Limits.from_dict({"max_closed_traces": 3}).max_closed_traces == 3
+
+
+def test_closing_an_unknown_trace_retains_nothing():
+    p = pipe()
+    for i in range(10_000):
+        p.close_trace(f"never-seen-{i}")
+    assert p.closed_trace_state() == (0, 0)
+    # the trace was never closed, so its first message is a fresh trace
+    assert admit(p, "never-seen-0", "m1", "r1") == OK
+    p.close_trace("never-seen-0")
+    assert p.closed_trace_state() == (1, 0)
+    p.close_trace("never-seen-0")  # closing a closed trace is a no-op too
+    assert p.closed_trace_state() == (1, 0)
+
+
+def test_retired_trace_stays_refused():
+    p = pipe(max_closed_traces=2)
+    for t in ("a", "b", "c"):
+        open_and_close(p, t)
+    # "a" left the window of the last 2 closed ids and was retired into the filter
+    assert p.closed_trace_state() == (2, 1_048_576)
+    assert admit(p, "a", "m1", "r1") == closed("a")  # the replay
+    assert admit(p, "a", "m2", "r2") == closed("a")  # and any new message
+    with pytest.raises(ValueError, match="^session closed: a$"):
+        p.register_input(input_rec("i1", "a"))
+    p.close_trace("a")  # closing a retired trace is a no-op
+    assert p.closed_trace_state() == (2, 1_048_576)
+    assert not p.ledger.holds("a") and p.inputs("a") == []
+    assert all(e.extra["trace_id"] != "a" for e in p.events)
+    assert admit(p, "d", "m1", "r1") == OK  # a fresh trace is admitted
+
+
+def test_retired_trace_refuses_continuations():
+    p = pipe(max_closed_traces=1)
+    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
+    p.close_trace("t")
+    open_and_close(p, "u")  # pushes "t" out of the window
+    assert p.closed_trace_state() == (1, 1_048_576)
+    with pytest.raises(ContinuationRefused) as e1:
+        p.continue_approval("t", "c1", continuation("c1", pa.approval_id), 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"
+
+
+def test_zero_filter_bits_refuses_every_new_trace_after_a_retirement():
+    p = pipe(max_closed_traces=0, retired_filter_bits=0)
+    assert admit(p, "held", "m1", "r1") == OK
+    assert admit(p, "fresh-before", "m1", "r1") == OK
+    open_and_close(p, "a")
+    assert p.closed_trace_state() == (0, 0)
+    assert admit(p, "a", "m1", "r1") == closed("a")
+    assert admit(p, "never-used", "m1", "r1") == closed("never-used")  # cannot be told apart
+    assert admit(p, "held", "m2", "r2") == OK  # held traces keep working
+
+
+def test_retirement_filter_is_identical_across_sdks():
+    """A 32-bit filter makes false refusals frequent; both SDKs refuse exactly the same fresh ids."""
+    p = pipe(max_closed_traces=0, retired_filter_bits=32)
+    for i in range(8):
+        open_and_close(p, f"r{i}")
+    assert p.closed_trace_state() == (0, 4)
+    assert all(admit(p, f"r{i}", "m2", "r2") == closed(f"r{i}") for i in range(8))
+    refused = [i for i in range(40) if admit(p, f"f{i}", "m1", "r1")[1] == "session_closed"]
+    assert refused == RETIRED_FILTER_PARITY
+
+
+def test_retirement_filter_uses_modulo_at_a_non_power_of_two_size():
+    p = pipe(max_closed_traces=0, retired_filter_bits=37)
+    for i in range(8):
+        open_and_close(p, f"r{i}")
+    assert p.closed_trace_state() == (0, 5)
+    refused = [i for i in range(200) if admit(p, f"f{i}", "m1", "r1")[1] == "session_closed"]
+    assert refused == RETIRED_FILTER_PARITY_37
+
+
+def test_retirement_filter_positions_match_the_spec_vector():
+    f = _RetiredFilter(1009)
+    assert [(t, f._positions(t)) for t, _ in RETIRED_FILTER_POSITIONS_1009] == RETIRED_FILTER_POSITIONS_1009
+    f.add("r0")
+    # Bit p is bit p mod 8, least significant first, of byte p div 8.
+    assert [i for i in range(1009) if f.data[i >> 3] >> (i & 7) & 1] == [20, 106, 629, 750]
+
+
+def test_open_close_cycles_stay_within_the_bound_and_replays_stay_refused():
+    p = pipe()
+    for i in range(CYCLES):
+        open_and_close(p, f"s{i}")
+    lim = p.limits
+    assert p.closed_trace_state() == (lim.max_closed_traces, lim.retired_filter_bits // 8)
+    assert p.events == [] and not list(p.ledger.traces())
+    for i in range(CYCLES):
+        assert admit(p, f"s{i}", "m1", "r1") == closed(f"s{i}")
+    assert p.closed_trace_state() == (lim.max_closed_traces, lim.retired_filter_bits // 8)
+
+
+def test_unknown_close_does_not_poison_the_trace():
+    """Before the fix both SDKs recorded the id of an unknown trace on close: its first message was
+    then refused ``session_closed``."""
+    p = pipe()
+    p.close_trace("never-seen")
+    assert admit(p, "never-seen", "m1", "r1") == OK
diff --git a/rust/crates/interplane-core/src/ledger.rs b/rust/crates/interplane-core/src/ledger.rs
index c58eb66..f8eb195 100644
--- a/rust/crates/interplane-core/src/ledger.rs
+++ b/rust/crates/interplane-core/src/ledger.rs
@@ -19,6 +19,15 @@ pub struct Limits {
     pub max_requests_per_trace: usize,
     #[serde(default = "default_session")]
     pub max_inputs_per_trace: usize,
+    /// Closed trace ids remembered exactly (CORE.md, "Closing a trace"); older ones are retired.
+    #[serde(default = "default_session")]
+    pub max_closed_traces: usize,
+    /// Size in bits of the filter that keeps retired closed trace ids refused.
+    #[serde(default = "default_filter_bits")]
+    pub retired_filter_bits: usize,
+}
+fn default_filter_bits() -> usize {
+    8_388_608
 }
 fn default_traces() -> usize {
     1024
@@ -41,6 +50,8 @@ impl Default for Limits {
             max_messages_per_trace: 4096,
             max_requests_per_trace: 4096,
             max_inputs_per_trace: 4096,
+            max_closed_traces: 4096,
+            retired_filter_bits: 8_388_608,
         }
     }
 }
diff --git a/rust/crates/interplane-crossveil/src/pipeline.rs b/rust/crates/interplane-crossveil/src/pipeline.rs
index a926f5c..102eae2 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, HashSet};
+use std::collections::{HashMap, HashSet, VecDeque};
 use std::panic::{catch_unwind, AssertUnwindSafe};
 
 use interplane_core::*;
@@ -149,8 +149,61 @@ pub struct Pipeline<'a> {
     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.
+    /// Traces closed by the host (session state limits): the last `max_closed_traces` in close
+    /// order, exactly (`closed_order` keeps the order). Older ones are retired into `retired`.
     closed: HashSet<String>,
+    closed_order: VecDeque<String>,
+    retired: Option<RetiredFilter>,
+}
+
+/// Fixed-size filter of retired closed-trace ids (CORE.md, "Closing a trace"). Positions: the
+/// first four big-endian 32-bit words of sha256(trace id as UTF-8), each modulo `bits`. It never
+/// forgets an added id; it can match an id never added (a false refusal, fail closed). With
+/// `bits` 0 it matches every id once anything was added.
+#[derive(Debug, Clone)]
+struct RetiredFilter {
+    bits: usize,
+    data: Vec<u8>,
+    count: u64,
+}
+
+impl RetiredFilter {
+    fn new(bits: usize) -> Self {
+        Self {
+            bits,
+            data: vec![0; bits.div_ceil(8)],
+            count: 0,
+        }
+    }
+
+    fn positions(&self, trace: &str) -> [usize; 4] {
+        let hex = digest_bytes(trace.as_bytes());
+        let hex = &hex["sha256:".len()..];
+        let mut out = [0usize; 4];
+        for (i, slot) in out.iter_mut().enumerate() {
+            let word = u32::from_str_radix(&hex[8 * i..8 * i + 8], 16).unwrap_or(0);
+            *slot = (word as usize) % self.bits;
+        }
+        out
+    }
+
+    fn add(&mut self, trace: &str) {
+        self.count += 1;
+        if self.bits > 0 {
+            for pos in self.positions(trace) {
+                self.data[pos >> 3] |= 1 << (pos & 7);
+            }
+        }
+    }
+
+    fn matches(&self, trace: &str) -> bool {
+        if self.bits == 0 {
+            return self.count > 0;
+        }
+        self.positions(trace)
+            .iter()
+            .all(|&pos| self.data[pos >> 3] & (1 << (pos & 7)) != 0)
+    }
 }
 
 /// Position in the trust order; `unknown` and anything unrecognized rank as `external_untrusted`.
@@ -287,6 +340,8 @@ impl<'a> Pipeline<'a> {
             pending: HashMap::new(),
             event_traces: vec![],
             closed: HashSet::new(),
+            closed_order: VecDeque::new(),
+            retired: None,
         }
     }
 
@@ -312,9 +367,29 @@ impl<'a> Pipeline<'a> {
         held.len()
     }
 
+    /// True for a closed trace: in the window of recent closed ids, or matched by the retirement
+    /// filter (which may also match a trace that was never used: refused, fail closed). A trace
+    /// that holds state is never matched by the filter (a retired id can never hold state again).
+    fn is_closed(&self, trace: &str) -> bool {
+        self.closed.contains(trace)
+            || self
+                .retired
+                .as_ref()
+                .is_some_and(|f| !self.holds(trace) && f.matches(trace))
+    }
+
+    /// `(closed ids held exactly, bytes of the retirement filter)`: the state closing traces keeps.
+    /// Bounded by `(max_closed_traces, ceil(retired_filter_bits / 8))`.
+    pub fn closed_trace_state(&self) -> (usize, usize) {
+        (
+            self.closed.len(),
+            self.retired.as_ref().map_or(0, |f| f.data.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) {
+        if self.is_closed(trace) {
             return false;
         }
         self.holds(trace) || self.held_count() < self.limits.max_traces
@@ -326,7 +401,7 @@ impl<'a> Pipeline<'a> {
 
     /// `(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) {
+        if self.is_closed(trace) {
             return Some(Self::closed_refusal(trace));
         }
         let limit = if !self.holds(trace) && self.held_count() >= self.limits.max_traces {
@@ -344,7 +419,7 @@ impl<'a> Pipeline<'a> {
 
     /// `(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) {
+        if self.is_closed(trace) {
             return Some(Self::closed_refusal(trace));
         }
         if self.ledger.request_count(trace) >= self.limits.max_requests_per_trace {
@@ -366,12 +441,26 @@ impl<'a> Pipeline<'a> {
 
     /// 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.
+    /// continuation on it with `session_closed`. Closing a trace that holds no state (unknown,
+    /// already closed or retired) is a no-op and records nothing. The id joins the window of the
+    /// last `max_closed_traces` closed ids; the oldest id leaving the window is retired into the
+    /// filter, so it stays refused. Not reachable from model output or an admitted envelope.
     pub fn close_trace(&mut self, trace: &str) {
-        if !self.closed.insert(trace.to_string()) {
+        if self.is_closed(trace) || !self.holds(trace) {
             return;
         }
+        self.closed.insert(trace.to_string());
+        self.closed_order.push_back(trace.to_string());
+        while self.closed_order.len() > self.limits.max_closed_traces {
+            let Some(oldest) = self.closed_order.pop_front() else {
+                break;
+            };
+            self.closed.remove(&oldest);
+            let bits = self.limits.retired_filter_bits;
+            self.retired
+                .get_or_insert_with(|| RetiredFilter::new(bits))
+                .add(&oldest);
+        }
         self.ledger.forget(trace);
         self.inputs.remove(trace);
         self.seq.remove(trace);
@@ -388,7 +477,7 @@ 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> {
-        if self.closed.contains(&rec.trace_id) {
+        if self.is_closed(&rec.trace_id) {
             return Err(format!("session closed: {}", rec.trace_id));
         }
         let held = self.inputs.get(&rec.trace_id).map_or(0, Vec::len);
@@ -958,7 +1047,7 @@ impl<'a> Pipeline<'a> {
         request_digest: &str,
         now: &str,
     ) -> Result<(ToolResult, ObservedRecord), Refusal> {
-        if self.closed.contains(trace) {
+        if self.is_closed(trace) {
             return Err(Refusal::SessionClosed);
         }
         let key = (trace.to_string(), request_id.to_string());
@@ -1052,7 +1141,7 @@ impl<'a> Pipeline<'a> {
         trace: &str,
         request_id: &str,
     ) -> Result<(ToolResult, ObservedRecord), Refusal> {
-        if self.closed.contains(trace) {
+        if self.is_closed(trace) {
             return Err(Refusal::SessionClosed);
         }
         let key = (trace.to_string(), request_id.to_string());
@@ -1290,3 +1379,30 @@ fn normalize(mut r: ToolResult, cap: &CapabilityRequest) -> ToolResult {
     p.trust = Some(trust);
     r
 }
+
+#[cfg(test)]
+mod tests {
+    use super::RetiredFilter;
+
+    /// Filter positions at 1009 bits, computed from the CORE.md rule with sha256sum, outside both
+    /// SDKs (same literals as python/tests/test_session_limits.py).
+    const RETIRED_FILTER_POSITIONS_1009: [(&str, [usize; 4]); 3] = [
+        ("r0", [20, 106, 629, 750]),
+        ("f6", [278, 703, 321, 847]),
+        ("trace-\u{e9}", [733, 695, 298, 954]),
+    ];
+
+    #[test]
+    fn retirement_filter_positions_match_the_spec_vector() {
+        let mut f = RetiredFilter::new(1009);
+        for (t, want) in RETIRED_FILTER_POSITIONS_1009 {
+            assert_eq!(f.positions(t), want, "{t}");
+        }
+        f.add("r0");
+        // Bit p is bit p mod 8, least significant first, of byte p div 8.
+        let set: Vec<usize> = (0..1009)
+            .filter(|&i| f.data[i >> 3] >> (i & 7) & 1 == 1)
+            .collect();
+        assert_eq!(set, [20, 106, 629, 750]);
+    }
+}
diff --git a/rust/crates/interplane-crossveil/tests/session_limits.rs b/rust/crates/interplane-crossveil/tests/session_limits.rs
index ebf2ba7..02294e4 100644
--- a/rust/crates/interplane-crossveil/tests/session_limits.rs
+++ b/rust/crates/interplane-crossveil/tests/session_limits.rs
@@ -297,3 +297,189 @@ fn refused_call_uses_its_request_id() {
     assert_eq!(e.code.as_str(), "duplicate_request_id");
     assert_eq!(e.message, "duplicate request_id: c8");
 }
+
+// -- closed-trace retirement (spec/CORE.md, "Closing a trace") ------------------------------------
+// Same scenarios and literals in python/tests/test_session_limits.py.
+
+const CYCLES: usize = 100_000;
+/// Fresh ids f0..f39 a 32-bit filter holding r0..r7 refuses (sha256 positions, CORE.md).
+const RETIRED_FILTER_PARITY: [usize; 8] = [6, 18, 19, 28, 30, 31, 37, 38];
+/// Fresh ids f0..f199 a 37-bit filter holding r0..r7 refuses. 37 is not a power of two, so an
+/// implementation that masks instead of taking the modulo refuses a different set.
+const RETIRED_FILTER_PARITY_37: [usize; 20] = [
+    0, 58, 61, 63, 70, 92, 102, 103, 111, 116, 121, 128, 147, 152, 154, 157, 159, 161, 183, 194,
+];
+
+fn open_and_close(p: &mut Pipeline<'_>, trace: &str) {
+    assert_eq!(admit(p, trace, "m1", "r1"), ok());
+    p.close_trace(trace);
+}
+
+fn closed(trace: &str) -> (String, Option<String>, Option<String>) {
+    refused("session_closed", &format!("session closed: {trace}"))
+}
+
+fn limits(max_closed_traces: usize, retired_filter_bits: usize) -> Limits {
+    Limits {
+        max_closed_traces,
+        retired_filter_bits,
+        ..Limits::default()
+    }
+}
+
+#[test]
+fn retirement_defaults() {
+    let l = Limits::default();
+    assert_eq!(
+        (l.max_closed_traces, l.retired_filter_bits),
+        (4096, 8_388_608)
+    );
+    let l: Limits = serde_json::from_str(r#"{"max_closed_traces": 3}"#).unwrap();
+    assert_eq!((l.max_closed_traces, l.retired_filter_bits), (3, 8_388_608));
+}
+
+#[test]
+fn closing_an_unknown_trace_retains_nothing() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, Limits::default());
+    for i in 0..10_000 {
+        p.close_trace(&format!("never-seen-{i}"));
+    }
+    assert_eq!(p.closed_trace_state(), (0, 0));
+    // The trace was never closed, so its first message is a fresh trace.
+    assert_eq!(admit(&mut p, "never-seen-0", "m1", "r1"), ok());
+    p.close_trace("never-seen-0");
+    assert_eq!(p.closed_trace_state(), (1, 0));
+    p.close_trace("never-seen-0"); // closing a closed trace is a no-op too
+    assert_eq!(p.closed_trace_state(), (1, 0));
+}
+
+#[test]
+fn retired_trace_stays_refused() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, limits(2, 8_388_608));
+    for t in ["a", "b", "c"] {
+        open_and_close(&mut p, t);
+    }
+    // "a" left the window of the last 2 closed ids and was retired into the filter.
+    assert_eq!(p.closed_trace_state(), (2, 1_048_576));
+    assert_eq!(admit(&mut p, "a", "m1", "r1"), closed("a")); // the replay
+    assert_eq!(admit(&mut p, "a", "m2", "r2"), closed("a")); // and any new message
+    assert_eq!(
+        p.register_input(input_rec("i1", "a")).unwrap_err(),
+        "session closed: a"
+    );
+    p.close_trace("a"); // closing a retired trace is a no-op
+    assert_eq!(p.closed_trace_state(), (2, 1_048_576));
+    assert!(!p.ledger.holds("a") && p.inputs("a").is_empty());
+    let n = p.events.len();
+    assert_eq!(admit(&mut p, "d", "m1", "r1"), ok()); // a fresh trace is admitted
+    assert!(p.events.len() > n);
+}
+
+#[test]
+fn retired_trace_refuses_continuations() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, limits(1, 8_388_608));
+    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");
+    p.close_trace("t");
+    open_and_close(&mut p, "u"); // pushes "t" out of the window
+    assert_eq!(p.closed_trace_state(), (1, 1_048_576));
+    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"
+    );
+}
+
+#[test]
+fn zero_filter_bits_refuses_every_new_trace_after_a_retirement() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, limits(0, 0));
+    assert_eq!(admit(&mut p, "held", "m1", "r1"), ok());
+    assert_eq!(admit(&mut p, "fresh-before", "m1", "r1"), ok());
+    open_and_close(&mut p, "a");
+    assert_eq!(p.closed_trace_state(), (0, 0));
+    assert_eq!(admit(&mut p, "a", "m1", "r1"), closed("a"));
+    assert_eq!(
+        admit(&mut p, "never-used", "m1", "r1"),
+        closed("never-used")
+    );
+    assert_eq!(admit(&mut p, "held", "m2", "r2"), ok()); // held traces keep working
+}
+
+/// A 32-bit filter makes false refusals frequent; both SDKs refuse exactly the same fresh ids.
+#[test]
+fn retirement_filter_is_identical_across_sdks() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, limits(0, 32));
+    for i in 0..8 {
+        open_and_close(&mut p, &format!("r{i}"));
+    }
+    assert_eq!(p.closed_trace_state(), (0, 4));
+    for i in 0..8 {
+        let t = format!("r{i}");
+        assert_eq!(admit(&mut p, &t, "m2", "r2"), closed(&t));
+    }
+    let refused: Vec<usize> = (0..40)
+        .filter(|i| {
+            admit(&mut p, &format!("f{i}"), "m1", "r1").1.as_deref() == Some("session_closed")
+        })
+        .collect();
+    assert_eq!(refused, RETIRED_FILTER_PARITY);
+}
+
+#[test]
+fn retirement_filter_uses_modulo_at_a_non_power_of_two_size() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, limits(0, 37));
+    for i in 0..8 {
+        open_and_close(&mut p, &format!("r{i}"));
+    }
+    assert_eq!(p.closed_trace_state(), (0, 5));
+    let refused: Vec<usize> = (0..200)
+        .filter(|i| {
+            admit(&mut p, &format!("f{i}"), "m1", "r1").1.as_deref() == Some("session_closed")
+        })
+        .collect();
+    assert_eq!(refused, RETIRED_FILTER_PARITY_37);
+}
+
+#[test]
+fn open_close_cycles_stay_within_the_bound_and_replays_stay_refused() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, Limits::default());
+    for i in 0..CYCLES {
+        open_and_close(&mut p, &format!("s{i}"));
+    }
+    let l = p.limits;
+    let bound = (l.max_closed_traces, l.retired_filter_bits / 8);
+    assert_eq!(p.closed_trace_state(), bound);
+    assert!(p.events.is_empty() && p.ledger.traces().next().is_none());
+    for i in 0..CYCLES {
+        let t = format!("s{i}");
+        assert_eq!(admit(&mut p, &t, "m1", "r1"), closed(&t));
+    }
+    assert_eq!(p.closed_trace_state(), bound);
+}
+
+/// Before the fix both SDKs recorded the id of an unknown trace on close: its first message was
+/// then refused `session_closed`.
+#[test]
+fn unknown_close_does_not_poison_the_trace() {
+    let mut rt = MockRuntime::new();
+    let mut p = pipe(&mut rt, Limits::default());
+    p.close_trace("never-seen");
+    assert_eq!(admit(&mut p, "never-seen", "m1", "r1"), ok());
+}
diff --git a/spec/CORE.md b/spec/CORE.md
index c477e55..722bec3 100644
--- a/spec/CORE.md
+++ b/spec/CORE.md
@@ -60,12 +60,40 @@ 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).
+any later message, request, registered input or approval continuation on a closed 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 a trace that holds no
+state (an unknown trace, or one already closed or retired) is a no-op and records nothing; such a
+trace's first message is then a fresh trace, which is safe because nothing of it was ever recorded.
+
+The closed ids are kept in bounded state, and a closed trace is never admitted again:
+
+| Limit | Default | Meaning |
+|---|---|---|
+| `max_closed_traces`: closed ids remembered exactly | 4096 | the last `max_closed_traces` ids closed, in close order |
+| `retired_filter_bits`: size of the retirement filter | 8388608 (1 MiB) | when a close pushes the oldest id out of the window, that id is *retired*: added to a fixed-size filter allocated on the first retirement |
+
+A trace is closed when its id is in the window, or when it holds no state and the filter matches it.
+The filter positions of an id are the first four big-endian 32-bit words of `sha256(trace_id as
+UTF-8)`, each modulo `retired_filter_bits` (a true modulo, also at sizes that are not a power of
+two); bit `p` is bit `p mod 8`, least significant first, of filter byte `floor(p / 8)`. The filter
+matches when all four bits are set. Both SDKs test the same position vector at 1009 bits and the
+same refusals at 37 bits. The
+filter never forgets an id, so every closed or retired id stays refused for the pipeline's lifetime
+(no replay of any previously closed trace is admitted). It can also match an id that was never used:
+that trace is refused `session_closed` (a false refusal, fail closed). After `R` retirements the
+chance that a given fresh trace id is refused is about `(1 - e^(-4R/retired_filter_bits))^4`; with
+the default, about 5e-6 at 100,000 retirements, 2 % at 1,000,000 and 14 % at 2,000,000. A trace that
+holds state is never refused by the filter (a retired id can never hold state again, so a match on a
+held trace can only be false). With `retired_filter_bits` 0 the filter matches every id once
+anything was retired: every trace that holds no state is then refused. The state that closing keeps
+is therefore at most `max_closed_traces` ids plus `ceil(retired_filter_bits / 8)` bytes, whatever
+the number of closes. This state lives in the pipeline's memory only; it is not persisted. A host
+that sees false refusals rise and starts a new pipeline (approvals pending in the old one are then
+refused, case A12) therefore also forgets every closed id, and the new pipeline admits a replay of
+any trace closed in the old one. Such a host must keep the old pipeline's trace ids out of the new
+one itself (for example a fresh trace-id namespace per pipeline). Both SDKs expose this state as `closed_trace_state()`
+`(ids held exactly, filter bytes)`.
 
 `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