From f4d3fc28b291bdb8fe6abd394946aa4056a6e694 Mon Sep 17 00:00:00 2001 From: Devin Phillip Davis <354534380+quantum-osiris@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:25:23 -0500 Subject: [PATCH 1/2] fix(bench): keep timed-out attempts out of calibration; clamp inference timeout to the substrate horizon Node Alpha audit F-03. A mentor attempt with no output (timeout, empty or malformed reply) was recorded as confidence 0 / wrong, which scores as a perfect Brier/ECE and can rank a model that answered nothing above one that answered. Such attempts are now skipped by sync_from_bench_candidates (they remain failures on the bench scorecard). query_model's default timeout is now min(420 s, substrate horizon), so Node Alpha gives up at 300 s; OSIRIS_INFERENCE_TIMEOUT overrides. Rows already in a calibration ledger are append-only and are not rewritten. Co-Authored-By: Claude Opus 5.5 --- osiris_cli/calibration.py | 8 +++-- osiris_termux_console.py | 31 +++++++++++++++-- tests/test_bench_calibration_horizon.py | 45 +++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 tests/test_bench_calibration_horizon.py diff --git a/osiris_cli/calibration.py b/osiris_cli/calibration.py index 8944c63c..d72c9e36 100644 --- a/osiris_cli/calibration.py +++ b/osiris_cli/calibration.py @@ -463,9 +463,13 @@ def sync_from_bench_candidates( Maps each candidate's self-test gate (`own_ok`) as empirical self-verification confidence (`1.000000` if `own_ok` else `0.000000`) against `hidden_ok` (`1` or `0`), skipping - infrastructure/artifact `integrity` exclusions. Returns count of newly appended rows. + infrastructure/artifact `integrity` exclusions and `no_output` attempts (a timeout or an empty + or malformed reply). A model that produced nothing made no prediction: scoring it as + "confidence 0, wrong" would give it a perfect Brier score for failing. Those attempts stay + counted as failures in the bench scorecard; they are availability failures, not calibration + evidence. Returns count of newly appended rows. """ - valid = [c for c in cands if isinstance(c, dict) and not c.get("integrity")] + valid = [c for c in cands if isinstance(c, dict) and not c.get("integrity") and not c.get("no_output")] if not valid: return 0 diff --git a/osiris_termux_console.py b/osiris_termux_console.py index 79b0d6a9..c41a07ed 100755 --- a/osiris_termux_console.py +++ b/osiris_termux_console.py @@ -422,7 +422,7 @@ def _suggest(command: str = ""): SUGGESTION 2: -- """ print(f"\n[*] Thinking of suggestions based on recent activity (Engine 1 · {suggest_model})...") - raw = query_model(prompt, suggest_model, stream=False, timeout=420) + raw = query_model(prompt, suggest_model, stream=False) _pending_suggestions.clear() found = re.findall(r"^SUGGESTION\s+(\d+):\s*(.+)$", raw, re.MULTILINE) if not found: @@ -5680,8 +5680,35 @@ def sanitize_input(text: str) -> str: clean = clean.replace('', '') return clean.strip() -def query_model(prompt: str, model: str, stream: bool = True, timeout: int = 420, +INFERENCE_TIMEOUT_CEILING_S = 420 + + +def inference_timeout_s() -> float: + """Default per-call model timeout: 420 s, never longer than this substrate's horizon. + + Node Alpha's horizon is 300 s, so a hung local model there gives up at 300 s rather than + 420 s. ``OSIRIS_INFERENCE_TIMEOUT`` overrides both (the operator's explicit choice). + """ + env = os.environ.get("OSIRIS_INFERENCE_TIMEOUT") + if env: + try: + v = float(env) + if v > 0: + return v + except ValueError: + pass + try: + import osiris_hardware_mesh + horizon = float(osiris_hardware_mesh.get_current_profile().execution_timeout_s) + except Exception: + horizon = float(INFERENCE_TIMEOUT_CEILING_S) + return min(float(INFERENCE_TIMEOUT_CEILING_S), horizon) + + +def query_model(prompt: str, model: str, stream: bool = True, timeout: float = None, fmt: dict = None) -> str: + if timeout is None: + timeout = inference_timeout_s() _last_backend.update(name=None, requested_model=model, model=None, substituted=False, is_mock=False, error=None) # First: attempt through OSIRIS BaseModelProvider when live (or when mock is explicitly opted in) try: diff --git a/tests/test_bench_calibration_horizon.py b/tests/test_bench_calibration_horizon.py new file mode 100644 index 00000000..f0cd789f --- /dev/null +++ b/tests/test_bench_calibration_horizon.py @@ -0,0 +1,45 @@ +"""Node Alpha audit F-03: timed-out attempts are not calibration evidence; inference honours the horizon.""" + +import importlib + +from osiris_cli import calibration + + +def _cand(task, mentor, own_ok, hidden_ok, no_output): + return {"entry": f"{task}-{mentor}", "run": "bench-r1", "task": task, "mentor": mentor, "n": 1, + "own_ok": own_ok, "hidden_ok": hidden_ok, "no_output": no_output, + "module_sha256": None if no_output else "ab" * 32} + + +def test_timed_out_attempts_do_not_earn_a_perfect_brier_score(tmp_path): + cal_path = tmp_path / "calibration.jsonl" + cands = [ + _cand("backlog", "ollama/gemma3:1b", False, False, True), # timed out + _cand("claims", "ollama/gemma3:1b", False, False, True), # timed out + _cand("gaps", "ollama/gemma3:1b", False, False, False), # produced code, own test failed + _cand("backlog", "ollama/qwen2.5-coder:7b", True, False, False), + ] + assert calibration.sync_from_bench_candidates(cands, path=cal_path) == 2 + obs = calibration.CalibrationLedger(cal_path).observations() + assert sorted((o.model_id, o.task_id) for o in obs) == [ + ("ollama/gemma3:1b", "gaps"), ("ollama/qwen2.5-coder:7b", "backlog")] + rep = calibration.compute_calibration(obs, num_bins=10, model_filter="ollama/gemma3:1b") + assert rep.num_samples == 1 # one real prediction, not three + + +def test_inference_timeout_is_clamped_to_the_substrate_horizon(monkeypatch): + import osiris_hardware_mesh + console = importlib.import_module("osiris_termux_console") + monkeypatch.delenv("OSIRIS_INFERENCE_TIMEOUT", raising=False) + + class P: + execution_timeout_s = 300.0 + + monkeypatch.setattr(osiris_hardware_mesh, "get_current_profile", lambda: P()) + assert console.inference_timeout_s() == 300.0 # Node Alpha: 300 s, not 420 s + P.execution_timeout_s = 1800.0 + assert console.inference_timeout_s() == 420.0 # Node Beta: the 420 s ceiling still applies + monkeypatch.setenv("OSIRIS_INFERENCE_TIMEOUT", "90") + assert console.inference_timeout_s() == 90.0 # explicit operator override + monkeypatch.setenv("OSIRIS_INFERENCE_TIMEOUT", "nonsense") + assert console.inference_timeout_s() == 420.0 From 6e049c546776cc11604a84e59e397e9e0c973006 Mon Sep 17 00:00:00 2001 From: Devin Phillip Davis <354534380+quantum-osiris@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:56:53 -0500 Subject: [PATCH 2/2] fix(calibration): leave no-output rows out of scores at read time and say how many Rows recorded before f4d3fc28 still scored timeouts as 'confidence 0, wrong'. On Node Beta this showed gemma4:e4b at n=9, Brier 0.000 with 6 of the 9 attempts producing nothing. /mentors and /bench calibration now drop the prediction IDs of no-output bench attempts when reading, and print the count ('6 attempt(s) with no output left out'). The append-only ledger is not rewritten; the scorecard still counts those attempts as failures. Co-Authored-By: Claude Opus 5.5 --- osiris_cli/calibration.py | 79 ++++++++++++++++++------- osiris_termux_console.py | 2 +- tests/test_bench_calibration_horizon.py | 25 ++++++++ 3 files changed, 85 insertions(+), 21 deletions(-) diff --git a/osiris_cli/calibration.py b/osiris_cli/calibration.py index d72c9e36..c0164aa7 100644 --- a/osiris_cli/calibration.py +++ b/osiris_cli/calibration.py @@ -17,7 +17,7 @@ from dataclasses import dataclass from decimal import ROUND_HALF_EVEN, Decimal, InvalidOperation from pathlib import Path -from typing import Any, Dict, List, Optional, Sequence, Tuple, Union +from typing import Any, Dict, FrozenSet, List, Optional, Sequence, Tuple, Union from .exec_kernel import ExecJournal, canon @@ -454,6 +454,22 @@ def evaluate( return report, receipt_hash +def _bench_prediction_id(c: Dict[str, Any]) -> str: + run_id = str(c.get("run") or c.get("entry") or "run") + task_id = str(c.get("task") or "task") + attempt_n = c.get("n") if c.get("n") is not None else 1 + return f"bench-{run_id}-{task_id}-{attempt_n}" + + +def no_output_prediction_ids(cands: Sequence[Dict[str, Any]]) -> FrozenSet[str]: + """Prediction IDs of bench attempts that produced no output (timeouts, empty or malformed replies). + + Used at read time so rows a ledger recorded before such attempts were skipped on ingest are + left out of the scores too. The append-only ledger itself is never rewritten. + """ + return frozenset(_bench_prediction_id(c) for c in cands if isinstance(c, dict) and c.get("no_output")) + + def sync_from_bench_candidates( cands: Sequence[Dict[str, Any]], *, @@ -479,8 +495,7 @@ def sync_from_bench_candidates( for c in valid: run_id = str(c.get("run") or c.get("entry") or "run") task_id = str(c.get("task") or "task") - attempt_n = c.get("n") if c.get("n") is not None else 1 - pid = f"bench-{run_id}-{task_id}-{attempt_n}" + pid = _bench_prediction_id(c) if pid in existing_ids: continue mentor = str(c.get("mentor") or "unknown") @@ -501,42 +516,59 @@ def sync_from_bench_candidates( return added -def sync_bench_ledger( - *, - bench_dir: PathArg = None, - path: PathArg = None, -) -> int: - """Load `~/.osiris/bench/results.ledger.jsonl` via `protege` and sync comparable candidates.""" +def load_bench_candidates(*, bench_dir: PathArg = None) -> List[Dict[str, Any]]: + """Comparable `protege` candidates from `~/.osiris/bench/results.ledger.jsonl` (empty if unavailable).""" try: import protege except ImportError: - return 0 + return [] bdir = str(Path(bench_dir).expanduser().resolve()) if bench_dir is not None else protege.BENCH_DIR entries, problem = protege.load_ledger(bdir) if problem or not entries: - return 0 + return [] cands, _skipped = protege.candidates( entries, protege.current_suite(), protege.current_runner(), bench_dir=bdir, ) - return sync_from_bench_candidates(cands, path=path) + return list(cands) + + +def sync_bench_ledger( + *, + bench_dir: PathArg = None, + path: PathArg = None, +) -> int: + """Load `~/.osiris/bench/results.ledger.jsonl` via `protege` and sync comparable candidates.""" + return sync_from_bench_candidates(load_bench_candidates(bench_dir=bench_dir), path=path) + + +def _drop_excluded(obs: List[CalibrationObservation], exclude_ids: FrozenSet[str]): + kept = [o for o in obs if o.prediction_id not in exclude_ids] + return kept, len(obs) - len(kept) + + +def _excluded_note(n: int) -> str: + return (f" · {n} attempt(s) with no output left out (availability failures, not predictions)" + if n else "") def format_summary( path: PathArg = None, *, model_filter: str = "", + exclude_ids: FrozenSet[str] = frozenset(), ) -> str: """Compact one-block summary surfaced in ``/mentors`` and ``/bench`` (<100 cols).""" ledger = CalibrationLedger(path) ok, _cnt, err = ledger.verify() if not ok: return f"Calibration ledger TAMPERED ({err}) -- inspect /bench calibration" - obs = ledger.observations(model_filter=model_filter) + obs, n_excluded = _drop_excluded(ledger.observations(model_filter=model_filter), exclude_ids) if not obs: - return "Calibration: 0 confidence-tagged predictions recorded (use /bench calibration)" + return ("Calibration: 0 confidence-tagged predictions recorded (use /bench calibration)" + + _excluded_note(n_excluded)) rep = compute_calibration(obs, num_bins=10, model_filter=model_filter) models = sorted({o.model_id for o in obs}) by_model: List[str] = [] @@ -546,6 +578,7 @@ def format_summary( head = ( f"Calibration ({rep.num_samples} scored): Brier={rep.brier_score_str} · " f"ECE={rep.ece_str} · conf={rep.mean_confidence_str} vs acc={rep.mean_accuracy_str}" + + _excluded_note(n_excluded) ) if len(models) > 1 or (models and not model_filter): return head + "\n " + " | ".join(by_model) @@ -557,13 +590,14 @@ def format_detailed( *, model_filter: str = "", num_bins: int = 10, + exclude_ids: FrozenSet[str] = frozenset(), ) -> str: """Full reliability-bin table (<100 cols) for ``/bench calibration`` and ``/calibration``.""" ledger = CalibrationLedger(path) ok, total_rows, err = ledger.verify() if not ok: return f"L6 CALIBRATION · TAMPERED ({err})" - obs = ledger.observations(model_filter=model_filter) + obs, n_excluded = _drop_excluded(ledger.observations(model_filter=model_filter), exclude_ids) rep = compute_calibration(obs, num_bins=num_bins, model_filter=model_filter) label = model_filter or "all models" lines = [ @@ -572,6 +606,8 @@ def format_detailed( f" Mean conf: {rep.mean_confidence_str} Empirical acc: {rep.mean_accuracy_str} " f"Overconf: {rep.overconfidence_str}", ] + if n_excluded: + lines.append(" " + _excluded_note(n_excluded).lstrip(" ·").rstrip()) if rep.num_samples == 0: lines.append(" No paired confidence/outcome observations recorded yet.") return "\n".join(lines) @@ -595,12 +631,15 @@ def run_command(args: str = "", *, osiris_home: PathArg = None) -> str: if from_bench_cmd: parts = parts[1:] path = default_calibration_path(osiris_home) + bdir = (default_osiris_home(osiris_home) / "bench") if osiris_home is not None else None + cands = load_bench_candidates(bench_dir=bdir) + exclude = no_output_prediction_ids(cands) if parts and parts[0].lower() == "sync": - bdir = (default_osiris_home(osiris_home) / "bench") if osiris_home is not None else None - added = sync_bench_ledger(bench_dir=bdir, path=path) - return f"Synced {added} new benchmark attempt(s) into calibration ledger.\n" + format_detailed(path) + added = sync_from_bench_candidates(cands, path=path) + return (f"Synced {added} new benchmark attempt(s) into calibration ledger.\n" + + format_detailed(path, exclude_ids=exclude)) if from_bench_cmd and osiris_home is None and "OSIRIS_CALIBRATION_LOG" not in os.environ: - sync_bench_ledger(path=path) + sync_from_bench_candidates(cands, path=path) if parts and parts[0].lower() == "verify": ledger = CalibrationLedger(path) ok, count, err = ledger.verify() @@ -608,4 +647,4 @@ def run_command(args: str = "", *, osiris_home: PathArg = None) -> str: status = "INTACT" if (ok and tail.intact) else "TAMPERED" return f"L6 calibration chain {status}: {count} entries, tail={tail.status}" + (f" ({err})" if err else "") model_filter = parts[0] if parts else "" - return format_detailed(path, model_filter=model_filter) + return format_detailed(path, model_filter=model_filter, exclude_ids=exclude) diff --git a/osiris_termux_console.py b/osiris_termux_console.py index c41a07ed..3217b0d3 100755 --- a/osiris_termux_console.py +++ b/osiris_termux_console.py @@ -3465,7 +3465,7 @@ def _mentors(command: str = ""): from osiris_cli import calibration as _cal_mod if cands: _cal_mod.sync_from_bench_candidates(cands) - cal_block = "\n\n" + _cal_mod.format_summary() + cal_block = "\n\n" + _cal_mod.format_summary(exclude_ids=_cal_mod.no_output_prediction_ids(cands)) except Exception: cal_block = "" print("\n" + protege.format_scorecard(card, skipped, suite) + runs + "\n\n" + protege.format_route(card) + cal_block + "\n") diff --git a/tests/test_bench_calibration_horizon.py b/tests/test_bench_calibration_horizon.py index f0cd789f..37158e44 100644 --- a/tests/test_bench_calibration_horizon.py +++ b/tests/test_bench_calibration_horizon.py @@ -43,3 +43,28 @@ class P: assert console.inference_timeout_s() == 90.0 # explicit operator override monkeypatch.setenv("OSIRIS_INFERENCE_TIMEOUT", "nonsense") assert console.inference_timeout_s() == 420.0 + + +def test_rows_recorded_under_the_old_rule_are_left_out_at_read_time(tmp_path): + """A ledger written before the fix already holds 'confidence 0, wrong' rows for timeouts. + + The append-only ledger is not rewritten; the summary drops those rows and says how many.""" + cal_path = tmp_path / "calibration.jsonl" + cands = [ + _cand("backlog", "ollama/gemma4:e4b", False, False, True), + _cand("claims", "ollama/gemma4:e4b", False, False, True), + _cand("gaps", "ollama/gemma4:e4b", True, False, False), + ] + led = calibration.CalibrationLedger(cal_path) + for c in cands: # what the old ingest did: every attempt, timeouts included + led.record_observation(c["mentor"], c["task"], "1.000000" if c["own_ok"] else "0.000000", + 1 if c["hidden_ok"] else 0, prediction_id=calibration._bench_prediction_id(c), + run_id=c["run"], evidence_ref="old") + before = calibration.format_summary(cal_path) + assert "3 scored" in before + after = calibration.format_summary(cal_path, exclude_ids=calibration.no_output_prediction_ids(cands)) + assert "1 scored" in after and "2 attempt(s) with no output left out" in after + assert "Brier=1.000000" in after # the one real prediction: confident and wrong + assert len(calibration.CalibrationLedger(cal_path).observations()) == 3 # ledger untouched + detailed = calibration.format_detailed(cal_path, exclude_ids=calibration.no_output_prediction_ids(cands)) + assert "1 scored" in detailed and "2 attempt(s) with no output left out" in detailed