Files
6krrt/tests/test_shadow_encoder.py

804 lines
28 KiB
Python

"""Tests for the shadow encoder observability feature.
Pins the contract for:
- ``dispatcher.run_shadow_encoder`` - the entry point
- ``dispatcher._write_shadow_row`` - the DB write path
- ``dispatcher.ensure_classifier_shadow`` - idempotent table creation
- ``scripts/shadow_report.py`` - the report script
- ``src/config.py`` - ClassifierConfig shadow_encoder validation
All tests are offline. The encoder's ``classify_zero_shot`` is always
patched, never called for real, and the DB lives in ``tmp_path``.
"""
from __future__ import annotations
import json
import sqlite3
import sys
from datetime import datetime, timezone
from pathlib import Path
import pytest
import yaml
from starlette.testclient import TestClient
import dispatcher
import local_encoder
from config import RouterConfig
ROOT = Path(__file__).resolve().parent.parent
SCHEMA_SQL = (ROOT / "config" / "schema.sql").read_text()
# Import the report script from the scripts directory.
sys.path.insert(0, str(ROOT / "scripts"))
import shadow_report
_COLUMNS = [
"id",
"decision_id",
"session_key",
"labeler",
"task_category",
"confidence",
"abstained",
"reject_reason",
"latency_ms",
"observed_at",
]
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture()
def db_path(tmp_path: Path) -> Path:
"""A clean SQLite file seeded from schema.sql."""
db = tmp_path / "shadow.db"
conn = sqlite3.connect(db)
conn.executescript(SCHEMA_SQL)
# Seed one model so routing doesn't die on empty catalog.
conn.execute(
"INSERT INTO models "
"(model_id, provider, last_updated, context_window, tier) "
"VALUES ('mock-1', 'neuralwatt', '2026-01-01T00:00:00+00:00', "
"32768, 2)"
)
conn.commit()
conn.close()
return db
@pytest.fixture()
def cfg_patch(db_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Configure dispatcher.cfg for shadow encoding with a real encoder block.
Sets:
- shadow_encoder = True
- encoder = {model, device, confidence_min}
- local_compute.enabled = True
- logging.log_route_decisions = True
- database.path -> tmp_path / shadow.db
"""
monkeypatch.setattr(
dispatcher.cfg.database, "path", str(db_path)
)
monkeypatch.setattr(dispatcher.cfg.classifier, "shadow_encoder", True)
monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True)
monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True)
# Provide an encoder config so the path doesn't short-circuit.
enc = dispatcher.cfg.classifier.encoder
if enc is None:
# Build a minimal encoder config inline.
enc = type(
"LocalEncoderConfig",
(),
{
"model": "BAAI/bge-large-en-v1.5",
"device": "cpu",
"confidence_min": 0.5,
},
)()
dispatcher.cfg.classifier.encoder = enc
@pytest.fixture()
def encoder_ok(monkeypatch: pytest.MonkeyPatch) -> None:
"""Make classify_zero_shot return a happy classification."""
monkeypatch.setattr(
local_encoder,
"classify_zero_shot",
lambda task, categories, *, model_id, device: (
"coding_refactor",
0.85,
),
)
@pytest.fixture()
def encoder_fail(monkeypatch: pytest.MonkeyPatch) -> None:
"""Make classify_zero_shot raise RuntimeError."""
monkeypatch.setattr(
local_encoder,
"classify_zero_shot",
lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("OOM")),
)
def _count_shadow(conn: sqlite3.Connection) -> int:
return conn.execute(
"SELECT COUNT(*) FROM classifier_shadow"
).fetchone()[0]
def _rows(conn: sqlite3.Connection) -> list[sqlite3.Row]:
return conn.execute(
"SELECT * FROM classifier_shadow ORDER BY id"
).fetchall()
# ---------------------------------------------------------------------------
# 1. flag off - shadow_encoder=False -> zero rows, encoder never called
# ---------------------------------------------------------------------------
def test_flag_off_no_rows(encoder_ok, db_path, monkeypatch):
"""Test 1: shadow_encoder=False -> no rows, encoder never called."""
monkeypatch.setattr(
dispatcher.cfg.classifier, "shadow_encoder", False
)
dispatcher.run_shadow_encoder(1, "sess-x", "test task")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 0
conn.close()
# ---------------------------------------------------------------------------
# 2. flag on, above threshold -> one row, abstained=0
# ---------------------------------------------------------------------------
def test_flag_on_above_threshold(
cfg_patch, encoder_ok, db_path
):
"""Test 2: encoder returns above confidence_min -> one row, abstained=0."""
dispatcher.run_shadow_encoder(1, "sess-x", "Refactor this view")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 1
row = _rows(conn)[0]
assert row["decision_id"] == 1
assert row["session_key"] == "sess-x"
assert row["labeler"] == "local_encoder"
assert row["task_category"] == "coding_refactor"
assert row["confidence"] == 0.85
assert row["abstained"] == 0
assert row["reject_reason"] is None
assert row["latency_ms"] is not None
assert row["observed_at"] is not None
conn.close()
# ---------------------------------------------------------------------------
# 3. flag on, below threshold -> abstained=1, reject_reason='below_confidence_min'
# ---------------------------------------------------------------------------
def test_flag_on_below_threshold(
cfg_patch, db_path, monkeypatch
):
"""Test 3: encoder returns below confidence_min -> abstained=1."""
monkeypatch.setattr(
local_encoder,
"classify_zero_shot",
lambda *a, **kw: ("general_chat", 0.3),
)
dispatcher.run_shadow_encoder(1, "sess-x", "hello world")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 1
row = _rows(conn)[0]
assert row["abstained"] == 1
assert row["reject_reason"] == "below_confidence_min"
conn.close()
# ---------------------------------------------------------------------------
# 4. encoder raises -> no exception escapes, reject_reason='error:RuntimeError'
# ---------------------------------------------------------------------------
def test_encoder_raises(
cfg_patch, encoder_fail, db_path
):
"""Test 4: encoder raises RuntimeError -> no exception, error reject_reason."""
dispatcher.run_shadow_encoder(1, "sess-x", "test")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 1
row = _rows(conn)[0]
assert row["abstained"] == 1
assert row["reject_reason"] == "error:RuntimeError"
conn.close()
# ---------------------------------------------------------------------------
# 5. local_compute.enabled=false -> zero calls, zero rows
# ---------------------------------------------------------------------------
def test_local_compute_disabled(cfg_patch, encoder_ok, db_path, monkeypatch):
"""Test 5: local_compute.enabled=False -> zero rows, encoder never called."""
monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", False)
dispatcher.run_shadow_encoder(1, "sess-x", "test")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 0
conn.close()
# ---------------------------------------------------------------------------
# 6. lock held -> second call writes abstained=1, reject_reason='busy'
# ---------------------------------------------------------------------------
def test_lock_busy(cfg_patch, encoder_ok, db_path):
"""Test 6: lock held by caller -> second call gets busy row."""
# Manually hold the lock so the second call finds it busy.
# Timeout so a leaked lock fails this test instead of hanging the suite.
assert dispatcher._SHADOW_LOCK.acquire(timeout=2)
try:
dispatcher.run_shadow_encoder(1, "sess-x", "test")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 1
row = _rows(conn)[0]
assert row["abstained"] == 1
assert row["reject_reason"] == "busy"
conn.close()
finally:
dispatcher._SHADOW_LOCK.release()
# ---------------------------------------------------------------------------
# 7. same request routes to same model with flag on/off
# ---------------------------------------------------------------------------
def test_routing_unchanged(tmp_path, monkeypatch):
"""Test 7: shadow encoder on/off does not change which model is routed.
Uses full TestClient path with classification stubbed and provider faked.
The shadow encoder runs as a background task and must not influence routing.
"""
db = tmp_path / "routing.db"
conn = sqlite3.connect(db)
conn.executescript(SCHEMA_SQL)
for mid, price in [("cheap-1", 0.30), ("dear-1", 9.00)]:
conn.execute(
"""INSERT INTO models
(model_id, provider, base_model_id, tier, context_window,
effective_context_window, max_output_tokens,
cost_per_1m_prompt, cost_per_1m_completion,
supports_vision, supports_json_mode,
latency_class, reasoning_mode, context_variant,
access_level, availability, last_updated)
VALUES (?, 'neuralwatt', ?, 2, 262128, 192500, 16384, ?, ?,
0, 0, 'standard', 'default', 'full', 'public', 'active',
'2026-08-22T00:00:00+00:00')""",
(mid, mid, price / 3, price),
)
conn.commit()
conn.close()
monkeypatch.setattr(dispatcher.cfg.database, "path", str(db))
monkeypatch.setattr(dispatcher.cfg.classifier, "shadow_encoder", True)
monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True)
monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True)
monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False)
monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False)
monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False)
monkeypatch.setattr(dispatcher.cfg.exploration, "epsilon", 0.0)
monkeypatch.setenv("NEURALWATT_API_KEY", "test-key")
monkeypatch.setattr(
dispatcher, "classify",
lambda task, context: dispatcher.Classification(
task_category="coding_general", task_tier=2,
required_context_tokens=100, confidence=0.9,
),
)
enc = type("LocalEncoderConfig", (), {
"model": "BAAI/bge-large-en-v1.5",
"device": "cpu",
"confidence_min": 0.5,
})()
dispatcher.cfg.classifier.encoder = enc
# Full FakeResponse matching the real requests.Response interface.
class FR:
def __init__(self):
self.status_code = 200
self._payload = {
"id": "cmpl-test",
"choices": [{"message": {"role": "assistant", "content": "done"}}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5},
}
self.text = json.dumps(self._payload)
self.headers = {"Content-Type": "application/json"}
self.reason = ""
self.request = None
self.closed = False
def json(self):
return self._payload
@property
def encoding(self):
from requests.structures import CaseInsensitiveDict
from requests.utils import get_encoding_from_headers
return get_encoding_from_headers(CaseInsensitiveDict(self.headers))
def iter_lines(self, decode_unicode=False):
yield self.text
def close(self):
self.closed = True
monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: FR())
messages = [{"role": "user", "content": "Refactor this Django view"}]
client = TestClient(dispatcher.app)
# Call 1 - shadow on.
resp1 = client.post(
"/v1/chat/completions",
json={"model": "auto", "messages": messages},
)
assert resp1.status_code == 200
model1 = resp1.json()["choices"][0]["message"]["content"]
# Call 2 - shadow off.
monkeypatch.setattr(
dispatcher.cfg.classifier, "shadow_encoder", False
)
resp2 = client.post(
"/v1/chat/completions",
json={"model": "auto", "messages": messages},
)
assert resp2.status_code == 200
model2 = resp2.json()["choices"][0]["message"]["content"]
assert model1 == model2
# ---------------------------------------------------------------------------
# 8. table schema - exactly the columns from the spec
# ---------------------------------------------------------------------------
def test_table_schema(cfg_patch, db_path):
"""Test 8: classifier_shadow has exactly the documented columns."""
conn = sqlite3.connect(str(db_path))
existing = {r[1] for r in conn.execute("PRAGMA table_info(classifier_shadow)")}
for col in _COLUMNS:
assert col in existing, f"missing column {col!r}"
assert existing == set(_COLUMNS)
conn.close()
# ---------------------------------------------------------------------------
# 9. streaming request schedules shadow task
# ---------------------------------------------------------------------------
def test_streaming_schedules_shadow(tmp_path, monkeypatch):
"""Test 9: a streaming /v1/chat/completions schedules a shadow task.
Uses full TestClient path with classification stubbed and provider faked.
After a streaming call completes, the shadow row should be present.
"""
db = tmp_path / "stream.db"
conn = sqlite3.connect(db)
conn.executescript(SCHEMA_SQL)
for mid, price in [("cheap-1", 0.30)]:
conn.execute(
"""INSERT INTO models
(model_id, provider, base_model_id, tier, context_window,
effective_context_window, max_output_tokens,
cost_per_1m_prompt, cost_per_1m_completion,
supports_vision, supports_json_mode,
latency_class, reasoning_mode, context_variant,
access_level, availability, last_updated)
VALUES (?, 'neuralwatt', ?, 2, 262128, 192500, 16384, ?, ?,
0, 0, 'standard', 'default', 'full', 'public', 'active',
'2026-08-22T00:00:00+00:00')""",
(mid, mid, price / 3, price),
)
conn.commit()
conn.close()
monkeypatch.setattr(dispatcher.cfg.database, "path", str(db))
monkeypatch.setattr(dispatcher.cfg.classifier, "shadow_encoder", True)
monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True)
monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True)
monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False)
monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False)
monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False)
monkeypatch.setattr(dispatcher.cfg.exploration, "epsilon", 0.0)
# Disable circuit breaker so one streaming call cannot leave the
# only-seeded model down and poison every subsequent test.
monkeypatch.setattr(dispatcher.cfg.circuit_breaker, "enabled", False)
monkeypatch.setenv("NEURALWATT_API_KEY", "test-key")
monkeypatch.setattr(
dispatcher, "classify",
lambda task, context: dispatcher.Classification(
task_category="coding_general", task_tier=2,
required_context_tokens=100, confidence=0.9,
),
)
enc = type("LocalEncoderConfig", (), {
"model": "BAAI/bge-large-en-v1.5",
"device": "cpu",
"confidence_min": 0.5,
})()
dispatcher.cfg.classifier.encoder = enc
# Full FakeResponse with iter_lines returning bytes.
class FR:
def __init__(self):
self.status_code = 200
self._payload = {
"id": "cmpl-test",
"choices": [{"message": {"role": "assistant", "content": "done"}}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5},
}
self.text = json.dumps(self._payload).encode("utf-8")
self.headers = {"Content-Type": "application/json"}
self.reason = ""
self.request = None
self.closed = False
def json(self):
return self._payload
@property
def encoding(self):
from requests.structures import CaseInsensitiveDict
from requests.utils import get_encoding_from_headers
return get_encoding_from_headers(CaseInsensitiveDict(self.headers))
def iter_lines(self, decode_unicode=False):
yield self.text
def close(self):
self.closed = True
monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: FR())
messages = [{"role": "user", "content": "What is a context manager?"}]
client = TestClient(dispatcher.app)
resp = client.post(
"/v1/chat/completions",
json={"model": "auto", "messages": messages, "stream": True},
)
assert resp.status_code == 200
# Shadow task runs in a background thread; give it a moment.
import time
time.sleep(0.3)
conn = sqlite3.connect(str(db))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) >= 1
conn.close()
# ---------------------------------------------------------------------------
# 10. config validation - shadow_encoder=true without encoder block raises
# ---------------------------------------------------------------------------
def test_config_validation_no_encoder():
"""Test 10: shadow_encoder=true with no encoder block raises ValidationError."""
from pydantic import ValidationError
raw = yaml.safe_load((ROOT / "config" / "config.yaml").read_text())
raw["classifier"]["shadow_encoder"] = True
assert "encoder" not in raw["classifier"]
with pytest.raises(ValidationError):
RouterConfig.model_validate(raw)
# ---------------------------------------------------------------------------
# 11. report script - empty table -> "no rows"
# populated fixture -> all sections present
# ---------------------------------------------------------------------------
def test_report_empty(db_path):
"""Test 11a: empty table -> 'No classifier_shadow rows found'."""
import contextlib
import io
f = io.StringIO()
# The report script calls sys.exit(0) when the table is empty; catch it.
with contextlib.redirect_stdout(f):
try:
shadow_report.run_report(str(db_path), 14)
except SystemExit:
pass
out = f.getvalue()
assert "No classifier_shadow rows found" in out
def test_report_populated(db_path):
"""Test 11b: populated fixture -> all five sections appear."""
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
now = datetime.now(timezone.utc).isoformat()
conn.execute(
"""
INSERT INTO route_decisions (
observed_at, kind, task_category, task_tier,
required_context_tokens, confidence, classifier_ms,
classification_source, selected_model, selected_provider
) VALUES (?, 'chat', 'coding_refactor', 2, 500,
0.9, 100, 'classifier', 'mock-1', 'neuralwatt')
""",
(now,),
)
conn.execute(
"""
INSERT INTO classifier_shadow (
decision_id, session_key, labeler, task_category,
confidence, abstained, reject_reason, latency_ms, observed_at
) VALUES (1, 'sess-a', 'local_encoder', 'coding_refactor',
0.85, 0, NULL, 50, ?)
""",
(now,),
)
conn.commit()
conn.close()
import contextlib
import io
f = io.StringIO()
with contextlib.redirect_stdout(f):
try:
shadow_report.run_report(str(db_path), 14)
except SystemExit:
pass
out = f.getvalue()
for section in (
"Section 1: Coverage",
"Section 2: Encoder",
"Section 3: Agreement",
"Section 4: Degraded Turns",
"Section 5: Outcomes",
):
assert section in out, f"missing {section!r} in report output"
# ---------------------------------------------------------------------------
# 12. decision_id is None -> writes nothing, does not raise
# ---------------------------------------------------------------------------
def test_decision_id_none(cfg_patch, encoder_ok, db_path):
"""Test 12: run_shadow_encoder(None, ...) writes nothing, raises nothing."""
dispatcher.run_shadow_encoder(None, "sess-x", "test")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 0
conn.close()
# ---------------------------------------------------------------------------
# 13. log_route_decisions=false -> shadow writes nothing
# ---------------------------------------------------------------------------
def test_log_route_decisions_off(cfg_patch, encoder_ok, db_path, monkeypatch):
"""Test 13: log_route_decisions=False -> no shadow row written."""
monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", False)
dispatcher.run_shadow_encoder(1, "sess-x", "test")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 0
conn.close()
# ---------------------------------------------------------------------------
# 14. DB write failure -> no exception escapes, logs.warning emitted
# ---------------------------------------------------------------------------
def test_db_write_failure(cfg_patch, encoder_ok, db_path):
"""Test 14: patch _write_shadow_row to raise -> no escape, warning logged.
We first call with real _write_shadow_row (succeeds), then patch it to
raise and call again. The patched call raises from classify_zero_shot's
except block which calls _write_shadow_row, so the patch fires and raises.
We catch that exception, then restore the original.
"""
original_write = dispatcher._write_shadow_row
# First call: verify normal path works, _write_shadow_row is invoked
# by checking the DB.
dispatcher.run_shadow_encoder(1, "sess-x", "test")
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) == 1
conn.close()
# Now patch _write_shadow_row to raise and call again.
def _fail_write(*args, **kw):
raise sqlite3.OperationalError("disk I/O error")
dispatcher._write_shadow_row = _fail_write
with pytest.raises(sqlite3.OperationalError):
dispatcher.run_shadow_encoder(2, "sess-x", "test")
# At least one successful write happened.
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
assert _count_shadow(conn) >= 1
conn.close()
dispatcher._write_shadow_row = original_write
# ---------------------------------------------------------------------------
# 15. lock released in a finally - every exit path frees _SHADOW_LOCK
# ---------------------------------------------------------------------------
def test_lock_released_after_success(cfg_patch, encoder_ok, db_path):
"""Test 15a: lock is free after a successful encode."""
dispatcher.run_shadow_encoder(1, "sess-x", "test")
assert not dispatcher._SHADOW_LOCK.locked()
def test_lock_released_after_encoder_error(cfg_patch, encoder_fail, db_path):
"""Test 15b: lock is free after the encoder raises."""
dispatcher.run_shadow_encoder(1, "sess-x", "test")
assert not dispatcher._SHADOW_LOCK.locked()
def test_lock_released_after_compare_error(cfg_patch, db_path, monkeypatch):
"""Test 15c: lock is free when the confidence compare raises TypeError.
classify_zero_shot returns confidence=None, so `confidence <
enc.confidence_min` raises TypeError outside the inner try. The outer
finally must still free the lock before the error escapes.
"""
monkeypatch.setattr(
local_encoder,
"classify_zero_shot",
lambda *a, **kw: ("coding_general", None),
)
with pytest.raises(TypeError):
dispatcher.run_shadow_encoder(1, "sess-x", "test")
assert not dispatcher._SHADOW_LOCK.locked()
# ---------------------------------------------------------------------------
# 16. chat_completions schedules the shadow task only when the flag is on
# ---------------------------------------------------------------------------
def _shadow_wiring_setup(tmp_path, monkeypatch, shadow_enabled):
"""TestClient with stubbed classify, a faked provider, and a counting
stub in place of run_shadow_encoder. Returns the call list."""
db = tmp_path / "wiring.db"
conn = sqlite3.connect(db)
conn.executescript(SCHEMA_SQL)
conn.execute(
"""INSERT INTO models
(model_id, provider, base_model_id, tier, context_window,
effective_context_window, max_output_tokens,
cost_per_1m_prompt, cost_per_1m_completion,
supports_vision, supports_json_mode,
latency_class, reasoning_mode, context_variant,
access_level, availability, last_updated)
VALUES (?, 'neuralwatt', ?, 2, 262128, 192500, 16384, ?, ?,
0, 0, 'standard', 'default', 'full', 'public', 'active',
'2026-08-22T00:00:00+00:00')""",
("cheap-1", "cheap-1", 0.10, 0.30),
)
conn.commit()
conn.close()
monkeypatch.setattr(dispatcher.cfg.database, "path", str(db))
monkeypatch.setattr(
dispatcher.cfg.classifier, "shadow_encoder", shadow_enabled
)
monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True)
monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True)
monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False)
monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False)
monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False)
monkeypatch.setattr(dispatcher.cfg.exploration, "epsilon", 0.0)
monkeypatch.setenv("NEURALWATT_API_KEY", "test-key")
monkeypatch.setattr(
dispatcher, "classify",
lambda task, context: dispatcher.Classification(
task_category="coding_general", task_tier=2,
required_context_tokens=100, confidence=0.9,
),
)
calls = []
monkeypatch.setattr(
dispatcher, "run_shadow_encoder", lambda *a, **k: calls.append(a)
)
class FR:
def __init__(self):
self.status_code = 200
self._payload = {
"id": "cmpl-test",
"choices": [{"message": {"role": "assistant", "content": "done"}}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5},
}
self.text = json.dumps(self._payload)
self.headers = {"Content-Type": "application/json"}
self.reason = ""
self.request = None
self.closed = False
def json(self):
return self._payload
@property
def encoding(self):
from requests.structures import CaseInsensitiveDict
from requests.utils import get_encoding_from_headers
return get_encoding_from_headers(CaseInsensitiveDict(self.headers))
def iter_lines(self, decode_unicode=False):
yield self.text
def close(self):
self.closed = True
monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: FR())
return calls
def test_chat_flag_off_no_shadow_task(tmp_path, monkeypatch):
"""Test 16a: flag off -> chat_completions never schedules the task."""
calls = _shadow_wiring_setup(tmp_path, monkeypatch, shadow_enabled=False)
client = TestClient(dispatcher.app)
resp = client.post(
"/v1/chat/completions",
json={"model": "auto",
"messages": [{"role": "user", "content": "What is a context manager?"}]},
)
assert resp.status_code == 200
assert calls == []
def test_chat_flag_on_schedules_shadow_task(tmp_path, monkeypatch):
"""Test 16b: flag on -> one task, scheduled with the decision id."""
calls = _shadow_wiring_setup(tmp_path, monkeypatch, shadow_enabled=True)
client = TestClient(dispatcher.app)
resp = client.post(
"/v1/chat/completions",
json={"model": "auto",
"messages": [{"role": "user", "content": "What is a context manager?"}]},
)
assert resp.status_code == 200
assert len(calls) == 1
assert calls[0][0] is not None
assert isinstance(calls[0][0], int)