Files
gamedev-the-steward/tests/simulation_state_serialization_test.gd
T
2026-07-11 19:58:47 +02:00

569 lines
19 KiB
GDScript

extends SceneTree
var failures: Array[String] = []
func _initialize() -> void:
call_deferred("_run")
func _run() -> void:
await _test_deterministic_continuation()
await _test_resource_state_round_trip()
_test_legacy_npc_migration()
_test_legacy_resource_migration()
_test_legacy_world_storage_migration()
_test_previous_world_event_migration()
_test_previous_world_relationship_migration()
_test_previous_world_knowledge_migration()
_test_previous_world_provenance_migration()
_test_relationship_schema_rejection()
_test_schema_rejection()
if failures.is_empty():
print("[TEST] Simulation state serialization passed")
quit(0)
return
for failure in failures:
push_error("[TEST] " + failure)
quit(1)
func _test_deterministic_continuation() -> void:
var uninterrupted := _create_manager(91234)
_advance_scenario(uninterrupted, 24)
uninterrupted.clock.advance(0.5)
_advance_scenario(uninterrupted, 24)
var uninterrupted_checksum: String = uninterrupted.get_state_checksum()
var before_save := _create_manager(91234)
_advance_scenario(before_save, 24)
before_save.clock.advance(0.5)
var saved_json: String = before_save.serialize_state()
var restored := _create_manager(1)
_check(
restored.restore_state_from_json(saved_json),
"A valid versioned state should restore into a fresh manager"
)
_check(restored.tick_count == 24, "Tick count should survive restoration")
_check(
is_equal_approx(restored.clock.accumulator, 0.5),
"Clock remainder should survive restoration"
)
_advance_scenario(restored, 24)
var restored_checksum: String = restored.get_state_checksum()
if restored_checksum != uninterrupted_checksum:
print(
"[TEST] uninterrupted=",
uninterrupted.serialize_state(),
"\n[TEST] restored=",
restored.serialize_state()
)
_check(
restored_checksum == uninterrupted_checksum,
"Restored simulation should match uninterrupted deterministic continuation"
)
uninterrupted.free()
before_save.free()
restored.free()
func _test_resource_state_round_trip() -> void:
var resource: ResourceNode = load("res://world/resource_nodes/ResourceNode.tscn").instantiate()
resource.node_id = &"SerializationTestBerry"
resource.initial_amount = 9.0
resource.yield_per_action = 2.0
root.add_child(resource)
await process_frame
var manager := _create_manager(77)
_check(
manager.register_resource_node(resource),
"Resource presentation should bind to simulation authority"
)
var resource_state: ResourceStateRecord = manager.get_resource_state(resource.node_id)
_check(resource_state.reserve(42), "Resource should accept the test reservation")
resource_state.extract()
var saved_json: String = manager.serialize_state()
resource.free()
_check(
is_equal_approx(resource_state.get_amount_remaining(), 7.0),
"Resource state should survive without its presentation node"
)
resource_state.extract(5.0)
resource_state.release(42)
resource_state.set_enabled(false)
_check(
manager.restore_state_from_json(saved_json),
"Unloaded resource state should restore with the simulation record"
)
resource_state = manager.get_resource_state(&"SerializationTestBerry")
_check(
is_equal_approx(resource_state.get_amount_remaining(), 7.0),
"Resource amount should round-trip"
)
_check(resource_state.get_reserved_by() == 42, "Resource reservation should round-trip")
_check(resource_state.is_enabled(), "Resource enabled state should round-trip")
var rebound: ResourceNode = load("res://world/resource_nodes/ResourceNode.tscn").instantiate()
rebound.node_id = &"SerializationTestBerry"
rebound.initial_amount = 999.0
root.add_child(rebound)
await process_frame
_check(
rebound.state == resource_state,
"Reloaded presentation should bind to the existing authoritative record"
)
_check(
is_equal_approx(rebound.get_amount_remaining(), 7.0),
"Reloaded presentation must not overwrite authoritative amount"
)
manager.free()
rebound.free()
func _test_schema_rejection() -> void:
var unsupported := JSON.stringify(
{"schema": SimulationStateRecord.SCHEMA_NAME, "schema_version": 999}
)
_check(
SimulationStateRecord.from_json(unsupported) == null,
"Unsupported schema versions should be rejected"
)
_check(SimulationStateRecord.from_json("[]") == null, "Non-record JSON should be rejected")
func _test_legacy_resource_migration() -> void:
var migrated := ResourceStateRecord.from_dictionary(
{
"schema_version": 1,
"node_id": "legacy_tree",
"amount_remaining": 6.0,
"reserved_by": 12,
"enabled": true
}
)
_check(migrated != null, "ResourceStateRecord v1 should migrate explicitly")
if migrated == null:
return
_check(
migrated.data["schema_version"] == ResourceStateRecord.SCHEMA_VERSION,
"Migrated resource state should use the current nested schema"
)
_check(
is_equal_approx(migrated.get_amount_remaining(), 6.0) and migrated.get_reserved_by() == 12,
"Resource migration should preserve mutable authority"
)
_check(
(
is_equal_approx(migrated.get_safety_risk(), 0.0)
and is_equal_approx(migrated.get_comfort_distance(), 18.0)
),
"Resource migration should default discovery metadata"
)
func _test_legacy_npc_migration() -> void:
var npc := SimNPC.new(88, "LegacyNPC", SimulationIds.PROFESSION_FARMER, 5.0, 5.0)
var legacy_data := NPCStateRecord.capture(npc).to_dictionary()
legacy_data["schema_version"] = NPCStateRecord.LEGACY_SCHEMA_VERSION
legacy_data.erase("travel_target_position")
legacy_data.erase("has_travel_target")
var migrated := NPCStateRecord.from_dictionary(legacy_data)
_check(migrated != null, "NPCStateRecord v1 should migrate explicitly")
if migrated == null:
return
_check(
not bool(migrated.data["has_travel_target"]),
"Legacy NPC migration should not invent an active travel target"
)
func _test_legacy_world_storage_migration() -> void:
var manager := _create_manager(55)
var legacy_data: Dictionary = manager.create_state_record().to_dictionary()
legacy_data["schema_version"] = SimulationStateRecord.LEGACY_SCHEMA_VERSION
legacy_data.erase("storages")
var migrated := SimulationStateRecord.from_dictionary(legacy_data)
_check(migrated != null, "World schema v1 should migrate authored storage")
if migrated != null:
var migrated_storages := {}
for storage in migrated.storages:
migrated_storages[storage.get_storage_id()] = storage
var pantry: StorageStateRecord = migrated_storages.get(SimulationIds.STORAGE_VILLAGE_PANTRY)
var woodpile: StorageStateRecord = migrated_storages.get(
SimulationIds.STORAGE_VILLAGE_WOODPILE
)
_check(
(
pantry != null
and woodpile != null
and is_equal_approx(
pantry.get_amount(SimulationIds.RESOURCE_FOOD), manager.village.food
)
and is_equal_approx(
woodpile.get_amount(SimulationIds.RESOURCE_WOOD), manager.village.wood
)
),
"World migration should preserve legacy village resources in their storage"
)
manager.free()
func _test_previous_world_event_migration() -> void:
var manager := _create_manager(56)
var previous_data: Dictionary = manager.create_state_record().to_dictionary()
previous_data["schema_version"] = SimulationStateRecord.EVENT_LEGACY_SCHEMA_VERSION
previous_data.erase("economic_events")
previous_data["simulation"].erase("next_event_id")
var migrated := SimulationStateRecord.from_dictionary(previous_data)
_check(migrated != null, "World schema v2 should add an empty event stream")
if migrated != null:
_check(
migrated.economic_events.is_empty() and int(migrated.simulation["next_event_id"]) == 0,
"World v2 migration should initialize deterministic event identity"
)
manager.free()
func _test_previous_world_relationship_migration() -> void:
var manager := _create_manager(57)
var previous_data: Dictionary = manager.create_state_record().to_dictionary()
previous_data["schema_version"] = SimulationStateRecord.RELATIONSHIP_LEGACY_SCHEMA_VERSION
previous_data.erase("relationships")
previous_data.erase("event_knowledge")
for npc_data in previous_data["npcs"]:
npc_data["schema_version"] = NPCStateRecord.RELATIONSHIP_LEGACY_SCHEMA_VERSION
npc_data["familiarity"] = []
previous_data["npcs"][0]["familiarity"] = [{"id": 1, "score": 0.75}]
var migrated := SimulationStateRecord.from_dictionary(previous_data)
_check(migrated != null, "World schema v3 should migrate NPC familiarity into relationships")
if migrated != null:
_check(
(
migrated.relationships.size() == 1
and migrated.relationships[0].get_observer_id() == 0
and migrated.relationships[0].get_subject_id() == 1
and is_equal_approx(migrated.relationships[0].get_familiarity(), 0.75)
and is_equal_approx(
migrated.relationships[0].get_trust(), RelationshipStateRecord.NEUTRAL_TRUST
)
),
"World v3 migration should preserve familiarity and initialize neutral trust"
)
_check(
not migrated.npcs[0].data.has("familiarity"),
"World v3 migration should remove obsolete NPC-local familiarity data"
)
manager.free()
func _test_previous_world_knowledge_migration() -> void:
var manager := _create_manager(59)
var previous_data: Dictionary = manager.create_state_record().to_dictionary()
previous_data["schema_version"] = SimulationStateRecord.KNOWLEDGE_LEGACY_SCHEMA_VERSION
previous_data.erase("event_knowledge")
var deposit_event := EconomicEventRecord.create(
0,
SimulationIds.EVENT_STORAGE_DEPOSITED,
12,
1,
SimulationIds.npc_inventory_id(1),
SimulationIds.STORAGE_VILLAGE_PANTRY,
SimulationIds.RESOURCE_FOOD,
2.0
)
previous_data["economic_events"] = [deposit_event.to_dictionary()]
previous_data["simulation"]["next_event_id"] = 1
previous_data["relationships"] = [
RelationshipStateRecord.create(0, 1, 0.5, 0.65, 0).to_dictionary()
]
var migrated := SimulationStateRecord.from_dictionary(previous_data)
_check(migrated != null, "World schema v4 should migrate causal facts into NPC knowledge")
if migrated != null:
_check(
(
migrated.event_knowledge.size() == 1
and migrated.event_knowledge[0].get_knower_id() == 0
and migrated.event_knowledge[0].get_event_id() == 0
and (
migrated.event_knowledge[0].get_acquisition_method()
== SimulationIds.KNOWLEDGE_ACQUISITION_LEGACY
)
),
"World v4 migration should preserve the fact implied by a relationship cause"
)
manager.free()
func _test_previous_world_provenance_migration() -> void:
var manager := _create_manager(60)
var previous_data: Dictionary = manager.create_state_record().to_dictionary()
previous_data["schema_version"] = SimulationStateRecord.PREVIOUS_SCHEMA_VERSION
var deposit_event := EconomicEventRecord.create(
0,
SimulationIds.EVENT_STORAGE_DEPOSITED,
12,
1,
SimulationIds.npc_inventory_id(1),
SimulationIds.STORAGE_VILLAGE_PANTRY,
SimulationIds.RESOURCE_FOOD,
2.0
)
previous_data["economic_events"] = [deposit_event.to_dictionary()]
previous_data["simulation"]["next_event_id"] = 1
previous_data["event_knowledge"] = [
{"schema_version": 1, "knower_id": 0, "event_id": 0},
{"schema_version": 1, "knower_id": 1, "event_id": 0},
]
previous_data["relationships"] = [
RelationshipStateRecord.create(0, 1, 0.5, 0.65, 0).to_dictionary()
]
var migrated := SimulationStateRecord.from_dictionary(previous_data)
_check(migrated != null, "World schema v5 should add honest acquisition provenance")
if migrated != null:
var observer_record: KnownEventStateRecord
var actor_record: KnownEventStateRecord
for known_event in migrated.event_knowledge:
if known_event.get_knower_id() == 0:
observer_record = known_event
elif known_event.get_knower_id() == 1:
actor_record = known_event
_check(
(
actor_record != null
and (
actor_record.get_acquisition_method()
== SimulationIds.KNOWLEDGE_ACQUISITION_PERFORMED
)
),
"World v5 migration can safely identify an actor's own completed fact"
)
_check(
(
observer_record != null
and (
observer_record.get_acquisition_method()
== SimulationIds.KNOWLEDGE_ACQUISITION_LEGACY
)
),
"World v5 migration must not invent witness or speaker provenance"
)
manager.free()
func _test_relationship_schema_rejection() -> void:
var manager := _create_manager(58)
var missing_cause_data: Dictionary = manager.create_state_record().to_dictionary()
missing_cause_data["relationships"] = [
RelationshipStateRecord.create(0, 1, 0.5, 0.65, 999).to_dictionary()
]
_check(
SimulationStateRecord.from_dictionary(missing_cause_data) == null,
"Relationship causes must reference an event in the same world record"
)
var duplicate_pair_data: Dictionary = manager.create_state_record().to_dictionary()
var relationship_data := RelationshipStateRecord.create(0, 1, 0.5).to_dictionary()
duplicate_pair_data["relationships"] = [relationship_data, relationship_data.duplicate(true)]
_check(
SimulationStateRecord.from_dictionary(duplicate_pair_data) == null,
"World state should reject duplicate directed relationship pairs"
)
var unknown_knowledge_data: Dictionary = manager.create_state_record().to_dictionary()
unknown_knowledge_data["event_knowledge"] = [
KnownEventStateRecord.create(0, 999).to_dictionary()
]
_check(
SimulationStateRecord.from_dictionary(unknown_knowledge_data) == null,
"Known-event records must reference an event in the same world record"
)
var duplicate_knowledge_data: Dictionary = manager.create_state_record().to_dictionary()
var event := EconomicEventRecord.create(
0,
SimulationIds.EVENT_STORAGE_DEPOSITED,
1,
0,
SimulationIds.npc_inventory_id(0),
SimulationIds.STORAGE_VILLAGE_PANTRY,
SimulationIds.RESOURCE_FOOD,
1.0
)
duplicate_knowledge_data["economic_events"] = [event.to_dictionary()]
duplicate_knowledge_data["simulation"]["next_event_id"] = 1
var known_event_data := KnownEventStateRecord.create(0, 0).to_dictionary()
duplicate_knowledge_data["event_knowledge"] = [
known_event_data, known_event_data.duplicate(true)
]
_check(
SimulationStateRecord.from_dictionary(duplicate_knowledge_data) == null,
"World state should reject duplicate NPC knowledge pairs"
)
var wrong_subject_cause_data: Dictionary = manager.create_state_record().to_dictionary()
var unrelated_deposit := EconomicEventRecord.create(
0,
SimulationIds.EVENT_STORAGE_DEPOSITED,
1,
2,
SimulationIds.npc_inventory_id(2),
SimulationIds.STORAGE_VILLAGE_PANTRY,
SimulationIds.RESOURCE_FOOD,
1.0
)
wrong_subject_cause_data["economic_events"] = [unrelated_deposit.to_dictionary()]
wrong_subject_cause_data["simulation"]["next_event_id"] = 1
wrong_subject_cause_data["event_knowledge"] = [
KnownEventStateRecord.create(0, 0).to_dictionary()
]
wrong_subject_cause_data["relationships"] = [
RelationshipStateRecord.create(0, 1, 0.5, 0.65, 0).to_dictionary()
]
_check(
SimulationStateRecord.from_dictionary(wrong_subject_cause_data) == null,
"A trust cause must be a known food deposit performed by the relationship subject"
)
var nonpositive_cause_data: Dictionary = manager.create_state_record().to_dictionary()
var nonpositive_deposit := EconomicEventRecord.create(
0,
SimulationIds.EVENT_STORAGE_DEPOSITED,
1,
1,
SimulationIds.npc_inventory_id(1),
SimulationIds.STORAGE_VILLAGE_PANTRY,
SimulationIds.RESOURCE_FOOD,
0.0
)
nonpositive_cause_data["economic_events"] = [nonpositive_deposit.to_dictionary()]
nonpositive_cause_data["simulation"]["next_event_id"] = 1
nonpositive_cause_data["event_knowledge"] = [KnownEventStateRecord.create(0, 0).to_dictionary()]
nonpositive_cause_data["relationships"] = [
RelationshipStateRecord.create(0, 1, 0.5, 0.65, 0).to_dictionary()
]
_check(
SimulationStateRecord.from_dictionary(nonpositive_cause_data) == null,
"A trust cause must describe a successful positive food deposit"
)
var provenance_event := EconomicEventRecord.create(
0,
SimulationIds.EVENT_STORAGE_DEPOSITED,
1,
0,
SimulationIds.npc_inventory_id(0),
SimulationIds.STORAGE_VILLAGE_PANTRY,
SimulationIds.RESOURCE_FOOD,
1.0
)
var missing_source_data: Dictionary = manager.create_state_record().to_dictionary()
missing_source_data["economic_events"] = [provenance_event.to_dictionary()]
missing_source_data["simulation"]["next_event_id"] = 1
missing_source_data["event_knowledge"] = [
(
KnownEventStateRecord
. create(1, 0, SimulationIds.KNOWLEDGE_ACQUISITION_COMMUNICATED, 2)
. to_dictionary()
)
]
_check(
SimulationStateRecord.from_dictionary(missing_source_data) == null,
"Communicated knowledge must reference a source who knows the same event"
)
var wrong_actor_data: Dictionary = manager.create_state_record().to_dictionary()
wrong_actor_data["economic_events"] = [provenance_event.to_dictionary()]
wrong_actor_data["simulation"]["next_event_id"] = 1
wrong_actor_data["event_knowledge"] = [
(
KnownEventStateRecord
. create(1, 0, SimulationIds.KNOWLEDGE_ACQUISITION_PERFORMED)
. to_dictionary()
)
]
_check(
SimulationStateRecord.from_dictionary(wrong_actor_data) == null,
"Performed provenance must belong to the event actor"
)
var relayed_source_data: Dictionary = manager.create_state_record().to_dictionary()
relayed_source_data["economic_events"] = [provenance_event.to_dictionary()]
relayed_source_data["simulation"]["next_event_id"] = 1
relayed_source_data["event_knowledge"] = [
(
KnownEventStateRecord
. create(1, 0, SimulationIds.KNOWLEDGE_ACQUISITION_COMMUNICATED, 2)
. to_dictionary()
),
(
KnownEventStateRecord
. create(2, 0, SimulationIds.KNOWLEDGE_ACQUISITION_COMMUNICATED, 0)
. to_dictionary()
),
(
KnownEventStateRecord
. create(0, 0, SimulationIds.KNOWLEDGE_ACQUISITION_PERFORMED)
. to_dictionary()
),
]
_check(
SimulationStateRecord.from_dictionary(relayed_source_data) == null,
"Communicated facts must not form a second relay hop in this phase"
)
var order_independent_data: Dictionary = manager.create_state_record().to_dictionary()
order_independent_data["economic_events"] = [provenance_event.to_dictionary()]
order_independent_data["simulation"]["next_event_id"] = 1
order_independent_data["event_knowledge"] = [
(
KnownEventStateRecord
. create(1, 0, SimulationIds.KNOWLEDGE_ACQUISITION_COMMUNICATED, 2)
. to_dictionary()
),
(
KnownEventStateRecord
. create(0, 0, SimulationIds.KNOWLEDGE_ACQUISITION_PERFORMED)
. to_dictionary()
),
(
KnownEventStateRecord
. create(2, 0, SimulationIds.KNOWLEDGE_ACQUISITION_WITNESSED)
. to_dictionary()
),
]
_check(
SimulationStateRecord.from_dictionary(order_independent_data) != null,
"Provenance validation should not depend on knowledge array ordering"
)
manager.free()
func _create_manager(seed_value: int) -> Node:
var manager: Node = load("res://simulation/SimulationManager.gd").new()
manager.simulation_seed = seed_value
manager.debug_logs = false
root.add_child(manager)
manager.set_process(false)
return manager
func _advance_scenario(manager: Node, steps: int) -> void:
for step in steps:
manager.simulate_tick()
for npc in manager.npcs:
manager.get_wander_offset(npc.id)
if npc.task_state == SimNPC.TASK_STATE_TRAVELING:
manager.notify_npc_arrived(npc.id)
func _check(condition: bool, message: String) -> void:
if not condition:
failures.append(message)