-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathengine.py
More file actions
2293 lines (1973 loc) · 84.9 KB
/
engine.py
File metadata and controls
2293 lines (1973 loc) · 84.9 KB
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main simulation engine orchestrator.
Coordinates the simulation loop: exposure, reasoning, propagation,
and aggregation across timesteps until stopping conditions are met.
Implements Phase 0 redesign:
- Two-pass reasoning (Pass 1: role-play, Pass 2: classification)
- Conviction-gated sharing (very_uncertain agents don't share)
- Conviction-based flip resistance
- Memory traces (sliding window of 3 per agent)
- Semantic peer influence (public_statement + sentiment, not position labels)
- Rate limiter integration (replaces hardcoded semaphore)
"""
import json
import logging
import queue
import random
import sqlite3
import threading
import time
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
from ..core.models import (
PopulationSpec,
ScenarioSpec,
AgentState,
ConvictionLevel,
CONVICTION_MAP,
MemoryEntry,
PeerOpinion,
ReasoningContext,
ReasoningResponse,
SimulationEvent,
SimulationEventType,
SimulationRunConfig,
TimestepSummary,
float_to_conviction,
)
from ..core.rate_limiter import DualRateLimiter
from ..population.persona import PersonaConfig
from ..storage import open_study_db
from .progress import SimulationProgress
from .state import StateManager
from .persona import generate_persona
from .reasoning import (
batch_reason_agents_async,
create_reasoning_context,
)
from .conversation import (
collect_conversation_requests,
prioritize_and_resolve_conflicts,
execute_conversation_batch_async,
ConversationResult,
)
from .propagation import (
apply_seed_exposures,
apply_timeline_exposures,
propagate_through_network,
)
from .stopping import evaluate_stopping_conditions
from ..utils.callbacks import TimestepProgressCallback
from ..utils.resource_governor import ResourceGovernor
from .aggregation import (
compute_timestep_summary,
compute_final_aggregates,
compute_outcome_distributions,
compute_timeline_aggregates,
compute_conversation_stats,
compute_most_impactful_conversations,
export_elaborations_csv,
)
logger = logging.getLogger(__name__)
# Conviction thresholds derived from the canonical model
_FIRM_CONVICTION = CONVICTION_MAP[ConvictionLevel.FIRM]
_MODERATE_CONVICTION = CONVICTION_MAP[ConvictionLevel.MODERATE]
_SHARING_CONVICTION_THRESHOLD = CONVICTION_MAP[ConvictionLevel.VERY_UNCERTAIN]
_CONVICTION_DECAY_RATE = 0.05
_BOUNDED_CONFIDENCE_RHO = 0.35
_PRIVATE_ADJUSTMENT_RHO = 0.12
_PRIVATE_FLIP_CONVICTION = CONVICTION_MAP[ConvictionLevel.FIRM]
class _StateTimelineAdapter:
"""Timeline adapter that persists events into StateManager timeline table."""
def __init__(self, state_manager: StateManager):
self.state_manager = state_manager
def log_event(self, event: SimulationEvent) -> None:
self.state_manager.log_event(event)
def flush(self) -> None:
return
def close(self) -> None:
return
class SimulationSummary:
"""Summary of a completed simulation run."""
def __init__(
self,
scenario_name: str,
run_id: str | None,
population_size: int,
total_timesteps: int,
stopped_reason: str | None,
total_reasoning_calls: int,
total_exposures: int,
final_exposure_rate: float,
outcome_distributions: dict[str, Any],
runtime_seconds: float,
model_used: str,
completed_at: datetime,
):
self.scenario_name = scenario_name
self.run_id = run_id
self.population_size = population_size
self.total_timesteps = total_timesteps
self.stopped_reason = stopped_reason
self.total_reasoning_calls = total_reasoning_calls
self.total_exposures = total_exposures
self.final_exposure_rate = final_exposure_rate
self.outcome_distributions = outcome_distributions
self.runtime_seconds = runtime_seconds
self.model_used = model_used
self.completed_at = completed_at
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary."""
return {
"scenario_name": self.scenario_name,
"run_id": self.run_id,
"population_size": self.population_size,
"total_timesteps": self.total_timesteps,
"stopped_reason": self.stopped_reason,
"total_reasoning_calls": self.total_reasoning_calls,
"total_exposures": self.total_exposures,
"final_exposure_rate": self.final_exposure_rate,
"outcome_distributions": self.outcome_distributions,
"runtime_seconds": self.runtime_seconds,
"model_used": self.model_used,
"completed_at": self.completed_at.isoformat(),
}
class SimulationEngine:
"""Main orchestrator for simulation execution.
Coordinates the simulation loop: exposure, reasoning, propagation,
and aggregation across timesteps.
"""
def __init__(
self,
scenario: ScenarioSpec,
population_spec: PopulationSpec,
agents: list[dict[str, Any]],
network: dict[str, Any],
config: SimulationRunConfig,
persona_config: PersonaConfig | None = None,
rate_limiter: DualRateLimiter | None = None,
chunk_size: int = 50,
state_db_path: Path | str | None = None,
run_id: str | None = None,
checkpoint_every_chunks: int = 1,
retention_lite: bool = False,
writer_queue_size: int = 256,
db_write_batch_size: int = 100,
resource_governor: ResourceGovernor | None = None,
):
"""Initialize simulation engine.
Args:
scenario: Scenario specification
population_spec: Population specification
agents: List of agent dictionaries
network: Network data
config: Simulation run configuration
persona_config: Optional PersonaConfig for embodied persona rendering
rate_limiter: Optional DualRateLimiter for API pacing (pivotal + routine)
chunk_size: Number of agents per reasoning chunk for checkpointing
"""
self.scenario = scenario
self.population_spec = population_spec
self.agents = agents
self.network = network
self.config = config
self.persona_config = persona_config
self.rate_limiter = rate_limiter
self.chunk_size = chunk_size # updated below after concurrency is resolved
self.run_id = run_id or f"run_{uuid.uuid4().hex[:12]}"
self.checkpoint_every_chunks = max(1, checkpoint_every_chunks)
self.retention_lite = retention_lite
self.writer_queue_size = max(1, writer_queue_size)
self.db_write_batch_size = max(1, db_write_batch_size)
self.resource_governor = resource_governor
# Auto-derive from rate limiter RPM, or use explicit override
if config.max_concurrent is not None:
self.reasoning_max_concurrency = config.max_concurrent
elif rate_limiter:
self.reasoning_max_concurrency = rate_limiter.pivotal.max_safe_concurrent
else:
self.reasoning_max_concurrency = 50
# Auto-size chunk_size to match concurrency when using the default.
# Small explicit chunk sizes (for fine-grained checkpointing) are respected.
if chunk_size == 50 and self.chunk_size < self.reasoning_max_concurrency:
self.chunk_size = self.reasoning_max_concurrency
logger.info(
f"[ENGINE] Auto-sized chunk_size to {self.chunk_size} "
f"to match concurrency"
)
self._last_guardrail_timestep = -1
# Build agent map for quick lookup
self.agent_map = {a.get("_id", str(i)): a for i, a in enumerate(agents)}
# Pre-build agent name lookup for peer reference resolution
self._agent_names: dict[str, str] = {
aid: a.get("first_name", "")
for aid, a in self.agent_map.items()
if a.get("first_name")
}
# Build adjacency list for O(1) neighbor lookups (both directions)
self.adjacency: dict[str, list[tuple[str, dict]]] = {}
for edge in network.get("edges", []):
src = edge.get("source")
tgt = edge.get("target")
if src is not None and tgt is not None:
self.adjacency.setdefault(src, []).append((tgt, edge))
self.adjacency.setdefault(tgt, []).append((src, edge))
# Initialize RNG
seed = config.random_seed
if seed is None:
seed = random.randint(0, 2**31 - 1)
self.rng = random.Random(seed)
self.seed = seed
# Create output directory
self.output_dir = Path(config.output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
# Initialize state manager
state_db_file = (
Path(state_db_path) if state_db_path else self.output_dir / "study.db"
)
self.state_manager = StateManager(
state_db_file,
agents,
run_id=self.run_id,
)
self.study_db = open_study_db(state_db_file)
# Initialize timeline manager
self.timeline = _StateTimelineAdapter(self.state_manager)
# Pre-generate personas for all agents
# Extract decision-relevant attributes from outcome config (trait salience)
decision_attrs = (
scenario.outcomes.decision_relevant_attributes
if hasattr(scenario.outcomes, "decision_relevant_attributes")
else None
)
self._personas: dict[str, str] = {}
for i, agent in enumerate(agents):
agent_id = agent.get("_id", str(i))
self._personas[agent_id] = generate_persona(
agent,
population_spec,
persona_config=persona_config,
decision_relevant_attributes=decision_attrs or None,
)
# Main categorical outcome used as the canonical behavioral position.
categorical = [
o
for o in scenario.outcomes.suggested_outcomes
if getattr(o.type, "value", str(o.type)) == "categorical"
]
required = [o for o in categorical if o.required]
primary = required[0] if required else (categorical[0] if categorical else None)
self._primary_position_outcome = primary.name if primary else None
self._primary_position_options = (
primary.options if primary and primary.options else []
)
self._primary_option_friction: dict[str, float] = {}
if primary and getattr(primary, "option_friction", None):
for option, score in primary.option_friction.items():
try:
self._primary_option_friction[str(option)] = max(
0.0, min(1.0, float(score))
)
except (TypeError, ValueError):
continue
self._private_anchor_position = self._infer_private_anchor_position(
self._primary_position_options
)
# Tracking variables
self.recent_summaries: list[TimestepSummary] = []
self.total_reasoning_calls = 0
self.total_exposures = 0
# Timeline state (active event for current timestep, if any)
self._active_timeline_event: Any = None
# Token usage tracking
self.pivotal_input_tokens = 0
self.pivotal_output_tokens = 0
self.routine_input_tokens = 0
self.routine_output_tokens = 0
# Progress callback
self._on_progress: TimestepProgressCallback | None = None
# Live progress state (thread-safe, for CLI display)
self._progress: SimulationProgress | None = None
self._summary_interval: int = 50
def set_progress_callback(self, callback: TimestepProgressCallback) -> None:
"""Set progress callback.
Args:
callback: Function(timestep, max_timesteps, status)
"""
self._on_progress = callback
def set_progress_state(self, progress: SimulationProgress) -> None:
"""Set shared progress state for live display.
Args:
progress: Thread-safe SimulationProgress instance
"""
self._progress = progress
def _apply_runtime_guardrails(self, timestep: int) -> None:
"""Downshift runtime knobs when process memory nears configured budget."""
if (
self.resource_governor is None
or self.resource_governor.resource_mode != "auto"
):
return
ratio = self.resource_governor.memory_pressure_ratio()
if ratio < 0.85:
return
factor = 0.5 if ratio >= 0.98 else 0.75
old_concurrency = self.reasoning_max_concurrency
old_batch = self.db_write_batch_size
old_queue = self.writer_queue_size
self.reasoning_max_concurrency = self.resource_governor.downshift_int(
self.reasoning_max_concurrency, factor=factor, minimum=1
)
self.db_write_batch_size = self.resource_governor.downshift_int(
self.db_write_batch_size, factor=factor, minimum=1
)
self.writer_queue_size = self.resource_governor.downshift_int(
self.writer_queue_size, factor=factor, minimum=4
)
changed = (
old_concurrency != self.reasoning_max_concurrency
or old_batch != self.db_write_batch_size
or old_queue != self.writer_queue_size
)
if changed and timestep != self._last_guardrail_timestep:
self._last_guardrail_timestep = timestep
logger.warning(
"[RESOURCE] Memory pressure %.2fx budget; "
"reasoning_concurrency %d->%d, writer_batch %d->%d, writer_queue %d->%d",
ratio,
old_concurrency,
self.reasoning_max_concurrency,
old_batch,
self.db_write_batch_size,
old_queue,
self.writer_queue_size,
)
def _report_progress(self, timestep: int, status: str) -> None:
"""Report progress to callback."""
if self._on_progress:
self._on_progress(
timestep,
self.scenario.simulation.max_timesteps,
status,
)
def _log_verbose_summary(self, snap: dict) -> None:
"""Log a periodic summary block with distribution and averages.
Args:
snap: Snapshot dict from SimulationProgress.snapshot()
"""
counts = snap.get("position_counts", {})
total = sum(counts.values()) or 1
avg_sent = snap.get("avg_sentiment")
avg_conv = snap.get("avg_conviction")
done = snap.get("agents_done", 0)
agents_total = snap.get("agents_total", 0)
lines = [
f"[SUMMARY] Timestep {snap['timestep']} | {done}/{agents_total} agents"
]
# Distribution sorted by count desc
for position, count in sorted(counts.items(), key=lambda x: -x[1]):
pct = count / total * 100
lines.append(f" {position}: {pct:.0f}% ({count})")
if avg_sent is not None:
lines.append(f" avg_sentiment: {avg_sent:.2f}")
if avg_conv is not None:
lines.append(f" avg_conviction: {avg_conv:.2f}")
logger.info("\n".join(lines))
def _get_resume_timestep(self) -> int:
"""Determine which timestep to start/resume from.
Returns:
Timestep number to begin execution at.
"""
checkpoint = self.state_manager.get_checkpoint_timestep()
if checkpoint is not None:
# Crashed mid-timestep — resume it
logger.info(f"Resuming from checkpoint timestep {checkpoint}")
return checkpoint
last_completed = self.state_manager.get_last_completed_timestep()
if last_completed >= 0:
# Completed some timesteps — start from next one
logger.info(f"Resuming from timestep {last_completed + 1}")
return last_completed + 1
return 0
def run(self) -> SimulationSummary:
"""Execute the full simulation.
Supports automatic resume: if the output directory contains a
study.db with partial progress, the engine picks up where
it left off.
Returns:
SimulationSummary with results
"""
start_time = time.time()
stopped_reason = None
final_timestep = 0
start_timestep = self._get_resume_timestep()
# Reload recent_summaries from DB on resume
if start_timestep > 0:
existing_summaries = self.state_manager.get_timestep_summaries()
self.recent_summaries = existing_summaries[-20:]
try:
for timestep in range(
start_timestep, self.scenario.simulation.max_timesteps
):
final_timestep = timestep
# Report progress
exposure_rate = self.state_manager.get_exposure_rate()
self._report_progress(timestep, f"Exposure: {exposure_rate:.1%}")
# Run timestep
summary = self._run_timestep(timestep)
self.recent_summaries.append(summary)
# Keep only last 20 summaries
if len(self.recent_summaries) > 20:
self.recent_summaries.pop(0)
# Check stopping conditions
should_stop, reason = evaluate_stopping_conditions(
timestep,
self.scenario.simulation,
self.state_manager,
self.recent_summaries,
)
if should_stop:
stopped_reason = reason
logger.info(f"Stopping at timestep {timestep}: {reason}")
break
except KeyboardInterrupt:
logger.warning("Simulation interrupted by user")
stopped_reason = "interrupted"
# Finalize and export
runtime = time.time() - start_time
try:
summary = self._finalize(final_timestep, stopped_reason, runtime)
self._export_results()
finally:
self.state_manager.close()
self.study_db.close()
return summary
def _run_timestep(self, timestep: int) -> TimestepSummary:
"""Execute one timestep of simulation.
Each phase (exposures, reasoning chunks, summary) has its own
transaction. This enables per-chunk checkpointing so that a crash
mid-timestep doesn't lose all progress.
Args:
timestep: Current timestep number
Returns:
TimestepSummary for this timestep
"""
logger.info(f"[TIMESTEP {timestep}] ========== STARTING ==========")
self.state_manager.mark_timestep_started(timestep)
return self._execute_timestep(timestep)
def _execute_timestep(self, timestep: int) -> TimestepSummary:
"""Execute the actual timestep logic — orchestrates sub-steps.
Args:
timestep: Current timestep number
Returns:
TimestepSummary for this timestep
"""
# 1. Exposures (seed + network) — own transaction
with self.state_manager.transaction():
total_new_exposures = self._apply_exposures(timestep)
self.total_exposures += total_new_exposures
# 2. Chunked reasoning — each chunk has its own transaction
agents_reasoned, state_changes, shares_occurred, reasoning_results = (
self._reason_agents(timestep)
)
# 2c. Execute conversations (if fidelity > low)
conversations_executed = 0
conversation_state_changes = 0
if self.config.fidelity != "low" and reasoning_results:
conv_results = self._execute_conversations(timestep, reasoning_results)
conversations_executed = len(conv_results)
conversation_state_changes = self._apply_conversation_overrides(
timestep, conv_results
)
if conversations_executed > 0:
logger.info(
f"[TIMESTEP {timestep}] Conversations: {conversations_executed} executed, "
f"{conversation_state_changes} state changes"
)
# 2e. Record social posts from agents who shared
posts_recorded = self._record_social_posts(timestep)
if posts_recorded > 0:
logger.info(
f"[TIMESTEP {timestep}] Social posts recorded: {posts_recorded}"
)
# 2d. Decay conviction for agents that did not reason this timestep.
# This adds attention-fade dynamics without forcing additional LLM calls.
with self.state_manager.transaction():
decayed = self.state_manager.apply_conviction_decay(
timestep=timestep,
decay_rate=_CONVICTION_DECAY_RATE,
sharing_threshold=_SHARING_CONVICTION_THRESHOLD,
firm_threshold=_FIRM_CONVICTION,
)
if decayed:
logger.info(
f"[TIMESTEP {timestep}] Conviction decay applied to {decayed} agents"
)
# 3. Compute and save timestep summary — own transaction
with self.state_manager.transaction():
summary = compute_timestep_summary(
timestep,
self.state_manager,
self.recent_summaries[-1] if self.recent_summaries else None,
)
summary.new_exposures = total_new_exposures
summary.agents_reasoned = agents_reasoned
summary.state_changes = state_changes
summary.shares_occurred = shares_occurred
self.state_manager.save_timestep_summary(summary)
self.state_manager.mark_timestep_completed(timestep)
# Flush timeline periodically
if timestep % 10 == 0:
self.timeline.flush()
return summary
def _apply_exposures(self, timestep: int) -> int:
"""Apply seed, timeline, and network exposures for this timestep.
Returns:
Total new exposures this timestep.
"""
new_seed = apply_seed_exposures(
timestep,
self.scenario,
self.agents,
self.state_manager,
self.rng,
)
logger.info(f"[TIMESTEP {timestep}] Seed exposures: {new_seed}")
# Apply timeline event exposures (if any timeline event fires this timestep)
new_timeline, active_event = apply_timeline_exposures(
timestep,
self.scenario,
self.agents,
self.state_manager,
self.rng,
)
if new_timeline > 0:
logger.info(f"[TIMESTEP {timestep}] Timeline exposures: {new_timeline}")
# Store active timeline event for prompt rendering
self._active_timeline_event = active_event
new_network = propagate_through_network(
timestep,
self.scenario,
self.agents,
self.network,
self.state_manager,
self.rng,
adjacency=self.adjacency,
agent_map=self.agent_map,
)
logger.info(f"[TIMESTEP {timestep}] Network exposures: {new_network}")
return new_seed + new_timeline + new_network
def _reason_agents(
self, timestep: int
) -> tuple[int, int, int, list[tuple[str, ReasoningResponse | None]]]:
"""Identify agents needing reasoning, run in chunks, commit per-chunk.
On resume, agents already processed this timestep are skipped.
Returns:
Tuple of (agents_reasoned, state_changes, shares_occurred, reasoning_results).
"""
self._apply_runtime_guardrails(timestep)
agents_to_reason = self.state_manager.get_agents_to_reason(
timestep,
self.config.multi_touch_threshold,
)
# Filter out agents already processed this timestep (resume support)
already_done = self.state_manager.get_agents_already_reasoned_this_timestep(
timestep
)
if already_done:
agents_to_reason = [a for a in agents_to_reason if a not in already_done]
logger.info(
f"[TIMESTEP {timestep}] Skipping {len(already_done)} already-processed agents"
)
logger.info(f"[TIMESTEP {timestep}] Agents to reason: {len(agents_to_reason)}")
# Update progress state for live display (even if 0 agents, so display updates)
if self._progress:
exposure_rate = self.state_manager.get_exposure_rate()
self._progress.begin_timestep(
timestep=timestep,
max_timesteps=self.scenario.simulation.max_timesteps,
agents_total=len(agents_to_reason),
exposure_rate=exposure_rate,
)
if not agents_to_reason:
return 0, 0, 0, []
# Create on_agent_done closure for progress tracking
def _on_agent_done(agent_id: str, result: Any) -> None:
if result is None:
return
if self._progress:
self._progress.record_agent_done(
position=result.position,
sentiment=result.sentiment,
conviction=result.conviction,
)
# Log verbose summary at intervals
if (
self._progress.agents_done % self._summary_interval == 0
and self._progress.agents_done > 0
):
self._log_verbose_summary(self._progress.snapshot())
# Build contexts and old states
contexts = []
old_states: dict[str, AgentState] = {}
for agent_id in agents_to_reason:
old_state = self.state_manager.get_agent_state(agent_id)
old_states[agent_id] = old_state
context = self._build_reasoning_context(agent_id, old_state, timestep)
contexts.append(context)
completed_chunks = self.study_db.get_completed_simulation_chunks(
self.run_id, timestep
)
totals = {"reasoned": 0, "changes": 0, "shares": 0}
all_reasoning_results: list[tuple[str, ReasoningResponse | None]] = []
work_queue: queue.Queue[tuple[int, list[tuple[str, Any]], bool] | object] = (
queue.Queue(maxsize=self.writer_queue_size)
)
sentinel = object()
writer_error: list[Exception] = []
def _writer_loop() -> None:
chunks_since_checkpoint = 0
pending_chunks: list[tuple[int, list[tuple[str, Any]], bool]] = []
def _flush_pending() -> None:
nonlocal chunks_since_checkpoint
if not pending_chunks:
return
with self.state_manager.transaction():
for chunk_index, chunk_results, _is_last_chunk in pending_chunks:
reasoned, changes, shares = self._process_reasoning_chunk(
timestep, chunk_results, old_states
)
totals["reasoned"] += reasoned
totals["changes"] += changes
totals["shares"] += shares
for chunk_index, _chunk_results, is_last_chunk in pending_chunks:
self.study_db.save_simulation_checkpoint(
run_id=self.run_id,
timestep=timestep,
chunk_index=chunk_index,
status="done",
)
chunks_since_checkpoint += 1
if (
chunks_since_checkpoint >= self.checkpoint_every_chunks
or is_last_chunk
):
self.study_db.set_run_metadata(
self.run_id,
"last_checkpoint",
f"{timestep}:{chunk_index}",
)
chunks_since_checkpoint = 0
pending_chunks.clear()
try:
while True:
item = work_queue.get()
try:
if item is sentinel:
_flush_pending()
break
chunk_index, chunk_results, is_last_chunk = item
if chunk_index in completed_chunks:
continue
pending_chunks.append(
(chunk_index, chunk_results, is_last_chunk)
)
if (
len(pending_chunks) >= self.db_write_batch_size
or is_last_chunk
):
_flush_pending()
finally:
work_queue.task_done()
except Exception as e: # pragma: no cover - surfaced to caller
writer_error.append(e)
writer_thread = threading.Thread(
target=_writer_loop,
name=f"sim-writer-{self.run_id}-{timestep}",
daemon=True,
)
writer_thread.start()
import asyncio
from ..core.providers import close_simulation_provider
async def _run_all_chunks():
try:
for chunk_start in range(0, len(contexts), self.chunk_size):
if writer_error:
break
self._apply_runtime_guardrails(timestep)
chunk_index = chunk_start // self.chunk_size
if chunk_index in completed_chunks:
logger.info(
f"[TIMESTEP {timestep}] Skipping completed chunk {chunk_index}"
)
continue
chunk_contexts = contexts[
chunk_start : chunk_start + self.chunk_size
]
reasoning_start = time.time()
chunk_results, chunk_usage = await batch_reason_agents_async(
chunk_contexts,
self.scenario,
self.config,
max_concurrency=self.reasoning_max_concurrency,
rate_limiter=self.rate_limiter,
on_agent_done=_on_agent_done,
)
reasoning_elapsed = time.time() - reasoning_start
self.total_reasoning_calls += len(chunk_results)
self.pivotal_input_tokens += chunk_usage.pivotal_input_tokens
self.pivotal_output_tokens += chunk_usage.pivotal_output_tokens
self.routine_input_tokens += chunk_usage.routine_input_tokens
self.routine_output_tokens += chunk_usage.routine_output_tokens
logger.info(
f"[TIMESTEP {timestep}] Chunk {chunk_start // self.chunk_size + 1}: "
f"{len(chunk_results)} agents in {reasoning_elapsed:.2f}s"
if chunk_results
else f"[TIMESTEP {timestep}] Chunk empty"
)
is_last_chunk = chunk_start + self.chunk_size >= len(contexts)
work_queue.put((chunk_index, chunk_results, is_last_chunk))
# Collect results for conversation phase
all_reasoning_results.extend(chunk_results)
finally:
await close_simulation_provider()
asyncio.run(_run_all_chunks())
work_queue.put(sentinel)
while work_queue.unfinished_tasks > 0:
if writer_error:
while True:
try:
work_queue.get_nowait()
work_queue.task_done()
except queue.Empty:
break
break
time.sleep(0.01)
work_queue.join()
writer_thread.join(timeout=1)
if writer_error:
raise writer_error[0]
return (
totals["reasoned"],
totals["changes"],
totals["shares"],
all_reasoning_results,
)
def _process_reasoning_chunk(
self,
timestep: int,
results: list[tuple[str, Any]],
old_states: dict[str, AgentState],
) -> tuple[int, int, int]:
"""Process a chunk of reasoning results and update agent states.
Returns:
Tuple of (agents_reasoned, state_changes, shares_occurred).
"""
agents_reasoned = 0
state_changes = 0
shares_occurred = 0
state_updates: list[tuple[str, AgentState]] = []
for agent_id, response in results:
if response is None:
continue
old_state = old_states[agent_id]
old_public_sentiment = (
old_state.public_sentiment
if old_state.public_sentiment is not None
else old_state.sentiment
)
old_public_conviction = (
old_state.public_conviction
if old_state.public_conviction is not None
else old_state.conviction
)
old_public_position = old_state.public_position or old_state.position
# Public state: what the agent says and propagates.
public_sentiment = response.sentiment
if old_public_sentiment is not None and response.sentiment is not None:
public_sentiment = old_public_sentiment + _BOUNDED_CONFIDENCE_RHO * (
response.sentiment - old_public_sentiment
)
public_sentiment = max(-1.0, min(1.0, public_sentiment))
public_conviction = response.conviction
if old_public_conviction is not None and response.conviction is not None:
public_conviction = old_public_conviction + _BOUNDED_CONFIDENCE_RHO * (
response.conviction - old_public_conviction
)
public_conviction = max(0.0, min(1.0, public_conviction))
public_will_share = response.will_share
public_position = response.position
if (
old_public_conviction is not None
and old_public_conviction >= _FIRM_CONVICTION
):
if (
old_public_position is not None
and response.position is not None
and old_public_position != response.position
):
new_conviction = (
public_conviction if public_conviction is not None else 0.0
)
if new_conviction < _MODERATE_CONVICTION:
logger.info(
f"[CONVICTION] Agent {agent_id}: public flip from {old_public_position} "
f"to {response.position} rejected (old conviction={float_to_conviction(old_public_conviction)}, "
f"new conviction={float_to_conviction(public_conviction)})"
)
public_position = old_public_position
if (
response.conviction is not None
and response.conviction <= _SHARING_CONVICTION_THRESHOLD
) or (
public_conviction is not None
and public_conviction <= _SHARING_CONVICTION_THRESHOLD
):
public_will_share = False
# Private state: what the agent is likely to actually do.
old_private_position = old_state.private_position or old_state.position
old_private_sentiment = (
old_state.private_sentiment
if old_state.private_sentiment is not None
else old_state.sentiment
)
old_private_conviction = (
old_state.private_conviction
if old_state.private_conviction is not None
else old_state.conviction
)
private_sentiment = public_sentiment
if old_private_sentiment is not None and public_sentiment is not None:
private_sentiment = old_private_sentiment + _PRIVATE_ADJUSTMENT_RHO * (
public_sentiment - old_private_sentiment
)
private_sentiment = max(-1.0, min(1.0, private_sentiment))
private_conviction = public_conviction
if old_private_conviction is not None and public_conviction is not None:
private_conviction = (
old_private_conviction
+ _PRIVATE_ADJUSTMENT_RHO
* (public_conviction - old_private_conviction)
)
private_conviction = max(0.0, min(1.0, private_conviction))
recent_sources = {
exp.source_agent_id
for exp in old_state.exposures
if (
exp.source_agent_id
and exp.timestep > old_state.last_reasoning_timestep
)
}
recent_source_count = len(recent_sources)
private_position = old_private_position
if private_position is None: