Spaces:
Sleeping
Sleeping
File size: 30,563 Bytes
3d5c3e3 dcd4298 3d5c3e3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 | import json
from collections import Counter
from dataclasses import FrozenInstanceError
from datetime import UTC, datetime
import pytest
from scenarios.examples.plant_quality_investigation.build import build_package
from tests.conftest import _test_cfg
from world_compiler.domain.events import (
EpistemicType,
EventEnvelope,
EventType,
MessageSentPayload,
Provenance,
ResolvedPrincipal,
)
from world_compiler.domain.schemas.package import ScenarioPackage
from world_compiler.infrastructure.database.store import EventStore
from world_compiler.integrations.llm.mock import MockProvider
from world_compiler.runtime.app import build_runtime
from world_compiler.runtime.transmission.engine import transmission_rule_hash
from world_compiler.runtime.world.scenario_store import ScenarioStore
def _runtime_with_cfg(tmp_path, cfg):
ScenarioStore(tmp_path / "data").save(build_package(), tenant_id="t1")
return build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=MockProvider(),
)
def _event_type_multiset(runtime):
return Counter(
event.event_type
for event in runtime.store.read_all(
"t1",
"c1",
"s1",
runtime.scope.scenario_id,
runtime.scope.scenario_version,
)
)
def test_session_budget_crossing_finishes_turn_then_refuses_cleanly(tmp_path):
cfg = _test_cfg(tmp_path)
cfg.parameters.session_token_budget = 1
runtime = _runtime_with_cfg(tmp_path, cfg)
runtime.start_default()
from world_compiler.runtime.orchestrator.router import SessionBudgetExceeded
reply = runtime.student_message("ACTOR-A", "hello")
assert reply
after_completed_turn = _event_type_multiset(runtime)
assert after_completed_turn[EventType.MESSAGE_SENT] == 2
assert after_completed_turn[EventType.PROVIDER_USAGE] >= 1
with pytest.raises(SessionBudgetExceeded):
runtime.student_message("ACTOR-A", "second turn")
assert _event_type_multiset(runtime) == after_completed_turn
def test_provider_usage_is_nonzero_and_cumulative(tmp_path):
runtime = _runtime_with_cfg(tmp_path, _test_cfg(tmp_path))
runtime.start_default()
runtime.student_message("ACTOR-A", "question one")
first_total = runtime.tokens_used
runtime.student_message("ACTOR-B", "question two")
events = runtime.store.read_all(
"t1", "c1", "s1", runtime.scope.scenario_id, runtime.scope.scenario_version
)
usages = [
event for event in events if event.event_type == EventType.PROVIDER_USAGE
]
by_id = {event.event_id: event for event in events}
assert first_total > 0
assert runtime.tokens_used > first_total
assert runtime.tokens_used == sum(
usage.payload["input_tokens"] + usage.payload["output_tokens"]
for usage in usages
)
for usage in usages:
assert len(usage.parent_event_ids) == 1
parent_id = usage.parent_event_ids[0]
assert usage.event_id == f"usage:{parent_id}"
assert by_id[parent_id].event_type in {
EventType.MESSAGE_SENT,
EventType.COMPACTION_WRITTEN,
EventType.PRIVATE_SIGNAL_DELIVERED,
}
assert {principal.kind for principal in usage.visibility} == {"instructor"}
def test_rebuilt_runtime_preserves_usage_and_refuses_below_recorded_total(tmp_path):
cfg = _test_cfg(tmp_path)
first = _runtime_with_cfg(tmp_path, cfg)
first.start_default()
first.student_message("ACTOR-A", "question one")
recorded_usage = first.tokens_used
assert recorded_usage > 0
cfg.parameters.session_token_budget = recorded_usage - 1
rebuilt = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=MockProvider(),
)
before_refusal = _event_type_multiset(rebuilt)
from world_compiler.runtime.orchestrator.router import SessionBudgetExceeded
assert rebuilt.tokens_used == recorded_usage
with pytest.raises(SessionBudgetExceeded):
rebuilt.student_message("ACTOR-A", "question two")
assert _event_type_multiset(rebuilt) == before_refusal
def test_rebuild_repairs_crash_orphaned_actor_reply_usage_and_refuses(tmp_path):
cfg = _test_cfg(tmp_path)
first = _runtime_with_cfg(tmp_path, cfg)
first.start_default()
reply_text = "01234567890123456789"
reply = EventEnvelope(
event_id="reply:t1:c1:s1:1:1",
tenant_id="t1",
course_id="c1",
session_id="s1",
scenario_id="plant_quality",
scenario_version="1.0.0",
turn=1,
actor_id="ACTOR-A",
event_type=EventType.MESSAGE_SENT,
payload=MessageSentPayload(
sender_role="ACTOR-A",
recipient_role="STUDENT",
text=reply_text,
epistemic_type=EpistemicType.CLAIM,
).model_dump(mode="json"),
visibility=[
ResolvedPrincipal(
kind="actor",
tenant_id="t1",
course_id="c1",
session_id="s1",
actor_id="ACTOR-A",
),
ResolvedPrincipal(
kind="participant",
tenant_id="t1",
course_id="c1",
session_id="s1",
actor_id="STUDENT",
),
ResolvedPrincipal(
kind="instructor",
tenant_id="t1",
course_id="c1",
session_id="s1",
),
],
provenance=Provenance(source_event_ids=[]),
rng_seed=None,
parent_event_ids=[],
retention_class="course",
created_at=datetime.now(UTC),
)
first.store.append("actor_runtime", reply, idempotency_key=reply.event_id)
cfg.parameters.session_token_budget = 10
rebuilt = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=MockProvider(),
)
before_refusal = _event_type_multiset(rebuilt)
from world_compiler.runtime.orchestrator.router import SessionBudgetExceeded
assert rebuilt.tokens_used == 10
with pytest.raises(SessionBudgetExceeded):
rebuilt.student_message("ACTOR-A", "question two")
assert _event_type_multiset(rebuilt) == before_refusal
def test_shared_session_id_is_isolated_across_tenants(tmp_path):
cfg = _test_cfg(tmp_path)
scenario_store = ScenarioStore(tmp_path / "data")
scenario_store.save(build_package(), tenant_id="tenant-a")
scenario_store.save(build_package(), tenant_id="tenant-b")
first = build_runtime(
cfg=cfg,
tenant_id="tenant-a",
course_id="course-1",
scenario_id="plant_quality",
version="1.0.0",
session_id="s1",
session_seed=42,
provider=MockProvider(),
)
second = build_runtime(
cfg=cfg,
tenant_id="tenant-b",
course_id="course-1",
scenario_id="plant_quality",
version="1.0.0",
session_id="s1",
session_seed=42,
provider=MockProvider(),
)
first.start_default()
second.start_default()
first_events = first.store.read_all(
"tenant-a", "course-1", "s1", "plant_quality", "1.0.0"
)
second_events = second.store.read_all(
"tenant-b", "course-1", "s1", "plant_quality", "1.0.0"
)
assert first_events
assert second_events
assert {event.tenant_id for event in first_events} == {"tenant-a"}
assert {event.tenant_id for event in second_events} == {"tenant-b"}
assert first_events[0].event_id == "session:tenant-a:course-1:s1:start"
assert second_events[0].event_id == "session:tenant-b:course-1:s1:start"
def test_full_scripted_session(runtime):
runtime.start_default()
for i, role in enumerate(["ACTOR-A", "ACTOR-B", "ACTOR-C", "ACTOR-A"]):
reply = runtime.student_message(role, f"question {i}")
assert isinstance(reply, str) and reply
runtime.submit("The resin change caused the defects", cited_event_ids=[])
types = {
e.event_type
for e in runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
}
assert EventType.ASSESSMENT_SUBMITTED in types
assert EventType.TRANSMISSION_EVALUATED in types
def test_submit_refuses_fabricated_citation_without_appending(runtime):
"""Rejecting an unknown citation must leave the ledger and symbols untouched."""
runtime.start_default()
events_before = runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
symbols_before = runtime.symbol_env
with pytest.raises(ValueError):
runtime.submit("The evidence supports my conclusion.", ["fabricated-event"])
assert (
runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
== events_before
)
assert runtime.symbol_env == symbols_before
def test_submit_refuses_duplicate_citation_without_appending(runtime):
"""Rejecting a duplicated citation must leave the ledger and symbols untouched."""
runtime.start_default()
events_before = runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
symbols_before = runtime.symbol_env
start_event_id = "session:t1:c1:s1:start"
with pytest.raises(ValueError):
runtime.submit(
"The evidence supports my conclusion.",
[start_event_id, start_event_id],
)
assert (
runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
== events_before
)
assert runtime.symbol_env == symbols_before
def test_submit_refuses_other_actor_private_citation_without_appending(runtime):
"""Student submissions cannot cite role assignments private to another actor."""
runtime.start_default()
events_before = runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
symbols_before = runtime.symbol_env
other_actor_assignment_id = "assign:t1:c1:s1:ACTOR-A"
with pytest.raises(ValueError):
runtime.submit(
"The evidence supports my conclusion.", [other_actor_assignment_id]
)
assert (
runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
== events_before
)
assert runtime.symbol_env == symbols_before
def test_submit_refuses_private_citation_after_projection_result_mutation(runtime):
"""Mutating a returned projection must not poison later citation checks."""
runtime.start_default()
student = ResolvedPrincipal(
kind="participant",
tenant_id="t1",
course_id="c1",
session_id="s1",
actor_id="STUDENT",
)
returned_projection = runtime.projection.for_principal(student, "s1")
private_event = next(
event
for event in runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if event.event_id == "assign:t1:c1:s1:ACTOR-A"
)
returned_projection[0].event_id = private_event.event_id
returned_projection.append(private_event)
events_before = runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
symbols_before = runtime.symbol_env
with pytest.raises(ValueError, match="visible to the student"):
runtime.submit("The evidence supports my conclusion.", [private_event.event_id])
assert (
runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
== events_before
)
assert runtime.symbol_env == symbols_before
def test_runtime_exposes_immutable_package_summary_without_raw_package(runtime):
summary = runtime.package_summary()
assert summary.scenario_id == "plant_quality"
assert summary.scenario_version == "1.0.0"
assert summary.roles == ("ACTOR-A", "ACTOR-B", "ACTOR-C", "ACTOR-D", "STUDENT")
assert summary.phase_names == ("Briefing", "Investigation", "Debrief")
with pytest.raises(FrozenInstanceError):
summary.scenario_id = "altered"
assert not hasattr(runtime, "pkg")
def test_runtime_rule_output_resists_mutation_of_loaded_package(tmp_path, monkeypatch):
cfg = _test_cfg(tmp_path)
caller_loaded_package = build_package()
def load_caller_package(*_args, **_kwargs):
return caller_loaded_package
monkeypatch.setattr(ScenarioStore, "load", load_caller_package)
runtime = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"mutation-resistant-session",
session_seed=42,
provider=MockProvider(),
)
caller_loaded_package.decision_rules[0].params["adjustment"] = 1.0
runtime.start_default()
runtime.student_message("ACTOR-A", "What changed?")
rule_output = next(
event.payload["changes"]["defect_rate"]["to"]
for event in runtime.store.read_all(
"t1", "c1", "mutation-resistant-session", "plant_quality", "1.0.0"
)
if event.event_type == EventType.WORLD_STATE_CHANGED
)
assert rule_output == 0.035
def test_runtime_mints_monotonic_message_reply_and_submission_ids(runtime):
runtime.start_default()
runtime.student_message("ACTOR-A", "What changed?")
runtime.submit("The line speed changed.", cited_event_ids=[])
conversational = [
event.event_id
for event in runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if event.event_type in {EventType.MESSAGE_SENT, EventType.ASSESSMENT_SUBMITTED}
]
assert conversational == [
"msg:t1:c1:s1:1:1",
"reply:t1:c1:s1:1:2",
"submit:t1:c1:s1:3",
]
def test_rebuilt_runtime_continues_full_ledger_derived_state(tmp_path, monkeypatch):
cfg = _test_cfg(tmp_path)
ScenarioStore(tmp_path / "data").save(build_package(), tenant_id="t1")
first = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=MockProvider(),
)
first.start_default()
first.student_message("ACTOR-A", "question 1")
first.student_message("ACTOR-B", "question 2")
first.submit(
"The line speed and sample evidence explain the defect rate.",
cited_event_ids=["msg:t1:c1:s1:1:1", "msg:t1:c1:s1:2:3"],
)
before_rebuild = [
event.payload["changes"]["defect_rate"]["to"]
for event in first.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if event.event_type == EventType.WORLD_STATE_CHANGED
]
assert before_rebuild == [0.035, 0.05]
original_read_all = EventStore.read_all
reconstruction_reads = 0
def counted_read_all(
store,
tenant_id,
course_id,
session_id,
scenario_id,
scenario_version,
):
nonlocal reconstruction_reads
reconstruction_reads += 1
return original_read_all(
store,
tenant_id,
course_id,
session_id,
scenario_id,
scenario_version,
)
monkeypatch.setattr(EventStore, "read_all", counted_read_all)
rebuilt_provider = MockProvider()
rebuilt = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=rebuilt_provider,
)
assert reconstruction_reads == 1
monkeypatch.setattr(EventStore, "read_all", original_read_all)
assert rebuilt.symbol_env == {
"turn": 2,
"phase": "DEBRIEF",
"interview_count": 2,
"submission_count": 1,
"has_pending_interview": False,
"evidence_cited_count": 2,
}
rebuilt.student_message("ACTOR-A", "question 3")
actor_a_request = next(
request
for request in rebuilt_provider.requests
if request.purpose == "actor_turn"
and request.metadata.get("role_id") == "ACTOR-A"
)
actor_a_context = " ".join(
message["content"] for message in actor_a_request.messages
)
assert "LWC-CANARY-KA" in actor_a_context
conversational = [
event.event_id
for event in rebuilt.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if event.event_type == EventType.MESSAGE_SENT
]
assert conversational == [
"msg:t1:c1:s1:1:1",
"reply:t1:c1:s1:1:2",
"msg:t1:c1:s1:2:3",
"reply:t1:c1:s1:2:4",
"msg:t1:c1:s1:3:6",
"reply:t1:c1:s1:3:7",
]
assert rebuilt.symbol_env["turn"] == 3
assert rebuilt.symbol_env["interview_count"] == 3
after_rebuild = [
event.payload["changes"]["defect_rate"]["to"]
for event in rebuilt.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if event.event_type == EventType.WORLD_STATE_CHANGED
]
assert after_rebuild == [0.035, 0.05, 0.065]
def test_rebuilt_runtime_delivers_fired_pending_transmission_once(tmp_path):
"""Dropping a fired-but-undelivered evaluation during restart must fail."""
package = build_package()
rule = package.transmission_rules[0]
rule.base_probability = 1.0
rule.modifiers = {}
rule.transformation = "verbatim"
rule.delay_turns = 1
package.manifest.rule_hashes[rule.rule_id] = transmission_rule_hash(rule)
cfg = _test_cfg(tmp_path)
ScenarioStore(tmp_path / "data").save(package, tenant_id="t1")
first = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"pending-delivery-session",
session_seed=42,
provider=MockProvider(),
)
first.start_default()
first.student_message("ACTOR-A", "The resin change caused the defects.")
before_rebuild = first.store.read_all(
"t1", "c1", "pending-delivery-session", "plant_quality", "1.0.0"
)
evaluated = next(
event
for event in before_rebuild
if event.event_type == EventType.TRANSMISSION_EVALUATED
)
assert evaluated.payload["fired"] is True
assert not any(
event.event_type == EventType.PRIVATE_SIGNAL_DELIVERED
and event.payload.get("expansion_kind") == "cross_role_transmission"
for event in before_rebuild
)
rebuilt_provider = MockProvider()
rebuilt = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"pending-delivery-session",
session_seed=42,
provider=rebuilt_provider,
)
assert rebuilt_provider.requests == []
rebuilt.student_message("ACTOR-B", "What did you observe?")
rebuilt.student_message("ACTOR-B", "Anything else?")
deliveries = [
event
for event in rebuilt.store.read_all(
"t1", "c1", "pending-delivery-session", "plant_quality", "1.0.0"
)
if event.event_type == EventType.PRIVATE_SIGNAL_DELIVERED
and event.payload.get("expansion_kind") == "cross_role_transmission"
and event.payload.get("source_event_id")
== "msg:t1:c1:pending-delivery-session:1:1"
]
assert len(deliveries) == 1
assert deliveries[0].turn == evaluated.turn + rule.delay_turns
assert deliveries[0].parent_event_ids == [
evaluated.event_id,
"msg:t1:c1:pending-delivery-session:1:1",
]
def test_session_seed_is_recorded_and_none_adopts_it_on_rebuild(tmp_path):
"""Replacing a recorded seed with a default during reconstruction must fail."""
cfg = _test_cfg(tmp_path)
ScenarioStore(tmp_path / "data").save(build_package(), tenant_id="t1")
first = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"seeded-session",
session_seed=8_675_309,
provider=MockProvider(),
)
first.start_default()
rebuilt_provider = MockProvider()
rebuilt = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"seeded-session",
session_seed=None,
provider=rebuilt_provider,
)
assert rebuilt_provider.requests == []
rebuilt.start_default()
starts = [
event
for event in rebuilt.store.read_all(
"t1", "c1", "seeded-session", "plant_quality", "1.0.0"
)
if event.event_type == EventType.SESSION_STARTED
]
assert len(starts) == 1
assert starts[0].payload == {
"scenario_id": "plant_quality",
"scenario_version": "1.0.0",
"session_seed": 8_675_309,
}
assert starts[0].rng_seed == 8_675_309
def test_rebuilt_runtime_refuses_seed_that_differs_from_ledger(tmp_path):
"""Permitting a caller seed to overwrite session identity must fail."""
cfg = _test_cfg(tmp_path)
ScenarioStore(tmp_path / "data").save(build_package(), tenant_id="t1")
first = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"seed-mismatch-session",
session_seed=42,
provider=MockProvider(),
)
first.start_default()
with pytest.raises(ValueError, match="does not match recorded session seed"):
build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"seed-mismatch-session",
session_seed=43,
provider=MockProvider(),
)
def test_rebuilt_runtime_refuses_scenario_version_that_differs_from_ledger(tmp_path):
cfg = _test_cfg(tmp_path)
scenario_store = ScenarioStore(tmp_path / "data")
scenario_store.save(build_package(), tenant_id="t1")
next_version = build_package()
next_version.manifest.version = "1.0.1"
scenario_store.save(next_version, tenant_id="t1")
first = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"scenario-mismatch-session",
session_seed=42,
provider=MockProvider(),
)
first.start_default()
with pytest.raises(ValueError, match="does not match recorded scenario identity"):
build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.1",
"scenario-mismatch-session",
session_seed=42,
provider=MockProvider(),
)
def test_rebuilt_runtime_refuses_scenario_id_that_differs_from_ledger(tmp_path):
cfg = _test_cfg(tmp_path)
scenario_store = ScenarioStore(tmp_path / "data")
scenario_store.save(build_package(), tenant_id="t1")
other_scenario = build_package()
other_scenario.manifest.scenario_id = "plant_quality_alt"
scenario_store.save(other_scenario, tenant_id="t1")
first = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"scenario-id-mismatch-session",
session_seed=42,
provider=MockProvider(),
)
first.start_default()
with pytest.raises(ValueError, match="does not match recorded scenario identity"):
build_runtime(
cfg,
"t1",
"c1",
"plant_quality_alt",
"1.0.0",
"scenario-id-mismatch-session",
session_seed=42,
provider=MockProvider(),
)
def test_rebuilt_runtime_derives_pending_interview_from_ledger_tail(tmp_path):
class FailingProvider(MockProvider):
def complete(self, req):
raise RuntimeError("provider interrupted after student message")
cfg = _test_cfg(tmp_path)
ScenarioStore(tmp_path / "data").save(build_package(), tenant_id="t1")
interrupted = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=FailingProvider(),
)
interrupted.start_default()
with pytest.raises(RuntimeError, match="provider interrupted"):
interrupted.student_message("ACTOR-A", "question 1")
rebuilt = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=MockProvider(),
)
assert rebuilt.symbol_env["interview_count"] == 1
assert rebuilt.symbol_env["has_pending_interview"] is True
def test_runtime_mints_disclosure_id_from_the_session_sequence(runtime):
disclosable = next(
fact
for fact in build_package().private_facts
if fact.governance.owner_role == "ACTOR-B"
and fact.disclosure_class == "disclosable"
)
runtime.provider.force_response = disclosable.text
runtime.start_default()
runtime.student_message("ACTOR-B", "What did the sample show?")
disclosure = next(
event
for event in runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if event.event_type == EventType.CONVERSATION_DISCLOSURE
)
assert disclosure.event_id == "disclosure:t1:c1:s1:1:3"
def test_runtime_mints_compaction_id_from_the_session_sequence(tmp_path):
cfg = _test_cfg(tmp_path)
# This budget is calibrated to the rendered actor system prompt: it must
# let the first turn through (post-compaction context <= budget) while
# still tripping the two compaction gates on the second turn. The test's
# subject is compaction-id MINTING, not token arithmetic — if a prompt
# change breaks it, re-tune the literal (or better: make compaction
# deterministic and assert only the id shape).
cfg.parameters.actor_memory_budget_tokens = 360
ScenarioStore(tmp_path / "data").save(build_package(), tenant_id="t1")
runtime = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"s1",
session_seed=42,
provider=MockProvider(),
)
runtime.start_default()
runtime.student_message("ACTOR-A", "first")
runtime.student_message("ACTOR-A", "What changed?")
compaction = next(
event
for event in runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if event.event_type == EventType.COMPACTION_WRITTEN
)
assert compaction.event_id == "compaction:t1:c1:s1:ACTOR-A:3"
def test_router_never_reads_payload_body(runtime):
runtime.start_default()
assert (
runtime.route_probe(sender="STUDENT", recipient="ACTOR-A", payload_ref=None)
== "ACTOR-A"
)
def test_shock_fires_at_scheduled_turn(runtime):
runtime.start_default()
for i in range(5):
runtime.student_message("ACTOR-A", f"q{i}")
shocks = [
e
for e in runtime.store.read_all("t1", "c1", "s1", "plant_quality", "1.0.0")
if e.event_type == EventType.SHOCK_OCCURRED
]
assert len(shocks) == 1
def test_actor_reply_uses_scope_derived_student_role(tmp_path):
package_json = json.dumps(build_package().model_dump(mode="json")).replace(
'"STUDENT"', '"LEARNER"'
)
package = ScenarioPackage.model_validate_json(package_json)
cfg = _test_cfg(tmp_path)
ScenarioStore(tmp_path / "data").save(package, tenant_id="t1")
runtime = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"learner-session",
session_seed=42,
provider=MockProvider(),
)
runtime.start_default()
runtime.student_message("ACTOR-A", "What changed?")
reply = next(
event
for event in runtime.store.read_all(
"t1", "c1", "learner-session", "plant_quality", "1.0.0"
)
if event.event_type == EventType.MESSAGE_SENT
and event.payload["sender_role"] == "ACTOR-A"
)
assert reply.payload["recipient_role"] == "LEARNER"
assert ("participant", "LEARNER") in {
(principal.kind, principal.actor_id) for principal in reply.visibility
}
def test_transmission_uses_model_routing_from_injected_config(tmp_path):
package = build_package()
rule = package.transmission_rules[0]
rule.base_probability = 1.0
rule.modifiers = {}
rule.delay_turns = 0
package.manifest.rule_hashes[rule.rule_id] = transmission_rule_hash(rule)
cfg = _test_cfg(tmp_path)
cfg.models.purpose_overrides["transmission_transform"] = (
"custom-transformation-model"
)
provider = MockProvider()
ScenarioStore(tmp_path / "data").save(package, tenant_id="t1")
runtime = build_runtime(
cfg,
"t1",
"c1",
"plant_quality",
"1.0.0",
"config-session",
session_seed=42,
provider=provider,
)
runtime.start_default()
runtime.student_message("ACTOR-A", "I think the resin change caused it.")
transformation_request = next(
request
for request in provider.requests
if request.purpose == "transmission_transform"
)
assert transformation_request.model == "custom-transformation-model"
events = runtime.store.read_all(
"t1", "c1", "config-session", "plant_quality", "1.0.0"
)
delivery = next(
event
for event in events
if event.event_type == EventType.PRIVATE_SIGNAL_DELIVERED
and event.payload.get("expansion_kind") == "cross_role_transmission"
)
usage = next(
event
for event in events
if event.event_type == EventType.PROVIDER_USAGE
and event.parent_event_ids == [delivery.event_id]
)
assert usage.payload["purpose"] == "transmission_transform"
assert usage.payload["model"] == "custom-transformation-model"
|