Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 65 additions & 22 deletions osiris_cli/calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]],
*,
Expand All @@ -463,9 +479,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

Expand All @@ -475,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")
Expand All @@ -497,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] = []
Expand All @@ -542,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)
Expand All @@ -553,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 = [
Expand All @@ -568,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)
Expand All @@ -591,17 +631,20 @@ 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()
tail = ledger.verify_tail()
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)
33 changes: 30 additions & 3 deletions osiris_termux_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ def _suggest(command: str = ""):
SUGGESTION 2: <ID> -- <one short reason, or omit this line>
"""
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:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand Down
70 changes: 70 additions & 0 deletions tests/test_bench_calibration_horizon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""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


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
Loading