arborist/tests/test_soft_preflight.py
russell@unturf.com a94d6a3244
qa(#000011 + 4 more): SOFT_PREFLIGHT_HINT impl + 5-task fan-out
Big batch — closes 4 of the 5 deferred items from the prior status
report plus opens & implements a previously-deferred design ticket
(#000011) zero-shot.

#000025 — Metacog test fixture expansion:
  bench/qa_questions_metacog_subset.txt grows from 6 → 28 questions
  covering edge cases per detector kind: temporal (4 cases),
  contradiction (4), false-premise (5), out-of-corpus (3), multi-
  trigger (2), well-formed controls (5). Documents two known
  detector ceilings: Q11 over-fires on past-tense factoid
  ("who was the first president"); Q16/Q17/Q19 (Edison/Australia/
  NASA-fake) miss false premises that lack a presupposition
  pattern match. Fixture now serves as long-term regression suite.

#000026 — --show-preflight full clause render:
  build_run_dag() and build_reject_run_dag() gain optional
  preflight_payload kwarg. When supplied, the canonical 5-clause
  CTI payload (classifier / answer_contract / prompt_contract /
  evidence_contract / policy_refs + question_state + node_version)
  persists alongside the leaf hash in run_dag_blob.
  aborist providence --show-preflight CACHE_KEY now renders the
  full payload + verifies the persisted hash matches the
  recomputed canonical hash (audit-replay tamper detection).
  Legacy rows fall through cleanly: payload_hash_check reports
  "unavailable: legacy row predates preflight_payload persistence".

#000027 — Latency profile:
  Microbenched preflight: 0.46ms/question (negligible). Single
  fresh call breakdown: search 2.4s, llm 2.8s, total 5.4s — the
  33-35s in Addendum 3 was vLLM concurrency contention at c=4
  (per qa-modes-bench.md saturation note), not substrate
  overhead. Added preflight_ms + soft_preflight_ms to timings
  dict for explicit confirmation in future cycles.

#000028 — Auto-quality-check sweep revival:
  scripts/bench_emergent.py running with EMERGENT_N=100 in
  background (PID 125680). Will accumulate cycles into
  bench/emergent_log.jsonl for #000006 rolling log re-aggregation.
  Async — not blocking on completion.

#000029#000011 SOFT_PREFLIGHT_HINT implementation:
  aborist/qa/soft_preflight.py — new module. SoftPreflightHint
  dataclass + soft_preflight_question() pure function. 9
  canonical labels mapping to soft analogues of #000010 hard
  detectors plus 2 stub states (SOFT_DISABLED, SOFT_PARSE_FAIL).
  Constrained-generation prompt (max_tokens=128, temp=0.0) asks
  the model to pick ONE label + one-line rationale.
  Fail-closed across every parse path:
    - chat_client raises → SOFT_PARSE_FAIL
    - response unparseable → SOFT_PARSE_FAIL
    - label outside enum → SOFT_PARSE_FAIL
  Sidecar enforces SOFT_ prefix at the normalize step so a
  model that drops the prefix still gets caught.

  Wired into query() between preflight & retrieval. Default
  OFF (`soft_preflight_enabled: False`). NOT folded into
  _VERIFIER_POLICY_FIELDS — soft hints don't gate cache
  identity (#000011 §4). Audit-line tail renders as
  "· soft: <label>" (e.g. "· soft: time sensitive") so the
  signal is visually distinct from hard tails.

  --soft-preflight CLI flag opts in per-call. End-to-end
  live-verified on "When did Mr. Burns become Homer's biological
  father?" — produces:

    EVIDENCE-WARRANTED · via claim_lattice
        · false premise · soft: time sensitive
        1/1  16.4s

  Hard `· false premise` (from #000010 deterministic detector)
  composed with soft `· soft: time sensitive` (from #000011
  sidecar). The model classified a different shape than the hard
  detector — by design; soft hints are independent advisory
  signals, not redundant with the hard layer.

  25 new tests pin: default-OFF behavior, parse-failure modes,
  label normalization (SOFT_ prefix enforced), all 8 actionable
  labels round-trip, fail-closed on client exceptions, dataclass
  JSON round-trip, rationale-length cap.

Other:
  - #000010 §13.3 documents 2/5 metacog-trigger questions return
    STRICT despite hard-detector warning — direct empirical
    motivation for #000011 design.
  - tests/test_dag.py extends with 3 _extract_preflight_hash_*
    helper tests (cleaning #000009 §7.2 unfinished state).
  - bench/emergent_log.jsonl adds new cycles from background run.

#000011 status: closed. Hard rule (D1) preserved across all
1021 tests (up from 996, +25 new). Soft preflight is purely
advisory; the verifier proof path is unchanged.
2026-05-03 23:00:56 -04:00

232 lines
7.6 KiB
Python

"""Soft preflight sidecar (#000011) tests.
The sidecar produces ONLY soft hints labeled SOFT_*; it cannot
create PREFLIGHT_OK or PREFLIGHT_BLOCKED. These tests pin:
- default-OFF (sidecar disabled by default)
- parse-failure modes (all return stub, never raise)
- label normalization (SOFT_ prefix enforced)
- rationale extraction
- the dataclass schema
Uses a fake ChatClient (mock chat_completion) — no LLM round-trip.
"""
from __future__ import annotations
import pytest
from aborist.qa.soft_preflight import (
SOFT_PREFLIGHT_VERSION,
SoftPreflightHint,
_normalize_label,
_parse_soft_hint_response,
soft_preflight_question,
)
class _FakeChatClient:
"""Mock ChatClient that returns a configured response."""
def __init__(self, response: str):
self.response = response
self.call_count = 0
def chat_completion(self, *args, **kwargs) -> str:
self.call_count += 1
return self.response
class _RaisingChatClient:
"""Mock that raises on call — tests fail-closed behavior."""
def chat_completion(self, *args, **kwargs) -> str:
raise RuntimeError("simulated network failure")
# ----------------------------------------------------------- defaults
def test_sidecar_default_off_returns_stub_hint():
"""Without soft_preflight_enabled=True in policy, sidecar
returns SOFT_DISABLED stub. No LLM call happens."""
client = _FakeChatClient("LABEL: SOFT_WELL_FORMED\nRATIONALE: ok")
hint = soft_preflight_question(
"what is the capital of france?",
chat_client=client,
model_id="test-model",
policy={}, # no soft_preflight_enabled
)
assert hint.classifier_label == "SOFT_DISABLED"
assert hint.confidence == 0.0
assert client.call_count == 0 # no LLM call
def test_sidecar_explicit_off_returns_stub():
client = _FakeChatClient("LABEL: SOFT_WELL_FORMED\nRATIONALE: ok")
hint = soft_preflight_question(
"anything", chat_client=client, model_id="test",
policy={"soft_preflight_enabled": False},
)
assert hint.classifier_label == "SOFT_DISABLED"
assert client.call_count == 0
def test_empty_question_returns_stub_even_when_enabled():
client = _FakeChatClient("LABEL: SOFT_WELL_FORMED\nRATIONALE: ok")
hint = soft_preflight_question(
"", chat_client=client, model_id="test",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == "SOFT_DISABLED"
assert client.call_count == 0
# ----------------------------------------------------------- happy path
def test_sidecar_returns_soft_hint_when_enabled():
client = _FakeChatClient(
"LABEL: SOFT_FALSE_PREMISE_SUSPECTED\n"
"RATIONALE: question presupposes Mr. Burns is Homer's father"
)
hint = soft_preflight_question(
"When did Mr. Burns become Homer's biological father?",
chat_client=client,
model_id="hermes-test",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == "SOFT_FALSE_PREMISE_SUSPECTED"
assert hint.confidence == 0.5
assert "Mr. Burns" in hint.rationale
assert hint.model_profile_id == "hermes-test"
assert hint.sidecar_version == SOFT_PREFLIGHT_VERSION
assert client.call_count == 1
@pytest.mark.parametrize("label", [
"SOFT_WELL_FORMED",
"SOFT_CONTRADICTION_SUSPECTED",
"SOFT_TIME_SENSITIVE",
"SOFT_OUT_OF_CORPUS_LIKELY",
"SOFT_BROAD_QUANTIFIER",
"SOFT_MULTI_HOP_REASONING",
"SOFT_SUBJECTIVE",
"SOFT_SCOPE_AMBIGUOUS",
])
def test_each_canonical_label_passes_through(label):
client = _FakeChatClient(f"LABEL: {label}\nRATIONALE: test")
hint = soft_preflight_question(
"test", chat_client=client, model_id="m",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == label
# ----------------------------------------------------------- failure modes
def test_chat_client_exception_returns_parse_fail():
"""Sidecar fails-closed on chat_completion exceptions."""
client = _RaisingChatClient()
hint = soft_preflight_question(
"test", chat_client=client, model_id="m",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == "SOFT_PARSE_FAIL"
assert hint.confidence == 0.0
assert "RuntimeError" in hint.rationale
def test_unparseable_response_returns_parse_fail():
client = _FakeChatClient("garbage output no label here")
hint = soft_preflight_question(
"test", chat_client=client, model_id="m",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == "SOFT_PARSE_FAIL"
assert hint.confidence == 0.0
def test_model_drift_label_outside_enum_returns_parse_fail():
"""Model returns a label not in the enum → fail-closed."""
client = _FakeChatClient(
"LABEL: SOFT_INVENTED_NEW_LABEL\nRATIONALE: model drift"
)
hint = soft_preflight_question(
"test", chat_client=client, model_id="m",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == "SOFT_PARSE_FAIL"
def test_label_without_soft_prefix_gets_normalized():
"""Model drops the SOFT_ prefix → normalizer adds it back."""
client = _FakeChatClient("LABEL: WELL_FORMED\nRATIONALE: ok")
hint = soft_preflight_question(
"test", chat_client=client, model_id="m",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == "SOFT_WELL_FORMED"
def test_label_with_trailing_punctuation_normalized():
client = _FakeChatClient("LABEL: SOFT_WELL_FORMED.\nRATIONALE: ok")
hint = soft_preflight_question(
"test", chat_client=client, model_id="m",
policy={"soft_preflight_enabled": True},
)
assert hint.classifier_label == "SOFT_WELL_FORMED"
# ----------------------------------------------------------- pure helpers
def test_normalize_label_handles_whitespace():
assert _normalize_label(" SOFT_WELL_FORMED ") == "SOFT_WELL_FORMED"
def test_normalize_label_uppercases():
assert _normalize_label("soft_well_formed") == "SOFT_WELL_FORMED"
def test_normalize_label_returns_parse_fail_for_garbage():
assert _normalize_label("just garbage") == "SOFT_PARSE_FAIL"
def test_parse_soft_hint_handles_mixed_case_keys():
label, rationale = _parse_soft_hint_response(
"label: SOFT_WELL_FORMED\nrationale: ok"
)
assert label == "SOFT_WELL_FORMED"
assert rationale == "ok"
def test_parse_soft_hint_handles_missing_rationale_line():
"""When the model only writes LABEL: but no RATIONALE: line."""
label, rationale = _parse_soft_hint_response("LABEL: SOFT_WELL_FORMED")
assert label == "SOFT_WELL_FORMED"
assert rationale # something, even if "(no rationale)"
def test_parse_soft_hint_caps_rationale_length():
"""Long rationales get capped to keep payload bounded."""
long_rationale = "x" * 500
label, rationale = _parse_soft_hint_response(
f"LABEL: SOFT_WELL_FORMED\nRATIONALE: {long_rationale}"
)
assert len(rationale) <= 200
# ----------------------------------------------------------- dataclass schema
def test_hint_to_dict_is_json_serializable():
"""Bench rows / run-DAG persist soft hints as JSON; the
dataclass round-trips cleanly."""
import json
client = _FakeChatClient("LABEL: SOFT_WELL_FORMED\nRATIONALE: ok")
hint = soft_preflight_question(
"test", chat_client=client, model_id="m",
policy={"soft_preflight_enabled": True},
)
d = hint.to_dict()
json.dumps(d, ensure_ascii=False) # raises if non-serializable
def test_version_pinned():
assert SOFT_PREFLIGHT_VERSION == "soft-preflight-v0.1"