feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
This commit is contained in:
@@ -0,0 +1,244 @@
|
||||
"""Completion ownership, persistence and terminal-state race regressions."""
|
||||
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
from test_agent_cycle import done, m, verdict
|
||||
from test_agent_cycle import setup as cycle_setup
|
||||
|
||||
setup = cycle_setup
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("lease_seconds", "expired_at"), [(10, 110.0), (100, 200.0)], ids=["lease", "deadline"]
|
||||
)
|
||||
def test_completion_rechecks_expiry_after_source_validation(
|
||||
setup, monkeypatch, lease_seconds, expired_at
|
||||
):
|
||||
c, plan, clock = setup
|
||||
plan["limits"]["lease_seconds"] = lease_seconds
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
monkeypatch.setattr(m, "validate_packet", lambda *args: clock.__setitem__(0, expired_at))
|
||||
|
||||
with pytest.raises(ValueError, match="(?i)expired|deadline|lease"):
|
||||
c.complete(claim["token"], "author", dict(reason="source inspected"))
|
||||
|
||||
attempt = c.db.execute(
|
||||
"SELECT finished,result,result_sha FROM agent_attempts WHERE token=?", (claim["token"],)
|
||||
).fetchone()
|
||||
assert tuple(attempt) == (None, None, None)
|
||||
tasks = c.db.execute(
|
||||
"SELECT stage,result FROM agent_tasks WHERE cycle=?", (identity,)
|
||||
).fetchall()
|
||||
assert [tuple(task) for task in tasks] == [("annotate", None)]
|
||||
|
||||
|
||||
def test_root_decision_cannot_close_a_newly_interrupted_executor(setup, monkeypatch):
|
||||
c, plan, clock = setup
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
other = m.Cycle(c.root, clock=c.clock)
|
||||
status = c.status
|
||||
|
||||
def status_with_competing_expiry(identity):
|
||||
snapshot = status(identity)
|
||||
# The old implementation releases its status transaction before decide.
|
||||
# Do not attempt a second writer if the fixed implementation keeps it held.
|
||||
if not c.db.in_transaction:
|
||||
clock[0] = claim["expires"]
|
||||
assert other.status(identity)["tasks"][0]["state"] == "interrupted"
|
||||
return snapshot
|
||||
|
||||
monkeypatch.setattr(c, "status", status_with_competing_expiry)
|
||||
rejected = dict(verdict(), verdict="rejected", next="revise", admitted_units=[])
|
||||
try:
|
||||
with pytest.raises(ValueError, match="(?i)root decision|executor|terminal|interrupted"):
|
||||
c.decide(identity, "root", rejected)
|
||||
assert other.status(identity)["state"] != "closed"
|
||||
c.reconcile(claim["token"], "root", "Executor confirmed stopped")
|
||||
assert other.status(identity)["tasks"][0]["state"] == "blocked"
|
||||
finally:
|
||||
other.close()
|
||||
|
||||
|
||||
def test_completion_rejects_unknown_token_and_wrong_actor(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
result = dict(reason="source inspected")
|
||||
for token, actor in (("unknown-token", "author"), (claim["token"], "other")):
|
||||
with pytest.raises(ValueError, match="ownership"):
|
||||
c.complete(token, actor, result)
|
||||
task = c.status(identity)["tasks"][0]
|
||||
assert task["state"] == "active" and task["result"] is None
|
||||
c.complete(claim["token"], "author", result)
|
||||
|
||||
|
||||
def test_completion_replay_after_reopen_preserves_evidence_and_review(setup):
|
||||
c, plan, clock = setup
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
result = dict(reason="source inspected", geometry=[1, 2])
|
||||
sha = c.complete(claim["token"], "author", result)
|
||||
original = dict(
|
||||
c.db.execute("SELECT * FROM agent_attempts WHERE token=?", (claim["token"],)).fetchone()
|
||||
)
|
||||
c.close()
|
||||
clock[0] = 201.0
|
||||
reopened = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
assert reopened.complete(claim["token"], "author", result) == sha
|
||||
with pytest.raises(ValueError, match="ownership"):
|
||||
reopened.complete(claim["token"], "other", result)
|
||||
with pytest.raises(ValueError, match="Changed duplicate"):
|
||||
reopened.complete(claim["token"], "author", dict(reason="changed"))
|
||||
persisted = dict(
|
||||
reopened.db.execute(
|
||||
"SELECT * FROM agent_attempts WHERE token=?", (claim["token"],)
|
||||
).fetchone()
|
||||
)
|
||||
assert persisted == original
|
||||
assert reopened.db.execute(
|
||||
"SELECT COUNT(*) FROM agent_tasks WHERE cycle=? AND stage='review'", (identity,)
|
||||
).fetchone()[0] == 1
|
||||
assert reopened.db.execute(
|
||||
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
|
||||
).fetchone()[0] == 1
|
||||
finally:
|
||||
reopened.close()
|
||||
|
||||
|
||||
def test_executor_actor_cannot_reconcile_or_decide(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
with pytest.raises(ValueError, match="Root reconciliation"):
|
||||
c.reconcile(claim["token"], "author", "Executor stopped")
|
||||
assert c.status(identity)["tasks"][0]["state"] == "active"
|
||||
c.reconcile(claim["token"], "root", "Executor confirmed stopped", retry=True)
|
||||
done(c, identity)
|
||||
with pytest.raises(ValueError, match="Root decision"):
|
||||
c.decide(identity, "author", verdict())
|
||||
assert c.status(identity)["root_review"] is None
|
||||
c.decide(identity, "root", verdict())
|
||||
|
||||
|
||||
def test_sqlite_failure_rolls_back_completion_and_allows_same_claim_retry(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
result = dict(reason="source inspected")
|
||||
c.db.executescript("""
|
||||
CREATE TEMP TRIGGER fail_review_creation BEFORE INSERT ON agent_tasks
|
||||
WHEN NEW.stage = 'review'
|
||||
BEGIN SELECT RAISE(ABORT, 'injected review insert failure'); END;
|
||||
""")
|
||||
with pytest.raises(sqlite3.IntegrityError, match="injected review insert failure"):
|
||||
c.complete(claim["token"], "author", result)
|
||||
attempt = c.db.execute(
|
||||
"SELECT finished,result,result_sha FROM agent_attempts WHERE token=?", (claim["token"],)
|
||||
).fetchone()
|
||||
assert tuple(attempt) == (None, None, None)
|
||||
tasks = c.status(identity)["tasks"]
|
||||
assert len(tasks) == 1 and tasks[0]["state"] == "active" and tasks[0]["result"] is None
|
||||
|
||||
c.db.execute("DROP TRIGGER fail_review_creation")
|
||||
assert c.complete(claim["token"], "author", result) == m.digest(result)
|
||||
tasks = c.status(identity)["tasks"]
|
||||
assert [(task["stage"], task["state"]) for task in tasks] == [
|
||||
("annotate", "done"),
|
||||
("review", "ready"),
|
||||
]
|
||||
|
||||
|
||||
def test_ready_cancellation_rejects_foreign_actor_without_changing_state(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
before = c.status(identity)
|
||||
with pytest.raises(ValueError, match="(?i)root"):
|
||||
c.cancel_ready(identity, "author", "Stop the bounded trial")
|
||||
assert c.status(identity) == before
|
||||
|
||||
|
||||
def test_ready_cancellation_preserves_evidence_and_requires_executor_reconciliation(setup):
|
||||
c, plan, clock = setup
|
||||
plan["limits"]["parallel"] = 3
|
||||
plan["units"].extend(
|
||||
dict(plan["units"][0], id=unit) for unit in ["two", "three", "four", "five"]
|
||||
)
|
||||
identity = c.begin(plan)
|
||||
done(c, identity)
|
||||
interrupted = c.claim(identity, "three", "annotate", "stopped-author")
|
||||
proposed = c.claim(identity, "four", "annotate", "finished-author")
|
||||
c.complete(proposed["token"], "finished-author", dict(reason="Preserve this proposal"))
|
||||
clock[0] = 105.0
|
||||
active = c.claim(identity, "two", "annotate", "active-author")
|
||||
clock[0] = 110.0
|
||||
before = c.status(identity)
|
||||
frozen = tuple(
|
||||
c.db.execute(
|
||||
"SELECT plan,created,deadline FROM agent_cycles WHERE id=?", (identity,)
|
||||
).fetchone()
|
||||
)
|
||||
attempts = [
|
||||
dict(row)
|
||||
for row in c.db.execute(
|
||||
"SELECT * FROM agent_attempts WHERE cycle=? ORDER BY token", (identity,)
|
||||
)
|
||||
]
|
||||
untouched = {
|
||||
(task["unit"], task["stage"]): task for task in before["tasks"] if task["state"] != "ready"
|
||||
}
|
||||
reason = "Abort this trial after the dispatched authors stopped; revise before resuming"
|
||||
c.cancel_ready(identity, "root", reason)
|
||||
|
||||
reopened = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
after = reopened.status(identity)
|
||||
tasks = {(task["unit"], task["stage"]): task for task in after["tasks"]}
|
||||
for key, task in untouched.items():
|
||||
assert tasks[key] == task
|
||||
for key in [("four", "review"), ("five", "annotate")]:
|
||||
task = tasks[key]
|
||||
assert task["state"] == "blocked" and task["token"] is None
|
||||
assert task["attempt"] == 0 and task["result"]["reason"] == reason
|
||||
assert task["result_sha"] == m.digest(task["result"])
|
||||
assert after["root_review"] is None
|
||||
assert after["dispatches"] == before["dispatches"]
|
||||
assert tuple(
|
||||
reopened.db.execute(
|
||||
"SELECT plan,created,deadline FROM agent_cycles WHERE id=?", (identity,)
|
||||
).fetchone()
|
||||
) == frozen
|
||||
assert [
|
||||
dict(row)
|
||||
for row in reopened.db.execute(
|
||||
"SELECT * FROM agent_attempts WHERE cycle=? ORDER BY token", (identity,)
|
||||
)
|
||||
] == attempts
|
||||
|
||||
# A retry with nothing left to cancel must not replace the recorded reason.
|
||||
reopened.cancel_ready(identity, "root", "A different later explanation")
|
||||
assert reopened.status(identity) == after
|
||||
rejected = dict(
|
||||
verdict(),
|
||||
verdict="rejected",
|
||||
next="revise",
|
||||
admitted_units=[],
|
||||
inspected_units=[unit["id"] for unit in plan["units"]],
|
||||
)
|
||||
with pytest.raises(ValueError, match="(?i)root decision|executor|terminal"):
|
||||
reopened.decide(identity, "root", rejected)
|
||||
reopened.reconcile(active["token"], "root", "Active executor confirmed stopped")
|
||||
with pytest.raises(ValueError, match="executors"):
|
||||
reopened.decide(identity, "root", rejected)
|
||||
reopened.reconcile(interrupted["token"], "root", "Expired executor confirmed stopped")
|
||||
reopened.decide(identity, "root", rejected)
|
||||
closed = reopened.status(identity)
|
||||
assert closed["state"] == "closed" and closed["root_review"] == rejected
|
||||
with pytest.raises(ValueError, match="(?i)root|closed"):
|
||||
reopened.cancel_ready(identity, "root", reason)
|
||||
assert reopened.status(identity) == closed
|
||||
finally:
|
||||
reopened.close()
|
||||
@@ -0,0 +1,295 @@
|
||||
"""Failure paths that must stop an autonomous annotation loop."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SOURCE = Path(__file__).parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SOURCE))
|
||||
checksum = __import__("dataset_store").checksum
|
||||
|
||||
spec = importlib.util.spec_from_file_location("tested_agent_cycle", SOURCE / "agent_cycle.py")
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(m, "validate_packet", lambda *args: None)
|
||||
source = tmp_path / "raw.bin"
|
||||
source.write_bytes(b"bounded synthetic evidence")
|
||||
clock = [100.0]
|
||||
c = m.Cycle(tmp_path, clock=lambda: clock[0])
|
||||
plan = dict(
|
||||
schema_version=m.SCHEMA,
|
||||
root_actor="root",
|
||||
objective="complete ROI",
|
||||
baseline_sha256="a" * 64,
|
||||
recipe="v1",
|
||||
acceptance="source review",
|
||||
limits=dict(parallel=2, attempts=2, dispatches=8, seconds=100, lease_seconds=10),
|
||||
units=[
|
||||
dict(
|
||||
id="one",
|
||||
physical_group="area",
|
||||
split="train",
|
||||
sources=[
|
||||
dict(path="raw.bin", sha256=checksum(source), bytes=source.stat().st_size)
|
||||
],
|
||||
payload={},
|
||||
)
|
||||
],
|
||||
parent=None,
|
||||
)
|
||||
yield c, plan, clock
|
||||
c.close()
|
||||
|
||||
|
||||
def annotated(c, identity):
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
result = dict(reason="source inspected", geometry=[1, 2])
|
||||
sha = c.complete(claim["token"], "author", result)
|
||||
return claim, result, sha
|
||||
|
||||
|
||||
def done(c, identity):
|
||||
_, _, sha = annotated(c, identity)
|
||||
claim = c.claim(identity, "one", "review", "reviewer")
|
||||
c.complete(
|
||||
claim["token"],
|
||||
"reviewer",
|
||||
dict(reason="raw + proposal checked", proposal_sha256=sha, verdict="accept"),
|
||||
)
|
||||
|
||||
|
||||
def verdict():
|
||||
return dict(
|
||||
verdict="accepted",
|
||||
next="continue",
|
||||
reason="reviewed",
|
||||
inspected_units=["one"],
|
||||
admitted_units=["one"],
|
||||
checks=dict(coverage=True),
|
||||
tuning="keep limits",
|
||||
)
|
||||
|
||||
|
||||
def test_root_gate_and_restart(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
done(c, identity)
|
||||
other = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
assert other.status(identity)["state"] == "root_pending"
|
||||
next_plan = dict(plan, parent=identity, recipe="v2")
|
||||
with pytest.raises(ValueError, match="close"):
|
||||
other.begin(next_plan)
|
||||
other.decide(identity, "root", verdict())
|
||||
assert other.begin(next_plan) != identity
|
||||
finally:
|
||||
other.close()
|
||||
|
||||
|
||||
def test_review_identity_and_exact_proposal(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
_, _, sha = annotated(c, identity)
|
||||
with pytest.raises(ValueError, match="own"):
|
||||
c.claim(identity, "one", "review", "author")
|
||||
review = c.claim(identity, "one", "review", "reviewer")
|
||||
with pytest.raises(ValueError, match="exact"):
|
||||
c.complete(
|
||||
review["token"],
|
||||
"reviewer",
|
||||
dict(reason="x", verdict="accept", proposal_sha256="f" * 64),
|
||||
)
|
||||
assert review["proposal_sha256"] == sha
|
||||
|
||||
|
||||
def test_expired_claim_reserves_resource_until_stopped(setup):
|
||||
c, plan, clock = setup
|
||||
plan["limits"]["parallel"] = 1
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
clock[0] += 11
|
||||
assert c.status(identity)["state"] == "root_pending"
|
||||
with pytest.raises(ValueError, match="Expired"):
|
||||
c.complete(claim["token"], "author", dict(reason="late"))
|
||||
with pytest.raises(ValueError, match="executors"):
|
||||
c.decide(identity, "root", verdict())
|
||||
c.reconcile(claim["token"], "root", "executor terminated, receipt abc", retry=True)
|
||||
replacement = c.claim(identity, "one", "annotate", "author")
|
||||
assert replacement["token"] != claim["token"]
|
||||
with pytest.raises(ValueError, match="superseded"):
|
||||
c.complete(claim["token"], "author", dict(reason="stale"))
|
||||
clock[0] += 11
|
||||
c.status(identity)
|
||||
with pytest.raises(ValueError, match="budget"):
|
||||
c.reconcile(replacement["token"], "root", "stopped", retry=True)
|
||||
|
||||
|
||||
def test_idempotent_completion_and_source_mutation(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
claim, result, sha = annotated(c, identity)
|
||||
assert c.complete(claim["token"], "author", result) == sha
|
||||
with pytest.raises(ValueError, match="Changed duplicate"):
|
||||
c.complete(claim["token"], "author", dict(reason="changed"))
|
||||
(c.root / "raw.bin").write_bytes(b"mutation")
|
||||
with pytest.raises(ValueError, match="source changed"):
|
||||
c.claim(identity, "one", "review", "reviewer")
|
||||
|
||||
|
||||
def test_dispatch_budget_and_no_claim_twice(setup):
|
||||
c, plan, _ = setup
|
||||
plan["limits"]["dispatches"] = 1
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
other = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
with pytest.raises(ValueError):
|
||||
other.claim(identity, "one", "annotate", "other")
|
||||
finally:
|
||||
other.close()
|
||||
c.complete(claim["token"], "author", dict(reason="done"))
|
||||
assert c.status(identity)["state"] == "root_pending"
|
||||
with pytest.raises(ValueError, match="incomplete"):
|
||||
c.decide(identity, "root", verdict())
|
||||
|
||||
|
||||
def test_rejection_cannot_be_retried_without_changed_evidence(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
_, _, sha = annotated(c, identity)
|
||||
review = c.claim(identity, "one", "review", "reviewer")
|
||||
c.complete(
|
||||
review["token"],
|
||||
"reviewer",
|
||||
dict(reason="bad boundary", verdict="reject", proposal_sha256=sha),
|
||||
)
|
||||
root = dict(verdict(), verdict="rejected", next="revise", admitted_units=[])
|
||||
c.decide(identity, "root", root)
|
||||
with pytest.raises(ValueError, match="No progress"):
|
||||
c.begin(dict(plan, parent=identity))
|
||||
new = dict(plan, parent=identity, recipe="review finer source crop")
|
||||
c.begin(new)
|
||||
|
||||
|
||||
def test_input_validation_and_deadline(setup):
|
||||
c, plan, clock = setup
|
||||
bad = copy.deepcopy(plan)
|
||||
bad["units"][0]["split"] = "test"
|
||||
with pytest.raises(ValueError, match="TRAIN"):
|
||||
c.begin(bad)
|
||||
identity = c.begin(plan)
|
||||
clock[0] += 101
|
||||
assert c.status(identity)["state"] == "root_pending"
|
||||
with pytest.raises(ValueError):
|
||||
c.claim(identity, "one", "annotate", "author")
|
||||
assert c.status(identity)["dispatches"] == 0
|
||||
|
||||
|
||||
def test_concurrency_across_connections(setup):
|
||||
c, plan, _ = setup
|
||||
plan["limits"]["parallel"] = 1
|
||||
plan["units"].append(dict(plan["units"][0], id="two"))
|
||||
identity = c.begin(plan)
|
||||
c.claim(identity, "one", "annotate", "author")
|
||||
other = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
with pytest.raises(ValueError, match="concurrency"):
|
||||
other.claim(identity, "two", "annotate", "other")
|
||||
finally:
|
||||
other.close()
|
||||
|
||||
|
||||
def test_accepted_iteration_cannot_repeat_same_work_with_new_id(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
done(c, identity)
|
||||
c.decide(identity, "root", verdict())
|
||||
new = copy.deepcopy(plan)
|
||||
new["parent"] = identity
|
||||
new["units"][0]["id"] = "renamed"
|
||||
with pytest.raises(ValueError, match="No progress"):
|
||||
c.begin(new)
|
||||
|
||||
|
||||
def test_parallel_claims_cannot_exceed_dispatch_budget(setup):
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from threading import Barrier
|
||||
|
||||
c, plan, _ = setup
|
||||
plan["limits"].update(parallel=2, dispatches=1)
|
||||
plan["units"].append(dict(plan["units"][0], id="two"))
|
||||
identity = c.begin(plan)
|
||||
gate = Barrier(2)
|
||||
|
||||
def compete(unit):
|
||||
other = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
gate.wait(timeout=5)
|
||||
try:
|
||||
other.claim(identity, unit, "annotate", unit)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
finally:
|
||||
other.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
assert sum(pool.map(compete, ["one", "two"])) == 1
|
||||
assert c.status(identity)["dispatches"] == 1
|
||||
|
||||
|
||||
def test_root_quarantines_rejected_unit_without_repeating_accepted_work(setup):
|
||||
c, plan, _ = setup
|
||||
plan["units"].append(dict(plan["units"][0], id="two"))
|
||||
identity = c.begin(plan)
|
||||
done(c, identity)
|
||||
claim = c.claim(identity, "two", "annotate", "other")
|
||||
sha = c.complete(claim["token"], "other", dict(reason="uncertain source"))
|
||||
review = c.claim(identity, "two", "review", "reviewer")
|
||||
c.complete(
|
||||
review["token"],
|
||||
"reviewer",
|
||||
dict(reason="insufficient evidence", verdict="reject", proposal_sha256=sha),
|
||||
)
|
||||
root = dict(verdict(), inspected_units=["one", "two"])
|
||||
with pytest.raises(ValueError, match="failed"):
|
||||
c.decide(identity, "root", dict(root, admitted_units=["one", "two"]))
|
||||
c.decide(identity, "root", root)
|
||||
assert c.status(identity)["root_review"]["admitted_units"] == ["one"]
|
||||
|
||||
|
||||
def test_deadline_rechecked_after_source_verification(setup, monkeypatch):
|
||||
c, plan, clock = setup
|
||||
identity = c.begin(plan)
|
||||
monkeypatch.setattr(m, "validate_packet", lambda *args: clock.__setitem__(0, 201))
|
||||
with pytest.raises(ValueError, match="deadline passed"):
|
||||
c.claim(identity, "one", "annotate", "author")
|
||||
assert c.status(identity)["dispatches"] == 0
|
||||
|
||||
|
||||
def test_evidence_quota_never_silently_drops_completion(setup, monkeypatch):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
monkeypatch.setattr(m, "MAX_LEDGER_JSON", 1)
|
||||
with pytest.raises(ValueError, match="quota"):
|
||||
c.complete(claim["token"], "author", dict(reason="bounded output"))
|
||||
state = c.status(identity)
|
||||
assert state["tasks"][0]["state"] == "active"
|
||||
assert state["tasks"][0]["result"] is None
|
||||
|
||||
|
||||
def test_large_output_is_rejected_before_it_can_bloat_root_packet(setup):
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
with pytest.raises(ValueError, match="Result byte"):
|
||||
c.complete(claim["token"], "author", dict(reason="x", dump="x" * m.MAX_RESULT))
|
||||
assert c.status(identity)["tasks"][0]["state"] == "active"
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Regression coverage for accountable dispatch and annotation objective outcomes."""
|
||||
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
from test_agent_cycle import m, verdict
|
||||
from test_agent_cycle import setup as legacy_setup
|
||||
|
||||
setup = legacy_setup
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def v2(setup):
|
||||
c, plan, clock = setup
|
||||
plan["schema_version"] = m.SCHEMA_V2
|
||||
plan["objective_contract"] = dict(
|
||||
deliverable="Approved annotation evidence for the bounded packet",
|
||||
min_admitted_units=1,
|
||||
required_checks=["artifact_verified", "regressions_resolved"],
|
||||
)
|
||||
return c, plan, clock
|
||||
|
||||
|
||||
def add_unit(plan, name):
|
||||
plan["units"].append(dict(plan["units"][0], id=name))
|
||||
|
||||
|
||||
def sent(c, identity, unit, stage, actor):
|
||||
claim = c.claim(identity, unit, stage, actor)
|
||||
c.confirm_dispatch(claim["token"], "root", actor, "Actual handoff receipt")
|
||||
return claim
|
||||
|
||||
|
||||
def finish(c, identity, unit="one", accepted=True):
|
||||
claim = sent(c, identity, unit, "annotate", "author")
|
||||
sha = c.complete(claim["token"], "author", dict(reason="Source inspected"))
|
||||
claim = sent(c, identity, unit, "review", "critic")
|
||||
c.complete(
|
||||
claim["token"],
|
||||
"critic",
|
||||
dict(
|
||||
reason="Source and proposal checked",
|
||||
proposal_sha256=sha,
|
||||
verdict="accept" if accepted else "reject",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def outcome(**changes):
|
||||
result = dict(
|
||||
verdict(),
|
||||
objective_outcome="achieved",
|
||||
objective_checks=dict(artifact_verified=True, regressions_resolved=True),
|
||||
outcome_reason="Approved proposals checked against the frozen packet target",
|
||||
remaining_work=[],
|
||||
)
|
||||
result.update(changes)
|
||||
return result
|
||||
|
||||
|
||||
def test_unconfirmed_handoff_blocks_new_work_and_receipt_is_fenced(v2):
|
||||
c, plan, _ = v2
|
||||
add_unit(plan, "two")
|
||||
identity = c.begin(plan)
|
||||
first = c.claim(identity, "one", "annotate", "author")
|
||||
state = c.status(identity)
|
||||
assert state["unconfirmed_handoffs"][0]["token"] == first["token"]
|
||||
assert state["progress"]["proposed"] == 0
|
||||
with pytest.raises(ValueError, match="handoff"):
|
||||
c.claim(identity, "two", "annotate", "second")
|
||||
with pytest.raises(ValueError, match="root"):
|
||||
c.confirm_dispatch(first["token"], "author", "executor/one", "sent")
|
||||
receipt = c.confirm_dispatch(first["token"], "root", "executor/one", "sent")
|
||||
assert c.confirm_dispatch(first["token"], "root", "executor/one", "sent") == receipt
|
||||
with pytest.raises(ValueError, match="Conflicting"):
|
||||
c.confirm_dispatch(first["token"], "root", "executor/other", "sent")
|
||||
assert c.status(identity)["unconfirmed_handoffs"] == []
|
||||
assert c.claim(identity, "two", "annotate", "second")["token"] != first["token"]
|
||||
|
||||
|
||||
def test_fast_completion_before_root_receipt_is_not_rejected(v2):
|
||||
c, plan, _ = v2
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
result = dict(reason="Executor finished before root recorded dispatch")
|
||||
sha = c.complete(claim["token"], "author", result)
|
||||
c.confirm_dispatch(claim["token"], "root", "executor/one", "actual message reference")
|
||||
assert c.complete(claim["token"], "author", result) == sha
|
||||
assert c.status(identity)["ready_tasks"] == [dict(unit="one", stage="review")]
|
||||
|
||||
|
||||
def test_unconfirmed_expired_handoff_never_releases_capacity(v2):
|
||||
c, plan, clock = v2
|
||||
add_unit(plan, "two")
|
||||
identity = c.begin(plan)
|
||||
claim = c.claim(identity, "one", "annotate", "author")
|
||||
clock[0] = claim["expires"]
|
||||
assert c.status(identity)["progress"]["unreconciled"] == 1
|
||||
with pytest.raises(ValueError, match="handoff"):
|
||||
c.claim(identity, "two", "annotate", "second")
|
||||
c.reconcile(claim["token"], "root", "Verified no running executor; explicit recovery")
|
||||
with pytest.raises(ValueError, match="superseded"):
|
||||
c.confirm_dispatch(claim["token"], "root", "executor/one", "late")
|
||||
assert c.claim(identity, "two", "annotate", "second")
|
||||
|
||||
|
||||
def test_review_streams_while_other_author_is_running(v2):
|
||||
c, plan, _ = v2
|
||||
add_unit(plan, "two")
|
||||
identity = c.begin(plan)
|
||||
first = sent(c, identity, "one", "annotate", "author-a")
|
||||
sent(c, identity, "two", "annotate", "author-b")
|
||||
sha = c.complete(first["token"], "author-a", dict(reason="First packet ready"))
|
||||
with pytest.raises(ValueError, match="own"):
|
||||
c.claim(identity, "one", "review", "author-a")
|
||||
review = sent(c, identity, "one", "review", "critic")
|
||||
assert review["proposal_sha256"] == sha
|
||||
tasks = c.status(identity)["tasks"]
|
||||
assert any(t["unit"] == "two" and t["state"] == "active" for t in tasks)
|
||||
|
||||
|
||||
def test_ready_review_has_priority_over_new_author(v2):
|
||||
c, plan, _ = v2
|
||||
add_unit(plan, "two")
|
||||
identity = c.begin(plan)
|
||||
first = sent(c, identity, "one", "annotate", "author")
|
||||
c.complete(first["token"], "author", dict(reason="Ready"))
|
||||
assert c.status(identity)["ready_tasks"][0] == dict(unit="one", stage="review")
|
||||
with pytest.raises(ValueError, match="Ready reviews"):
|
||||
c.claim(identity, "two", "annotate", "second")
|
||||
|
||||
|
||||
def test_partial_admission_is_preserved_without_false_objective_completion(v2):
|
||||
c, plan, _ = v2
|
||||
add_unit(plan, "two")
|
||||
plan["objective_contract"]["min_admitted_units"] = 2
|
||||
identity = c.begin(plan)
|
||||
finish(c, identity)
|
||||
c.cancel_ready(identity, "root", "Second unit unavailable; preserve accepted first unit")
|
||||
review = outcome(inspected_units=["one", "two"])
|
||||
with pytest.raises(ValueError, match="not achieved"):
|
||||
c.decide(identity, "root", review)
|
||||
review.update(objective_outcome="not_achieved", remaining_work=["Review second unit"])
|
||||
c.decide(identity, "root", review)
|
||||
state = c.status(identity)
|
||||
assert state["root_review"]["admitted_units"] == ["one"]
|
||||
assert state["progress"]["admitted"] == 1
|
||||
assert state["progress"]["objective_outcome"] == "not_achieved"
|
||||
|
||||
|
||||
def test_frozen_one_of_two_target_can_be_achieved(v2):
|
||||
c, plan, _ = v2
|
||||
add_unit(plan, "two")
|
||||
identity = c.begin(plan)
|
||||
finish(c, identity)
|
||||
finish(c, identity, "two", accepted=False)
|
||||
c.decide(identity, "root", outcome(inspected_units=["one", "two"]))
|
||||
state = c.status(identity)
|
||||
assert state["progress"]["reviewed"] == 2
|
||||
assert state["progress"]["review_accepted"] == 1
|
||||
assert state["progress"]["objective_outcome"] == "achieved"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"checks",
|
||||
[
|
||||
{},
|
||||
dict(artifact_verified=True),
|
||||
dict(artifact_verified=True, regressions_resolved=True, invented=True),
|
||||
dict(artifact_verified=True, regressions_resolved="true"),
|
||||
dict(artifact_verified=True, regressions_resolved=False),
|
||||
],
|
||||
)
|
||||
def test_achievement_requires_exact_frozen_boolean_checks(v2, checks):
|
||||
c, plan, _ = v2
|
||||
identity = c.begin(plan)
|
||||
finish(c, identity)
|
||||
with pytest.raises(ValueError, match="(?i)objective"):
|
||||
c.decide(identity, "root", outcome(objective_checks=checks))
|
||||
assert c.status(identity)["state"] == "root_pending"
|
||||
|
||||
|
||||
def test_budget_exhaustion_is_inconclusive_not_achievement(v2):
|
||||
c, plan, clock = v2
|
||||
identity = c.begin(plan)
|
||||
clock[0] += plan["limits"]["seconds"]
|
||||
review = outcome(verdict="rejected", next="revise", admitted_units=[])
|
||||
with pytest.raises(ValueError, match="not achieved"):
|
||||
c.decide(identity, "root", review)
|
||||
review.update(
|
||||
objective_outcome="inconclusive",
|
||||
remaining_work=["No units executed; repair dispatch"],
|
||||
objective_checks=dict(artifact_verified=False, regressions_resolved=True),
|
||||
)
|
||||
c.decide(identity, "root", review)
|
||||
assert c.status(identity)["progress"]["objective_outcome"] == "inconclusive"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", [0, 2, True])
|
||||
def test_infeasible_annotation_target_is_rejected_before_claim(v2, target):
|
||||
c, plan, _ = v2
|
||||
plan["objective_contract"]["min_admitted_units"] = target
|
||||
with pytest.raises(ValueError, match="feasible"):
|
||||
c.begin(plan)
|
||||
assert c.db.execute("SELECT count(*) FROM agent_attempts").fetchone()[0] == 0
|
||||
|
||||
|
||||
def test_weaker_acceptance_alone_does_not_authorize_repeating_same_work(v2):
|
||||
c, plan, _ = v2
|
||||
add_unit(plan, "two")
|
||||
plan["objective_contract"]["min_admitted_units"] = 2
|
||||
identity = c.begin(plan)
|
||||
finish(c, identity)
|
||||
finish(c, identity, "two")
|
||||
c.decide(
|
||||
identity, "root", outcome(inspected_units=["one", "two"], admitted_units=["one", "two"])
|
||||
)
|
||||
successor = copy.deepcopy(plan)
|
||||
successor["parent"] = identity
|
||||
successor["objective_contract"]["min_admitted_units"] = 1
|
||||
with pytest.raises(ValueError, match="No progress"):
|
||||
c.begin(successor)
|
||||
|
||||
|
||||
def test_v1_history_keeps_original_decision_and_does_not_require_dispatch_receipt(setup):
|
||||
from test_agent_cycle import done
|
||||
|
||||
c, plan, _ = setup
|
||||
identity = c.begin(plan)
|
||||
done(c, identity)
|
||||
decision = verdict()
|
||||
sha = c.decide(identity, "root", decision)
|
||||
reopened = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
assert reopened.begin(plan) == identity
|
||||
state = reopened.status(identity)
|
||||
assert state["plan"] == plan and state["root_review"] == decision
|
||||
assert m.digest(state["root_review"]) == sha
|
||||
assert "progress" not in state
|
||||
finally:
|
||||
reopened.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("target", "dispatches", "feasible"),
|
||||
[
|
||||
(1, 1, False),
|
||||
(1, 2, True),
|
||||
(2, 3, False),
|
||||
(2, 4, True),
|
||||
],
|
||||
)
|
||||
def test_target_requires_both_author_and_review_budget(v2, target, dispatches, feasible):
|
||||
c, plan, _ = v2
|
||||
add_unit(plan, "two")
|
||||
plan["objective_contract"]["min_admitted_units"] = target
|
||||
plan["limits"]["dispatches"] = dispatches
|
||||
if feasible:
|
||||
assert c.begin(plan)
|
||||
else:
|
||||
with pytest.raises(ValueError, match="Dispatch budget"):
|
||||
c.begin(plan)
|
||||
assert c.db.execute("SELECT count(*) FROM agent_cycles").fetchone()[0] == 0
|
||||
|
||||
|
||||
def test_receipt_recovery_after_close_preserves_frozen_outcome(v2):
|
||||
c, plan, _ = v2
|
||||
identity = c.begin(plan)
|
||||
author = c.claim(identity, "one", "annotate", "author")
|
||||
sha = c.complete(author["token"], "author", dict(reason="Fast completion"))
|
||||
review = c.claim(identity, "one", "review", "critic")
|
||||
c.complete(
|
||||
review["token"], "critic", dict(reason="Checked", verdict="accept", proposal_sha256=sha)
|
||||
)
|
||||
c.decide(identity, "root", outcome())
|
||||
before = c.status(identity)
|
||||
reopened = m.Cycle(c.root, clock=c.clock)
|
||||
try:
|
||||
receipt = reopened.confirm_dispatch(
|
||||
author["token"], "root", "executor/author", "Recovered actual message reference"
|
||||
)
|
||||
assert (
|
||||
reopened.confirm_dispatch(
|
||||
author["token"], "root", "executor/author", "Recovered actual message reference"
|
||||
)
|
||||
== receipt
|
||||
)
|
||||
with pytest.raises(ValueError, match="Conflicting"):
|
||||
reopened.confirm_dispatch(author["token"], "root", "executor/wrong", "different")
|
||||
assert reopened.status(identity) == before
|
||||
finally:
|
||||
reopened.close()
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Real immutable admission/corpus binding for the agent's TRAIN boundary."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_semantic_admission import (
|
||||
admission as admission_fixture,
|
||||
)
|
||||
from test_semantic_admission import (
|
||||
corpus as corpus_fixture,
|
||||
)
|
||||
from test_semantic_admission import (
|
||||
dataset,
|
||||
decision,
|
||||
release,
|
||||
)
|
||||
from test_semantic_corpus import group, opened, plan, refs
|
||||
from test_semantic_delivery import ds
|
||||
|
||||
admission = admission_fixture
|
||||
corpus = corpus_fixture
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def regions(admission, monkeypatch):
|
||||
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/semantic-learning"))
|
||||
monkeypatch.setitem(__import__("sys").modules, "admission_store", admission)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"agent_binding_regions",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/region_coverage.py",
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.mark.parametrize("split", ["train", "regression"])
|
||||
def test_pinned_physical_split_cannot_be_relabeled(regions, admission, corpus, tmp_path, split):
|
||||
source = dataset(tmp_path, "source")
|
||||
receipt = corpus.build(
|
||||
tmp_path, plan(corpus, [source], [group("physical", split, "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, receipt) as reader:
|
||||
ref = refs(reader, split=split)[0]
|
||||
d = decision(admission, ref)
|
||||
ptr, _ = release(admission, tmp_path, receipt, [ref], [d])
|
||||
with admission.Supervision(tmp_path, ptr["path"], ptr["sha256"]) as reader:
|
||||
e = next(e for b in reader.batches("observed_paint", split) for e in b)
|
||||
v, t = e["inputs"][0], e["targets"][0]
|
||||
protected = bytearray(48)
|
||||
protected[18:21] = bytes([1]) * 3
|
||||
payload = dict(
|
||||
supervision=ptr,
|
||||
sample_id=e["sample_id"],
|
||||
view="top",
|
||||
size=[8, 6],
|
||||
roi=[0, 0, 8, 6],
|
||||
target_sha256=regions.sha(admission.pixel_target(t)),
|
||||
protected_sha256=regions.sha(protected),
|
||||
)
|
||||
files = [
|
||||
tmp_path / ref["dataset"] / v["rgb"]["name"],
|
||||
tmp_path / ref["dataset"] / v["cameras_member"]["name"],
|
||||
reader.root / "supervision.json",
|
||||
reader.root / reader.manifest["records"][e["sample_id"]]["path"],
|
||||
]
|
||||
unit = dict(
|
||||
id="roi",
|
||||
split="train",
|
||||
physical_group="physical",
|
||||
payload=payload,
|
||||
sources=[
|
||||
dict(
|
||||
path=f.relative_to(tmp_path).as_posix(),
|
||||
sha256=ds.checksum(f),
|
||||
bytes=f.stat().st_size,
|
||||
)
|
||||
for f in files
|
||||
],
|
||||
)
|
||||
if split == "regression":
|
||||
with pytest.raises(ValueError, match="physical split"):
|
||||
regions.validate_packet(tmp_path, unit)
|
||||
else:
|
||||
regions.validate_packet(tmp_path, unit)
|
||||
bad = copy.deepcopy(unit)
|
||||
bad["physical_group"] = "wrong street"
|
||||
with pytest.raises(ValueError, match="physical split"):
|
||||
regions.validate_packet(tmp_path, bad)
|
||||
bad = copy.deepcopy(unit)
|
||||
bad["payload"]["protected_sha256"] = regions.sha(b"")
|
||||
with pytest.raises(ValueError, match="protected unknown"):
|
||||
regions.validate_packet(tmp_path, bad)
|
||||
|
||||
|
||||
def test_root_accepted_publication_preserves_labels_and_replays(
|
||||
regions, admission, corpus, tmp_path, monkeypatch
|
||||
):
|
||||
source = dataset(tmp_path, "source")
|
||||
receipt = corpus.build(
|
||||
tmp_path, plan(corpus, [source], [group("physical", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, receipt) as reader:
|
||||
ref = refs(reader)[0]
|
||||
d = decision(admission, ref)
|
||||
ptr, _ = release(admission, tmp_path, receipt, [ref], [d])
|
||||
with admission.Supervision(tmp_path, ptr["path"], ptr["sha256"]) as reader:
|
||||
e = next(e for b in reader.training_batches("observed_paint") for e in b)
|
||||
before = admission.pixel_target(e["targets"][0])
|
||||
protected = bytearray(48)
|
||||
protected[18:21] = bytes([1]) * 3
|
||||
payload = dict(
|
||||
supervision=ptr,
|
||||
sample_id=e["sample_id"],
|
||||
view="top",
|
||||
size=[8, 6],
|
||||
roi=[0, 0, 8, 2],
|
||||
target_sha256=regions.sha(before),
|
||||
protected_sha256=regions.sha(protected),
|
||||
)
|
||||
unit = dict(id="roi", physical_group="physical", split="train", payload=payload)
|
||||
proposal = dict(
|
||||
reason="synthetic stripe",
|
||||
background_reviewed=True,
|
||||
boundary_ignore_px=1,
|
||||
paint_polygons=[[[1, 0], [6, 0], [6, 2], [1, 2]]],
|
||||
unknown_polygons=[],
|
||||
)
|
||||
state = dict(
|
||||
state="root_pending",
|
||||
plan=dict(root_actor="root", units=[unit, dict(unit, id="quarantined")]),
|
||||
root_review=None,
|
||||
tasks=[
|
||||
dict(unit="roi", stage="annotate", result=proposal),
|
||||
dict(unit="quarantined", stage="annotate", result=proposal),
|
||||
],
|
||||
)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"tested_agent_admission",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/agent_admission.py",
|
||||
)
|
||||
pub = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(pub)
|
||||
|
||||
class FakeCycle:
|
||||
def __init__(self, *args):
|
||||
pass
|
||||
|
||||
def status(self, identity):
|
||||
return state
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(pub, "Cycle", FakeCycle)
|
||||
with pytest.raises(ValueError, match="Root acceptance"):
|
||||
pub.publish(tmp_path, "c" * 64, "supervision/agent")
|
||||
state.update(
|
||||
state="closed",
|
||||
root_review=dict(verdict="accepted", admitted_units=["roi"], reason="synthetic test root"),
|
||||
)
|
||||
out = pub.publish(tmp_path, "c" * 64, "supervision/agent")
|
||||
assert pub.publish(tmp_path, "c" * 64, "supervision/agent") == out
|
||||
assert ds.checksum(tmp_path / ptr["path"] / "supervision.json") == ptr["sha256"]
|
||||
with admission.Supervision(tmp_path, out["path"], out["sha256"]) as reader:
|
||||
new = next(e for b in reader.training_batches("observed_paint") for e in b)
|
||||
after = admission.pixel_target(new["targets"][0])
|
||||
assert all(after[i] == value for i, value in enumerate(before) if value != 255)
|
||||
assert after[2:5] == bytes([1, 1, 1])
|
||||
assert after[18:21] == bytes([255, 255, 255])
|
||||
assert all(y < 3 for y, _, _ in new["targets"][0]["unknown"])
|
||||
assert new["physical_group"] == "physical" and new["split"] == "train"
|
||||
|
||||
# A later explicit source uncertainty cannot silently retain baseline paint.
|
||||
proposal["unknown_polygons"] = [[[2, 1], [3, 1], [3, 2], [2, 2]]]
|
||||
proposal["unknown_reason"] = "New source review finds ambiguity"
|
||||
with pytest.raises(ValueError, match="Explicit source uncertainty"):
|
||||
pub.publish(tmp_path, "d" * 64, "supervision/conflicting-uncertainty")
|
||||
assert not (tmp_path / "supervision/conflicting-uncertainty").exists()
|
||||
assert not (tmp_path / "agent-reviews" / ("d" * 64)).exists()
|
||||
@@ -0,0 +1,92 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
from annotation_boundary_review import withdraw_labels
|
||||
|
||||
|
||||
def fixture():
|
||||
target = np.full((8, 9), 255, dtype="uint8")
|
||||
target[1:7, 1:4] = 0
|
||||
target[1:7, 5:8] = 1
|
||||
h = hashlib.sha256(target.tobytes()).hexdigest()
|
||||
sample = dict(
|
||||
name="frame",
|
||||
input=dict(rgb=dict(sha256="raw")),
|
||||
size=[9, 8],
|
||||
target_sha256=h,
|
||||
components=[dict(id="B1", sha256="b"), dict(id="P1", sha256="p")],
|
||||
)
|
||||
review = dict(
|
||||
name="frame",
|
||||
input_sha256="raw",
|
||||
target_sha256=h,
|
||||
raw_first=True,
|
||||
reviewed_components={"B1": "b", "P1": "p"},
|
||||
reason="All regions inspected",
|
||||
withdrawals=[
|
||||
dict(
|
||||
id="edge",
|
||||
label=0,
|
||||
polygon=[[0, 0], [6, 0], [6, 3], [0, 3]],
|
||||
reason="Visible contradictory edge",
|
||||
)
|
||||
],
|
||||
)
|
||||
return sample, review, target
|
||||
|
||||
|
||||
def test_only_explicit_old_class_withdrawn_without_mutating_source():
|
||||
s, r, t = fixture()
|
||||
before = t.copy()
|
||||
got, stats = withdraw_labels(s, r, t)
|
||||
assert np.array_equal(t, before)
|
||||
assert np.all(got[t == 255] == 255) and np.array_equal(got[t == 1], t[t == 1])
|
||||
assert stats["removed_background"] == 9 and stats["removed_paint"] == 0
|
||||
assert np.array_equal(got[4:], t[4:])
|
||||
|
||||
|
||||
def test_foreground_uncertainty_and_overlapping_zones_count_once():
|
||||
s, r, t = fixture()
|
||||
r["withdrawals"][0]["label"] = 1
|
||||
duplicate = copy.deepcopy(r["withdrawals"][0])
|
||||
duplicate["id"] = "overlap"
|
||||
r["withdrawals"].append(duplicate)
|
||||
got, stats = withdraw_labels(s, r, t)
|
||||
assert stats["removed_paint"] == 6 and stats["removed_background"] == 0
|
||||
assert stats["zones"][1]["newly_withdrawn"] == 0
|
||||
assert not np.any((got != t) & (got != 255))
|
||||
|
||||
|
||||
def test_empty_review_preserves_every_pixel():
|
||||
s, r, t = fixture()
|
||||
r["withdrawals"] = []
|
||||
got, stats = withdraw_labels(s, r, t)
|
||||
assert np.array_equal(got, t) and stats["revised_sha256"] == s["target_sha256"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
lambda s, r, t: r.update(input_sha256="other"),
|
||||
lambda s, r, t: r.update(target_sha256="other"),
|
||||
lambda s, r, t: s.update(target_sha256="other"),
|
||||
lambda s, r, t: r.update(reviewed_components={"B1": "b"}),
|
||||
lambda s, r, t: r.update(raw_first=False),
|
||||
lambda s, r, t: r["withdrawals"][0].update(label=255),
|
||||
lambda s, r, t: r["withdrawals"][0].update(reason=""),
|
||||
lambda s, r, t: r["withdrawals"][0].update(polygon=[[0, 0], [9, 0], [0, 3]]),
|
||||
lambda s, r, t: r["withdrawals"][0].update(polygon=[[0, 0], [float("nan"), 0], [0, 3]]),
|
||||
lambda s, r, t: r["withdrawals"][0].update(polygon=[[0, 0], [0, 7], [0, 3]]),
|
||||
],
|
||||
)
|
||||
def test_invalid_or_unbound_review_rejected(change):
|
||||
s, r, t = fixture()
|
||||
change(s, r, t)
|
||||
with pytest.raises(ValueError):
|
||||
withdraw_labels(s, r, t)
|
||||
@@ -0,0 +1,278 @@
|
||||
"""Provenance validates mechanics without changing labels or inventing evidence."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_semantic_admission import admission as admission_fixture
|
||||
from test_semantic_admission import corpus as corpus_fixture
|
||||
from test_semantic_admission import dataset, decision, release
|
||||
from test_semantic_corpus import group, opened, plan, refs
|
||||
|
||||
admission = admission_fixture
|
||||
corpus = corpus_fixture
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parents[1] / "simulation/semantic-learning"))
|
||||
import annotation_provenance as a # noqa: E402
|
||||
import region_coverage as r # noqa: E402
|
||||
|
||||
|
||||
def case():
|
||||
old = bytearray([255]) * 48
|
||||
old[0] = 0 # Outside ROI: earlier known background, not a new review.
|
||||
old[18] = 1 # Inside automatic margin: preserve prior paint.
|
||||
protected = bytearray(48)
|
||||
protected[47] = 1 # Historical protected unknown, subtype unavailable.
|
||||
packet = dict(
|
||||
size=[8, 6],
|
||||
roi=[1, 1, 7, 5],
|
||||
view="top",
|
||||
target_sha256=a.sha(old),
|
||||
protected_sha256=a.sha(protected),
|
||||
)
|
||||
proposal = dict(
|
||||
background_reviewed=True,
|
||||
reason="synthetic complete ROI",
|
||||
boundary_ignore_px=1,
|
||||
paint_polygons=[[[2, 1], [6, 1], [6, 5], [2, 5]]],
|
||||
unknown_polygons=[[[4, 2], [5, 2], [5, 3], [4, 3]]],
|
||||
unknown_reason="synthetic source ambiguity",
|
||||
)
|
||||
record = r.raster_proposal(packet, proposal)
|
||||
merged, stats = r.merge(packet, record, old, protected)
|
||||
return packet, record, old, bytearray(merged), protected, stats
|
||||
|
||||
|
||||
def check(values):
|
||||
p, rec, old, merged, protected, stats = values
|
||||
return a.audit_unit(p, rec, old, merged, protected, merged_sha256=stats["merged_sha256"])
|
||||
|
||||
|
||||
def test_exact_partition_old_known_survives_and_outside_is_not_reviewed():
|
||||
values = case()
|
||||
snapshots = copy.deepcopy(values)
|
||||
proof = check(values)
|
||||
assert values == snapshots
|
||||
assert proof["source_subtypes_known"] is True
|
||||
assert proof["reviewed_pixels"] == 24
|
||||
assert proof["categories"]["source_unknown"]["pixels"] == 1
|
||||
assert proof["categories"]["source_unknown"]["remaining_unknown"] == 1
|
||||
margin = proof["categories"]["automatic_margin"]
|
||||
assert margin["retained_old_paint"] == 1
|
||||
assert margin["remaining_unknown"] == margin["pixels"] - 1
|
||||
assert proof["prior_protected_untyped"] == dict(
|
||||
pixels=1, inside_roi=0, outside_roi=1, remaining_unknown=1
|
||||
)
|
||||
assert proof["outside_roi"] == dict(
|
||||
pixels=24, prior_known=1, prior_protected_untyped=1, unassigned_unknown=22
|
||||
)
|
||||
assert proof["merged_sha256"] == a.sha(values[3])
|
||||
|
||||
|
||||
def test_legacy_record_does_not_invent_source_or_margin_subtypes():
|
||||
values = case()
|
||||
del values[1]["source_unknown"]
|
||||
proof = check(values)
|
||||
assert proof["source_subtypes_known"] is False
|
||||
assert proof["categories"]["source_unknown"]["pixels"] == 0
|
||||
assert proof["categories"]["automatic_margin"]["pixels"] == 0
|
||||
assert proof["categories"]["untyped_unknown"]["pixels"] > 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("known", [0, 1])
|
||||
def test_source_unknown_cannot_retain_prior_known(known):
|
||||
p, rec, old, merged, protected, stats = case()
|
||||
old[20] = merged[20] = known
|
||||
p["target_sha256"] = a.sha(old)
|
||||
stats["merged_sha256"] = a.sha(merged)
|
||||
with pytest.raises(ValueError, match="Source unknown conflicts"):
|
||||
check((p, rec, old, merged, protected, stats))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
"target_sha",
|
||||
"merged_sha",
|
||||
"protected_sha",
|
||||
"outside",
|
||||
"old_known",
|
||||
"source_known",
|
||||
"missing",
|
||||
"overlap",
|
||||
"source_overlap",
|
||||
"source_outside",
|
||||
"view",
|
||||
"protected_change",
|
||||
],
|
||||
)
|
||||
def test_tamper_and_false_coverage_fail_closed(change):
|
||||
p, rec, old, merged, protected, stats = case()
|
||||
if change == "target_sha":
|
||||
p["target_sha256"] = "0" * 64
|
||||
elif change == "merged_sha":
|
||||
stats["merged_sha256"] = "0" * 64
|
||||
elif change == "protected_sha":
|
||||
p["protected_sha256"] = "0" * 64
|
||||
elif change == "outside":
|
||||
merged[1] = 0
|
||||
elif change == "old_known":
|
||||
merged[18] = 255
|
||||
elif change == "source_known":
|
||||
merged[20] = 0
|
||||
elif change == "missing":
|
||||
rec["unknown"].pop()
|
||||
elif change == "overlap":
|
||||
rec["paint"] += [rec["paint"][0]]
|
||||
rec["paint"].sort()
|
||||
elif change == "source_overlap":
|
||||
rec["source_unknown"] *= 2
|
||||
elif change == "source_outside":
|
||||
rec["source_unknown"] = [[0, 1, 2]]
|
||||
elif change == "view":
|
||||
rec["view"] = "other"
|
||||
elif change == "protected_change":
|
||||
merged[47] = 0
|
||||
if change in {"outside", "old_known", "source_known", "protected_change"}:
|
||||
stats["merged_sha256"] = a.sha(merged) # Valid checksum cannot hide invalid semantics.
|
||||
with pytest.raises(ValueError):
|
||||
check((p, rec, old, merged, protected, stats))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def publication(admission, corpus, tmp_path, monkeypatch):
|
||||
source = dataset(tmp_path, "source")
|
||||
receipt = corpus.build(
|
||||
tmp_path, plan(corpus, [source], [group("physical", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, receipt) as reader:
|
||||
ref = refs(reader)[0]
|
||||
ptr, _ = release(admission, tmp_path, receipt, [ref], [decision(admission, ref)])
|
||||
with admission.Supervision(tmp_path, ptr["path"], ptr["sha256"]) as reader:
|
||||
entry = next(e for b in reader.training_batches("observed_paint") for e in b)
|
||||
target = entry["targets"][0]
|
||||
original = admission.pixel_target(target)
|
||||
protected = bytearray(len(original))
|
||||
for y, start, end in target["unknown"]:
|
||||
protected[y * 8 + start : y * 8 + end] = bytes([1]) * (end - start)
|
||||
payload = dict(
|
||||
supervision=ptr,
|
||||
sample_id=entry["sample_id"],
|
||||
view="top",
|
||||
size=[8, 6],
|
||||
roi=[0, 0, 8, 2],
|
||||
target_sha256=a.sha(original),
|
||||
protected_sha256=a.sha(protected),
|
||||
)
|
||||
unit = dict(id="roi", physical_group="physical", split="train", payload=payload)
|
||||
proposal = dict(
|
||||
reason="reviewed synthetic stripe",
|
||||
background_reviewed=True,
|
||||
boundary_ignore_px=1,
|
||||
paint_polygons=[[[1, 0], [6, 0], [6, 2], [1, 2]]],
|
||||
unknown_polygons=[],
|
||||
)
|
||||
state = dict(
|
||||
state="closed",
|
||||
plan=dict(root_actor="root", units=[unit]),
|
||||
root_review=dict(verdict="accepted", admitted_units=["roi"]),
|
||||
tasks=[dict(unit="roi", stage="annotate", result=proposal)],
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, "admission_store", admission)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"provenance_publish_test",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/agent_admission.py",
|
||||
)
|
||||
pub = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(pub)
|
||||
|
||||
class FakeCycle:
|
||||
def __init__(self, *args):
|
||||
pass
|
||||
|
||||
def status(self, identity):
|
||||
return state
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(pub, "Cycle", FakeCycle)
|
||||
identity = "c" * 64
|
||||
result = pub.publish(tmp_path, identity, "supervision/published")
|
||||
return pub, result, tmp_path / "agent-reviews" / identity, identity
|
||||
|
||||
|
||||
@pytest.mark.parametrize("corrupt_legacy", [False, True])
|
||||
def test_real_publication_legacy_retry_preserves_every_existing_byte(
|
||||
publication, tmp_path, corrupt_legacy
|
||||
):
|
||||
pub, expected, journal, identity = publication
|
||||
path = journal / "audit.json"
|
||||
current = json.loads(path.read_bytes())
|
||||
assert "provenance" in current["units"][0] # New publication includes proof.
|
||||
legacy = copy.deepcopy(current)
|
||||
for unit in legacy["units"]:
|
||||
del unit["provenance"]
|
||||
if corrupt_legacy:
|
||||
legacy["units"][0]["coverage"]["paint"] += 1
|
||||
# Model an actual historical audit, including different insignificant whitespace.
|
||||
path.write_text(json.dumps(legacy, indent=4) + "\n")
|
||||
saved = {
|
||||
p: p.read_bytes()
|
||||
for directory in (journal, tmp_path / "supervision/published")
|
||||
for p in directory.rglob("*")
|
||||
if p.is_file()
|
||||
}
|
||||
sidecar = journal / "audit-provenance-v1.json"
|
||||
if corrupt_legacy:
|
||||
with pytest.raises(ValueError, match="legacy audit differs"):
|
||||
pub.publish(tmp_path, identity, "supervision/published")
|
||||
assert not sidecar.exists()
|
||||
else:
|
||||
assert pub.publish(tmp_path, identity, "supervision/published") == expected
|
||||
proof = json.loads(sidecar.read_bytes())
|
||||
assert proof["legacy_audit_sha256"] == a.sha(saved[path])
|
||||
assert proof["audit"] == current
|
||||
exact_sidecar = sidecar.read_bytes()
|
||||
assert pub.publish(tmp_path, identity, "supervision/published") == expected
|
||||
assert sidecar.read_bytes() == exact_sidecar
|
||||
# Existing sidecar is immutable too; even an otherwise valid legacy retry fails.
|
||||
sidecar.write_text("{}\n")
|
||||
with pytest.raises(ValueError, match="Published evidence changed"):
|
||||
pub.publish(tmp_path, identity, "supervision/published")
|
||||
assert sidecar.read_text() == "{}\n"
|
||||
assert all(p.read_bytes() == before for p, before in saved.items())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["changed_to_current", "missing_audit"])
|
||||
def test_existing_sidecar_blocks_audit_replacement_or_removal(publication, tmp_path, change):
|
||||
pub, expected, journal, identity = publication
|
||||
path = journal / "audit.json"
|
||||
current_bytes = path.read_bytes()
|
||||
legacy = json.loads(current_bytes)
|
||||
for unit in legacy["units"]:
|
||||
del unit["provenance"]
|
||||
path.write_text(json.dumps(legacy, indent=4) + "\n")
|
||||
assert pub.publish(tmp_path, identity, "supervision/published") == expected
|
||||
sidecar = journal / "audit-provenance-v1.json"
|
||||
sidecar_bytes = sidecar.read_bytes()
|
||||
release_bytes = {
|
||||
p: p.read_bytes() for p in (tmp_path / "supervision/published").rglob("*") if p.is_file()
|
||||
}
|
||||
if change == "changed_to_current":
|
||||
path.write_bytes(current_bytes)
|
||||
else:
|
||||
path.unlink()
|
||||
with pytest.raises(
|
||||
ValueError, match="Published evidence changed|requires its original legacy audit"
|
||||
):
|
||||
pub.publish(tmp_path, identity, "supervision/published")
|
||||
assert sidecar.read_bytes() == sidecar_bytes
|
||||
assert all(p.read_bytes() == value for p, value in release_bytes.items())
|
||||
if change == "changed_to_current":
|
||||
assert path.read_bytes() == current_bytes
|
||||
else:
|
||||
assert not path.exists() # A rejected retry must not recreate audit.json.
|
||||
@@ -0,0 +1,79 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"annotation_training_view",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/annotation_training_view.py",
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
training_view = module.training_view
|
||||
|
||||
|
||||
def example():
|
||||
t = np.array([[1, 1, 0, 255], [1, 0, 1, 255]], dtype="uint8")
|
||||
b = t.copy()
|
||||
b[1, 2] = 255
|
||||
added = (b == 255) & (t == 1)
|
||||
weak = added.copy()
|
||||
weak[0, 1] = True
|
||||
return dict(
|
||||
split="train", target=t, base_target=b, added=added, weak=weak, clear=(t == 1) & ~weak
|
||||
)
|
||||
|
||||
|
||||
def test_withdrawal_updates_both_targets_and_conditions_without_mutation():
|
||||
r = example()
|
||||
t = r["target"].copy()
|
||||
t[0, 0] = t[0, 2] = 255
|
||||
n = training_view(r, t)
|
||||
assert n["target"][0, 0] == n["base_target"][0, 0] == 255
|
||||
assert n["target"][0, 2] == n["base_target"][0, 2] == 255
|
||||
assert not n["clear"][0, 0]
|
||||
assert r["clear"][0, 0] and r["target"][0, 0] == 1
|
||||
assert np.array_equal(n["weak"], r["weak"])
|
||||
n["target"][1, 0] = 255
|
||||
assert t[1, 0] == r["target"][1, 0] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("split", ["regression", "test", "validation"])
|
||||
def test_forbid_nontraining(split):
|
||||
r = example()
|
||||
r["split"] = split
|
||||
with pytest.raises(ValueError):
|
||||
training_view(r, r["target"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"where,value",
|
||||
[((0, 0), 0), ((0, 2), 1), ((0, 3), 0), ((0, 3), 1), ((0, 1), 255), ((1, 2), 255)],
|
||||
)
|
||||
def test_forbid_class_flips_new_labels_or_loss_of_weak_support(where, value):
|
||||
r = example()
|
||||
t = r["target"].copy()
|
||||
t[where] = value
|
||||
with pytest.raises(ValueError):
|
||||
training_view(r, t)
|
||||
|
||||
|
||||
def test_invalid_parent_and_condition():
|
||||
r = example()
|
||||
r["base_target"][0, 0] = 0
|
||||
with pytest.raises(ValueError):
|
||||
training_view(r, r["target"])
|
||||
r = example()
|
||||
r["clear"][0, 2] = True
|
||||
with pytest.raises(ValueError):
|
||||
training_view(r, r["target"])
|
||||
|
||||
|
||||
def test_identity_and_wrong_shape():
|
||||
r = example()
|
||||
n = training_view(r, r["target"])
|
||||
for key in ["target", "base_target", "weak", "clear", "added"]:
|
||||
assert np.array_equal(n[key], r[key])
|
||||
with pytest.raises(ValueError):
|
||||
training_view(r, r["target"][:, :2])
|
||||
@@ -0,0 +1,156 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
from background_admission import add_background, prepare_background
|
||||
from coverage_mass_control import prepare, schedule_digest
|
||||
|
||||
|
||||
def review_case():
|
||||
t = np.full((64, 64), 255, dtype="uint8")
|
||||
t[:5] = 1
|
||||
t[55:] = 0
|
||||
protected = np.zeros(t.shape, dtype=bool)
|
||||
protected[25:28, 25:28] = True
|
||||
s = dict(
|
||||
name="sample",
|
||||
split="train",
|
||||
size=[64, 64],
|
||||
rgb_sha256="a" * 64,
|
||||
target_sha256=hashlib.sha256(t.tobytes()).hexdigest(),
|
||||
protected_sha256=hashlib.sha256(protected.tobytes()).hexdigest(),
|
||||
)
|
||||
review = dict(
|
||||
s,
|
||||
boundary_ignore_px=2,
|
||||
regions=[
|
||||
dict(
|
||||
id="inside",
|
||||
reason="Visible non-paint interior",
|
||||
polygon=[[128, 128], [384, 128], [384, 384], [128, 384]],
|
||||
)
|
||||
],
|
||||
)
|
||||
return s, review, t, protected
|
||||
|
||||
|
||||
def test_background_admission_preserves_known_and_protected_pixels():
|
||||
s, r, t, p = review_case()
|
||||
before = t.copy()
|
||||
out, added, audit = add_background(s, r, t, p)
|
||||
assert added.any() and not added[p].any()
|
||||
assert np.all(out[p] == 255)
|
||||
assert np.array_equal(out[t != 255], t[t != 255])
|
||||
assert np.array_equal(out == 1, t == 1)
|
||||
assert not added[16, 16] and added[20, 20]
|
||||
assert audit[0]["protected_excluded"] == 9
|
||||
assert np.array_equal(t, before)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad", ["split", "image", "target", "protected", "margin", "paint", "overlap", "polygon"]
|
||||
)
|
||||
def test_invalid_or_conflicting_admission_is_rejected(bad):
|
||||
s, r, t, p = review_case()
|
||||
if bad == "split":
|
||||
s["split"] = "regression"
|
||||
if bad == "image":
|
||||
r["rgb_sha256"] = "b" * 64
|
||||
if bad == "target":
|
||||
t[10, 10] = 0
|
||||
if bad == "protected":
|
||||
p[30, 30] = True
|
||||
if bad == "margin":
|
||||
r["boundary_ignore_px"] = 0
|
||||
if bad == "paint":
|
||||
r["regions"][0]["polygon"] = [[0, 0], [512, 0], [512, 512], [0, 512]]
|
||||
if bad == "overlap":
|
||||
r["regions"].append(dict(r["regions"][0], id="second"))
|
||||
if bad == "polygon":
|
||||
r["regions"][0]["polygon"][0] = [-1, 0]
|
||||
with pytest.raises(ValueError):
|
||||
add_background(s, r, t, p)
|
||||
|
||||
|
||||
def records():
|
||||
out = []
|
||||
for j in range(2):
|
||||
t = np.array([[1, 1, 0, 255], [1, 0, 255, 255]], dtype="uint8")
|
||||
b = t.copy()
|
||||
b[0, 1] = 255
|
||||
added = np.zeros(t.shape, dtype=bool)
|
||||
added[1, 2:] = True
|
||||
out.append(
|
||||
dict(
|
||||
name=str(j),
|
||||
sample_id=str(j),
|
||||
group=str(j),
|
||||
split="train",
|
||||
target=t,
|
||||
base_target=b,
|
||||
added_background=added,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy", ["base", "mass", "equal_window"])
|
||||
def test_negative_mass_conserved_positive_weights_exact_and_order_unchanged(policy):
|
||||
original = records()
|
||||
before = copy.deepcopy(original)
|
||||
rr, weights = prepare(original, policy)
|
||||
out, ww = prepare_background(rr, weights)
|
||||
assert schedule_digest(rr, 7, 120) == schedule_digest(out, 7, 120)
|
||||
for old, new in zip(rr, out, strict=True):
|
||||
n = old["name"]
|
||||
paint = old["target"] == 1
|
||||
bg = old["target"] == 0
|
||||
added = old["added_background"]
|
||||
assert np.array_equal(ww[n][paint], weights[n][paint])
|
||||
assert float(ww[n][new["target"] == 0].sum()) == pytest.approx(float(weights[n][bg].sum()))
|
||||
np.testing.assert_allclose(ww[n][bg], weights[n][bg] * 0.5)
|
||||
assert np.all(new["target"][added] == 0) and not ww[n][new["target"] == 255].any()
|
||||
assert all(
|
||||
np.array_equal(x["target"], y["target"]) for x, y in zip(original, before, strict=True)
|
||||
)
|
||||
|
||||
|
||||
def test_zero_add_is_exact_identity_including_empty_window():
|
||||
rr = records()
|
||||
for r in rr:
|
||||
r["added_background"][:] = False
|
||||
rr[1]["target"][:] = 255
|
||||
rr[1]["base_target"][:] = 255
|
||||
prepared, w = prepare(rr, "base")
|
||||
out, ww = prepare_background(prepared, w)
|
||||
for a, b in zip(prepared, out, strict=True):
|
||||
assert np.array_equal(a["target"], b["target"])
|
||||
assert np.array_equal(w[a["name"]], ww[a["name"]])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad", ["split", "known", "negative", "nan", "unknown_weight", "empty_bg", "duplicate"]
|
||||
)
|
||||
def test_invalid_background_weight_inputs_rejected(bad):
|
||||
rr, w = prepare(records(), "mass")
|
||||
if bad == "split":
|
||||
rr[0]["split"] = "test"
|
||||
if bad == "known":
|
||||
rr[0]["added_background"][0, 0] = True
|
||||
if bad == "negative":
|
||||
w["0"][0, 0] = -1
|
||||
if bad == "nan":
|
||||
w["0"][0, 0] = np.nan
|
||||
if bad == "unknown_weight":
|
||||
w["0"][1, 2] = 1
|
||||
if bad == "empty_bg":
|
||||
w["0"][rr[0]["target"] == 0] = 0
|
||||
if bad == "duplicate":
|
||||
rr.append(rr[0])
|
||||
with pytest.raises(ValueError):
|
||||
prepare_background(rr, w)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Numerical and fitting safeguards for the Worker-only ranking probe."""
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
if importlib.util.find_spec("cv2") is None:
|
||||
raise unittest.SkipTest("Scientific probe checks run in the pinned Worker renderer image")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "simulation/semantic-learning"))
|
||||
sys.path.insert(0, str(ROOT / "simulation/urban-plan-research/pipeline/base"))
|
||||
|
||||
PhysicalFields = importlib.import_module("boundary_anchors").PhysicalFields
|
||||
probe = importlib.import_module("boundary_rank_probe")
|
||||
components, describe, fit, PRIOR = probe.components, probe.describe, probe.fit, probe.PRIOR
|
||||
|
||||
|
||||
class ProbeTests(unittest.TestCase):
|
||||
def fields(self):
|
||||
rgb = np.zeros((128, 128, 3), np.uint8)
|
||||
rgb[:, 64:] = 160
|
||||
z = np.zeros((128, 128), np.float32)
|
||||
z[:, 64:] = 0.12
|
||||
one = np.ones(z.shape, np.float32)
|
||||
zero = np.zeros_like(one)
|
||||
return PhysicalFields(rgb, z, one, zero, zero, zero, 0.05)
|
||||
|
||||
def test_reference_score_preserved_exactly(self):
|
||||
f = self.fields()
|
||||
uv = np.array([[63.0, 40.0], [64.0, 60.0], [67.0, 90.0]])
|
||||
before = [a.copy() for a in (f.gray, f.z, f.alpha)]
|
||||
expected, mask = f.measure(uv, [1, 0])
|
||||
terms, got = components(f, uv, [1, 0])
|
||||
np.testing.assert_array_equal(got, expected * mask)
|
||||
np.testing.assert_allclose(terms @ PRIOR, got, atol=1e-7, rtol=1e-6)
|
||||
for a, b in zip(before, (f.gray, f.z, f.alpha), strict=True):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
|
||||
def test_missing_evidence_cannot_gain_score(self):
|
||||
f = self.fields()
|
||||
f.alpha[:] = 0
|
||||
terms, score = components(f, np.array([[64.0, 64.0]]), [1, 0])
|
||||
self.assertFalse(terms.any())
|
||||
self.assertFalse(score.any())
|
||||
|
||||
def test_reverse_geometry_same_measurement(self):
|
||||
f = self.fields()
|
||||
path = np.array([[64.0, 25.0], [64.0, 95.0]])
|
||||
a, sa = describe(f, path, [10, 10, 110, 110], [1, 0])
|
||||
b, sb = describe(f, path[::-1], [10, 10, 110, 110], [1, 0])
|
||||
np.testing.assert_allclose(a, b, atol=1e-7)
|
||||
self.assertAlmostEqual(sa, sb, places=7)
|
||||
|
||||
def test_pair_fit_is_bounded_and_deterministic(self):
|
||||
d = np.array([[0.3, 0, -0.1, 0], [0.2, 0.1, 0, 0], [0.1, 0, 0, 0.1]])
|
||||
a = fit(d)
|
||||
b = fit(d)
|
||||
np.testing.assert_array_equal(a, b)
|
||||
self.assertTrue(((a >= 0) & (a <= 2)).all())
|
||||
self.assertGreater(a[0], PRIOR[0])
|
||||
|
||||
def test_invalid_pairs_fail_closed(self):
|
||||
for d in [[], [[1, 2, 3, 4]], [[float("nan")] * 4] * 2]:
|
||||
with self.assertRaises(ValueError):
|
||||
fit(d)
|
||||
|
||||
def test_outside_review_has_no_target(self):
|
||||
with self.assertRaises(ValueError):
|
||||
describe(
|
||||
self.fields(),
|
||||
np.array([[1.0, 1.0], [5.0, 5.0]]),
|
||||
[30, 30, 90, 90],
|
||||
[1, 0],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,174 @@
|
||||
import copy
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "simulation" / "semantic-learning"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
spec = importlib.util.spec_from_file_location("boundary_review", ROOT / "boundary_review.py")
|
||||
review = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(review)
|
||||
|
||||
|
||||
def fixture():
|
||||
feature = dict(
|
||||
id="curb",
|
||||
properties={"class": "road_boundary"},
|
||||
geometry=dict(type="LineString", coordinates=[[0.0, 0.0, 1.0], [10.0, 0.0, 1.0]]),
|
||||
)
|
||||
old = copy.deepcopy(feature)
|
||||
old["geometry"]["coordinates"][0][1] = 2.0
|
||||
labels = dict(
|
||||
proposed_element=[feature],
|
||||
original_element=[old],
|
||||
projections=dict(
|
||||
top=[dict(feature_id="curb", uv=[[-10.0, 40.0], [110.0, 40.0]], in_front=[True, True])]
|
||||
),
|
||||
)
|
||||
cameras = dict(views=[dict(id="top", projection="ortho", size=[100, 100])])
|
||||
decision = dict(
|
||||
id="one",
|
||||
sample="part-000/tile-0/sample.json",
|
||||
feature_id="curb",
|
||||
view="top",
|
||||
rect_px=[20, 30, 80, 50],
|
||||
evidence="visible",
|
||||
reviewer="assistant-visual-review",
|
||||
reason="Edited contour follows visible curb; original cuts pavement.",
|
||||
preference="edited-better-than-original",
|
||||
)
|
||||
return labels, cameras, decision
|
||||
|
||||
|
||||
def test_exact_ranges_and_no_implicit_background():
|
||||
labels, cameras, decision = fixture()
|
||||
before = copy.deepcopy(labels)
|
||||
result = review.compile_record(labels, cameras, decision)
|
||||
assert result["segment_ranges"] == [dict(segment=0, t=[0.25, 0.75])]
|
||||
assert labels == before
|
||||
assert result["ranking_trial_eligible"]
|
||||
assert not result["dense_segmentation_eligible"]
|
||||
assert not result["metric_ground_truth"]
|
||||
assert result["background_targets"] == result["complete_regions"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("evidence", ["context", "uncertain"])
|
||||
def test_inferred_or_uncertain_cannot_enter_ranking(evidence):
|
||||
labels, cameras, decision = fixture()
|
||||
decision["evidence"] = evidence
|
||||
with pytest.raises(ValueError, match="visible evidence"):
|
||||
review.compile_record(labels, cameras, decision)
|
||||
decision.pop("preference")
|
||||
assert not review.compile_record(labels, cameras, decision)["ranking_trial_eligible"]
|
||||
|
||||
|
||||
def test_editor_accepted_does_not_admit_training():
|
||||
labels, cameras, decision = fixture()
|
||||
labels["proposed_element"][0]["properties"]["review_status"] = "accepted"
|
||||
decision.pop("preference")
|
||||
assert not review.compile_record(labels, cameras, decision)["ranking_trial_eligible"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["rejected", "marking", "nan", "empty", "perspective", "same"])
|
||||
def test_invalid_target_fails_closed(change):
|
||||
labels, cameras, decision = fixture()
|
||||
if change == "rejected":
|
||||
labels["proposed_element"][0]["properties"]["review_status"] = "rejected"
|
||||
elif change == "marking":
|
||||
labels["proposed_element"][0]["properties"]["class"] = "road_marking"
|
||||
elif change == "nan":
|
||||
labels["projections"]["top"][0]["uv"][0][0] = float("nan")
|
||||
elif change == "empty":
|
||||
decision["rect_px"] = [20, 60, 80, 90]
|
||||
elif change == "perspective":
|
||||
cameras["views"][0]["projection"] = "pinhole"
|
||||
else:
|
||||
labels["original_element"] = copy.deepcopy(labels["proposed_element"])
|
||||
with pytest.raises(ValueError):
|
||||
review.compile_record(labels, cameras, decision)
|
||||
|
||||
|
||||
def test_control_scene_cannot_leak_into_training():
|
||||
control = dict(
|
||||
schema_version="missioncore.boundary-control/v1",
|
||||
role="held-out-scene",
|
||||
world_sha256="a" * 64,
|
||||
model_sha256="b" * 64,
|
||||
training_eligible=False,
|
||||
windows=[dict(center=[0, 0, 0])],
|
||||
frozen_utc="2026-10-21T00:00:00Z",
|
||||
)
|
||||
review.check_control(control, "c" * 64)
|
||||
with pytest.raises(ValueError, match="distinct frozen"):
|
||||
review.check_control(control, "a" * 64)
|
||||
|
||||
|
||||
def test_clipping_is_direction_invariant():
|
||||
assert review.clipped_range([-10, 40], [110, 40], [20, 30, 80, 50]) == [0.25, 0.75]
|
||||
assert review.clipped_range([110, 40], [-10, 40], [20, 30, 80, 50]) == [0.25, 0.75]
|
||||
assert review.clipped_range([40, -10], [40, 110], [30, 20, 50, 80]) == [0.25, 0.75]
|
||||
|
||||
|
||||
def make_pack(root):
|
||||
labels, cameras, decision = fixture()
|
||||
folder = root / "observations/part-000/tile-0"
|
||||
folder.mkdir(parents=True)
|
||||
review.write(folder / "labels.json", labels)
|
||||
review.write(folder / "cameras.json", cameras)
|
||||
review.write(root / "decisions.json", {"records": [decision]})
|
||||
review.write(root / "records.json", [review.compile_record(labels, cameras, decision)])
|
||||
review.write(
|
||||
root / "control.json",
|
||||
dict(
|
||||
schema_version="missioncore.boundary-control/v1",
|
||||
role="held-out-scene",
|
||||
world_sha256="a" * 64,
|
||||
model_sha256="b" * 64,
|
||||
training_eligible=False,
|
||||
windows=[{"center": [0, 0, 0]}],
|
||||
frozen_utc="2026-10-21T00:00:00Z",
|
||||
),
|
||||
)
|
||||
review.write(
|
||||
root / "pack.json",
|
||||
dict(
|
||||
schema_version=review.SCHEMA,
|
||||
source={"world_sha256": "c" * 64},
|
||||
files={
|
||||
p.relative_to(root).as_posix(): dict(
|
||||
sha256=review.checksum(p), bytes=p.stat().st_size
|
||||
)
|
||||
for p in root.rglob("*")
|
||||
if p.is_file()
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_pack_is_portable_and_detects_changed_observation(tmp_path):
|
||||
root = tmp_path / "source"
|
||||
make_pack(root)
|
||||
before = review.verify_pack(root)
|
||||
moved = tmp_path / "elsewhere"
|
||||
root.rename(moved)
|
||||
assert review.verify_pack(moved) == before
|
||||
(moved / "observations/part-000/tile-0/cameras.json").write_text("{}")
|
||||
with pytest.raises(ValueError, match="Pack member changed"):
|
||||
review.verify_pack(moved)
|
||||
|
||||
|
||||
def test_pack_recomputes_admission_instead_of_trusting_exported_flags(tmp_path):
|
||||
make_pack(tmp_path)
|
||||
records = review.read(tmp_path / "records.json")
|
||||
records[0]["dense_segmentation_eligible"] = True
|
||||
review.write(tmp_path / "records.json", records)
|
||||
manifest = review.read(tmp_path / "pack.json")
|
||||
manifest["files"]["records.json"] = dict(
|
||||
sha256=review.checksum(tmp_path / "records.json"),
|
||||
bytes=(tmp_path / "records.json").stat().st_size,
|
||||
)
|
||||
review.write(tmp_path / "pack.json", manifest)
|
||||
with pytest.raises(ValueError, match="Admission differs"):
|
||||
review.verify_pack(tmp_path)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Finite-group pooling, coordinate alignment and invalid input checks."""
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
np = pytest.importorskip("numpy")
|
||||
for dependency in ["cv2", "scipy", "shapely"]:
|
||||
pytest.importorskip(dependency)
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
study = importlib.import_module("c4_admission_study")
|
||||
|
||||
|
||||
def test_uniform_pool_is_cyclically_invariant_without_best_angle():
|
||||
orbit = np.random.default_rng(61).normal(size=(4, 8, 512)).astype(np.float32)
|
||||
mean = study.c4_mean(orbit)
|
||||
for k in range(4):
|
||||
assert np.array_equal(mean, study.c4_mean(np.roll(orbit, k, axis=0)))
|
||||
assert np.allclose(mean, orbit.astype(np.float64).sum(0) / 4)
|
||||
assert not np.array_equal(mean, orbit.max(0))
|
||||
|
||||
|
||||
def test_mask_field_alignment_commutes_with_quarter_turns():
|
||||
mask = np.zeros((512, 512), bool)
|
||||
mask[51:211, 91:93] = True
|
||||
mask[101:122, 50:211] = True
|
||||
field = np.random.default_rng(19).normal(size=(128, 128)).astype(np.float32)
|
||||
original = np.sum(study.fractional_weights(mask, (128, 128)) * field)
|
||||
for k in range(4):
|
||||
rotated = np.sum(
|
||||
study.fractional_weights(np.rot90(mask, k), (128, 128)) * np.rot90(field, k)
|
||||
)
|
||||
assert rotated == pytest.approx(original, abs=1e-7)
|
||||
restored = np.rot90(np.rot90(field, k), -k)
|
||||
assert np.array_equal(restored, field)
|
||||
|
||||
|
||||
def test_partial_or_nonfinite_orbit_refused():
|
||||
with pytest.raises(ValueError):
|
||||
study.c4_mean(np.zeros((3, 1, 512)))
|
||||
with pytest.raises(ValueError):
|
||||
study.c4_mean(np.full((4, 1, 512), np.nan))
|
||||
assert study.c4_mean(np.empty((4, 0, 512))).shape == (0, 512)
|
||||
@@ -0,0 +1,111 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"context_background",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/context_background.py",
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def fixtures():
|
||||
rr = [
|
||||
dict(name="a", split="train", group="g", target=np.array([[1, 255]], np.uint8)),
|
||||
dict(name="b", split="train", group="g", target=np.array([[0, 255]], np.uint8)),
|
||||
dict(name="c", split="train", group="h", target=np.array([[0, 1]], np.uint8)),
|
||||
]
|
||||
w = {
|
||||
"a": np.array([[0.25, 0]], np.float32),
|
||||
"b": np.array([[0.3, 0]], np.float32),
|
||||
"c": np.array([[0.2, 0.25]], np.float32),
|
||||
}
|
||||
a = {r["name"]: np.zeros((1, 2), bool) for r in rr}
|
||||
return rr, w, a
|
||||
|
||||
|
||||
def test_positive_only_window_receives_shared_negative_mass():
|
||||
rr, w, a = fixtures()
|
||||
a["a"][0, 1] = True
|
||||
out, ww = m.prepare_context(rr, w, a)
|
||||
assert out[0]["target"].tolist() == [[1, 0]]
|
||||
np.testing.assert_array_equal(ww["a"], np.array([[0.25, 0.15]], np.float32))
|
||||
np.testing.assert_array_equal(ww["b"], np.array([[0.15, 0]], np.float32))
|
||||
np.testing.assert_array_equal(ww["c"], w["c"])
|
||||
assert rr[0]["target"][0, 1] == 255 and w["a"][0, 1] == 0
|
||||
|
||||
|
||||
def test_empty_additions_are_bit_exact():
|
||||
rr, w, a = fixtures()
|
||||
out, ww = m.prepare_context(rr, w, a)
|
||||
for b, n in zip(rr, out, strict=True):
|
||||
np.testing.assert_array_equal(n["target"], b["target"])
|
||||
np.testing.assert_array_equal(ww[b["name"]], w[b["name"]])
|
||||
|
||||
|
||||
def test_redistribute_known_background_without_new_window():
|
||||
rr, w, a = fixtures()
|
||||
a["b"][0, 1] = True
|
||||
out, ww = m.prepare_context(rr, w, a)
|
||||
np.testing.assert_array_equal(ww["b"], np.array([[0.15, 0.15]], np.float32))
|
||||
np.testing.assert_array_equal(ww["a"], w["a"])
|
||||
assert out[0]["target"][0, 1] == 255
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[
|
||||
"paint",
|
||||
"existing_bg",
|
||||
"test",
|
||||
"negative",
|
||||
"unknown_weight",
|
||||
"nan",
|
||||
"missing",
|
||||
"zero_street_mass",
|
||||
],
|
||||
)
|
||||
def test_reject_invalid_admission(failure):
|
||||
rr, w, a = fixtures()
|
||||
if failure == "paint":
|
||||
a["a"][0, 0] = True
|
||||
if failure == "existing_bg":
|
||||
a["b"][0, 0] = True
|
||||
if failure == "test":
|
||||
rr[0]["split"] = "test"
|
||||
if failure == "negative":
|
||||
w["b"][0, 0] = -1
|
||||
if failure == "unknown_weight":
|
||||
w["a"][0, 1] = 0.1
|
||||
if failure == "nan":
|
||||
w["a"][0, 0] = np.nan
|
||||
if failure == "missing":
|
||||
a.pop("b")
|
||||
if failure == "zero_street_mass":
|
||||
w["b"][0, 0] = 0
|
||||
a["a"][0, 1] = True
|
||||
with pytest.raises(ValueError):
|
||||
m.prepare_context(rr, w, a)
|
||||
|
||||
|
||||
def test_gate_rejects_paint_regression_despite_better_background():
|
||||
context_gate = m.context_gate
|
||||
|
||||
old = dict(
|
||||
context_fp=100,
|
||||
bce=1.0,
|
||||
original_fp=3,
|
||||
prior_added_fp=2,
|
||||
weak_fn=0,
|
||||
clear_fn=0,
|
||||
background_fp=105,
|
||||
)
|
||||
new = dict(old, context_fp=20, bce=0.2, background_fp=25)
|
||||
assert context_gate(old, new, old)["passed"]
|
||||
assert not context_gate(old, dict(new, weak_fn=1), old)["passed"]
|
||||
assert not context_gate(old, dict(new, original_fp=4), old)["passed"]
|
||||
assert not context_gate(old, dict(new, context_fp=51), old)["passed"]
|
||||
assert not context_gate(old, dict(new, bce=1.0), old)["passed"]
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Coverage experiments must not turn unknown into background or fit controls."""
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
np = pytest.importorskip("numpy")
|
||||
for dependency in ["cv2", "scipy", "shapely"]:
|
||||
pytest.importorskip(dependency)
|
||||
from shapely.geometry import box, mapping # noqa: E402
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
study = importlib.import_module("coverage_admission_study")
|
||||
|
||||
|
||||
def test_background_is_explicit_unknown_stays_unknown_and_paint_wins():
|
||||
review = dict(
|
||||
objects=[dict(geometry=mapping(box(10, 10, 20, 20)))],
|
||||
negative=[],
|
||||
complete_background=[mapping(box(0, 0, 100, 100))],
|
||||
)
|
||||
candidates = [
|
||||
dict(geometry=mapping(g))
|
||||
for g in [
|
||||
box(10, 10, 20, 20),
|
||||
box(40, 40, 60, 60),
|
||||
box(110, 110, 130, 130),
|
||||
box(90, 90, 110, 110),
|
||||
]
|
||||
]
|
||||
assert study.labels(candidates, review).tolist() == [1, -1, -1, -1]
|
||||
assert study.expanded_labels(candidates, review).tolist() == [1, 0, -1, -1]
|
||||
|
||||
|
||||
def test_both_arms_exclude_control_and_regression_records():
|
||||
records = [
|
||||
dict(id=rid, split=split)
|
||||
for rid, split in [
|
||||
("old", "development"),
|
||||
("new-coverage-1", "development"),
|
||||
("control-coverage-1", "heldout"),
|
||||
("old-control", "regression"),
|
||||
]
|
||||
]
|
||||
assert [r["id"] for r in study.training_records(records, "old104")] == ["old"]
|
||||
assert [r["id"] for r in study.training_records(records, "expanded")] == [
|
||||
"old",
|
||||
"new-coverage-1",
|
||||
]
|
||||
|
||||
|
||||
def test_expanded_fit_only_passed_records_and_unknown_excluded(monkeypatch):
|
||||
geoms = [box(i * 20, 0, i * 20 + 10, 10) for i in range(5)]
|
||||
record = dict(id="dev", variants={"retained": [dict(geometry=mapping(g)) for g in geoms]})
|
||||
review = {
|
||||
"dev": dict(
|
||||
objects=[dict(geometry=mapping(g)) for g in geoms[:2]],
|
||||
negative=[],
|
||||
complete_background=[mapping(box(40, 0, 70, 10))],
|
||||
)
|
||||
}
|
||||
data = {
|
||||
"dev": {"c4_512": np.arange(15).reshape(5, 3)},
|
||||
"control": {"c4_512": np.full((5, 3), 999)},
|
||||
}
|
||||
captured = []
|
||||
|
||||
def fitted(x, y, l2, maxiter):
|
||||
captured.append((x.copy(), y.copy()))
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(study, "fit_classifier", fitted)
|
||||
model = study.fit([record], review, data, 0.1, True)
|
||||
assert model == dict(positive=2, negative=2)
|
||||
assert captured[0][1].tolist() == [1, 1, 0, 0]
|
||||
assert np.array_equal(captured[0][0], data["dev"]["c4_512"][:4])
|
||||
data["control"]["c4_512"] *= 2
|
||||
study.fit([record], review, data, 0.1, True)
|
||||
assert np.array_equal(captured[0][0], captured[1][0])
|
||||
|
||||
|
||||
def test_clipped_identity_loss_cannot_be_hidden_by_another_gain():
|
||||
def result(ids):
|
||||
return {
|
||||
"rows": [{"clipped_components": {"objects": [{"id": i, "matched": True} for i in ids]}}]
|
||||
}
|
||||
|
||||
assert study.partial_gate(result(["a", "b"]), result(["a", "c"])) == ["b"]
|
||||
assert study.partial_gate(result(["a"]), result(["a", "b"])) == []
|
||||
@@ -0,0 +1,135 @@
|
||||
import copy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import coverage_mass_control as m
|
||||
|
||||
|
||||
def records():
|
||||
out = []
|
||||
for group in ["a", "b"]:
|
||||
for j in range(2):
|
||||
old = np.array([[1, 1, 0, 255], [1, 0, 255, 255]], dtype="uint8")
|
||||
out.append(
|
||||
dict(
|
||||
name=f"{group}{j}",
|
||||
sample_id=f"id-{group}{j}",
|
||||
group=group,
|
||||
split="train",
|
||||
target=old.copy(),
|
||||
base_target=old,
|
||||
)
|
||||
)
|
||||
new = np.full((2, 4), 255, dtype="uint8")
|
||||
out.append(
|
||||
dict(
|
||||
name="new",
|
||||
sample_id="id-new",
|
||||
group="a",
|
||||
split="train",
|
||||
target=new.copy(),
|
||||
base_target=new,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_zero_add_preserves_exact_weights_including_zero_window():
|
||||
rr = records()
|
||||
_, base = m.prepare(rr, "base")
|
||||
for policy in ["mass", "equal_window"]:
|
||||
_, ww = m.prepare(rr, policy)
|
||||
for name in base:
|
||||
assert np.array_equal(ww[name], base[name])
|
||||
_, small = m.prepare(rr[:-1], "base")
|
||||
assert all(np.array_equal(v, base[n]) for n, v in small.items())
|
||||
|
||||
|
||||
def test_positive_mass_and_background_are_preserved_without_small_window_bonus():
|
||||
rr = records()
|
||||
rr[-1]["target"][0, 0] = 1
|
||||
_, old = m.prepare(rr, "base")
|
||||
_, ww = m.prepare(rr, "mass")
|
||||
_, equal = m.prepare(rr, "equal_window")
|
||||
assert ww["new"].sum() == pytest.approx(0.25 / 7)
|
||||
assert equal["new"].sum() == pytest.approx(0.25 / 3)
|
||||
for group in ["a", "b"]:
|
||||
g = [r for r in rr if r["group"] == group]
|
||||
assert sum(float(ww[r["name"]][r["target"] == 1].sum()) for r in g) == pytest.approx(0.25)
|
||||
for r in g:
|
||||
bg = r["base_target"] == 0
|
||||
assert np.array_equal(ww[r["name"]][bg], old[r["name"]][bg])
|
||||
assert not ww[r["name"]][r["target"] == 255].any()
|
||||
for r in rr[:2]:
|
||||
known = r["base_target"] == 1
|
||||
np.testing.assert_allclose(ww[r["name"]][known], old[r["name"]][known] * 6 / 7)
|
||||
|
||||
|
||||
def test_controls_do_not_mutate_targets_or_depend_on_window_order():
|
||||
rr = records()
|
||||
rr[0]["target"][1, 2] = 1
|
||||
before = copy.deepcopy(rr)
|
||||
for policy in m.POLICIES:
|
||||
a, wa = m.prepare(rr, policy)
|
||||
b, wb = m.prepare(list(reversed(rr)), policy)
|
||||
assert [r["sample_id"] for r in a] == [r["sample_id"] for r in b]
|
||||
for n in wa:
|
||||
assert np.array_equal(wa[n], wb[n])
|
||||
for a, b in zip(rr, before, strict=True):
|
||||
assert np.array_equal(a["target"], b["target"])
|
||||
assert np.array_equal(a["base_target"], b["base_target"])
|
||||
|
||||
|
||||
def test_augmentation_does_not_shift_when_a_window_is_added():
|
||||
rr = records()
|
||||
assert m.schedule_digest(rr, 7, 120) == m.schedule_digest(rr[::-1], 7, 120)
|
||||
for step in range(120):
|
||||
small = {r["sample_id"]: m.rotation(7, step, r["sample_id"]) for r in rr[:-1]}
|
||||
full = {r["sample_id"]: m.rotation(7, step, r["sample_id"]) for r in rr}
|
||||
assert all(full[k] == v for k, v in small.items())
|
||||
assert len({m.rotation(7, step, rr[0]["sample_id"]) for step in range(120)}) == 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
[
|
||||
"split",
|
||||
"duplicate",
|
||||
"old_changed",
|
||||
"background_added",
|
||||
"shape",
|
||||
"class",
|
||||
"dtype",
|
||||
"unsupported",
|
||||
"no_old_paint",
|
||||
],
|
||||
)
|
||||
def test_invalid_or_leaking_inputs_are_rejected(bad):
|
||||
rr = records()
|
||||
policy = "mass"
|
||||
if bad == "split":
|
||||
rr[0]["split"] = "regression"
|
||||
if bad == "duplicate":
|
||||
rr.append(copy.deepcopy(rr[0]))
|
||||
if bad == "old_changed":
|
||||
rr[0]["target"][0, 0] = 0
|
||||
if bad == "background_added":
|
||||
rr[-1]["target"][0, 0] = 0
|
||||
if bad == "shape":
|
||||
rr[0]["target"] = rr[0]["target"][:1]
|
||||
if bad == "class":
|
||||
rr[0]["target"][0, 3] = 2
|
||||
if bad == "dtype":
|
||||
rr[0]["target"] = rr[0]["target"].astype("int16")
|
||||
if bad == "unsupported":
|
||||
policy = "other"
|
||||
if bad == "no_old_paint":
|
||||
for r in rr[:2]:
|
||||
r["base_target"][r["base_target"] == 1] = 255
|
||||
r["target"][:] = r["base_target"]
|
||||
with pytest.raises(ValueError):
|
||||
m.prepare(rr, policy)
|
||||
@@ -0,0 +1,106 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning/detail_refinement.py"
|
||||
if not SRC.exists():
|
||||
SRC = Path(__file__).with_name("detail_refinement.py")
|
||||
spec = importlib.util.spec_from_file_location("detail_refinement", SRC)
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
|
||||
|
||||
def test_group_exclusion_rejects_parent_and_record_leakage():
|
||||
groups = ["a", "b", "c", "d"]
|
||||
rr = [dict(sample_id=g, split="train", group=g) for g in groups[1:]]
|
||||
probe.validate_groups(rr, "a", groups, groups[1:])
|
||||
for parent, rows in [
|
||||
(groups, rr),
|
||||
(groups[1:], rr + [rr[0]]),
|
||||
(groups[1:], rr[:-1]),
|
||||
(groups[1:], [dict(rr[0], split="regression"), *rr[1:]]),
|
||||
(groups[1:], [dict(rr[0], group="a"), *rr[1:]]),
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
probe.validate_groups(rows, "a", groups, parent)
|
||||
|
||||
|
||||
def torch_fixture():
|
||||
torch = pytest.importorskip("torch")
|
||||
torch.set_num_threads(2)
|
||||
torch.manual_seed(19)
|
||||
return (
|
||||
torch,
|
||||
torch.randn(1, 1, 17, 23),
|
||||
torch.randint(0, 256, (1, 3, 17, 23), dtype=torch.uint8),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arm", ["coarse_only", "native_rgb"])
|
||||
def test_zero_initialization_is_exact_parent_under_c4_and_tiles(arm):
|
||||
t, coarse, rgb = torch_fixture()
|
||||
net = probe.network(12)
|
||||
x = probe.inputs(coarse, rgb, arm)
|
||||
for tile in [None, 1, 7, 32]:
|
||||
with t.no_grad():
|
||||
got = probe.prediction(net, coarse, x, tile)
|
||||
assert t.equal(got, coarse)
|
||||
assert t.equal(got >= 0, coarse >= 0)
|
||||
|
||||
|
||||
def test_shared_initialization_and_rgb_ablation():
|
||||
t, coarse, rgb = torch_fixture()
|
||||
a, b = probe.network(42), probe.network(42)
|
||||
assert all(t.equal(v, b.state_dict()[k]) for k, v in a.state_dict().items())
|
||||
x = probe.inputs(coarse, rgb, "coarse_only")
|
||||
assert t.equal(x[:, :1], coarse) and not x[:, 1:].any()
|
||||
y = probe.inputs(coarse, rgb, "native_rgb")
|
||||
assert t.equal(y[:, :1], coarse) and t.equal(y[:, 1:], rgb.float() / 127.5 - 1)
|
||||
assert sum(p.numel() for p in a.parameters()) == 2929
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["shape", "dtype", "nonfinite", "gradient", "arm"])
|
||||
def test_input_contract_rejects_invalid_pairs(bad):
|
||||
t, coarse, rgb = torch_fixture()
|
||||
arm = "native_rgb"
|
||||
if bad == "shape":
|
||||
rgb = rgb[..., :-1]
|
||||
elif bad == "dtype":
|
||||
rgb = rgb.float()
|
||||
elif bad == "nonfinite":
|
||||
coarse[0, 0, 0, 0] = float("nan")
|
||||
elif bad == "gradient":
|
||||
coarse.requires_grad_(True)
|
||||
else:
|
||||
arm = "street_patch"
|
||||
with pytest.raises(ValueError):
|
||||
probe.inputs(coarse, rgb, arm)
|
||||
|
||||
|
||||
def test_nonzero_correction_tiling_c4_equivariance_and_gradients():
|
||||
t, coarse, rgb = torch_fixture()
|
||||
net = probe.network(42)
|
||||
x = probe.inputs(coarse, rgb, "native_rgb")
|
||||
opt = t.optim.AdamW(net.parameters(), lr=0.001)
|
||||
yy = (rgb[:, :1].float() / 255 > 0.5).float()
|
||||
for _ in range(3):
|
||||
opt.zero_grad()
|
||||
t.nn.functional.binary_cross_entropy_with_logits(coarse + net(x), yy).backward()
|
||||
opt.step()
|
||||
assert net[0].weight.grad[:, 1:].abs().sum() > 0
|
||||
assert coarse.grad is None
|
||||
assert net[-1].weight.abs().sum() > 0
|
||||
with t.no_grad():
|
||||
expected = probe.prediction(net, coarse, x)
|
||||
for tile in [1, 7, 32]:
|
||||
assert t.allclose(
|
||||
probe.prediction(net, coarse, x, tile), expected, atol=2e-6, rtol=1e-6
|
||||
)
|
||||
for k in range(4):
|
||||
xx = probe.inputs(t.rot90(coarse, k, [-2, -1]), t.rot90(rgb, k, [-2, -1]), "native_rgb")
|
||||
got = t.rot90(probe.prediction(net, t.rot90(coarse, k, [-2, -1]), xx), -k, [-2, -1])
|
||||
assert t.allclose(got, expected, atol=2e-6, rtol=1e-6)
|
||||
assert not t.equal(expected, coarse)
|
||||
with pytest.raises(ValueError):
|
||||
probe.residual(net, x, 0)
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Mass conservation and sampling budgets for paired data-diversity fits."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import diversity_mass as mass
|
||||
|
||||
FAMILIES = {"a": "fa", "a-extra": "fa", "b": "fb", "held": "fh"}
|
||||
|
||||
|
||||
def records():
|
||||
return [
|
||||
dict(name="a1", sample_id="20", group="a", split="original-role",
|
||||
target=np.array([[1, 1, 1, 0, 255]], dtype=np.uint8)),
|
||||
dict(name="a2", sample_id="30", group="a", split="original-role",
|
||||
target=np.array([[1, 255]], dtype=np.uint8)),
|
||||
dict(name="b1", sample_id="10", group="b", split="original-role",
|
||||
target=np.array([[1, 0, 0, 0, 255]], dtype=np.uint8)),
|
||||
]
|
||||
|
||||
|
||||
def test_mass_is_equal_per_class_family_and_supported_frame_not_pixel_count():
|
||||
original = records()
|
||||
out, weights, audit = mass.prepare(original, "fh", FAMILIES)
|
||||
assert [r["sample_id"] for r in out] == ["10", "20", "30"]
|
||||
np.testing.assert_allclose(weights["a1"], [[1 / 24, 1 / 24, 1 / 24, 1 / 4, 0]])
|
||||
np.testing.assert_allclose(weights["a2"], [[1 / 8, 0]])
|
||||
np.testing.assert_allclose(weights["b1"], [[1 / 4, 1 / 12, 1 / 12, 1 / 12, 0]])
|
||||
assert audit["total_mass"] == pytest.approx(1)
|
||||
assert [r["mass"] for r in audit["classes"]] == pytest.approx([0.5, 0.5])
|
||||
assert all(r["mass"] == pytest.approx(0.25) for r in audit["family_classes"])
|
||||
assert {r["name"]: r["mass"] for r in audit["frames"]} == pytest.approx(
|
||||
{"a1": 3 / 8, "a2": 1 / 8, "b1": 1 / 2}
|
||||
)
|
||||
assert json.loads(json.dumps(audit)) == audit
|
||||
for r in out:
|
||||
assert r["split"] == "original-role"
|
||||
assert weights[r["name"]].dtype == np.float64
|
||||
assert (weights[r["name"]][r["target"] != 255] > 0).all()
|
||||
assert not weights[r["name"]][r["target"] == 255].any()
|
||||
|
||||
|
||||
def test_bg_only_frame_redistributes_only_its_family_background_mass():
|
||||
old = records()
|
||||
added = dict(name="new", sample_id="40", group="a-extra", split="regression",
|
||||
target=np.array([[0, 0, 255]], dtype=np.uint8))
|
||||
_, before, ba = mass.prepare(old, "fh", FAMILIES)
|
||||
out, after, aa = mass.prepare(old + [added], "fh", FAMILIES)
|
||||
for r in old:
|
||||
np.testing.assert_array_equal(before[r["name"]][r["target"] == 1],
|
||||
after[r["name"]][r["target"] == 1])
|
||||
np.testing.assert_array_equal(before["b1"], after["b1"])
|
||||
assert after["a1"][0, 3] == pytest.approx(1 / 8)
|
||||
np.testing.assert_allclose(after["new"], [[1 / 16, 1 / 16, 0]])
|
||||
assert [r["mass"] for r in ba["classes"]] == pytest.approx(
|
||||
[r["mass"] for r in aa["classes"]]
|
||||
)
|
||||
assert [r["mass"] for r in ba["family_classes"]] == pytest.approx(
|
||||
[r["mass"] for r in aa["family_classes"]]
|
||||
)
|
||||
assert next(r for r in out if r["name"] == "new")["group"] == "a-extra"
|
||||
assert next(r for r in out if r["name"] == "new")["split"] == "regression"
|
||||
|
||||
|
||||
def test_no_input_mutation_and_permutation_independence():
|
||||
source = records()
|
||||
previous = copy.deepcopy(source)
|
||||
out, weights, audit = mass.prepare(source, "fh", FAMILIES)
|
||||
other, ww, aa = mass.prepare(source[::-1], "fh", dict(reversed(list(FAMILIES.items()))))
|
||||
assert audit == aa
|
||||
assert [r["sample_id"] for r in other] == [r["sample_id"] for r in out]
|
||||
for r, old in zip(source, previous, strict=True):
|
||||
np.testing.assert_array_equal(r["target"], old["target"])
|
||||
np.testing.assert_array_equal(weights[r["name"]], ww[r["name"]])
|
||||
out[0]["target"][:] = 255
|
||||
out[0]["group"] = "changed"
|
||||
np.testing.assert_array_equal(source[2]["target"], previous[2]["target"])
|
||||
assert source[2]["group"] == "b"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fault", [
|
||||
"held", "duplicate-name", "duplicate-id", "missing-group", "missing-family",
|
||||
"one-class-family", "one-class-global", "unknown-only", "bad-label", "float",
|
||||
"nan", "infinity", "empty-target", "one-dimensional", "missing-target", "empty",
|
||||
"missing-held-map", "bad-mapping", "blank-id",
|
||||
])
|
||||
def test_invalid_admissions_fail_closed(fault):
|
||||
rows, mapping = records(), dict(FAMILIES)
|
||||
if fault == "held":
|
||||
rows[0]["group"] = "held"
|
||||
elif fault == "duplicate-name":
|
||||
rows[1]["name"] = rows[0]["name"]
|
||||
elif fault == "duplicate-id":
|
||||
rows[1]["sample_id"] = rows[0]["sample_id"]
|
||||
elif fault == "missing-group":
|
||||
del mapping["a"]
|
||||
elif fault == "missing-family":
|
||||
mapping["extra-unseen-group"] = "extra-family"
|
||||
elif fault == "one-class-family":
|
||||
rows[2]["target"][rows[2]["target"] == 1] = 0
|
||||
elif fault == "one-class-global":
|
||||
for r in rows:
|
||||
r["target"][r["target"] == 1] = 0
|
||||
elif fault == "unknown-only":
|
||||
rows[0]["target"][:] = 255
|
||||
elif fault == "bad-label":
|
||||
rows[0]["target"][0, 0] = 2
|
||||
elif fault in ("float", "nan", "infinity"):
|
||||
rows[0]["target"] = rows[0]["target"].astype(float)
|
||||
rows[0]["target"][0, 0] = {"float": 1.0, "nan": np.nan, "infinity": np.inf}[fault]
|
||||
elif fault == "empty-target":
|
||||
rows[0]["target"] = np.empty((0, 2), dtype=np.uint8)
|
||||
elif fault == "one-dimensional":
|
||||
rows[0]["target"] = rows[0]["target"].reshape(-1)
|
||||
elif fault == "missing-target":
|
||||
del rows[0]["target"]
|
||||
elif fault == "empty":
|
||||
rows = []
|
||||
elif fault == "missing-held-map":
|
||||
del mapping["held"]
|
||||
elif fault == "bad-mapping":
|
||||
mapping["a"] = None
|
||||
elif fault == "blank-id":
|
||||
rows[0]["sample_id"] = ""
|
||||
with pytest.raises(ValueError):
|
||||
mass.prepare(rows, "fh", mapping)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("budget,frames", [(10, 3), (10240, 12), (10240, 14), (9216, 11),
|
||||
(8, 8), (7, 1)])
|
||||
def test_quotas_exact_budget_positive_and_fair_over_a_full_cycle(budget, frames):
|
||||
cycle = np.stack([mass.quotas(budget, frames, step) for step in range(frames)])
|
||||
assert cycle.dtype == np.int64 and (cycle > 0).all()
|
||||
np.testing.assert_array_equal(cycle.sum(axis=1), np.full(frames, budget))
|
||||
np.testing.assert_array_equal(cycle.sum(axis=0), np.full(frames, budget))
|
||||
assert cycle.max() - cycle.min() <= 1
|
||||
np.testing.assert_array_equal(mass.quotas(budget, frames, 0),
|
||||
mass.quotas(budget, frames, frames))
|
||||
|
||||
|
||||
def test_remainder_wraps_and_arms_have_equal_total_draws():
|
||||
np.testing.assert_array_equal(mass.quotas(11, 4, 3), [3, 3, 2, 3])
|
||||
np.testing.assert_array_equal(mass.quotas(11, 4, 4), [3, 3, 3, 2])
|
||||
for step in range(20):
|
||||
assert mass.quotas(10240, 10, step).sum() == mass.quotas(10240, 14, step).sum()
|
||||
np.testing.assert_array_equal(mass.quotas(np.int64(5), np.int64(2), np.int64(1)), [2, 3])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", [
|
||||
(0, 1, 0), (2, 3, 0), (2, 0, 0), (2, -1, 0), (4, 2, -1),
|
||||
(3.0, 2, 0), (3, 2.0, 0), (3, 2, 0.0), (True, 1, 0), (3, True, 0),
|
||||
(3, 2, False), (np.nan, 2, 0), (np.inf, 2, 0), (2**63, 2, 0),
|
||||
])
|
||||
def test_invalid_quotas_rejected(args):
|
||||
with pytest.raises(ValueError):
|
||||
mass.quotas(*args)
|
||||
@@ -0,0 +1,78 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"feature_refinement",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/feature_refinement.py",
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def tensor():
|
||||
return pytest.importorskip("torch")
|
||||
|
||||
|
||||
def test_identity_and_ablation():
|
||||
t = tensor()
|
||||
n = m.network(12, channels=4, width=8)
|
||||
f, c = t.randn(31, 4), t.randn(31, 1)
|
||||
assert t.equal(n(f, c, "scene_features"), c)
|
||||
with t.no_grad():
|
||||
n.output.weight.fill_(0.02)
|
||||
assert t.equal(n(f, c, "coarse_only"), n(f * 100, c, "coarse_only"))
|
||||
assert not t.equal(n(f, c, "scene_features"), n(f * 100, c, "scene_features"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shape", [(8, 9), (13, 17), (1, 1)])
|
||||
def test_native_alignment(shape):
|
||||
t = tensor()
|
||||
f = t.arange(2 * 3 * 5).float().reshape(1, 2, 3, 5)
|
||||
ids = t.arange(shape[0] * shape[1])
|
||||
got = m.sample_native(f, shape, ids)
|
||||
expected = t.nn.functional.interpolate(f, size=shape, mode="bilinear", align_corners=False)
|
||||
t.testing.assert_close(got, expected[0].flatten(1).T, atol=1e-5, rtol=1e-6)
|
||||
|
||||
|
||||
def test_tiled_full_and_c4():
|
||||
t = tensor()
|
||||
n = m.network(7, channels=4, width=8)
|
||||
with t.no_grad():
|
||||
n.output.weight.fill_(0.02)
|
||||
f, c = t.randn(1, 4, 7, 7), t.randn(21, 21)
|
||||
a = m.predict(n, f, c, "scene_features", chunk=441)
|
||||
b = m.predict(n, f, c, "scene_features", chunk=37)
|
||||
t.testing.assert_close(a, b, atol=2e-5, rtol=1e-6)
|
||||
for k in range(4):
|
||||
z = m.predict(n, t.rot90(f, k, [-2, -1]), t.rot90(c, k), "scene_features")
|
||||
t.testing.assert_close(a, t.rot90(z, -k), atol=2e-5, rtol=1e-6)
|
||||
|
||||
|
||||
def test_seed_and_no_fine_gradient():
|
||||
t = tensor()
|
||||
a, b = m.network(8, 4, 8), m.network(8, 4, 8)
|
||||
assert all(t.equal(x, y) for x, y in zip(a.parameters(), b.parameters(), strict=True))
|
||||
with t.no_grad():
|
||||
a.output.weight.fill_(0.02)
|
||||
a(t.randn(7, 4), t.ones(7, 1), "coarse_only").sum().backward()
|
||||
assert t.count_nonzero(a.layers[0].weight.grad[:, :4]) == 0
|
||||
|
||||
|
||||
def test_outside_points_rejected():
|
||||
t = tensor()
|
||||
with pytest.raises(ValueError):
|
||||
m.sample_native(t.ones(1, 4, 2, 2), (4, 4), t.tensor([16]))
|
||||
|
||||
|
||||
def test_capacity_gate():
|
||||
b = dict(bce=1.0, weak_fn=2, clear_fn=4, background_fp=100)
|
||||
a = dict(bce=0.4, weak_fn=1, clear_fn=3, background_fp=40)
|
||||
c = dict(bce=0.8, weak_fn=2, clear_fn=4, background_fp=80)
|
||||
assert m.capacity_screen(b, a, c)["passed"]
|
||||
for key, bad in [("bce", 0.6), ("weak_fn", 3), ("clear_fn", 5), ("background_fp", 51)]:
|
||||
assert not m.capacity_screen(b, dict(a, **{key: bad}), c)["passed"]
|
||||
assert not m.capacity_screen(b, a, dict(c, weak_fn=0))["passed"]
|
||||
with pytest.raises(ValueError):
|
||||
m.capacity_screen(b, dict(a, bce=float("nan")), c)
|
||||
@@ -0,0 +1,67 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning/fit_capacity.py"
|
||||
if not SRC.exists():
|
||||
SRC = Path(__file__).with_name("fit_capacity.py")
|
||||
spec = importlib.util.spec_from_file_location("fit_capacity", SRC)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def before():
|
||||
return dict(bce=0.2, weak_fn=10, background_fp=20, clear_fn=2)
|
||||
|
||||
|
||||
def test_exact_half_boundary_passes_without_promotion():
|
||||
a = dict(bce=0.1, weak_fn=5, background_fp=10, clear_fn=2)
|
||||
r = m.capacity_screen(before(), a)
|
||||
assert r["passed"] and not r["production_eligible"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"metric,value", [("bce", 0.100001), ("weak_fn", 6), ("background_fp", 11), ("clear_fn", 3)]
|
||||
)
|
||||
def test_each_guard_fails_even_when_other_metrics_improve(metric, value):
|
||||
a = dict(bce=0.01, weak_fn=0, background_fp=0, clear_fn=0)
|
||||
a[metric] = value
|
||||
r = m.capacity_screen(before(), a)
|
||||
assert not r["passed"] and r["failures"] == [metric]
|
||||
|
||||
|
||||
def test_zero_baseline_cannot_hide_new_errors_or_divide_by_zero():
|
||||
z = dict(bce=0.0, weak_fn=0, background_fp=0, clear_fn=0)
|
||||
assert m.capacity_screen(z, z)["passed"]
|
||||
a = dict(z, background_fp=1)
|
||||
assert m.capacity_screen(z, a)["failures"] == ["background_fp"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"metric,value",
|
||||
[
|
||||
("bce", float("nan")),
|
||||
("bce", float("inf")),
|
||||
("bce", -1),
|
||||
("bce", True),
|
||||
("weak_fn", 1.5),
|
||||
("background_fp", -1),
|
||||
("clear_fn", True),
|
||||
],
|
||||
)
|
||||
def test_invalid_metrics_are_rejected(metric, value):
|
||||
a = before()
|
||||
a[metric] = value
|
||||
for left, right in [(a, before()), (before(), a)]:
|
||||
with pytest.raises(ValueError):
|
||||
m.capacity_screen(left, right)
|
||||
|
||||
|
||||
def test_extra_or_missing_cohorts_are_rejected():
|
||||
for a in [
|
||||
dict(before(), street_threshold=1),
|
||||
{k: v for k, v in before().items() if k != "weak_fn"},
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
m.capacity_screen(a, before())
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Scientific isolation and nonregression gates for grouped threshold selection."""
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
for dependency in ["numpy", "cv2", "scipy", "shapely"]:
|
||||
pytest.importorskip(dependency)
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for directory in [
|
||||
"simulation/semantic-learning",
|
||||
"simulation/urban-plan-research/systematic",
|
||||
"simulation/urban-plan-research/marking_pass",
|
||||
]:
|
||||
sys.path.insert(0, str(ROOT / directory))
|
||||
study = importlib.import_module("grouped_selection_study")
|
||||
|
||||
|
||||
def test_control_street_never_enters_development():
|
||||
records = [dict(street="a", split="heldout"), dict(street="control", split="train")]
|
||||
assert study.development(records, ["a"]) == [records[0]]
|
||||
|
||||
|
||||
def test_threshold_rejects_known_false_positives_and_uses_interior_plateau():
|
||||
rows = [
|
||||
dict(threshold=t, unsupported=0, worst_street=0.8, macro_family=0.9, found=10)
|
||||
for t in [0.2, 0.25, 0.3, 0.35, 0.4]
|
||||
]
|
||||
rows.append(dict(threshold=0.1, unsupported=1, worst_street=1, macro_family=1, found=20))
|
||||
assert study.select(rows)["threshold"] == 0.3
|
||||
assert study.select([rows[-1]]) is None
|
||||
|
||||
|
||||
def cohort(found, fp=0):
|
||||
return dict(
|
||||
rows=[dict(id="window", objects=[dict(id=i, matched=True) for i in found])],
|
||||
streets={"a": dict(unsupported=fp)},
|
||||
summary=dict(found=len(found), unsupported=fp),
|
||||
)
|
||||
|
||||
|
||||
def test_equal_count_cannot_hide_loss_of_a_previously_found_object():
|
||||
verdict = study.transfer_gate(cohort(["x", "y"]), cohort(["x", "z", "w"]))
|
||||
assert verdict["lost_objects"] == ["y"]
|
||||
assert not verdict["passed"]
|
||||
|
||||
|
||||
def test_improvement_requires_no_loss_and_no_extra_false_positive():
|
||||
assert study.transfer_gate(cohort(["x"], 1), cohort(["x"], 0))["passed"]
|
||||
assert not study.transfer_gate(cohort(["x"]), cohort(["x", "y"], 1))["passed"]
|
||||
assert not study.transfer_gate(cohort(["x"]), cohort(["x"]))["passed"]
|
||||
|
||||
|
||||
def test_unmatchable_objects_do_not_distort_threshold_objective():
|
||||
objects = [
|
||||
dict(id="a", family="arrow", matched=True),
|
||||
dict(id="b", family="bar", matched=False),
|
||||
]
|
||||
rows = [dict(id="w", street="s", objects=objects)]
|
||||
result = study.objective(rows, {"w": dict(objects=objects)})
|
||||
assert result["worst_street"] == 1
|
||||
assert result["family_matchable"] == {"arrow": [1, 1]}
|
||||
@@ -0,0 +1,41 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
p = Path(__file__).resolve().parents[1]/"simulation/semantic-learning/label_extension.py"
|
||||
s = importlib.util.spec_from_file_location("label_extension", p)
|
||||
m = importlib.util.module_from_spec(s)
|
||||
s.loader.exec_module(m)
|
||||
|
||||
|
||||
def test_expanding_background_keeps_old_uncertain_band_and_known_labels():
|
||||
base = np.full((5, 8), 255, np.uint8)
|
||||
base[2, 3:5] = 1
|
||||
base[1, 3:5] = 0
|
||||
base[4, 7] = 1
|
||||
lock = np.zeros(base.shape, bool)
|
||||
lock[1:4, 2:6] = True
|
||||
proposal = np.zeros(base.shape, np.uint8)
|
||||
proposal[0, 0] = 1
|
||||
got = m.extend_reviewed_target(base, proposal, lock)
|
||||
np.testing.assert_array_equal(got[lock], base[lock])
|
||||
np.testing.assert_array_equal(got[base != 255], base[base != 255])
|
||||
assert got[0, 0] == got[4, 7] == 1 and got[0, 1] == 0
|
||||
assert got[2, 2] == 255 and proposal[4, 7] == 0
|
||||
|
||||
|
||||
def test_omitted_or_misaligned_protection_rejected():
|
||||
base = np.full((2, 3), 255, np.uint8)
|
||||
for lock in [None, np.zeros((3, 2), bool), np.zeros((2, 3), np.uint8)]:
|
||||
with pytest.raises(ValueError):
|
||||
m.extend_reviewed_target(base, base, lock)
|
||||
|
||||
|
||||
def test_out_of_vocabulary_labels_rejected():
|
||||
base = np.full((2, 3), 255, np.uint8)
|
||||
proposal = base.copy()
|
||||
proposal[0, 0] = 2
|
||||
with pytest.raises(ValueError):
|
||||
m.extend_reviewed_target(base, proposal, np.zeros(base.shape, bool))
|
||||
@@ -0,0 +1,540 @@
|
||||
"""Resume, lost acknowledgement and provenance failures must never duplicate fit."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SOURCE = Path(__file__).parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SOURCE))
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"tested_learning_execution", SOURCE / "learning_execution.py"
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path):
|
||||
(tmp_path / "runner.py").write_text("# synthetic pinned runner\n")
|
||||
(tmp_path / "release.json").write_text('{"accepted":true}\n')
|
||||
calls = []
|
||||
|
||||
def invoke(root, argv, timeout):
|
||||
calls.append(argv[1])
|
||||
phase = argv[1].removeprefix("verify-")
|
||||
name = phase + ".json"
|
||||
if argv[1].startswith("verify-"):
|
||||
return json.dumps(
|
||||
dict(
|
||||
valid=True,
|
||||
outputs={name: m.pin(root, name)},
|
||||
artifacts={name: m.pin(root, name)},
|
||||
)
|
||||
)
|
||||
(root / name).write_text(json.dumps(dict(phase=phase)))
|
||||
return ""
|
||||
|
||||
plan = dict(
|
||||
schema=m.SCHEMA,
|
||||
objective="synthetic resumable fit/replay",
|
||||
inputs={name: m.pin(tmp_path, name) for name in ["runner.py", "release.json"]},
|
||||
phases=[
|
||||
dict(
|
||||
name=n,
|
||||
run=["runner.py", n],
|
||||
verify=["runner.py", "verify-" + n],
|
||||
outputs=[n + ".json"],
|
||||
run_timeout_seconds=5,
|
||||
verify_timeout_seconds=5,
|
||||
)
|
||||
for n in ["fit", "replay"]
|
||||
],
|
||||
)
|
||||
ledger = m.Execution(tmp_path, runner=invoke)
|
||||
yield ledger, plan, calls, invoke
|
||||
ledger.close()
|
||||
|
||||
|
||||
def test_restart_reuses_completed_fit_and_checks_order(setup):
|
||||
ledger, plan, calls, runner = setup
|
||||
identity = ledger.register(plan)
|
||||
with pytest.raises(ValueError, match="Previous"):
|
||||
ledger.execute(identity, "replay")
|
||||
first = ledger.execute(identity, "fit")
|
||||
assert first["artifact_validation"] and first["model_acceptance"] is False
|
||||
reopened = m.Execution(ledger.root, runner=runner)
|
||||
try:
|
||||
assert reopened.register(plan) == identity
|
||||
assert reopened.execute(identity, "fit") == first
|
||||
reopened.execute(identity, "replay")
|
||||
assert calls == ["fit", "verify-fit", "replay", "verify-replay"]
|
||||
finally:
|
||||
reopened.close()
|
||||
|
||||
|
||||
def test_lost_acknowledgement_no_retry_and_root_recovers_outputs(setup):
|
||||
ledger, plan, calls, runner = setup
|
||||
identity = ledger.register(plan)
|
||||
|
||||
def lost_ack(root, argv, timeout):
|
||||
result = runner(root, argv, timeout)
|
||||
if argv[1] == "fit":
|
||||
raise ConnectionError("acknowledgement lost after artifacts were written")
|
||||
return result
|
||||
|
||||
ledger.runner = lost_ack
|
||||
with pytest.raises(ConnectionError):
|
||||
ledger.execute(identity, "fit")
|
||||
state = ledger.status(identity)["phases"][0]
|
||||
assert state["state"] == "unknown"
|
||||
ledger.clock = lambda: 10**15
|
||||
with pytest.raises(ValueError, match="reconciliation"):
|
||||
ledger.execute(identity, "fit")
|
||||
with pytest.raises(ValueError, match="matching"):
|
||||
ledger.reconcile(identity, "fit", "wrong-token", "process stopped")
|
||||
recovered = ledger.reconcile(
|
||||
identity, "fit", state["token"], "trusted root verified PID stopped"
|
||||
)
|
||||
assert ledger.execute(identity, "fit") == recovered
|
||||
assert calls.count("fit") == 1
|
||||
|
||||
|
||||
def test_failure_with_partial_outputs_does_not_become_success(setup):
|
||||
ledger, plan, _, _ = setup
|
||||
identity = ledger.register(plan)
|
||||
|
||||
def crash(root, argv, timeout):
|
||||
(root / "partial-model.pt").write_bytes(b"synthetic partial checkpoint")
|
||||
raise TimeoutError("training stopped before receipt")
|
||||
|
||||
ledger.runner = crash
|
||||
with pytest.raises(TimeoutError):
|
||||
ledger.execute(identity, "fit")
|
||||
state = ledger.status(identity)["phases"][0]
|
||||
with pytest.raises(ValueError, match="Missing"):
|
||||
ledger.reconcile(identity, "fit", state["token"], "process stopped")
|
||||
assert ledger.status(identity)["phases"][0]["state"] == "unknown"
|
||||
(ledger.root / "failure-archive.txt").write_text("synthetic archived diagnostics")
|
||||
archive = {"failure-archive.txt": m.pin(ledger.root, "failure-archive.txt")}
|
||||
result = ledger.close_failed(identity, "fit", state["token"], "verified stopped", archive)
|
||||
assert result["retry_authorized"] is False
|
||||
assert (ledger.root / "partial-model.pt").exists()
|
||||
with pytest.raises(ValueError, match="reconciliation"):
|
||||
ledger.execute(identity, "fit")
|
||||
|
||||
|
||||
def test_two_controllers_cannot_start_same_phase(setup):
|
||||
ledger, plan, calls, runner = setup
|
||||
identity = ledger.register(plan)
|
||||
competitor = m.Execution(ledger.root, runner=runner)
|
||||
|
||||
def during(root, argv, timeout):
|
||||
if argv[1] == "fit":
|
||||
with pytest.raises(ValueError, match="reconciliation"):
|
||||
competitor.execute(identity, "fit")
|
||||
return runner(root, argv, timeout)
|
||||
|
||||
ledger.runner = during
|
||||
try:
|
||||
ledger.execute(identity, "fit")
|
||||
assert calls.count("fit") == 1
|
||||
finally:
|
||||
competitor.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changed", ["release.json", "runner.py", "fit.json"])
|
||||
def test_changed_provenance_blocks_completed_resume_and_next_phase(setup, changed):
|
||||
ledger, plan, calls, _ = setup
|
||||
identity = ledger.register(plan)
|
||||
ledger.execute(identity, "fit")
|
||||
(ledger.root / changed).write_text("changed")
|
||||
for phase in ["fit", "replay"]:
|
||||
with pytest.raises(ValueError, match="changed"):
|
||||
ledger.execute(identity, phase)
|
||||
assert calls.count("fit") == 1 and "replay" not in calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["false", "missing-output", "mutated-after-pin", "extra-field"])
|
||||
def test_invalid_verifier_cannot_complete_phase(setup, mode):
|
||||
ledger, plan, _, runner = setup
|
||||
identity = ledger.register(plan)
|
||||
|
||||
def bad(root, argv, timeout):
|
||||
raw = runner(root, argv, timeout)
|
||||
if not argv[1].startswith("verify-"):
|
||||
return raw
|
||||
value = json.loads(raw)
|
||||
if mode == "false":
|
||||
value["valid"] = False
|
||||
if mode == "missing-output":
|
||||
value["outputs"] = {}
|
||||
if mode == "extra-field":
|
||||
value["promote"] = True
|
||||
if mode == "mutated-after-pin":
|
||||
(root / "fit.json").write_text("tampered")
|
||||
return json.dumps(value)
|
||||
|
||||
ledger.runner = bad
|
||||
with pytest.raises(ValueError):
|
||||
ledger.execute(identity, "fit")
|
||||
assert ledger.status(identity)["phases"][0]["state"] == "unknown"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("member", ["../escape", "/absolute", "a\\b", "a:stream"])
|
||||
def test_unsafe_outputs_are_rejected(setup, member):
|
||||
ledger, plan, _, _ = setup
|
||||
plan["phases"][0]["outputs"] = [member]
|
||||
with pytest.raises(ValueError, match="Unsafe"):
|
||||
ledger.register(plan)
|
||||
|
||||
|
||||
def test_existing_outputs_require_explicit_ownership(setup):
|
||||
ledger, plan, calls, _ = setup
|
||||
(ledger.root / "fit.json").write_text("existing result")
|
||||
with pytest.raises(ValueError, match="Unowned"):
|
||||
ledger.register(plan)
|
||||
assert not calls
|
||||
|
||||
|
||||
def test_unfinished_owner_blocks_different_plan(setup):
|
||||
ledger, plan, _, _ = setup
|
||||
identity = ledger.register(plan)
|
||||
ledger.runner = lambda *args: (_ for _ in ()).throw(ConnectionError("lost"))
|
||||
with pytest.raises(ConnectionError):
|
||||
ledger.execute(identity, "fit")
|
||||
changed = copy.deepcopy(plan)
|
||||
changed["objective"] = "another run"
|
||||
with pytest.raises(ValueError, match="owns resources"):
|
||||
ledger.register(changed)
|
||||
|
||||
|
||||
def test_real_bounded_subprocess_verifier(tmp_path):
|
||||
code = """import sys,json,hashlib
|
||||
from pathlib import Path
|
||||
p=Path('result.json')
|
||||
if sys.argv[1]=='fit': p.write_text('{"value":42}')
|
||||
else:
|
||||
h=hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
outputs={'result.json':dict(bytes=p.stat().st_size,sha256=h)}
|
||||
print(json.dumps(dict(valid=True,outputs=outputs,artifacts=outputs)))
|
||||
"""
|
||||
(tmp_path / "runner.py").write_text(code)
|
||||
plan = dict(
|
||||
schema=m.SCHEMA,
|
||||
objective="real synthetic subprocess",
|
||||
inputs={"runner.py": m.pin(tmp_path, "runner.py")},
|
||||
phases=[
|
||||
dict(
|
||||
name="fit",
|
||||
run=["runner.py", "fit"],
|
||||
verify=["runner.py", "verify"],
|
||||
outputs=["result.json"],
|
||||
run_timeout_seconds=5,
|
||||
verify_timeout_seconds=5,
|
||||
)
|
||||
],
|
||||
)
|
||||
ledger = m.Execution(tmp_path)
|
||||
try:
|
||||
identity = ledger.register(plan)
|
||||
receipt = ledger.execute(identity, "fit")
|
||||
assert receipt["outputs"]["result.json"]["bytes"] == 12
|
||||
assert ledger.execute(identity, "fit") == receipt
|
||||
finally:
|
||||
ledger.close()
|
||||
|
||||
|
||||
def test_small_output_cap_and_deadline(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(m, "MAX_LOG", 16)
|
||||
(tmp_path / "runner.py").write_text("print('x'*32)\n")
|
||||
with pytest.raises(ValueError, match="output exceeded"):
|
||||
m.invoke(tmp_path, ["runner.py"], 2)
|
||||
(tmp_path / "runner.py").write_text("import time; time.sleep(2)\n")
|
||||
with pytest.raises(subprocess.TimeoutExpired):
|
||||
m.invoke(tmp_path, ["runner.py"], 0.02)
|
||||
|
||||
|
||||
def test_manifest_payload_tamper_blocks_resume_and_next_phase(setup):
|
||||
ledger, plan, calls, runner = setup
|
||||
identity = ledger.register(plan)
|
||||
|
||||
def with_payload(root, argv, timeout):
|
||||
raw = runner(root, argv, timeout)
|
||||
if argv[1] == "fit":
|
||||
(root / "model.pt").write_bytes(b"synthetic model")
|
||||
if argv[1] == "verify-fit":
|
||||
value = json.loads(raw)
|
||||
value["artifacts"]["model.pt"] = m.pin(root, "model.pt")
|
||||
return json.dumps(value)
|
||||
return raw
|
||||
|
||||
ledger.runner = with_payload
|
||||
receipt = ledger.execute(identity, "fit")
|
||||
assert set(receipt["artifacts"]) == {"fit.json", "model.pt"}
|
||||
(ledger.root / "model.pt").write_bytes(b"corrupted model")
|
||||
for phase in ["fit", "replay"]:
|
||||
with pytest.raises(ValueError, match="changed: model.pt"):
|
||||
ledger.execute(identity, phase)
|
||||
assert calls.count("fit") == 1 and "replay" not in calls
|
||||
|
||||
|
||||
def test_verifier_cannot_omit_output_from_closure(setup):
|
||||
ledger, plan, _, runner = setup
|
||||
identity = ledger.register(plan)
|
||||
|
||||
def missing(root, argv, timeout):
|
||||
raw = runner(root, argv, timeout)
|
||||
if argv[1].startswith("verify-"):
|
||||
value = json.loads(raw)
|
||||
value["artifacts"] = {}
|
||||
return json.dumps(value)
|
||||
return raw
|
||||
|
||||
ledger.runner = missing
|
||||
with pytest.raises(ValueError, match="closure"):
|
||||
ledger.execute(identity, "fit")
|
||||
|
||||
|
||||
def test_separate_process_budgets_and_compact_status(setup):
|
||||
ledger, plan, _, runner = setup
|
||||
plan["phases"][0].update(run_timeout_seconds=7, verify_timeout_seconds=3)
|
||||
calls = []
|
||||
|
||||
def budget(root, argv, timeout):
|
||||
calls.append(timeout)
|
||||
return runner(root, argv, timeout)
|
||||
|
||||
ledger.runner = budget
|
||||
identity = ledger.register(plan)
|
||||
ledger.execute(identity, "fit")
|
||||
assert calls == [7, 3]
|
||||
phase = ledger.status(identity)["phases"][0]
|
||||
assert "receipt" not in phase and phase["artifact_count"] == 1
|
||||
assert len(phase["receipt_sha256"]) == 64
|
||||
|
||||
|
||||
def test_readonly_input_root_with_separate_state_checks_real_external_files(tmp_path):
|
||||
store = tmp_path / "store"
|
||||
store.mkdir()
|
||||
state = tmp_path / "state"
|
||||
(store / "release.json").write_text('{"target":42}')
|
||||
(store / "runner.py").write_text("# trusted synthetic runner")
|
||||
|
||||
def invoke(root, argv, timeout):
|
||||
if argv[1] == "fit":
|
||||
(root / "output.json").write_text('{"result":42}')
|
||||
return ""
|
||||
values = {"output.json": m.pin(root, "output.json")}
|
||||
return json.dumps(dict(valid=True, outputs=values, artifacts=values))
|
||||
|
||||
plan = dict(
|
||||
schema=m.SCHEMA,
|
||||
objective="separate ledger and explicit source pins",
|
||||
inputs={n: m.pin(store, n) for n in ["release.json", "runner.py"]},
|
||||
phases=[
|
||||
dict(
|
||||
name="fit",
|
||||
run=["runner.py", "fit"],
|
||||
verify=["runner.py", "verify"],
|
||||
outputs=["output.json"],
|
||||
run_timeout_seconds=5,
|
||||
verify_timeout_seconds=5,
|
||||
)
|
||||
],
|
||||
)
|
||||
ledger = m.Execution(store, state_root=state, runner=invoke)
|
||||
try:
|
||||
identity = ledger.register(plan)
|
||||
ledger.execute(identity, "fit")
|
||||
assert (state / "learning-execution.sqlite3").exists()
|
||||
assert not (store / "learning-execution.sqlite3").exists()
|
||||
(store / "release.json").write_text("changed external target")
|
||||
with pytest.raises(ValueError, match="changed: release.json"):
|
||||
ledger.execute(identity, "fit")
|
||||
finally:
|
||||
ledger.close()
|
||||
|
||||
|
||||
def test_input_closure_above_128_files_is_bounded_and_checked(tmp_path):
|
||||
(tmp_path / "runner.py").write_text("# synthetic")
|
||||
inputs = {"runner.py": m.pin(tmp_path, "runner.py")}
|
||||
for i in range(130):
|
||||
name = f"input-{i}.json"
|
||||
(tmp_path / name).write_text(str(i))
|
||||
inputs[name] = m.pin(tmp_path, name)
|
||||
plan = dict(
|
||||
schema=m.SCHEMA,
|
||||
objective="explicit real closure",
|
||||
inputs=inputs,
|
||||
phases=[
|
||||
dict(
|
||||
name="fit",
|
||||
run=["runner.py"],
|
||||
verify=["runner.py"],
|
||||
outputs=["out.json"],
|
||||
run_timeout_seconds=1,
|
||||
verify_timeout_seconds=1,
|
||||
)
|
||||
],
|
||||
)
|
||||
ledger = m.Execution(tmp_path)
|
||||
try:
|
||||
identity = ledger.register(plan)
|
||||
(tmp_path / "input-129.json").write_text("changed")
|
||||
with pytest.raises(ValueError, match="input-129.json"):
|
||||
ledger.execute(identity, "fit")
|
||||
finally:
|
||||
ledger.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cumulative_artifacts(tmp_path):
|
||||
"""Three real completed receipts retain the same model and earlier outputs."""
|
||||
(tmp_path / "runner.py").write_text("# synthetic cumulative pipeline\n")
|
||||
(tmp_path / "release.json").write_text('{"accepted":true}\n')
|
||||
phases = ["fit", "score", "replay", "judge"]
|
||||
calls, receipts = [], []
|
||||
|
||||
def invoke(root, argv, timeout):
|
||||
calls.append(argv[1])
|
||||
phase = argv[1].removeprefix("verify-")
|
||||
index = phases.index(phase)
|
||||
if not argv[1].startswith("verify-"):
|
||||
(root / (phase + ".json")).write_text(json.dumps(dict(phase=phase)))
|
||||
if phase == "fit":
|
||||
for name in ("model.pt", "copy.pt"):
|
||||
(root / name).write_bytes(b"same bytes, distinct physical paths")
|
||||
if phase == "score":
|
||||
(root / "held.npz").write_bytes(b"synthetic prediction payload")
|
||||
return ""
|
||||
names = [n + ".json" for n in phases[: index + 1]] + ["model.pt", "copy.pt"]
|
||||
if index >= 1:
|
||||
names.append("held.npz")
|
||||
return json.dumps(
|
||||
dict(
|
||||
valid=True,
|
||||
outputs={phase + ".json": m.pin(root, phase + ".json")},
|
||||
artifacts={name: m.pin(root, name) for name in names},
|
||||
)
|
||||
)
|
||||
|
||||
plan = dict(
|
||||
schema=m.SCHEMA,
|
||||
objective="cumulative synthetic artifact closure",
|
||||
inputs={name: m.pin(tmp_path, name) for name in ["runner.py", "release.json"]},
|
||||
phases=[
|
||||
dict(
|
||||
name=name,
|
||||
run=["runner.py", name],
|
||||
verify=["runner.py", "verify-" + name],
|
||||
outputs=[name + ".json"],
|
||||
run_timeout_seconds=5,
|
||||
verify_timeout_seconds=5,
|
||||
)
|
||||
for name in phases
|
||||
],
|
||||
)
|
||||
ledger = m.Execution(tmp_path, runner=invoke)
|
||||
try:
|
||||
identity = ledger.register(plan)
|
||||
for phase in phases[:3]:
|
||||
receipts.append(ledger.execute(identity, phase))
|
||||
yield ledger, identity, plan, receipts, calls, invoke
|
||||
finally:
|
||||
ledger.close()
|
||||
|
||||
|
||||
def test_cumulative_boundary_hashes_unique_paths_and_rechecks_next_boundary(
|
||||
cumulative_artifacts, monkeypatch
|
||||
):
|
||||
ledger, identity, plan, receipts, _, _ = cumulative_artifacts
|
||||
old_entries = [item for receipt in receipts for item in receipt["artifacts"].items()]
|
||||
unique = dict(old_entries)
|
||||
assert len(old_entries) == 14 and len(unique) == 6
|
||||
assert unique["model.pt"] == unique["copy.pt"] # Equal hashes must not merge physical paths.
|
||||
original = m.checksum
|
||||
reads = []
|
||||
|
||||
def counted(path):
|
||||
reads.append((path.relative_to(ledger.root).as_posix(), path.stat().st_size))
|
||||
return original(path)
|
||||
|
||||
monkeypatch.setattr(m, "checksum", counted)
|
||||
for _ in range(2):
|
||||
reads.clear()
|
||||
ledger._context(identity, "judge")
|
||||
assert len(reads) == len(plan["inputs"]) + len(unique) == 8
|
||||
assert {name for name, _ in reads} == set(plan["inputs"]) | set(unique)
|
||||
assert sum(size for _, size in reads) == sum(
|
||||
pin["bytes"] for pin in [*plan["inputs"].values(), *unique.values()]
|
||||
)
|
||||
assert sum(size for _, size in reads) < sum(
|
||||
pin["bytes"] for pin in [*plan["inputs"].values(), *(pin for _, pin in old_entries)]
|
||||
)
|
||||
# The previous loop made16 calls/boundary (2 inputs +14 prior artifact entries).
|
||||
# This is a structural count, not a latency or disk-throughput benchmark.
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["missing", "tampered"])
|
||||
def test_cumulative_payload_change_blocks_next_and_completed_resume(cumulative_artifacts, mode):
|
||||
ledger, identity, _, _, calls, _ = cumulative_artifacts
|
||||
path = ledger.root / "copy.pt"
|
||||
if mode == "missing":
|
||||
path.unlink()
|
||||
else:
|
||||
path.write_bytes(b"corrupted despite model.pt remaining valid")
|
||||
before = list(calls)
|
||||
for phase in ("judge", "replay"):
|
||||
with pytest.raises(
|
||||
ValueError, match="(?:Missing regular artifact|Artifact changed): copy.pt"
|
||||
):
|
||||
ledger.execute(identity, phase)
|
||||
assert calls == before
|
||||
assert ledger.status(identity)["phases"][-1]["state"] == "pending"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field,value", [("sha256", "0" * 64), ("bytes", 999)])
|
||||
def test_conflicting_previous_pins_fail_before_any_payload_hash(
|
||||
cumulative_artifacts, monkeypatch, field, value
|
||||
):
|
||||
ledger, identity, _, receipts, calls, _ = cumulative_artifacts
|
||||
conflict = copy.deepcopy(receipts[-1])
|
||||
conflict["artifacts"]["model.pt"][field] = value
|
||||
with ledger.db:
|
||||
ledger.db.execute(
|
||||
"UPDATE learning_phases SET receipt=? WHERE run=? AND name='replay'",
|
||||
(json.dumps(conflict), identity),
|
||||
)
|
||||
reads = []
|
||||
original = m.checksum
|
||||
|
||||
def counted(path):
|
||||
reads.append(path)
|
||||
return original(path)
|
||||
|
||||
monkeypatch.setattr(m, "checksum", counted)
|
||||
before = list(calls)
|
||||
with pytest.raises(ValueError, match="Conflicting previous artifact pins: model.pt"):
|
||||
ledger.execute(identity, "judge")
|
||||
assert not reads and calls == before
|
||||
|
||||
|
||||
def test_previous_payload_modified_during_phase_still_fails_post_verification(cumulative_artifacts):
|
||||
ledger, identity, _, _, calls, runner = cumulative_artifacts
|
||||
|
||||
def corrupt_during_run(root, argv, timeout):
|
||||
if argv[1] == "judge":
|
||||
(root / "model.pt").write_bytes(b"mutated after precheck")
|
||||
# The current verifier honestly reports new bytes; prior receipts still bind old bytes.
|
||||
return runner(root, argv, timeout)
|
||||
|
||||
ledger.runner = corrupt_during_run
|
||||
with pytest.raises(ValueError, match="Artifact changed: model.pt"):
|
||||
ledger.execute(identity, "judge")
|
||||
assert calls.count("judge") == 1
|
||||
assert ledger.status(identity)["phases"][-1]["state"] == "unknown"
|
||||
@@ -0,0 +1,208 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def load_module(name):
|
||||
source = Path(__file__).parents[1] / "simulation/semantic-learning" / f"{name}.py"
|
||||
if not source.exists():
|
||||
source = Path(__file__).with_name(f"{name}.py")
|
||||
spec = importlib.util.spec_from_file_location(name, source)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
m = load_module("linear_refinement")
|
||||
|
||||
|
||||
def tensors():
|
||||
t = pytest.importorskip("torch")
|
||||
x = t.tensor([[-2., 1.], [-1., -1.], [0., 2.], [1., -2.], [2., 1.]], dtype=t.float64)
|
||||
c = t.tensor([[0.4], [-0.2], [0.], [-0.4], [0.2]], dtype=t.float64)
|
||||
y = t.tensor([0, 0, 0, 1, 1])
|
||||
w = t.tensor([1., 2., 0., 3., 1.], dtype=t.float64)
|
||||
return t, x, c, y, w
|
||||
|
||||
|
||||
def test_identity_parameter_count_and_rng_preservation():
|
||||
t = pytest.importorskip("torch")
|
||||
rng = t.random.get_rng_state().clone()
|
||||
a, b = m.network(1), m.network(999)
|
||||
assert t.equal(rng, t.random.get_rng_state())
|
||||
assert sum(p.numel() for p in a.parameters()) == 258
|
||||
assert all(t.equal(p, q) for p, q in zip(a.parameters(), b.parameters(), strict=True))
|
||||
fine, coarse = t.ones(7, 256), t.arange(7).float().reshape(-1, 1)
|
||||
for arm in m.ARMS:
|
||||
assert t.equal(a(fine, coarse, arm), coarse)
|
||||
|
||||
|
||||
def test_predict_native_alignment_chunking_and_ablation():
|
||||
t = pytest.importorskip("torch")
|
||||
feature = load_module("feature_refinement")
|
||||
net = m.network(channels=2)
|
||||
with t.no_grad():
|
||||
net.weight.copy_(t.tensor([[0.1, -0.2, 0.3]]))
|
||||
net.bias.fill_(0.2)
|
||||
fine = t.arange(2 * 3 * 5).float().reshape(1, 2, 3, 5) / 10
|
||||
coarse = t.arange(7 * 9).float().reshape(7, 9) / 10
|
||||
expected = feature.predict(net, fine, coarse, "scene_features", chunk=100)
|
||||
actual = feature.predict(net, fine, coarse, "scene_features", chunk=11)
|
||||
t.testing.assert_close(actual, expected)
|
||||
for k in range(4):
|
||||
rotated = feature.predict(
|
||||
net, t.rot90(fine, k, [-2, -1]), t.rot90(coarse, k), "scene_features", chunk=11,
|
||||
)
|
||||
t.testing.assert_close(t.rot90(rotated, -k), expected, atol=2e-6, rtol=1e-6)
|
||||
a = feature.predict(net, fine, coarse, "coarse_only")
|
||||
b = feature.predict(net, fine * 100, coarse, "coarse_only")
|
||||
assert t.equal(a, b)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arm", ["coarse_only", "scene_features"])
|
||||
def test_fit_stationarity_weight_scale_duplication_and_chunk_invariance(arm):
|
||||
t, x, c, y, w = tensors()
|
||||
a, report = m.fit(x, c, y, w, arm, chunk=2)
|
||||
b, repeated = m.fit(x.repeat(2, 1), c.repeat(2, 1), y.repeat(2), w.repeat(2) * 9, arm)
|
||||
assert report["converged"] and repeated["converged"]
|
||||
assert report["status"] == "converged"
|
||||
assert report["gradient_inf_norm"] <= 1e-4
|
||||
assert report["evaluations"] <= 400
|
||||
assert report["production_eligible"] is False
|
||||
for p, q in zip(a.parameters(), b.parameters(), strict=True):
|
||||
t.testing.assert_close(p, q, atol=1e-4, rtol=1e-4)
|
||||
if arm == "coarse_only":
|
||||
assert t.count_nonzero(a.weight[:, :-1]) == 0
|
||||
|
||||
# Independently recompute the full objective and every parameter gradient.
|
||||
logits = a(x, c, arm)[:, 0]
|
||||
per_point = t.nn.functional.binary_cross_entropy_with_logits(
|
||||
logits, y.double(), reduction="none"
|
||||
)
|
||||
data = (per_point * w).sum() / w.sum()
|
||||
penalty = 0.5 * 0.01 * sum(p.square().sum() for p in a.parameters())
|
||||
objective = data + penalty
|
||||
objective.backward()
|
||||
grad = max(float(p.grad.abs().max()) for p in a.parameters())
|
||||
assert float(data) == pytest.approx(report["data_loss"], abs=1e-12)
|
||||
assert float(penalty) == pytest.approx(report["l2_loss"], abs=1e-12)
|
||||
assert float(objective) == pytest.approx(report["loss"], abs=1e-12)
|
||||
assert grad == pytest.approx(report["gradient_inf_norm"], abs=1e-12)
|
||||
assert grad <= 1e-4
|
||||
|
||||
|
||||
def test_bias_is_regularized_even_for_one_class():
|
||||
t = pytest.importorskip("torch")
|
||||
x, c = t.zeros(8, 2, dtype=t.float64), t.zeros(8, 1, dtype=t.float64)
|
||||
net, report = m.fit(x, c, t.ones(8), t.ones(8, dtype=t.float64))
|
||||
assert report["converged"]
|
||||
assert 0 < float(net.bias) < 10
|
||||
assert report["l2_loss"] == pytest.approx(0.005 * float(net.bias.square()), abs=1e-12)
|
||||
assert abs(float(t.sigmoid(net.bias) - 1 + 0.01 * net.bias)) <= 1e-4
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unknown", [-1, 255, 0.5])
|
||||
@pytest.mark.parametrize("weight", [0., 1.])
|
||||
def test_unknown_rejected_even_at_zero_weight(unknown, weight):
|
||||
t, x, c, y, w = tensors()
|
||||
y = y.double()
|
||||
y[0], w[0] = unknown, weight
|
||||
with pytest.raises(ValueError, match="binary known"):
|
||||
m.fit(x, c, y, w)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
[
|
||||
"fine_shape", "coarse_shape", "target_shape", "weight_shape", "empty", "dtype",
|
||||
"fine_nan", "coarse_inf", "target_nan", "weight_nan", "negative_weight", "zero_sum",
|
||||
"input_gradient", "arm", "chunk",
|
||||
],
|
||||
)
|
||||
def test_input_validation(bad):
|
||||
t, x, c, y, w = tensors()
|
||||
kwargs = {}
|
||||
if bad == "fine_shape":
|
||||
x = x[None]
|
||||
elif bad == "coarse_shape":
|
||||
c = c[:, 0]
|
||||
elif bad == "target_shape":
|
||||
y = y[:-1]
|
||||
elif bad == "weight_shape":
|
||||
w = w[:-1]
|
||||
elif bad == "empty":
|
||||
x, c, y, w = x[:0], c[:0], y[:0], w[:0]
|
||||
elif bad == "dtype":
|
||||
c = c.float()
|
||||
elif bad == "fine_nan":
|
||||
x[0, 0] = float("nan")
|
||||
elif bad == "coarse_inf":
|
||||
c[0] = float("inf")
|
||||
elif bad == "target_nan":
|
||||
y = y.double()
|
||||
y[0] = float("nan")
|
||||
elif bad == "weight_nan":
|
||||
w[0] = float("nan")
|
||||
elif bad == "negative_weight":
|
||||
w[0] = -1
|
||||
elif bad == "zero_sum":
|
||||
w.zero_()
|
||||
elif bad == "input_gradient":
|
||||
x.requires_grad_(True)
|
||||
elif bad == "arm":
|
||||
kwargs["arm"] = "location_specific"
|
||||
else:
|
||||
kwargs["chunk"] = 0
|
||||
with pytest.raises(ValueError):
|
||||
m.fit(x, c, y, w, **kwargs)
|
||||
|
||||
|
||||
def test_no_optimizer_progress_is_technical_stop(monkeypatch):
|
||||
t, x, c, y, w = tensors()
|
||||
real = t.optim.LBFGS
|
||||
|
||||
def stopped(parameters, **kwargs):
|
||||
optimizer = real(parameters, **kwargs)
|
||||
monkeypatch.setattr(optimizer, "step", lambda closure: closure())
|
||||
return optimizer
|
||||
|
||||
monkeypatch.setattr(t.optim, "LBFGS", stopped)
|
||||
_, report = m.fit(x, c, y, w)
|
||||
assert not report["converged"]
|
||||
assert report["status"] == "technical_stop"
|
||||
assert report["stop_reason"] == "stationarity_not_met"
|
||||
|
||||
|
||||
def test_total_timeout_cannot_be_reported_as_convergence(monkeypatch):
|
||||
_, x, c, y, w = tensors()
|
||||
now = iter([0., 121., 121., 121.])
|
||||
monkeypatch.setattr(m.time, "monotonic", lambda: next(now, 121.))
|
||||
net, report = m.fit(x, c, y, w)
|
||||
assert not report["converged"]
|
||||
assert report["stop_reason"] == "fit_timeout"
|
||||
assert report["evaluations"] == 0
|
||||
assert report["gradient_inf_norm"] is None
|
||||
assert all(float(p.abs().sum()) == 0 for p in net.parameters())
|
||||
|
||||
|
||||
def test_line_search_evaluation_budget_is_enforced(monkeypatch):
|
||||
t, x, c, y, w = tensors()
|
||||
real = t.optim.LBFGS
|
||||
monkeypatch.setattr(m, "MAX_EVAL", 3)
|
||||
|
||||
def repeated(parameters, **kwargs):
|
||||
optimizer = real(parameters, **kwargs)
|
||||
|
||||
def step(closure):
|
||||
for _ in range(10):
|
||||
closure()
|
||||
|
||||
monkeypatch.setattr(optimizer, "step", step)
|
||||
return optimizer
|
||||
|
||||
monkeypatch.setattr(t.optim, "LBFGS", repeated)
|
||||
_, report = m.fit(x, c, y, w)
|
||||
assert report["status"] == "technical_stop"
|
||||
assert report["stop_reason"] == "evaluation_limit"
|
||||
assert report["evaluations"] == 2
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Mixed admission rejects identity drift and preserves class mass across folds."""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import mixed_supervision as m
|
||||
|
||||
|
||||
def target_view(target):
|
||||
runs = {"paint": [], "background": [], "unknown": []}
|
||||
for row, col in np.ndindex(target.shape):
|
||||
label = int(target[row, col])
|
||||
if label != 255:
|
||||
runs["paint" if label else "background"].append([row, col, col + 1])
|
||||
return dict(view="top", size=list(target.shape[::-1]), **runs)
|
||||
|
||||
|
||||
def fixtures():
|
||||
records, weights, entries = [], {}, {}
|
||||
for name, group, values in [
|
||||
("a", "g", [[1, 1, 0, 255], [255, 0, 255, 255]]),
|
||||
("b", "g", [[1, 255, 0, 255], [255, 255, 255, 255]]),
|
||||
("c", "h", [[1, 0, 255, 255], [255, 255, 255, 255]]),
|
||||
]:
|
||||
t = np.array(values, dtype=np.uint8)
|
||||
image = dict(
|
||||
sample_id=name,
|
||||
view="top",
|
||||
camera={"size": [4, 2]},
|
||||
rgb={"path": name + "/top.png", "sha256": name * 64},
|
||||
)
|
||||
r = dict(name=name, sample_id=name, group=group, split="train", input=image, target=t)
|
||||
records.append(r)
|
||||
weights[name] = np.where(t == 255, 0, 0.2 if name == "a" else 0.1).astype(np.float32)
|
||||
entries[name] = dict(
|
||||
sample_id=name,
|
||||
physical_group=group,
|
||||
split="train",
|
||||
task="observed_paint",
|
||||
source={"world_sha256": name * 64},
|
||||
inputs=[copy.deepcopy(image)],
|
||||
targets=[target_view(t)],
|
||||
)
|
||||
return records, weights, entries, copy.deepcopy(entries)
|
||||
|
||||
|
||||
def admission(records, new):
|
||||
a = records[0]["target"].copy()
|
||||
a[0, 1] = 255
|
||||
a[1, 0] = 1
|
||||
new["a"]["targets"] = [target_view(a)]
|
||||
b = records[1]["target"].copy()
|
||||
b[1, 0] = 0
|
||||
new["b"]["targets"] = [target_view(b)]
|
||||
|
||||
|
||||
def proof(records, old):
|
||||
value = dict(
|
||||
schema="missioncore.mixed-withdrawals/v1",
|
||||
evidence=[dict(path="archive/review.json", sha256="e" * 64)],
|
||||
records={
|
||||
"a": dict(
|
||||
source=old["a"]["source"],
|
||||
input=records[0]["input"],
|
||||
old_target_sha256=m._sha(records[0]["target"].tobytes()),
|
||||
runs=[[0, 1, 2]],
|
||||
)
|
||||
},
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def kwargs(value):
|
||||
payload = json.dumps(value, sort_keys=True).encode()
|
||||
return dict(withdrawal_bytes=payload, withdrawal_sha256=hashlib.sha256(payload).hexdigest())
|
||||
|
||||
|
||||
def test_mixed_growth_with_exact_withdrawal_and_conserved_group_class_mass():
|
||||
records, weights, old, new = fixtures()
|
||||
admission(records, new)
|
||||
original = copy.deepcopy((records, weights, old, new))
|
||||
out, ww, audit = m.prepare_mixed(records, weights, old, new, **kwargs(proof(records, old)))
|
||||
assert out[0]["target"].tolist() == [[1, 255, 0, 255], [1, 0, 255, 255]]
|
||||
assert out[0]["mixed_added_paint"].sum() == 1
|
||||
assert out[0]["mixed_withdrawn"].sum() == 1
|
||||
assert out[1]["mixed_added_background"].sum() == 1
|
||||
assert audit["records"][0]["withdrawn_paint"] == 1
|
||||
for mass in audit["masses"]:
|
||||
assert mass["after"] == pytest.approx(mass["before"])
|
||||
for label in (0, 1):
|
||||
group_rows = [r for r in out if r["group"] == "g"]
|
||||
amounts = [ww[r["name"]][r["target"] == label].sum() for r in group_rows]
|
||||
assert amounts[0] == pytest.approx(amounts[1])
|
||||
np.testing.assert_array_equal(ww["c"], weights["c"])
|
||||
for r, previous in zip(records, original[0], strict=True):
|
||||
np.testing.assert_array_equal(r["target"], previous["target"])
|
||||
np.testing.assert_array_equal(weights[r["name"]], original[1][r["name"]])
|
||||
assert old == original[2] and new == original[3]
|
||||
assert all(not ww[r["name"]][r["target"] == 255].any() for r in out)
|
||||
|
||||
|
||||
def test_identity_release_is_bit_exact_and_fold_can_use_global_proof():
|
||||
records, weights, old, new = fixtures()
|
||||
out, ww, _ = m.prepare_mixed(records, weights, old, new)
|
||||
for r, n in zip(records, out, strict=True):
|
||||
np.testing.assert_array_equal(r["target"], n["target"])
|
||||
np.testing.assert_array_equal(weights[r["name"]], ww[r["name"]])
|
||||
_, fold_weights, _ = m.prepare_mixed(
|
||||
records[2:],
|
||||
{"c": weights["c"]},
|
||||
{"c": old["c"]},
|
||||
{"c": new["c"]},
|
||||
**kwargs(proof(records, old)),
|
||||
)
|
||||
np.testing.assert_array_equal(fold_weights["c"], weights["c"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"field", ["source", "physical_group", "split", "sample_id", "task", "inputs"]
|
||||
)
|
||||
def test_release_identity_drift_is_rejected(field):
|
||||
records, weights, old, new = fixtures()
|
||||
new["a"][field] = "changed"
|
||||
with pytest.raises(ValueError, match="binding changed"):
|
||||
m.prepare_mixed(records, weights, old, new)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fault",
|
||||
[
|
||||
"missing_proof",
|
||||
"bad_hash",
|
||||
"wrong_source",
|
||||
"wrong_input",
|
||||
"old_hash",
|
||||
"extra",
|
||||
"missing",
|
||||
"duplicate",
|
||||
"outside",
|
||||
"no_evidence",
|
||||
"flip",
|
||||
"cached_target",
|
||||
"unknown_weight",
|
||||
"zero_weight",
|
||||
"nan",
|
||||
"wrong_record",
|
||||
"duplicate_id",
|
||||
],
|
||||
)
|
||||
def test_fail_closed_for_invalid_admission_or_provenance(fault):
|
||||
records, weights, old, new = fixtures()
|
||||
admission(records, new)
|
||||
doc = proof(records, old)
|
||||
p = doc["records"]["a"]
|
||||
if fault == "wrong_source":
|
||||
p["source"] = {}
|
||||
elif fault == "wrong_input":
|
||||
p["input"] = {}
|
||||
elif fault == "old_hash":
|
||||
p["old_target_sha256"] = "0" * 64
|
||||
elif fault == "extra":
|
||||
p["runs"].append([0, 0, 1])
|
||||
elif fault == "missing":
|
||||
p["runs"] = []
|
||||
elif fault == "duplicate":
|
||||
p["runs"].append([0, 1, 2])
|
||||
elif fault == "outside":
|
||||
p["runs"] = [[2, 0, 1]]
|
||||
elif fault == "no_evidence":
|
||||
doc["evidence"] = []
|
||||
elif fault == "flip":
|
||||
t = records[1]["target"].copy()
|
||||
t[0, 0] = 0
|
||||
new["b"]["targets"] = [target_view(t)]
|
||||
elif fault == "cached_target":
|
||||
records[1]["target"][0, 0] = 0
|
||||
elif fault == "unknown_weight":
|
||||
weights["b"][0, 1] = 0.1
|
||||
elif fault == "zero_weight":
|
||||
weights["b"][0, 0] = 0
|
||||
elif fault == "nan":
|
||||
weights["b"][0, 0] = np.nan
|
||||
elif fault == "wrong_record":
|
||||
records[1]["group"] = "g-other"
|
||||
elif fault == "duplicate_id":
|
||||
records[1]["sample_id"] = "a"
|
||||
kw = kwargs(doc)
|
||||
if fault == "missing_proof":
|
||||
kw = {}
|
||||
elif fault == "bad_hash":
|
||||
kw["withdrawal_sha256"] = "0" * 64
|
||||
with pytest.raises(ValueError):
|
||||
m.prepare_mixed(records, weights, old, new, **kw)
|
||||
|
||||
|
||||
def test_withdrawing_last_class_support_cannot_silently_discard_mass():
|
||||
records, weights, old, new = fixtures()
|
||||
records, old, new = records[2:], {"c": old["c"]}, {"c": new["c"]}
|
||||
target = records[0]["target"].copy()
|
||||
target[0, 0] = 255
|
||||
new["c"]["targets"] = [target_view(target)]
|
||||
doc = dict(
|
||||
schema="missioncore.mixed-withdrawals/v1",
|
||||
evidence=[dict(path="review.json", sha256="e" * 64)],
|
||||
records={
|
||||
"c": dict(
|
||||
source=old["c"]["source"],
|
||||
input=records[0]["input"],
|
||||
old_target_sha256=m._sha(records[0]["target"].tobytes()),
|
||||
runs=[[0, 0, 1]],
|
||||
)
|
||||
},
|
||||
)
|
||||
with pytest.raises(ValueError, match="baseline mass and final support"):
|
||||
m.prepare_mixed(records, {"c": weights["c"]}, old, new, **kwargs(doc))
|
||||
|
||||
|
||||
def test_target_view_order_does_not_choose_context_view():
|
||||
records, weights, old, new = fixtures()
|
||||
for entries in (old, new):
|
||||
for entry in entries.values():
|
||||
view = copy.deepcopy(entry["targets"][0])
|
||||
view["view"] = "oblique"
|
||||
entry["targets"].insert(0, view)
|
||||
out, _, _ = m.prepare_mixed(records, weights, old, new)
|
||||
for a, b in zip(records, out, strict=True):
|
||||
np.testing.assert_array_equal(a["target"], b["target"])
|
||||
new["a"]["targets"][-1]["size"] = [8, 1]
|
||||
with pytest.raises(ValueError, match="dimensions differ"):
|
||||
m.prepare_mixed(records, weights, old, new)
|
||||
|
||||
|
||||
def test_new_class_without_baseline_mass_is_rejected():
|
||||
records, weights, old, new = fixtures()
|
||||
records = records[2:]
|
||||
records[0]["target"][0, 0] = 0
|
||||
old = {"c": old["c"]}
|
||||
old["c"]["targets"] = [target_view(records[0]["target"])]
|
||||
new = copy.deepcopy(old)
|
||||
target = records[0]["target"].copy()
|
||||
target[0, 2] = 1
|
||||
new["c"]["targets"] = [target_view(target)]
|
||||
with pytest.raises(ValueError, match="baseline mass and final support"):
|
||||
m.prepare_mixed(records, {"c": weights["c"]}, old, new)
|
||||
|
||||
|
||||
def test_paint_only_addition_preserves_background_weights_exactly():
|
||||
records, weights, old, new = fixtures()
|
||||
target = records[0]["target"].copy()
|
||||
target[1, 0] = 1
|
||||
new["a"]["targets"] = [target_view(target)]
|
||||
out, ww, _ = m.prepare_mixed(records, weights, old, new)
|
||||
for original, updated in zip(records, out, strict=True):
|
||||
mask = updated["target"] == 0
|
||||
np.testing.assert_array_equal(ww[original["name"]][mask], weights[original["name"]][mask])
|
||||
@@ -0,0 +1,260 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def load_module():
|
||||
source = Path(__file__).parents[1] / "simulation/semantic-learning/native_detail.py"
|
||||
if not source.exists():
|
||||
source = Path(__file__).with_name("native_detail.py")
|
||||
spec = importlib.util.spec_from_file_location("native_detail", source)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
# The standalone Worker package keeps native_detail and feature_refinement
|
||||
# together; the repository tests import from their source directory instead.
|
||||
sys.path.insert(0, str(source.parent))
|
||||
try:
|
||||
spec.loader.exec_module(module)
|
||||
finally:
|
||||
sys.path.pop(0)
|
||||
return module
|
||||
|
||||
|
||||
m = load_module()
|
||||
|
||||
|
||||
def fixture():
|
||||
t = pytest.importorskip("torch")
|
||||
fine = t.arange(4 * 2 * 3).float().reshape(1, 4, 2, 3) / 20 - 0.5
|
||||
coarse = t.linspace(-2, 2, 7 * 11).reshape(7, 11)
|
||||
rgb = ((t.arange(3 * 7 * 11) * 17) % 101).float().reshape(1, 3, 7, 11) / 100
|
||||
return t, fine, coarse, rgb
|
||||
|
||||
|
||||
def test_network_shape_identity_seed_and_rng():
|
||||
t, fine, coarse, rgb = fixture()
|
||||
rng = t.random.get_rng_state().clone()
|
||||
default = m.network(5)
|
||||
assert sum(p.numel() for p in default.parameters()) == 25602
|
||||
assert [layer.in_features for layer in default.layers] == [332, 65]
|
||||
assert default.output.in_features == 65
|
||||
a, b = m.network(12, channels=4), m.network(12, channels=4)
|
||||
assert t.equal(rng, t.random.get_rng_state())
|
||||
assert all(t.equal(p, q) for p, q in zip(a.parameters(), b.parameters(), strict=True))
|
||||
for arm in sorted(m.ARMS):
|
||||
got = m.predict(a, fine, coarse, rgb, arm, chunk=9)
|
||||
assert t.equal(got, coarse)
|
||||
|
||||
|
||||
def test_prepare_native_and_lowpass_have_same_shape_and_fixed_center():
|
||||
t = pytest.importorskip("torch")
|
||||
yy, xx = t.meshgrid(t.arange(8), t.arange(10), indexing="ij")
|
||||
checker = ((yy + xx) % 2).float()[None, None].expand(1, 3, -1, -1).clone()
|
||||
native = m.prepare_rgb(checker, (2, 5), "native_rgb")
|
||||
lowpass = m.prepare_rgb(checker, (2, 5), "lowpass_rgb")
|
||||
assert native.shape == lowpass.shape == checker.shape
|
||||
assert t.equal(native, checker * 2 - 1)
|
||||
assert t.equal(lowpass, t.zeros_like(lowpass))
|
||||
assert not t.equal(native, lowpass)
|
||||
for arm in m.ARMS:
|
||||
constant = t.full((1, 3, 6, 8), 0.25)
|
||||
t.testing.assert_close(m.prepare_rgb(constant, (2, 4), arm), constant - 0.75)
|
||||
same_grid = m.prepare_rgb(checker, (8, 10), arm)
|
||||
assert t.equal(same_grid, native)
|
||||
|
||||
|
||||
def test_lowpass_matches_explicit_area_then_bilinear_on_noninteger_grid():
|
||||
t, fine, _, rgb = fixture()
|
||||
low = t.nn.functional.interpolate(rgb, size=fine.shape[-2:], mode="area")
|
||||
expected = t.nn.functional.interpolate(
|
||||
low, size=rgb.shape[-2:], mode="bilinear", align_corners=False
|
||||
)
|
||||
t.testing.assert_close(m.prepare_rgb(rgb, fine.shape[-2:], "lowpass_rgb"), expected * 2 - 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shape", [(6, 8), (1, 1), (1, 4), (4, 1)])
|
||||
def test_patch_rgb_order_centres_and_replicated_borders(shape):
|
||||
t = pytest.importorskip("torch")
|
||||
h, w = shape
|
||||
image = t.arange(3 * h * w).double().reshape(1, 3, h, w) / (3 * h * w)
|
||||
prepared = m.prepare_rgb(image, (1, 1), "native_rgb")
|
||||
indices = t.tensor([0, (h // 2) * w + w // 2, h * w - 1], dtype=t.long)
|
||||
actual = m.sample_patch(prepared, indices)
|
||||
# Independent scalar lookup specifies the patch contract, including corners.
|
||||
expected = []
|
||||
for index in indices.tolist():
|
||||
cy, cx = divmod(index, w)
|
||||
expected.append([
|
||||
prepared[0, channel, min(max(cy + dy, 0), h - 1), min(max(cx + dx, 0), w - 1)]
|
||||
for channel in range(3) for dy in range(-2, 3) for dx in range(-2, 3)
|
||||
])
|
||||
assert t.equal(actual, t.tensor(expected, dtype=t.float64))
|
||||
for channel in range(3):
|
||||
t.testing.assert_close(
|
||||
actual[:, channel * 25 + 12], prepared[0, channel].flatten()[indices]
|
||||
)
|
||||
|
||||
|
||||
def test_rotate_patch_keeps_channels_and_rotates_spatial_axes_only():
|
||||
t = pytest.importorskip("torch")
|
||||
patch = t.arange(75).float().reshape(1, 75) / 75
|
||||
for k in range(4):
|
||||
rotated = m.rotate_patch(patch, k).reshape(1, 3, 5, 5)
|
||||
original = patch.reshape(1, 3, 5, 5)
|
||||
for channel in range(3):
|
||||
assert t.equal(rotated[:, channel], t.rot90(original[:, channel], k, (-2, -1)))
|
||||
assert t.equal(rotated[:, :, 2, 2], original[:, :, 2, 2])
|
||||
repeated = patch
|
||||
for _ in range(4):
|
||||
repeated = m.rotate_patch(repeated, 1)
|
||||
assert t.equal(repeated, patch)
|
||||
for bad in [-1, 4, 1.0, True]:
|
||||
with pytest.raises(ValueError):
|
||||
m.rotate_patch(patch, bad)
|
||||
|
||||
|
||||
def test_sample_points_fine_alignment_coarse_centres_and_empty_indices():
|
||||
t, fine, coarse, rgb = fixture()
|
||||
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
|
||||
indices = t.tensor([0, 4, 20, coarse.numel() - 1], dtype=t.long)
|
||||
ff, cc, pp = m.sample_points(fine, coarse, prepared, indices)
|
||||
expected_fine = t.nn.functional.interpolate(
|
||||
fine, size=coarse.shape, mode="bilinear", align_corners=False
|
||||
)[0].flatten(1).T[indices]
|
||||
t.testing.assert_close(ff, expected_fine, atol=2e-6, rtol=1e-6)
|
||||
assert t.equal(cc[:, 0], coarse.flatten()[indices])
|
||||
assert t.equal(pp, m.sample_patch(prepared, indices))
|
||||
empty = m.sample_points(fine, coarse, prepared, t.empty(0, dtype=t.long))
|
||||
assert [value.shape for value in empty] == [(0, 4), (0, 1), (0, 75)]
|
||||
assert m.sample_patch(prepared, t.empty(0, dtype=t.long)).shape == (0, 75)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arm", ["native_rgb", "lowpass_rgb"])
|
||||
def test_prediction_c4_equivariance_chunking_and_explicit_logit_average(arm):
|
||||
t, fine, coarse, rgb = fixture()
|
||||
net = m.network(8, channels=4, width=8)
|
||||
with t.no_grad():
|
||||
net.output.weight.copy_(t.linspace(-0.2, 0.2, 9).reshape(1, 9))
|
||||
net.output.bias.fill_(0.1)
|
||||
expected = m.predict(net, fine, coarse, rgb, arm, chunk=coarse.numel())
|
||||
assert not t.equal(expected, coarse)
|
||||
for chunk in [1, 13, 200]:
|
||||
actual = m.predict(net, fine, coarse, rgb, arm, chunk=chunk)
|
||||
t.testing.assert_close(actual, expected, atol=2e-6, rtol=1e-6)
|
||||
for k in range(4):
|
||||
actual = m.predict(
|
||||
net, t.rot90(fine, k, (-2, -1)), t.rot90(coarse, k),
|
||||
t.rot90(rgb, k, (-2, -1)), arm, chunk=13,
|
||||
)
|
||||
t.testing.assert_close(t.rot90(actual, -k), expected, atol=3e-6, rtol=1e-6)
|
||||
|
||||
prepared = m.prepare_rgb(rgb, fine.shape[-2:], arm)
|
||||
points, logits, patches = m.sample_points(fine, coarse, prepared, t.arange(coarse.numel()))
|
||||
with t.no_grad():
|
||||
four = [net(points, logits, m.rotate_patch(patches, k)) for k in range(4)]
|
||||
explicit_mean = t.stack(four).mean(0).reshape(coarse.shape)
|
||||
t.testing.assert_close(expected, explicit_mean, atol=2e-6, rtol=1e-6)
|
||||
|
||||
|
||||
def test_head_parameters_get_gradients_but_inputs_stay_frozen():
|
||||
t, fine, coarse, rgb = fixture()
|
||||
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
|
||||
points = m.sample_points(fine, coarse, prepared, t.tensor([0, 11, 44]))
|
||||
net = m.network(3, channels=4, width=8)
|
||||
loss = net(*points).square().mean()
|
||||
loss.backward()
|
||||
assert net.output.weight.grad is not None
|
||||
assert float(net.output.weight.grad.abs().sum()) > 0
|
||||
assert all(
|
||||
not value.requires_grad and value.grad is None for value in (*points, fine, coarse, rgb)
|
||||
)
|
||||
for index in range(3):
|
||||
bad = list(points)
|
||||
bad[index] = bad[index].clone().requires_grad_(True)
|
||||
with pytest.raises(ValueError, match="frozen"):
|
||||
net(*bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["fine_channels", "coarse_shape", "patch_shape", "patch_nan"])
|
||||
def test_head_rejects_invalid_point_shapes_and_nonfinite_patches(bad):
|
||||
t, fine, coarse, rgb = fixture()
|
||||
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
|
||||
ff, cc, pp = m.sample_points(fine, coarse, prepared, t.tensor([0, 1]))
|
||||
if bad == "fine_channels":
|
||||
ff = ff[:, :-1]
|
||||
elif bad == "coarse_shape":
|
||||
cc = cc[:, 0]
|
||||
elif bad == "patch_shape":
|
||||
pp = pp[:, :-1]
|
||||
else:
|
||||
pp[0, 0] = float("nan")
|
||||
with pytest.raises(ValueError):
|
||||
m.network(1, channels=4, width=8)(ff, cc, pp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [
|
||||
"rgb_shape", "rgb_negative", "rgb_above_one", "rgb_nan", "rgb_dtype", "rgb_gradient",
|
||||
"fine_shape", "fine_nan", "fine_gradient", "coarse_shape", "coarse_inf",
|
||||
"coarse_gradient", "dtype_mismatch", "arm", "chunk",
|
||||
])
|
||||
def test_predict_rejects_invalid_maps(bad):
|
||||
t, fine, coarse, rgb = fixture()
|
||||
net = m.network(1, channels=4, width=8)
|
||||
arm, chunk = "native_rgb", 9
|
||||
if bad == "rgb_shape":
|
||||
rgb = rgb[:, :2]
|
||||
elif bad == "rgb_negative":
|
||||
rgb[0, 0, 0, 0] = -0.1
|
||||
elif bad == "rgb_above_one":
|
||||
rgb[0, 0, 0, 0] = 1.1
|
||||
elif bad == "rgb_nan":
|
||||
rgb[0, 0, 0, 0] = float("nan")
|
||||
elif bad == "rgb_dtype":
|
||||
rgb = (rgb * 255).to(t.uint8)
|
||||
elif bad == "rgb_gradient":
|
||||
rgb.requires_grad_(True)
|
||||
elif bad == "fine_shape":
|
||||
fine = fine[0]
|
||||
elif bad == "fine_nan":
|
||||
fine[0, 0, 0, 0] = float("nan")
|
||||
elif bad == "fine_gradient":
|
||||
fine.requires_grad_(True)
|
||||
elif bad == "coarse_shape":
|
||||
coarse = coarse[:, :-1]
|
||||
elif bad == "coarse_inf":
|
||||
coarse[0, 0] = float("inf")
|
||||
elif bad == "coarse_gradient":
|
||||
coarse.requires_grad_(True)
|
||||
elif bad == "dtype_mismatch":
|
||||
coarse = coarse.double()
|
||||
elif bad == "arm":
|
||||
arm = "scene_specific"
|
||||
else:
|
||||
chunk = 0
|
||||
with pytest.raises(ValueError):
|
||||
m.predict(net, fine, coarse, rgb, arm, chunk)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["negative", "outside", "dtype", "shape"])
|
||||
def test_patch_rejects_invalid_native_indices(bad):
|
||||
t, fine, coarse, rgb = fixture()
|
||||
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
|
||||
indices = t.tensor([0], dtype=t.long)
|
||||
if bad == "negative":
|
||||
indices[0] = -1
|
||||
elif bad == "outside":
|
||||
indices[0] = coarse.numel()
|
||||
elif bad == "dtype":
|
||||
indices = indices.float()
|
||||
else:
|
||||
indices = indices[None]
|
||||
with pytest.raises(ValueError):
|
||||
m.sample_patch(prepared, indices)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shape", [(0, 1), (2,), (2.0, 3), (True, 2), (8, 2)])
|
||||
def test_prepare_rejects_invalid_or_upsampling_feature_grid(shape):
|
||||
_, _, _, rgb = fixture()
|
||||
with pytest.raises(ValueError):
|
||||
m.prepare_rgb(rgb, shape, "lowpass_rgb")
|
||||
@@ -0,0 +1,66 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
p = Path(__file__).resolve().parents[1]/"simulation/semantic-learning/native_sliding.py"
|
||||
s = importlib.util.spec_from_file_location("native_sliding", p)
|
||||
m = importlib.util.module_from_spec(s)
|
||||
s.loader.exec_module(m)
|
||||
|
||||
|
||||
def test_native_placement_and_irregular_last_tiles():
|
||||
rgb = np.zeros((5, 7, 3), np.uint8)
|
||||
rgb[:, :, 0] = np.arange(35).reshape(5, 7)
|
||||
out, meta = m.sliding_logits(rgb, lambda a: np.stack([a[:, :, 0], a[:, :, 0]]).astype(float),
|
||||
tile=4, stride=2)
|
||||
np.testing.assert_array_equal(out[0], rgb[:, :, 0])
|
||||
assert meta["tiles"] == 6 and meta["minimum_overlap"] == 1
|
||||
|
||||
|
||||
def test_logits_uniformly_average_overlaps_before_activation():
|
||||
rgb = np.zeros((5, 7, 3), np.uint8)
|
||||
rgb[:, :, 0] = np.arange(7)
|
||||
out, _ = m.sliding_logits(rgb, lambda a: np.full((2, 4, 4), a[0, 0, 0], np.float32),
|
||||
tile=4, stride=2)
|
||||
np.testing.assert_allclose(out[0], np.tile([0, 0, 1, 5/3, 2.5, 2.5, 3], (5, 1)))
|
||||
|
||||
|
||||
def test_small_image_padding_does_not_change_native_extent():
|
||||
rgb = np.full((2, 3, 3), 7, np.uint8)
|
||||
def predict(a):
|
||||
assert a.shape == (4, 4, 3)
|
||||
assert not a[2:].any() and not a[:, 3:].any()
|
||||
return np.stack([a[:, :, 0], a[:, :, 0]]).astype(np.float32)
|
||||
out, meta = m.sliding_logits(rgb, predict, tile=4, stride=2)
|
||||
assert out.shape == (2, 2, 3) and (out == 7).all() and meta["tiles"] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("output", [np.full((2, 4, 4), np.nan), np.zeros((2, 3, 4))])
|
||||
def test_bad_prediction_refused(output):
|
||||
with pytest.raises(ValueError, match="finite native"):
|
||||
m.sliding_logits(np.zeros((4, 4, 3), np.uint8), lambda _: output, tile=4, stride=2)
|
||||
|
||||
|
||||
def test_resource_or_stride_rejection_before_predictor():
|
||||
def fail(_):
|
||||
raise AssertionError("Must reject before inference")
|
||||
a = np.zeros((5, 7, 3), np.uint8)
|
||||
for options in [dict(max_pixels=4), dict(tile=4, stride=2, max_tiles=1),
|
||||
dict(tile=4, stride=5)]:
|
||||
with pytest.raises(ValueError):
|
||||
m.sliding_logits(a, fail, **options)
|
||||
|
||||
|
||||
def test_declared_1024_recipe_has_nine_native_tiles():
|
||||
assert m.starts(1024, 512, 256) == [0, 256, 512]
|
||||
|
||||
|
||||
def test_oversized_tile_and_grid_rejected_before_allocation():
|
||||
def fail(_):
|
||||
raise AssertionError("Must not run predictor")
|
||||
with pytest.raises(ValueError, match="Tile working budget"):
|
||||
m.sliding_logits(np.zeros((2, 3, 3), np.uint8), fail, tile=100000, stride=256)
|
||||
with pytest.raises(ValueError, match="Tile grid budget"):
|
||||
m.starts(1000000, 2, 1, limit=256)
|
||||
@@ -0,0 +1,116 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
from nested_calibration import calibrate_inner, nested_folds
|
||||
|
||||
GROUPS = ["a", "b", "c", "d"]
|
||||
|
||||
|
||||
def rows():
|
||||
out = []
|
||||
for p in nested_folds(GROUPS):
|
||||
if p["outer"] != "a":
|
||||
continue
|
||||
out.append(
|
||||
dict(
|
||||
group=p["inner"],
|
||||
training_groups=p["training_groups"],
|
||||
initialization_groups=p["training_groups"],
|
||||
split="train",
|
||||
sample_ids=[p["inner"]],
|
||||
old=np.array([2.0, -1.0, -2.0, 99.0]),
|
||||
new=np.array([1.0, -2.0, -3.0, 100.0]),
|
||||
paint=np.array([True, False, False, False]),
|
||||
original_bg=np.array([False, True, False, False]),
|
||||
added_bg=np.array([False, False, True, False]),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_nested_folds_no_leakage_and_reusable_fit_sets():
|
||||
plans = nested_folds(GROUPS)
|
||||
assert len(plans) == 12
|
||||
assert len({tuple(p["training_groups"]) for p in plans}) == 6
|
||||
for p in plans:
|
||||
assert set(p["training_groups"]) == set(GROUPS) - {p["outer"], p["inner"]}
|
||||
|
||||
|
||||
def test_common_threshold_ties_and_unknown_excluded():
|
||||
rs = rows()
|
||||
rs[0]["new"] = np.array([1.0, 1.0, -3.0, 100.0])
|
||||
result = calibrate_inner(rs, "a", GROUPS)
|
||||
assert result["new"]["threshold"] is None
|
||||
assert result["new"]["counts"]["paint"] == 0
|
||||
assert result["old"]["counts"]["paint"] == 3
|
||||
|
||||
|
||||
def test_uniform_shift_changes_threshold_not_predictions():
|
||||
rs = rows()
|
||||
for r in rs:
|
||||
r["new"] = r["old"] - 4
|
||||
out = calibrate_inner(rs, "a", GROUPS)
|
||||
assert out["new"]["threshold"] == out["old"]["threshold"] - 4
|
||||
assert out["new"]["counts"] == out["old"]["counts"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["training_groups", "initialization_groups"])
|
||||
def test_excluded_street_in_fit_or_normalization_rejected(field):
|
||||
rs = rows()
|
||||
rs[0][field] = ["a", "c"]
|
||||
with pytest.raises(ValueError, match="exclude both"):
|
||||
calibrate_inner(rs, "a", GROUPS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ["missing", "duplicate", "outer", "control", "duplicate_id"])
|
||||
def test_bad_calibration_membership_rejected(mutation):
|
||||
rs = rows()
|
||||
if mutation == "missing":
|
||||
rs.pop()
|
||||
elif mutation == "duplicate":
|
||||
rs[1] = rs[0]
|
||||
elif mutation == "outer":
|
||||
rs[0]["group"] = "a"
|
||||
elif mutation == "control":
|
||||
rs[0]["split"] = "regression"
|
||||
else:
|
||||
rs[1]["sample_ids"] = rs[0]["sample_ids"]
|
||||
with pytest.raises(ValueError):
|
||||
calibrate_inner(rs, "a", GROUPS)
|
||||
|
||||
|
||||
def test_exact_threshold_matches_independent_bruteforce():
|
||||
rng = np.random.default_rng(123)
|
||||
for _ in range(30):
|
||||
rs = rows()
|
||||
for r in rs:
|
||||
r["old"] = rng.integers(-4, 5, 4).astype(float)
|
||||
r["new"] = rng.integers(-4, 5, 4).astype(float)
|
||||
out = calibrate_inner(rs, "a", GROUPS)
|
||||
for origin in ["old", "new"]:
|
||||
candidates = sorted(
|
||||
{np.inf} | {float(v) for r in rs for v in r[origin][:3]}, reverse=True
|
||||
)
|
||||
valid = [
|
||||
t
|
||||
for t in candidates
|
||||
if all(
|
||||
int(np.count_nonzero((r[origin] >= t) & r[k]))
|
||||
<= int(np.count_nonzero((r["old"] >= 0) & r[k]))
|
||||
for r in rs
|
||||
for k in ["original_bg", "added_bg"]
|
||||
)
|
||||
]
|
||||
expected = valid[-1]
|
||||
assert out[origin]["threshold"] == (None if np.isinf(expected) else expected)
|
||||
|
||||
|
||||
def test_invalid_masks_rejected():
|
||||
rs = rows()
|
||||
rs[0]["added_bg"] = rs[0]["paint"]
|
||||
with pytest.raises(ValueError):
|
||||
calibrate_inner(rs, "a", GROUPS)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Safety and scientific-isolation checks for the offline assembly study."""
|
||||
|
||||
import copy
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
np = pytest.importorskip("numpy")
|
||||
pytest.importorskip("cv2")
|
||||
pytest.importorskip("shapely")
|
||||
pytest.importorskip("scipy")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for directory in [
|
||||
"simulation/semantic-learning",
|
||||
"simulation/urban-plan-research/systematic",
|
||||
"simulation/urban-plan-research/marking_pass",
|
||||
]:
|
||||
sys.path.insert(0, str(ROOT / directory))
|
||||
from shapely.geometry import box, mapping, shape # noqa: E402
|
||||
from shapely.ops import unary_union # noqa: E402
|
||||
|
||||
study = importlib.import_module("object_assembly_study")
|
||||
|
||||
|
||||
def policy():
|
||||
return dict(
|
||||
mpp=12 / 512,
|
||||
min_length=0.35,
|
||||
max_length=12,
|
||||
min_width=0.045,
|
||||
max_width=1.2,
|
||||
min_aspect=2,
|
||||
min_fill=0.4,
|
||||
max_pair_angle_deg=6,
|
||||
max_pair_lateral_fraction=0.25,
|
||||
max_pair_width_ratio=1.8,
|
||||
max_join_gap=0.15,
|
||||
max_group=12,
|
||||
min_group_fill=0.55,
|
||||
min_total_weak_paint=0.85,
|
||||
min_added_weak_paint=0.9,
|
||||
min_physical_valid=0.97,
|
||||
)
|
||||
|
||||
|
||||
def candidate(poly, name, value=1):
|
||||
return dict(id=name, geometry=mapping(poly), features=[value] * 22, fixed_admitted=True)
|
||||
|
||||
|
||||
def test_supported_bridge_requires_observation_and_physical_validity():
|
||||
source = unary_union([box(100, 100, 150, 110), box(154, 100, 204, 110)])
|
||||
valid = np.ones((512, 512), bool)
|
||||
weak = valid.copy()
|
||||
fitted, verdict = study.supported_envelope(source, weak, valid, policy())
|
||||
assert verdict == "supported"
|
||||
assert fitted.bounds == source.bounds
|
||||
weak[100:111, 151:154] = False
|
||||
assert study.supported_envelope(source, weak, valid, policy())[1] == "added_paint"
|
||||
valid[100:111, 149:155] = False
|
||||
assert study.supported_envelope(source, np.ones_like(valid), valid, policy())[1] == "physical"
|
||||
|
||||
|
||||
def test_exact_union_preserves_holes_and_original_candidates():
|
||||
p = box(100, 100, 180, 110).difference(box(130, 102, 140, 108))
|
||||
q = box(160, 100, 204, 110)
|
||||
original = [candidate(p, "p"), candidate(q, "q")]
|
||||
snapshot = copy.deepcopy(original)
|
||||
rgb = np.full((512, 512, 3), 180, np.uint8)
|
||||
fields = {
|
||||
k: np.zeros((512, 512), np.float32)
|
||||
for k in ["vehicle", "road", "roadway", "sidewalk", "road marking", "crosswalk"]
|
||||
}
|
||||
fields["alpha"] = np.ones((512, 512), np.float32)
|
||||
out, _ = study.assemble(original, rgb, fields, policy())
|
||||
unions = [
|
||||
shape(c["geometry"]) for c in out if c.get("properties", {}).get("kind") == "exact_union"
|
||||
]
|
||||
assert len(unions) == 1
|
||||
assert unions[0].symmetric_difference(p.union(q)).area < 1e-8
|
||||
assert len(unions[0].interiors) == 1
|
||||
assert original == snapshot
|
||||
assert [c["id"] for c in out[:2]] == ["p", "q"]
|
||||
|
||||
|
||||
def test_adjacent_crosswalk_bars_are_not_joined():
|
||||
p, q = box(100, 100, 300, 110), box(100, 116, 300, 126)
|
||||
assert not study.pair_allowed(
|
||||
p, q, study.rectangle(p, 12 / 512), study.rectangle(q, 12 / 512), policy()
|
||||
)
|
||||
|
||||
|
||||
def test_merged_reference_objects_are_counted_even_with_one_match():
|
||||
p, q = box(0, 0, 10, 100), box(12, 0, 22, 100)
|
||||
review = {"objects": [dict(geometry=mapping(t), complete=True) for t in [p, q]]}
|
||||
assert study.merged_count([candidate(p.union(q).convex_hull, "bad")], review) == 1
|
||||
assert study.merged_count([candidate(p, "p"), candidate(q, "q")], review) == 0
|
||||
|
||||
|
||||
def test_control_geometry_and_labels_cannot_change_fit_or_selection():
|
||||
records, review = [], {}
|
||||
for split in ["train", "validation", "heldout"]:
|
||||
cs = [
|
||||
candidate(box(10 + i * 20, 10, 20 + i * 20, 30), str(i), float(i % 2)) for i in range(6)
|
||||
]
|
||||
variants = {
|
||||
k: copy.deepcopy(cs) for k in ["retained_on", "retained_off", "hard_off", "hard_on"]
|
||||
}
|
||||
records.append(dict(id=split, split=split, variants=variants))
|
||||
review[split] = dict(
|
||||
objects=[
|
||||
dict(id=str(i), family="stripe", complete=True, geometry=cs[i]["geometry"])
|
||||
for i in [1, 3, 5]
|
||||
],
|
||||
negative=[[(0, 0), (200, 0), (200, 100), (0, 100)]],
|
||||
)
|
||||
first = study.fit_models(records, review, [0.1, 0.5, 0.9])
|
||||
records[-1]["variants"] = {"unreadable": "never accessed"}
|
||||
review["heldout"] = {"corrupted": True}
|
||||
second = study.fit_models(records, review, [0.1, 0.5, 0.9])
|
||||
assert first == second
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Focused checks for the offline object study and opt-in proposal policy."""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
np = pytest.importorskip("numpy")
|
||||
cv2 = pytest.importorskip("cv2")
|
||||
pytest.importorskip("shapely")
|
||||
pytest.importorskip("scipy")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for path in [
|
||||
ROOT / "simulation/semantic-learning",
|
||||
ROOT / "simulation/urban-plan-research/systematic",
|
||||
ROOT / "simulation/urban-plan-research/marking_pass",
|
||||
]:
|
||||
sys.path.insert(0, str(path))
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"object_study_test", ROOT / "simulation/semantic-learning/object_proposal_study.py"
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
from shapely.geometry import box, mapping # noqa: E402
|
||||
|
||||
|
||||
def candidate(poly, **kw):
|
||||
return dict(geometry=mapping(poly), **kw)
|
||||
|
||||
|
||||
def test_unknown_is_never_a_negative():
|
||||
review = dict(
|
||||
objects=[dict(geometry=mapping(box(0, 0, 1, 1)), complete=True, id="p", family="stripe")],
|
||||
negative=[[(3, 3), (5, 3), (5, 5), (3, 5)]],
|
||||
)
|
||||
cs = [candidate(box(0, 0, 1, 1)), candidate(box(3.2, 3.2, 4, 4)), candidate(box(8, 8, 9, 9))]
|
||||
assert m.labels(cs, review).tolist() == [1, 0, -1]
|
||||
|
||||
|
||||
def test_one_proposal_cannot_recall_two_objects():
|
||||
review = dict(
|
||||
objects=[
|
||||
dict(geometry=mapping(box(0, 0, 1, 1)), complete=True, id=str(i), family="stripe")
|
||||
for i in range(2)
|
||||
],
|
||||
negative=[],
|
||||
)
|
||||
assert m.matched([candidate(box(0, 0, 1, 1))], review)["found"] == 1
|
||||
|
||||
|
||||
def test_heldout_cannot_change_model_or_selection():
|
||||
review, records = {}, []
|
||||
for split in ["train", "validation", "heldout"]:
|
||||
objects = [
|
||||
dict(
|
||||
geometry=mapping(box(i * 3, 0, i * 3 + 1, 1)),
|
||||
complete=True,
|
||||
id=str(i),
|
||||
family="stripe",
|
||||
)
|
||||
for i in range(2)
|
||||
]
|
||||
review[split] = dict(objects=objects, negative=[[(0, 3), (6, 3), (6, 6), (0, 6)]])
|
||||
cs = [
|
||||
candidate(box(i * 3, 0, i * 3 + 1, 1), features=[1 + i * 0.1] * 19, fixed_admitted=True)
|
||||
for i in range(2)
|
||||
]
|
||||
cs += [
|
||||
candidate(
|
||||
box(i * 3, 4, i * 3 + 1, 5), features=[-1 - i * 0.1] * 19, fixed_admitted=False
|
||||
)
|
||||
for i in range(2)
|
||||
]
|
||||
records.append(dict(id=split, split=split, variants=dict(hard=cs, retained=cs)))
|
||||
a = m.fit_models(records, review, [0.1, 0.5, 0.9])
|
||||
review["heldout"] = None
|
||||
b = m.fit_models(records, review, [0.1, 0.5, 0.9])
|
||||
assert a == b
|
||||
|
||||
|
||||
def test_retaining_context_does_not_bypass_physical_validity():
|
||||
image = np.full((512, 512, 3), 45, np.uint8)
|
||||
image[245:253, 100:400] = 210
|
||||
zero = np.zeros((512, 512), np.float32)
|
||||
g = dict(
|
||||
view=np.array([[1, 0, 0, -6], [0, -1, 0, 6], [0, 0, -1, 10], [0, 0, 0, 1]], float),
|
||||
intrinsics=np.array([[100, 0, 600], [0, 100, 600], [0, 0, 1]], float),
|
||||
)
|
||||
args = (
|
||||
image,
|
||||
zero,
|
||||
g,
|
||||
zero,
|
||||
zero,
|
||||
np.zeros((120, 120), bool),
|
||||
[0, 0],
|
||||
[12, 12],
|
||||
{"id": "test"},
|
||||
np.full((120, 120), 100.0),
|
||||
)
|
||||
assert m.collect(*args, span_m=12) == ([], [])
|
||||
assert m.collect(*args, span_m=12, retain_uncertain=True)[0]
|
||||
assert m.collect(*args, span_m=12, retain_uncertain=True, valid=zero) == ([], [])
|
||||
with pytest.raises(ValueError):
|
||||
m.collect(*args, span_m=0)
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Checkable partial-support paths; no implicit topology through unknown/exterior."""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"topology_test", Path(__file__).parents[1] / "simulation/semantic-learning/observed_topology.py"
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def pair():
|
||||
t = np.zeros((5, 7), np.uint8)
|
||||
left, right, gap = (np.zeros(t.shape, bool) for _ in range(3))
|
||||
left[2, 1] = right[2, 5] = True
|
||||
gap[2, 2:5] = True
|
||||
t[left | right] = 1
|
||||
p = np.zeros(t.shape, np.float32)
|
||||
p[2, 1:6] = 1
|
||||
return p, t, dict(left=left, right=right), [dict(left="left", right="right", gap=gap)]
|
||||
|
||||
|
||||
def run(args, **kw):
|
||||
return m.audit_topology(
|
||||
*args, roi=kw.pop("roi", [0, 0, 7, 5]), connectivity=kw.pop("connectivity", 4), **kw
|
||||
)
|
||||
|
||||
|
||||
def test_confirmed_bridge_with_unknown_bypass_is_still_known_witness():
|
||||
args = pair()
|
||||
p, t, _, _ = args
|
||||
t[1, 1:6] = 255
|
||||
p[1, 1:6] = 1
|
||||
before = [x.copy() for x in (p, t)]
|
||||
result = run(args)
|
||||
row = result["relations"][0]
|
||||
assert row["status"] == "confirmed_known_support_bridge"
|
||||
assert row["witness"] == [[x, 2] for x in range(1, 6)]
|
||||
assert row["witness_unknown_pixels"] == 0
|
||||
assert not row["full_object_merge_assessed"]
|
||||
assert np.array_equal(p, before[0]) and np.array_equal(t, before[1])
|
||||
json.dumps(result) # Public result must be plain JSON data.
|
||||
|
||||
|
||||
def test_unknown_connection_requires_predicted_paint_on_unknown():
|
||||
args = pair()
|
||||
p, t, _, rel = args
|
||||
t[2, 3] = 255
|
||||
rel[0]["gap"][2, 3] = False
|
||||
row = run(args)["relations"][0]
|
||||
assert row["status"] == "indeterminate_unknown_connection"
|
||||
assert row["witness_unknown_pixels"] == 1
|
||||
p[2, 3] = 0
|
||||
assert run(args)["relations"][0]["status"] == "no_connection_within_reviewed_corridor"
|
||||
|
||||
|
||||
def test_missing_endpoint_never_proves_separation():
|
||||
args = pair()
|
||||
args[0][2, 1] = 0
|
||||
result = run(args)
|
||||
assert result["relations"][0]["status"] == "unassessed_missing_predicted_endpoint"
|
||||
assert result["cores"][0]["fully_missed_original_components"] == 1
|
||||
|
||||
|
||||
def test_exterior_bypass_is_not_an_inside_roi_connection():
|
||||
args = pair()
|
||||
p, t, _, rel = args
|
||||
p[2, 3] = 0
|
||||
p[1, 1:6] = 1
|
||||
t[1, 1:6] = 255
|
||||
row = run(args, roi=[0, 2, 7, 3])["relations"][0]
|
||||
assert row["status"] == "no_connection_within_reviewed_corridor"
|
||||
assert row["exterior_connection_assessed"] is False
|
||||
|
||||
|
||||
def test_diagonal_is_explicitly_four_vs_eight_connectivity():
|
||||
p, t, cores, relations = pair()
|
||||
t[:] = 0
|
||||
p[:] = 0
|
||||
for mask in cores.values():
|
||||
mask[:] = False
|
||||
cores["left"][1, 1] = cores["right"][3, 3] = True
|
||||
t[cores["left"] | cores["right"]] = 1
|
||||
relations[0]["gap"][:] = False
|
||||
relations[0]["gap"][2, 2] = True
|
||||
p[1, 1] = p[2, 2] = p[3, 3] = 1
|
||||
assert run((p, t, cores, relations), connectivity=4)["relations"][0]["witness"] is None
|
||||
assert (
|
||||
run((p, t, cores, relations), connectivity=8)["relations"][0]["status"]
|
||||
== "confirmed_known_support_bridge"
|
||||
)
|
||||
|
||||
|
||||
def test_core_adjacency_without_background_is_not_false_bridge():
|
||||
p, t, cores, relations = pair()
|
||||
cores["right"][:] = False
|
||||
cores["right"][2, 2] = True
|
||||
t[2, 5] = 0
|
||||
t[2, 2] = 1
|
||||
relations[0]["gap"][2, 2] = False
|
||||
assert (
|
||||
run((p, t, cores, relations))["relations"][0]["status"]
|
||||
== "unassessed_core_adjacency_without_background"
|
||||
)
|
||||
|
||||
|
||||
def test_fragmentation_is_per_original_known_component():
|
||||
t = np.zeros((5, 7), np.uint8)
|
||||
t[2, 1:6] = 1
|
||||
p = (t == 1).astype(np.float32)
|
||||
p[2, 3] = 0
|
||||
core = t == 1
|
||||
result = run((p, t, {"line": core}, []))["cores"][0]
|
||||
assert result["fragmented_original_components"] == 1
|
||||
assert result["known_core_fragmentation_witness"] == [[x, 2] for x in range(2, 5)]
|
||||
assert result["full_object_split_assessed"] is False
|
||||
t[2, 3] = 255
|
||||
core[2, 3] = False
|
||||
row = run((p, t, {"line": core}, []))["cores"][0]
|
||||
assert row["original_components"] == 2 and row["recovered_components"] == 2
|
||||
assert row["fragmented_original_components"] == 0
|
||||
p[:] = 0
|
||||
row = run((p, t, {"line": core}, []))["cores"][0]
|
||||
assert row["fully_missed_original_components"] == 2
|
||||
assert row["known_core_fragmentation_witness"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
"nan",
|
||||
"range",
|
||||
"shape",
|
||||
"target",
|
||||
"core_unknown",
|
||||
"gap_paint",
|
||||
"overlap",
|
||||
"outside",
|
||||
"duplicate",
|
||||
],
|
||||
)
|
||||
def test_invalid_support_rejected(error):
|
||||
p, t, cores, relations = pair()
|
||||
kwargs = {}
|
||||
if error == "nan":
|
||||
p[0, 0] = np.nan
|
||||
elif error == "range":
|
||||
p[0, 0] = 1.1
|
||||
elif error == "shape":
|
||||
p = p[:-1]
|
||||
elif error == "target":
|
||||
t = t.astype(np.int64)
|
||||
elif error == "core_unknown":
|
||||
t[2, 1] = 255
|
||||
elif error == "gap_paint":
|
||||
relations[0]["gap"][2, 1] = True
|
||||
elif error == "overlap":
|
||||
cores["right"][2, 1] = True
|
||||
elif error == "outside":
|
||||
kwargs["roi"] = [0, 0, 4, 5]
|
||||
elif error == "duplicate":
|
||||
relations *= 2
|
||||
with pytest.raises(ValueError):
|
||||
run((p, t, cores, relations), **kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs", [dict(max_nodes=1), dict(max_path=2), dict(connectivity=6), dict(roi=[0, 0, 8, 5])]
|
||||
)
|
||||
def test_bounds_refuse_without_truncated_confirmed_witness(kwargs):
|
||||
with pytest.raises(ValueError):
|
||||
run(pair(), **kwargs)
|
||||
|
||||
|
||||
def test_many_original_components_do_not_overflow_int32_pair_ids():
|
||||
y, x = np.indices((384, 384))
|
||||
core = (x + y) % 2 == 0
|
||||
target = core.astype(np.uint8)
|
||||
result = m.audit_topology(
|
||||
target.astype(np.float32), target, {"many": core}, [], roi=[0, 0, 384, 384], connectivity=4
|
||||
)
|
||||
row = result["cores"][0]
|
||||
assert row["original_components"] == row["recovered_components"] == 73728
|
||||
assert row["fragmented_original_components"] == row["fully_missed_original_components"] == 0
|
||||
|
||||
|
||||
def test_outside_core_bypass_does_not_erase_local_fragmentation():
|
||||
target = np.zeros((5, 7), np.uint8)
|
||||
target[2, 1:6] = 1
|
||||
core = target == 1
|
||||
probability = core.astype(np.float32)
|
||||
probability[2, 3] = 0 # A genuine FN cuts the recovered known-positive core.
|
||||
probability[1, 1:6] = 1 # Predicted paint reconnects it through known BG.
|
||||
bypass = [(1, 2), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (5, 2)]
|
||||
assert all(probability[y, x] == 1 for x, y in bypass)
|
||||
row = run((probability, target, {"line": core}, []))["cores"][0]
|
||||
assert row["original_components"] == 1 and row["recovered_components"] == 2
|
||||
assert row["fragmented_original_components"] == 1
|
||||
assert row["full_object_split_assessed"] is False
|
||||
witness = row["known_core_fragmentation_witness"]
|
||||
assert [3, 2] in witness and all(core[y, x] for x, y in witness)
|
||||
@@ -0,0 +1,73 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
p = Path(__file__).resolve().parents[1]/"simulation/semantic-learning/paint_comparison.py"
|
||||
s = importlib.util.spec_from_file_location("paint_comparison", p)
|
||||
m = importlib.util.module_from_spec(s)
|
||||
s.loader.exec_module(m)
|
||||
|
||||
|
||||
def fixture():
|
||||
t = np.zeros((12, 16), np.uint8)
|
||||
t[:, :2] = 255
|
||||
objs = []
|
||||
for i, x in enumerate([3, 10]):
|
||||
t[2:10, x:x+3] = 1
|
||||
objs.append(dict(id=str(i), outline_native_pixels=[[x,2],[x+2,2],[x+2,9],[x,9]],
|
||||
final_paint_pixels=24, kind="observed_crosswalk_bar",
|
||||
semantic_group="one", visibility="complete_in_view"))
|
||||
return t, objs
|
||||
|
||||
|
||||
def test_unknown_does_not_change_errors_or_create_instance_split():
|
||||
t, objs = fixture()
|
||||
t[5, 3:6] = 255
|
||||
objs[0]["final_paint_pixels"] -= 3
|
||||
a = (t == 1).astype(float)
|
||||
before = m.score(a, t, objs)
|
||||
a[t == 255] = 1
|
||||
after = m.score(a, t, objs)
|
||||
for key in ["tp", "fn", "fp", "tn", "observations", "gaps"]:
|
||||
assert before[key] == after[key]
|
||||
assert after["fn"] == after["fp"] == 0
|
||||
assert "instance_merge_split" in after["not_assessed"]
|
||||
|
||||
|
||||
def test_gap_is_known_background_only_and_not_merge_claim():
|
||||
t, objs = fixture()
|
||||
t[5, 6:10] = 255
|
||||
p = np.ones_like(t, float)
|
||||
got = m.score(p, t, objs)
|
||||
assert got["gaps"][0]["background_pixels"] == 28
|
||||
assert got["gaps"][0]["fp"] == 28
|
||||
assert "instance_merge_split" in got["not_assessed"]
|
||||
|
||||
|
||||
def test_partial_line_unknown_gap_not_assessed():
|
||||
t, objs = fixture()
|
||||
for o in objs:
|
||||
o["kind"] = "observed_line_fragment"
|
||||
assert not m.score((t == 1).astype(float), t, objs)["gaps"]
|
||||
|
||||
|
||||
def test_corrupt_core_or_native_prediction_rejected():
|
||||
t, objs = fixture()
|
||||
objs[0]["final_paint_pixels"] += 1
|
||||
with pytest.raises(ValueError):
|
||||
m.score(np.zeros_like(t, float), t, objs)
|
||||
with pytest.raises(ValueError):
|
||||
m.score(np.zeros((2, 2)), t, [])
|
||||
with pytest.raises(ValueError):
|
||||
m.score(np.full_like(t, np.nan, dtype=float), t, [])
|
||||
|
||||
|
||||
def test_paired_errors_exclude_unknown_and_reconcile():
|
||||
t, objs = fixture()
|
||||
b = (t == 1).astype(float)
|
||||
a = 1-b
|
||||
a[t == 255] = 1
|
||||
got=m.paired_changes(a,b,t)
|
||||
assert got==dict(new_fn=48,recovered_fn=0,new_fp=120,removed_fp=0)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Checks for isolation, ignored pixels, fixed comparator, and spatial limits."""
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
if importlib.util.find_spec("cv2") is None:
|
||||
raise unittest.SkipTest("Scientific checks run in the pinned Worker image")
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
probe = importlib.import_module("paint_evidence_probe")
|
||||
|
||||
|
||||
class PaintEvidenceTests(unittest.TestCase):
|
||||
def test_unknown_pixels_do_not_change_score(self):
|
||||
pos = np.zeros((8, 8), bool)
|
||||
pos[1, 1] = True
|
||||
neg = np.zeros_like(pos)
|
||||
neg[6, 6] = True
|
||||
a = pos.copy()
|
||||
b = np.ones_like(pos)
|
||||
b[6, 6] = False
|
||||
self.assertEqual(probe.counts(a, pos, neg), probe.counts(b, pos, neg))
|
||||
|
||||
def test_conflicting_review_rejected(self):
|
||||
with self.assertRaises(AssertionError):
|
||||
probe.probe_masks(
|
||||
dict(positive=[[[1, 1], [5, 5]]], negative=[[[0, 0], [10, 0], [10, 10], [0, 10]]])
|
||||
)
|
||||
|
||||
def test_threshold_uses_validation_false_positive_limit(self):
|
||||
probability = np.array([[0.9, 0.7, 0.65, 0.2]])
|
||||
positive = np.array([[True, True, False, False]])
|
||||
negative = ~positive
|
||||
threshold, _ = probe.choose_threshold(
|
||||
[(probability, positive, negative)], [0.5, 0.6, 0.7, 0.8]
|
||||
)
|
||||
self.assertEqual(threshold, 0.7)
|
||||
|
||||
def test_spatial_filter_cannot_invent_empty_line(self):
|
||||
mask = np.zeros((64, 64), bool)
|
||||
self.assertFalse(probe.spatial_rule(mask).any())
|
||||
mask[30:33, 5:20] = True
|
||||
mask[30:33, 40:59] = True
|
||||
out = probe.spatial_rule(mask)
|
||||
self.assertFalse(out[:, 23:37].any())
|
||||
self.assertTrue(out[31, 10])
|
||||
|
||||
def test_uniform_brightness_is_not_fixed_paint_evidence(self):
|
||||
_, mask, _ = probe.features(np.full((64, 64, 3), 180, np.uint8))
|
||||
self.assertFalse(mask.any())
|
||||
|
||||
def test_pixel_features_do_not_encode_position(self):
|
||||
image = np.full((80, 80, 3), 110, np.uint8)
|
||||
a, fixed, names = probe.features(image)
|
||||
b, other, other_names = probe.features(image)
|
||||
np.testing.assert_array_equal(a, b)
|
||||
np.testing.assert_array_equal(fixed, other)
|
||||
self.assertEqual(names, other_names)
|
||||
self.assertEqual(a.shape, (80, 80, 10))
|
||||
np.testing.assert_array_equal(a[30, 30], a[40, 40])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Exact observed paint survives a supported editor path; lossy cases fail closed."""
|
||||
import copy
|
||||
import importlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, apply_operations
|
||||
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
|
||||
|
||||
np = pytest.importorskip("numpy")
|
||||
pytest.importorskip("shapely", minversion="2.0")
|
||||
from shapely import affinity # noqa: E402
|
||||
from shapely.geometry import Polygon, box, shape # noqa: E402
|
||||
from shapely.ops import unary_union # noqa: E402
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
geometry = importlib.import_module("paint_geometry")
|
||||
gate = importlib.import_module("geometry_contract_gate")
|
||||
|
||||
IDENTITY = [1, 0, 0, 1, 0, 0]
|
||||
|
||||
|
||||
def proposal(labels, matrix=IDENTITY):
|
||||
return geometry.vectorize(labels, pixel_to_scene=matrix, source_id="synthetic-test-only")
|
||||
|
||||
|
||||
def lifted(p):
|
||||
return geometry.editor_features(
|
||||
p, height_at=lambda xy: 2 + .01 * xy[:, 0], height_source="synthetic-known-plane"
|
||||
)
|
||||
|
||||
|
||||
def test_all_512_three_by_three_masks_are_exact():
|
||||
# Exhaustive small topology oracle, independent of run polygonization.
|
||||
for bits in range(512):
|
||||
labels = np.array([(bits >> k) & 1 for k in range(9)], dtype=np.uint8).reshape(3, 3)
|
||||
p = proposal(labels)
|
||||
union = unary_union([shape(f["geometry"]) for f in p["features"]])
|
||||
assert union.area == np.count_nonzero(labels)
|
||||
assert np.array_equal(gate.rasterize(p["features"], labels.shape, IDENTITY), labels == 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("matrix", [IDENTITY, [.2, .03, .04, -.3, 123.25, -72.125]])
|
||||
def test_unknown_holes_gap_and_affine_pixel_edges(matrix):
|
||||
labels = np.zeros((9, 13), np.uint8)
|
||||
labels[1:8, 1:5] = 1
|
||||
labels[3, 2] = 255
|
||||
labels[4, 3] = 0
|
||||
labels[1:8, 6:12] = 1
|
||||
p = proposal(labels, matrix)
|
||||
assert len(p["features"]) == 2
|
||||
polys = [shape(f["geometry"]) for f in p["features"]]
|
||||
assert sum(len(poly.interiors) for poly in polys) == 2
|
||||
det = abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])
|
||||
assert sum(poly.area for poly in polys) == pytest.approx(np.count_nonzero(labels == 1) * det)
|
||||
assert np.array_equal(gate.rasterize(p["features"], labels.shape, matrix), labels == 1)
|
||||
single = shape(proposal([[1]], matrix)["features"][0]["geometry"])
|
||||
assert single.equals(affinity.affine_transform(box(0, 0, 1, 1), matrix))
|
||||
assert p == proposal(labels.copy(), matrix)
|
||||
assert p["source_sha256"] != proposal(labels, [1, 0, 0, 1, 1, 0])["source_sha256"]
|
||||
|
||||
|
||||
def test_empty_unknown_diagonal_and_edge_connectivity():
|
||||
for value in [0, 255]:
|
||||
p = proposal(np.full((3, 3), value, dtype=np.uint8))
|
||||
assert p["features"] == []
|
||||
assert lifted(p) == []
|
||||
assert len(proposal([[1, 0], [0, 1]])["features"]) == 2
|
||||
assert len(proposal([[1, 1], [0, 1]])["features"]) == 1
|
||||
|
||||
|
||||
def test_support_flags_never_claim_complete_instances():
|
||||
labels = np.zeros((6, 12), np.uint8)
|
||||
labels[2:4, :3] = 1
|
||||
labels[2:4, 7:9] = 1
|
||||
labels[:, 9:] = 255
|
||||
p = proposal(labels)
|
||||
assert sorted(f["properties"]["support_boundary"] for f in p["features"]) == [
|
||||
["tile-edge"], ["unknown-support"]
|
||||
]
|
||||
assert all(f["properties"]["instance_completeness"] == "not-assessed" for f in p["features"])
|
||||
|
||||
|
||||
def test_point_touching_hole_preserved_but_editor_refuses():
|
||||
p = proposal([[1, 1, 1], [1, 0, 1], [1, 1, 0]])
|
||||
assert sum(shape(f["geometry"]).area for f in p["features"]) == 7
|
||||
assert np.array_equal(gate.rasterize(p["features"], (3, 3), IDENTITY),
|
||||
np.array([[1, 1, 1], [1, 0, 1], [1, 1, 0]], bool))
|
||||
with pytest.raises(ValueError, match="пересекаются|самопересечение"):
|
||||
lifted(p)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("labels,matrix", [
|
||||
([[2]], IDENTITY), ([[1.0]], IDENTITY), ([[1]], [0, 0, 0, 0, 0, 0]),
|
||||
([[1]], [1, 0, 0, 1, float("nan"), 0]), ([], IDENTITY),
|
||||
])
|
||||
def test_invalid_input_refused(labels, matrix):
|
||||
with pytest.raises(ValueError):
|
||||
proposal(labels, matrix)
|
||||
|
||||
|
||||
def test_complexity_bound_and_unsupported_height_fail_closed(monkeypatch):
|
||||
monkeypatch.setattr(geometry, "MAX_RUNS", 2)
|
||||
with pytest.raises(ValueError, match="budget"):
|
||||
proposal([[1, 0, 1, 0, 1]])
|
||||
p = proposal([[1]])
|
||||
with pytest.raises(ValueError, match="height"):
|
||||
geometry.editor_features(p, height_at=lambda xy: np.full(len(xy), np.nan),
|
||||
height_source="missing")
|
||||
changed = copy.deepcopy(p)
|
||||
changed["features"][0]["geometry"]["coordinates"][0][0][0] += 1
|
||||
with pytest.raises(ValueError, match="Changed"):
|
||||
lifted(changed)
|
||||
|
||||
|
||||
def synthetic_document(features):
|
||||
# This envelope exists ONLY in pytest's deleted temporary store. It exercises
|
||||
# the v3 API requirement; it is not an actual qualified Gaussian derivation.
|
||||
return dict(
|
||||
schema_version="missioncore.urban-map/v3", type="FeatureCollection",
|
||||
coordinate_system=dict(frame="scene-local", units="metres", up="Z", georeferenced=False),
|
||||
source=dict(world_sha256="a" * 64, collider_sha256=None, gaussian_only=True,
|
||||
artifact_sha256="c" * 64, synthetic_fixture=True),
|
||||
coverage=dict(cell_m=.1, accepted_cells=0), features=features,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", list(gate.fixtures()))
|
||||
def test_actual_map_store_edit_store_restart_keep_components_and_holes(tmp_path, name):
|
||||
labels = gate.fixtures()[name]
|
||||
p = proposal(labels, [.1, 0, 0, -.1, 10, 20])
|
||||
original = copy.deepcopy(p)
|
||||
features = lifted(p)
|
||||
assert p == original
|
||||
assert all("subtype" not in f["properties"] and "semantic_element_id" not in f["properties"]
|
||||
for f in features)
|
||||
document = synthetic_document(features)
|
||||
world = dict(sha256="a" * 64)
|
||||
maps = UrbanMapStore(tmp_path)
|
||||
receipt = maps.save(world, document)
|
||||
assert maps.get(world) == document
|
||||
chosen = features[0]
|
||||
delta = [.5, -.25]
|
||||
operation = dict(kind="transform", feature_id=chosen["id"], delta=delta, angle=0)
|
||||
edits = SemanticEdits(tmp_path, maps)
|
||||
saved = edits.save(world, dict(expected_revision=None, model_sha256=receipt["sha256"],
|
||||
request_id="synthetic-geometry-0001", operations=[operation]))
|
||||
assert saved["edited"]["schema_version"] == "missioncore.urban-edit/v1"
|
||||
assert SemanticEdits(tmp_path, maps).get(world) == saved
|
||||
assert not saved["learning"]["dataset_ready"]
|
||||
assert maps.get(world) == document
|
||||
for before, after in zip(features, saved["edited"]["features"], strict=True):
|
||||
if before["id"] == chosen["id"]:
|
||||
assert shape(after["geometry"]).equals(
|
||||
affinity.translate(shape(before["geometry"]), *delta))
|
||||
assert len(after["geometry"]["coordinates"]) == len(before["geometry"]["coordinates"])
|
||||
else:
|
||||
assert before == after
|
||||
# Don't disguise arbitrary components as linear markings to claim vertex editing.
|
||||
with pytest.raises(ValueError, match="вершины"):
|
||||
apply_operations(document, [dict(kind="move", feature_id=chosen["id"], path=0, index=0,
|
||||
position=[0, 0, 2])])
|
||||
assert json.loads(json.dumps(p)) == p
|
||||
|
||||
|
||||
def test_native_summary_representations_are_not_invertible():
|
||||
# Information-content counterexamples, NOT execution of the upstream VMA model.
|
||||
dashes_a = unary_union([box(0, 0, 2, 1), box(4, 0, 6, 1), box(8, 0, 12, 1)])
|
||||
dashes_b = unary_union([box(0, 0, 3, 1), box(5, 0, 7, 1), box(9, 0, 12, 1)])
|
||||
zebra_a = unary_union([box(x, 0, x + 1, 8) for x in [0, 3, 6, 9]])
|
||||
zebra_b = unary_union([box(x, 0, x + 2, 8) for x in [0, 4, 8]])
|
||||
for a, b in [(dashes_a, dashes_b), (zebra_a, zebra_b)]:
|
||||
assert not a.equals(b)
|
||||
assert a.envelope.equals(b.envelope)
|
||||
holed = Polygon([(0, 0), (6, 0), (3, 8)], [[(2, 2), (4, 2), (3, 5)]])
|
||||
solid = Polygon(holed.exterior)
|
||||
assert holed.exterior.equals(solid.exterior)
|
||||
assert not holed.equals(solid)
|
||||
|
||||
|
||||
def test_editor_preflight_bounds_holes_before_callbacks(monkeypatch):
|
||||
from k1link.simulation.ai_polygon import semantic_edits
|
||||
|
||||
labels = np.ones((40, 40), dtype=np.uint8)
|
||||
labels[2:-1:3, 2:-1:3] = 0
|
||||
p = proposal(labels)
|
||||
|
||||
def forbidden(*args):
|
||||
raise AssertionError("Expensive validation or sampling ran before budget check")
|
||||
|
||||
monkeypatch.setattr(semantic_edits, "validate_path", forbidden)
|
||||
monkeypatch.setattr(semantic_edits, "validate_holes", forbidden)
|
||||
with pytest.raises(ValueError, match="budget"):
|
||||
geometry.editor_features(p, height_at=forbidden, height_source="test")
|
||||
|
||||
|
||||
def test_editor_work_bound_applies_to_whole_batch_before_sampling(monkeypatch):
|
||||
p = proposal([[1, 0, 1]])
|
||||
monkeypatch.setattr(geometry, "MAX_EDITOR_WORK", 20)
|
||||
|
||||
def forbidden(*args):
|
||||
raise AssertionError("Height callback ran for partial batch")
|
||||
|
||||
with pytest.raises(ValueError, match="work budget"):
|
||||
geometry.editor_features(p, height_at=forbidden, height_source="test")
|
||||
|
||||
|
||||
def test_height_callback_cannot_move_xy():
|
||||
p = proposal([[1, 1]])
|
||||
|
||||
def mutating_sampler(xy):
|
||||
xy += 100
|
||||
return np.full(len(xy), 3.)
|
||||
|
||||
features = geometry.editor_features(p, height_at=mutating_sampler, height_source="test")
|
||||
for before, after in zip(p["features"], features, strict=True):
|
||||
assert [[p[:2] for p in ring] for ring in after["geometry"]["coordinates"]] == (
|
||||
before["geometry"]["coordinates"]
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Diagnostic boundaries: no invented geometry, rejected context, frozen outputs."""
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
if importlib.util.find_spec("cv2") is None:
|
||||
raise unittest.SkipTest("Scientific checks run in the pinned Worker image")
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
study = importlib.import_module("paint_hypothesis_study")
|
||||
|
||||
|
||||
class PaintHypothesisTests(unittest.TestCase):
|
||||
def test_photometric_counterfactual_preserves_geometry(self):
|
||||
image = np.full((64, 64, 3), 80, np.uint8)
|
||||
image[20:25, 5:58] = 180
|
||||
darker = study.transformed(image, "gain", 0.55)
|
||||
np.testing.assert_array_equal(image[:, :, 0] > 100, darker[:, :, 0] > 50)
|
||||
np.testing.assert_array_equal(study.transformed(image, "identity", 1), image)
|
||||
|
||||
def test_context_does_not_fabricate_missing_support(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
self.assertIsNone(study.context(root, {"id": "absent"}, "semantic"))
|
||||
(root / "data").mkdir()
|
||||
road = np.array([[0.8, 0.1, 0.8]], np.float32)
|
||||
sidewalk = np.array([[0.1, 0.05, 0.9]], np.float32)
|
||||
np.savez(root / "data/a-context.npz", road=road, sidewalk=sidewalk)
|
||||
np.testing.assert_array_equal(
|
||||
study.context(root, {"id": "a"}, "semantic"), [[True, False, False]]
|
||||
)
|
||||
|
||||
def test_high_recall_candidate_cannot_bypass_false_positive_limit(self):
|
||||
rows = [
|
||||
dict(variant="bad", recall=0.99, false_positive_rate=0.5),
|
||||
dict(variant="good", recall=0.8, false_positive_rate=0.005),
|
||||
]
|
||||
self.assertEqual(study.choose_candidate(rows)["variant"], "good")
|
||||
self.assertEqual(study.choose_candidate(list(reversed(rows)))["variant"], "good")
|
||||
|
||||
def test_frozen_model_cannot_be_overwritten(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "model.json"
|
||||
study.save_new(path, {"model": 1})
|
||||
with self.assertRaises(FileExistsError):
|
||||
study.save_new(path, {"model": 2})
|
||||
self.assertEqual(study.json.loads(path.read_text()), {"model": 1})
|
||||
|
||||
def test_deterministic_fit_needs_no_spatial_identity(self):
|
||||
x = np.array([[-2.0, 0.1], [-1.0, 0.2], [1.0, 0.4], [2.0, 0.3]])
|
||||
y = np.array([0, 0, 1, 1])
|
||||
a = study.fit_classifier(x, y, 0.01, 200)
|
||||
b = study.fit_classifier(x, y, 0.01, 200)
|
||||
np.testing.assert_array_equal(a["coefficients"], b["coefficients"])
|
||||
np.testing.assert_array_equal(study.probability(x, a) > 0.5, y == 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,63 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
p = Path(__file__).resolve().parents[1] / "simulation/semantic-learning/pixel_permutation.py"
|
||||
s = importlib.util.spec_from_file_location("pixel_permutation", p)
|
||||
m = importlib.util.module_from_spec(s)
|
||||
s.loader.exec_module(m)
|
||||
|
||||
|
||||
def pair():
|
||||
target = np.full((5, 5), 255, np.uint8)
|
||||
target[0, :3] = [0, 1, 1]
|
||||
target[2, 1] = 0
|
||||
# Encode the target and original coordinate in RGB to test alignment.
|
||||
rgb = np.stack([target, np.arange(25, dtype=np.uint8).reshape(5, 5),
|
||||
np.zeros((5, 5), np.uint8)], axis=-1)
|
||||
return rgb, target
|
||||
|
||||
|
||||
@pytest.mark.parametrize("element", range(8))
|
||||
def test_inverse_alignment_counts_padding_and_no_input_mutation(element):
|
||||
rgb, target = pair()
|
||||
original = rgb.copy(), target.copy()
|
||||
image, labels = m.permute_training_pair(rgb, target, element)
|
||||
assert image.flags.c_contiguous and labels.flags.c_contiguous
|
||||
np.testing.assert_array_equal(image[:, :, 0], labels)
|
||||
np.testing.assert_array_equal(np.bincount(labels.ravel(), minlength=256),
|
||||
np.bincount(target.ravel(), minlength=256))
|
||||
inverse = element if element >= 4 else (-element) % 4
|
||||
restored = m.permute_training_pair(image, labels, inverse)
|
||||
np.testing.assert_array_equal(restored[0], rgb)
|
||||
np.testing.assert_array_equal(restored[1], target)
|
||||
image[:] = 0
|
||||
labels[:] = 0
|
||||
np.testing.assert_array_equal(rgb, original[0])
|
||||
np.testing.assert_array_equal(target, original[1])
|
||||
|
||||
|
||||
def test_all_eight_distinct_and_rng_unchanged():
|
||||
rgb, target = pair()
|
||||
before = np.random.get_state()
|
||||
results = [m.permute_training_pair(rgb, target, k)[0].tobytes() for k in range(8)]
|
||||
after = np.random.get_state()
|
||||
assert len(set(results)) == 8
|
||||
assert before[0] == after[0] and before[2:] == after[2:]
|
||||
np.testing.assert_array_equal(before[1], after[1])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("element", [-1, 8, True, 1.0, None])
|
||||
def test_invalid_element(element):
|
||||
with pytest.raises(ValueError):
|
||||
m.permute_training_pair(*pair(), element)
|
||||
|
||||
|
||||
def test_invalid_shape_dtype_and_label_rejected():
|
||||
rgb, target = pair()
|
||||
for image, labels in [(rgb[:3], target[:3]), (rgb, target.astype(float)),
|
||||
(rgb[:, :, :2], target), (rgb, np.full_like(target, 2))]:
|
||||
with pytest.raises(ValueError):
|
||||
m.permute_training_pair(image, labels, 0)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Coverage is explicit, source labels and unknown exclusions remain protected."""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SOURCE = Path(__file__).parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SOURCE))
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"tested_region_coverage", SOURCE / "region_coverage.py"
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def inputs():
|
||||
raw = bytes([255] * 80)
|
||||
packet = dict(
|
||||
size=[10, 8],
|
||||
roi=[1, 1, 9, 7],
|
||||
view="top",
|
||||
target_sha256=m.sha(raw),
|
||||
protected_sha256=m.sha(b""),
|
||||
)
|
||||
proposal = dict(
|
||||
reason="synthetic visible stripe and background",
|
||||
background_reviewed=True,
|
||||
boundary_ignore_px=1,
|
||||
paint_polygons=[[[3, 1], [7, 1], [7, 7], [3, 7]]],
|
||||
unknown_polygons=[],
|
||||
)
|
||||
return raw, packet, proposal
|
||||
|
||||
|
||||
def test_complete_region_and_no_implicit_background_elsewhere():
|
||||
original, packet, proposal = inputs()
|
||||
record = m.raster_proposal(packet, proposal)
|
||||
out, audit = m.merge(packet, record, original)
|
||||
assert audit["roi_pixels"] == 48
|
||||
assert audit["added"] == dict(paint=12, background=12)
|
||||
assert out[:10] == original[:10]
|
||||
assert out[2 * 10 + 4] == 1
|
||||
assert out[2 * 10 + 3] == 255 # uncertain boundary
|
||||
assert out[2 * 10 + 1] == 0
|
||||
|
||||
|
||||
def test_missing_pixels_and_outside_roi_are_rejected():
|
||||
original, packet, proposal = inputs()
|
||||
record = m.raster_proposal(packet, proposal)
|
||||
record["background"].pop()
|
||||
with pytest.raises(ValueError, match="Incomplete"):
|
||||
m.merge(packet, record, original)
|
||||
record = m.raster_proposal(packet, proposal)
|
||||
record["background"].insert(0, [0, 0, 1])
|
||||
with pytest.raises(ValueError, match="outside"):
|
||||
m.merge(packet, record, original)
|
||||
|
||||
|
||||
def test_existing_label_conflict_protected_unknown_and_pin():
|
||||
original, packet, proposal = inputs()
|
||||
record = m.raster_proposal(packet, proposal)
|
||||
old = bytearray(original)
|
||||
old[21] = 1
|
||||
packet["target_sha256"] = m.sha(old)
|
||||
with pytest.raises(ValueError, match="conflicts"):
|
||||
m.merge(packet, record, old)
|
||||
packet["target_sha256"] = m.sha(original)
|
||||
protected = bytearray(len(original))
|
||||
protected[21] = 1
|
||||
packet["protected_sha256"] = m.sha(protected)
|
||||
with pytest.raises(ValueError, match="protected unknown"):
|
||||
m.merge(packet, record, original, protected)
|
||||
with pytest.raises(ValueError, match="identity changed"):
|
||||
m.merge(packet, record, original)
|
||||
|
||||
|
||||
def test_explicit_background_and_finite_polygons():
|
||||
_, packet, proposal = inputs()
|
||||
proposal["background_reviewed"] = False
|
||||
with pytest.raises(ValueError, match="Explicit"):
|
||||
m.raster_proposal(packet, proposal)
|
||||
proposal["background_reviewed"] = True
|
||||
proposal["paint_polygons"][0][0] = [float("nan"), 0]
|
||||
with pytest.raises(ValueError, match="outside"):
|
||||
m.raster_proposal(packet, proposal)
|
||||
|
||||
|
||||
def test_protected_unknown_cannot_overlap_accepted_label():
|
||||
original, packet, proposal = inputs()
|
||||
original = bytearray(original)
|
||||
original[23] = 1 # New proposal marks its boundary unknown.
|
||||
packet["target_sha256"] = m.sha(original)
|
||||
protected = bytearray(len(original))
|
||||
protected[23] = 1
|
||||
packet["protected_sha256"] = m.sha(protected)
|
||||
with pytest.raises(ValueError, match="only unknown"):
|
||||
m.merge(packet, m.raster_proposal(packet, proposal), original, protected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("known", [0, 1])
|
||||
def test_explicit_source_uncertainty_cannot_silently_keep_known_label(known):
|
||||
original, packet, proposal = inputs()
|
||||
original = bytearray(original)
|
||||
original[24] = known
|
||||
packet["target_sha256"] = m.sha(original)
|
||||
proposal["unknown_polygons"] = [[[4, 2], [5, 2], [5, 3], [4, 3]]]
|
||||
proposal["unknown_reason"] = "Source is obscured here"
|
||||
record = m.raster_proposal(packet, proposal)
|
||||
with pytest.raises(ValueError, match="Explicit source uncertainty"):
|
||||
m.merge(packet, record, original)
|
||||
|
||||
|
||||
def test_boundary_ignore_does_not_revoke_prior_known_label():
|
||||
original, packet, proposal = inputs()
|
||||
original = bytearray(original)
|
||||
original[23] = 1
|
||||
packet["target_sha256"] = m.sha(original)
|
||||
out, _ = m.merge(packet, m.raster_proposal(packet, proposal), original)
|
||||
assert out[23] == 1
|
||||
|
||||
|
||||
def test_explicit_unknown_on_unreviewed_source_stays_unknown():
|
||||
original, packet, proposal = inputs()
|
||||
proposal["unknown_polygons"] = [[[4, 2], [5, 2], [5, 3], [4, 3]]]
|
||||
proposal["unknown_reason"] = "Visible ambiguity"
|
||||
out, _ = m.merge(packet, m.raster_proposal(packet, proposal), original)
|
||||
assert out[24] == 255
|
||||
assert out[14] == 1
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Research must stay advisory and bound to source evidence and root review."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inputs(tmp_path, monkeypatch):
|
||||
source = Path(__file__).parents[1] / "simulation/semantic-learning"
|
||||
monkeypatch.syspath_prepend(str(source))
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"tested_research_gate", source / "research_gate.py"
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
baseline = tmp_path / "baseline.json"
|
||||
baseline.write_text('{"synthetic":true}')
|
||||
brief = dict(
|
||||
schema_version=m.SCHEMA,
|
||||
root_actor="root",
|
||||
scout_actor="scout",
|
||||
trigger="user_request",
|
||||
question="Where does review effort go?",
|
||||
baseline=dict(path="baseline.json", sha256=m.checksum(baseline)),
|
||||
)
|
||||
src = dict(
|
||||
id="primary",
|
||||
title="Synthetic documentation",
|
||||
url="https://example.com/docs",
|
||||
kind="official_docs",
|
||||
checked_utc="2026-10-25T10:00:00Z",
|
||||
supports="A workflow exists",
|
||||
limitations="No result on our data",
|
||||
)
|
||||
idea = dict(
|
||||
id="measure",
|
||||
title="Bounded measurement",
|
||||
basis="external",
|
||||
source_ids=["primary"],
|
||||
evidence="Source describes workflow",
|
||||
hypothesis="May reduce repeated work",
|
||||
minimal_test="Compare equal budgets",
|
||||
success="Lower review effort at same quality",
|
||||
failure="More errors or no gain",
|
||||
cost="Small metadata-only test",
|
||||
risks="Correlated reviewers",
|
||||
not_applicable="No measured bottleneck",
|
||||
)
|
||||
report = dict(
|
||||
brief_sha256=m.digest(brief),
|
||||
baseline_option="Keep current workflow",
|
||||
sources=[src],
|
||||
ideas=[idea],
|
||||
unknowns="Active effort is not measured",
|
||||
recommendation="Measure before switching",
|
||||
)
|
||||
decision = dict(
|
||||
actor="root",
|
||||
report_sha256=m.digest(report),
|
||||
source_checks=["primary"],
|
||||
verdicts=[
|
||||
dict(
|
||||
idea_id="measure",
|
||||
outcome="test",
|
||||
reason="Useful bounded uncertainty reduction",
|
||||
revisit_when="After the measured pilot",
|
||||
)
|
||||
],
|
||||
test_plan=dict(
|
||||
idea_id="measure",
|
||||
control="Unchanged workflow",
|
||||
data_selection="Preselected physical groups",
|
||||
metric="Review effort with fixed quality audit",
|
||||
success="Complete evidence without extra errors",
|
||||
failure="Missing timing or changed quality",
|
||||
budget=dict(max_units=4, max_dispatches=8, max_wall_seconds=1800, gpu_training_runs=0),
|
||||
),
|
||||
)
|
||||
return m, tmp_path, brief, report, decision
|
||||
|
||||
|
||||
def test_selected_idea_is_only_a_draft_not_execution_authority(inputs):
|
||||
m, root, b, r, d = inputs
|
||||
result = m.review_research(root, b, r, d)
|
||||
assert result["selected_idea"] == "measure"
|
||||
assert result["next_action"] == "freeze_separate_experiment"
|
||||
assert not any(
|
||||
result[k] for k in ("execution_authorized", "training_authorized", "map_write_authorized")
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change", ["actor", "baseline", "report", "citation", "training", "unverified"]
|
||||
)
|
||||
def test_rejects_escalation_stale_evidence_and_unverified_selection(inputs, change):
|
||||
m, root, b, r, d = inputs
|
||||
if change == "actor":
|
||||
d["actor"] = "scout"
|
||||
elif change == "baseline":
|
||||
(root / "baseline.json").write_text("changed")
|
||||
elif change == "report":
|
||||
r["recommendation"] = "new unchecked recommendation"
|
||||
elif change == "citation":
|
||||
r["ideas"][0]["source_ids"] = ["invented"]
|
||||
d["report_sha256"] = m.digest(r)
|
||||
elif change == "training":
|
||||
d["test_plan"]["budget"]["gpu_training_runs"] = 1
|
||||
else:
|
||||
d["source_checks"] = []
|
||||
with pytest.raises(ValueError):
|
||||
m.review_research(root, b, r, d)
|
||||
|
||||
|
||||
def test_no_useful_idea_is_a_valid_closed_result(inputs):
|
||||
m, root, b, r, d = inputs
|
||||
r.update(ideas=[], sources=[])
|
||||
d.update(report_sha256=m.digest(r), source_checks=[], verdicts=[], test_plan=None)
|
||||
result = m.review_research(root, b, r, d)
|
||||
assert result["selected_idea"] is None
|
||||
assert result["next_action"] == "keep_current_workflow"
|
||||
|
||||
|
||||
def test_only_one_test_can_be_selected(inputs):
|
||||
m, root, b, r, d = inputs
|
||||
r["ideas"].append(dict(copy.deepcopy(r["ideas"][0]), id="second"))
|
||||
d["verdicts"].append(dict(d["verdicts"][0], idea_id="second"))
|
||||
d["report_sha256"] = m.digest(r)
|
||||
with pytest.raises(ValueError, match="at most one"):
|
||||
m.review_research(root, b, r, d)
|
||||
|
||||
|
||||
def test_output_budget_and_schema_do_not_accept_commands(inputs):
|
||||
m, root, b, r, d = inputs
|
||||
r["execute"] = "start a worker"
|
||||
d["report_sha256"] = m.digest(r)
|
||||
with pytest.raises(ValueError, match="fields"):
|
||||
m.review_research(root, b, r, d)
|
||||
del r["execute"]
|
||||
r["unknowns"] = "x" * m.MAX_BYTES
|
||||
with pytest.raises(ValueError, match="byte limit"):
|
||||
m.review_research(root, b, r, d)
|
||||
@@ -0,0 +1,194 @@
|
||||
"""RGB adapter uses real pinned stores, native pixels and isolated split readers."""
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from test_semantic_admission import admission as admission_fixture
|
||||
from test_semantic_admission import corpus as corpus_fixture
|
||||
from test_semantic_admission import dataset, decision, release
|
||||
from test_semantic_corpus import group, opened, plan
|
||||
from test_semantic_delivery import ds
|
||||
|
||||
np = pytest.importorskip("numpy")
|
||||
admission = admission_fixture
|
||||
corpus = corpus_fixture
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rgb(admission, monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "admission_store", admission)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"rgb_training_input_test",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/rgb_training_input.py",
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def rgb_dataset(root, name, world, color):
|
||||
entry = dataset(root, name, world=world)
|
||||
folder = root / entry["path"]
|
||||
for view in ["top", "oblique"]:
|
||||
Image.new("RGB", (8, 6), color).save(folder / "window" / (view + ".png"))
|
||||
path = folder / "dataset.json"
|
||||
manifest = json.loads(path.read_text())
|
||||
for name in manifest["files"]:
|
||||
member = folder / name
|
||||
manifest["files"][name] = dict(sha256=ds.checksum(member), bytes=member.stat().st_size)
|
||||
ds.write(path, manifest)
|
||||
entry["sha256"] = ds.checksum(path)
|
||||
return entry
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admitted(admission, corpus, tmp_path):
|
||||
entries = [
|
||||
rgb_dataset(tmp_path, "train", "a" * 64, (230, 17, 5)),
|
||||
rgb_dataset(tmp_path, "test", "d" * 64, (4, 9, 240)),
|
||||
]
|
||||
index = corpus.build(
|
||||
tmp_path,
|
||||
plan(corpus, entries, [group("train-area", "train", "a" * 64),
|
||||
group("test-area", "test", "d" * 64)]),
|
||||
"corpora/rgb",
|
||||
)
|
||||
with opened(corpus, tmp_path, index) as reader:
|
||||
rr = [r for split in ["train", "test"] for b in reader.batches(split) for r in b]
|
||||
admitted, _ = release(admission, tmp_path, index, rr,
|
||||
[decision(admission, r) for r in rr])
|
||||
return admitted
|
||||
|
||||
|
||||
def reader(admission, root, receipt):
|
||||
return admission.Supervision(root, receipt["path"], receipt["sha256"])
|
||||
|
||||
|
||||
def test_pinned_rgb_targets_and_split_isolation(rgb, admission, admitted, tmp_path):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
training = list(rgb.training_frames(source))
|
||||
testing = list(rgb.evaluation_frames(source, split="test"))
|
||||
assert len(training) == len(testing) == 1
|
||||
a, b = training[0], testing[0]
|
||||
assert a["metadata"]["split"] == "train" and b["metadata"]["split"] == "test"
|
||||
assert a["metadata"]["physical_group"] != b["metadata"]["physical_group"]
|
||||
assert a["img"][0, 0].tolist() == [230, 17, 5] # no silent RGB/BGR swap
|
||||
assert b["img"][0, 0].tolist() == [4, 9, 240]
|
||||
mask = a["target"]
|
||||
assert np.count_nonzero(mask == 1) == 3
|
||||
assert np.count_nonzero(mask == 0) == 6
|
||||
assert np.count_nonzero(mask == 255) == 39
|
||||
assert a["metadata"]["input"]["view"] == "top"
|
||||
assert a["img"].shape == (6, 8, 3)
|
||||
|
||||
|
||||
def test_hash_failure_precedes_decode(rgb, admission, admitted, tmp_path):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
image = tmp_path / "datasets/train/window/top.png"
|
||||
image.write_bytes(image.read_bytes() + b"changed")
|
||||
with pytest.raises(ValueError, match="changed"):
|
||||
next(rgb.training_frames(source))
|
||||
|
||||
|
||||
def test_loader_does_not_open_next_image_early(rgb, admission, admitted, tmp_path, monkeypatch):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
opened = []
|
||||
original = source.open_image
|
||||
def tracked(value):
|
||||
opened.append(value["sample_id"])
|
||||
return original(value)
|
||||
monkeypatch.setattr(source, "open_image", tracked)
|
||||
iterator = rgb.training_frames(source)
|
||||
assert opened == []
|
||||
next(iterator)
|
||||
assert len(opened) == 1
|
||||
iterator.close()
|
||||
assert len(opened) == 1
|
||||
|
||||
|
||||
def test_native_crop_padding_and_source_mapping(rgb, admission, admitted, tmp_path):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
frame = next(rgb.training_frames(source))
|
||||
original = copy.deepcopy(frame["metadata"])
|
||||
cropped = rgb.crop(frame, left=1, top=1, size=8)
|
||||
expected = np.full((8, 8), 255, np.uint8)
|
||||
expected[:5, :7] = frame["target"][1:, 1:]
|
||||
assert np.array_equal(cropped["target"], expected)
|
||||
assert np.array_equal(cropped["img"][:5, :7], frame["img"][1:, 1:])
|
||||
assert np.all(cropped["img"][5:] == 0)
|
||||
assert cropped["metadata"]["crop_to_source_edges"] == [1, 0, 0, 1, 1, 1]
|
||||
assert cropped["metadata"]["input"] == original["input"] # no guessed camera rewrite
|
||||
assert frame["metadata"] == original
|
||||
assert rgb.crop(frame, left=7, top=5, size=4) is None
|
||||
cropped["target"][0, 1] = 0
|
||||
assert frame["target"][1, 2] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", [
|
||||
lambda e: e.update(split="test", training_eligible=False),
|
||||
lambda e: e.update(task="contextual_map"),
|
||||
lambda e: e.update(background_from_absence=True),
|
||||
lambda e: e["targets"][0].update(ignore_index=0),
|
||||
lambda e: e["targets"][0].update(size=[8, 7]),
|
||||
])
|
||||
def test_invalid_training_contract_refused_before_image(rgb, admission, admitted, tmp_path,
|
||||
monkeypatch, mutation):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
example = next(source.training_batches("observed_paint"))[0]
|
||||
mutation(example)
|
||||
def forbidden(*args):
|
||||
raise AssertionError("Unaligned image was opened")
|
||||
monkeypatch.setattr(source, "open_image", forbidden)
|
||||
with pytest.raises(ValueError):
|
||||
rgb.load_frame(source, example, "top", split="train")
|
||||
|
||||
|
||||
def test_all_unknown_does_not_open_media(rgb, admission, admitted, tmp_path, monkeypatch):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
example = next(source.training_batches("observed_paint"))[0]
|
||||
example["targets"][0].update(paint=[], background=[], unknown=[])
|
||||
def forbidden(*args):
|
||||
raise AssertionError("All-ignore sample decoded")
|
||||
monkeypatch.setattr(source, "open_image", forbidden)
|
||||
assert rgb.load_frame(source, example, "top", split="train") is None
|
||||
|
||||
|
||||
def test_evaluation_cannot_select_train(rgb):
|
||||
with pytest.raises(ValueError, match="non-training"):
|
||||
next(rgb.evaluation_frames(None, split="train"))
|
||||
|
||||
|
||||
def test_mmseg_input_loss_contract(rgb):
|
||||
options = rgb.mmseg_overrides()
|
||||
assert options["dataset"] == {"reduce_zero_label": False, "ignore_index": 255}
|
||||
head = options["model"]["decode_head"]
|
||||
assert head["num_classes"] == head["out_channels"] == 2
|
||||
assert head["ignore_index"] == 255
|
||||
assert head["loss_decode"]["avg_non_ignore"] is True
|
||||
assert options["model"]["data_preprocessor"]["bgr_to_rgb"] is False
|
||||
assert options["model"]["data_preprocessor"]["seg_pad_val"] == 255
|
||||
|
||||
|
||||
def test_forged_split_flags_cannot_admit_test_image(rgb, admission, admitted, tmp_path,
|
||||
monkeypatch):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
example = next(source.batches("observed_paint", "test"))[0]
|
||||
example.update(split="train", training_eligible=True)
|
||||
def forbidden(*args):
|
||||
raise AssertionError("Test image reached training decode")
|
||||
monkeypatch.setattr(source, "open_image", forbidden)
|
||||
with pytest.raises(ValueError, match="pinned source split"):
|
||||
rgb.load_frame(source, example, "top", split="train")
|
||||
|
||||
|
||||
def test_nested_crop_rejected_instead_of_resetting_source_offset(rgb, admission, admitted,
|
||||
tmp_path):
|
||||
with reader(admission, tmp_path, admitted) as source:
|
||||
frame = next(rgb.training_frames(source))
|
||||
first = rgb.crop(frame, left=1, top=1, size=8)
|
||||
with pytest.raises(ValueError, match="Nested crop"):
|
||||
rgb.crop(first, left=0, top=0, size=4)
|
||||
@@ -0,0 +1,104 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
PATH = Path(__file__).resolve().parents[1] / "simulation/semantic-learning/score_diagnostic.py"
|
||||
spec = importlib.util.spec_from_file_location("score_diagnostic", PATH)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def masks(y):
|
||||
y = np.array(y)
|
||||
return {"overall": y == 1}, {"bg": y == 0}
|
||||
|
||||
|
||||
def test_known_ap_auc_example():
|
||||
p, n = masks([0, 0, 1, 1])
|
||||
c = m.curve(np.array([0.1, 0.4, 0.35, 0.8]), p, n)
|
||||
r = m.ranking(c, "overall", ["bg"])
|
||||
assert r["ap"] == pytest.approx(5 / 6)
|
||||
assert r["auc"] == 0.75
|
||||
|
||||
|
||||
def test_ties_cannot_be_split_and_zero_budget_is_possible():
|
||||
p, n = masks([1, 0, 1])
|
||||
c = m.curve(np.array([1.0, 1.0, 0.0]), p, n)
|
||||
assert m.matched(c, {"bg": 0})["counts"] == {"overall": 0, "bg": 0}
|
||||
assert m.at_threshold(c, 1)["counts"] == {"overall": 1, "bg": 1}
|
||||
assert m.ranking(c, "overall", ["bg"])["ap"] == pytest.approx(7 / 12)
|
||||
|
||||
|
||||
def test_both_models_get_oracle_and_shift_does_not_improve_ranking():
|
||||
p, n = masks([1, 1, 0, 0])
|
||||
r = m.paired(np.array([2.0, -0.1, -0.2, -1.0]), np.array([1.0, -1.1, -1.2, -2.0]), p, n)
|
||||
assert r["fixed"]["old"]["counts"]["overall"] == 1
|
||||
assert r["oracle"]["old"]["counts"] == r["oracle"]["new"]["counts"] == {"overall": 2, "bg": 0}
|
||||
assert r["ranking"]["old"] == r["ranking"]["new"]
|
||||
|
||||
|
||||
def test_two_negative_budgets_prevent_swapping_errors():
|
||||
s = np.array([1.0, 0.5, 0.1])
|
||||
c = m.curve(
|
||||
s,
|
||||
{"overall": np.array([1, 0, 0], bool)},
|
||||
{"old_bg": np.array([0, 1, 0], bool), "added_bg": np.array([0, 0, 1], bool)},
|
||||
)
|
||||
r = m.matched(c, {"old_bg": 0, "added_bg": 1})
|
||||
assert r["counts"] == {"overall": 1, "old_bg": 0, "added_bg": 0}
|
||||
|
||||
|
||||
def test_unknown_scores_cannot_change_metrics():
|
||||
p, n = masks([1, 0, 255])
|
||||
a = m.paired(np.array([1.0, -1.0, 10.0]), np.array([1.0, -1.0, -99.0]), p, n)
|
||||
assert a["ranking"]["old"] == a["ranking"]["new"]
|
||||
assert a["support"] == {"overall": 1, "bg": 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scores", [[], [np.nan], [np.inf], [[1.0]]])
|
||||
def test_invalid_scores_rejected(scores):
|
||||
p, n = masks([1])
|
||||
with pytest.raises(ValueError):
|
||||
m.curve(np.array(scores), p, n)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("budget", [-1, 0.5, True, 3])
|
||||
def test_invalid_budgets_rejected(budget):
|
||||
p, n = masks([1, 0])
|
||||
with pytest.raises(ValueError):
|
||||
m.matched(m.curve(np.array([1.0, 0.0]), p, n), {"bg": budget})
|
||||
|
||||
|
||||
def test_overlap_rejected():
|
||||
with pytest.raises(ValueError):
|
||||
m.curve(np.array([1.0]), {"overall": np.ones(1, bool)}, {"bg": np.ones(1, bool)})
|
||||
|
||||
|
||||
def test_all_background_and_no_background_are_undefined():
|
||||
for y in [[0, 0], [1, 1]]:
|
||||
p, n = masks(y)
|
||||
r = m.ranking(m.curve(np.array([1.0, -1.0]), p, n), "overall", ["bg"])
|
||||
assert r["ap"] is None and r["auc"] is None
|
||||
|
||||
|
||||
def test_exhaustive_threshold_counts_and_budget_maximality():
|
||||
rng = np.random.default_rng(7)
|
||||
for _ in range(30):
|
||||
s = rng.integers(-3, 4, 25).astype(float)
|
||||
y = rng.integers(0, 2, 25)
|
||||
p, n = masks(y)
|
||||
c = m.curve(s, p, n)
|
||||
for t in np.unique(np.r_[s, np.inf]):
|
||||
expected = {k: int(((s >= t) & v).sum()) for k, v in dict(p, **n).items()}
|
||||
got = m.point(c, int(np.flatnonzero(c["thresholds"] == t)[0]))
|
||||
assert got["counts"] == expected
|
||||
for budget in range(int((y == 0).sum()) + 1):
|
||||
got = m.matched(c, {"bg": budget})
|
||||
candidates = [
|
||||
int(((s >= t) & (y == 1)).sum())
|
||||
for t in np.r_[np.unique(s), np.inf]
|
||||
if ((s >= t) & (y == 0)).sum() <= budget
|
||||
]
|
||||
assert got["counts"]["overall"] == max(candidates)
|
||||
@@ -0,0 +1,539 @@
|
||||
"""Task-specific evidence, unchanged labels, context isolation and sparse ignore masks."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_semantic_corpus import corpus as corpus_fixture
|
||||
from test_semantic_corpus import group, opened, plan, refs
|
||||
from test_semantic_delivery import ds
|
||||
|
||||
corpus = corpus_fixture
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admission(corpus, monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "corpus_store", corpus)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"admission_store_test",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/admission_store.py",
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def dataset(root, name, world="a" * 64, revision="b" * 64):
|
||||
folder = root / "datasets" / name / "window"
|
||||
folder.mkdir(parents=True)
|
||||
# Synthetic media bytes: admission checks identity, not image interpretation.
|
||||
for view in ("top", "oblique"):
|
||||
(folder / f"{view}.png").write_bytes(b"synthetic-raw-view-" + view.encode())
|
||||
ds.write(
|
||||
folder / "cameras.json",
|
||||
dict(
|
||||
views=[
|
||||
dict(
|
||||
id=v,
|
||||
size=[8, 6],
|
||||
projection="ortho",
|
||||
eye=[0, 0, 10],
|
||||
target=[0, 0, 0],
|
||||
up=[0, 1, 0],
|
||||
width_m=8,
|
||||
)
|
||||
for v in ("top", "oblique")
|
||||
],
|
||||
coordinates="scene-local XYZ, metres, Z up",
|
||||
pixel_convention="pixel centres",
|
||||
),
|
||||
)
|
||||
geometry = dict(
|
||||
type="LineString",
|
||||
coordinates=[
|
||||
[0.0, 0.0, 0.1234567890123],
|
||||
[4.0, 0.0, 0.1234567890123],
|
||||
[8.0, 0.0, 0.1234567890123],
|
||||
],
|
||||
)
|
||||
features = [
|
||||
dict(
|
||||
id="road",
|
||||
properties=dict(**{"class": "road_boundary"}, review_status="accepted"),
|
||||
geometry=geometry,
|
||||
),
|
||||
dict(
|
||||
id="deleted",
|
||||
properties=dict(**{"class": "road_boundary"}, review_status="rejected"),
|
||||
geometry=geometry,
|
||||
),
|
||||
]
|
||||
ds.write(
|
||||
folder / "labels.json",
|
||||
dict(
|
||||
original_element=copy.deepcopy(features),
|
||||
proposed_element=features,
|
||||
projections={
|
||||
v: [
|
||||
dict(feature_id=f["id"], uv=[[0, 0], [4, 0], [8, 0]], in_front=[True] * 3)
|
||||
for f in features
|
||||
]
|
||||
for v in ("top", "oblique")
|
||||
},
|
||||
),
|
||||
)
|
||||
parent = folder.parent
|
||||
ds.write(
|
||||
folder / "sample.json",
|
||||
dict(
|
||||
members=[p.relative_to(parent).as_posix() for p in sorted(folder.iterdir())],
|
||||
revision=revision,
|
||||
split_group=world,
|
||||
training_eligible=False,
|
||||
complete_regions=[],
|
||||
),
|
||||
)
|
||||
ds.write(
|
||||
parent / "dataset.json",
|
||||
dict(
|
||||
schema_version=ds.SCHEMA,
|
||||
world_sha256=world,
|
||||
revision=revision,
|
||||
annotation_sha256="c" * 64,
|
||||
split_group=world,
|
||||
samples=["window/sample.json"],
|
||||
training_eligible=False,
|
||||
files={
|
||||
p.relative_to(parent).as_posix(): dict(
|
||||
sha256=ds.checksum(p), bytes=p.stat().st_size
|
||||
)
|
||||
for p in parent.rglob("*")
|
||||
if p.is_file()
|
||||
},
|
||||
),
|
||||
)
|
||||
return dict(
|
||||
path=parent.relative_to(root).as_posix(), sha256=ds.checksum(parent / "dataset.json")
|
||||
)
|
||||
|
||||
|
||||
def identity(reference):
|
||||
return {k: reference["source"][k] for k in ("world_sha256", "revision", "annotation_sha256")}
|
||||
|
||||
|
||||
def input_view(reference, view="top"):
|
||||
return dict(sample_id=reference["id"], view=view)
|
||||
|
||||
|
||||
def decision(admission, reference):
|
||||
geometry = dict(
|
||||
type="LineString",
|
||||
coordinates=[
|
||||
[0.0, 0.0, 0.1234567890123],
|
||||
[4.0, 0.0, 0.1234567890123],
|
||||
[8.0, 0.0, 0.1234567890123],
|
||||
],
|
||||
)
|
||||
return dict(
|
||||
schema_version=admission.DECISION_SCHEMA,
|
||||
sample_id=reference["id"],
|
||||
reviewer=dict(id="synthetic-reviewer", kind="assistant"),
|
||||
reviewed_utc="2026-10-23T12:00:00+00:00",
|
||||
reason="Synthetic test evidence",
|
||||
inputs=[input_view(reference), input_view(reference, "oblique")],
|
||||
observed_paint=[
|
||||
dict(view="top", paint=[[1, 2, 5]], background=[[4, 1, 7]], unknown=[[2, 2, 5]])
|
||||
],
|
||||
contextual_map=[
|
||||
dict(
|
||||
feature_id="road",
|
||||
geometry_sha256=ds.digest(geometry),
|
||||
ranges=[[0, 0, 0.25, 0.75]],
|
||||
state="confirmed",
|
||||
evidence="context",
|
||||
support=[input_view(reference, "oblique")],
|
||||
reason="Synthetic surrounding view supports this interval",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample(admission, corpus, tmp_path):
|
||||
a = dataset(tmp_path, "source")
|
||||
receipt = corpus.build(
|
||||
tmp_path, plan(corpus, [a], [group("physical-a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, receipt) as reader:
|
||||
reference = refs(reader)[0]
|
||||
return receipt, reference, decision(admission, reference)
|
||||
|
||||
|
||||
def release(admission, root, receipt, references, decisions, destination="supervision/v1"):
|
||||
(root / "reviews").mkdir(exist_ok=True)
|
||||
entries = []
|
||||
for i, d in enumerate(decisions):
|
||||
path = root / "reviews" / f"{destination.replace('/', '-')}-{i}.json"
|
||||
ds.write(path, d)
|
||||
entries.append(dict(path=path.relative_to(root).as_posix(), sha256=ds.checksum(path)))
|
||||
revisions = {r["source"]["world_sha256"]: identity(r) for r in references}
|
||||
p = dict(
|
||||
schema_version=admission.PLAN_SCHEMA,
|
||||
corpus=receipt,
|
||||
revisions=list(revisions.values()),
|
||||
decisions=entries,
|
||||
)
|
||||
return admission.build(root, p, destination), p
|
||||
|
||||
|
||||
def records(reader, task="observed_paint", split="train"):
|
||||
return [r for b in reader.batches(task, split) for r in b]
|
||||
|
||||
|
||||
def test_sparse_pixels_preserve_unknown_and_context_is_a_separate_target(
|
||||
admission, corpus, tmp_path, sample
|
||||
):
|
||||
receipt, reference, d = sample
|
||||
with opened(corpus, tmp_path, receipt) as c:
|
||||
value = admission.compile_decision(c, d, admission.revision_policy([identity(reference)]))
|
||||
pixels = admission.pixel_target(value["observed_paint"][0])
|
||||
assert len(pixels) == 48 and pixels.count(1) == 3 and pixels.count(0) == 6
|
||||
assert pixels.count(255) == 39 and pixels[2 * 8 + 3] == 255
|
||||
# No automatic conversion of reconstructed geometry to a visible-paint mask.
|
||||
assert value["contextual_map"][0]["fragments"] == [
|
||||
[[1.0, 0.0, 0.1234567890123], [3.0, 0.0, 0.1234567890123]]
|
||||
]
|
||||
assert value["contextual_map"][0]["completeness"] == "reviewed-ranges-only"
|
||||
assert not value["background_from_absence"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
["pixel-conflict", "unknown-conflict", "bounds", "float", "duplicate-view", "missing-view"],
|
||||
)
|
||||
def test_ambiguous_pixel_supervision_fails(admission, corpus, tmp_path, sample, change):
|
||||
receipt, r, d = sample
|
||||
v = d["observed_paint"][0]
|
||||
if change == "pixel-conflict":
|
||||
v["background"] = [[1, 4, 6]]
|
||||
elif change == "unknown-conflict":
|
||||
v["unknown"] = [[1, 3, 4]]
|
||||
elif change == "bounds":
|
||||
v["paint"] = [[6, 1, 2]]
|
||||
elif change == "float":
|
||||
v["paint"] = [[1, 1.2, 2.2]]
|
||||
elif change == "duplicate-view":
|
||||
d["observed_paint"].append(copy.deepcopy(v))
|
||||
else:
|
||||
d["inputs"] = [input_view(r, "oblique")]
|
||||
with opened(corpus, tmp_path, receipt) as c, pytest.raises(ValueError):
|
||||
admission.compile_decision(c, d, admission.revision_policy([identity(r)]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
"rule",
|
||||
"no-support",
|
||||
"hidden-support",
|
||||
"deleted",
|
||||
"geometry",
|
||||
"range",
|
||||
"overlap",
|
||||
"no-reviewer",
|
||||
"time",
|
||||
],
|
||||
)
|
||||
def test_unsafe_vector_admission_fails(admission, corpus, tmp_path, sample, change):
|
||||
receipt, r, d = sample
|
||||
v = d["contextual_map"][0]
|
||||
if change == "rule":
|
||||
v["evidence"] = "rule"
|
||||
elif change == "no-support":
|
||||
v["support"] = []
|
||||
elif change == "hidden-support":
|
||||
d["inputs"] = [input_view(r)]
|
||||
elif change == "deleted":
|
||||
v["feature_id"] = "deleted"
|
||||
elif change == "geometry":
|
||||
v["geometry_sha256"] = "0" * 64
|
||||
elif change == "range":
|
||||
v["ranges"] = [[0, 2, 0, 1]]
|
||||
elif change == "overlap":
|
||||
d["contextual_map"].append(copy.deepcopy(v))
|
||||
elif change == "no-reviewer":
|
||||
d["reviewer"]["kind"] = "rule"
|
||||
else:
|
||||
d["reviewed_utc"] = "2026-10-23T12:00:00"
|
||||
with opened(corpus, tmp_path, receipt) as c, pytest.raises(ValueError):
|
||||
admission.compile_decision(c, d, admission.revision_policy([identity(r)]))
|
||||
|
||||
|
||||
def test_weak_and_unknown_are_retained_but_never_training_targets(
|
||||
admission, corpus, tmp_path, sample
|
||||
):
|
||||
receipt, r, d = sample
|
||||
d["observed_paint"][0]["paint"] = []
|
||||
d["observed_paint"][0]["background"] = []
|
||||
d["contextual_map"][0].update(state="weak", evidence="rule", support=[])
|
||||
unknown = copy.deepcopy(d["contextual_map"][0])
|
||||
unknown.update(state="unknown", evidence="unknown", ranges=[[0, 1, 0, 1]])
|
||||
d["contextual_map"].append(unknown)
|
||||
with opened(corpus, tmp_path, receipt) as c:
|
||||
compiled = admission.compile_decision(c, d, admission.revision_policy([identity(r)]))
|
||||
assert len(compiled["excluded_vectors"]) == 2 and not compiled["contextual_map"]
|
||||
assert set(admission.pixel_target(compiled["observed_paint"][0])) == {255}
|
||||
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
|
||||
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
|
||||
assert records(reader) == records(reader, "contextual_map") == []
|
||||
|
||||
|
||||
def test_release_uses_exact_revisions_and_does_not_modify_sources(
|
||||
admission, corpus, tmp_path, sample
|
||||
):
|
||||
receipt, r, d = sample
|
||||
source = tmp_path / "datasets/source"
|
||||
before = {p.relative_to(source): p.read_bytes() for p in source.rglob("*") if p.is_file()}
|
||||
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
|
||||
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
|
||||
paint = records(reader)[0]
|
||||
geometry = records(reader, "contextual_map")[0]
|
||||
assert paint["task"] == "observed_paint" and len(paint["targets"]) == 1
|
||||
assert "fragments" not in paint["targets"][0]
|
||||
assert geometry["targets"][0]["evidence"] == "context"
|
||||
assert geometry["supervision_scope"] == "reviewed-vector-ranges-only"
|
||||
assert not geometry["background_from_absence"]
|
||||
assert geometry["targets"][0]["supervised_axes"] == ["x", "y"]
|
||||
assert not geometry["targets"][0]["z_supervision"]
|
||||
assert len(geometry["inputs"]) == 2
|
||||
assert all("labels" not in i for i in geometry["inputs"])
|
||||
assert len(list(reader.training_batches("observed_paint"))) == 1
|
||||
assert before == {
|
||||
p.relative_to(source): p.read_bytes() for p in source.rglob("*") if p.is_file()
|
||||
}
|
||||
with opened(corpus, tmp_path, receipt) as c:
|
||||
wrong = identity(r)
|
||||
wrong["revision"] = "d" * 64
|
||||
with pytest.raises(ValueError, match="selected annotation"):
|
||||
admission.compile_decision(c, d, admission.revision_policy([wrong]))
|
||||
with pytest.raises(ValueError, match="exactly one"):
|
||||
admission.revision_policy([identity(r), wrong])
|
||||
|
||||
|
||||
def test_context_from_neighbors_must_be_present_and_cannot_cross_controls(
|
||||
admission, corpus, tmp_path
|
||||
):
|
||||
a = dataset(tmp_path, "a")
|
||||
neighbor = dataset(tmp_path, "neighbor")
|
||||
# Distinct export identity, still same frozen world/annotation coordinate frame.
|
||||
manifest = tmp_path / neighbor["path"] / "dataset.json"
|
||||
data = ds.read(manifest)
|
||||
data["description"] = "adjacent window fixture"
|
||||
ds.write(manifest, data)
|
||||
neighbor["sha256"] = ds.checksum(manifest)
|
||||
b = dataset(tmp_path, "b", world="f" * 64)
|
||||
receipt = corpus.build(
|
||||
tmp_path,
|
||||
plan(
|
||||
corpus, [a, neighbor, b], [group("a", "train", "a" * 64), group("b", "test", "f" * 64)]
|
||||
),
|
||||
"corpora/v1",
|
||||
)
|
||||
with opened(corpus, tmp_path, receipt) as c:
|
||||
aa = refs(c)
|
||||
rr = refs(c, "test")[0]
|
||||
d = decision(admission, aa[0])
|
||||
d["inputs"].append(input_view(aa[1]))
|
||||
d["contextual_map"][0]["support"] = [input_view(aa[1])]
|
||||
policy = admission.revision_policy([identity(aa[0]), identity(rr)])
|
||||
assert len(admission.compile_decision(c, d, policy)["inputs"]) == 3
|
||||
d["inputs"].append(input_view(rr))
|
||||
with pytest.raises(ValueError, match="Context must share"):
|
||||
admission.compile_decision(c, d, policy)
|
||||
d = decision(admission, aa[0])
|
||||
control = decision(admission, rr)
|
||||
frozen, _ = release(admission, tmp_path, receipt, [aa[0], rr], [d, control])
|
||||
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
|
||||
train = [r for batch in reader.training_batches("contextual_map") for r in batch]
|
||||
assert {v["sample_id"] for v in train} == {aa[0]["id"]}
|
||||
test = records(reader, "contextual_map", "test")
|
||||
assert len(test) == 1 and not test[0]["training_eligible"]
|
||||
|
||||
|
||||
def test_pinned_reviews_media_and_corpus_are_verified(admission, tmp_path, sample):
|
||||
receipt, r, d = sample
|
||||
frozen, p = release(admission, tmp_path, receipt, [r], [d])
|
||||
# Editing a draft decision does not change the already published release.
|
||||
ds.write(tmp_path / p["decisions"][0]["path"], {})
|
||||
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
|
||||
assert len(records(reader)) == 1
|
||||
with pytest.raises(ValueError, match="decision changed"):
|
||||
admission.build(tmp_path, p, "supervision/v2")
|
||||
(tmp_path / r["dataset"] / "window/top.png").write_bytes(b"corrupted")
|
||||
with pytest.raises(ValueError, match="member changed"):
|
||||
release(admission, tmp_path, receipt, [r], [d], "supervision/v3")
|
||||
assert not (tmp_path / "supervision/v3").exists()
|
||||
assert not list((tmp_path / "supervision").glob(".supervision-*"))
|
||||
manifest = ds.read(tmp_path / frozen["path"] / "supervision.json")
|
||||
member = next(v["path"] for v in manifest["records"].values())
|
||||
ds.write(tmp_path / frozen["path"] / member, {})
|
||||
with pytest.raises(ValueError, match="member changed"):
|
||||
admission.Supervision(tmp_path, frozen["path"], frozen["sha256"])
|
||||
|
||||
|
||||
def test_reader_is_lazy_and_portable_with_a_bounded_batch(admission, tmp_path, sample, monkeypatch):
|
||||
receipt, r, d = sample
|
||||
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
|
||||
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
|
||||
original = Path.open
|
||||
|
||||
def no_media(path, *a, **kw):
|
||||
if path.suffix == ".png":
|
||||
pytest.fail("metadata iteration opened RGB")
|
||||
return original(path, *a, **kw)
|
||||
|
||||
with monkeypatch.context() as scoped:
|
||||
scoped.setattr(Path, "open", no_media)
|
||||
assert len(records(reader)) == 1
|
||||
moved = tmp_path.with_name(tmp_path.name + "-moved")
|
||||
tmp_path.rename(moved)
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-B",
|
||||
str(moved / frozen["path"] / "admission_store.py"),
|
||||
"inspect",
|
||||
str(moved),
|
||||
frozen["path"],
|
||||
frozen["sha256"],
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert json.loads(result.stdout)["counts"]["train"]["contextual_map"] == 1
|
||||
with admission.Supervision(moved, frozen["path"], frozen["sha256"]) as reader:
|
||||
with pytest.raises(ValueError):
|
||||
list(reader.training_batches("all"))
|
||||
with pytest.raises(ValueError):
|
||||
list(reader.training_batches("contextual_map", 129))
|
||||
moved.rename(tmp_path)
|
||||
|
||||
|
||||
def test_overwrite_duplicate_and_budget_failure_preserve_old_release(
|
||||
admission, tmp_path, sample, monkeypatch
|
||||
):
|
||||
receipt, r, d = sample
|
||||
frozen, p = release(admission, tmp_path, receipt, [r], [d])
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
admission.build(tmp_path, p, frozen["path"])
|
||||
duplicate = copy.deepcopy(p)
|
||||
duplicate["decisions"] *= 2
|
||||
with pytest.raises(ValueError, match="Conflicting decisions"):
|
||||
admission.build(tmp_path, duplicate, "supervision/duplicate")
|
||||
for path in ("../escape", "datasets/source/inside", "corpora/v1/inside", "reviews"):
|
||||
with pytest.raises(ValueError):
|
||||
admission.build(tmp_path, p, path)
|
||||
monkeypatch.setattr(admission, "MAX_RELEASE", 10)
|
||||
with pytest.raises(ValueError, match="byte budget"):
|
||||
admission.build(tmp_path, p, "supervision/v2")
|
||||
assert not list((tmp_path / "supervision").glob(".supervision-*"))
|
||||
assert ds.checksum(tmp_path / frozen["path"] / "supervision.json") == frozen["sha256"]
|
||||
|
||||
|
||||
def test_ranges_never_silently_flatten_curves_or_fill_polygons(admission):
|
||||
f = dict(
|
||||
geometry=dict(type="Polygon", coordinates=[[[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 0, 0]]]),
|
||||
properties={},
|
||||
)
|
||||
assert admission.fragments(f, [[0, 0, 0, 1]]) == [[[0, 0, 0], [1, 0, 0]]]
|
||||
f["properties"]["editor_curves"] = {"0": {"mode": "curved"}}
|
||||
with pytest.raises(ValueError, match="curve-aware"):
|
||||
admission.fragments(f, [[0, 0, 0, 1]])
|
||||
|
||||
|
||||
def test_one_object_cannot_have_conflicting_geometry_in_one_selected_revision(
|
||||
admission, corpus, tmp_path
|
||||
):
|
||||
a = dataset(tmp_path, "a")
|
||||
b = dataset(tmp_path, "b")
|
||||
root = tmp_path / b["path"]
|
||||
labels = ds.read(root / "window/labels.json")
|
||||
labels["proposed_element"][0]["geometry"]["coordinates"][0][0] = 1.0
|
||||
ds.write(root / "window/labels.json", labels)
|
||||
manifest = ds.read(root / "dataset.json")
|
||||
manifest["files"]["window/labels.json"] = dict(
|
||||
sha256=ds.checksum(root / "window/labels.json"),
|
||||
bytes=(root / "window/labels.json").stat().st_size,
|
||||
)
|
||||
ds.write(root / "dataset.json", manifest)
|
||||
b["sha256"] = ds.checksum(root / "dataset.json")
|
||||
receipt = corpus.build(
|
||||
tmp_path, plan(corpus, [a, b], [group("a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, receipt) as c:
|
||||
references = refs(c)
|
||||
decisions = [decision(admission, r) for r in references]
|
||||
for d, r in zip(decisions, references, strict=True):
|
||||
d["contextual_map"][0]["geometry_sha256"] = ds.digest(
|
||||
c.review(r)["active_candidates"][0]["geometry"]
|
||||
)
|
||||
with pytest.raises(ValueError, match="Conflicting source geometry"):
|
||||
release(admission, tmp_path, receipt, references, decisions)
|
||||
assert not (tmp_path / "supervision/v1").exists()
|
||||
|
||||
|
||||
def test_unknown_only_views_are_not_empty_loss_targets_and_media_is_rechecked(
|
||||
admission, tmp_path, sample
|
||||
):
|
||||
receipt, r, d = sample
|
||||
d["observed_paint"].append(dict(view="oblique", paint=[], background=[], unknown=[[0, 0, 8]]))
|
||||
frozen, _ = release(admission, tmp_path, receipt, [r], [d])
|
||||
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
|
||||
example = records(reader)[0]
|
||||
assert len(example["targets"]) == 1 and len(example["inputs"]) == 2
|
||||
value = example["inputs"][0]
|
||||
with reader.open_image(value) as stream:
|
||||
assert stream.read() == b"synthetic-raw-view-top"
|
||||
assert stream.closed
|
||||
fake = copy.deepcopy(value)
|
||||
fake["rgb"]["name"] = "window/labels.json"
|
||||
with pytest.raises(ValueError, match="bound raw RGB"):
|
||||
reader.open_image(fake)
|
||||
(tmp_path / r["dataset"] / value["rgb"]["name"]).write_bytes(b"changed")
|
||||
with pytest.raises(ValueError, match="member changed"), reader.open_image(value):
|
||||
pass
|
||||
|
||||
|
||||
def test_multiple_reviewed_windows_use_bounded_batches(admission, corpus, tmp_path):
|
||||
inputs = []
|
||||
for i in range(3):
|
||||
entry = dataset(tmp_path, str(i))
|
||||
path = tmp_path / entry["path"] / "dataset.json"
|
||||
manifest = ds.read(path)
|
||||
manifest["window_identity"] = i
|
||||
ds.write(path, manifest)
|
||||
entry["sha256"] = ds.checksum(path)
|
||||
inputs.append(entry)
|
||||
receipt = corpus.build(
|
||||
tmp_path, plan(corpus, inputs, [group("area-a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, receipt) as c:
|
||||
references = refs(c)
|
||||
frozen, _ = release(
|
||||
admission, tmp_path, receipt, references, [decision(admission, r) for r in references]
|
||||
)
|
||||
with admission.Supervision(tmp_path, frozen["path"], frozen["sha256"]) as reader:
|
||||
assert [len(b) for b in reader.training_batches("contextual_map", 2)] == [2, 1]
|
||||
|
||||
|
||||
def test_unverified_vertical_height_is_not_a_planar_target(admission):
|
||||
feature = dict(
|
||||
geometry=dict(type="LineString", coordinates=[[1, 2, 3], [1, 2, 4]]), properties={}
|
||||
)
|
||||
with pytest.raises(ValueError, match="planar"):
|
||||
admission.fragments(feature, [[0, 0, 0, 1]])
|
||||
@@ -0,0 +1,133 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"condition_inventory",
|
||||
Path(__file__).resolve().parents[1] / "simulation/semantic-learning/condition_inventory.py",
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def example():
|
||||
t = np.array([[1, 0], [255, 1]], dtype="uint8")
|
||||
s = dict(
|
||||
name="sample",
|
||||
split="train",
|
||||
kind="existing",
|
||||
size=[2, 2],
|
||||
group="street",
|
||||
target_sha256=hashlib.sha256(t.tobytes()).hexdigest(),
|
||||
rgb_sha256="a" * 64,
|
||||
)
|
||||
r = dict(
|
||||
name=s["name"],
|
||||
target_sha256=s["target_sha256"],
|
||||
input_sha256=s["rgb_sha256"],
|
||||
regions=[
|
||||
dict(
|
||||
id="paint",
|
||||
tag="paint_weak_visible",
|
||||
family="line",
|
||||
polygon=[[0, 0], [512, 0], [512, 512], [0, 512]],
|
||||
reason="Visible low contrast trace",
|
||||
)
|
||||
],
|
||||
)
|
||||
return s, r, t
|
||||
|
||||
|
||||
def test_conditions_never_create_targets_or_background():
|
||||
s, r, t = example()
|
||||
before = t.copy()
|
||||
t.flags.writeable = False
|
||||
out, masks = m.compile_record(s, r, t)
|
||||
assert out["regions"][0]["reviewed_pixels"] == 2
|
||||
assert out["regions"][0]["unknown_region_pixels"] == 1
|
||||
assert np.array_equal(t, before)
|
||||
assert np.array_equal(masks["paint"], t == 1)
|
||||
bg = copy.deepcopy(r["regions"][0])
|
||||
bg.update(id="background", tag="background_asphalt", family="surface")
|
||||
r["regions"].append(bg)
|
||||
out, masks = m.compile_record(s, r, t)
|
||||
assert int(masks["background"].sum()) == 1
|
||||
assert not masks["background"][1, 0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
[
|
||||
"split",
|
||||
"target",
|
||||
"source",
|
||||
"shape",
|
||||
"class",
|
||||
"duplicate",
|
||||
"overlap",
|
||||
"polygon",
|
||||
"family",
|
||||
"kind",
|
||||
"missing_target_pin",
|
||||
],
|
||||
)
|
||||
def test_invalid_evidence_is_rejected(mutation):
|
||||
s, r, t = example()
|
||||
if mutation == "kind":
|
||||
s["kind"] = "unsupported"
|
||||
elif mutation == "missing_target_pin":
|
||||
s["target_sha256"] = r["target_sha256"] = None
|
||||
elif mutation == "split":
|
||||
s["split"] = "regression"
|
||||
elif mutation == "target":
|
||||
t[0, 0] = 0
|
||||
elif mutation == "source":
|
||||
r["input_sha256"] = "b" * 64
|
||||
elif mutation == "shape":
|
||||
s["size"] = [4, 1]
|
||||
elif mutation == "class":
|
||||
t[0, 0] = 7
|
||||
elif mutation == "duplicate":
|
||||
r["regions"].append(copy.deepcopy(r["regions"][0]))
|
||||
elif mutation == "overlap":
|
||||
rr = copy.deepcopy(r["regions"][0])
|
||||
rr.update(id="conflict", tag="paint_clear")
|
||||
r["regions"].append(rr)
|
||||
elif mutation == "polygon":
|
||||
r["regions"][0]["polygon"] = [[0, 0], [512, 512], [0, 512], [512, 0]]
|
||||
elif mutation == "family":
|
||||
r["regions"][0]["family"] = "surface"
|
||||
with pytest.raises(ValueError):
|
||||
m.compile_record(s, r, t)
|
||||
|
||||
|
||||
def test_candidate_remains_unknown():
|
||||
s, r, t = example()
|
||||
s.update(kind="candidate", target_sha256=None)
|
||||
r["target_sha256"] = None
|
||||
t[:] = 255
|
||||
out, masks = m.compile_record(s, r, t)
|
||||
assert out["regions"][0]["reviewed_pixels"] == 0
|
||||
assert not masks["paint"].any()
|
||||
t[0, 0] = 1
|
||||
with pytest.raises(ValueError):
|
||||
m.compile_record(s, r, t)
|
||||
|
||||
|
||||
def test_overlap_detects_shifted_duplicate_not_new_street():
|
||||
assert m.overlap_fraction([0, 0, 12, 12], [4.5, 4, 16.5, 16]) == pytest.approx(5 / 12)
|
||||
assert m.overlap_fraction([0, 0, 12, 12], [12, 0, 24, 12]) == 0
|
||||
camera = dict(
|
||||
projection="ortho",
|
||||
size=[512, 512],
|
||||
view_matrix=[[1, 0, 0, -100], [0, -1, 0, 20], [0, 0, -1, 30], [0, 0, 0, 1]],
|
||||
intrinsics=[[512 / 12, 0, 256], [0, 512 / 12, 256], [0, 0, 1]],
|
||||
)
|
||||
assert m.footprint(camera) == pytest.approx([94, 14, 106, 26])
|
||||
camera["projection"] = "pinhole"
|
||||
with pytest.raises(ValueError):
|
||||
m.footprint(camera)
|
||||
@@ -0,0 +1,387 @@
|
||||
"""Frozen multi-area corpus: lazy views, source integrity and growth isolation."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_semantic_delivery import ds
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def corpus(monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "dataset_store", ds)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"corpus_store_test", ROOT / "simulation/semantic-learning/corpus_store.py"
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def dataset(store, name, world, *, count=3, split_group=None, revision="a" * 64):
|
||||
root = store / "datasets" / name
|
||||
root.mkdir(parents=True)
|
||||
samples = []
|
||||
for i in range(count):
|
||||
folder = root / f"sample-{i}"
|
||||
folder.mkdir()
|
||||
(folder / "top.rgb.bin").write_bytes(b"synthetic-top")
|
||||
(folder / "oblique.rgb.bin").write_bytes(b"synthetic-oblique")
|
||||
ds.write(folder / "camera.json", dict(projection="orthographic", metric_scale=0.1))
|
||||
feature = dict(id="edited", properties=dict(review_status="accepted"))
|
||||
ds.write(
|
||||
folder / "labels.json",
|
||||
dict(
|
||||
original_element=[],
|
||||
proposed_element=[feature],
|
||||
projections={
|
||||
"top": [dict(feature_id="edited")],
|
||||
"oblique": [dict(feature_id="edited")],
|
||||
},
|
||||
),
|
||||
)
|
||||
ds.write(
|
||||
folder / "sample.json",
|
||||
dict(
|
||||
members=[p.relative_to(root).as_posix() for p in sorted(folder.iterdir())],
|
||||
training_eligible=False,
|
||||
complete_regions=[],
|
||||
revision=revision,
|
||||
split_group=split_group or world,
|
||||
),
|
||||
)
|
||||
samples.append(f"sample-{i}/sample.json")
|
||||
ds.write(
|
||||
root / "dataset.json",
|
||||
dict(
|
||||
schema_version=ds.SCHEMA,
|
||||
training_eligible=False,
|
||||
revision=revision,
|
||||
world_sha256=world,
|
||||
split_group=split_group or world,
|
||||
annotation_sha256="c" * 64,
|
||||
samples=samples,
|
||||
files={
|
||||
p.relative_to(root).as_posix(): dict(sha256=ds.checksum(p), bytes=p.stat().st_size)
|
||||
for p in root.rglob("*")
|
||||
if p.is_file()
|
||||
},
|
||||
),
|
||||
)
|
||||
return dict(path=root.relative_to(store).as_posix(), sha256=ds.checksum(root / "dataset.json"))
|
||||
|
||||
|
||||
def group(name, split, *worlds):
|
||||
return dict(id=name, split=split, worlds=list(worlds))
|
||||
|
||||
|
||||
def plan(corpus, datasets, groups, **kw):
|
||||
return dict(schema_version=corpus.PLAN_SCHEMA, datasets=datasets, groups=groups, **kw)
|
||||
|
||||
|
||||
def refs(reader, split="train", **kw):
|
||||
return [r for batch in reader.batches(split, **kw) for r in batch]
|
||||
|
||||
|
||||
def opened(corpus, root, receipt):
|
||||
return corpus.Corpus(root, receipt["path"], receipt["sha256"])
|
||||
|
||||
|
||||
def test_batches_keep_all_views_and_do_not_promote_editor_acceptance(corpus, tmp_path):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
b = dataset(tmp_path, "b", "b" * 64)
|
||||
frozen = corpus.build(
|
||||
tmp_path,
|
||||
plan(
|
||||
corpus,
|
||||
[a, b],
|
||||
[
|
||||
group("area-a", "train", "a" * 64),
|
||||
group("area-b", "test", "b" * 64),
|
||||
],
|
||||
),
|
||||
"corpora/v1",
|
||||
)
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
batches = list(reader.batches("train", batch_size=2))
|
||||
assert [len(b) for b in batches] == [2, 1]
|
||||
assert {r["dataset"] for b in batches for r in b} == {a["path"]}
|
||||
assert len(refs(reader, "test")) == 3
|
||||
reference = batches[0][0]
|
||||
assert len(reference["members"]) == 4
|
||||
viewed = reader.review(reference)
|
||||
assert set(viewed["views"]) == {"top", "oblique"}
|
||||
assert viewed["approved_targets"] == viewed["background_targets"] == []
|
||||
assert viewed["training_eligible"] is False
|
||||
name = next(n for n in reference["members"] if n.endswith("top.rgb.bin"))
|
||||
with reader.open_member(reference, name) as stream:
|
||||
assert stream.read() == b"synthetic-top"
|
||||
assert stream.closed
|
||||
|
||||
|
||||
def test_same_area_scans_and_revisions_share_split(corpus, tmp_path):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
revision = dataset(tmp_path, "a2", "a" * 64, revision="e" * 64)
|
||||
other_scan = dataset(tmp_path, "b", "b" * 64)
|
||||
frozen = corpus.build(
|
||||
tmp_path,
|
||||
plan(
|
||||
corpus,
|
||||
[a, revision, other_scan],
|
||||
[
|
||||
group("same-physical-area", "validation", "a" * 64, "b" * 64),
|
||||
],
|
||||
),
|
||||
"corpora/v1",
|
||||
)
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
assert not refs(reader, "train")
|
||||
rows = refs(reader, "validation")
|
||||
assert len(rows) == 9
|
||||
assert {r["physical_group"] for r in rows} == {"same-physical-area"}
|
||||
|
||||
|
||||
def test_ambiguous_groups_and_related_source_groups_fail(corpus, tmp_path):
|
||||
a = dataset(tmp_path, "a", "a" * 64, split_group="c" * 64)
|
||||
b = dataset(tmp_path, "b", "b" * 64, split_group="c" * 64)
|
||||
with pytest.raises(ValueError, match="multiple physical"):
|
||||
corpus.build(
|
||||
tmp_path,
|
||||
plan(
|
||||
corpus,
|
||||
[a],
|
||||
[
|
||||
group("a", "train", "a" * 64),
|
||||
group("b", "test", "a" * 64),
|
||||
],
|
||||
),
|
||||
"corpora/bad",
|
||||
)
|
||||
with pytest.raises(ValueError, match="split_group"):
|
||||
corpus.build(
|
||||
tmp_path,
|
||||
plan(
|
||||
corpus,
|
||||
[a, b],
|
||||
[
|
||||
group("a", "train", "a" * 64),
|
||||
group("b", "test", "b" * 64),
|
||||
],
|
||||
),
|
||||
"corpora/bad",
|
||||
)
|
||||
assert not (tmp_path / "corpora/bad").exists()
|
||||
assert not list((tmp_path / "corpora").glob(".corpus-*"))
|
||||
|
||||
|
||||
def test_adding_unlisted_data_does_not_change_pinned_corpus(corpus, tmp_path, monkeypatch):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
frozen = corpus.build(
|
||||
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
before = refs(reader)
|
||||
dataset(tmp_path, "unlisted", "b" * 64)
|
||||
monkeypatch.setattr(Path, "rglob", lambda *a, **k: pytest.fail("Reader scanned the store"))
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
assert refs(reader) == before
|
||||
assert ds.checksum(tmp_path / "corpora/v1/corpus.json") == frozen["sha256"]
|
||||
|
||||
|
||||
def test_growth_preserves_old_data_and_split_assignments(corpus, tmp_path):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
policy = [group("a", "train", "a" * 64)]
|
||||
old = corpus.build(tmp_path, plan(corpus, [a], policy), "corpora/v1")
|
||||
b = dataset(tmp_path, "b", "b" * 64)
|
||||
new_policy = policy + [group("b", "test", "b" * 64)]
|
||||
expanded = plan(corpus, [a, b], new_policy, parent=old)
|
||||
new = corpus.build(tmp_path, expanded, "corpora/v2")
|
||||
with opened(corpus, tmp_path, old) as first, opened(corpus, tmp_path, new) as second:
|
||||
assert refs(first) == refs(second)
|
||||
assert len(refs(second, "test")) == 3
|
||||
bad = copy.deepcopy(expanded)
|
||||
bad["groups"][0]["split"] = "test"
|
||||
with pytest.raises(ValueError, match="prior physical"):
|
||||
corpus.build(tmp_path, bad, "corpora/v3")
|
||||
bad = copy.deepcopy(expanded)
|
||||
bad["datasets"] = [b]
|
||||
with pytest.raises(ValueError, match="discard"):
|
||||
corpus.build(tmp_path, bad, "corpora/v3")
|
||||
|
||||
|
||||
def test_reader_does_not_open_media_until_requested_and_detects_tampering(
|
||||
corpus, tmp_path, monkeypatch
|
||||
):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
frozen = corpus.build(
|
||||
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
original_open = Path.open
|
||||
with monkeypatch.context() as scoped:
|
||||
|
||||
def no_media(path, *args, **kwargs):
|
||||
if path.suffix == ".bin":
|
||||
pytest.fail("Unexpected media read")
|
||||
return original_open(path, *args, **kwargs)
|
||||
|
||||
scoped.setattr(Path, "open", no_media)
|
||||
reference = refs(reader)[0]
|
||||
reader.review(reference)
|
||||
name = next(n for n in reference["members"] if n.endswith("top.rgb.bin"))
|
||||
(tmp_path / a["path"] / name).write_bytes(b"X" * len(b"synthetic-top"))
|
||||
with pytest.raises(ValueError, match="member changed"), reader.open_member(reference, name):
|
||||
pass
|
||||
|
||||
|
||||
def test_reference_and_index_identity_cannot_be_substituted(corpus, tmp_path):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
frozen = corpus.build(
|
||||
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with pytest.raises(ValueError, match="manifest changed"):
|
||||
corpus.Corpus(tmp_path, frozen["path"], "0" * 64)
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
row = refs(reader)[0]
|
||||
row["split"] = "test"
|
||||
with pytest.raises(ValueError, match="Reference"):
|
||||
reader.review(row)
|
||||
with (tmp_path / "corpora/v1/index.sqlite3").open("ab") as f:
|
||||
f.write(b"corruption")
|
||||
with pytest.raises(ValueError, match="member changed"):
|
||||
opened(corpus, tmp_path, frozen)
|
||||
|
||||
|
||||
def test_relocated_store_works_with_bundled_reader_cli(corpus, tmp_path):
|
||||
root = tmp_path / "original"
|
||||
a = dataset(root, "a", "a" * 64)
|
||||
frozen = corpus.build(root, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1")
|
||||
moved = tmp_path / "relocated store"
|
||||
root.rename(moved)
|
||||
with opened(corpus, moved, frozen) as reader:
|
||||
assert len(refs(reader)) == 3
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-B",
|
||||
str(moved / "corpora/v1/corpus_store.py"),
|
||||
"inspect",
|
||||
str(moved),
|
||||
frozen["path"],
|
||||
frozen["sha256"],
|
||||
"--split",
|
||||
"train",
|
||||
"--limit",
|
||||
"2",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=tmp_path,
|
||||
)
|
||||
data = json.loads(result.stdout)
|
||||
assert data["total"] == 3 and len(data["samples"]) == 2
|
||||
|
||||
|
||||
def test_batch_byte_budget_and_invalid_requests(corpus, tmp_path, monkeypatch):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
frozen = corpus.build(
|
||||
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
size = len(json.dumps(refs(reader)[0], sort_keys=True, allow_nan=False).encode())
|
||||
monkeypatch.setattr(corpus, "MAX_BATCH_BYTES", size * 2 - 1)
|
||||
assert [len(b) for b in reader.batches("train", batch_size=128)] == [1, 1, 1]
|
||||
for split, count in [("all", 8), ("train", 0), ("train", 129), ("train", True)]:
|
||||
with pytest.raises(ValueError):
|
||||
list(reader.batches(split, count))
|
||||
assert not refs(reader, physical_group="not-present")
|
||||
|
||||
|
||||
def test_refuses_overwrite_unsafe_paths_and_unknown_sources(corpus, tmp_path):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
p = plan(corpus, [a], [group("a", "train", "a" * 64)])
|
||||
corpus.build(tmp_path, p, "corpora/v1")
|
||||
for destination in ["corpora/v1", "datasets/a/corpus", "../escape", "/tmp/escape"]:
|
||||
with pytest.raises(ValueError):
|
||||
corpus.build(tmp_path, p, destination)
|
||||
with pytest.raises(ValueError, match="Missing physical"):
|
||||
corpus.build(
|
||||
tmp_path, plan(corpus, [a], [group("unknown", "train", "b" * 64)]), "corpora/v2"
|
||||
)
|
||||
with pytest.raises(ValueError, match="Duplicate corpus dataset"):
|
||||
corpus.build(tmp_path, plan(corpus, [a, a], p["groups"]), "corpora/v2")
|
||||
|
||||
|
||||
def test_collection_member_paths_and_source_geometry_remain_bound(corpus, tmp_path):
|
||||
from test_semantic_review_reader import collection, labels
|
||||
|
||||
root = tmp_path / "datasets" / "collection"
|
||||
original = labels()
|
||||
collection(root, [original, original])
|
||||
entry = dict(path="datasets/collection", sha256=ds.checksum(root / "dataset.json"))
|
||||
frozen = corpus.build(
|
||||
tmp_path,
|
||||
plan(corpus, [entry], [group("same-area", "regression", "b" * 64)]),
|
||||
"corpora/v1",
|
||||
)
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
rows = refs(reader, "regression")
|
||||
assert len(rows) == 2
|
||||
assert {r["sample"] for r in rows} == {"part-000/sample.json", "part-001/sample.json"}
|
||||
for row in rows:
|
||||
reviewed = reader.review(row)
|
||||
assert reviewed["original"] == original["original_element"]
|
||||
assert reviewed["active_candidates"][0] == original["proposed_element"][0]
|
||||
assert reviewed["rejected_history"] == [original["proposed_element"][1]]
|
||||
with reader.open_member(row, row["labels"]) as stream:
|
||||
assert json.load(stream) == original
|
||||
|
||||
|
||||
def test_index_capacity_failure_cleans_only_own_scratch(corpus, tmp_path, monkeypatch):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
p = plan(corpus, [a], [group("a", "train", "a" * 64)])
|
||||
old = corpus.build(tmp_path, p, "corpora/v1")
|
||||
monkeypatch.setattr(corpus, "MAX_INDEX_BYTES", 4096)
|
||||
with pytest.raises(ValueError, match="capacity exhausted"):
|
||||
corpus.build(tmp_path, p, "corpora/v2")
|
||||
assert not (tmp_path / "corpora/v2").exists()
|
||||
assert not list((tmp_path / "corpora").glob(".corpus-*"))
|
||||
with opened(corpus, tmp_path, old) as reader:
|
||||
assert len(refs(reader)) == 3
|
||||
assert ds.checksum(tmp_path / a["path"] / "dataset.json") == a["sha256"]
|
||||
|
||||
|
||||
def test_unbound_sqlite_sidecars_cannot_override_pinned_index(corpus, tmp_path):
|
||||
a = dataset(tmp_path, "a", "a" * 64)
|
||||
frozen = corpus.build(
|
||||
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
||||
)
|
||||
index = tmp_path / "corpora/v1/index.sqlite3"
|
||||
# A WAL is outside the published manifest. Even a pending valid SQLite
|
||||
# transaction must not contribute unbound rows to the frozen corpus.
|
||||
db = sqlite3.connect(index)
|
||||
try:
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
# WAL mode changes the main header; pin this consistent mode before the
|
||||
# separate sidecar transaction, to exercise the reader's WAL isolation.
|
||||
manifest_path = tmp_path / "corpora/v1/corpus.json"
|
||||
manifest = ds.read(manifest_path)
|
||||
manifest["files"]["index.sqlite3"]["sha256"] = ds.checksum(index)
|
||||
ds.write(manifest_path, manifest)
|
||||
frozen["sha256"] = ds.checksum(manifest_path)
|
||||
db.execute("UPDATE samples SET split='test'")
|
||||
db.commit()
|
||||
assert ds.checksum(index) == manifest["files"]["index.sqlite3"]["sha256"]
|
||||
with opened(corpus, tmp_path, frozen) as reader:
|
||||
assert len(refs(reader, "train")) == 3
|
||||
assert not refs(reader, "test")
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,90 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
spec = importlib.util.spec_from_file_location("coverage_factorial", ROOT / "coverage_factorial.py")
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def fixture():
|
||||
rows = []
|
||||
for group in "abcd":
|
||||
for coverage in ["old", "new"]:
|
||||
for family, fpr in [("linear", 0.20), ("head", 0.15), ("decoder", 0.10)]:
|
||||
arms = (
|
||||
[f"{coverage}-linear"]
|
||||
if family == "linear"
|
||||
else [f"{coverage}-{family}-{s}" for s in [1, 2, 3]]
|
||||
)
|
||||
for arm in arms:
|
||||
rows.append(
|
||||
dict(
|
||||
phase="development",
|
||||
arm=arm,
|
||||
held_out=group,
|
||||
fitted_groups=[g for g in "abcd" if g != group],
|
||||
completed=True,
|
||||
metrics=dict(recall=0.9, fpr=fpr),
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def test_training_view_preserves_common_targets_and_unknown():
|
||||
old = np.array([[1, 255], [0, 255]], dtype="uint8")
|
||||
new = np.array([[1, 1], [0, 0]], dtype="uint8")
|
||||
r = dict(split="train", target=new, old_target=old, name="x")
|
||||
view = m.learning_view([r], "old")
|
||||
assert np.array_equal(view[0]["target"], old)
|
||||
assert view[0] is not r and r["target"] is new
|
||||
assert (view[0]["target"] == 255).sum() == 2
|
||||
with pytest.raises(ValueError):
|
||||
m.learning_view([dict(r, split="regression")], "old")
|
||||
|
||||
|
||||
def test_all_seeds_and_components_required_even_if_ber_improves():
|
||||
rows = fixture()
|
||||
assert m.assess(rows, [1, 2, 3])["eligible_families"] == [
|
||||
"old-head",
|
||||
"old-decoder",
|
||||
"new-head",
|
||||
"new-decoder",
|
||||
]
|
||||
bad = next(r for r in rows if r["held_out"] == "a" and r["arm"] == "old-decoder-2")
|
||||
bad["metrics"] = dict(recall=0.89, fpr=0.08)
|
||||
result = m.assess(rows, [1, 2, 3])
|
||||
assert "old-decoder" not in result["eligible_families"]
|
||||
checks = [c for c in result["audits"] if c["arm"] == "old-decoder-2"]
|
||||
assert all(c["composite_pass"] and not c["all_components_non_regressing"] for c in checks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["missing", "duplicate", "control", "leak", "incomplete"])
|
||||
def test_reject_invalid_comparison(kind):
|
||||
rows = fixture()
|
||||
if kind == "missing":
|
||||
rows.pop()
|
||||
elif kind == "duplicate":
|
||||
rows.append(dict(rows[0]))
|
||||
elif kind == "control":
|
||||
rows[0]["phase"] = "regression"
|
||||
elif kind == "leak":
|
||||
rows[0]["fitted_groups"].append(rows[0]["held_out"])
|
||||
else:
|
||||
rows[0]["completed"] = False
|
||||
with pytest.raises(ValueError):
|
||||
m.assess(rows, [1, 2, 3])
|
||||
|
||||
|
||||
def test_paired_interaction_does_not_select_a_seed():
|
||||
rows = fixture()
|
||||
out = m.effects(rows, [1, 2, 3])
|
||||
assert len(out) == 24 and {r["seed"] for r in out} == {1, 2, 3}
|
||||
assert all(r["interaction"] == 0 for r in out)
|
||||
rr = m.relabel_parent([dict(arm="decoder-1", metrics={"recall": 1})], "parent")
|
||||
assert rr[0]["arm"] == "new-decoder-1"
|
||||
@@ -0,0 +1,54 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SRC))
|
||||
spec = importlib.util.spec_from_file_location("crossing_probe", SRC / "crossing_diversity_probe.py")
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
sys.path.remove(str(SRC))
|
||||
|
||||
|
||||
def example(sid, split="train", group="a"):
|
||||
return dict(
|
||||
sample_id=sid,
|
||||
source="rev1",
|
||||
physical_group=group,
|
||||
split=split,
|
||||
inputs=[dict(rgb=dict(sha256=sid))],
|
||||
)
|
||||
|
||||
|
||||
def test_expansion_preserves_targets_and_rejects_control_or_duplicate_additions():
|
||||
old = {"a": example("a"), "c": example("c", "regression", "b")}
|
||||
new = dict(old, d=example("d"))
|
||||
before = {k: np.array([[0, 1, 255]], dtype="uint8") for k in old}
|
||||
after = dict(before, d=np.array([[0, 1, 255]], dtype="uint8"))
|
||||
probe.check_expansion(old, new, before, after)
|
||||
with pytest.raises(ValueError, match="training physical group"):
|
||||
probe.check_expansion(old, dict(new, d=example("d", "regression", "b")), before, after)
|
||||
with pytest.raises(ValueError, match="training targets changed"):
|
||||
probe.check_expansion(old, new, before, dict(after, a=np.array([[0, 1, 0]])))
|
||||
with pytest.raises(ValueError, match="Duplicate observation"):
|
||||
probe.check_expansion(
|
||||
old, dict(new, d=dict(example("d"), inputs=[dict(rgb=dict(sha256="a"))])), before, after
|
||||
)
|
||||
with pytest.raises(ValueError, match="both paint and gap"):
|
||||
probe.check_expansion(old, new, before, dict(after, d=np.array([[1, 255]])))
|
||||
|
||||
|
||||
def test_strict_control_and_gap_gates():
|
||||
good = dict(baseline=dict(recall=1.0, fpr=0.1), expanded=dict(recall=1.0, fpr=0.1))
|
||||
audit = dict(baseline=dict(recall=1.0, fpr=1.0), expanded=dict(recall=1.0, fpr=0.5))
|
||||
assert probe.qualify({"a": good}, audit, True)["accepted"]
|
||||
bad = dict(baseline=dict(recall=None, fpr=0.01), expanded=dict(recall=None, fpr=0.02))
|
||||
assert not probe.qualify({"a": good, "b": bad}, audit, True)["accepted"]
|
||||
assert not probe.qualify({"a": good}, audit, False)["accepted"]
|
||||
assert not probe.qualify({"a": good}, dict(audit, expanded=dict(recall=0.99, fpr=0.1)), True)[
|
||||
"accepted"
|
||||
]
|
||||
assert not probe.qualify({"a": good}, dict(audit, expanded=audit["baseline"]), True)["accepted"]
|
||||
@@ -0,0 +1,60 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SRC))
|
||||
spec = importlib.util.spec_from_file_location("decoder_probe", SRC / "decoder_adaptation_probe.py")
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
sys.path.remove(str(SRC))
|
||||
SEEDS = [20261023, 20261024, 20261025]
|
||||
|
||||
|
||||
def fixture():
|
||||
result = []
|
||||
for arm in ["old-linear", "new-linear"] + [
|
||||
f"{f}-{s}" for f in ["head", "decoder"] for s in SEEDS
|
||||
]:
|
||||
error = 0.2 if arm.endswith("linear") else 0.15 if arm.startswith("head") else 0.1
|
||||
for i in range(4):
|
||||
result.append(
|
||||
dict(
|
||||
phase="development",
|
||||
arm=arm,
|
||||
held_out=str(i),
|
||||
fitted_groups=[str(j) for j in range(4) if j != i],
|
||||
completed=True,
|
||||
metrics=dict(recall=1 - error, fpr=error),
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def test_decoder_requires_every_seed_and_improvement_over_paired_optimizer():
|
||||
rows = fixture()
|
||||
assert probe.choose(rows, SEEDS)["selected_family"] == "decoder"
|
||||
# One weak seed cannot be hidden by selecting the other two.
|
||||
bad = [
|
||||
dict(r, metrics=dict(recall=0.79, fpr=0.21)) if r["arm"] == f"decoder-{SEEDS[-1]}" else r
|
||||
for r in rows
|
||||
]
|
||||
assert probe.choose(bad, SEEDS)["selected_family"] == "head"
|
||||
# Beating the linear reference alone is insufficient for decoder attribution.
|
||||
tied = [
|
||||
dict(r, metrics=dict(recall=0.85, fpr=0.15)) if r["arm"].startswith("decoder") else r
|
||||
for r in rows
|
||||
]
|
||||
assert probe.choose(tied, SEEDS)["selected_family"] == "head"
|
||||
|
||||
|
||||
def test_selection_rejects_leakage_controls_or_missing_folds():
|
||||
rows = fixture()
|
||||
with pytest.raises(ValueError, match="leakage"):
|
||||
probe.choose([dict(rows[0], fitted_groups=["0", "1", "2"])] + rows[1:], SEEDS)
|
||||
with pytest.raises(ValueError, match="Development"):
|
||||
probe.choose([dict(rows[0], phase="regression")] + rows[1:], SEEDS)
|
||||
with pytest.raises(ValueError, match="Incomplete"):
|
||||
probe.choose(rows[:-1], SEEDS)
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Durable outbox/inbox boundaries, including crash and acknowledgement replay."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_semantic_edits import change, make_setup
|
||||
|
||||
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, digest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"dataset_store", Path(__file__).parents[1] / "simulation/semantic-learning/dataset_store.py"
|
||||
)
|
||||
ds = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(ds)
|
||||
|
||||
|
||||
def fixture(tmp_path):
|
||||
world, model, maps, edits, sha = make_setup(tmp_path / "core")
|
||||
world["world_id"] = "aiworld-fixture"
|
||||
body = change(sha)
|
||||
body["origin"] = "agent-proposal"
|
||||
saved = edits.save(world, body)
|
||||
envelope = dict(
|
||||
world=world,
|
||||
source={"world_sha256": world["sha256"]},
|
||||
annotation=edits.export(world, saved["revision"]),
|
||||
)
|
||||
return world, edits, maps, saved, envelope
|
||||
|
||||
|
||||
def test_outbox_commit_and_receipt_replay(tmp_path):
|
||||
world, edits, maps, saved, env = fixture(tmp_path)
|
||||
edits = SemanticEdits(edits.root.parents[1], maps)
|
||||
assert edits.pending([world])[0]["revision"] == saved["revision"]
|
||||
assert saved["edited"]["features"][0]["properties"]["annotation_origin"] == "agent-proposal"
|
||||
worker = ds.Store(tmp_path / "worker", reserve=0)
|
||||
key = worker.accept(env)
|
||||
worker.db.close() # Received data survives process loss before HTTP ack.
|
||||
worker = ds.Store(tmp_path / "worker", reserve=0)
|
||||
assert worker.accept(env) == key
|
||||
assert worker.db.execute("SELECT count(*) FROM jobs").fetchone()[0] == 1
|
||||
receipt = json.loads(worker.db.execute("SELECT receipt FROM jobs").fetchone()[0])
|
||||
assert edits.receipt(world, key, receipt) == receipt
|
||||
assert edits.receipt(world, key, receipt) == receipt
|
||||
assert edits.pending([world]) == []
|
||||
assert edits.get(world)["learning"]["state"] == "received"
|
||||
newer = {**receipt, "state": "building"}
|
||||
edits.receipt(world, key, newer)
|
||||
assert edits.receipt(world, key, receipt) == newer
|
||||
altered = {**receipt, "package_sha256": "0" * 64}
|
||||
with pytest.raises(ValueError):
|
||||
edits.receipt(world, key, altered)
|
||||
assert edits.export(world, key) == env["annotation"]
|
||||
|
||||
|
||||
def test_inbox_conflict_capacity_and_orphan_replay(tmp_path):
|
||||
_, _, _, saved, env = fixture(tmp_path)
|
||||
worker = ds.Store(tmp_path / "worker", reserve=0)
|
||||
key = saved["revision"]
|
||||
ds.write(worker.root / "inbox" / (key + ".json"), env) # crash before SQL commit
|
||||
worker.accept(env)
|
||||
changed = copy.deepcopy(env)
|
||||
changed["annotation"]["package"]["review"]["state"] = "fake-approved"
|
||||
with pytest.raises(ValueError):
|
||||
worker.accept(changed)
|
||||
changed["annotation"]["sha256"] = digest(changed["annotation"]["package"])
|
||||
with pytest.raises(ValueError):
|
||||
worker.accept(changed)
|
||||
full = ds.Store(tmp_path / "full", reserve=0, quota=1)
|
||||
with pytest.raises(RuntimeError):
|
||||
full.accept(env)
|
||||
assert full.db.execute("SELECT count(*) FROM jobs").fetchone()[0] == 0
|
||||
|
||||
|
||||
def draft(root):
|
||||
root.mkdir()
|
||||
ds.write(root / "labels.json", {"review": "unreviewed"})
|
||||
ds.write(
|
||||
root / "sample.json",
|
||||
{"members": ["labels.json"], "training_eligible": False, "complete_regions": []},
|
||||
)
|
||||
files = {p.name: {"sha256": ds.checksum(p), "bytes": p.stat().st_size} for p in root.iterdir()}
|
||||
ds.write(
|
||||
root / "dataset.json",
|
||||
{
|
||||
"schema_version": ds.SCHEMA,
|
||||
"training_eligible": False,
|
||||
"files": files,
|
||||
"samples": ["sample.json"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_atomic_publication_restart_portability_and_corruption(tmp_path):
|
||||
_, _, _, _, env = fixture(tmp_path)
|
||||
worker = ds.Store(tmp_path / "worker", reserve=0)
|
||||
key = worker.accept(env)
|
||||
assert worker.next() == key
|
||||
staging = worker.root / "work" / "draft"
|
||||
draft(staging)
|
||||
expected = ds.verify(staging)
|
||||
# Crash after atomic publication but before state commit.
|
||||
staging.rename(worker.root / "datasets" / key)
|
||||
worker.db.close()
|
||||
worker = ds.Store(worker.root, reserve=0)
|
||||
assert worker.next() is None
|
||||
receipt = json.loads(worker.db.execute("SELECT receipt FROM jobs").fetchone()[0])
|
||||
assert receipt["dataset_sha256"] == expected["sha256"]
|
||||
import shutil
|
||||
|
||||
elsewhere = tmp_path / "unrelated-root"
|
||||
shutil.copytree(worker.root / "datasets" / key, elsewhere)
|
||||
assert ds.verify(elsewhere) == expected
|
||||
(elsewhere / "labels.json").write_text("{}")
|
||||
with pytest.raises(ValueError):
|
||||
ds.verify(elsewhere)
|
||||
|
||||
|
||||
def test_retry_bound_and_next_job_not_starved(tmp_path):
|
||||
_, _, _, _, env = fixture(tmp_path)
|
||||
worker = ds.Store(tmp_path / "worker", reserve=0)
|
||||
key = worker.accept(env)
|
||||
for _ in range(3):
|
||||
assert worker.next() == key
|
||||
assert worker.next() is None
|
||||
assert worker.db.execute("SELECT state FROM jobs").fetchone()[0] == "failed"
|
||||
assert not ds.confined(worker.root, "labels.json").exists()
|
||||
for bad in ("../outside", "/absolute", "C:/data", "a\\b"):
|
||||
with pytest.raises(ValueError):
|
||||
ds.confined(worker.root, bad)
|
||||
|
||||
|
||||
def test_failed_job_does_not_block_next_and_published_corruption_is_preserved(tmp_path):
|
||||
_, _, _, _, first = fixture(tmp_path / "first")
|
||||
_, _, _, _, second = fixture(tmp_path / "second")
|
||||
worker = ds.Store(tmp_path / "worker", reserve=0)
|
||||
a, b = worker.accept(first), worker.accept(second)
|
||||
assert worker.next() == a
|
||||
target = worker.root / "datasets" / a
|
||||
draft(target)
|
||||
(target / "labels.json").write_text("corrupted")
|
||||
assert worker.next() is None
|
||||
assert worker.db.execute("SELECT state FROM jobs WHERE id=?", (a,)).fetchone()[0] == "failed"
|
||||
assert (target / "labels.json").read_text() == "corrupted"
|
||||
assert worker.next() == b
|
||||
|
||||
|
||||
def test_complete_collection_receipt_keeps_identity_and_terminal_invariants(tmp_path):
|
||||
world, edits, _, saved, env = fixture(tmp_path)
|
||||
receipt = dict(
|
||||
state="draft-ready",
|
||||
package_sha256=env["annotation"]["sha256"],
|
||||
dataset_sha256="c" * 64,
|
||||
sample_count=213,
|
||||
)
|
||||
for count in [-1, 0, True, 213.0, 1025]:
|
||||
with pytest.raises(ValueError):
|
||||
edits.receipt(world, saved["revision"], {**receipt, "sample_count": count})
|
||||
with pytest.raises(ValueError):
|
||||
edits.receipt(world, saved["revision"], {**receipt, "package_sha256": "d" * 64})
|
||||
with pytest.raises(ValueError):
|
||||
edits.receipt(world, saved["revision"], {**receipt, "dataset_sha256": None})
|
||||
assert edits.receipt(world, saved["revision"], receipt) == receipt
|
||||
assert edits.receipt(world, saved["revision"], receipt) == receipt
|
||||
assert edits.get(world)["learning"]["state"] == "draft-ready"
|
||||
with pytest.raises(RuntimeError):
|
||||
edits.receipt(world, saved["revision"], {**receipt, "sample_count": 212})
|
||||
@@ -0,0 +1,49 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SRC))
|
||||
spec = importlib.util.spec_from_file_location("density_probe", SRC / "supervision_density_probe.py")
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
sys.path.remove(str(SRC))
|
||||
|
||||
|
||||
def example(split="train"):
|
||||
return dict(
|
||||
sample_id="a", source="r1", physical_group="street-a", split=split, inputs=["rgb-sha"]
|
||||
)
|
||||
|
||||
|
||||
def test_growth_adds_labels_but_cannot_rewrite_them_or_move_controls():
|
||||
a = np.array([[1, 0, 255]], dtype="uint8")
|
||||
b = np.array([[1, 0, 0]], dtype="uint8")
|
||||
probe.check_pair(example(), example(), a, b)
|
||||
with pytest.raises(ValueError, match="Existing"):
|
||||
probe.check_pair(example(), example(), a, np.array([[0, 0, 0]]))
|
||||
with pytest.raises(ValueError, match="control"):
|
||||
probe.check_pair(example("regression"), example("regression"), a, b)
|
||||
with pytest.raises(ValueError, match="input"):
|
||||
probe.check_pair(example(), dict(example(), inputs=["different-image"]), a, b)
|
||||
|
||||
|
||||
def test_street_regression_cannot_hide_behind_gain_on_another_street():
|
||||
good = dict(sparse=dict(recall=0.8, fpr=0.1), dense=dict(recall=0.9, fpr=0.08))
|
||||
bad = dict(sparse=dict(recall=None, fpr=0.01), dense=dict(recall=None, fpr=0.02))
|
||||
audit = dict(sparse=dict(recall=0.9, fpr=0.9), dense=dict(recall=0.9, fpr=0.5))
|
||||
result = probe.qualify({"paint": good, "paving": bad}, audit, True)
|
||||
assert not result["accepted"] and result["failures"] == ["paving: fpr"]
|
||||
assert probe.qualify({"paint": good}, audit, True)["accepted"]
|
||||
assert not probe.qualify({"paint": good}, audit, False)["accepted"]
|
||||
|
||||
|
||||
def test_diagnostic_cannot_be_improved_by_erasing_real_paint():
|
||||
metrics = dict(a=dict(sparse=dict(recall=0.8, fpr=0.1), dense=dict(recall=0.9, fpr=0.08)))
|
||||
audit = dict(sparse=dict(recall=0.9, fpr=0.9), dense=dict(recall=0.8, fpr=0.1))
|
||||
assert "diagnostic paint recall" in probe.qualify(metrics, audit, True)["failures"]
|
||||
with pytest.raises(ValueError, match="Only train"):
|
||||
probe.samples(None, None, {"split": "regression"}, {})
|
||||
@@ -0,0 +1,78 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from scipy.optimize import check_grad
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SRC))
|
||||
spec = importlib.util.spec_from_file_location("nonlinear_probe", SRC / "nonlinear_head_probe.py")
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
sys.path.remove(str(SRC))
|
||||
|
||||
|
||||
def test_analytic_gradient_matches_finite_differences():
|
||||
rng = np.random.default_rng(7)
|
||||
x = rng.normal(size=(8, 3))
|
||||
y = np.array([0, 1] * 4)
|
||||
weight = np.array([0.03, 0.07, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2])
|
||||
hidden = 4
|
||||
theta = rng.normal(scale=0.2, size=3 * hidden + 2 * hidden + 1)
|
||||
|
||||
def loss(t):
|
||||
return probe.objective(t, x, y, weight, hidden, 0.01)[0]
|
||||
|
||||
def grad(t):
|
||||
return probe.objective(t, x, y, weight, hidden, 0.01)[1]
|
||||
|
||||
assert check_grad(loss, grad, theta) < 1e-6
|
||||
|
||||
|
||||
def test_non_linear_head_can_learn_xor_and_rejects_control_data():
|
||||
x = np.array([[-1, -1], [-1, 1], [1, -1], [1, 1]], dtype=float)
|
||||
y = np.array([0, 1, 1, 0])
|
||||
units = [dict(x=x, y=y, split="train", group="synthetic")]
|
||||
m = probe.fit_mlp(units, 4, 7, 0.001, 500)
|
||||
assert m["converged"]
|
||||
assert np.array_equal(probe.mlp_logits(x, m) > 0, y.astype(bool))
|
||||
m2 = probe.fit_mlp(units, 4, 7, 0.001, 500)
|
||||
assert m["w1"] == m2["w1"] and m["w2"] == m2["w2"]
|
||||
with pytest.raises(ValueError, match="training units"):
|
||||
probe.fit_mlp([dict(units[0], split="regression")], 4, 7, 0.001, 500)
|
||||
|
||||
|
||||
def test_all_seeds_and_each_street_must_pass_without_winner_selection():
|
||||
group = dict(
|
||||
linear=dict(recall=1.0, fpr=0.2), a=dict(recall=1.0, fpr=0.1), b=dict(recall=1.0, fpr=0.1)
|
||||
)
|
||||
audit = dict(
|
||||
linear=dict(recall=1.0, fpr=0.4), a=dict(recall=1.0, fpr=0.2), b=dict(recall=1.0, fpr=0.2)
|
||||
)
|
||||
hist = {"road": dict(recall=1.0, fpr=0.05)}
|
||||
out = probe.qualify({"road": group}, audit, ["a", "b"], dict(a=True, b=True), True, hist)
|
||||
assert (
|
||||
out["capacity_test_passed"]
|
||||
and not out["historical_repair_all_seeds"]
|
||||
and out["selected_model"] is None
|
||||
)
|
||||
bad = dict(group, b=dict(recall=0.99, fpr=0.01))
|
||||
assert not probe.qualify({"road": bad}, audit, ["a", "b"], dict(a=True, b=True), True, hist)[
|
||||
"capacity_test_passed"
|
||||
]
|
||||
assert not probe.qualify({"road": group}, audit, ["a", "b"], dict(a=True, b=False), True, hist)[
|
||||
"capacity_test_passed"
|
||||
]
|
||||
assert not probe.qualify({"road": group}, audit, ["a", "b"], dict(a=True, b=True), False, hist)[
|
||||
"capacity_test_passed"
|
||||
]
|
||||
assert not probe.qualify(
|
||||
{"road": group},
|
||||
dict(audit, b=audit["linear"]),
|
||||
["a", "b"],
|
||||
dict(a=True, b=True),
|
||||
True,
|
||||
hist,
|
||||
)["capacity_test_passed"]
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Marking editing keeps rigid shape, exact heights and immutable provenance."""
|
||||
|
||||
import copy
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.simulation.ai_polygon.semantic_edits import apply_operations, paths
|
||||
from k1link.simulation.ai_polygon.semantic_objects import catalog, object_operation, pivot
|
||||
|
||||
|
||||
def place(template="zebra"):
|
||||
return dict(
|
||||
kind="place",
|
||||
feature_id="user-1234567890123456",
|
||||
template_id=template,
|
||||
position=[300.0123, -60.034, 2.5206789941457233],
|
||||
surface="gaussian-visual",
|
||||
)
|
||||
|
||||
|
||||
def document():
|
||||
return dict(
|
||||
schema_version="missioncore.urban-map/v3", source=dict(world_sha256="a" * 64), features=[]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("template", [t["id"] for t in catalog()["templates"]])
|
||||
def test_templates_pass_existing_geometry_checks(template):
|
||||
base = document()
|
||||
op = place(template)
|
||||
result = apply_operations(base, [op])
|
||||
assert base["features"] == []
|
||||
assert all(
|
||||
f["properties"]["review_status"] == "unreviewed"
|
||||
and f["properties"]["annotation_origin"] == "human-edit"
|
||||
for f in result["features"]
|
||||
)
|
||||
assert all(
|
||||
p[2] == op["position"][2] for f in result["features"] for ring in paths(f) for p in ring
|
||||
)
|
||||
assert result == apply_operations(copy.deepcopy(base), [op], verified_history=True)
|
||||
|
||||
|
||||
def test_rigid_group_translate_rotate_and_noop():
|
||||
base = apply_operations(document(), [place()])
|
||||
snapshot = copy.deepcopy(base)
|
||||
op = dict(kind="transform", feature_id=base["features"][3]["id"], delta=[0, 0], angle=0)
|
||||
assert object_operation(base["features"], op) is base["features"]
|
||||
op.update(delta=[0.125, -0.25], angle=0.42)
|
||||
result = apply_operations(base, [op])
|
||||
assert base == snapshot
|
||||
assert len(result["features"]) == 6
|
||||
before = [p for f in base["features"] for r in paths(f) for p in r]
|
||||
after = [p for f in result["features"] for r in paths(f) for p in r]
|
||||
assert all(a[2] == b[2] for a, b in zip(before, after, strict=True))
|
||||
assert math.dist(before[0][:2], before[-1][:2]) == pytest.approx(
|
||||
math.dist(after[0][:2], after[-1][:2]), abs=1e-12
|
||||
)
|
||||
assert pivot(result["features"])[:2] != pivot(base["features"])[:2]
|
||||
rejected = apply_operations(
|
||||
result, [dict(kind="remove", feature_id=result["features"][2]["id"])]
|
||||
)
|
||||
assert all(f["properties"]["review_status"] == "rejected" for f in rejected["features"])
|
||||
assert [f["geometry"] for f in rejected["features"]] == [
|
||||
f["geometry"] for f in result["features"]
|
||||
]
|
||||
|
||||
|
||||
def test_no_marking_vertex_deformation_and_no_unknown_surface():
|
||||
base = apply_operations(document(), [place("letter_A")])
|
||||
f = base["features"][0]
|
||||
with pytest.raises(ValueError, match="целиком"):
|
||||
apply_operations(
|
||||
base, [dict(kind="move", feature_id=f["id"], path=0, index=0, position=paths(f)[0][0])]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(document(), [{**place(), "surface": "invented-ground"}])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [place("letter_A")])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(document(), [{**place(), "position": [0, 0, float("nan")]}])
|
||||
|
||||
|
||||
def test_legacy_verified_marking_history_still_replays():
|
||||
base = apply_operations(document(), [place("straight_arrow")])
|
||||
p = paths(base["features"][0])[0][0][:]
|
||||
p[0] += 0.02
|
||||
old = dict(kind="move", feature_id=base["features"][0]["id"], path=0, index=0, position=p)
|
||||
result = apply_operations(copy.deepcopy(base), [old], verified_history=True)
|
||||
assert paths(result["features"][0])[0][0] == p
|
||||
|
||||
|
||||
def test_worker_replays_place_transform_remove_with_actual_previous_revision(monkeypatch):
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.simulation.ai_polygon import semantic_objects, semantic_vectors
|
||||
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
file = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
functions = [
|
||||
n
|
||||
for n in ast.parse(file.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "centres", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=functions, type_ignores=[]), str(file), "exec"), scope)
|
||||
first = place()
|
||||
move = dict(
|
||||
kind="transform", feature_id=first["feature_id"] + "-2", delta=[0.25, 0.5], angle=0.2
|
||||
)
|
||||
package = dict(model=document(), revisions=[dict(operations=[first]), dict(operations=[move])])
|
||||
before, after, affected = scope["contexts"](package)
|
||||
expected = apply_operations(apply_operations(document(), [first]), [move])
|
||||
assert [f["geometry"] for f in after] == [f["geometry"] for f in expected["features"]]
|
||||
assert len(before) == 6 and len(after) == 6 and len(affected) == 1
|
||||
assert before[0]["geometry"] != after[0]["geometry"]
|
||||
package["revisions"].append(
|
||||
dict(operations=[dict(kind="remove", feature_id=first["feature_id"])])
|
||||
)
|
||||
_, after, affected = scope["contexts"](package)
|
||||
assert all(f["properties"]["review_status"] == "rejected" for f in after)
|
||||
|
||||
|
||||
def test_worker_coalesces_parts_of_one_placement(monkeypatch):
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.simulation.ai_polygon import semantic_objects, semantic_vectors
|
||||
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
file = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [
|
||||
n
|
||||
for n in ast.parse(file.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(file), "exec"), scope)
|
||||
first = place()
|
||||
second = dict(
|
||||
kind="transform", feature_id=first["feature_id"] + "-2", delta=[0.125, 0.25], angle=0.12
|
||||
)
|
||||
_, after, affected = scope["contexts"](
|
||||
dict(
|
||||
model=document(), revisions=[dict(origin="agent-proposal", operations=[first, second])]
|
||||
)
|
||||
)
|
||||
assert len(affected) == 1
|
||||
assert affected[0][0] == first["feature_id"]
|
||||
assert all(f["properties"]["annotation_origin"] == "agent-proposal" for f in after)
|
||||
|
||||
|
||||
def test_road_letter_artwork_and_immutable_legacy_replay():
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
templates = {t["id"]: t for t in catalog()["templates"]}
|
||||
for key, expected in {
|
||||
"letter_A": "2a9a60141bbd80b3544057964526182c479775d98ce88a7fe180377f12ec886e",
|
||||
"letter_A_v2": "4c7d30d688044ffb18debef08f20e4c5aca9c025dd2e0acae8af93715133af08",
|
||||
}.items():
|
||||
raw = json.dumps(templates[key]["polygons"], sort_keys=True).encode()
|
||||
assert hashlib.sha256(raw).hexdigest() == expected
|
||||
assert templates[key]["hidden"]
|
||||
visible = [
|
||||
t["id"] for t in templates.values() if t["label"] == "Буква А" and not t.get("hidden")
|
||||
]
|
||||
assert visible == ["letter_A_v3"]
|
||||
feature = apply_operations(document(), [place("letter_A_v3")])["features"][0]
|
||||
outer, hole = feature["geometry"]["coordinates"]
|
||||
assert max(p[0] for p in outer) - min(p[0] for p in outer) == pytest.approx(3)
|
||||
assert max(p[1] for p in outer) - min(p[1] for p in outer) == pytest.approx(1.4)
|
||||
# A flat 0.25 m tip, open feet and a closed counter distinguish road artwork.
|
||||
tip = [p for p in outer if p[0] == max(v[0] for v in outer)]
|
||||
assert len(tip) == 2 and abs(tip[0][1] - tip[1][1]) == pytest.approx(0.25)
|
||||
assert len(hole) == 4
|
||||
|
||||
|
||||
def test_retemplate_is_reversible_by_history_and_preserves_slope_and_other_objects():
|
||||
base = apply_operations(
|
||||
document(),
|
||||
[place("letter_A"), {**place("linear_marking"), "feature_id": "user-9876543210987654"}],
|
||||
)
|
||||
snapshot = copy.deepcopy(base)
|
||||
op = dict(
|
||||
kind="retemplate",
|
||||
feature_id=base["features"][0]["id"],
|
||||
template_id="letter_A_v3",
|
||||
frame=[[20, 30, 4], [0, 1, 0.1], [-1, 0, 0.2]],
|
||||
)
|
||||
result = apply_operations(base, [op], origin="agent-proposal")
|
||||
assert base == snapshot
|
||||
assert result["features"][1] == base["features"][1]
|
||||
expected = catalog()["templates"]
|
||||
expected = next(t for t in expected if t["id"] == "letter_A_v3")["polygons"][0]
|
||||
assert result["features"][0]["geometry"]["coordinates"] == [
|
||||
[[20 - y, 30 + x, 4 + 0.1 * x + 0.2 * y] for x, y in ring] for ring in expected
|
||||
]
|
||||
assert result == apply_operations(base, [op], origin="agent-proposal", verified_history=True)
|
||||
for frame in (
|
||||
[[0, 0, 0], [0, 0, 0], [0, 1, 0]],
|
||||
[[0, 0, 0], [1, 0, 0], [1, 1, 0]],
|
||||
[[0, 0, 0], [1, 0, 0], [0, -1, 0]],
|
||||
):
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [{**op, "frame": frame}])
|
||||
@@ -0,0 +1,50 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"pixel_growth_probe",
|
||||
Path(__file__).resolve().parents[1] / "simulation/semantic-learning/pixel_growth_probe.py",
|
||||
)
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
|
||||
|
||||
def unit(group, y, split="train"):
|
||||
y = np.array(y)
|
||||
return dict(
|
||||
group=group, split=split, y=y, x=np.column_stack([y * 2 - 1, np.arange(len(y)) % 2])
|
||||
)
|
||||
|
||||
|
||||
def test_weights_balance_area_window_class_not_pixel_volume():
|
||||
units = [unit("a", [0] * 30 + [1] * 10), unit("a", [0, 1]), unit("b", [0] * 100)]
|
||||
w = probe.balanced_weights(units)
|
||||
y = np.concatenate([u["y"] for u in units])
|
||||
assert w[y == 1].sum() == pytest.approx(0.5)
|
||||
assert w[:42][y[:42] == 0].sum() == pytest.approx(0.25)
|
||||
assert w[42:].sum() == pytest.approx(0.25)
|
||||
assert w[:40][y[:40] == 1].sum() == pytest.approx(0.25)
|
||||
|
||||
|
||||
def test_controls_cannot_fit_or_normalize():
|
||||
with pytest.raises(ValueError, match="Only training"):
|
||||
probe.fit([unit("a", [0, 1]), unit("b", [0, 1], "regression")])
|
||||
|
||||
|
||||
def test_ignore_pixels_never_enter_counts_and_negative_recall_is_undefined():
|
||||
c = probe.counts([[True, True, False]], np.array([[255, 0, 0]], dtype="uint8"))
|
||||
assert c == dict(tp=0, fn=0, fp=1, tn=1, ignored=1)
|
||||
assert probe.aggregate([c])["recall"] is None
|
||||
assert probe.aggregate([c])["fpr"] == 0.5
|
||||
|
||||
|
||||
def test_fit_is_invariant_to_renaming_groups_and_uses_both_classes():
|
||||
a = probe.fit([unit("a", [0, 0, 1, 1]), unit("b", [0, 1])])
|
||||
b = probe.fit([unit("x", [0, 0, 1, 1]), unit("y", [0, 1])])
|
||||
assert np.allclose(a["coefficients"], b["coefficients"])
|
||||
assert a["coefficients"][1] > 0 and a["production_eligible"] is False
|
||||
with pytest.raises(ValueError, match="Both reviewed"):
|
||||
probe.fit([unit("a", [0, 0])])
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Training review separates current geometry, deleted history and admission."""
|
||||
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
from test_semantic_delivery import ds
|
||||
|
||||
|
||||
def feature(id, status, z=0.123456789012345):
|
||||
return dict(
|
||||
id=id,
|
||||
properties={"review_status": status, "class": "road_boundary"},
|
||||
geometry={"type": "LineString", "coordinates": [[0, 0, z], [1, 2, z]]},
|
||||
)
|
||||
|
||||
|
||||
def labels():
|
||||
features = [
|
||||
feature("moved", "unreviewed"),
|
||||
feature("old-A", "rejected"),
|
||||
feature("untouched", "accepted"),
|
||||
]
|
||||
projections = [
|
||||
dict(feature_id=f["id"], uv=[[0.25, 1.75]], in_front=[True], inside=[True])
|
||||
for f in features
|
||||
]
|
||||
return dict(
|
||||
original_element=[feature("old-A", "accepted")],
|
||||
proposed_element=features,
|
||||
projections={"top": projections, "oblique": copy.deepcopy(projections)},
|
||||
)
|
||||
|
||||
|
||||
def test_history_and_editor_acceptance_never_become_training_targets():
|
||||
original = labels()
|
||||
before = copy.deepcopy(original)
|
||||
result = ds.review_labels(original)
|
||||
assert original == before
|
||||
assert result["active_candidates"] == [
|
||||
before["proposed_element"][0],
|
||||
before["proposed_element"][2],
|
||||
]
|
||||
assert result["rejected_history"] == [before["proposed_element"][1]]
|
||||
assert result["original"] == before["original_element"]
|
||||
assert not result["approved_targets"] and not result["background_targets"]
|
||||
for name, view in result["views"].items():
|
||||
assert view["candidate_projections"] == [
|
||||
before["projections"][name][0],
|
||||
before["projections"][name][2],
|
||||
]
|
||||
assert view["rejected_projections"] == [before["projections"][name][1]]
|
||||
assert view["training_eligible"] is False and view["complete_regions"] == []
|
||||
assert view["evidence"] == "unreviewed" and not view["approved_targets"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("damage", ["duplicate", "unknown-status", "unknown-projection"])
|
||||
def test_ambiguous_label_identity_fails_closed(damage):
|
||||
value = labels()
|
||||
if damage == "duplicate":
|
||||
value["proposed_element"].append(value["proposed_element"][0])
|
||||
elif damage == "unknown-status":
|
||||
value["proposed_element"][0]["properties"]["review_status"] = "training-approved"
|
||||
else:
|
||||
value["projections"]["top"][0]["feature_id"] = "missing"
|
||||
with pytest.raises(ValueError):
|
||||
ds.review_labels(value)
|
||||
|
||||
|
||||
def shard(root, value):
|
||||
root.mkdir(parents=True)
|
||||
ds.write(root / "labels.json", value)
|
||||
ds.write(
|
||||
root / "sample.json",
|
||||
dict(
|
||||
members=["labels.json"],
|
||||
training_eligible=False,
|
||||
complete_regions=[],
|
||||
revision="a" * 64,
|
||||
split_group="b" * 64,
|
||||
),
|
||||
)
|
||||
ds.write(
|
||||
root / "dataset.json",
|
||||
dict(
|
||||
schema_version=ds.SCHEMA,
|
||||
training_eligible=False,
|
||||
revision="a" * 64,
|
||||
world_sha256="b" * 64,
|
||||
split_group="b" * 64,
|
||||
annotation_sha256="c" * 64,
|
||||
samples=["sample.json"],
|
||||
files={
|
||||
p.name: dict(sha256=ds.checksum(p), bytes=p.stat().st_size) for p in root.iterdir()
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def collection(root, values):
|
||||
for i, value in enumerate(values):
|
||||
shard(root / f"part-{i:03d}", value)
|
||||
ds.write(
|
||||
root / "dataset.json",
|
||||
dict(
|
||||
schema_version="missioncore.semantic-collection/v1",
|
||||
files={},
|
||||
shards={p.name: ds.verify(p) for p in root.iterdir()},
|
||||
training_eligible=False,
|
||||
revision="a" * 64,
|
||||
world_sha256="b" * 64,
|
||||
split_group="b" * 64,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_review_index_relocates_without_core_and_retains_exact_evidence(tmp_path):
|
||||
root = tmp_path / "dataset"
|
||||
collection(root, [labels(), labels()])
|
||||
before = {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()}
|
||||
index = ds.review_index(root)
|
||||
assert index["active_candidate_ids"] == ["moved", "untouched"]
|
||||
assert index["rejected_history_ids"] == ["old-A"]
|
||||
assert index["approved_targets"] == index["background_targets"] == []
|
||||
assert index["source"]["annotation_sha256"] == "c" * 64
|
||||
assert len(index["samples"]) == 2
|
||||
assert {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()} == before
|
||||
root.rename(tmp_path / "portable")
|
||||
assert ds.review_index(tmp_path / "portable") == index
|
||||
(tmp_path / "portable/part-000/labels.json").write_text("{}")
|
||||
with pytest.raises(ValueError, match="integrity"):
|
||||
ds.review_index(tmp_path / "portable")
|
||||
|
||||
|
||||
def test_conflicting_windows_refused_even_with_valid_file_hashes(tmp_path):
|
||||
other = labels()
|
||||
other["proposed_element"][0]["properties"]["review_status"] = "rejected"
|
||||
collection(tmp_path / "data", [labels(), other])
|
||||
with pytest.raises(ValueError, match="Feature changed"):
|
||||
ds.review_index(tmp_path / "data")
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Final geometry coverage and portable sharding never turn unknown into negatives."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_semantic_delivery import draft, ds
|
||||
|
||||
from k1link.simulation.ai_polygon import semantic_objects, semantic_vectors
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def snapshot(monkeypatch):
|
||||
for key, value in {
|
||||
"dataset_store": ds,
|
||||
"semantic_objects": semantic_objects,
|
||||
"semantic_vectors": semantic_vectors,
|
||||
}.items():
|
||||
monkeypatch.setitem(sys.modules, key, value)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"final_snapshot",
|
||||
Path(__file__).parents[1] / "simulation/semantic-learning/final_snapshot.py",
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def feature(points, kind="road_boundary", id="road"):
|
||||
return dict(
|
||||
id=id,
|
||||
properties={"class": kind, "review_status": "unreviewed"},
|
||||
geometry=dict(type="LineString", coordinates=points),
|
||||
)
|
||||
|
||||
|
||||
def package(features):
|
||||
return dict(
|
||||
model={"features": copy.deepcopy(features)},
|
||||
edited={"features": copy.deepcopy(features)},
|
||||
revisions=[],
|
||||
revision="a" * 64,
|
||||
world_sha256="b" * 64,
|
||||
)
|
||||
|
||||
|
||||
def test_long_edges_cover_every_grid_cell_without_changing_vertices(snapshot):
|
||||
p = package([feature([[1, 2, 3], [91, 2, 12]])])
|
||||
original = copy.deepcopy(p)
|
||||
result = snapshot.plan(p, ["road_boundary"])
|
||||
assert len(result["windows"]) == 10 and p == original
|
||||
assert all(w["features"] == ["road"] for w in result["windows"])
|
||||
split = package([feature([[1, 2, 3], [36, 2, 6.5], [91, 2, 12]])])
|
||||
assert snapshot.plan(split, ["road_boundary"])["windows"] == result["windows"]
|
||||
|
||||
|
||||
def test_large_edit_uses_final_geometry_and_keeps_other_classes_ignored(snapshot):
|
||||
p = package(
|
||||
[
|
||||
feature([[1, 2, 3], [91, 2, 12]]),
|
||||
feature([[1, 100, 3], [91, 100, 12]], "building_facade", "house"),
|
||||
]
|
||||
)
|
||||
p["revisions"] = [
|
||||
dict(
|
||||
operations=[dict(kind="move", feature_id="road", path=0, index=0, position=[1, 32, 3])]
|
||||
)
|
||||
]
|
||||
p["edited"]["features"][0]["geometry"]["coordinates"][0] = [1, 32, 3]
|
||||
result = snapshot.plan(p, ["road_boundary"])
|
||||
assert len(result["windows"]) > 10
|
||||
assert all(w["features"] == ["road"] for w in result["windows"])
|
||||
assert not result["training_eligible"]
|
||||
p["edited"]["features"][0]["geometry"]["coordinates"][0][0] += 1
|
||||
with pytest.raises(ValueError, match="Replayed"):
|
||||
snapshot.plan(p, ["road_boundary"])
|
||||
|
||||
|
||||
def test_collection_portable_integrity_and_policy(tmp_path):
|
||||
root = tmp_path / "collection"
|
||||
root.mkdir()
|
||||
draft(root / "part-000")
|
||||
result = ds.verify(root / "part-000")
|
||||
ds.write(
|
||||
root / "dataset.json",
|
||||
dict(
|
||||
schema_version="missioncore.semantic-collection/v1",
|
||||
shards={"part-000": result},
|
||||
files={},
|
||||
training_eligible=False,
|
||||
),
|
||||
)
|
||||
verified = ds.verify(root)
|
||||
moved = tmp_path / "renamed"
|
||||
root.rename(moved)
|
||||
assert ds.verify(moved) == verified
|
||||
(moved / "part-000/labels.json").write_text("{}")
|
||||
with pytest.raises(ValueError):
|
||||
ds.verify(moved)
|
||||
|
||||
|
||||
def test_batched_crops_preserve_float_sampling_and_source_order(monkeypatch):
|
||||
import ast
|
||||
import types
|
||||
|
||||
import numpy as np
|
||||
|
||||
source = Path(__file__).parents[1] / "simulation/urban-mapping/mapping.py"
|
||||
tree = ast.parse(source.read_text())
|
||||
fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "prepare_crops")
|
||||
rng = np.random.default_rng(42)
|
||||
data = np.zeros(1001, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("identity", "i4")])
|
||||
for k in ["x", "y", "z"]:
|
||||
data[k] = rng.uniform(-80, 80, len(data))
|
||||
data["x"][:4] = [-21, 21, -21.00001, 21.00001]
|
||||
data["y"][:4] = 0
|
||||
data["identity"] = np.arange(len(data))
|
||||
|
||||
class Ply:
|
||||
@staticmethod
|
||||
def read(*args, **kwargs):
|
||||
return {"vertex": types.SimpleNamespace(data=data)}
|
||||
|
||||
monkeypatch.setitem(sys.modules, "plyfile", types.SimpleNamespace(PlyData=Ply))
|
||||
ns = dict(np=np, Path=Path)
|
||||
exec(compile(ast.Module(body=[fn], type_ignores=[]), str(source), "exec"), ns)
|
||||
transform = np.eye(4)
|
||||
jobs = [
|
||||
dict(
|
||||
source=dict(ply="synthetic.ply", source_to_world=transform.tolist()),
|
||||
bounds_xy=[[x - 6, -6], [x + 6, 6]],
|
||||
halo_m=15,
|
||||
)
|
||||
for x in [0, 10, 20, 30]
|
||||
]
|
||||
got = list(ns["prepare_crops"](jobs))
|
||||
xyz = np.column_stack([data[n] for n in ["x", "y", "z"]])
|
||||
world = xyz @ transform[:3, :3].T + transform[:3, 3]
|
||||
for job, rows in zip(jobs, got, strict=True):
|
||||
bounds = np.asarray(job["bounds_xy"], dtype=float)
|
||||
mask = ((world[:, :2] >= bounds[0] - 15) & (world[:, :2] <= bounds[1] + 15)).all(axis=1)
|
||||
assert rows.tobytes() == data[mask].tobytes()
|
||||
with pytest.raises(ValueError):
|
||||
list(ns["prepare_crops"](jobs + jobs))
|
||||
|
||||
|
||||
def test_worker_resumes_verified_parts_without_rebuilding_them(tmp_path, monkeypatch, snapshot):
|
||||
import json
|
||||
import types
|
||||
|
||||
from test_semantic_delivery import fixture
|
||||
|
||||
monkeypatch.setitem(sys.modules, "final_snapshot", snapshot)
|
||||
monkeypatch.setitem(sys.modules, "core_client", types.SimpleNamespace(CoreClient=object))
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"infrastructure_gaussian_sources",
|
||||
types.SimpleNamespace(resolve_gaussian_entry=lambda *args: None),
|
||||
)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/worker.py"
|
||||
spec = importlib.util.spec_from_file_location("snapshot_worker", path)
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(worker)
|
||||
release = tmp_path / "release"
|
||||
release.mkdir()
|
||||
ds.write(release / "release.json", {"id": "original-builder"})
|
||||
(release / "dataset_store.py").write_text("# portable verifier fixture\n")
|
||||
monkeypatch.setattr(worker, "HERE", release)
|
||||
_, _, _, _, env = fixture(tmp_path / "fixture")
|
||||
store = ds.Store(tmp_path / "worker", reserve=0)
|
||||
key = store.accept(env)
|
||||
assert store.next() == key
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"plan",
|
||||
lambda _: dict(windows=[{}] * 8, classes=["road_boundary"], world_sha256="b" * 64),
|
||||
)
|
||||
monkeypatch.setattr(worker, "source_for", lambda *args: (tmp_path, {}))
|
||||
monkeypatch.setattr(
|
||||
worker.subprocess, "run", lambda *args, **kwargs: types.SimpleNamespace(returncode=1)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
worker, "docker", lambda *args, **kwargs: types.SimpleNamespace(stdout=b"[]")
|
||||
)
|
||||
called = []
|
||||
interrupt = True
|
||||
|
||||
def render(*args):
|
||||
batch = ds.read(store.root / "work" / key / "batch.json")
|
||||
called.append(batch["name"])
|
||||
part = store.root / "work" / key / "dataset" / batch["name"]
|
||||
if interrupt and batch["name"] == "part-001":
|
||||
part.mkdir()
|
||||
(part / "incomplete").write_text("interrupted")
|
||||
raise InterruptedError("priority job")
|
||||
draft(part)
|
||||
|
||||
monkeypatch.setattr(worker, "run_shard", render)
|
||||
with pytest.raises(InterruptedError):
|
||||
worker.build(key, store, tmp_path / "state")
|
||||
part0 = store.root / "work" / key / "dataset/part-000"
|
||||
preserved = {p.name: p.read_bytes() for p in part0.iterdir()}
|
||||
# A different builder must not silently mix with the completed part.
|
||||
ds.write(release / "release.json", {"id": "different-builder"})
|
||||
with pytest.raises(ValueError, match="original builder"):
|
||||
worker.build(key, store, tmp_path / "state")
|
||||
assert called == ["part-000", "part-001"]
|
||||
ds.write(release / "release.json", {"id": "original-builder"})
|
||||
interrupt = False
|
||||
result = worker.build(key, store, tmp_path / "state")
|
||||
assert called == ["part-000", "part-001", "part-001"]
|
||||
published = store.root / "datasets" / key
|
||||
assert {p.name: p.read_bytes() for p in (published / "part-000").iterdir()} == preserved
|
||||
assert not (published / "part-001/incomplete").exists()
|
||||
assert result["sample_count"] == 2 and ds.verify(published)["sample_count"] == 2
|
||||
assert not (store.root / "work" / key).exists()
|
||||
assert (
|
||||
json.loads(store.db.execute("SELECT receipt FROM jobs").fetchone()[0])["state"]
|
||||
== "draft-ready"
|
||||
)
|
||||
@@ -0,0 +1,70 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SRC))
|
||||
spec = importlib.util.spec_from_file_location("spatial_probe", SRC / "spatial_decoder_probe.py")
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
sys.path.remove(str(SRC))
|
||||
|
||||
|
||||
def test_loss_is_balanced_by_class_street_window_and_unknown_has_zero_weight():
|
||||
records = [
|
||||
dict(name="a1", group="a", split="train", target=np.array([[0, 1, 255], [0, 1, 255]])),
|
||||
dict(name="a2", group="a", split="train", target=np.array([[0, 255, 255], [0, 255, 255]])),
|
||||
dict(name="b", group="b", split="train", target=np.array([[1, 1, 1], [0, 0, 0]])),
|
||||
]
|
||||
ww = probe.dense_weights(records)
|
||||
for label in (0, 1):
|
||||
assert sum(ww[r["name"]][r["target"] == label].sum() for r in records) == pytest.approx(0.5)
|
||||
for group in ["a", "b"]:
|
||||
assert sum(
|
||||
ww[r["name"]][r["target"] == label].sum() for r in records if r["group"] == group
|
||||
) == pytest.approx(0.25)
|
||||
assert all(not np.any(ww[r["name"]][r["target"] == 255]) for r in records)
|
||||
with pytest.raises(ValueError, match="training"):
|
||||
probe.dense_weights([dict(records[0], split="regression")])
|
||||
|
||||
|
||||
def rows(arm, errors):
|
||||
return [
|
||||
dict(
|
||||
phase="development",
|
||||
arm=arm,
|
||||
held_out=str(i),
|
||||
completed=True,
|
||||
metrics=dict(recall=1 - e, fpr=e),
|
||||
)
|
||||
for i, e in enumerate(errors)
|
||||
]
|
||||
|
||||
|
||||
def test_selection_rejects_single_good_seed_and_control_rows():
|
||||
rr = rows("old-linear", [0.1, 0.2, 0.3, 0.4]) + rows("new-linear", [0.1, 0.2, 0.3, 0.4])
|
||||
for family in ["pointwise", "spatial"]:
|
||||
for seed in [20261023, 20261024, 20261025]:
|
||||
errors = (
|
||||
[0.05, 0.1, 0.2, 0.3]
|
||||
if family == "spatial" and seed != 20261025
|
||||
else [0.1, 0.2, 0.3, 0.5]
|
||||
)
|
||||
rr += rows(f"{family}-{seed}", errors)
|
||||
assert probe.choose(rr)["selected_family"] == "old-linear"
|
||||
with pytest.raises(ValueError, match="Development"):
|
||||
probe.choose([dict(rr[0], phase="regression")] + rr[1:])
|
||||
with pytest.raises(ValueError, match="Incomplete"):
|
||||
probe.choose(rr[:-1])
|
||||
better = [
|
||||
dict(r, metrics=dict(recall=0.95, fpr=0.05)) if r["arm"].startswith("spatial") else r
|
||||
for r in rr
|
||||
]
|
||||
assert probe.choose(better)["selected_arms"] == [
|
||||
"spatial-20261023",
|
||||
"spatial-20261024",
|
||||
"spatial-20261025",
|
||||
]
|
||||
@@ -0,0 +1,76 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
sys.path.insert(0, str(SRC))
|
||||
spec = importlib.util.spec_from_file_location("street_probe", SRC / "street_holdout_probe.py")
|
||||
probe = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(probe)
|
||||
|
||||
sys.path.remove(str(SRC))
|
||||
|
||||
|
||||
def record(group, name, split="train", rgb=None):
|
||||
return dict(
|
||||
group=group, name=name, sample_id=name, split=split, input={"rgb": {"sha256": rgb or name}}
|
||||
)
|
||||
|
||||
|
||||
def test_physical_street_is_excluded_together_and_controls_never_enter_folds():
|
||||
records = [
|
||||
record("a", "a1"),
|
||||
record("a", "a2"),
|
||||
record("b", "b"),
|
||||
record("c", "c"),
|
||||
record("r", "r", "regression"),
|
||||
]
|
||||
ff = list(probe.folds(records))
|
||||
assert len(ff) == 3
|
||||
for group, learn, held in ff:
|
||||
assert all(r["group"] != group and r["split"] == "train" for r in learn)
|
||||
assert all(r["group"] == group and r["split"] == "train" for r in held)
|
||||
assert {r["name"] for r in ff[0][2]} == {"a1", "a2"}
|
||||
with pytest.raises(ValueError, match="Identical RGB"):
|
||||
list(
|
||||
probe.folds(
|
||||
[record("a", "a", rgb="same"), record("b", "b", rgb="same"), record("c", "c")]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def result(candidate, errors):
|
||||
return [
|
||||
dict(
|
||||
phase="development",
|
||||
candidate=candidate,
|
||||
held_out=str(i),
|
||||
converged=True,
|
||||
metrics=dict(recall=1 - e, fpr=e),
|
||||
)
|
||||
for i, e in enumerate(errors)
|
||||
]
|
||||
|
||||
|
||||
def test_selection_checks_worst_street_and_missing_folds_and_rejects_controls():
|
||||
rows = (
|
||||
result("base", [0.1, 0.2, 0.3])
|
||||
+ result("good", [0.1, 0.1, 0.2])
|
||||
+ result("bad", [0, 0, 0.31])
|
||||
)
|
||||
assert probe.select_candidate(rows, "base")["selected"] == "good"
|
||||
with pytest.raises(ValueError, match="Missing"):
|
||||
probe.select_candidate(rows[:-1], "base")
|
||||
with pytest.raises(ValueError, match="Development"):
|
||||
probe.select_candidate([dict(rows[0], phase="regression")] + rows[1:], "base")
|
||||
worse = result("base", [0.1, 0.2, 0.3]) + result("bad", [0, 0, 0.31])
|
||||
assert probe.select_candidate(worse, "base")["selected"] == "base"
|
||||
|
||||
|
||||
def test_held_out_group_cannot_fit_even_if_original_split_was_train():
|
||||
with pytest.raises(ValueError, match="Held-out street"):
|
||||
probe.fit_candidate(
|
||||
[dict(group="a", split="train")], dict(head="linear", l2=0.01), held_out="a"
|
||||
)
|
||||
@@ -0,0 +1,122 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
from spatial_decoder_probe import dense_weights
|
||||
from supervision_balance import assess_balance, release_balanced_weights
|
||||
|
||||
|
||||
def record(name, group, old, target):
|
||||
return dict(
|
||||
name=name,
|
||||
group=group,
|
||||
split="train",
|
||||
old_target=np.array(old, dtype="uint8"),
|
||||
target=np.array(target, dtype="uint8"),
|
||||
)
|
||||
|
||||
|
||||
def test_cohort_mass_does_not_shrink_with_added_pixel_count():
|
||||
for count in [1, 20, 1000]:
|
||||
r = record(
|
||||
"a", "one", [1, 0] + [255] * (2 * count + 1), [1, 0] + [1] * count + [0] * count + [255]
|
||||
)
|
||||
before = dense_weights([r])["a"]
|
||||
after = release_balanced_weights([r])["a"]
|
||||
assert after[0] == pytest.approx(0.25) and after[1] == pytest.approx(0.25)
|
||||
assert after[-1] == 0 and after.sum() == pytest.approx(1)
|
||||
for label in [0, 1]:
|
||||
mask = r["target"] == label
|
||||
assert after[mask].sum() == pytest.approx(before[mask].sum())
|
||||
|
||||
|
||||
def test_preserve_class_street_window_mass_and_unchanged_windows():
|
||||
records = [
|
||||
record("a", "one", [1, 0, 255, 255], [1, 0, 1, 0]),
|
||||
record("b", "one", [1, 0], [1, 0]),
|
||||
record("c", "two", [0, 255], [0, 0]),
|
||||
]
|
||||
before = dense_weights(records)
|
||||
after = release_balanced_weights(records)
|
||||
for r in records:
|
||||
for label in [0, 1]:
|
||||
mask = r["target"] == label
|
||||
assert after[r["name"]][mask].sum() == pytest.approx(before[r["name"]][mask].sum())
|
||||
assert np.array_equal(before["b"], after["b"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", ["control", "changed", "shape", "duplicate", "unknown"])
|
||||
def test_reject_invalid_supervision(error):
|
||||
r = record("a", "one", [1, 0, 255], [1, 0, 1])
|
||||
records = [r]
|
||||
if error == "control":
|
||||
r["split"] = "regression"
|
||||
elif error == "changed":
|
||||
r["target"][0] = 0
|
||||
elif error == "shape":
|
||||
r["old_target"] = r["old_target"][:2]
|
||||
elif error == "duplicate":
|
||||
records.append(r)
|
||||
else:
|
||||
r["target"][2] = 2
|
||||
with pytest.raises(ValueError):
|
||||
release_balanced_weights(records)
|
||||
|
||||
|
||||
def rows():
|
||||
result = []
|
||||
for g in "abcd":
|
||||
arms = {"old-linear": 0.25, "new-linear": 0.20}
|
||||
for s in [1, 2, 3]:
|
||||
arms.update(
|
||||
{
|
||||
f"uniform-head-{s}": 0.16,
|
||||
f"uniform-decoder-{s}": 0.14,
|
||||
f"balanced-head-{s}": 0.12,
|
||||
f"balanced-decoder-{s}": 0.10,
|
||||
}
|
||||
)
|
||||
for a, fpr in arms.items():
|
||||
result.append(
|
||||
dict(
|
||||
phase="development",
|
||||
arm=a,
|
||||
held_out=g,
|
||||
fitted_groups=[x for x in "abcd" if x != g],
|
||||
completed=True,
|
||||
metrics=dict(recall=0.9, fpr=fpr),
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def test_no_seed_or_average_hides_lost_paint():
|
||||
rr = rows()
|
||||
assert assess_balance(rr, [1, 2, 3])["eligible_families"] == [
|
||||
"balanced-head",
|
||||
"balanced-decoder",
|
||||
]
|
||||
next(r for r in rr if r["arm"] == "balanced-decoder-2" and r["held_out"] == "a")["metrics"][
|
||||
"recall"
|
||||
] = 0.89
|
||||
out = assess_balance(rr, [1, 2, 3])
|
||||
assert "balanced-decoder" not in out["eligible_families"]
|
||||
assert "balanced-decoder" not in out["paired_policy_pass"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", ["control", "leak", "duplicate", "missing"])
|
||||
def test_gate_rejects_unpaired_or_contaminated_rows(error):
|
||||
rr = rows()
|
||||
if error == "control":
|
||||
rr[0]["phase"] = "regression"
|
||||
elif error == "leak":
|
||||
rr[0]["fitted_groups"].append(rr[0]["held_out"])
|
||||
elif error == "duplicate":
|
||||
rr.append(rr[0])
|
||||
else:
|
||||
rr.pop()
|
||||
with pytest.raises(ValueError):
|
||||
assess_balance(rr, [1, 2, 3])
|
||||
@@ -0,0 +1,51 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"transfer_gates",
|
||||
Path(__file__).resolve().parents[1] / "simulation/semantic-learning/transfer_gates.py",
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
def row(arm, recall, fpr, group="a"):
|
||||
return dict(
|
||||
phase="development",
|
||||
arm=arm,
|
||||
held_out=group,
|
||||
fitted_groups=["other"],
|
||||
completed=True,
|
||||
metrics=dict(recall=recall, fpr=fpr),
|
||||
)
|
||||
|
||||
|
||||
def test_lower_average_error_cannot_hide_lost_paint_and_negative_only_has_no_recall():
|
||||
rows = [
|
||||
row("base", 1.0, 0.2),
|
||||
row("candidate", 0.95, 0.01),
|
||||
row("base", None, 0.1, "negative"),
|
||||
row("candidate", None, 0.0, "negative"),
|
||||
]
|
||||
result = module.component_regressions(rows, "base", ["candidate"])
|
||||
assert not result["all_components_non_regressing"]
|
||||
assert [(r["group"], r["metric"]) for r in result["regressions"]] == [("a", "recall")]
|
||||
|
||||
|
||||
def test_unpaired_or_exposed_control_rows_cannot_define_future_gate():
|
||||
rows = [row("base", 1.0, 0.2), row("candidate", 1.0, 0.1)]
|
||||
assert module.component_regressions(rows, "base", ["candidate"])[
|
||||
"all_components_non_regressing"
|
||||
]
|
||||
with pytest.raises(ValueError, match="Development"):
|
||||
module.component_regressions(
|
||||
[dict(rows[0], phase="regression"), rows[1]], "base", ["candidate"]
|
||||
)
|
||||
with pytest.raises(ValueError, match="Unmatched"):
|
||||
module.component_regressions([rows[0]], "base", ["candidate"])
|
||||
with pytest.raises(ValueError, match="Leaked"):
|
||||
module.component_regressions(
|
||||
[dict(rows[0], fitted_groups=["a"]), rows[1]], "base", ["candidate"]
|
||||
)
|
||||
@@ -0,0 +1,478 @@
|
||||
"""Independent admission tests for vector editor topology, history and Worker replay."""
|
||||
|
||||
import ast
|
||||
import copy
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.simulation.ai_polygon import semantic_objects, semantic_vectors
|
||||
from k1link.simulation.ai_polygon.semantic_edits import apply_operations, paths
|
||||
|
||||
|
||||
def document():
|
||||
return {
|
||||
"schema_version": "missioncore.urban-map/v3",
|
||||
"source": {"world_sha256": "a" * 64},
|
||||
"features": [
|
||||
{
|
||||
"id": "road",
|
||||
"properties": {
|
||||
"class": "road_boundary",
|
||||
"authority": "observation-only",
|
||||
"route_permission": "unassigned",
|
||||
},
|
||||
"geometry": {
|
||||
"type": "Polygon",
|
||||
"coordinates": [
|
||||
[
|
||||
[0, 0, 2],
|
||||
[2, 0, 2],
|
||||
[4, 0, 2],
|
||||
[4, 4, 2],
|
||||
[2, 4, 2],
|
||||
[0, 4, 2],
|
||||
[0, 0, 2],
|
||||
]
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_group_delete_reconnects_closed_ring_and_is_atomic():
|
||||
base = document()
|
||||
before = copy.deepcopy(base)
|
||||
op = {
|
||||
"kind": "delete_vertices",
|
||||
"vertices": [{"feature_id": "road", "path": 0, "index": i} for i in (1, 2)],
|
||||
}
|
||||
result = apply_operations(base, [op])
|
||||
ring = paths(result["features"][0])[0]
|
||||
assert ring == [[0, 0, 2], [4, 4, 2], [2, 4, 2], [0, 4, 2], [0, 0, 2]]
|
||||
assert base == before
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base,
|
||||
[
|
||||
{
|
||||
"kind": "delete_vertices",
|
||||
"vertices": [
|
||||
{"feature_id": "road", "path": 0, "index": i} for i in (0, 1, 2, 3, 4)
|
||||
],
|
||||
}
|
||||
],
|
||||
)
|
||||
assert base == before
|
||||
|
||||
|
||||
def test_curve_and_vertical_axis_keep_provenance_and_validate_shape():
|
||||
base = document()
|
||||
op = dict(
|
||||
kind="curve", feature_id="road", path=0, index=1, incoming=[-0.6, -0.2], outgoing=[0.6, 0.2]
|
||||
)
|
||||
c = apply_operations(base, [op])
|
||||
assert c == apply_operations(copy.deepcopy(base), [op], verified_history=True)
|
||||
assert len(semantic_vectors.knots(c["features"][0], 0)) == 6
|
||||
moved = apply_operations(
|
||||
c,
|
||||
[
|
||||
dict(
|
||||
kind="translate",
|
||||
feature_id="road",
|
||||
vertices=[dict(feature_id="road", path=0, index=1)],
|
||||
axis="z",
|
||||
delta=[0, 0, 0.2],
|
||||
)
|
||||
],
|
||||
)
|
||||
assert semantic_vectors.knots(moved["features"][0], 0)[1]["point"] == [2, 0, 2.2]
|
||||
assert moved["features"][0]["properties"]["height_source"] == "human-axis-edit-unverified"
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
c, [dict(kind="move", feature_id="road", path=0, index=1, position=[2, 0, 3])]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
c,
|
||||
[
|
||||
dict(
|
||||
kind="curve",
|
||||
feature_id="road",
|
||||
path=0,
|
||||
index=1,
|
||||
incoming=[float("nan"), 0],
|
||||
outgoing=[0, 0],
|
||||
)
|
||||
],
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base, [dict(kind="move", feature_id="road", path=0, index=0, position=[5, 2, 2])]
|
||||
)
|
||||
|
||||
|
||||
def test_pedestrian_region_holes_are_still_checked():
|
||||
base = document()
|
||||
base["features"][0]["properties"]["class"] = "pedestrian_area"
|
||||
outer = paths(base["features"][0])[0]
|
||||
op = dict(
|
||||
kind="region",
|
||||
feature_id="road",
|
||||
token="abcdefghijklmnop",
|
||||
mode="union",
|
||||
brush=[[1, 1, 2], [3, 1, 2], [3, 3, 2], [1, 3, 2], [1, 1, 2]],
|
||||
polygons=[[outer]],
|
||||
)
|
||||
result = apply_operations(base, [op])
|
||||
assert result["features"][0]["properties"]["review_status"] == "unreviewed"
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base, [{**op, "polygons": [[outer, [[5, 5, 2], [6, 5, 2], [6, 6, 2], [5, 5, 2]]]]}]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
base, [{**op, "polygons": [[[[0, 0, 2], [4, 4, 2], [0, 4, 2], [4, 0, 2], [0, 0, 2]]]]}]
|
||||
)
|
||||
|
||||
|
||||
def test_worker_replays_vector_history_exactly(monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [
|
||||
n
|
||||
for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
first = dict(
|
||||
kind="curve", feature_id="road", path=0, index=1, incoming=[-0.6, -0.2], outgoing=[0.6, 0.2]
|
||||
)
|
||||
second = dict(
|
||||
kind="translate",
|
||||
feature_id="road",
|
||||
vertices=[dict(feature_id="road", path=0, index=1)],
|
||||
axis="xz",
|
||||
delta=[0.1, 0, 0.2],
|
||||
)
|
||||
before, replayed, affected = scope["contexts"](
|
||||
dict(model=document(), revisions=[dict(operations=[first]), dict(operations=[second])])
|
||||
)
|
||||
expected = apply_operations(document(), [first, second])
|
||||
assert [f["geometry"] for f in replayed] == [f["geometry"] for f in expected["features"]]
|
||||
assert len(affected) == 1 and before[0]["geometry"] != replayed[0]["geometry"]
|
||||
|
||||
|
||||
def duplicate(index=1, delta=None, axis="x"):
|
||||
return dict(
|
||||
kind="duplicate_vertex",
|
||||
feature_id="road",
|
||||
path=0,
|
||||
index=index,
|
||||
delta=delta if delta is not None else [0.5, 0, 0],
|
||||
axis=axis,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"index,delta,slot", [(0, [-1, 0, 0], 0), (1, [1, 0, 0], 2), (2, [1, 0, 0], 3)]
|
||||
)
|
||||
def test_duplicate_extends_ends_and_inserts_interior_without_moving_source(index, delta, slot):
|
||||
base = document()
|
||||
base["features"][0]["geometry"] = dict(
|
||||
type="LineString", coordinates=[[0, 0, 2], [2, 0, 2], [4, 0, 2]]
|
||||
)
|
||||
original = copy.deepcopy(base)
|
||||
result = apply_operations(base, [duplicate(index, delta)])
|
||||
nodes = semantic_vectors.knots(result["features"][0], 0)
|
||||
assert nodes[slot]["point"] == [
|
||||
original["features"][0]["geometry"]["coordinates"][index][k] + delta[k] for k in range(3)
|
||||
]
|
||||
assert [n["point"] for i, n in enumerate(nodes) if i != slot] == original["features"][0][
|
||||
"geometry"
|
||||
]["coordinates"]
|
||||
assert base == original
|
||||
assert result == apply_operations(base, [duplicate(index, delta)], verified_history=True)
|
||||
assert apply_operations(base, [duplicate(index, [0, 0, 0])]) == base
|
||||
|
||||
|
||||
def test_duplicate_closed_ring_curves_and_invalid_geometry_remain_checked():
|
||||
base = apply_operations(
|
||||
document(),
|
||||
[
|
||||
dict(
|
||||
kind="curve",
|
||||
feature_id="road",
|
||||
path=0,
|
||||
index=1,
|
||||
incoming=[-0.2, 0],
|
||||
outgoing=[0.2, 0],
|
||||
)
|
||||
],
|
||||
)
|
||||
old = semantic_vectors.knots(base["features"][0], 0)
|
||||
result = apply_operations(base, [duplicate()])
|
||||
new = semantic_vectors.knots(result["features"][0], 0)
|
||||
assert new[1] == old[1] and new[2]["incoming"] == old[1]["incoming"]
|
||||
ring = paths(result["features"][0])[0]
|
||||
assert ring[0] == ring[-1]
|
||||
for op in [
|
||||
duplicate(delta=[2, 0, 0]),
|
||||
duplicate(delta=[0, 0, 1], axis="z"),
|
||||
duplicate(delta=[0, 1, 0]),
|
||||
duplicate(delta=[float("nan"), 0, 0]),
|
||||
duplicate(index=-1),
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(document(), [op])
|
||||
|
||||
|
||||
def test_strip_vertices_stretch_but_legacy_rigid_history_and_symbols_keep_their_meaning():
|
||||
base = document()
|
||||
f = base["features"][0]
|
||||
f["properties"].update({"class": "road_marking", "subtype": "linear_marking"})
|
||||
f["geometry"]["coordinates"] = [[[0, 0, 2], [4, 0, 2], [4, 0.2, 2], [0, 0.2, 2], [0, 0, 2]]]
|
||||
op = dict(
|
||||
kind="translate_vertices",
|
||||
feature_id="road",
|
||||
vertices=[dict(feature_id="road", path=0, index=i) for i in (1, 2)],
|
||||
axis="x",
|
||||
delta=[2, 0, 0],
|
||||
)
|
||||
result = apply_operations(base, [op])
|
||||
assert paths(result["features"][0])[0] == [
|
||||
[0, 0, 2],
|
||||
[6, 0, 2],
|
||||
[6, 0.2, 2],
|
||||
[0, 0.2, 2],
|
||||
[0, 0, 2],
|
||||
]
|
||||
legacy = apply_operations(base, [{**op, "kind": "translate"}], verified_history=True)
|
||||
assert paths(legacy["features"][0])[0][0] == [2, 0, 2]
|
||||
for subtype in (None, "letter_A", "straight_arrow", "bicycle", "crosswalk"):
|
||||
symbol = copy.deepcopy(base)
|
||||
symbol["features"][0]["properties"]["subtype"] = subtype
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(symbol, [op])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(symbol, [duplicate()])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [{**op, "delta": [-4, 0, 0]}])
|
||||
|
||||
|
||||
def test_duplicate_save_reload_and_worker_replay(monkeypatch, tmp_path):
|
||||
from test_semantic_edits import make_setup
|
||||
|
||||
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits
|
||||
|
||||
world, model, maps, store, sha = make_setup(tmp_path)
|
||||
op = {**duplicate(2, [1, 0, 0]), "feature_id": "curb-1"}
|
||||
body = dict(
|
||||
expected_revision=None, model_sha256=sha, request_id="shift-duplicate-0001", operations=[op]
|
||||
)
|
||||
saved = store.save(world, body)
|
||||
assert SemanticEdits(store.root.parents[1], maps).get(world) == saved
|
||||
assert store.save(world, body) == saved and maps.get(world) == model
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [
|
||||
n
|
||||
for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
_, replayed, affected = scope["contexts"](dict(model=model, revisions=[dict(operations=[op])]))
|
||||
assert replayed[0]["geometry"] == saved["edited"]["features"][0]["geometry"]
|
||||
assert affected == [("curb-1", [4.5, 1.0, 2.0])]
|
||||
with pytest.raises(ValueError, match="window"):
|
||||
scope["contexts"](
|
||||
dict(model=model, revisions=[dict(operations=[{**op, "delta": [9, 0, 0]}])])
|
||||
)
|
||||
|
||||
|
||||
def test_linear_placement_edit_copy_and_worker_replay(monkeypatch):
|
||||
from test_semantic_objects import document, place
|
||||
|
||||
base = document()
|
||||
placement = place("linear_marking")
|
||||
fid = placement["feature_id"]
|
||||
vertices = [dict(feature_id=fid, path=0, index=i) for i in (1, 2)]
|
||||
stretch = dict(
|
||||
kind="translate_vertices", feature_id=fid, vertices=vertices, axis="x", delta=[2, 0, 0]
|
||||
)
|
||||
copy_op = dict(
|
||||
kind="duplicate_marking",
|
||||
feature_id=fid,
|
||||
new_feature_id="user-copy-1234567890123456",
|
||||
axis="y",
|
||||
delta=[0, 2, 0],
|
||||
)
|
||||
ops = [placement, stretch, copy_op]
|
||||
result = apply_operations(base, ops)
|
||||
assert len(result["features"]) == 2
|
||||
assert result["features"][0]["properties"]["subtype"] == "linear_marking"
|
||||
assert "semantic_element_id" not in result["features"][1]["properties"]
|
||||
assert result["features"][1]["properties"]["height_source"] == "human-copy-unverified"
|
||||
assert base["features"] == []
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(result, [copy_op])
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(
|
||||
result, [{**copy_op, "new_feature_id": "user-other-1234567890", "delta": [1, 2, 0]}]
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [
|
||||
n
|
||||
for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")
|
||||
]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
before, replayed, affected = scope["contexts"](
|
||||
dict(model=base, revisions=[dict(operations=ops)])
|
||||
)
|
||||
assert before == [] and replayed == result["features"]
|
||||
assert len(affected) == 2 and affected[-1][0] == copy_op["new_feature_id"]
|
||||
# New editable curve metadata must move with the whole strip, then remain editable.
|
||||
curved = apply_operations(
|
||||
result, [dict(kind="curve", **vertices[0], incoming=[-0.2, 0], outgoing=[0, 0.01])]
|
||||
)
|
||||
original = copy.deepcopy(curved)
|
||||
moved = apply_operations(curved, [{**copy_op, "new_feature_id": "user-curved-1234567890"}])
|
||||
assert curved == original
|
||||
for a, b in zip(
|
||||
semantic_vectors.knots(curved["features"][0], 0),
|
||||
semantic_vectors.knots(moved["features"][-1], 0),
|
||||
strict=True,
|
||||
):
|
||||
assert b["point"] == [a["point"][0], a["point"][1] + 2, a["point"][2]]
|
||||
assert b["incoming"] == a["incoming"]
|
||||
|
||||
|
||||
def test_copy_rigid_group_is_new_group_and_does_not_modify_source():
|
||||
from test_semantic_objects import document, place
|
||||
|
||||
base = apply_operations(document(), [place()])
|
||||
original = copy.deepcopy(base)
|
||||
op = dict(
|
||||
kind="duplicate_marking",
|
||||
feature_id=base["features"][2]["id"],
|
||||
new_feature_id="user-zebra-1234567890123",
|
||||
delta=[0, 2, 0],
|
||||
axis="y",
|
||||
)
|
||||
result = apply_operations(base, [op])
|
||||
assert base == original and result["features"][:6] == base["features"]
|
||||
assert len(result["features"]) == 12
|
||||
assert {f["properties"]["semantic_element_id"] for f in result["features"][6:]} == {
|
||||
op["new_feature_id"]
|
||||
}
|
||||
for a, b in zip(base["features"], result["features"][6:], strict=True):
|
||||
for r, s in zip(semantic_objects.paths(a), semantic_objects.paths(b), strict=True):
|
||||
assert s == [[p[0], p[1] + 2, p[2]] for p in r]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case",
|
||||
json.loads((Path(__file__).parent / "fixtures/semantic_duplicate_direction.json").read_text()),
|
||||
ids=lambda c: c["name"],
|
||||
)
|
||||
def test_directional_duplicate_exact_order_and_legacy_compatibility(case):
|
||||
base = document()
|
||||
points = case["points"]
|
||||
base["features"][0]["geometry"] = (
|
||||
dict(type="Polygon", coordinates=[points + [points[0]]])
|
||||
if case["closed"] else dict(type="LineString", coordinates=points)
|
||||
)
|
||||
original = copy.deepcopy(base)
|
||||
op = duplicate(case["index"], case["delta"], "yz" if case["delta"][2] else "xy")
|
||||
op["side"] = case["side"]
|
||||
result = apply_operations(base, [op])
|
||||
slot = case["index"] + int(case["side"] == "after")
|
||||
expected = copy.deepcopy(points)
|
||||
expected.insert(slot, [v + case["delta"][k] for k, v in enumerate(points[case["index"]])])
|
||||
assert [n["point"] for n in semantic_vectors.knots(result["features"][0], 0)] == expected
|
||||
assert base == original
|
||||
assert result == apply_operations(copy.deepcopy(base), [op], verified_history=True)
|
||||
if case["closed"]:
|
||||
ring = paths(result["features"][0])[0]
|
||||
assert ring[0] == ring[-1]
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [{**op, "side": "guess"}])
|
||||
|
||||
|
||||
def test_directional_insert_still_rejects_backtracking():
|
||||
base = document()
|
||||
base["features"][0]["geometry"] = dict(
|
||||
type="LineString", coordinates=[[0, 0, 2], [4, 0, 2], [8, 0, 2]]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
apply_operations(base, [{**duplicate(1, [-1, 0, 0]), "side": "after"}])
|
||||
assert apply_operations(base, [{**duplicate(1, [-1, 0, 0]), "side": "before"}])
|
||||
|
||||
|
||||
def test_worker_replays_explicit_side_and_legacy_chain(monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "semantic_objects", semantic_objects)
|
||||
monkeypatch.setitem(sys.modules, "semantic_vectors", semantic_vectors)
|
||||
path = Path(__file__).parents[1] / "simulation/semantic-learning/build_samples.py"
|
||||
nodes = [n for n in ast.parse(path.read_text()).body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in ("contexts", "apply")]
|
||||
scope = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)
|
||||
base = document()
|
||||
base["features"][0]["geometry"] = dict(
|
||||
type="LineString", coordinates=[[0, 0, 2], [4, 0, 2], [8, 0, 2]]
|
||||
)
|
||||
legacy = duplicate(2, [1, 0, 0])
|
||||
new = {**duplicate(1, [-1, 0, 0]), "side": "before"}
|
||||
before, replayed, _ = scope["contexts"](
|
||||
dict(model=base, revisions=[dict(operations=[legacy]), dict(operations=[new])])
|
||||
)
|
||||
expected = apply_operations(base, [legacy, new])
|
||||
assert [f["geometry"] for f in replayed] == [f["geometry"] for f in expected["features"]]
|
||||
assert before[0]["geometry"]["coordinates"] == [[0, 0, 2], [4, 0, 2], [8, 0, 2], [9, 0, 2]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["translate_vertices", "delete_vertices"])
|
||||
def test_group_validation_does_not_copy_the_spline_for_every_selected_vertex(monkeypatch, kind):
|
||||
base = document()
|
||||
feature = base["features"][0]
|
||||
feature["geometry"] = dict(type="LineString", coordinates=[[i, 0, 2] for i in range(130)])
|
||||
feature = semantic_vectors.with_knots(feature, 0, semantic_vectors.knots(feature, 0))
|
||||
base["features"][0] = feature
|
||||
original = copy.deepcopy(base)
|
||||
references = [dict(feature_id="road", path=0, index=i) for i in range(1, 129)]
|
||||
op = dict(kind=kind, vertices=references)
|
||||
if kind == "translate_vertices":
|
||||
op.update(feature_id="road", delta=[0, 1, 0], axis="y")
|
||||
copied_points = 0
|
||||
real = semantic_vectors.knots
|
||||
|
||||
def count(*args):
|
||||
nonlocal copied_points
|
||||
nodes = real(*args)
|
||||
copied_points += len(nodes)
|
||||
return nodes
|
||||
|
||||
monkeypatch.setattr(semantic_vectors, "knots", count)
|
||||
result = apply_operations(base, [op])
|
||||
# Linear allocation budget: group validation must not be O(vertices * spline).
|
||||
assert copied_points <= 3 * 130
|
||||
expected = [[0, 0, 2], [129, 0, 2]] if kind == "delete_vertices" else (
|
||||
[[0, 0, 2]] + [[i, 1, 2] for i in range(1, 129)] + [[129, 0, 2]]
|
||||
)
|
||||
assert result["features"][0]["geometry"]["coordinates"] == expected
|
||||
invalid = copy.deepcopy(op)
|
||||
invalid["vertices"].append(dict(feature_id="road", path=0, index=130))
|
||||
with pytest.raises(ValueError, match="Точка не найдена"):
|
||||
apply_operations(base, [invalid])
|
||||
assert base == original
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Isolation, partial-pixel pooling and complete-background checks."""
|
||||
|
||||
import copy
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
np = pytest.importorskip("numpy")
|
||||
for dependency in ["cv2", "scipy", "shapely"]:
|
||||
pytest.importorskip(dependency)
|
||||
from shapely.geometry import box, mapping # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for directory in [
|
||||
"simulation/semantic-learning",
|
||||
"simulation/urban-plan-research/systematic",
|
||||
"simulation/urban-plan-research/marking_pass",
|
||||
]:
|
||||
sys.path.insert(0, str(ROOT / directory))
|
||||
study = importlib.import_module("visual_admission_study")
|
||||
|
||||
|
||||
def test_thin_masks_survive_fractional_pooling():
|
||||
mask = np.zeros((512, 512), bool)
|
||||
mask[100:400, 103] = True
|
||||
weights = study.fractional_weights(mask, (128, 128))
|
||||
assert weights.sum() == pytest.approx(1)
|
||||
assert np.count_nonzero(weights) == 75
|
||||
assert weights[:, 25].sum() == pytest.approx(1)
|
||||
with pytest.raises(ValueError):
|
||||
study.fractional_weights(np.zeros_like(mask), (128, 128))
|
||||
|
||||
|
||||
def test_complete_background_counts_false_objects_but_preserves_unknown_and_paint():
|
||||
review = dict(
|
||||
objects=[
|
||||
dict(id="truth", family="bar", complete=True, geometry=mapping(box(10, 10, 30, 20)))
|
||||
],
|
||||
negative=[],
|
||||
complete_background=[mapping(box(0, 0, 100, 100).difference(box(8, 8, 32, 22)))],
|
||||
)
|
||||
cs = [
|
||||
dict(id="paint", geometry=mapping(box(10, 10, 30, 20))),
|
||||
dict(id="false", geometry=mapping(box(40, 40, 60, 60))),
|
||||
dict(id="unknown", geometry=mapping(box(110, 110, 130, 130))),
|
||||
]
|
||||
result = study.assessed(cs, review)
|
||||
assert result["found"] == 1
|
||||
assert result["unsupported_sparse"] == 0
|
||||
assert result["false_ids"] == ["false"]
|
||||
|
||||
|
||||
def test_feature_pooling_is_independent_of_labels():
|
||||
mask = np.zeros((16, 16), bool)
|
||||
mask[3:9, 7:12] = True
|
||||
weights = study.fractional_weights(mask, (4, 4))
|
||||
assert np.all(weights >= 0)
|
||||
assert weights.sum() == pytest.approx(1)
|
||||
constant = np.full((4, 4), 7.0)
|
||||
assert np.sum(weights * constant) == pytest.approx(7)
|
||||
|
||||
|
||||
def test_fit_uses_only_passed_development_records(monkeypatch):
|
||||
records = [
|
||||
dict(
|
||||
id="dev",
|
||||
variants={
|
||||
"retained": [
|
||||
dict(features=[0], geometry=mapping(box(0, 0, 10, 10))),
|
||||
dict(features=[1], geometry=mapping(box(20, 20, 30, 30))),
|
||||
dict(features=[2], geometry=mapping(box(40, 40, 50, 50))),
|
||||
dict(features=[3], geometry=mapping(box(60, 60, 70, 70))),
|
||||
]
|
||||
},
|
||||
)
|
||||
]
|
||||
truth = dict(
|
||||
objects=[
|
||||
dict(geometry=mapping(box(0, 0, 10, 10))),
|
||||
dict(geometry=mapping(box(20, 20, 30, 30))),
|
||||
],
|
||||
negative=[[(35, 35), (80, 35), (80, 80), (35, 80)]],
|
||||
)
|
||||
review = {"dev": truth, "control": copy.deepcopy(truth)}
|
||||
data = {
|
||||
"dev": {"visual512": np.arange(8).reshape(4, 2)},
|
||||
"control": {"visual512": np.full((4, 2), 999)},
|
||||
}
|
||||
captured = []
|
||||
|
||||
def fitted(x, y, l2, maxiter):
|
||||
captured.append((x.copy(), y.copy()))
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(study, "fit_classifier", fitted)
|
||||
study.fit_head(records, review, data, "visual512", 0.1)
|
||||
review["control"] = {"objects": [], "negative": []}
|
||||
data["control"]["visual512"] *= 2
|
||||
study.fit_head(records, review, data, "visual512", 0.1)
|
||||
assert np.array_equal(captured[0][0], captured[1][0])
|
||||
assert np.array_equal(captured[0][1], captured[1][1])
|
||||
@@ -0,0 +1,82 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "simulation/semantic-learning"
|
||||
for name in ["condition_inventory", "weak_paint_admission"]:
|
||||
spec = importlib.util.spec_from_file_location(name, ROOT / (name + ".py"))
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
m = sys.modules["weak_paint_admission"]
|
||||
|
||||
|
||||
def example():
|
||||
t = np.full((16, 16), 255, dtype="uint8")
|
||||
t[0, 0] = 0
|
||||
t[15, 15] = 1
|
||||
s = dict(
|
||||
name="a",
|
||||
kind="existing",
|
||||
split="train",
|
||||
size=[16, 16],
|
||||
rgb_sha256="a" * 64,
|
||||
target_sha256=hashlib.sha256(t.tobytes()).hexdigest(),
|
||||
)
|
||||
r = dict(
|
||||
name="a",
|
||||
input_sha256=s["rgb_sha256"],
|
||||
target_sha256=s["target_sha256"],
|
||||
boundary_ignore_px=1,
|
||||
paint_fragments=[[[128, 128], [384, 128], [384, 384], [128, 384]]],
|
||||
)
|
||||
return s, r, t, [[0, 0], [512, 0], [512, 512], [0, 512]]
|
||||
|
||||
|
||||
def test_only_explicit_paint_added_and_original_untouched():
|
||||
s, r, t, roi = example()
|
||||
before = t.copy()
|
||||
t.flags.writeable = False
|
||||
out, added = m.add_fragments(s, r, t, roi)
|
||||
assert np.array_equal(t, before) and np.array_equal(out[t != 255], t[t != 255])
|
||||
assert added.sum() == 49 and np.all(out[added] == 1) and np.array_equal(out == 0, t == 0)
|
||||
assert out[4, 4] == 255 and out[5, 5] == 1 and out[3, 3] == 255
|
||||
rr = m.runs(out)
|
||||
rebuilt = np.full_like(out, 255)
|
||||
for kind, label in [("paint", 1), ("background", 0)]:
|
||||
for y, a, b in rr[kind]:
|
||||
rebuilt[y, a:b] = label
|
||||
assert np.array_equal(out, rebuilt)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mutation", ["control", "source", "target", "conflict", "roi", "empty", "policy", "candidate"]
|
||||
)
|
||||
def test_invalid_admission_rejected(mutation):
|
||||
s, r, t, roi = example()
|
||||
r = copy.deepcopy(r)
|
||||
if mutation == "control":
|
||||
s["split"] = "regression"
|
||||
elif mutation == "source":
|
||||
r["input_sha256"] = "b" * 64
|
||||
elif mutation == "target":
|
||||
t[0, 1] = 1
|
||||
elif mutation == "conflict":
|
||||
t[8, 8] = 0
|
||||
s["target_sha256"] = r["target_sha256"] = hashlib.sha256(t.tobytes()).hexdigest()
|
||||
elif mutation == "roi":
|
||||
roi = [[0, 0], [64, 0], [64, 64], [0, 64]]
|
||||
elif mutation == "empty":
|
||||
r["paint_fragments"] = [[[128, 128], [130, 128], [130, 130], [128, 130]]]
|
||||
elif mutation == "policy":
|
||||
r["boundary_ignore_px"] = 0
|
||||
elif mutation == "candidate":
|
||||
s["kind"] = "candidate"
|
||||
s["target_sha256"] = r["target_sha256"] = None
|
||||
with pytest.raises(ValueError):
|
||||
m.add_fragments(s, r, t, roi)
|
||||
@@ -0,0 +1,55 @@
|
||||
import copy
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"weak_paint_transfer",
|
||||
Path(__file__).resolve().parents[1] / "simulation/semantic-learning/weak_paint_transfer.py",
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def rows():
|
||||
out = []
|
||||
groups = {"a", "b", "c", "d"}
|
||||
for group in sorted(groups):
|
||||
for arm, hit in [("base-1", 5), ("added-1", 6)]:
|
||||
metric = dict(tp=hit, fn=10 - hit, fp=1, tn=9, recall=hit / 10, fpr=0.1)
|
||||
out.append(
|
||||
dict(
|
||||
phase="development",
|
||||
arm=arm,
|
||||
held_out=group,
|
||||
fitted_groups=sorted(groups - {group}),
|
||||
completed=True,
|
||||
**{k: copy.deepcopy(metric) for k in ["weak", "clear", "original", "added"]},
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_tradeoff_cannot_hide_behind_mean_improvement():
|
||||
rr = rows()
|
||||
assert m.assess(rr, [1])["passed"]
|
||||
rr[1]["original"].update(fp=2, tn=8, fpr=0.2)
|
||||
assert not m.assess(rr, [1])["passed"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["leak", "missing", "support", "pair", "duplicate"])
|
||||
def test_bad_pairs_rejected(bad):
|
||||
rr = rows()
|
||||
if bad == "leak":
|
||||
rr[0]["fitted_groups"].append("a")
|
||||
if bad == "missing":
|
||||
rr.pop()
|
||||
if bad == "support":
|
||||
rr[0]["weak"]["recall"] = None
|
||||
if bad == "pair":
|
||||
rr[1]["weak"]["fn"] += 1
|
||||
if bad == "duplicate":
|
||||
rr[-1] = copy.deepcopy(rr[1])
|
||||
with pytest.raises(ValueError):
|
||||
m.assess(rr, [1])
|
||||
@@ -0,0 +1,123 @@
|
||||
import math
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import weighted_paint_loss as subject
|
||||
|
||||
try:
|
||||
import torch
|
||||
from torch.nn import functional as functional
|
||||
except ImportError:
|
||||
torch = None
|
||||
|
||||
|
||||
@unittest.skipIf(torch is None, "Torch training runtime required; run on pinned Worker image")
|
||||
class WeightedPaintLossTests(unittest.TestCase):
|
||||
def example(self):
|
||||
x = torch.tensor(
|
||||
[[[[1.0, -2.0, 8.0], [0.3, -0.4, 1.0]], [[-0.5, 3.0, -9.0], [1.0, 0.8, -0.1]]]],
|
||||
dtype=torch.float64,
|
||||
)
|
||||
y = torch.tensor([[[0, 1, 255], [1, 0, 255]]])
|
||||
return x, y
|
||||
|
||||
def test_weighted_mean_formula(self):
|
||||
x, y = self.example()
|
||||
weights = [1.0, 8.0]
|
||||
expected = (
|
||||
sum(
|
||||
-x.log_softmax(1)[0, int(y[0, a, b]), a, b] * weights[int(y[0, a, b])]
|
||||
for a, b in [(0, 0), (0, 1), (1, 0), (1, 1)]
|
||||
)
|
||||
/ 18
|
||||
)
|
||||
self.assertTrue(
|
||||
torch.allclose(subject.weighted_paint_cross_entropy(x, y, weights), expected)
|
||||
)
|
||||
|
||||
def test_unknown_has_zero_gradient(self):
|
||||
x, y = self.example()
|
||||
x.requires_grad_()
|
||||
subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0]).backward()
|
||||
self.assertEqual(torch.count_nonzero(x.grad.permute(0, 2, 3, 1)[y == 255]), 0)
|
||||
self.assertGreater(torch.count_nonzero(x.grad.permute(0, 2, 3, 1)[y != 255]), 0)
|
||||
|
||||
def test_ignore_padding_invariance(self):
|
||||
x, y = self.example()
|
||||
a = subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0])
|
||||
b = subject.weighted_paint_cross_entropy(
|
||||
functional.pad(x, (0, 2), value=50), functional.pad(y, (0, 2), value=255), [1.0, 8.0]
|
||||
)
|
||||
self.assertTrue(torch.allclose(a, b))
|
||||
|
||||
def test_uniform_weights_reproduce_original(self):
|
||||
x, y = self.example()
|
||||
self.assertTrue(
|
||||
torch.allclose(
|
||||
subject.weighted_paint_cross_entropy(x, y, [1.0, 1.0]),
|
||||
functional.cross_entropy(x, y, ignore_index=255),
|
||||
)
|
||||
)
|
||||
|
||||
def test_bg_only_not_weakened_and_correct_gradient(self):
|
||||
y = torch.zeros((1, 2, 2), dtype=torch.long)
|
||||
x = torch.zeros((1, 2, 2, 2), dtype=torch.float64, requires_grad=True)
|
||||
loss = subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0])
|
||||
self.assertTrue(torch.allclose(loss, functional.cross_entropy(x, y)))
|
||||
loss.backward()
|
||||
self.assertTrue(bool((x.grad[:, 1] > 0).all()))
|
||||
z = x.detach().clone()
|
||||
z[:, 1] += 2
|
||||
self.assertGreater(subject.weighted_paint_cross_entropy(z, y, [1.0, 8.0]), loss)
|
||||
|
||||
def test_common_weight_scale_invariant(self):
|
||||
x, y = self.example()
|
||||
self.assertTrue(
|
||||
torch.allclose(
|
||||
subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0]),
|
||||
subject.weighted_paint_cross_entropy(x, y, [2.0, 16.0]),
|
||||
)
|
||||
)
|
||||
|
||||
def test_permutations_preserve_loss(self):
|
||||
x, y = self.example()
|
||||
expected = subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0])
|
||||
for k in range(4):
|
||||
for flip in [False, True]:
|
||||
a, b = x.rot90(k, (2, 3)), y.rot90(k, (1, 2))
|
||||
if flip:
|
||||
a, b = a.flip(-1), b.flip(-1)
|
||||
self.assertTrue(
|
||||
torch.allclose(expected, subject.weighted_paint_cross_entropy(a, b, [1.0, 8.0]))
|
||||
)
|
||||
|
||||
def test_all_unknown_rejected(self):
|
||||
x, y = self.example()
|
||||
with self.assertRaises(ValueError):
|
||||
subject.weighted_paint_cross_entropy(x, torch.full_like(y, 255), [1.0, 8.0])
|
||||
|
||||
def test_invalid_weights_rejected(self):
|
||||
x, y = self.example()
|
||||
for w in [[1.0], [0.0, 1.0], [1.0, -2.0], [math.inf, 1.0], [math.nan, 1.0], [1.0, 1e100]]:
|
||||
with self.subTest(weights=w), self.assertRaises(ValueError):
|
||||
subject.weighted_paint_cross_entropy(x.float(), y, w)
|
||||
|
||||
def test_invalid_labels_and_shape_rejected(self):
|
||||
x, y = self.example()
|
||||
for target in [y.float(), y[..., :2], torch.full_like(y, 2)]:
|
||||
with self.assertRaises(ValueError):
|
||||
subject.weighted_paint_cross_entropy(x, target, [1.0, 8.0])
|
||||
with self.assertRaises(ValueError):
|
||||
subject.weighted_paint_cross_entropy(x[:, :1], y, [1.0, 8.0])
|
||||
|
||||
def test_rare_paint_error_has_larger_gradient(self):
|
||||
x = torch.zeros((1, 2, 1, 2), dtype=torch.float64, requires_grad=True)
|
||||
y = torch.tensor([[[0, 1]]])
|
||||
subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0]).backward()
|
||||
self.assertAlmostEqual(float(x.grad[0, 1, 0, 1].abs() / x.grad[0, 1, 0, 0].abs()), 8.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user