From 212c41ac95a576cd8f40f774bba3209daedd412d Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:15:40 +0200 Subject: [PATCH 01/35] Canonicalize direct option ordering --- src/decisio/compiler.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/decisio/compiler.py b/src/decisio/compiler.py index ca499d1..212c385 100644 --- a/src/decisio/compiler.py +++ b/src/decisio/compiler.py @@ -12,7 +12,8 @@ SEMANTIC_PROMPT_VERSION = "semantic-comparative-v2" INDEPENDENT_SEMANTIC_PROMPT_VERSION = "semantic-binary-v1" -LETTER_PROMPT_VERSION = "letter-baseline-v1" +LETTER_PROMPT_VERSION = "letter-baseline-v2" +LETTER_STATEFUL_PROMPT_VERSION = "letter-question-prefix-v2" SEMANTIC_SYSTEM = ( "You are a precise comparative decision scorer. Use only the supplied evidence. " @@ -230,11 +231,11 @@ def compile_letter_choice( raise ValueError("letter baseline supports at most 26 candidates") evidence = canonical_json(request.state) question = canonical_json(request.question) + canonical_candidates = tuple(sorted(request.candidates, key=lambda candidate: candidate.id)) + letters = string.ascii_uppercase[: len(canonical_candidates)] lines = [ f"{letter}. {canonical_json(candidate.description)}" - for letter, candidate in zip( - string.ascii_uppercase[: len(request.candidates)], request.candidates, strict=True - ) + for letter, candidate in zip(letters, canonical_candidates, strict=True) ] user = ( f"EVIDENCE:\n{evidence}\n\n" @@ -252,9 +253,7 @@ def compile_letter_choice( ) readout_texts = { candidate.id: letter - for candidate, letter in zip( - request.candidates, string.ascii_uppercase[: len(request.candidates)], strict=True - ) + for candidate, letter in zip(canonical_candidates, letters, strict=True) } return _compile( tokenizer, @@ -263,6 +262,6 @@ def compile_letter_choice( {"role": "user", "content": user}, ], readout_texts=readout_texts, - version="letter-question-prefix-v1" if reuse_prefix else LETTER_PROMPT_VERSION, + version=LETTER_STATEFUL_PROMPT_VERSION if reuse_prefix else LETTER_PROMPT_VERSION, reusable_user_prefix=reusable_user_prefix, ) From 279da02e399493cdbc1f51a579fc73392b3e51e7 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:15:52 +0200 Subject: [PATCH 02/35] Version canonical direct scorer contract --- src/decisio/scorers/letters.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/decisio/scorers/letters.py b/src/decisio/scorers/letters.py index a4bc3ad..dd76ac1 100644 --- a/src/decisio/scorers/letters.py +++ b/src/decisio/scorers/letters.py @@ -9,7 +9,7 @@ class LetterTokenScorer: - name = "letter_token_baseline_v1" + name = "letter_token_baseline_v2" def __init__( self, @@ -22,7 +22,7 @@ def __init__( self.reuse_prefix = reuse_prefix self.shared_prefix_execution = shared_prefix_execution if reuse_prefix: - self.name = "letter_question_prefix_v1" + self.name = "letter_question_prefix_v2" def score(self, request: ChoiceRequest) -> DecisionResult: compiled = compile_letter_choice( From 09afa5f5e354591099c83b494f1e487cf4edfbb1 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:16:26 +0200 Subject: [PATCH 03/35] Avoid redundant prefix snapshots on cache hits --- src/decisio/backends/llama_cpp.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/decisio/backends/llama_cpp.py b/src/decisio/backends/llama_cpp.py index 02da29d..9807f57 100644 --- a/src/decisio/backends/llama_cpp.py +++ b/src/decisio/backends/llama_cpp.py @@ -582,10 +582,23 @@ def shared_prefix_batch_next_token_logits( token_ids_batch[candidate_index] ) - prefix_state = self._capture_sequence_state(0) - self._metrics["prefix_state_snapshot_bytes"] += len(prefix_state) + suffix_branch_count = sum( + len(input_ids) > prefix_len for input_ids in input_ids_batch + ) + prefix_state = None if cache_key is not None and cache_entry is None: + # Capture once on the cold path so later decisions can restore the stable prefix. + prefix_state = self._capture_sequence_state(0) + self._metrics["prefix_state_snapshot_bytes"] += len(prefix_state) self._store_repeated_prefix_state(cache_key, prefix_state) + elif suffix_branch_count > 1: + # Multiple prompt branches need a rollback point between suffixes. On a cache hit the + # cached state already is that rollback point when it covers the full decoded prefix. + if cache_entry is not None and cache_reused_tokens == prefix_len: + prefix_state = cache_entry.state + else: + prefix_state = self._capture_sequence_state(0) + self._metrics["prefix_state_snapshot_bytes"] += len(prefix_state) live_prefix_state = True for candidate_index, input_ids in enumerate(input_ids_batch): @@ -593,6 +606,10 @@ def shared_prefix_batch_next_token_logits( if not suffix: continue if not live_prefix_state: + if prefix_state is None: + raise RuntimeError( + "llama.cpp shared-prefix branch requires a reusable prefix state" + ) self._clear_scoring_state() restored = self._restore_sequence_state(prefix_state, 0) self._metrics["prefix_state_restore_bytes"] += restored From 3c69eb28ca159660ba9b92e194277cfb93816ce0 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:17:23 +0200 Subject: [PATCH 04/35] Test canonical direct-choice ordering --- tests/test_core.py | 63 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/tests/test_core.py b/tests/test_core.py index f2e6a7b..328d937 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -69,6 +69,21 @@ def batch_next_token_logits(self, input_ids_batch, token_ids_batch): return responses +class TokenIdBackend: + def __init__(self, logits_by_token_id): + self.tokenizer = FakeTokenizer() + self.logits_by_token_id = dict(logits_by_token_id) + self.calls = [] + + @property + def identity(self): + return {"backend": "token-aware-fake", "model": "unit-test"} + + def next_token_logits(self, input_ids, token_ids): + self.calls.append((input_ids, list(token_ids))) + return [self.logits_by_token_id[token_id] for token_id in token_ids] + + class SharedPrefixQueueBackend(QueueBackend): def __init__(self, responses): super().__init__(responses) @@ -178,7 +193,53 @@ def test_independent_compiler_remains_available_as_v1_baseline(): def test_letter_compiler_maps_ids_to_distinct_tokens(): compiled = compile_letter_choice(FakeTokenizer(), request()) - assert compiled.readout == {"billing": 100, "technical": 101, "sales": 102} + assert compiled.readout == {"billing": 100, "sales": 101, "technical": 102} + assert compiled.version == "letter-baseline-v2" + + +def test_letter_compiler_is_invariant_to_candidate_presentation_order(): + item = request() + reversed_request = ChoiceRequest( + id=item.id, + state=item.state, + question=item.question, + candidates=tuple(reversed(item.candidates)), + ) + + left = compile_letter_choice(FakeTokenizer(), item, reuse_prefix=True) + right = compile_letter_choice(FakeTokenizer(), reversed_request, reuse_prefix=True) + + assert left.prompt == right.prompt + assert left.sha256 == right.sha256 + assert left.readout == right.readout + assert left.version == right.version == "letter-question-prefix-v2" + + +def test_letter_scorer_preserves_candidate_scores_when_caller_order_changes(): + item = request() + reversed_request = ChoiceRequest( + id=item.id, + state=item.state, + question=item.question, + candidates=tuple(reversed(item.candidates)), + ) + logits_by_token_id = {100: 5.0, 101: 1.0, 102: 3.0} + left_backend = TokenIdBackend(logits_by_token_id) + right_backend = TokenIdBackend(logits_by_token_id) + + left = LetterTokenScorer( + left_backend, reuse_prefix=True, shared_prefix_execution=False + ).score(item) + right = LetterTokenScorer( + right_backend, reuse_prefix=True, shared_prefix_execution=False + ).score(reversed_request) + + assert left_backend.calls[0][0] == right_backend.calls[0][0] + assert left.prompt_sha256 == right.prompt_sha256 + assert left.scores == right.scores + assert left.distribution == right.distribution + assert left.choice == right.choice == "billing" + assert left.scorer == right.scorer == "letter_question_prefix_v2" def test_semantic_scorer_batches_candidate_prompts(): From c2f82827bd2da299a1d62f14377bd1eff917e3f3 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:17:46 +0200 Subject: [PATCH 05/35] Test cached prefix snapshot reuse --- tests/test_llama_cpp_backend.py | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/tests/test_llama_cpp_backend.py b/tests/test_llama_cpp_backend.py index a84c90a..11f5cde 100644 --- a/tests/test_llama_cpp_backend.py +++ b/tests/test_llama_cpp_backend.py @@ -360,6 +360,72 @@ def test_native_sequence_state_round_trip_uses_llama_state_api(): assert restored == 4 assert runtime._llama_cpp.restored == [(b"test", 0)] +def test_repeated_single_prompt_cache_hit_reuses_existing_snapshot(): + from collections import OrderedDict, defaultdict + + runtime = object.__new__(_NativeLlamaCppRuntime) + runtime.n_seq_max = 8 + runtime.n_batch = 4 + runtime.n_ctx = 128 + runtime.n_vocab = 256 + runtime._metrics = defaultdict(int) + runtime._require_open = lambda: None + runtime._repeated_state_cache_max_entries = 2 + runtime._repeated_state_cache_max_bytes = 1024 + runtime._repeated_state_cache = OrderedDict() + runtime._repeated_state_cache_bytes = 0 + + state = [] + decoded = [] + captures = [] + + runtime._clear_scoring_state = state.clear + + def decode(tokens, *, seq_id, n_past): + assert seq_id == 0 + assert len(state) == n_past + state.extend(tokens) + decoded.append(tuple(tokens)) + + def capture(seq_id): + assert seq_id == 0 + captures.append(tuple(state)) + return tuple(state) + + def restore(snapshot, seq_id): + assert seq_id == 0 + state[:] = snapshot + return len(snapshot) + + runtime._decode_tokens = decode + runtime._capture_sequence_state = capture + runtime._restore_sequence_state = restore + runtime._selected_logits = lambda ids: [float(sum(state) + token) for token in ids] + + first = runtime.shared_prefix_batch_next_token_logits( + [(1, 2, 3, 4, 10)], + [[1, 2]], + reusable_prefix_len=4, + ) + second = runtime.shared_prefix_batch_next_token_logits( + [(1, 2, 3, 4, 11)], + [[1, 2]], + reusable_prefix_len=4, + ) + + assert first == [[21.0, 22.0]] + assert second == [[22.0, 23.0]] + assert captures == [(1, 2, 3, 4)] + assert runtime._metrics["repeated_state_cache_misses"] == 1 + assert runtime._metrics["repeated_state_cache_hits"] == 1 + assert runtime._metrics["prefix_state_snapshot_bytes"] == 4 + assert runtime._metrics["prefix_state_restore_bytes"] == 4 + assert runtime._metrics["prefix_state_restores"] == 1 + assert runtime._metrics["logical_input_tokens"] == 10 + assert runtime._metrics["physically_evaluated_tokens"] == 6 + assert decoded == [(1, 2, 3, 4), (10,), (11,)] + + @pytest.mark.parametrize("count", [1, 8, 9, 77]) def test_serial_candidate_reuse_is_independent_of_sequence_capacity(count): from collections import defaultdict From d6b88c04cba3c379a90475ecaf392a64316c7fe8 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:18:19 +0200 Subject: [PATCH 06/35] Version direct-choice benchmark protocol --- benchmarks/run_snake_controller_benchmark.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/benchmarks/run_snake_controller_benchmark.py b/benchmarks/run_snake_controller_benchmark.py index 9717baa..6a4a009 100644 --- a/benchmarks/run_snake_controller_benchmark.py +++ b/benchmarks/run_snake_controller_benchmark.py @@ -10,6 +10,7 @@ from pathlib import Path from typing import Any +from decisio.compiler import LETTER_STATEFUL_PROMPT_VERSION from decisio.backends.llama_cpp import ( LLAMA_CPP_PYTHON_VERSION, LlamaCppBackend, @@ -290,6 +291,10 @@ def run(args: argparse.Namespace) -> dict[str, Any]: "max_steps": args.episode_max_steps, "stall_steps": args.stall_steps, }, + "direct_choice": { + "prompt_version": LETTER_STATEFUL_PROMPT_VERSION, + "candidate_order": "candidate_id_lexicographic", + }, } protocol = {**protocol_payload, "sha256": canonical_sha256(protocol_payload)} requested_model = _requested_model_identity(args) From b9d58adebc06c21d1211632593ee102f35cdec9a Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:19:33 +0200 Subject: [PATCH 07/35] Keep benchmark imports ordered --- benchmarks/run_snake_controller_benchmark.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmarks/run_snake_controller_benchmark.py b/benchmarks/run_snake_controller_benchmark.py index 6a4a009..431567c 100644 --- a/benchmarks/run_snake_controller_benchmark.py +++ b/benchmarks/run_snake_controller_benchmark.py @@ -10,12 +10,12 @@ from pathlib import Path from typing import Any -from decisio.compiler import LETTER_STATEFUL_PROMPT_VERSION from decisio.backends.llama_cpp import ( LLAMA_CPP_PYTHON_VERSION, LlamaCppBackend, LlamaCppBackendConfig, ) +from decisio.compiler import LETTER_STATEFUL_PROMPT_VERSION from examples.snake.planner import PLANNER_VERSION, SnakePlanner from .snake_controller_benchmark import ( From f04dba56b46003c2a81d7e8659257c2fb7985788 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:19:48 +0200 Subject: [PATCH 08/35] Document canonical direct-choice ordering --- examples/snake/README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/examples/snake/README.md b/examples/snake/README.md index 7eeefbe..ac624e4 100644 --- a/examples/snake/README.md +++ b/examples/snake/README.md @@ -175,8 +175,9 @@ same configurations with two complementary signals: `board_filled` completion. The benchmark records exact model/runtime/configuration identity in an append-only JSONL ledger. -The direct shared-vs-fresh pair uses the same question-first stateful prompt; only execution reuse -changes. This keeps cache effects separate from prompt-order effects. +The direct shared-vs-fresh pair uses the same canonical question-first stateful prompt; only +execution reuse changes. Direct v2 sorts candidates by stable candidate ID before assigning A/B/C, +so caller presentation order cannot silently change the direct prompt. ## Compare scoring strategies @@ -248,8 +249,9 @@ Both the web and headless commands accept these independently selectable experim it) and encode candidate sensors in short fields. Full body coordinates remain available. - `--reuse-prefix`: direct/letters scoring only; explicitly force the default stateful path. It places the fixed decision context before changing state, marks its exact token prefix, and use the existing bounded sequence-state cache. This has a distinct - `letter_question_prefix_v1` scorer identity. It changes prompt order, so compare quality as well - as latency. Fresh backends evaluate the same prompt without reuse. + `letter_question_prefix_v2` scorer identity. Candidate IDs are canonicalized before A/B/C lettering, + so caller presentation order does not change the compiled direct-choice prompt. Fresh backends + evaluate that same prompt without reuse. - `--controller adjacent-food`: bypass the model when a safe action eats food and leaves at least one immediately safe next action. This is an application heuristic, not proof of long-term safety; traces identify it as `deterministic_adjacent_food_policy`. The default remains `model`. From b27009c305f78e28694ae52c0d0f9f0cf7eef94c Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:20:04 +0200 Subject: [PATCH 09/35] Label canonical direct scorer in Snake UI --- examples/snake/static/js/metrics-renderer.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/snake/static/js/metrics-renderer.js b/examples/snake/static/js/metrics-renderer.js index 577993f..481c8bf 100644 --- a/examples/snake/static/js/metrics-renderer.js +++ b/examples/snake/static/js/metrics-renderer.js @@ -17,8 +17,10 @@ export function modelLabel(model) { } export function scorerLabel(name) { + if (name === "letter_question_prefix_v2") return "DIRECT CHOICE · canonical A/B/C · reusable prefix"; if (name === "letter_question_prefix_v1") return "DIRECT CHOICE · reusable question prefix"; if (name === "snake_adjacent_food_policy_v1") return "FOOD POLICY · model skipped"; + if (name === "letter_token_baseline_v2") return "DIRECT CHOICE · canonical A/B/C logits · 1 forward"; if (name === "letter_token_baseline_v1") return "DIRECT CHOICE · A/B/C logits · 1 forward"; if (name === "semantic_comparative_logodds_v2") return "SEMANTIC v2 · YES/NO per candidate"; if (name === "semantic_binary_logodds_v1") return "SEMANTIC v1 · YES/NO per candidate"; @@ -76,7 +78,7 @@ export function renderMetrics(ui, displayState, status, lastRecord) { if (ui.modeBadge) { ui.modeBadge.textContent = mode === "model" - ? scorer === "letter_token_baseline_v1" + ? scorer?.startsWith("letter_") ? "DIRECT" : "MODEL" : mode From 123b3dd72108277cfc87026a1db6d762d3fafdfe Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:20:23 +0200 Subject: [PATCH 10/35] Align product hypothesis with direct-choice evidence --- docs/product.md | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/docs/product.md b/docs/product.md index ed3e417..161443e 100644 --- a/docs/product.md +++ b/docs/product.md @@ -36,7 +36,7 @@ For decision-shaped workloads, Decisio aims to provide: - **zero answer generation** — no decoding loop for the final decision; - **no mandatory training** — start from an existing open-weight causal LLM; -- **semantic candidates** — score the meaning of each candidate rather than an arbitrary A/B/C label; +- **bounded candidates** — rank runtime-defined alternatives directly without generating an answer; - **shared computation** — reuse state/question work across candidates and related decisions; - **typed outputs** — no JSON repair or free-form parsing on the decision path; - **honest probability semantics** — distinguish conditional model scores from calibrated probability of correctness; @@ -50,10 +50,15 @@ The initial scorer hypothesis was that **comparative candidate-level binary sema would be a better general decision primitive than arbitrary answer-token scoring or candidate-independent binary scoring. -The first representative 2B short/fresh scorer gate did **not** support that as a general default. -Semantic v2 therefore remains experimental, with the active question narrowed to repeated-state -workloads. Direct A/B/C option-token scoring remains an explicit benchmark baseline and is also a -legitimate low-latency application path for small bounded controls such as Snake. +The first representative 2B short/fresh scorer gate did **not** support that as a general default, +and the later repeated-state gate also failed its precommitted quality guardrails despite strong +cache reuse. Semantic v2 therefore remains an experimental comparison path, not the promoted v1 +decision primitive. + +The active v1 hypothesis is **stateful direct choice**: deterministically canonicalize the supplied +candidate identities, compile one A/B/C/... choice prompt, evaluate it once, and read all option +logits from the same final model position. Stateful execution must remain equivalent to the same +compiled prompt evaluated fresh. For semantic candidate `c_i`: @@ -119,7 +124,7 @@ Decisio deliberately does not own: - **Decisions, not strings.** If the valid output space is bounded, do not generate prose to recover it. - **Training-free before trained.** Establish the inference-time ceiling before adding learned components. - **Constrain before score.** Deterministic validity/safety/business constraints stay with the owning domain and remove impossible candidates before probabilistic scoring. -- **Choose the readout deliberately.** Prefer semantic candidate readouts when evidence supports them; direct option-token logits are valid for latency-oriented bounded controls, but scorer identity and order/verbalizer sensitivity must stay explicit. +- **Choose the readout deliberately.** v1 promotes one-pass direct option logits for bounded choices; candidate IDs are canonicalized before A/B/C lettering, while scorer identity and verbalizer sensitivity remain explicit. - **Answerability is separate from preference.** "Which option?" and "Can this be answered?" are different questions. - **Scores are not confidence until calibrated.** API naming and metadata must preserve that distinction. - **State is first-class.** Split stable decision context from changing world state; process the stable prefix once wherever model/runtime semantics safely allow it. @@ -146,10 +151,11 @@ The reference implementation can execute boolean and choice decisions with zero ### Outcome -On frozen evaluation sets, semantic candidate scoring is compared against: +On frozen evaluation sets, the promoted stateful direct-choice path is compared against: -- direct A/B/C or equivalent answer-token scoring; -- autoregressive structured-output generation; +- the exact same compiled prompt evaluated fresh; +- autoregressive structured-output generation where useful; +- experimental semantic scorers as non-promoted comparisons; - optional external references when legally/reproducibly available. The key question is not only "is it accurate?" but "does it improve the decision-specific trade-off?" From 25d7db648ce9ea2f52d165ee8945628b1dfd2811 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:21:01 +0200 Subject: [PATCH 11/35] Record local 2B evidence and direct v2 remediation --- docs/current-state.md | 52 ++++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 18 deletions(-) diff --git a/docs/current-state.md b/docs/current-state.md index c9ee79a..594c653 100644 --- a/docs/current-state.md +++ b/docs/current-state.md @@ -16,10 +16,10 @@ Active plans: [llama.cpp reference runtime evidence closure](workstreams/llama-c | llama.cpp reference runtime | DONE | local-GGUF backend/CLI and scorer primitives implemented | | Shared context-state fast path | DONE | native-batch-safe branching + bounded repeated-state cache | | Scorer gate v2 | FAILED | short independent workload does not justify v2 promotion | -| Repeated-state gate v3 | ACTIVE | frozen 48-case/8-state scoped experiment; 2B reference execution is local/manual, not PR CI | +| Repeated-state gate v3 | FAILED | cache/runtime criteria passed strongly, but semantic-v2 quality and p95 latency criteria failed on the pinned 2B local run | | Product foundation | ACTIVE | supported direct-choice DecisionSession integrated; answerability/calibration remain planned | | Snake stateful reference loop | ACTIVE | fixed decision context + current-only dynamic state + direct logits + fresh/cache oracle | -| Snake controller quality benchmark | ACTIVE | bounded dynamic-body oracle + append-only fixed/episode matrix implemented; reference 2B screening evidence pending | +| Snake controller quality benchmark | ACTIVE | first pinned-2B direct v1 screening completed; stateful/fresh matched exactly but quality/order robustness were insufficient; direct v2 remediation requires rerun | | Repository adoption hardening | DONE | one-command demo, docs, package metadata and public intake integrated; GitHub settings remain external (#9) | ## Reference identity @@ -64,25 +64,41 @@ performance-regression case, semantic p50 was 14.98 s versus 68.40 s generated ( generated zero answer tokens, and the semantic path evaluated 9,226 physical versus 181,258 logical tokens. This is diagnostic evidence, not promotion evidence. -Repeated-state gate v3 is frozen before representative execution. The 2B reference run is intentionally local/manual rather than automatic PR CI; its fixture, scorer semantics and precommitted thresholds remain unchanged. Fixture SHA -`f9e5f56128f93efb952f1fc3f4f38441150cb0c29906f688977ffa69ea61338a` covers 48 unique decisions -in eight shared-state groups, four families, 2/4/8 candidates, short/medium/long state tiers and -normal/reversed candidate order. Its precommitted gate requires comparable quality, zero semantic -order changes, exact cache behavior, <=50% physical/logical tokens, and at least 2x p50/p95 group -latency advantage over generated JSON. See `benchmarks/repeated-state-gate-v3.md`. +The frozen repeated-state gate v3 was then executed locally on the pinned Qwen3.5-2B Q4_K_M CPU +identity and **FAILED** without changing the fixture or thresholds. Cache reuse passed exactly: +8 cold misses, 40 hits, zero fallbacks, zero semantic order changes and 94,244 physical versus +1,058,852 logical input tokens (~8.9%). Semantic-v2 nevertheless scored 32/48 versus generated +JSON 39/48, failing overall quality, evidence-entailment/rule-application family guardrails and the +4-candidate guardrail. Group latency narrowly passed the 2x p50 target (93.34 s vs 187.42 s) but +missed the 2x p95 target (226.43 s vs 438.35 s). This closes semantic-v2 promotion for the scoped +repeated-state path while preserving the runtime/cache evidence. See +`benchmarks/repeated-state-gate-v3.md`. + +## Snake direct screening evidence + +The first complete pinned-2B direct screening ran on clean `main` commit +`263f7ba1274f6f798d7a93a3c0cf4fcfffeae92f`. Stateful and fresh direct execution produced the +same fixed-state choices/scores and the same four episode outcomes, proving cache execution did not +change semantics. Both variants achieved only 5/10 fixed-state optimal-set agreement, 20% +catastrophic misses and 30% candidate-order changes; median episode food was 16 with 50% loop rate, +75% stall rate and 25% controller-failure rate. + +The stateful path reused 151,808 of 503,070 logical input tokens (~30.2%) with 593 cache hits and one +miss. Fixed-state p50 latency improved from 40.44 s fresh to 5.11 s stateful, but long episodes did +not retain that advantage because the runtime snapshotted roughly 23 MB of prefix state on each +shared call in addition to restoring cached state. Direct v2 therefore canonicalizes candidates by +stable ID before A/B/C lettering and reuses the existing cached prefix snapshot instead of capturing +it again on cache hits. The representative 2B screening must be rerun before holdout selection. ## Product direction -The general semantic-v2 gate remains valid evidence about that scorer, but it no longer defines the -whole product thesis. The primary direction is the stateful runtime contract demonstrated by Snake: -fixed decision context, current-only dynamic state, deterministic candidate sensors, direct -zero-generation choice readout and observable context reuse. +Semantic-v2 now has two failed promotion gates and remains an experimental comparison path. The +primary product hypothesis is stateful direct choice: canonical candidate ordering, one +zero-generation option-logit readout, deterministic constraints first, and exact fresh equivalence. ## Next -1. Validate the exact-head Snake stateful direct path on real-model smoke: cached and fresh stateful prompts must return identical choices/scores and cached execution must reduce physical token work. -2. Run repeated-state gate v3 locally on the unchanged pinned 2B CPU identity and record PASS/FAIL with host/runtime identity, without broadening the semantic-v2 claim. -3. Run the Snake controller screening matrix on the pinned reference 2B model; require oracle coverage, fixed-state quality, episode outcomes and append-only evidence before selecting a controller family. -4. Freeze a holdout Snake fixture before prompt/controller tuning is treated as validated; cache efficiency is not controller quality. -5. Exercise the supported DecisionSession contract in local 2B evidence without treating API stability as a quality/performance endorsement. -6. Protect `main` and add GitHub description/topics/social preview through repository settings; source-controlled checks cannot substitute for those settings. +1. Rerun the unchanged Snake controller screening on the pinned 2B model with direct v2 and compare stateful vs fresh exact outputs, quality, physical tokens, snapshot/restore bytes and latency. +2. If the remediated direct controller has acceptable screening quality, freeze a separate holdout fixture before any further prompt/controller tuning. +3. Exercise the supported DecisionSession contract on the pinned 2B model without treating API stability as a quality/performance endorsement. +4. Protect `main` and add GitHub description/topics/social preview through repository settings; source-controlled checks cannot substitute for those settings. From 34d79db643253b96433ec4547c87940887f8d2b0 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:21:20 +0200 Subject: [PATCH 12/35] Document direct v2 benchmark identity --- benchmarks/snake-controller-benchmark-v1.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/benchmarks/snake-controller-benchmark-v1.md b/benchmarks/snake-controller-benchmark-v1.md index 6b77771..66c806d 100644 --- a/benchmarks/snake-controller-benchmark-v1.md +++ b/benchmarks/snake-controller-benchmark-v1.md @@ -76,10 +76,15 @@ The initial matrix isolates controller/readout choices before broad model tuning | `generated-verbose` | generated JSON baseline | verbose | generated JSON v1 | generated | model (optional) | The stateful-vs-fresh direct comparison is deliberately controlled: both variants compile the exact -same question-first stateful prompt and therefore the same prompt hash. Only execution changes: -`shared` may restore the reusable prefix; `fresh` evaluates the same compiled prompt without -shared-prefix execution. A prompt-order change is a different experiment and must not be attributed -to caching. +same question-first stateful prompt and therefore the same prompt hash. Direct v2 canonicalizes +candidates lexicographically by stable candidate ID before assigning A/B/C/... readout labels, so +caller presentation order cannot change the direct prompt or candidate-to-token mapping. Only +execution changes: `shared` may restore the reusable prefix; `fresh` evaluates the same compiled +prompt without shared-prefix execution. + +The benchmark protocol fingerprint records the direct prompt version and candidate-order strategy. +This keeps direct-v1 screening evidence separate from direct-v2 reruns without changing or +overwriting the append-only ledger. Do not expand into a model/quantization Cartesian product until this first matrix identifies useful controller families. Different model artifacts are separate evidence identities. @@ -102,7 +107,7 @@ Each row records at least: - planner version and search/survival bounds; - configuration ID, scorer, input format, prompt mode, execution mode, effective prefix reuse and controller; - GGUF filename/SHA/size/quantization, llama.cpp binding/runtime, CPU/context/batch/thread settings; -- selected fixed cases plus episode seeds/board/horizon/stall threshold, hashed as a protocol fingerprint; +- selected fixed cases plus episode seeds/board/horizon/stall threshold and the direct compiler/order contract, hashed as a protocol fingerprint; - fixed-state metrics, oracle coverage, raw normal/reversed decision readouts and detailed per-case planner evidence; - episode metrics and per-seed outcomes; From da1ca650616288f151b133a567705fc05ca250d2 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:21:59 +0200 Subject: [PATCH 13/35] Test direct benchmark protocol identity --- tests/test_snake_controller_benchmark.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_snake_controller_benchmark.py b/tests/test_snake_controller_benchmark.py index 2356b72..20ca8da 100644 --- a/tests/test_snake_controller_benchmark.py +++ b/tests/test_snake_controller_benchmark.py @@ -291,6 +291,10 @@ def test_backend_load_failure_is_appended_and_reported(tmp_path: Path): rows = [json.loads(line) for line in ledger.read_text(encoding="utf-8").splitlines()] assert [row["record_type"] for row in rows] == ["run_start", "run_end"] assert rows[0]["model_runtime"]["artifact_filename"] == "missing.gguf" + assert rows[0]["protocol"]["direct_choice"] == { + "prompt_version": "letter-question-prefix-v2", + "candidate_order": "candidate_id_lexicographic", + } assert rows[0]["model_runtime"]["artifact_exists"] is False assert rows[-1]["status"] == "failed" assert "FileNotFoundError" in rows[-1]["error"] From 09b3f085b066804bd419ba811b3bcecc72015581 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:23:27 +0200 Subject: [PATCH 14/35] Document canonical direct choice and snapshot reuse --- docs/architecture.md | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 3fdbb8e..9c411f3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -118,8 +118,9 @@ runtime tolerance. A cache hit is an implementation event, not evidence of corre ## Direct choice readout -For small bounded action sets, Decisio can compile all valid candidates once as A/B/C/... options and -read the corresponding next-token logits from a single model evaluation: +For small bounded action sets, Decisio canonicalizes candidates by stable candidate ID, assigns +A/B/C/... labels deterministically, and reads the corresponding next-token logits from a single model +evaluation: ```text state + question + options @@ -137,7 +138,11 @@ state + question + options DecisionResult ``` -This is implemented by `LetterTokenScorer` and is the action readout used by the stateful Snake reference. It generates zero answer tokens and avoids one YES/NO evaluation per candidate. Direct logits are an internal primitive, not the product differentiator; option-order sensitivity and uncalibrated probability semantics remain explicit. +This is implemented by `LetterTokenScorer` and is the action readout used by the stateful Snake +reference. It generates zero answer tokens and avoids one YES/NO evaluation per candidate. Direct v2 +sorts by candidate ID before lettering, so caller presentation order compiles to the same prompt and +candidate-to-token mapping. Direct logits are an internal primitive, not the product differentiator; +verbalizer sensitivity and uncalibrated probability semantics remain explicit. `LetterTokenScorer(..., reuse_prefix=True)` marks an exact token prefix for model-context reuse. The generic scorer keeps this explicit; Snake selects it by default and offers `--fresh-prefix` as @@ -226,10 +231,12 @@ Semantic candidate branching remains a second scoped use of the same exact snaps The semantic scorer exposes an optional backend fast path, `shared_prefix_batch_next_token_logits`. The compiler can also mark a token-safe reusable state -prefix. The llama.cpp backend keeps one canonical sequence, snapshots complete sequence state, -restores candidate branches from that state, and keeps repeated-state checkpoints in an LRU bounded -by both entry count and serialized bytes. Keys are exact token prefixes within one loaded runtime; -unsupported boundaries fall back to ordinary shared-prefix evaluation. +prefix. The llama.cpp backend keeps one canonical sequence and repeated-state checkpoints in an LRU +bounded by both entry count and serialized bytes. A cold reusable prefix is snapshotted once; cache +hits restore that existing snapshot instead of serializing the same prefix again. Multi-prompt +branches reuse the cached snapshot as their rollback point when it exactly covers the decoded prefix. +Keys are exact token prefixes within one loaded runtime; unsupported boundaries fall back to ordinary +shared-prefix evaluation. Candidate branches execute serially on sequence 0, so their count is not limited by `max_sequences`. Native batch-aligned checkpoint requirements still apply; prompts without a safe checkpoint fall back to fresh evaluation. @@ -348,9 +355,11 @@ These should be answered by evidence rather than preference: ## Current implementation boundary -The canonical path is local GGUF through llama.cpp. The backend snapshots/restores complete -single-sequence model context state and keeps exact compiler-marked checkpoints in a byte-bounded -LRU. This deliberately avoids a KV-only assumption for hybrid/recurrent Qwen3.5 state. +The canonical path is local GGUF through llama.cpp. The backend snapshots complete single-sequence +model context state on the cold reusable-prefix path, restores that checkpoint on later exact hits, +and avoids redundant re-snapshotting when the cached state already represents the required rollback +point. Checkpoints stay in a byte-bounded LRU. This deliberately avoids a KV-only assumption for +hybrid/recurrent Qwen3.5 state. Snake now uses a fixed decision contract as the reusable direct-scoring prefix and sends only current world state plus deterministic candidate sensors on each model decision. The same prompt can be run From 5e74df572ce276f7898226fda068e4591b32181f Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:23:51 +0200 Subject: [PATCH 15/35] Describe canonical one-pass direct choice --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index cff8232..8f432e0 100644 --- a/README.md +++ b/README.md @@ -280,8 +280,8 @@ reuses only exact/prefix-safe context under explicit compiler/runtime rules. ### 4. Read the decision instead of generating an answer -For a small bounded action set, Decisio can render the valid actions as A/B/C/... and read the -corresponding next-token logits from one model evaluation: +For a small bounded action set, Decisio canonicalizes the valid actions by stable candidate ID, +renders them as A/B/C/..., and reads the corresponding next-token logits from one model evaluation: ```text A. UP @@ -405,8 +405,9 @@ typed action ``` A separate comparative semantic-v2 scorer also exists for experiments. It is **not** the general -default: its frozen short/fresh gate failed the precommitted general-purpose criteria. Repeated-state -experiments remain a scoped evidence lane. +default: both its frozen short/fresh gate and its later repeated-state promotion gate failed their +precommitted criteria. The promoted v1 direction is one-pass direct choice with deterministic +candidate ordering and fresh-equivalent model-state reuse. ## How this differs from SemIf @@ -463,7 +464,7 @@ Implemented now: - local GGUF + llama.cpp execution; - stable-context model-state reuse with fresh-path correctness checks; - bounded repeated-state context cache and runtime instrumentation; -- direct A/B/C choice logits with zero generated answer tokens; +- canonical direct A/B/C choice logits with zero generated answer tokens and caller-order invariance; - deterministic constraints-before-score examples; - exact model/runtime provenance; - frozen benchmark/evaluation tooling; From cb880aaa6f0d421deebf9e4c077d7159900cfd58 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:24:05 +0200 Subject: [PATCH 16/35] Record direct v2 correctness and reuse changes --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ab6ac8..f4acf13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ milestones rather than every experimental commit. - local GGUF + llama.cpp reference runtime with exact artifact/runtime provenance; - reusable single-sequence model-state snapshot/restore with a bounded repeated-state cache; - stateful direct A/B/C action readout with zero generated answer tokens; +- canonical candidate-ID ordering for direct-choice compiler v2, so caller presentation order does not change the prompt/readout mapping; +- repeated-prefix cache hits reuse the existing captured sequence state instead of serializing the same prefix again; - comparative semantic v2, semantic v1, direct-letter and generated JSON evidence paths; - frozen short/fresh and repeated-state benchmark contracts with retained machine-readable evidence; - constraint-first Snake, support-routing and policy-gate examples; From ac2cd475c57b70b9997a7bc21784b6e6c29a7b44 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:25:15 +0200 Subject: [PATCH 17/35] Record completed local benchmark evidence --- benchmarks/README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/benchmarks/README.md b/benchmarks/README.md index 3f6bb3d..b9b6124 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -112,6 +112,11 @@ The runner prints live progress/ETA. The evaluator includes the cold decision in group and applies the quality, order, cache/token and >=2x p50/p95 latency criteria frozen in the methodology document. +The pinned 2B local run **FAILED** the frozen gate: cache reuse/order/zero-generation mechanics passed, +but semantic-v2 scored 32/48 versus generated JSON 39/48 and failed the family/4-candidate quality +guardrails; p50 met the 2x target while p95 narrowly missed it. This closes semantic-v2 promotion for +the repeated-state scope without weakening the runtime/cache evidence. + ## Snake controller benchmark v1 [Snake controller benchmark v1](snake-controller-benchmark-v1.md) evaluates the Snake application @@ -119,8 +124,10 @@ at two levels: fixed-state decisions against a bounded dynamic-body planner, and seeded episodes. It is the controller-quality benchmark; it is separate from scorer promotion gates and from the smaller input/cache diagnostic. -The initial matrix compares the same stateful direct prompt under shared versus fresh execution, -compact input, semantic v2/v1 and the adjacent-food application policy. Every run appends a +The matrix compares the same stateful direct prompt under shared versus fresh execution, compact +input, semantic v2/v1 and the adjacent-food application policy. Direct v2 canonicalizes candidate IDs +before A/B/C lettering; its compiler version and ordering rule are part of the protocol fingerprint. +Every run appends a `run_start` manifest plus terminal configuration results to a JSONL ledger. Evidence binds source commit, fixture/protocol hashes, exact GGUF/runtime identity, prompt/execution mode, controller parameters, decision-quality metrics, episode outcomes and runtime/token/cache metrics. From 3e479a03c196b7f50e7336a881e862749510ef4e Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:25:18 +0200 Subject: [PATCH 18/35] Align repository quality with local 2B evidence --- docs/repository-quality.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/repository-quality.md b/docs/repository-quality.md index 1ef7301..eb2803f 100644 --- a/docs/repository-quality.md +++ b/docs/repository-quality.md @@ -66,9 +66,10 @@ Current evidence boundaries: - 0.8B CI real-model smoke proves the mechanism and directional token reduction; - pinned 2B reference gates are local/manual evidence, not automatic PR CI; - the pinned 2B short/fresh semantic-v2 gate remains a recorded FAIL and is not rewritten; -- repeated-state gate v3 decides only the scoped semantic-v2 repeated-state question; +- repeated-state gate v3 is a recorded FAIL: cache mechanics passed, semantic-v2 promotion did not; - Snake controller quality is separate from cache efficiency; -- representative 2B Snake screening and a later holdout remain pending. +- the first representative 2B direct screening is retained as v1 evidence; direct v2 remediation + requires a comparable rerun before holdout. Done when the relevant exact-head evidence is retained and `docs/current-state.md` records the result without broadening the claim beyond the benchmark contract. @@ -185,8 +186,9 @@ Remaining: | One-command pinned Snake demo | DONE | download/checksum/launch behavior has deterministic tests | | Package discovery metadata | DONE | wheel metadata exposes keywords, classifiers and project URLs | | Structured issue intake | DONE | bug reports request reproducible runtime identity; proposals start from user outcome | -| Exact-head 0.8B real-model smoke | PENDING | fresh/reused equivalence and physical-token reduction pass on candidate | -| 2B repeated-state gate v3 | PENDING LOCAL EVIDENCE | run locally on the pinned artifact and retain PASS/FAIL plus host/runtime identity | +| Exact-head 0.8B real-model smoke | PASS ON INTEGRATED PATH | fresh/reused equivalence and physical-token reduction covered by current real-model smoke | +| 2B repeated-state gate v3 | FAILED | cache/runtime criteria passed; semantic-v2 quality and global p95 criteria failed | +| 2B Snake direct screening v1 | EVIDENCE RETAINED | stateful/fresh exact semantics matched; quality/order robustness insufficient, so direct v2 rerun is required | | Stable `DecisionSession` | IMPLEMENTED NARROW SCOPE | direct-choice API only; 2B quality/performance evidence remains separate | | First alpha release | BLOCKED | API + release contract satisfied | | Branch protection / GitHub topics | PENDING REPOSITORY SETTING | source changes cannot substitute for the setting | From 59f55ca1e66ec606d58b7cdf26ad3a6e06cee7d4 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:25:22 +0200 Subject: [PATCH 19/35] Close semantic evidence lane and focus direct rerun --- .../llama-cpp-reference-runtime.md | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/workstreams/llama-cpp-reference-runtime.md b/docs/workstreams/llama-cpp-reference-runtime.md index f08347e..7dc151a 100644 --- a/docs/workstreams/llama-cpp-reference-runtime.md +++ b/docs/workstreams/llama-cpp-reference-runtime.md @@ -64,9 +64,9 @@ Semantic-v2 remains a separate evidence lane. Its failed general-purpose gate is | W4 | DONE | 2B semantic scorer-gate identity frozen before results. | | W5 | FAILED | Semantic-v2 short/fresh general gate failed family + latency criteria. | | W5a | DONE | Repeated-state diagnostic justified a scoped semantic experiment. | -| W5b | ACTIVE | Frozen repeated-state gate v3 decides only semantic-v2 repeated-state scope; pinned 2B execution is local/manual rather than automatic PR CI. | -| W6 | BLOCKED | Record semantic-v2 scope from W5b without rewriting failed evidence. | -| W7 | ACTIVE | Prove stateful direct Snake loop with fixed context and fresh/cache oracle. | +| W5b | FAILED | Frozen repeated-state gate v3 passed cache mechanics but failed semantic-v2 quality and global p95 promotion criteria on pinned 2B local evidence. | +| W6 | DONE | Semantic-v2 remains experimental/non-promoted; failed evidence is retained unchanged. | +| W7 | ACTIVE | Direct v1 stateful/fresh equivalence is proven; canonical direct v2 + snapshot-reuse remediation requires pinned-2B rerun before holdout. | ## Runtime contract @@ -116,9 +116,12 @@ The result remains authoritative for general short/fresh semantic-v2 use. Repeated-state diagnostic v2 later found equal observed quality on 6/7 unique cases and materially lower latency for semantic scoring with heavy context reuse. That justified the separately frozen -48-decision repeated-state gate v3. A PASS can support only `NARROW_SCOPE`; it cannot erase v2. +48-decision repeated-state gate v3. The pinned 2B gate then **FAILED**: exact cache behavior, order +robustness and zero generation passed, but semantic-v2 scored 32/48 versus generated JSON 39/48, +failed family/4-candidate quality guardrails and narrowly missed the global p95 >=2x latency target. -Contract: `benchmarks/repeated-state-gate-v3.md`. +Contract: `benchmarks/repeated-state-gate-v3.md`. The result closes semantic-v2 promotion for this +scope without invalidating the underlying reuse mechanism. ## W7 stateful direct reference loop @@ -158,10 +161,10 @@ build, method and calibration dataset. Without an exact match, output remains un Before this workstream can be finalized: -1. record W5b from its unchanged criteria as the semantic-v2 scope decision; -2. prove W7 fresh/cache equivalence plus physical-token reduction on an exact-head real-model smoke candidate; -3. retain representative 2B Snake controller screening separately from runtime-reuse evidence; +1. rerun W7 direct v2 on the pinned 2B identity after canonical candidate ordering and redundant-snapshot removal; +2. retain stateful/fresh exact-equivalence, controller-quality and runtime evidence separately; +3. freeze a Snake holdout only if the remediated screening quality is acceptable; 4. keep durable docs synchronized with the evidence results; -5. only then shape the smallest stable high-level session API and delete this workstream once its remaining obligations have durable owners. +5. delete this workstream once the remaining evidence obligations have durable owners. Historical failed gates remain failed; the stateful product direction does not rewrite them. From b008f6c7e8dd224a8921166f97b34cdb04b5486e Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:28:08 +0200 Subject: [PATCH 20/35] Render direct options in compiler order --- examples/snake/static/js/model-io-renderer.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/examples/snake/static/js/model-io-renderer.js b/examples/snake/static/js/model-io-renderer.js index b019d49..41b8a92 100644 --- a/examples/snake/static/js/model-io-renderer.js +++ b/examples/snake/static/js/model-io-renderer.js @@ -25,6 +25,14 @@ function positionText(value) { return `(${value.x}, ${value.y})`; } +function modelCandidates(request, scorer) { + const candidates = [...(request?.candidates || [])]; + if (scorer?.startsWith("letter_")) { + candidates.sort((left, right) => String(left.id).localeCompare(String(right.id))); + } + return candidates; +} + function skipReason(mode) { if (mode === "deterministic_adjacent_food_policy") { return "Adjacent-food policy: eat now with a safe next move available. Long-term safety is not guaranteed."; @@ -121,7 +129,8 @@ function renderModelInput(ui, request, record, status) { const options = make("div", "io-block"); options.append(make("span", "io-label", "OPTIONS SENT TO MODEL")); const optionList = make("div", "input-options"); - (request.candidates || []).forEach((candidate, index) => { + const scorer = record?.decision?.scorer || status?.scorer; + modelCandidates(request, scorer).forEach((candidate, index) => { optionList.append(renderInputOption(candidate, index, features[candidate.id])); }); options.append(optionList); @@ -176,7 +185,7 @@ function renderModelOutput(ui, request, record, busy) { return; } - const candidates = request?.candidates || []; + const candidates = modelCandidates(request, decision.scorer); const selectedIndex = candidates.findIndex((candidate) => candidate.id === decision.choice); const selectedSlot = selectedIndex >= 0 ? LETTERS[selectedIndex] : "?"; const hero = make("div", "readout-hero selected-output"); From 4c3351c57ddd1ac848468f3e34d18407cacea260 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:29:33 +0200 Subject: [PATCH 21/35] Keep product direction concise --- docs/product.md | 37 ++++++++----------------------------- 1 file changed, 8 insertions(+), 29 deletions(-) diff --git a/docs/product.md b/docs/product.md index 161443e..3c149e5 100644 --- a/docs/product.md +++ b/docs/product.md @@ -46,35 +46,14 @@ For decision-shaped workloads, Decisio aims to provide: A normal causal LLM already contains enough semantic information in its logits/hidden state to support useful bounded decisions without generating text. -The initial scorer hypothesis was that **comparative candidate-level binary semantic scoring** -would be a better general decision primitive than arbitrary answer-token scoring or -candidate-independent binary scoring. - -The first representative 2B short/fresh scorer gate did **not** support that as a general default, -and the later repeated-state gate also failed its precommitted quality guardrails despite strong -cache reuse. Semantic v2 therefore remains an experimental comparison path, not the promoted v1 -decision primitive. - -The active v1 hypothesis is **stateful direct choice**: deterministically canonicalize the supplied -candidate identities, compile one A/B/C/... choice prompt, evaluate it once, and read all option -logits from the same final model position. Stateful execution must remain equivalent to the same -compiled prompt evaluated fresh. - -For semantic candidate `c_i`: - -```text -state + question + all alternatives + candidate_i - | - v - YES / NO logits - | - v -score_i = logit(YES) - logit(NO) -``` - -Candidate scores are then normalized across the supplied alternatives. - -A separate answerability judgment estimates whether the state contains enough information to answer at all. +The initial comparative semantic-scoring hypothesis failed both its representative short/fresh +gate and its later repeated-state promotion gate. Semantic v2 remains an experimental comparison, +not the promoted v1 decision primitive. + +The active v1 hypothesis is **stateful direct choice**: canonicalize candidate identities, compile one +A/B/C/... prompt, evaluate it once, and read all option logits from the same final model position. +Stateful execution must remain equivalent to that same compiled prompt evaluated fresh. Answerability +remains a separate future judgment from candidate preference. ## Reference runtime From d870a5d7a2fd6b280b9bea74d29abf82a9b957c9 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:30:15 +0200 Subject: [PATCH 22/35] Record repeated-state gate v3 result --- benchmarks/repeated-state-gate-v3.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/benchmarks/repeated-state-gate-v3.md b/benchmarks/repeated-state-gate-v3.md index 8b0be27..0b5ff9b 100644 --- a/benchmarks/repeated-state-gate-v3.md +++ b/benchmarks/repeated-state-gate-v3.md @@ -1,6 +1,6 @@ # Repeated-state gate v3 -Status: frozen before representative execution +Status: executed on pinned 2B reference identity — **FAIL** Scope: many decisions over one unchanged application state Reference runtime: Qwen3.5-2B Q4_K_M GGUF + llama.cpp CPU @@ -13,6 +13,18 @@ This gate does **not** retry the failed general-purpose scorer-gate v2. A PASS c repeated-state product scope. Scorer-gate v2 remains the authority for short/fresh general-purpose use and remains FAIL. +## Representative result + +The unchanged pinned 2B local run failed the precommitted gate. Runtime/cache mechanics passed: +8 misses, 40 hits, zero fallbacks, zero semantic order changes and 94,244 physical versus 1,058,852 +logical input tokens (~8.9%). Semantic-v2 quality did not: 32/48 correct versus generated JSON +39/48, with failures in evidence entailment, rule application and the four-candidate guardrail. +Group p50 met the 2x latency target (93.34 s versus 187.42 s), while p95 narrowly missed it +(226.43 s versus 438.35 s). + +The result does not weaken any threshold and does not invalidate the state-reuse mechanism. It closes +semantic-v2 promotion for this repeated-state scope. + ## Why this gate exists Scorer-gate v2 run `35788235063` showed that semantic v2 was not suitable as a general default: From 061f9b057412ecec7745c9a00c2f0beb811463fe Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:30:37 +0200 Subject: [PATCH 23/35] Record first pinned 2B direct screening --- benchmarks/snake-controller-benchmark-v1.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/benchmarks/snake-controller-benchmark-v1.md b/benchmarks/snake-controller-benchmark-v1.md index 66c806d..a33d327 100644 --- a/benchmarks/snake-controller-benchmark-v1.md +++ b/benchmarks/snake-controller-benchmark-v1.md @@ -124,6 +124,23 @@ CI uploads the ledger as a retained artifact. Multiple ledger files can be summa history summarizer groups only comparable `configuration + model SHA + fixture SHA + protocol SHA` identities. +## First pinned-2B direct screening + +Clean `main` commit `263f7ba1274f6f798d7a93a3c0cf4fcfffeae92f` completed the first +representative `direct-stateful-verbose` versus `direct-fresh-verbose` screening on the pinned +Qwen3.5-2B Q4_K_M CPU identity. + +Stateful and fresh returned the same choices/scores and identical episode outcomes. Controller +quality was not sufficient for holdout: 5/10 fixed-state optimal-set agreement, 20% catastrophic +misses and 30% order changes. Stateful execution reused 151,808 / 503,070 logical tokens (~30.2%) +with 593 hits, one miss and zero fallbacks. Fixed-state p50 improved from 40.44 s fresh to 5.11 s +stateful, but repeated ~23 MB sequence-state snapshot/restore traffic erased that advantage in long +episodes. + +That run remains valid **direct-v1 evidence**. Direct v2 canonicalizes candidate IDs before lettering +and removes redundant snapshots on cache hits, so its rerun receives a different protocol fingerprint +and must not be merged statistically with the v1 screening. + ## Run ```bash From 86e96612a5f99b25f206c78b1fb257ea3dd1ad06 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:31:29 +0200 Subject: [PATCH 24/35] Document DecisionSession candidate ordering --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8f432e0..b2edb94 100644 --- a/README.md +++ b/README.md @@ -192,10 +192,11 @@ The first matching decision warms reusable model context; later decisions can re compiler/runtime rules permit. `fresh=True` evaluates the **same prompt** without shared-prefix execution and is the supported oracle/debug path. -This API deliberately exposes only the direct A/B/C/... readout in v1. It does not select among -experimental scorers, does not turn normalized option scores into calibrated confidence, and does -not replace deterministic application constraints. Remove impossible candidates before calling -`choose`. +This API deliberately exposes only the direct A/B/C/... readout in v1. Candidate IDs are +canonicalized before lettering, so caller presentation order does not change the compiled choice. +The API does not select among experimental scorers, turn normalized option scores into calibrated +confidence, or replace deterministic application constraints. Remove impossible candidates before +calling `choose`. ## Snake: the idea in one loop From 5de9d070d794c1f8235ba66c35ce5552d35cc97a Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:33:49 +0200 Subject: [PATCH 25/35] Focus roadmap on stateful direct evidence --- docs/roadmap.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 7eb0671..92193ed 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -13,7 +13,7 @@ Implementation order must optimize for learning. Performance engineering that do ## Milestone 0 — Reproducible decision laboratory -**Implementation status:** the pinned Qwen3.5-2B Q4_K_M GGUF + llama.cpp reference runtime, scorer/compiler core, zero-generation readouts and runtime evidence tooling are implemented. The general short/fresh semantic-v2 gate has completed and failed; repeated-state scope is being tested separately. +**Implementation status:** the pinned Qwen3.5-2B Q4_K_M GGUF + llama.cpp reference runtime, scorer/compiler core, zero-generation readouts and runtime evidence tooling are implemented. Both semantic-v2 promotion gates have completed and failed; the active evidence lane is stateful direct choice. Goal: establish a trustworthy baseline before building a service. @@ -44,7 +44,7 @@ Exit evidence: ## Milestone 1 — Prove the stateful decision loop -**Harness status:** generated JSON, direct A/B/C logits, candidate-order reversal, comparative semantic v2, independent semantic v1 and real-model llama.cpp execution are implemented. Scorer-gate v2 failed for semantic v2 as a short/fresh general default; repeated-state gate v3 is the active precommitted experiment. +**Harness status:** generated JSON, canonical direct A/B/C logits, candidate-order perturbation, semantic v2/v1 and real-model llama.cpp execution are implemented. Semantic-v2 failed both short/fresh and repeated-state promotion gates. The first pinned-2B direct screening proved stateful/fresh equivalence but exposed controller-quality and order-bias issues; direct v2 remediation is awaiting rerun. Goal: prove the core differentiator before expanding APIs: stable decision context is reusable, fresh-equivalent and materially reduces repeated prefill while decision quality is evaluated independently. @@ -71,8 +71,8 @@ Required experiment variants: Decision gate: - scorer-gate v2 remains FAIL for semantic v2 as a short/fresh general-purpose default and is not the product thesis; -- repeated-state gate v3 may support only a narrower semantic-v2 scope if its frozen criteria pass; -- direct A/B/C logits are the reference control primitive for the stateful Snake loop; the differentiator is the surrounding context/session contract, not the logits themselves; +- repeated-state gate v3 is FAIL and does not promote semantic-v2 even in its scoped workload; +- canonical direct A/B/C logits are the reference control primitive for the stateful Snake loop; the differentiator is the surrounding context/session contract, not the logits themselves; - no scorer becomes a universal default without scope-specific evidence. ## Milestone 2 — Answerability From cc55b807c022c8e64d2b4e2ce61ec565a514414b Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:33:53 +0200 Subject: [PATCH 26/35] Update contribution evidence boundaries --- CONTRIBUTING.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a5e0ebc..a1807ab 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,10 +69,7 @@ The pinned reference identity is Qwen3.5-2B Q4_K_M GGUF through exact host/runtime identity; PR CI is limited to cheaper 0.8B mechanism smoke. Smaller models and Metal runs are separate evidence identities. -The general short/fresh semantic-v2 gate is a recorded **FAIL** and must not be reinterpreted. -Repeated-state semantic evidence is governed separately by -`benchmarks/repeated-state-gate-v3.md`. Snake controller quality is governed by -`benchmarks/snake-controller-benchmark-v1.md` and is deliberately separate from cache efficiency. +Both semantic-v2 promotion gates are recorded **FAIL** results and must not be reinterpreted; the repeated-state run still retains strong cache-mechanism evidence. Snake controller quality is governed by `benchmarks/snake-controller-benchmark-v1.md` and remains deliberately separate from cache efficiency. Direct-v1 screening evidence is append-only; direct-v2 reruns use a distinct protocol fingerprint. Do not edit a frozen fixture silently. A fixture change requires a new explicit dataset/protocol identity or version decision. From 0d7ad51776c1eaa68cbbac457d3e90a3bb1f0797 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:33:57 +0200 Subject: [PATCH 27/35] Update evidence status after local 2B runs --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4acf13..b6f87d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,8 +38,8 @@ milestones rather than every experimental commit. - the pinned 2B short/fresh semantic-v2 gate remains **FAIL** on its unchanged criteria; - 0.8B real-model smoke proves fresh/reused correctness and physical-token reduction directionally; -- repeated-state gate v3 on the pinned 2B CPU identity remains the scoped semantic promotion gate; -- representative 2B Snake controller screening and a later holdout remain pending. +- repeated-state gate v3 on the pinned 2B CPU identity is **FAIL** for semantic-v2 promotion while retaining strong cache-reuse evidence; +- first representative 2B direct screening is retained: stateful/fresh semantics matched, but controller quality/order robustness were insufficient; direct v2 requires rerun before holdout. ### Still planned From 063c66745ea42ba4a2b6a6a84347225f2b855682 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:34:01 +0200 Subject: [PATCH 28/35] Align E2E residual gaps with local evidence --- .engineering/e2e.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.engineering/e2e.json b/.engineering/e2e.json index b815737..3e65a32 100644 --- a/.engineering/e2e.json +++ b/.engineering/e2e.json @@ -147,8 +147,8 @@ ], "minimum_automated_fidelity": "host_or_fake", "residual_gaps": [ - "repeated-state gate v3 decides only its frozen scoped semantic-v2 workload", - "the pinned 2B gate is intentionally executed locally and performance evidence remains bound to exact model/runtime/host identity" + "repeated-state gate v3 is a recorded semantic-v2 promotion FAIL while its cache/runtime evidence remains valid only for the frozen workload", + "the pinned 2B evidence is local and remains bound to exact model/runtime/host identity" ], "real_environment_confirmation": "required", "automation_gap_reason": null @@ -166,8 +166,8 @@ ], "minimum_automated_fidelity": "host_or_fake", "residual_gaps": [ - "representative 2B controller screening is not established by the 0.8B smoke rollout", - "controller quality and holdout evidence remain separate from cache-efficiency proof" + "first representative 2B direct-v1 screening is retained but direct-v2 remediation requires a comparable rerun", + "controller quality and later holdout evidence remain separate from cache-efficiency proof" ], "real_environment_confirmation": "conditional", "automation_gap_reason": null From f4a3350a7000a9addf5976be2a3a650438ac23e6 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:34:36 +0200 Subject: [PATCH 29/35] Test public session order invariance --- tests/test_session.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/test_session.py b/tests/test_session.py index dad008f..cb66a3f 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -152,6 +152,33 @@ def factory(config): assert session.closed is True +def test_session_canonicalizes_candidate_presentation_order(): + backend = None + + def factory(config): + nonlocal backend + backend = FakeBackend(config) + return backend + + with DecisionSession( + "model.gguf", + "Which support queue should own this ticket?", + _backend_factory=factory, + ) as session: + normal = session.choose(state={"ticket": "x"}, candidates=candidates()) + reversed_result = session.choose( + state={"ticket": "x"}, + candidates=tuple(reversed(candidates())), + ) + + assert backend is not None + assert normal.prompt_sha256 == reversed_result.prompt_sha256 + assert normal.scores == reversed_result.scores + assert normal.distribution == reversed_result.distribution + assert normal.choice == reversed_result.choice + assert backend.shared_calls[0][0] == backend.shared_calls[1][0] + + def test_fresh_mode_uses_identical_prompt_but_bypasses_shared_execution(): backend = None From bf4350347145e60125417d04f2b75682ccadcec5 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:34:49 +0200 Subject: [PATCH 30/35] Document DecisionSession canonical ordering --- src/decisio/session.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/decisio/session.py b/src/decisio/session.py index b4da3f9..d723dbd 100644 --- a/src/decisio/session.py +++ b/src/decisio/session.py @@ -20,7 +20,8 @@ class DecisionSession: The supported v1 session intentionally exposes one evidence-backed readout: direct A/B/C/... option logits with zero generated answer tokens. The stable decision context is compiled into the reusable question prefix; each choose call supplies only changing state - and the currently valid candidates. + and the currently valid candidates. Candidate IDs are canonicalized before direct option + lettering, so caller presentation order does not change the compiled choice. """ def __init__( From e39dade500a145559a2ef4052f0f0800890b1329 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:35:25 +0200 Subject: [PATCH 31/35] Cover direct ordering in both prompt modes --- tests/test_core.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tests/test_core.py b/tests/test_core.py index 328d937..8853f58 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -197,7 +197,8 @@ def test_letter_compiler_maps_ids_to_distinct_tokens(): assert compiled.version == "letter-baseline-v2" -def test_letter_compiler_is_invariant_to_candidate_presentation_order(): +@pytest.mark.parametrize("reuse_prefix", [False, True]) +def test_letter_compiler_is_invariant_to_candidate_presentation_order(reuse_prefix): item = request() reversed_request = ChoiceRequest( id=item.id, @@ -206,13 +207,18 @@ def test_letter_compiler_is_invariant_to_candidate_presentation_order(): candidates=tuple(reversed(item.candidates)), ) - left = compile_letter_choice(FakeTokenizer(), item, reuse_prefix=True) - right = compile_letter_choice(FakeTokenizer(), reversed_request, reuse_prefix=True) + left = compile_letter_choice(FakeTokenizer(), item, reuse_prefix=reuse_prefix) + right = compile_letter_choice( + FakeTokenizer(), reversed_request, reuse_prefix=reuse_prefix + ) assert left.prompt == right.prompt assert left.sha256 == right.sha256 assert left.readout == right.readout - assert left.version == right.version == "letter-question-prefix-v2" + assert left.version == right.version + assert left.version == ( + "letter-question-prefix-v2" if reuse_prefix else "letter-baseline-v2" + ) def test_letter_scorer_preserves_candidate_scores_when_caller_order_changes(): From e33f803778bb27468c1b892d191919cc71fce730 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:36:22 +0200 Subject: [PATCH 32/35] Expose prefix snapshot counts --- src/decisio/backends/llama_cpp.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/decisio/backends/llama_cpp.py b/src/decisio/backends/llama_cpp.py index 9807f57..2e3495c 100644 --- a/src/decisio/backends/llama_cpp.py +++ b/src/decisio/backends/llama_cpp.py @@ -231,6 +231,7 @@ def __init__(self, config: LlamaCppBackendConfig): "shared_prefix_calls": 0, "shared_prefix_fallbacks": 0, "prefix_state_snapshot_bytes": 0, + "prefix_state_snapshots": 0, "prefix_state_restore_bytes": 0, "prefix_state_restores": 0, "repeated_state_cache_hits": 0, @@ -590,6 +591,7 @@ def shared_prefix_batch_next_token_logits( # Capture once on the cold path so later decisions can restore the stable prefix. prefix_state = self._capture_sequence_state(0) self._metrics["prefix_state_snapshot_bytes"] += len(prefix_state) + self._metrics["prefix_state_snapshots"] += 1 self._store_repeated_prefix_state(cache_key, prefix_state) elif suffix_branch_count > 1: # Multiple prompt branches need a rollback point between suffixes. On a cache hit the @@ -599,6 +601,7 @@ def shared_prefix_batch_next_token_logits( else: prefix_state = self._capture_sequence_state(0) self._metrics["prefix_state_snapshot_bytes"] += len(prefix_state) + self._metrics["prefix_state_snapshots"] += 1 live_prefix_state = True for candidate_index, input_ids in enumerate(input_ids_batch): From 8e2f09db15fbc135ed4b1b206483e79b64b7851e Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:36:38 +0200 Subject: [PATCH 33/35] Assert cached snapshot count --- tests/test_llama_cpp_backend.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_llama_cpp_backend.py b/tests/test_llama_cpp_backend.py index 11f5cde..7d155d6 100644 --- a/tests/test_llama_cpp_backend.py +++ b/tests/test_llama_cpp_backend.py @@ -419,6 +419,7 @@ def restore(snapshot, seq_id): assert runtime._metrics["repeated_state_cache_misses"] == 1 assert runtime._metrics["repeated_state_cache_hits"] == 1 assert runtime._metrics["prefix_state_snapshot_bytes"] == 4 + assert runtime._metrics["prefix_state_snapshots"] == 1 assert runtime._metrics["prefix_state_restore_bytes"] == 4 assert runtime._metrics["prefix_state_restores"] == 1 assert runtime._metrics["logical_input_tokens"] == 10 From 1e6f185a2153615857754d8b7c055202c6487c10 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:41:43 +0200 Subject: [PATCH 34/35] Compact current state around durable evidence --- docs/current-state.md | 117 +++++++++++++++--------------------------- 1 file changed, 41 insertions(+), 76 deletions(-) diff --git a/docs/current-state.md b/docs/current-state.md index 594c653..85df59b 100644 --- a/docs/current-state.md +++ b/docs/current-state.md @@ -5,100 +5,65 @@ Owner: repository ## Current milestone -Make Decisio a stateful local decision runtime: keep stable task context reusable, score changing application state with typed zero-generation choices, and prove cache reuse against fresh execution on the pinned llama.cpp/GGUF path. +Make Decisio a stateful local decision runtime: reuse stable model context across changing +application state and return bounded typed actions with zero answer generation. -Active plans: [llama.cpp reference runtime evidence closure](workstreams/llama-cpp-reference-runtime.md) and [repository quality/adoption](repository-quality.md). +Active plan: [llama.cpp reference runtime evidence closure](workstreams/llama-cpp-reference-runtime.md). -## Active workstreams +## Workstreams -| Workstream | State | Blocker | +| Workstream | State | Current boundary | | --- | --- | --- | -| llama.cpp reference runtime | DONE | local-GGUF backend/CLI and scorer primitives implemented | -| Shared context-state fast path | DONE | native-batch-safe branching + bounded repeated-state cache | -| Scorer gate v2 | FAILED | short independent workload does not justify v2 promotion | -| Repeated-state gate v3 | FAILED | cache/runtime criteria passed strongly, but semantic-v2 quality and p95 latency criteria failed on the pinned 2B local run | -| Product foundation | ACTIVE | supported direct-choice DecisionSession integrated; answerability/calibration remain planned | -| Snake stateful reference loop | ACTIVE | fixed decision context + current-only dynamic state + direct logits + fresh/cache oracle | -| Snake controller quality benchmark | ACTIVE | first pinned-2B direct v1 screening completed; stateful/fresh matched exactly but quality/order robustness were insufficient; direct v2 remediation requires rerun | -| Repository adoption hardening | DONE | one-command demo, docs, package metadata and public intake integrated; GitHub settings remain external (#9) | +| llama.cpp reference runtime | DONE | local GGUF backend, direct logits and provenance implemented | +| Shared context-state fast path | DONE | exact single-sequence snapshot/restore + bounded prefix cache | +| Semantic scorer gate v2 | FAILED | short/fresh semantic-v2 is not promoted | +| Repeated-state gate v3 | FAILED | cache mechanics passed; semantic-v2 quality and global p95 promotion criteria failed | +| DecisionSession | ACTIVE | supported direct-choice API; answerability/calibration remain planned | +| Snake controller benchmark | ACTIVE | direct-v1 2B screening retained; direct-v2 remediation requires rerun | +| Repository adoption hardening | DONE | source-controlled onboarding/docs/intake integrated; GitHub settings remain #9 | ## Reference identity -The canonical evidence artifact remains Qwen3.5-2B Q4_K_M from +Representative evidence pins Qwen3.5-2B Q4_K_M from `unsloth/Qwen3.5-2B-GGUF` revision `1c466474d208da1a7c4b8cb87ebcdac78f160e34`, SHA-256 `aaf42c8b7c3cab2bf3d69c355048d4a0ee9973d48f16c731c0520ee914699223`, -with `llama-cpp-python==0.3.35` on CPU. +with `llama-cpp-python==0.3.35` on CPU. Metal is supported operationally but is a separate evidence +identity. -The integrated backend also exposes optional Apple Metal execution through `--device metal`. It -uses the same GGUF scoring and reusable sequence-state path, records its offload configuration in -runtime identity, and requires a Metal-enabled `llama-cpp-python` build. This is an operational -runtime option, not evidence equivalent to the pinned CPU reference. +## Evidence -## Scorer-gate v2 result - -Exact-head run `35788235063` completed the full 64-case matrix and **FAILED** without weakening any -precommitted criterion. - -Passed: runtime identity; shared/fresh and repeated-state correctness; overall quality -(`50/64` versus strongest baseline `53/64`); order robustness (`0/64` changes); native zero -generation. - -Failed: `evidence_entailment` was `12/16` versus `16/16` for the strongest baseline, and -short-workload latency was semantic p50 `829.39 s` versus generated JSON `199.38 s`. - -The four missed entailment cases are exact arithmetic/time conclusions (team size, storage, schedule, -budget). They are diagnostic evidence; the prompt is not tuned against these observed failures. - -All 64 short rows used conservative fresh fallback. Semantic v2 made 240 fresh candidate evaluations -and processed 53,333 physical input tokens per measured round. - -## Repeated-state evidence - -The 2B runtime oracle proved exact cached-vs-fresh scoring with 526 physical tokens versus 2574 fresh -and ~4.45x observed speedup. - -Diagnostic v2 then replicated the product signal on remote run `35840582210`: semantic and generated -both scored 12/14 across two rounds (6/7 unique cases), both missed only the same -performance-regression case, semantic p50 was 14.98 s versus 68.40 s generated (~4.57x), semantic -generated zero answer tokens, and the semantic path evaluated 9,226 physical versus 181,258 logical -tokens. This is diagnostic evidence, not promotion evidence. - -The frozen repeated-state gate v3 was then executed locally on the pinned Qwen3.5-2B Q4_K_M CPU -identity and **FAILED** without changing the fixture or thresholds. Cache reuse passed exactly: -8 cold misses, 40 hits, zero fallbacks, zero semantic order changes and 94,244 physical versus -1,058,852 logical input tokens (~8.9%). Semantic-v2 nevertheless scored 32/48 versus generated -JSON 39/48, failing overall quality, evidence-entailment/rule-application family guardrails and the -4-candidate guardrail. Group latency narrowly passed the 2x p50 target (93.34 s vs 187.42 s) but -missed the 2x p95 target (226.43 s vs 438.35 s). This closes semantic-v2 promotion for the scoped -repeated-state path while preserving the runtime/cache evidence. See +**Semantic-v2.** The frozen short/fresh scorer gate remains FAIL. The later pinned-2B repeated-state +gate also **FAILED** without changing thresholds: cache behavior passed with 8 misses, 40 hits, zero +fallbacks/order changes and 94,244 physical versus 1,058,852 logical tokens (~8.9%), but semantic-v2 +scored 32/48 versus generated JSON 39/48. Group p50 met the 2x target (93.34 s vs 187.42 s); p95 +missed it (226.43 s vs 438.35 s). Semantic-v2 is therefore experimental, not promoted. See `benchmarks/repeated-state-gate-v3.md`. -## Snake direct screening evidence - -The first complete pinned-2B direct screening ran on clean `main` commit -`263f7ba1274f6f798d7a93a3c0cf4fcfffeae92f`. Stateful and fresh direct execution produced the -same fixed-state choices/scores and the same four episode outcomes, proving cache execution did not -change semantics. Both variants achieved only 5/10 fixed-state optimal-set agreement, 20% -catastrophic misses and 30% candidate-order changes; median episode food was 16 with 50% loop rate, -75% stall rate and 25% controller-failure rate. +**Direct Snake v1.** Clean `main` commit +`263f7ba1274f6f798d7a93a3c0cf4fcfffeae92f` proved stateful and fresh direct execution returned +identical choices/scores and identical four-episode outcomes. Quality was insufficient for holdout: +5/10 optimal-set agreement, 20% catastrophic misses and 30% candidate-order changes. Stateful reused +151,808/503,070 logical tokens (~30.2%) with 593 hits/1 miss; fixed-state p50 improved from 40.44 s +fresh to 5.11 s stateful. Long episodes lost that advantage because each shared call also +re-snapshotted roughly 23 MB of prefix state. -The stateful path reused 151,808 of 503,070 logical input tokens (~30.2%) with 593 cache hits and one -miss. Fixed-state p50 latency improved from 40.44 s fresh to 5.11 s stateful, but long episodes did -not retain that advantage because the runtime snapshotted roughly 23 MB of prefix state on each -shared call in addition to restoring cached state. Direct v2 therefore canonicalizes candidates by -stable ID before A/B/C lettering and reuses the existing cached prefix snapshot instead of capturing -it again on cache hits. The representative 2B screening must be rerun before holdout selection. +**Direct v2 remediation.** Candidate IDs are canonicalized before A/B/C lettering so caller order +compiles to the same one-pass direct prompt/readout mapping. On cache hits the runtime reuses the +existing prefix snapshot instead of serializing it again. Prompt version and ordering strategy are +part of the Snake benchmark protocol fingerprint, so v1 evidence remains separate. ## Product direction -Semantic-v2 now has two failed promotion gates and remains an experimental comparison path. The -primary product hypothesis is stateful direct choice: canonical candidate ordering, one -zero-generation option-logit readout, deterministic constraints first, and exact fresh equivalence. +The promoted v1 hypothesis is stateful direct choice: deterministic constraints first, canonical +candidate ordering, one zero-generation option-logit readout, stable-context reuse and exact fresh +equivalence. ## Next -1. Rerun the unchanged Snake controller screening on the pinned 2B model with direct v2 and compare stateful vs fresh exact outputs, quality, physical tokens, snapshot/restore bytes and latency. -2. If the remediated direct controller has acceptable screening quality, freeze a separate holdout fixture before any further prompt/controller tuning. -3. Exercise the supported DecisionSession contract on the pinned 2B model without treating API stability as a quality/performance endorsement. -4. Protect `main` and add GitHub description/topics/social preview through repository settings; source-controlled checks cannot substitute for those settings. +1. Rerun the unchanged Snake screening locally on the pinned 2B identity with direct v2; compare + exact stateful/fresh outputs, quality, physical tokens, snapshot/restore bytes and latency. +2. Freeze a separate holdout only if the remediated screening quality is acceptable. +3. Exercise `DecisionSession` on the pinned 2B identity without turning API stability into a + quality/performance claim. +4. Complete repository settings tracked by #9. From a27607a588b78c281f688de542d8e641ecacb6c8 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Mon, 28 Sep 2026 15:43:26 +0200 Subject: [PATCH 35/35] Keep architecture contract context bounded --- docs/architecture.md | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 9c411f3..319987d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -118,9 +118,8 @@ runtime tolerance. A cache hit is an implementation event, not evidence of corre ## Direct choice readout -For small bounded action sets, Decisio canonicalizes candidates by stable candidate ID, assigns -A/B/C/... labels deterministically, and reads the corresponding next-token logits from a single model -evaluation: +For bounded choices, Decisio sorts stable candidate IDs, assigns A/B/C/... deterministically and +reads those next-token logits from one model evaluation: ```text state + question + options @@ -138,11 +137,8 @@ state + question + options DecisionResult ``` -This is implemented by `LetterTokenScorer` and is the action readout used by the stateful Snake -reference. It generates zero answer tokens and avoids one YES/NO evaluation per candidate. Direct v2 -sorts by candidate ID before lettering, so caller presentation order compiles to the same prompt and -candidate-to-token mapping. Direct logits are an internal primitive, not the product differentiator; -verbalizer sensitivity and uncalibrated probability semantics remain explicit. +`LetterTokenScorer` implements this zero-generation readout. Direct v2's ID sort makes caller order +compile identically; verbalizer sensitivity and uncalibrated score semantics remain explicit. `LetterTokenScorer(..., reuse_prefix=True)` marks an exact token prefix for model-context reuse. The generic scorer keeps this explicit; Snake selects it by default and offers `--fresh-prefix` as @@ -229,14 +225,10 @@ stable decision context -> reusable model context -> changing state/question -> Semantic candidate branching remains a second scoped use of the same exact snapshot/restore primitive. -The semantic scorer exposes an optional backend fast path, -`shared_prefix_batch_next_token_logits`. The compiler can also mark a token-safe reusable state -prefix. The llama.cpp backend keeps one canonical sequence and repeated-state checkpoints in an LRU -bounded by both entry count and serialized bytes. A cold reusable prefix is snapshotted once; cache -hits restore that existing snapshot instead of serializing the same prefix again. Multi-prompt -branches reuse the cached snapshot as their rollback point when it exactly covers the decoded prefix. -Keys are exact token prefixes within one loaded runtime; unsupported boundaries fall back to ordinary -shared-prefix evaluation. +`shared_prefix_batch_next_token_logits` uses compiler-marked safe prefixes on one canonical +sequence. Checkpoints live in an entry/byte-bounded LRU: cold prefixes snapshot once; exact hits +restore the cached snapshot, which also serves as the rollback point for compatible branches. +Unsupported boundaries fall back conservatively. Candidate branches execute serially on sequence 0, so their count is not limited by `max_sequences`. Native batch-aligned checkpoint requirements still apply; prompts without a safe checkpoint fall back to fresh evaluation. @@ -355,11 +347,9 @@ These should be answered by evidence rather than preference: ## Current implementation boundary -The canonical path is local GGUF through llama.cpp. The backend snapshots complete single-sequence -model context state on the cold reusable-prefix path, restores that checkpoint on later exact hits, -and avoids redundant re-snapshotting when the cached state already represents the required rollback -point. Checkpoints stay in a byte-bounded LRU. This deliberately avoids a KV-only assumption for -hybrid/recurrent Qwen3.5 state. +The canonical path is local GGUF through llama.cpp. Cold reusable prefixes snapshot complete +single-sequence state once; exact hits restore the cached checkpoint without re-snapshotting it. +This avoids a KV-only assumption for hybrid/recurrent Qwen3.5 state. Snake now uses a fixed decision contract as the reusable direct-scoring prefix and sends only current world state plus deterministic candidate sensors on each model decision. The same prompt can be run