2 files changed, +188, -0
6cf31d0Update tests
author
mogi <git@paramogi.world> on 13-08-2026 16:08 UTC+1
committer
mogi <git@paramogi.world> on 13-08-2026 16:08 UTC+1
parent1aee430
    @@ -19,6 +19,7 @@ def test_the_defaults_are_the_mandated_paths() -> None:
1919     assert config.output_path == DEFAULT_OUTPUT
2020     assert config.model_name == DEFAULT_MODEL
2121     assert not config.verbose
  22+    assert not config.trace
2223 
2324 
2425 def test_another_model_can_be_asked_for() -> None:
    @@ -39,6 +40,7 @@ def test_every_flag_is_understood(tmp_path: Path) -> None:
3940             "--output",
4041             str(tmp_path / "results.json"),
4142             "--verbose",
  43+            "--trace",
4244         ]
4345     )
4446 
    @@ -46,6 +48,7 @@ def test_every_flag_is_understood(tmp_path: Path) -> None:
4648     assert config.input_path == tmp_path / "prompts.json"
4749     assert config.output_path == tmp_path / "results.json"
4850     assert config.verbose
  51+    assert config.trace
4952 
5053 
5154 def test_a_missing_input_file_fails_without_a_traceback(tmp_path: Path, capsys: object) -> None:
      @@ -0,0 +1,185 @@
     1+"""Tests for the report of the generation.
     2+
     3+Two things matter. The trace has to be honest: what it calls blocked really is
     4+refused by the rule, and what it calls taken really is what was written. And it
     5+has to be free of consequence: turning it on must not change one byte of the
     6+answer, since it only looks at what the decoder has already decided.
     7+"""
     8+
     9+from typing import Any, Tuple
    10+
    11+import pytest
    12+from conftest import BiasedModel, FakeModel
    13+
    14+from src.decoder import ConstrainedDecoder, DecoderError
    15+from src.grammar import Choice, parameters_template
    16+from src.models import JsonType, ParameterDefinition
    17+from src.trace import NO_TEXT, STOP_TEXT, Candidate, Tracer
    18+
    19+PARAMETERS = {"a": ParameterDefinition(type=JsonType.NUMBER)}
    20+
    21+
    22+def build(
    23+    token_bytes: Tuple[bytes, ...],
    24+    llm: Any,
    25+    tracer: Any = None,
    26+    stop_ids: Tuple[int, ...] = (),
    27+    budget: int = 128,
    28+) -> ConstrainedDecoder:
    29+    """Assemble a decoder over a fake vocabulary and a fake model.
    30+
    31+    Args:
    32+        token_bytes: The bytes of every token id.
    33+        llm: The fake model to drive.
    34+        tracer: Where to report the steps, or None to say nothing.
    35+        stop_ids: The ids the fake model ends a turn with.
    36+        budget: How many tokens one answer may take.
    37+
    38+    Returns:
    39+        The decoder to test.
    40+    """
    41+    return ConstrainedDecoder(
    42+        llm=llm,
    43+        token_bytes=token_bytes,
    44+        stop_ids=stop_ids,
    45+        tracer=tracer,
    46+        max_new_tokens=budget,
    47+    )
    48+
    49+
    50+def test_a_traced_run_writes_the_same_answer(token_bytes: Tuple[bytes, ...], capsys: Any) -> None:
    51+    """Watching the decoder must not change what it does."""
    52+    quiet = build(token_bytes, FakeModel(len(token_bytes), seed=3), budget=4096)
    53+    loud = build(token_bytes, FakeModel(len(token_bytes), seed=3), tracer=Tracer(), budget=4096)
    54+
    55+    assert loud.generate("anything", parameters_template(PARAMETERS)) == quiet.generate(
    56+        "anything", parameters_template(PARAMETERS)
    57+    )
    58+    assert capsys.readouterr().err != ""
    59+
    60+
    61+def test_nothing_is_said_when_no_tracer_is_given(token_bytes: Tuple[bytes, ...], capsys: Any) -> None:
    62+    """The trace is opt-in, so an ordinary run stays silent."""
    63+    build(token_bytes, FakeModel(len(token_bytes))).generate("anything", Choice(options=("fn_greet",)))
    64+
    65+    assert capsys.readouterr().err == ""
    66+
    67+
    68+def test_the_trace_reports_the_label_the_steps_and_the_answer(
    69+    token_bytes: Tuple[bytes, ...],
    70+    capsys: Any,
    71+) -> None:
    72+    """One header, one block per token written, one closing line."""
    73+    decoder = build(token_bytes, FakeModel(len(token_bytes)), tracer=Tracer())
    74+
    75+    decoder.generate("anything", Choice(options=("fn_greet",)), "choosing a function")
    76+
    77+    reported = capsys.readouterr().err
    78+    assert reported.startswith("trace: choosing a function\n")
    79+    assert "  step 0  so far \"\"\n" in reported
    80+    assert "  done \"fn_greet\" (the rule allows nothing more)" in reported
    81+
    82+
    83+def test_only_the_asked_for_number_of_tokens_is_described(
    84+    token_bytes: Tuple[bytes, ...],
    85+    capsys: Any,
    86+) -> None:
    87+    """A step describes the best-scoring few, plus the one taken if it sat deeper.
    88+
    89+    The model here is noise, so the token the rule ends up taking is almost
    90+    never among the best three, and each step costs one line more than asked.
    91+    """
    92+    decoder = build(token_bytes, FakeModel(len(token_bytes)), tracer=Tracer(top_k=3))
    93+
    94+    decoder.generate("anything", Choice(options=("fn_greet",)))
    95+
    96+    lines = capsys.readouterr().err.splitlines()
    97+    steps = sum(line.startswith("  step ") for line in lines)
    98+    described = sum(line.startswith("    ") for line in lines)
    99+    assert steps > 0
   100+    assert 3 * steps <= described <= 4 * steps
   101+
   102+
   103+def test_the_token_the_model_wanted_is_shown_as_blocked(
   104+    token_bytes: Tuple[bytes, ...],
   105+    capsys: Any,
   106+) -> None:
   107+    """The rigged model ranks an illegal piece first, and the trace says so."""
   108+    hello = token_bytes.index(b"hello")
   109+    decoder = build(token_bytes, BiasedModel(len(token_bytes), favourite=hello), tracer=Tracer())
   110+
   111+    decoder.generate("anything", Choice(options=("fn_greet",)))
   112+
   113+    first = capsys.readouterr().err.splitlines()[2]
   114+    assert first.startswith("    blocked")
   115+    assert first.endswith('"hello"')
   116+
   117+
   118+def test_exactly_one_token_per_step_is_taken(token_bytes: Tuple[bytes, ...], capsys: Any) -> None:
   119+    """Whatever the model wants, every step names the one token it acted on."""
   120+    decoder = build(token_bytes, FakeModel(len(token_bytes)), tracer=Tracer())
   121+
   122+    decoder.generate("anything", Choice(options=("fn_greet",)))
   123+
   124+    lines = capsys.readouterr().err.splitlines()
   125+    assert sum(line.startswith("    taken") for line in lines) == sum(
   126+        line.startswith("  step ") for line in lines
   127+    )
   128+
   129+
   130+def test_ending_the_turn_is_shown_as_a_choice_of_its_own(
   131+    token_bytes: Tuple[bytes, ...],
   132+    capsys: Any,
   133+) -> None:
   134+    """The marker writes no text, so it is named rather than quoted."""
   135+    end_of_turn = len(token_bytes)
   136+    llm = BiasedModel(end_of_turn + 1, favourite=end_of_turn)
   137+    decoder = build(token_bytes, llm, tracer=Tracer(), stop_ids=(end_of_turn,))
   138+
   139+    decoder.generate("anything", Choice(options=("fn_greet", "fn_greet_loudly")))
   140+
   141+    reported = capsys.readouterr().err
   142+    marker = [line.split() for line in reported.splitlines() if line.endswith(STOP_TEXT)]
   143+
   144+    assert all(fields[3] == str(end_of_turn) for fields in marker)
   145+    assert marker[0][0] == "blocked"
   146+    assert marker[-1][0] == "taken"
   147+    assert "(the model ended its turn)" in reported
   148+
   149+
   150+def test_a_token_that_writes_nothing_is_named_too(token_bytes: Tuple[bytes, ...], capsys: Any) -> None:
   151+    """An id the vocabulary does not describe cannot be quoted, only named."""
   152+    table = token_bytes + (b"",)
   153+    decoder = build(table, BiasedModel(len(table), favourite=len(table) - 1), tracer=Tracer())
   154+
   155+    decoder.generate("anything", Choice(options=("fn_greet",)))
   156+
   157+    assert NO_TEXT in capsys.readouterr().err
   158+
   159+
   160+def test_a_failure_is_traced_before_it_is_raised(token_bytes: Tuple[bytes, ...], capsys: Any) -> None:
   161+    """Why an answer stopped is worth seeing most when it stopped badly."""
   162+    decoder = build(token_bytes, FakeModel(len(token_bytes)), tracer=Tracer(), budget=2)
   163+
   164+    with pytest.raises(DecoderError):
   165+        decoder.generate("anything", parameters_template(PARAMETERS))
   166+
   167+    assert "(the budget of 2 tokens ran out)" in capsys.readouterr().err
   168+
   169+
   170+def test_a_candidate_names_what_became_of_it() -> None:
   171+    """The three outcomes a token may meet are told apart."""
   172+    taken = Candidate(token_id=1, text='"a"', score=1.0, legal=True, chosen=True)
   173+    passed = Candidate(token_id=2, text='"b"', score=0.5, legal=True)
   174+    refused = Candidate(token_id=3, text='"c"', score=0.1)
   175+
   176+    assert (taken.status, passed.status, refused.status) == ("taken", "allowed", "blocked")
   177+
   178+
   179+def test_a_long_answer_is_shown_by_its_end(token_bytes: Tuple[bytes, ...], capsys: Any) -> None:
   180+    """The step follows on from the end of the answer, so that is what is kept."""
   181+    decoder = build(token_bytes, FakeModel(len(token_bytes), seed=1), tracer=Tracer(), budget=4096)
   182+
   183+    decoder.generate("anything", parameters_template({f"p{index}": ParameterDefinition() for index in range(8)}))
   184+
   185+    assert '  step 60  so far "...' in capsys.readouterr().err