Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Update SimPy skill for current semantics
Timothy Kassis65f46984c5eb
diff --git a/skills/simpy/SKILL.md b/skills/simpy/SKILL.mdindex 9ff0ab01..896fe622 100644--- a/skills/simpy/SKILL.md+++ b/skills/simpy/SKILL.md@@ -1,426 +1,283 @@---name: simpy-description: Process-based discrete-event simulation framework in Python. Use this skill when building simulations of systems with processes, queues, resources, and time-based events such as manufacturing systems, service operations, network traffic, logistics, or any system where entities interact with shared resources over time.-license: MIT license-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}+description: Build, inspect, test, and analyze bounded process-based discrete-event simulations with SimPy, including events, resources, interrupts, monitoring, replications, warm-up, and reproducible output analysis.+license: MIT+compatibility: Upstream SimPy 4.1.2 supports Python 3.8+; bundled CLIs require Python 3.10+, uv, and SimPy 4.1.2. They use only SimPy and the standard library, operate on local bounded inputs, and make no network calls.+allowed-tools: Read, Write, Edit, Bash, Glob+metadata:+ version: "1.1"+ skill-author: K-Dense Inc.----# SimPy - Discrete-Event Simulation+# SimPy-## Overview+## Scope-SimPy is a process-based discrete-event simulation framework based on standard Python. Use SimPy to model systems where entities (customers, vehicles, packets, etc.) interact with each other and compete for shared resources (servers, machines, bandwidth, etc.) over time.+Use this skill for process-based discrete-event models where active entities yield+events and contend for resources: queues, production systems, logistics, networks,+service operations, inventory, and other event-driven systems.-**Core capabilities:**-- Process modeling using Python generator functions-- Shared resource management (servers, containers, stores)-- Event-driven scheduling and synchronization-- Real-time simulations synchronized with wall-clock time-- Comprehensive monitoring and data collection+SimPy supplies an event scheduler and modeling primitives. It does **not** choose a+scientifically valid conceptual model, input distribution, warm-up, run length,+replication count, estimand, or causal interpretation. Treat those as simulation-study+methodology, not SimPy API behavior.-## When to Use This Skill+## Current release and installation-Use the SimPy skill when:+Verified **2026-07-23**:-1. **Modeling discrete-event systems** - Systems where events occur at irregular intervals-2. **Resource contention** - Entities compete for limited resources (servers, machines, staff)-3. **Queue analysis** - Studying waiting lines, service times, and throughput-4. **Process optimization** - Analyzing manufacturing, logistics, or service processes-5. **Network simulation** - Packet routing, bandwidth allocation, latency analysis-6. **Capacity planning** - Determining optimal resource levels for desired performance-7. **System validation** - Testing system behavior before implementation+- Latest stable: **SimPy 4.1.2**, released on PyPI 2026-05-24; source tag+ `4.1.2` points to commit `f4381649`.+- Package metadata requires Python **>=3.8** and classifies CPython 3.8-3.14+ plus PyPy. SimPy has no runtime dependencies.+- 4.1.2 adds Python 3.13/3.14 support and modern-interpreter test fixes.+- Upstream and this skill are MIT-licensed.-**Not suitable for:**-- Continuous simulations with fixed time steps (consider SciPy ODE solvers)-- Independent processes without resource sharing-- Pure mathematical optimization (consider SciPy optimize)+Create a reproducible environment:-## Quick Start--### Basic Simulation Structure--```python-import simpy--def process(env, name):- """A simple process that waits and prints."""- print(f'{name} starting at {env.now}')- yield env.timeout(5)- print(f'{name} finishing at {env.now}')--# Create environment-env = simpy.Environment()--# Start processes-env.process(process(env, 'Process 1'))-env.process(process(env, 'Process 2'))--# Run simulation-env.run(until=10)-```--### Resource Usage Pattern--```python-import simpy--def customer(env, name, resource):- """Customer requests resource, uses it, then releases."""- with resource.request() as req:- yield req # Wait for resource- print(f'{name} got resource at {env.now}')- yield env.timeout(3) # Use resource- print(f'{name} released resource at {env.now}')--env = simpy.Environment()-server = simpy.Resource(env, capacity=1)--env.process(customer(env, 'Customer 1', server))-env.process(customer(env, 'Customer 2', server))-env.run()+```bash+uv venv --python 3.13+source .venv/bin/activate+uv pip install "simpy==4.1.2"+python -c "import importlib.metadata; print(importlib.metadata.version('simpy'))"```-## Core Concepts--### 1. Environment--The simulation environment manages time and schedules events.--```python-import simpy--# Standard environment (runs as fast as possible)-env = simpy.Environment(initial_time=0)--# Real-time environment (synchronized with wall-clock)-import simpy.rt-env_rt = simpy.rt.RealtimeEnvironment(factor=1.0)--# Run simulation-env.run(until=100) # Run until time 100-env.run() # Run until no events remain-```--### 2. Processes--Processes are defined using Python generator functions (functions with `yield` statements).--```python-def my_process(env, param1, param2):- """Process that yields events to pause execution."""- print(f'Starting at {env.now}')-- # Wait for time to pass- yield env.timeout(5)-- print(f'Resumed at {env.now}')-- # Wait for another event- yield env.timeout(3)-- print(f'Done at {env.now}')- return 'result'--# Start the process-env.process(my_process(env, 'value1', 'value2'))-```--### 3. Events--Events are the fundamental mechanism for process synchronization. Processes yield events and resume when those events are triggered.--**Common event types:**-- `env.timeout(delay)` - Wait for time to pass-- `resource.request()` - Request a resource-- `env.event()` - Create a custom event-- `env.process(func())` - Process as an event-- `event1 & event2` - Wait for all events (AllOf)-- `event1 | event2` - Wait for any event (AnyOf)--## Resources--SimPy provides several resource types for different scenarios. For comprehensive details, see `references/resources.md`.--### Resource Types Summary--| Resource Type | Use Case |-|---------------|----------|-| Resource | Limited capacity (servers, machines) |-| PriorityResource | Priority-based queuing |-| PreemptiveResource | High-priority can interrupt low-priority |-| Container | Bulk materials (fuel, water) |-| Store | Python object storage (FIFO) |-| FilterStore | Selective item retrieval |-| PriorityStore | Priority-ordered items |--### Quick Reference+Do not silently substitute the `latest` documentation build: it may describe an+unreleased development revision. Use the versioned 4.1.2 links in+`references/sources.md`.++## Model workflow++1. **Define purpose and estimands.** State the decision/question, system boundary,+ entities, resources, state, outputs, time units, and terminating event or+ steady-state target.+2. **Write a conceptual model first.** Record assumptions, distributions,+ routing, priorities, initial conditions, and omitted mechanisms.+3. **Implement generators.** A SimPy process is an event-yielding Python generator.+ Register the generator object with `env.process(...)`.+4. **Bound execution.** Give every production run explicit time, entity, event, and+ replication caps. Never call `env.run()` on a model containing an endless process.+5. **Separate random streams.** Use local RNG instances for logically distinct+ stochastic sources; retain a seed manifest.+6. **Instrument deliberately.** Observe state after the transition of interest,+ close time-weighted intervals at the horizon, and test that monitoring does not+ alter event order.+7. **Verify and validate.** Test deterministic edge cases, conservation identities,+ traces, queue discipline, and analytical benchmarks; compare against system or+ expert evidence for the stated purpose.+8. **Run independent replications.** Make intervals from replication-level+ estimates, not correlated entities within one run.+9. **Report limitations.** Include initialization, unfinished entities, run length,+ seeds/streams, precision, sensitivity, and validation evidence. Never convert+ simulation association into a causal claim.++Read `references/simulation-methodology.md` before making inferential claims.++## Minimal bounded model```python+import randomimport simpy+HORIZON = 480.0+arrival_rng = random.Random(101)+service_rng = random.Random(202)env = simpy.Environment()+server = simpy.Resource(env, capacity=2)+completed = []-# Basic resource (e.g., servers)-resource = simpy.Resource(env, capacity=2)--# Priority resource-priority_resource = simpy.PriorityResource(env, capacity=1)--# Container (e.g., fuel tank)-fuel_tank = simpy.Container(env, capacity=100, init=50)--# Store (e.g., warehouse)-warehouse = simpy.Store(env, capacity=10)-```--## Common Simulation Patterns--### Pattern 1: Customer-Server Queue--```python-import simpy-import random--def customer(env, name, server):- arrival = env.now- with server.request() as req:- yield req+def customer(arrival):+ with server.request() as request:+ yield requestwait = env.now - arrival- print(f'{name} waited {wait:.2f}, served at {env.now}')- yield env.timeout(random.uniform(2, 4))--def customer_generator(env, server):- i = 0- while True:- yield env.timeout(random.uniform(1, 3))- i += 1- env.process(customer(env, f'Customer {i}', server))--env = simpy.Environment()-server = simpy.Resource(env, capacity=2)-env.process(customer_generator(env, server))-env.run(until=20)+ yield env.timeout(service_rng.expovariate(1 / 6.0))+ completed.append((env.now, wait))++def arrivals():+ for _ in range(10_000): # Entity cap.+ delay = arrival_rng.expovariate(1 / 4.0)+ if env.now + delay >= HORIZON:+ return+ yield env.timeout(delay)+ env.process(customer(env.now))++env.process(arrivals())+env.run(until=HORIZON)```-### Pattern 2: Producer-Consumer+The numeric horizon is half-open: normal events scheduled exactly at `480.0` are+not processed. Report unfinished entities rather than silently treating them as+completed observations.++## Core semantics++### Environment and deterministic ordering++`Environment` is single-threaded. The queue is ordered by simulation time, event+priority, then a strictly increasing event ID. Same-time, same-priority events are+therefore processed FIFO in scheduling order. Model processes may represent+concurrency, but callbacks execute sequentially and deterministically.++- `env.now`: unitless simulation clock; choose and document one unit.+- `env.peek()`: next event time or infinity.+- `env.step()`: process one event; raises `EmptySchedule` when empty.+- `env.active_process`: currently executing process, otherwise `None`.+- `env.run()`: drain the queue; unsafe with recurring or endless processes.++`env.run(until=number)` and `env.run(until=event)` are not interchangeable at+boundaries:++- A numeric value schedules an urgent stop event and excludes ordinary events at+ that exact time.+- An Event criterion returns that event's value when its stop callback fires.+ Other same-time ordering depends on priority and scheduling order.+- In 4.1.2, `Environment.step()` preserves callbacks remaining after+ `StopSimulation` by rescheduling the target. Consequently, after+ `env.run(until=target)`, `target.processed` can remain `False` until one more+ `step()`/`run()` even though its value was returned. Do not use `processed` as the+ sole post-run completion test.++See `references/events.md` and `references/monitoring.md`.++### Event, Timeout, Process, and Condition++- An `Event` moves once through not-triggered -> triggered/scheduled -> processed.+ `succeed(value)` or `fail(exception)` triggers it once.+- A `Timeout` triggers when created, is scheduled for `now + delay`, and cannot be+ manually succeeded again.+- `env.process(generator)` creates a `Process`; the generator resumes with the+ yielded event value. Returning from the generator succeeds the Process with that+ return value. Uncaught exceptions fail it.+- `AnyOf` / `a | b` and `AllOf` / `a & b` yield a `ConditionValue`: an ordered,+ dict-like mapping from **event objects** to their values. Test membership using+ the original event objects; do not assume a scalar result.+- `AnyOf` does not cancel losing events. Explicitly cancel pending resource+ requests when abandoning them; ordinary timeouts remain scheduled.++### Interrupts++`process.interrupt(cause)` schedules an urgent interruption that throws+`simpy.Interrupt` into the target generator. Catch it around the yielded work that+may be interrupted, inspect `interrupt.cause`, update remaining work, then either+resume, re-yield the original event, or terminate.++Interrupting a process removes its resume callback from its current target; it does+not cancel that target event. A process cannot interrupt itself or a terminated+process. See `references/process-interaction.md`.++## Shared resources++| Type | Semantics |+|---|---|+| `Resource` | FIFO semaphore-like usage slots |+| `PriorityResource` | Queued requests sorted by lower numeric priority first |+| `PreemptiveResource` | Priority queue plus optional preemption of a current user |+| `Container` | Homogeneous numeric level; `put`/`get` wait for capacity/material |+| `Store` | FIFO Python objects |+| `FilterStore` | First available item satisfying the request's predicate |+| `PriorityStore` | Comparable items returned in priority order |++Use a request context manager:```python-import simpy--def producer(env, store):- item_id = 0- while True:- yield env.timeout(2)- item = f'Item {item_id}'- yield store.put(item)- print(f'Produced {item} at {env.now}')- item_id += 1--def consumer(env, store):- while True:- item = yield store.get()- print(f'Consumed {item} at {env.now}')+def job(env, resource):+ with resource.request() as request:+ yield requestyield env.timeout(3)--env = simpy.Environment()-store = simpy.Store(env, capacity=10)-env.process(producer(env, store))-env.process(consumer(env, store))-env.run(until=20)-```--### Pattern 3: Parallel Task Execution--```python-import simpy--def task(env, name, duration):- print(f'{name} starting at {env.now}')- yield env.timeout(duration)- print(f'{name} done at {env.now}')- return f'{name} result'--def coordinator(env):- # Start tasks in parallel- task1 = env.process(task(env, 'Task 1', 5))- task2 = env.process(task(env, 'Task 2', 3))- task3 = env.process(task(env, 'Task 3', 4))-- # Wait for all to complete- results = yield task1 & task2 & task3- print(f'All done at {env.now}')--env = simpy.Environment()-env.process(coordinator(env))-env.run()```-## Workflow Guide+On exit it releases an acquired request or cancels a still-pending one, including+during exception unwinding. For a manually retained pending `put`/`get`/request,+call `cancel()` if an interrupt or timeout makes the process abandon it.-### Step 1: Define the System+`PreemptiveResource.request(priority=..., preempt=True)` uses lower numbers as+higher priority. The preempted process receives an `Interrupt` whose cause is a+`Preempted` object: `cause.by` is the preempting Process,+`cause.usage_since` is when use began, and `cause.resource` is the resource.+Queued priority takes precedence over the `preempt` flag; mixing preempting and+non-preempting requests needs explicit tests.-Identify:-- **Entities**: What moves through the system? (customers, parts, packets)-- **Resources**: What are the constraints? (servers, machines, bandwidth)-- **Processes**: What are the activities? (arrival, service, departure)-- **Metrics**: What to measure? (wait times, utilization, throughput)+Read `references/resources.md` for blocked operations, queue rules, and examples.-### Step 2: Implement Process Functions+## Monitoring and stepping-Create generator functions for each process type:+Prefer explicit domain observations at state transitions. For generic resource+monitoring, wrappers or subclasses can inspect `count`, `queue`, `level`, `items`,+`put_queue`, and `get_queue`. For event tracing, `schedule()` and `step()` are the+central hooks.-```python-def entity_process(env, name, resources, parameters):- # Arrival logic- arrival_time = env.now+Queue measurements are timing-sensitive:- # Request resources- with resource.request() as req:- yield req+- A request method's pre-state, post-call state, grant callback, and release+ callback can all differ at the same simulation timestamp.+- Sample averages weight event observations, not time. Compute area under the+ left-continuous state path and divide by elapsed time.+- Add initial and final samples; close the last interval at the analysis horizon.+- `env._queue`, resource `_env`, and monkey-patching are implementation details.+ Pin SimPy, isolate the instrumentation, and regression-test after upgrades.+- Tracing every event changes runtime and memory use; cap trace records.- # Service logic- service_time = calculate_service_time(parameters)- yield env.timeout(service_time)+Use `scripts/resource_monitor.py` and `references/monitoring.md`.- # Departure logic- collect_statistics(env.now - arrival_time)-```+## Real-time execution-### Step 3: Set Up Monitoring+`simpy.rt.RealtimeEnvironment(initial_time=0, factor=1.0, strict=True)` maps one+simulation unit to `factor` wall-clock seconds. In strict mode, `step()`/`run()`+raises `RuntimeError` when computation falls behind. `strict=False` tolerates lag;+it does not restore timing accuracy. Develop logic with `Environment`, then run+separate timing tests with generous platform-aware tolerances. See+`references/real-time.md`.-Use monitoring utilities to collect data. See `references/monitoring.md` for comprehensive techniques.+## Bundled safe CLIs-```python-from scripts.resource_monitor import ResourceMonitor+All CLIs use a fixed built-in queue model or summarize local artifacts. They reject+unknown JSON keys, URLs, symlinks, non-finite numbers, oversized inputs, and+unbounded time/events/entities/replications. They never evaluate config text,+execute user Python, import plugins, or call a network service.-# Create and monitor resource-resource = simpy.Resource(env, capacity=2)-monitor = ResourceMonitor(env, resource, "Server")+```bash+# Inspect all options.+python skills/simpy/scripts/bounded_queue_scenario.py --help+python skills/simpy/scripts/replication_runner.py --help+python skills/simpy/scripts/event_trace_summary.py --help+python skills/simpy/scripts/validate_simulation_config.py --help-# After simulation-monitor.report()-```--### Step 4: Run and Analyze--```python-# Run simulation-env.run(until=simulation_time)+# Deterministic built-in scenario.+python skills/simpy/scripts/bounded_queue_scenario.py-# Generate reports-monitor.report()-stats.report()+# Independent replications with replication-level Student-t intervals.+python skills/simpy/scripts/replication_runner.py-# Export data for further analysis-monitor.export_csv('results.csv')+# Validate only; no simulation runs.+python skills/simpy/scripts/validate_simulation_config.py config.json```-## Advanced Features+The replication runner refuses one-replication intervals. Its intervals quantify+Monte Carlo uncertainty under the configured model; they neither validate the model+nor identify causal effects. See `references/cli-guide.md`.-### Process Interaction+## Testing-Processes can interact through events, process yields, and interrupts. See `references/process-interaction.md` for detailed patterns.+Use deterministic unit tests for ordering, boundary times, conditions, interrupts,+all resource disciplines, conservation, event/entity limits, seed reproducibility,+and monitor non-interference. Add stochastic tests only as broad distributional+checks with fixed seeds; avoid brittle exact sample estimates.-**Key mechanisms:**-- **Event signaling**: Shared events for coordination-- **Process yields**: Wait for other processes to complete-- **Interrupts**: Forcefully resume processes for preemption+Run the bundled suite in the exact pinned environment without bytecode artifacts:-### Real-Time Simulations--Synchronize simulation with wall-clock time for hardware-in-the-loop or interactive applications. See `references/real-time.md`.--```python-import simpy.rt--env = simpy.rt.RealtimeEnvironment(factor=1.0) # 1:1 time mapping-# factor=0.5 means 1 sim unit = 0.5 seconds (2x faster)-```--### Comprehensive Monitoring--Monitor processes, resources, and events. See `references/monitoring.md` for techniques including:-- State variable tracking-- Resource monkey-patching-- Event tracing-- Statistical collection--## Scripts and Templates--### basic_simulation_template.py--Complete template for building queue simulations with:-- Configurable parameters-- Statistics collection-- Customer generation-- Resource usage-- Report generation--**Usage:**-```python-from scripts.basic_simulation_template import SimulationConfig, run_simulation--config = SimulationConfig()-config.num_resources = 2-config.sim_time = 100-stats = run_simulation(config)-stats.report()+```bash+PYTHONDONTWRITEBYTECODE=1 uv run --isolated --no-project \+ --python 3.13 --with "simpy==4.1.2" \+ python -m unittest discover -s skills/simpy/tests -v```-### resource_monitor.py--Reusable monitoring utilities:-- `ResourceMonitor` - Track single resource-- `MultiResourceMonitor` - Monitor multiple resources-- `ContainerMonitor` - Track container levels-- Automatic statistics calculation-- CSV export functionality--**Usage:**-```python-from scripts.resource_monitor import ResourceMonitor--monitor = ResourceMonitor(env, resource, "My Resource")-# ... run simulation ...-monitor.report()-monitor.export_csv('data.csv')-```--## Reference Documentation--Detailed guides for specific topics:--- **`references/resources.md`** - All resource types with examples-- **`references/events.md`** - Event system and patterns-- **`references/process-interaction.md`** - Process synchronization-- **`references/monitoring.md`** - Data collection techniques-- **`references/real-time.md`** - Real-time simulation setup--## Best Practices--1. **Generator functions**: Always use `yield` in process functions-2. **Resource context managers**: Use `with resource.request() as req:` for automatic cleanup-3. **Reproducibility**: Set `random.seed()` for consistent results-4. **Monitoring**: Collect data throughout simulation, not just at the end-5. **Validation**: Compare simple cases with analytical solutions-6. **Documentation**: Comment process logic and parameter choices-7. **Modular design**: Separate process logic, statistics, and configuration--## Common Pitfalls--1. **Forgetting yield**: Processes must yield events to pause-2. **Event reuse**: Events can only be triggered once-3. **Resource leaks**: Use context managers or ensure release-4. **Blocking operations**: Avoid Python blocking calls in processes-5. **Time units**: Stay consistent with time unit interpretation-6. **Deadlocks**: Ensure at least one process can make progress--## Example Use Cases--- **Manufacturing**: Machine scheduling, production lines, inventory management-- **Healthcare**: Emergency room simulation, patient flow, staff allocation-- **Telecommunications**: Network traffic, packet routing, bandwidth allocation-- **Transportation**: Traffic flow, logistics, vehicle routing-- **Service operations**: Call centers, retail checkout, appointment scheduling-- **Computer systems**: CPU scheduling, memory management, I/O operations+## References+- `references/events.md` — scheduler, lifecycle, run boundaries, conditions+- `references/process-interaction.md` — generators, shared events, interrupts+- `references/resources.md` — all Resource, Container, and Store variants+- `references/monitoring.md` — time weighting, queue timing, tracing, stepping+- `references/real-time.md` — factor, strict mode, drift, timing tests+- `references/simulation-methodology.md` — replications, warm-up, validation, CI+- `references/cli-guide.md` — schemas, bounds, outputs, and safe CLI examples+- `references/sources.md` — dated official and primary-method sourcesdiff --git a/skills/simpy/references/cli-guide.md b/skills/simpy/references/cli-guide.mdnew file mode 100644index 00000000..3fb47f54--- /dev/null+++ b/skills/simpy/references/cli-guide.md@@ -0,0 +1,266 @@+# Bundled CLI guide++Verified 2026-07-23 for skill version 1.1 and SimPy 4.1.2.++The scripts implement one transparent finite-horizon exponential+arrival/exponential service multi-server queue. They are examples and diagnostics,+not a generic model execution platform.++## Safety contract++All scripts:++- use only SimPy and the Python standard library;+- build `--help` when SimPy is absent, so options remain inspectable before+ installation;+- make no network or external-service calls;+- accept only local regular files with fixed suffixes;+- reject URLs, symlinks, duplicate JSON keys, `NaN`/infinity, unknown keys, and+ oversized inputs;+- never evaluate configuration text, run user Python, resolve callables, or import+ plugins;+- enforce time, event, entity, queue, trace, and replication caps;+- emit strict deterministic JSON (`allow_nan=False`);+- write explicit outputs atomically with mode `0600`;+- refuse overwrite unless `--force` is supplied.++Run from the repository root after the pinned install:++```bash+uv pip install "simpy==4.1.2"+```++Commands that execute a simulation gate SimPy through a shared dependency loader.+If it is absent, they exit without a traceback and print the pinned installation+command above. Configuration validation and artifact summarization remain usable+without SimPy.++## Queue configuration schema++Every field is optional; defaults are shown:++```json+{+ "analysis_mode": "terminating",+ "base_seed": 20260723,+ "horizon": 480.0,+ "max_entities": 10000,+ "max_events": 200000,+ "mean_interarrival": 4.0,+ "mean_service": 6.0,+ "queue_capacity": 20,+ "servers": 2,+ "warm_up": 0.0+}+```++Semantics:++- arrival and service durations are exponential means in the declared model time+ unit;+- there are `servers` simultaneous slots and at most `queue_capacity` waiting+ entities;+- an arrival seeing `servers + queue_capacity` admitted entities is rejected;+- arrivals and services use separate deterministic stream seeds;+- arrivals occur strictly before `horizon`;+- numeric horizon excludes ordinary events exactly at that time;+- completed-customer metrics exclude unfinished entities and disclose their count.++Bounds:++- `0 < horizon <= 1,000,000`;+- `1 <= servers <= 10,000`;+- `0 <= queue_capacity <= 100,000`;+- positive finite means no greater than 1,000,000;+- `1 <= max_entities <= 100,000`;+- `10 <= max_events <= 1,000,000`;+- base seed from 0 through `2^63 - 1`.++For `analysis_mode="terminating"`, `warm_up` must be zero. For+`analysis_mode="steady_state"`, warm-up must be positive and less than horizon.+This validates consistency only; it does not establish that steady state was+reached.++## Basic template++```bash+python skills/simpy/scripts/basic_simulation_template.py --help+python skills/simpy/scripts/basic_simulation_template.py+python skills/simpy/scripts/basic_simulation_template.py \+ --config queue.json --output run.json+```++`--replication INDEX` selects deterministic derived arrival/service seeds. It does+not itself create a confidence interval.++Library use:++```python+from basic_simulation_template import QueueConfig, run_simulation++config = QueueConfig.from_mapping({"horizon": 120, "servers": 3})+report = run_simulation(config, replication=0)+```++## Bounded queue scenario and trace++```bash+python skills/simpy/scripts/bounded_queue_scenario.py \+ --config queue.json \+ --output scenario.json \+ --trace-output trace.jsonl \+ --trace-max-records 50000+```++The trace is capped and contains no event `repr`:++```json+{+ "event_id": 0,+ "event_type": "Initialize",+ "priority": 0,+ "queue_size_before": 1,+ "time": 0.0+}+```++The `.jsonl` file has one compact object per line. A trace can truncate while the+bounded simulation completes; the report discloses `trace.truncated`.++## Replication configuration schema++```json+{+ "confidence": 0.95,+ "model": {+ "analysis_mode": "terminating",+ "base_seed": 20260723,+ "horizon": 480,+ "max_entities": 10000,+ "max_events": 200000,+ "mean_interarrival": 4,+ "mean_service": 6,+ "queue_capacity": 20,+ "servers": 2,+ "warm_up": 0+ },+ "replications": 20+}+```++Additional experiment bounds:++- 2-1,000 replications; one-run confidence intervals are rejected;+- confidence strictly greater than 0.50 and at most 0.999;+- `replications * max_events <= 5,000,000`;+- `replications * max_entities <= 2,000,000`.++```bash+python skills/simpy/scripts/replication_runner.py --help+python skills/simpy/scripts/replication_runner.py \+ --config experiment.json --output intervals.json+```++The runner makes a two-sided Student-t interval from independent+replication-level estimates. A metric undefined in any run is marked unavailable+instead of dropping that run. It never constructs a CI from individual customers+within one run.++The seed manifest uses stable BLAKE2b derivation for separate arrival/service RNG+objects. This is deterministic stream separation for the bundled example, not a+formal proof of independent substreams. See `simulation-methodology.md`.++## Configuration validator++Validation performs no simulation:++```bash+python skills/simpy/scripts/validate_simulation_config.py queue.json+python skills/simpy/scripts/validate_simulation_config.py \+ experiment.json --schema replication+```++Schemas are `queue`, `replication`, or `auto`. Auto identifies the replication+schema by any top-level `model`, `replications`, or `confidence` key. There are no+custom model names, module paths, class names, predicates, or callable fields.++Unknown keys such as the following are rejected:++```json+{+ "plugin": "package.module",+ "python": "print('run me')"+}+```++## Event/resource artifact summarizer++Summarize a trace without importing or executing its originating model:++```bash+python skills/simpy/scripts/event_trace_summary.py trace.jsonl+```++Summarize ResourceMonitor CSV:++```bash+python skills/simpy/scripts/resource_monitor.py \+ --samples resource.csv --output monitor.json+python skills/simpy/scripts/event_trace_summary.py resource.csv+```++Accepted trace fields are exactly:++`event_id`, `event_type`, `priority`, `queue_size_before`, `time`.++Accepted resource CSV fields are exactly:++`time`, `event`, `count`, `queue_length`, `utilization`.++The summarizer checks event trace order by `(time, priority, event_id)` and computes+resource time averages by carrying each state left-continuously to the next sample.+It does not infer queue semantics from arbitrary column names.++## Resource monitor library++```python+from resource_monitor import EventTraceRecorder, ResourceMonitor++monitor = ResourceMonitor(env, server, "server")+trace = EventTraceRecorder(env, max_records=10_000)+env.run(until=100)+trace.detach()+monitor.finalize(at=100)++print(monitor.summary(start=20, end=100))+monitor.export_csv("resource.csv")+trace.export_jsonl("trace.jsonl")+```++The monitor patches one resource instance. Do not attach multiple wrappers to the+same resource. Its queue timing and private-API caveats are in `monitoring.md`.++## Exit behavior++Expected validation failures use `argparse` errors and nonzero exit status:++- malformed/unknown config;+- unsafe path or overwrite;+- event/entity/replication budget violation;+- event limit reached during the run;+- invalid trace/resource artifact.++An event-budget error is a failed/incomplete simulation, not a valid censored+result. Increase a cap only after diagnosing why it was reached.++## Exact pinned tests++```bash+PYTHONDONTWRITEBYTECODE=1 uv run --isolated --no-project \+ --python 3.13 --with "simpy==4.1.2" \+ python -m unittest discover -s skills/simpy/tests -v+```++Tests cover scheduler boundaries, deterministic ties, Conditions, all resource+families, preemption causes, monitor time weighting, trace round-trip, config/path+safety, hard limits, seed determinism, and Student-t calculations.diff --git a/skills/simpy/references/events.md b/skills/simpy/references/events.mdindex 3b215a77..f3587756 100644--- a/skills/simpy/references/events.md+++ b/skills/simpy/references/events.md@@ -1,374 +1,225 @@-# SimPy Events System+# Events, environments, and scheduling-This guide covers the event system in SimPy, which forms the foundation of discrete-event simulation.+Verified 2026-07-23 against SimPy 4.1.2 documentation and tagged source.-## Event Basics+## Scheduler model-Events are the core mechanism for controlling simulation flow. Processes yield events and resume when those events are triggered.+`Environment` owns a single event queue and processes one event at a time. Tagged+4.1.2 stores queue entries as `(time, priority, event_id, event)`:-### Event Lifecycle+1. smallest simulation time first;+2. smallest numeric priority first (`URGENT=0`, `NORMAL=1` in public event APIs);+3. smallest strictly increasing event ID first.-Events progress through three states:+Thus same-time, same-priority events are FIFO by scheduling order. This is+deterministic sequential execution, even when model processes represent concurrent+activities. Floating-point discretization can collapse physically distinct times+onto the same value, so test tie behavior explicitly.-1. **Not triggered** - Initial state as memory objects-2. **Triggered** - Scheduled in event queue; `triggered` property is `True`-3. **Processed** - Removed from queue with callbacks executed; `processed` property is `True`+## Event lifecycle-```python-import simpy--env = simpy.Environment()--# Create an event-event = env.event()-print(f'Triggered: {event.triggered}, Processed: {event.processed}') # Both False--# Trigger the event-event.succeed(value='Event result')-print(f'Triggered: {event.triggered}, Processed: {event.processed}') # True, False--# Run to process the event-env.run()-print(f'Triggered: {event.triggered}, Processed: {event.processed}') # True, True-print(f'Value: {event.value}') # 'Event result'-```--## Core Event Types--### Timeout+An `Event` moves once through:-Controls time progression in simulations. Most common event type.+1. **not triggered** — not scheduled and no value;+2. **triggered** — outcome/value fixed and scheduled; `event.triggered` is true;+3. **processed** — removed for callback execution; `event.processed` is true when+ `event.callbacks is None`.```pythonimport simpy-def process(env):- print(f'Starting at {env.now}')- yield env.timeout(5)- print(f'Resumed at {env.now}')-- # Timeout with value- result = yield env.timeout(3, value='Done')- print(f'Result: {result} at {env.now}')-env = simpy.Environment()-env.process(process(env))-env.run()-```--**Usage:**-- `env.timeout(delay)` - Wait for specified time-- `env.timeout(delay, value=val)` - Wait and return value--### Process Events--Processes themselves are events, allowing processes to wait for other processes to complete.--```python-import simpy--def worker(env, name, duration):- print(f'{name} starting at {env.now}')- yield env.timeout(duration)- print(f'{name} finished at {env.now}')- return f'{name} result'--def coordinator(env):- # Start worker processes- worker1 = env.process(worker(env, 'Worker 1', 5))- worker2 = env.process(worker(env, 'Worker 2', 3))-- # Wait for worker1 to complete- result = yield worker1- print(f'Coordinator received: {result}')+event = env.event()+assert not event.triggered and not event.processed- # Wait for worker2- result = yield worker2- print(f'Coordinator received: {result}')+event.succeed("ready")+assert event.triggered and not event.processed-env = simpy.Environment()-env.process(coordinator(env))-env.run()+env.step()+assert event.processed and event.value == "ready"```-### Event--Generic event that can be manually triggered.+`event.succeed(value)` and `event.fail(exception)` return that event and may be+called only once. In 4.1.2 `fail()` requires an `Exception`. `event.trigger(other)`+copies the other event's success/failure and value, and returns `None`.-```python-import simpy+A failed event throws its exception into a waiting process. If no process or+callback defuses it, `Environment.step()` raises it. Treat private `_ok`, `_value`,+and `_defused` as implementation details.-def waiter(env, event):- print(f'Waiting for event at {env.now}')- value = yield event- print(f'Event received with value: {value} at {env.now}')+## Callbacks-def triggerer(env, event):- yield env.timeout(5)- print(f'Triggering event at {env.now}')- event.succeed(value='Hello!')+Before processing, `event.callbacks` is a mutable list of one-argument callables.+Yielding an event adds the waiting process's resume method. Processing executes+callbacks in list order. Once fully processed, callbacks becomes `None`; appending+then is invalid.-env = simpy.Environment()-event = env.event()-env.process(waiter(env, event))-env.process(triggerer(env, event))+```python+log = []+timeout = env.timeout(2, value=7)+timeout.callbacks.append(lambda completed: log.append(completed.value))env.run()+assert log == [7]```-## Composite Events+Keep callbacks short and non-blocking. A callback runs synchronously inside+`Environment.step()` and can affect scheduler latency.-### AllOf - Wait for Multiple Events+## Timeout-Triggers when all specified events have occurred.+`env.timeout(delay, value=None)` creates a `Timeout`, immediately triggers it, and+schedules it at `env.now + delay`. Because it is already triggered at construction,+do not call `succeed()` or `fail()` on it.```python-import simpy--def process(env):- # Start multiple tasks- task1 = env.timeout(3, value='Task 1 done')- task2 = env.timeout(5, value='Task 2 done')- task3 = env.timeout(4, value='Task 3 done')-- # Wait for all to complete- results = yield simpy.AllOf(env, [task1, task2, task3])- print(f'All tasks completed at {env.now}')- print(f'Results: {results}')-- # Alternative syntax using & operator- task4 = env.timeout(2)- task5 = env.timeout(3)- yield task4 & task5- print(f'Tasks 4 and 5 completed at {env.now}')--env = simpy.Environment()-env.process(process(env))-env.run()+def timer(env):+ result = yield env.timeout(3, value="elapsed")+ assert result == "elapsed"```-**Returns:** Dictionary mapping events to their values+Reject negative delay. Use a consistent numeric time unit; SimPy does not attach+units or protect against incompatible scales.-**Use cases:**-- Parallel task completion-- Barrier synchronization-- Waiting for multiple resources+## Process-### AnyOf - Wait for Any Event--Triggers when at least one specified event has occurred.+`env.process(generator)` requires a **generator object**, not an ordinary function+result. It schedules an urgent `Initialize` event. Each yielded event suspends the+generator; after the event's outcome, SimPy sends its value back or throws its+failure into the generator.```python-import simpy--def process(env):- # Start multiple tasks with different durations- fast_task = env.timeout(2, value='Fast')- slow_task = env.timeout(10, value='Slow')+def child(env):+ yield env.timeout(1)+ return 42- # Wait for first to complete- results = yield simpy.AnyOf(env, [fast_task, slow_task])- print(f'First task completed at {env.now}')- print(f'Results: {results}')-- # Alternative syntax using | operator- task1 = env.timeout(5)- task2 = env.timeout(3)- yield task1 | task2- print(f'One of the tasks completed at {env.now}')+def parent(env):+ child_process = env.process(child(env))+ result = yield child_process+ assert result == 42env = simpy.Environment()-env.process(process(env))+env.process(parent(env))env.run()```-**Returns:** Dictionary with completed events and their values--**Use cases:**-- Racing conditions-- Timeout mechanisms-- First-to-respond scenarios+A `Process` is itself an event. It succeeds with the generator's return value or+fails with an uncaught exception. `process.is_alive`, `process.target`, and+`process.name` expose its current status.-## Event Triggering Methods+Common mistakes:-Events can be triggered in three ways:+- `env.process(worker)` instead of `env.process(worker(env))`;+- a function without any reachable `yield`, which is not a generator;+- performing blocking I/O or `time.sleep()` inside a normal Environment process;+- yielding a number rather than an Event.-### succeed(value=None)+## Condition events-Marks event as successful.+`AnyOf(env, events)` / `a | b` and `AllOf(env, events)` / `a & b` return a+`Condition`. Yielding one produces a `ConditionValue`, an ordered dict-like mapping+whose keys are the original Event objects and whose values are their values.```python-event = env.event()-event.succeed(value='Success!')-```--### fail(exception)--Marks event as failed with an exception.--```python-def process(env):- event = env.event()- event.fail(ValueError('Something went wrong'))+def coordinate(env):+ fast = env.timeout(1, value="fast")+ slow = env.timeout(2, value="slow")- try:- yield event- except ValueError as e:- print(f'Caught exception: {e}')+ first = yield fast | slow+ assert fast in first+ assert first[fast] == "fast"-env = simpy.Environment()-env.process(process(env))-env.run()+ both = yield fast & slow+ assert list(both.items()) == [(fast, "fast"), (slow, "slow")]```-### trigger(event)+For `AllOf`, all input events appear. For `AnyOf`, all target events that occurred+before the condition itself is processed can appear; do not assume exactly one+winner when events tie. Input order determines result order.-Copies another event's outcome.+If any input event fails before the condition succeeds, `AnyOf` and `AllOf` fail.+Conditions can be nested. `AnyOf` does **not** cancel losing events:```python-event1 = env.event()-event1.succeed(value='Original')--event2 = env.event()-event2.trigger(event1) # event2 now has same outcome as event1+with resource.request() as request:+ patience = env.timeout(5)+ result = yield request | patience+ if request not in result:+ # Context-manager exit cancels the still-pending request.+ return+ yield env.timeout(2)```-## Callbacks+An ordinary losing timeout remains scheduled. This is usually harmless but matters+for event counts and traces.-Attach functions to execute when events are triggered.+## `Environment.run()` boundaries-```python-import simpy+### No criterion-def callback(event):- print(f'Callback executed! Event value: {event.value}')+`env.run()` stops only when the event queue is empty. An endless generator such as+`while True: yield env.timeout(1)` makes it nonterminating.-def process(env):- event = env.timeout(5, value='Done')- event.callbacks.append(callback)- yield event+### Numeric criterion-env = simpy.Environment()-env.process(process(env))-env.run()-```--**Note:** Yielding an event from a process automatically adds the process's resume method as a callback.--## Event Sharing--Multiple processes can wait for the same event.+`env.run(until=10)` creates an internal urgent stop event at time 10. It advances+`env.now` to 10 but does **not** process ordinary events scheduled exactly at 10:```python-import simpy--def waiter(env, name, event):- print(f'{name} waiting at {env.now}')- value = yield event- print(f'{name} resumed with {value} at {env.now}')--def trigger_event(env, event):- yield env.timeout(5)- event.succeed(value='Go!')-env = simpy.Environment()-shared_event = env.event()--env.process(waiter(env, 'Process 1', shared_event))-env.process(waiter(env, 'Process 2', shared_event))-env.process(waiter(env, 'Process 3', shared_event))-env.process(trigger_event(env, shared_event))--env.run()+boundary = env.timeout(10)+env.run(until=10)+assert env.now == 10+assert not boundary.processed```-**Use cases:**-- Broadcasting signals-- Barrier synchronization-- Coordinated process resumption--## Advanced Event Patterns--### Timeout with Cancellation--```python-import simpy--def process_with_timeout(env):- work = env.timeout(10, value='Work complete')- timeout = env.timeout(5, value='Timeout!')-- # Race between work and timeout- result = yield work | timeout+The numeric target must be strictly greater than `env.now`.- if work in result:- print(f'Work completed: {result[work]}')- else:- print(f'Timed out: {result[timeout]}')+### Event criterion-env = simpy.Environment()-env.process(process_with_timeout(env))-env.run()-```+`env.run(until=event)` attaches a stop callback and returns the event value when+that callback fires. It raises `RuntimeError` if the schedule empties before the+criterion is triggered.-### Event Chaining+Important 4.1.2 implementation detail: `Environment.step()` catches+`StopSimulation`, preserves callbacks after the stopping callback, and reschedules+the event at priority `-1`. Since `processed` means callbacks is `None`, the target+can still report `processed == False` immediately after `run()` returns:```python-import simpy--def event_chain(env):- # Create chain of dependent events- event1 = env.event()- event2 = env.event()- event3 = env.event()-- def trigger_sequence(env):- yield env.timeout(2)- event1.succeed(value='Step 1')- yield env.timeout(2)- event2.succeed(value='Step 2')- yield env.timeout(2)- event3.succeed(value='Step 3')-- env.process(trigger_sequence(env))-- # Wait for sequence- val1 = yield event1- print(f'{val1} at {env.now}')- val2 = yield event2- print(f'{val2} at {env.now}')- val3 = yield event3- print(f'{val3} at {env.now}')-env = simpy.Environment()-env.process(event_chain(env))-env.run()+target = env.timeout(5, value="done")+assert env.run(until=target) == "done"+assert target.triggered+assert not target.processed+env.step()+assert target.processed```-### Conditional Events+This behavior follows tagged 4.1.2 `simpy/core.py`; the topical guide's informal+"processed" wording is not a safe postcondition. Depend on the returned value and+your model state, not solely on `processed`.-```python-import simpy+A timeout event and a numeric time can reach the same clock value but differ in+same-time ordering. Numeric stopping is the clearer half-open horizon.-def conditional_process(env):- temperature = 20+## Manual stepping- if temperature > 25:- yield env.timeout(5) # Cooling required- print('System cooled')- else:- yield env.timeout(1) # No cooling needed- print('Temperature acceptable')--env = simpy.Environment()-env.process(conditional_process(env))-env.run()+```python+until = 10+steps = 0+max_steps = 100_000+while env.peek() < until and steps < max_steps:+ env.step()+ steps += 1+if steps == max_steps:+ raise RuntimeError("event budget reached")```-## Best Practices+`peek()` returns infinity when empty; `step()` raises `simpy.core.EmptySchedule`+when no event remains. Explicit step/event caps prevent a zero-delay loop from+hanging diagnostics.++## Sources-1. **Always yield events**: Processes must yield events to pause execution-2. **Don't trigger events multiple times**: Events can only be triggered once-3. **Handle failures**: Use try-except when yielding events that might fail-4. **Composite events for parallelism**: Use AllOf/AnyOf for concurrent operations-5. **Shared events for broadcasting**: Multiple processes can yield the same event-6. **Event values for data passing**: Use event values to pass results between processes+See `sources.md` for versioned environment/event guides, API references, tagged+`core.py`, and the scheduling guide.diff --git a/skills/simpy/references/monitoring.md b/skills/simpy/references/monitoring.mdindex 8a1abd52..b895168e 100644--- a/skills/simpy/references/monitoring.md+++ b/skills/simpy/references/monitoring.md@@ -1,475 +1,260 @@-# SimPy Monitoring and Data Collection+# Monitoring, tracing, and stepping-This guide covers techniques for collecting data and monitoring simulation behavior in SimPy.+Verified 2026-07-23 against SimPy 4.1.2.-## Monitoring Strategy+Monitoring is model instrumentation, not an automatic statistical analysis. Define:-Before implementing monitoring, define three things:+1. the estimand/state (queue waiting only, users in service, total in system);+2. the observation instant (before request, after request, grant, release, final);+3. the aggregation rule (time average, entity average, count, quantile);+4. the analysis window and warm-up;+5. memory/trace caps.-1. **What to monitor**: Processes, resources, events, or system state-2. **When to monitor**: On change, at intervals, or at specific events-3. **How to store data**: Lists, files, databases, or real-time output+## Prefer explicit domain observations-## 1. Process Monitoring--### State Variable Tracking--Track process state by recording variables when they change.+Record domain events where their meaning is unambiguous:```python-import simpy--def customer(env, name, service_time, log):- arrival_time = env.now- log.append(('arrival', name, arrival_time))-- yield env.timeout(service_time)-- departure_time = env.now- log.append(('departure', name, departure_time))-- wait_time = departure_time - arrival_time- log.append(('wait_time', name, wait_time))--env = simpy.Environment()-log = []--env.process(customer(env, 'Customer 1', 5, log))-env.process(customer(env, 'Customer 2', 3, log))-env.run()--print('Simulation log:')-for entry in log:- print(entry)-```--### Time-Series Data Collection--```python-import simpy--def system_monitor(env, system_state, data_log, interval):- while True:- data_log.append((env.now, system_state['queue_length'], system_state['utilization']))- yield env.timeout(interval)--def process(env, system_state):- while True:- system_state['queue_length'] += 1+def customer(env, resource, log):+ arrival = env.now+ log.append({"event": "arrival", "time": env.now})+ with resource.request() as request:+ yield request+ log.append(+ {+ "event": "service_start",+ "queue_wait": env.now - arrival,+ "time": env.now,+ }+ )yield env.timeout(2)- system_state['queue_length'] -= 1- system_state['utilization'] = system_state['queue_length'] / 10- yield env.timeout(3)--env = simpy.Environment()-system_state = {'queue_length': 0, 'utilization': 0.0}-data_log = []--env.process(system_monitor(env, system_state, data_log, interval=1))-env.process(process(env, system_state))-env.run(until=20)--print('Time series data:')-for time, queue, util in data_log:- print(f'Time {time}: Queue={queue}, Utilization={util:.2f}')-```--### Multiple Variable Tracking--```python-import simpy--class SimulationData:- def __init__(self):- self.timestamps = []- self.queue_lengths = []- self.processing_times = []- self.utilizations = []-- def record(self, timestamp, queue_length, processing_time, utilization):- self.timestamps.append(timestamp)- self.queue_lengths.append(queue_length)- self.processing_times.append(processing_time)- self.utilizations.append(utilization)--def monitored_process(env, data):- queue_length = 0- processing_time = 0- utilization = 0.0-- for i in range(5):- queue_length = i % 3- processing_time = 2 + i- utilization = queue_length / 10-- data.record(env.now, queue_length, processing_time, utilization)- yield env.timeout(2)--env = simpy.Environment()-data = SimulationData()-env.process(monitored_process(env, data))-env.run()--print(f'Collected {len(data.timestamps)} data points')+ log.append({"event": "departure", "time": env.now})```-## 2. Resource Monitoring+Entity-average wait and time-average queue length are different estimands.-### Monkey-Patching Resources+## Why queue samples are timing-sensitive-Patch resource methods to intercept and log operations.+For `Resource.request()`:-```python-import simpy+- before the method: the new request is absent;+- immediately after: an available slot may already be allocated, or the request is+ in `queue`;+- when the request Event is processed: waiting Process callbacks run;+- during release: a queued request may be granted synchronously before the release+ Event's callbacks finish.-def patch_resource(resource, data_log):- """Patch a resource to log all requests and releases."""+Several states may therefore exist at the same simulation timestamp. Label sample+phase. Equal-time samples contribute zero duration to a time integral but affect an+unweighted sample average.- # Save original methods- original_request = resource.request- original_release = resource.release+`len(resource.queue)` counts pending requests, not users in service. Total number in+the congestion point is normally `resource.count + len(resource.queue)`.- # Create wrapper for request- def logged_request(*args, **kwargs):- req = original_request(*args, **kwargs)- data_log.append(('request', resource._env.now, len(resource.queue)))- return req+For Container/Store, distinguish `level`/`len(items)` from pending+`put_queue`/`get_queue`.- # Create wrapper for release- def logged_release(*args, **kwargs):- result = original_release(*args, **kwargs)- data_log.append(('release', resource._env.now, len(resource.queue)))- return result+## Time-weighted state- # Replace methods- resource.request = logged_request- resource.release = logged_release+For a left-continuous piecewise-constant state `q(t)`, compute:-def user(env, name, resource):- with resource.request() as req:- yield req- print(f'{name} using resource at {env.now}')- yield env.timeout(3)- print(f'{name} releasing resource at {env.now}')--env = simpy.Environment()-resource = simpy.Resource(env, capacity=1)-log = []+`average = sum(q_i * (t_{i+1} - t_i)) / (end - start)`.-patch_resource(resource, log)+Requirements:-env.process(user(env, 'User 1', resource))-env.process(user(env, 'User 2', resource))-env.run()+- initial sample at monitoring start;+- every relevant state transition;+- final sample exactly at the reporting horizon;+- warm-up window clipping;+- nondecreasing timestamps.-print('\nResource log:')-for entry in log:- print(entry)-```+Do not use `sum(queue_samples) / len(queue_samples)` as time-average queue length;+busy periods typically generate more events and become overrepresented.-### Resource Subclassing+## Bundled ResourceMonitor-Create custom resource classes with built-in monitoring.+`scripts/resource_monitor.py` wraps one Resource-like instance, records request,+grant, cancellation, release, and final states, and calculates time-weighted+utilization/queue length.```pythonimport simpy--class MonitoredResource(simpy.Resource):- def __init__(self, env, capacity):- super().__init__(env, capacity)- self.data = []- self.utilization_data = []-- def request(self, *args, **kwargs):- req = super().request(*args, **kwargs)- queue_length = len(self.queue)- utilization = self.count / self.capacity- self.data.append(('request', self._env.now, queue_length, utilization))- self.utilization_data.append((self._env.now, utilization))- return req-- def release(self, *args, **kwargs):- result = super().release(*args, **kwargs)- queue_length = len(self.queue)- utilization = self.count / self.capacity- self.data.append(('release', self._env.now, queue_length, utilization))- self.utilization_data.append((self._env.now, utilization))- return result-- def average_utilization(self):- if not self.utilization_data:- return 0.0- return sum(u for _, u in self.utilization_data) / len(self.utilization_data)--def user(env, name, resource):- with resource.request() as req:- yield req- print(f'{name} using resource at {env.now}')- yield env.timeout(2)+from resource_monitor import ResourceMonitorenv = simpy.Environment()-resource = MonitoredResource(env, capacity=2)--for i in range(5):- env.process(user(env, f'User {i+1}', resource))--env.run()+resource = simpy.Resource(env, capacity=2)+monitor = ResourceMonitor(env, resource, "server")-print(f'\nAverage utilization: {resource.average_utilization():.2%}')-print(f'Total operations: {len(resource.data)}')+# Register bounded processes, then run.+env.run(until=100)+monitor.finalize(at=100)+summary = monitor.summary(start=20, end=100)```-### Container Level Monitoring+The warm-up sample state is reconstructed from the last transition at or before+`start`; the final sample closes the interval. `export_csv()` writes local private+CSV atomically and refuses overwrite unless requested.-```python-import simpy--class MonitoredContainer(simpy.Container):- def __init__(self, env, capacity, init=0):- super().__init__(env, capacity, init)- self.level_data = [(0, init)]-- def put(self, amount):- result = super().put(amount)- self.level_data.append((self._env.now, self.level))- return result-- def get(self, amount):- result = super().get(amount)- self.level_data.append((self._env.now, self.level))- return result--def producer(env, container, amount, interval):- while True:- yield env.timeout(interval)- yield container.put(amount)- print(f'Produced {amount}. Level: {container.level} at {env.now}')--def consumer(env, container, amount, interval):- while True:- yield env.timeout(interval)- yield container.get(amount)- print(f'Consumed {amount}. Level: {container.level} at {env.now}')--env = simpy.Environment()-container = MonitoredContainer(env, capacity=100, init=50)+Monkey-patching changes method identity and can interact with other wrappers. Attach+one monitor per instance, patch before processes obtain method references, and call+`detach()` before another instrumentation layer.-env.process(producer(env, container, 20, 3))-env.process(consumer(env, container, 15, 4))-env.run(until=20)+## Generic resource wrappers-print('\nLevel history:')-for time, level in container.level_data:- print(f'Time {time}: Level={level}')-```--## 3. Event Tracing--### Environment Step Monitoring--Monitor all events by patching the environment's step function.+The official guide demonstrates pre/post method wrappers:```python-import simpy--def trace(env, callback):- """Trace all events processed by the environment."""+from functools import wraps++def patch_resource(resource, pre=None, post=None):+ def wrap(operation):+ @wraps(operation)+ def wrapper(*args, **kwargs):+ if pre is not None:+ pre(resource)+ event = operation(*args, **kwargs)+ if post is not None:+ post(resource)+ return event+ return wrapper++ for name in ("put", "get", "request", "release"):+ if hasattr(resource, name):+ setattr(resource, name, wrap(getattr(resource, name)))+```- def _trace_step():- # Get next event before it's processed- if env._queue:- time, priority, event_id, event = env._queue[0]- callback(time, priority, event_id, event)+Here "post" means after the method call, not necessarily after the returned Event+is processed. To observe completion, append a callback while `event.callbacks` is+still a list. Handle immediately triggered events before the environment steps.- # Call original step- return original_step()+Subclassing can be clearer for one stable use case, but it still depends on+protected `_env` in common examples. Prefer an explicit `env` reference.- original_step = env.step- env.step = _trace_step+## Event tracing-def event_callback(time, priority, event_id, event):- print(f'Event: time={time}, priority={priority}, id={event_id}, type={type(event).__name__}')+The official guide identifies:-def process(env, name):- print(f'{name}: Starting at {env.now}')- yield env.timeout(5)- print(f'{name}: Done at {env.now}')+- `Environment.schedule()` — event enters the queue;+- `Environment.step()` — next queued event is processed.-env = simpy.Environment()-trace(env, event_callback)--env.process(process(env, 'Process 1'))-env.process(process(env, 'Process 2'))-env.run()-```+The bundled `EventTraceRecorder` wraps `step()`, reads the next queue tuple, and+records only:-### Event Scheduling Monitor+- simulation time;+- priority;+- event ID;+- event class name;+- queue size before the step.-Track when events are scheduled.+It avoids `repr(event)`, which can contain nondeterministic memory addresses. It+caps records and writes JSON Lines.```python-import simpy+from resource_monitor import EventTraceRecorder-class MonitoredEnvironment(simpy.Environment):- def __init__(self):- super().__init__()- self.scheduled_events = []-- def schedule(self, event, priority=simpy.core.NORMAL, delay=0):- super().schedule(event, priority, delay)- scheduled_time = self.now + delay- self.scheduled_events.append((scheduled_time, priority, type(event).__name__))--def process(env, name, delay):- print(f'{name}: Scheduling timeout for {delay} at {env.now}')- yield env.timeout(delay)- print(f'{name}: Resumed at {env.now}')--env = MonitoredEnvironment()-env.process(process(env, 'Process 1', 5))-env.process(process(env, 'Process 2', 3))-env.run()--print('\nScheduled events:')-for time, priority, event_type in env.scheduled_events:- print(f'Time {time}, Priority {priority}, Type {event_type}')+trace = EventTraceRecorder(env, max_records=10_000)+env.run(until=100)+trace.detach()+trace.export_jsonl("trace.jsonl")```-## 4. Statistical Monitoring--### Queue Statistics--```python-import simpy--class QueueStatistics:- def __init__(self):- self.arrival_times = []- self.departure_times = []- self.queue_lengths = []- self.wait_times = []-- def record_arrival(self, time, queue_length):- self.arrival_times.append(time)- self.queue_lengths.append(queue_length)-- def record_departure(self, arrival_time, departure_time):- self.departure_times.append(departure_time)- self.wait_times.append(departure_time - arrival_time)-- def average_wait_time(self):- return sum(self.wait_times) / len(self.wait_times) if self.wait_times else 0-- def average_queue_length(self):- return sum(self.queue_lengths) / len(self.queue_lengths) if self.queue_lengths else 0+This intentionally accesses `env._queue`, a private implementation detail. Pin+SimPy and regression-test the tuple shape after upgrades. Full tracing increases+runtime and memory; use a small deterministic diagnostic scenario.-def customer(env, resource, stats):- arrival_time = env.now- stats.record_arrival(arrival_time, len(resource.queue))+Summarize without executing model code:- with resource.request() as req:- yield req- departure_time = env.now- stats.record_departure(arrival_time, departure_time)- yield env.timeout(2)+```bash+python skills/simpy/scripts/event_trace_summary.py trace.jsonl+python skills/simpy/scripts/event_trace_summary.py resource_samples.csv+```-env = simpy.Environment()-resource = simpy.Resource(env, capacity=1)-stats = QueueStatistics()+The summarizer validates fixed schemas, file size, record count, numeric finiteness,+and ordering.-for i in range(5):- env.process(customer(env, resource, stats))+## Manual stepping-env.run()+Stepping is useful for debuggers, GUI integration, invariants, and hard event caps:-print(f'Average wait time: {stats.average_wait_time():.2f}')-print(f'Average queue length: {stats.average_queue_length():.2f}')+```python+from simpy.core import EmptySchedule++max_events = 100_000+processed = 0+while env.peek() < 100 and processed < max_events:+ env.step()+ processed += 1++if processed == max_events:+ raise RuntimeError("event budget exhausted")+if env.peek() == float("inf"):+ # Empty schedule; verify intended completion instead of assuming success.+ pass```-## 5. Data Export--### CSV Export+`env.peek() < horizon` gives the same half-open boundary policy as numeric+`run(until=horizon)`. `<=` processes events at the boundary and is a different+estimand/termination convention.-```python-import simpy-import csv+If a stop callback fires during `step()` in 4.1.2, SimPy may reschedule the Event to+preserve remaining callbacks. See `events.md`.-def export_to_csv(data, filename):- with open(filename, 'w', newline='') as f:- writer = csv.writer(f)- writer.writerow(['Time', 'Metric', 'Value'])- writer.writerows(data)+## Periodic polling-def monitored_simulation(env, data_log):- for i in range(10):- data_log.append((env.now, 'queue_length', i % 3))- data_log.append((env.now, 'utilization', (i % 3) / 10))- yield env.timeout(1)+Polling is simple but approximates the state path and adds events:-env = simpy.Environment()-data = []-env.process(monitored_simulation(env, data))-env.run()--export_to_csv(data, 'simulation_data.csv')-print('Data exported to simulation_data.csv')+```python+def poll(env, resource, interval, end, samples):+ while env.now < end:+ samples.append((env.now, resource.count, len(resource.queue)))+ delay = min(interval, end - env.now)+ if delay <= 0:+ return+ yield env.timeout(delay)```-### Real-time Plotting (requires matplotlib)+Never use a zero/negative interval. Polling can miss short peaks. It is suitable+for visualization at a declared resolution, not exact time integrals.-```python-import simpy-import matplotlib.pyplot as plt--class RealTimePlotter:- def __init__(self):- self.times = []- self.values = []-- def update(self, time, value):- self.times.append(time)- self.values.append(value)-- def plot(self, title='Simulation Results'):- plt.figure(figsize=(10, 6))- plt.plot(self.times, self.values)- plt.xlabel('Time')- plt.ylabel('Value')- plt.title(title)- plt.grid(True)- plt.show()--def monitored_process(env, plotter):- value = 0- for i in range(20):- value = value * 0.9 + (i % 5)- plotter.update(env.now, value)- yield env.timeout(1)+## Measurement windows and censoring-env = simpy.Environment()-plotter = RealTimePlotter()-env.process(monitored_process(env, plotter))-env.run()--plotter.plot('Process Value Over Time')-```+At a finite horizon:-## Best Practices+- an entity may arrive but remain queued;+- service may start but not finish;+- a future timeout may remain scheduled;+- numeric `run(until=horizon)` excludes ordinary events exactly at the horizon.-1. **Minimize overhead**: Only monitor what's necessary; excessive logging can slow simulations+Report arrived, admitted, rejected, completed, and unfinished counts. A+completed-only customer mean can be biased when long waits/services are more likely+to be unfinished. Consider a terminating design that drains the system, a+right-censoring-aware estimand, or sensitivity to a longer horizon.-2. **Structured data**: Use classes or named tuples for complex data points+For steady-state replication/deletion, define whether an observation enters the+analysis by arrival time, service-start time, departure time, or time-integral+window. Do not choose after seeing favorable results.-3. **Time-stamping**: Always include timestamps with monitored data+## Monitor non-interference tests-4. **Aggregation**: For long simulations, aggregate data rather than storing every event+For a deterministic miniature model, compare monitored and unmonitored runs:-5. **Lazy evaluation**: Consider collecting raw data and computing statistics after simulation+- same completion order and timestamps;+- same resource counts and outputs;+- same random draws/seed manifest;+- no pending monitor bookkeeping after completion;+- identical exception/interrupt behavior.-6. **Memory management**: For very long simulations, periodically flush data to disk+Also test:-7. **Validation**: Verify monitoring code doesn't affect simulation behavior+- simultaneous request/release;+- cancellation while queued;+- preemption;+- zero queue capacity;+- final interval closure;+- warm-up starting between transitions;+- trace-cap behavior.-8. **Separation of concerns**: Keep monitoring code separate from simulation logic+## Sources-9. **Reusable components**: Create generic monitoring classes that can be reused across simulations+See `sources.md` for the official monitoring, environment, time/scheduling, and+tagged core source links.diff --git a/skills/simpy/references/process-interaction.md b/skills/simpy/references/process-interaction.mdindex 158d0d0a..87b79bfd 100644--- a/skills/simpy/references/process-interaction.md+++ b/skills/simpy/references/process-interaction.md@@ -1,424 +1,269 @@-# SimPy Process Interaction+# Process interaction and interrupts-This guide covers the mechanisms for processes to interact and synchronize in SimPy simulations.+Verified 2026-07-23 against SimPy 4.1.2.-## Interaction Mechanisms Overview+## Processes are event-yielding generators-SimPy provides three primary ways for processes to interact:--1. **Event-based passivation/reactivation** - Shared events for signaling-2. **Waiting for process termination** - Yielding process objects-3. **Interruption** - Forcefully resuming paused processes--## 1. Event-Based Passivation and Reactivation--Processes can share events to coordinate their execution.--### Basic Signal Pattern+A process function must return a generator object. `env.process(generator)` starts+it through an urgent `Initialize` event. The generator executes until it yields an+Event, then resumes with that Event's value or exception.```pythonimport simpy-def controller(env, signal_event):- print(f'Controller: Preparing at {env.now}')- yield env.timeout(5)- print(f'Controller: Sending signal at {env.now}')- signal_event.succeed()--def worker(env, signal_event):- print(f'Worker: Waiting for signal at {env.now}')- yield signal_event- print(f'Worker: Received signal, starting work at {env.now}')- yield env.timeout(3)- print(f'Worker: Work complete at {env.now}')+def operation(env, duration):+ yield env.timeout(duration)+ return {"finished_at": env.now}env = simpy.Environment()-signal = env.event()-env.process(controller(env, signal))-env.process(worker(env, signal))-env.run()+process = env.process(operation(env, 3))+result = env.run(until=process)+assert result == {"finished_at": 3}```-**Use cases:**-- Start signals for coordinated operations-- Completion notifications-- Broadcasting state changes--### Multiple Waiters+Store a `Process` reference when another process must wait for or interrupt it.+`Process` is itself an Event.-Multiple processes can wait for the same signal event.+## Waiting for another process```python-import simpy--def broadcaster(env, signal):- yield env.timeout(5)- print(f'Broadcasting signal at {env.now}')- signal.succeed(value='Go!')--def listener(env, name, signal):- print(f'{name}: Waiting at {env.now}')- msg = yield signal- print(f'{name}: Received "{msg}" at {env.now}')- yield env.timeout(2)- print(f'{name}: Done at {env.now}')--env = simpy.Environment()-broadcast_signal = env.event()+def stage(env, label, duration):+ yield env.timeout(duration)+ return label-env.process(broadcaster(env, broadcast_signal))-for i in range(3):- env.process(listener(env, f'Listener {i+1}', broadcast_signal))+def workflow(env):+ first = env.process(stage(env, "first", 2))+ first_result = yield first-env.run()+ second = env.process(stage(env, "second", 3))+ second_result = yield second+ return first_result, second_result```-### Barrier Synchronization+For parallel activities, create all Processes before yielding:```python-import simpy--class Barrier:- def __init__(self, env, n):- self.env = env- self.n = n- self.count = 0- self.event = env.event()-- def wait(self):- self.count += 1- if self.count >= self.n:- self.event.succeed()- return self.event--def worker(env, barrier, name, work_time):- print(f'{name}: Working at {env.now}')- yield env.timeout(work_time)- print(f'{name}: Reached barrier at {env.now}')- yield barrier.wait()- print(f'{name}: Passed barrier at {env.now}')--env = simpy.Environment()-barrier = Barrier(env, 3)--env.process(worker(env, barrier, 'Worker A', 3))-env.process(worker(env, barrier, 'Worker B', 5))-env.process(worker(env, barrier, 'Worker C', 7))--env.run()+def parallel(env):+ a = env.process(stage(env, "a", 2))+ b = env.process(stage(env, "b", 3))+ results = yield a & b+ assert results[a] == "a"+ assert results[b] == "b"```-## 2. Waiting for Process Termination+Condition results map Event objects to values. Keep the original Process/Event+references.-Processes are events themselves, so you can yield them to wait for completion.+## Shared one-shot events-### Sequential Process Execution+A plain Event can passivate multiple waiters and broadcast one value:```python-import simpy--def task(env, name, duration):- print(f'{name}: Starting at {env.now}')- yield env.timeout(duration)- print(f'{name}: Completed at {env.now}')- return f'{name} result'--def sequential_coordinator(env):- # Execute tasks sequentially- result1 = yield env.process(task(env, 'Task 1', 5))- print(f'Coordinator: {result1}')-- result2 = yield env.process(task(env, 'Task 2', 3))- print(f'Coordinator: {result2}')-- result3 = yield env.process(task(env, 'Task 3', 4))- print(f'Coordinator: {result3}')+def listener(env, signal, log, name):+ value = yield signal+ log.append((name, env.now, value))env = simpy.Environment()-env.process(sequential_coordinator(env))+signal = env.event()+log = []+env.process(listener(env, signal, log, "a"))+env.process(listener(env, signal, log, "b"))+signal.succeed("go")env.run()```-### Parallel Process Execution+Events are one-shot. For repeated signals, replace the shared Event **after**+triggering it and ensure all participants read the same shared attribute:```python-import simpy--def task(env, name, duration):- print(f'{name}: Starting at {env.now}')- yield env.timeout(duration)- print(f'{name}: Completed at {env.now}')- return f'{name} result'--def parallel_coordinator(env):- # Start all tasks- task1 = env.process(task(env, 'Task 1', 5))- task2 = env.process(task(env, 'Task 2', 3))- task3 = env.process(task(env, 'Task 3', 4))-- # Wait for all to complete- results = yield task1 & task2 & task3- print(f'All tasks completed at {env.now}')- print(f'Task 1 result: {task1.value}')- print(f'Task 2 result: {task2.value}')- print(f'Task 3 result: {task3.value}')+class Clock:+ def __init__(self, env):+ self.env = env+ self.tick = env.event()-env = simpy.Environment()-env.process(parallel_coordinator(env))-env.run()+ def pulse(self):+ current = self.tick+ self.tick = self.env.event()+ current.succeed(self.env.now)```-### First-to-Complete Pattern--```python-import simpy--def server(env, name, processing_time):- print(f'{name}: Starting request at {env.now}')- yield env.timeout(processing_time)- print(f'{name}: Completed at {env.now}')- return name--def load_balancer(env):- # Send request to multiple servers- server1 = env.process(server(env, 'Server 1', 5))- server2 = env.process(server(env, 'Server 2', 3))- server3 = env.process(server(env, 'Server 3', 7))-- # Wait for first to respond- result = yield server1 | server2 | server3-- # Get the winner- winner = list(result.values())[0]- print(f'Load balancer: {winner} responded first at {env.now}')--env = simpy.Environment()-env.process(load_balancer(env))-env.run()-```+Passing separate local event variables to two loops and then "resetting" each local+variable creates disconnected signals. Encapsulate ownership.-## 3. Process Interruption+## Interrupt delivery-Processes can be interrupted using `process.interrupt()`, which throws an `Interrupt` exception.+`target_process.interrupt(cause=None)` schedules an urgent `Interruption`. When+processed, it:-### Basic Interruption+1. removes the target process's resume callback from its current target Event;+2. throws `simpy.Interrupt(cause)` into the generator immediately.```python-import simpy--def worker(env):+def worker(env, log):try:- print(f'Worker: Starting long task at {env.now}')yield env.timeout(10)- print(f'Worker: Task completed at {env.now}')+ log.append(("finished", env.now))except simpy.Interrupt as interrupt:- print(f'Worker: Interrupted at {env.now}')- print(f'Interrupt cause: {interrupt.cause}')+ log.append(("interrupted", env.now, interrupt.cause))-def interrupter(env, target_process):- yield env.timeout(5)- print(f'Interrupter: Interrupting worker at {env.now}')- target_process.interrupt(cause='Higher priority task')+def controller(env, target):+ yield env.timeout(3)+ target.interrupt("maintenance")env = simpy.Environment()-worker_process = env.process(worker(env))-env.process(interrupter(env, worker_process))+log = []+worker_process = env.process(worker(env, log))+env.process(controller(env, worker_process))env.run()+assert log == [("interrupted", 3, "maintenance")]```-### Resumable Interruption+Interrupting a terminated process or the currently active process itself raises+`RuntimeError`.-Process can re-yield the same event after interruption to continue waiting.--```python-import simpy+### The target Event is not canceled-def resumable_worker(env):- work_left = 10+An interrupt removes the Process callback from the Event it was yielding; it does+not cancel the Event. The generator can re-yield that same Event:- while work_left > 0:+```python+def temporarily_distracted(env, opening_event):+ while True:try:- print(f'Worker: Working ({work_left} units left) at {env.now}')- start = env.now- yield env.timeout(work_left)- work_left = 0- print(f'Worker: Completed at {env.now}')+ return (yield opening_event)except simpy.Interrupt:- work_left -= (env.now - start)- print(f'Worker: Interrupted! {work_left} units left at {env.now}')+ yield env.timeout(1) # Handle interruption.+ # Loop and wait for the original opening_event again.+```-def interrupter(env, worker_proc):- yield env.timeout(3)- worker_proc.interrupt()- yield env.timeout(2)- worker_proc.interrupt()+If the original Event occurred during handling, yielding it resumes immediately+with its value.-env = simpy.Environment()-worker_proc = env.process(resumable_worker(env))-env.process(interrupter(env, worker_proc))-env.run()-```+Resource request events need an additional decision:-### Interrupt with Custom Cause+- still waiting: re-yield the same request;+- abandoning the wait: call `request.cancel()`;+- already acquired: release it when leaving.-```python-import simpy+Using the resource request as a context manager handles release/cancel on exception+exit.-def machine(env, name):- while True:+## Resumable work++A Timeout cannot be "paused." On interruption, calculate completed work and create+a new Timeout for the remainder:++```python+def resumable_job(env, total_work, log):+ remaining = total_work+ while remaining > 0:+ started = env.nowtry:- print(f'{name}: Operating at {env.now}')- yield env.timeout(5)+ yield env.timeout(remaining)+ remaining = 0except simpy.Interrupt as interrupt:- if interrupt.cause == 'maintenance':- print(f'{name}: Maintenance required at {env.now}')- yield env.timeout(2)- print(f'{name}: Maintenance complete at {env.now}')- elif interrupt.cause == 'emergency':- print(f'{name}: Emergency stop at {env.now}')- break--def maintenance_scheduler(env, machine_proc):- yield env.timeout(7)- machine_proc.interrupt(cause='maintenance')- yield env.timeout(10)- machine_proc.interrupt(cause='emergency')--env = simpy.Environment()-machine_proc = env.process(machine(env, 'Machine 1'))-env.process(maintenance_scheduler(env, machine_proc))-env.run()+ remaining -= env.now - started+ log.append(+ {+ "cause": interrupt.cause,+ "remaining": remaining,+ "time": env.now,+ }+ )```-### Preemptive Resource with Interruption--```python-import simpy+Define whether interrupted setup is lost, retained, or repeated. The code above+assumes linear preempt-resume work.-def user(env, name, resource, priority, duration):- with resource.request(priority=priority) as req:- try:- yield req- print(f'{name} (priority {priority}): Got resource at {env.now}')- yield env.timeout(duration)- print(f'{name}: Done at {env.now}')- except simpy.Interrupt:- print(f'{name}: Preempted at {env.now}')+## PreemptiveResource interrupts-env = simpy.Environment()-resource = simpy.PreemptiveResource(env, capacity=1)+A `PreemptiveResource` generates the interrupt, not application code. The cause is+a `Preempted` record:-env.process(user(env, 'Low priority user', resource, priority=10, duration=10))-env.process(user(env, 'High priority user', resource, priority=1, duration=5))-env.run()+```python+def preemptible(env, resource, priority, work):+ with resource.request(priority=priority, preempt=True) as request:+ try:+ yield request+ yield env.timeout(work)+ except simpy.Interrupt as interrupt:+ cause = interrupt.cause+ print(+ "preempted by",+ cause.by,+ "used since",+ cause.usage_since,+ "resource",+ cause.resource,+ )```-## Advanced Patterns+Do not assume every Interrupt has those attributes; manually generated interrupt+causes can be any object. Use `isinstance(cause, simpy.resources.resource.Preempted)`+when the distinction matters.-### Producer-Consumer with Signaling+## Timeout/renege races```python-import simpy--class Buffer:- def __init__(self, env, capacity):- self.env = env- self.capacity = capacity- self.items = []- self.item_available = env.event()-- def put(self, item):- if len(self.items) < self.capacity:- self.items.append(item)- if not self.item_available.triggered:- self.item_available.succeed()- return True- return False-- def get(self):- if self.items:- return self.items.pop(0)- return None--def producer(env, buffer):- item_id = 0- while True:+def impatient(env, resource, patience):+ with resource.request() as request:+ patience_event = env.timeout(patience)+ result = yield request | patience_event+ if request not in result:+ return {"outcome": "reneged", "time": env.now}yield env.timeout(2)- item = f'Item {item_id}'- if buffer.put(item):- print(f'Producer: Added {item} at {env.now}')- item_id += 1+ return {"outcome": "served", "time": env.now}+```-def consumer(env, buffer):- while True:- if buffer.items:- item = buffer.get()- print(f'Consumer: Retrieved {item} at {env.now}')- yield env.timeout(3)- else:- print(f'Consumer: Waiting for items at {env.now}')- yield buffer.item_available- buffer.item_available = env.event()+At an exact tie, `AnyOf` may contain multiple events that occurred before the+Condition was processed. Decide tie policy explicitly:-env = simpy.Environment()-buffer = Buffer(env, capacity=5)-env.process(producer(env, buffer))-env.process(consumer(env, buffer))-env.run(until=20)+```python+if request in result:+ # This policy treats simultaneous grant/patience as served.+ ...```-### Handshake Protocol+The losing Timeout remains in the queue. The context manager cancels only a pending+request, not arbitrary condition members.-```python-import simpy+## Failure propagation-def sender(env, request_event, acknowledge_event):- for i in range(3):- print(f'Sender: Sending request {i} at {env.now}')- request_event.succeed(value=f'Request {i}')- yield acknowledge_event- print(f'Sender: Received acknowledgment at {env.now}')-- # Reset events for next iteration- request_event = env.event()- acknowledge_event = env.event()- yield env.timeout(1)--def receiver(env, request_event, acknowledge_event):- for i in range(3):- request = yield request_event- print(f'Receiver: Got {request} at {env.now}')- yield env.timeout(2) # Process request- acknowledge_event.succeed()- print(f'Receiver: Sent acknowledgment at {env.now}')-- # Reset for next iteration- request_event = env.event()- acknowledge_event = env.event()+An uncaught process exception fails the Process. A parent yielding that Process+receives the exception:-env = simpy.Environment()-request = env.event()-ack = env.event()-env.process(sender(env, request, ack))-env.process(receiver(env, request, ack))-env.run()-```+```python+def broken(env):+ yield env.timeout(1)+ raise ValueError("model invariant failed")-## Best Practices+def supervisor(env):+ try:+ yield env.process(broken(env))+ except ValueError:+ return "handled"+```-1. **Choose the right mechanism**:- - Use events for signals and broadcasts- - Use process yields for sequential/parallel workflows- - Use interrupts for preemption and emergency handling+Do not broadly suppress failures merely to keep a simulation running. Convert only+expected domain failures into explicit state; let invariant/programming errors fail+tests.-2. **Exception handling**: Always wrap interrupt-prone code in try-except blocks+## Deadlock and liveness checks-3. **Event lifecycle**: Remember that events can only be triggered once; create new events for repeated signaling+`env.run()` returning because the queue is empty does not prove that every intended+process completed. Processes can remain waiting on untriggered events with no future+trigger. Keep references to required completion Processes and run until an explicit+completion Event; if the schedule empties first, SimPy raises `RuntimeError`.-4. **Process references**: Store process objects if you need to interrupt them later+For production models:-5. **Cause information**: Use interrupt causes to communicate why interruption occurred+- set a numeric horizon and event/entity caps;+- count completed and unfinished entities;+- assert conservation of resources/items;+- detect zero-delay recurrence;+- trace a small deterministic scenario before stochastic experiments.-6. **Resumable patterns**: Track progress to enable resumption after interruption+## Sources-7. **Avoid deadlocks**: Ensure at least one process can make progress at any time+See `sources.md` for the versioned Process Interaction, Events, and resource guides+and API references.diff --git a/skills/simpy/references/real-time.md b/skills/simpy/references/real-time.mdindex 70ba789d..8bf321ce 100644--- a/skills/simpy/references/real-time.md+++ b/skills/simpy/references/real-time.md@@ -1,395 +1,174 @@-# SimPy Real-Time Simulations+# Real-time simulation-This guide covers real-time simulation capabilities in SimPy, where simulation time is synchronized with wall-clock time.+Verified 2026-07-23 against SimPy 4.1.2.-## Overview--Real-time simulations synchronize simulation time with actual wall-clock time. This is useful for:--- **Hardware-in-the-loop (HIL)** testing-- **Human interaction** with simulations-- **Algorithm behavior analysis** under real-time constraints-- **System integration** testing-- **Demonstration** purposes--## RealtimeEnvironment--Replace the standard `Environment` with `simpy.rt.RealtimeEnvironment` to enable real-time synchronization.--### Basic Usage+`simpy.rt.RealtimeEnvironment` retains the Event/Process API but delays event+processing so simulation time tracks wall-clock time.```python-import simpy.rt+from simpy.rt import RealtimeEnvironment-def process(env):- while True:- print(f'Tick at {env.now}')- yield env.timeout(1)--# Real-time environment with 1:1 time mapping-env = simpy.rt.RealtimeEnvironment(factor=1.0)-env.process(process(env))-env.run(until=5)-```--### Constructor Parameters--```python-simpy.rt.RealtimeEnvironment(- initial_time=0, # Starting simulation time- factor=1.0, # Real time per simulation time unit- strict=True # Raise errors on timing violations+env = RealtimeEnvironment(+ initial_time=0,+ factor=0.1,+ strict=True,)```-## Time Scaling with Factor+## Parameters-The `factor` parameter controls how simulation time maps to real time.+- `initial_time`: starting simulation clock.+- `factor`: wall-clock seconds per simulation time unit; must be positive.+ - `1.0`: one simulation unit takes one second;+ - `0.1`: one simulation unit takes 0.1 seconds;+ - `60.0`: one simulation unit takes one minute.+- `strict=True`: raise `RuntimeError` when processing falls more than the allotted+ factor behind.-### Factor Examples+`strict=False` suppresses deadline failure. It permits drift; it does not make an+overloaded simulation accurately synchronized.++## Minimal bounded example```python-import simpy.rtimport time+from simpy.rt import RealtimeEnvironment-def timed_process(env, label):- start = time.time()- print(f'{label}: Starting at {env.now}')- yield env.timeout(2)- elapsed = time.time() - start- print(f'{label}: Completed at {env.now} (real time: {elapsed:.2f}s)')--# Factor = 1.0: 1 simulation time unit = 1 second-print('Factor = 1.0 (2 sim units = 2 seconds)')-env = simpy.rt.RealtimeEnvironment(factor=1.0)-env.process(timed_process(env, 'Normal speed'))-env.run()--# Factor = 0.5: 1 simulation time unit = 0.5 seconds-print('\nFactor = 0.5 (2 sim units = 1 second)')-env = simpy.rt.RealtimeEnvironment(factor=0.5)-env.process(timed_process(env, 'Double speed'))-env.run()--# Factor = 2.0: 1 simulation time unit = 2 seconds-print('\nFactor = 2.0 (2 sim units = 4 seconds)')-env = simpy.rt.RealtimeEnvironment(factor=2.0)-env.process(timed_process(env, 'Half speed'))-env.run()-```+def ticker(env, count):+ for index in range(count):+ before = time.monotonic()+ yield env.timeout(1)+ elapsed = time.monotonic() - before+ print(index, env.now, elapsed)-**Factor interpretation:**-- `factor=1.0` → 1 simulation time unit takes 1 real second-- `factor=0.1` → 1 simulation time unit takes 0.1 real seconds (10x faster)-- `factor=60` → 1 simulation time unit takes 60 real seconds (1 minute)+env = RealtimeEnvironment(factor=0.05, strict=True)+process = env.process(ticker(env, count=3))+env.run(until=process)+```-## Strict Mode+Use `time.monotonic()` for elapsed wall time. Calendar time can jump.-### strict=True (Default)+## Strict-mode behavior-Raises `RuntimeError` if computation exceeds allocated real-time budget.+Callbacks and generator code execute synchronously on the simulation thread. Slow+computation, blocking I/O, logging, garbage collection, OS scheduling, and loaded+CI hosts all consume the real-time budget.```python-import simpy.rtimport time+import simpy.rt-def heavy_computation(env):- print(f'Starting computation at {env.now}')+def slow(env):+ time.sleep(0.02)yield env.timeout(1)- # Simulate heavy computation (exceeds 1 second budget)- time.sleep(1.5)-- print(f'Computation done at {env.now}')--env = simpy.rt.RealtimeEnvironment(factor=1.0, strict=True)-env.process(heavy_computation(env))-+env = simpy.rt.RealtimeEnvironment(factor=0.01, strict=True)+env.process(slow(env))try:env.run()-except RuntimeError as e:- print(f'Error: {e}')+except RuntimeError:+ print("simulation missed its real-time budget")```-### strict=False--Allows simulation to run slower than intended without crashing.--```python-import simpy.rt-import time--def heavy_computation(env):- print(f'Starting at {env.now}')- yield env.timeout(1)-- # Heavy computation- time.sleep(1.5)-- print(f'Done at {env.now}')--env = simpy.rt.RealtimeEnvironment(factor=1.0, strict=False)-env.process(heavy_computation(env))-env.run()--print('Simulation completed (slower than real-time)')-```--**Use strict=False when:**-- Development and debugging-- Computation time is unpredictable-- Acceptable to run slower than target rate-- Analyzing worst-case behavior--## Hardware-in-the-Loop Example--```python-import simpy.rt--class HardwareInterface:- """Simulated hardware interface."""-- def __init__(self):- self.sensor_value = 0-- def read_sensor(self):- """Simulate reading from hardware sensor."""- import random- self.sensor_value = random.uniform(20.0, 30.0)- return self.sensor_value-- def write_actuator(self, value):- """Simulate writing to hardware actuator."""- print(f'Actuator set to {value:.2f}')--def control_loop(env, hardware, setpoint):- """Simple control loop running in real-time."""- while True:- # Read sensor- sensor_value = hardware.read_sensor()- print(f'[{env.now}] Sensor: {sensor_value:.2f}°C')-- # Simple proportional control- error = setpoint - sensor_value- control_output = error * 0.1+This `sleep()` intentionally demonstrates a missed deadline. Do not put blocking+sleep in ordinary SimPy process logic to represent simulated delay; use+`env.timeout()`.- # Write actuator- hardware.write_actuator(control_output)+## Appropriate use- # Control loop runs every 0.5 seconds- yield env.timeout(0.5)+Real-time execution is useful when wall-clock synchronization is intrinsic:-# Real-time environment: 1 sim unit = 1 second-env = simpy.rt.RealtimeEnvironment(factor=1.0, strict=False)-hardware = HardwareInterface()-setpoint = 25.0+- hardware- or software-in-the-loop tests;+- human-paced demonstrations;+- interactive controllers;+- adapters to an external system with explicit timing contracts.-env.process(control_loop(env, hardware, setpoint))-env.run(until=5)-```--## Human Interaction Example--```python-import simpy.rt+It is usually inappropriate for Monte Carlo replications: normal `Environment`+runs faster, is less affected by host load, and preserves the same model-time+logic.-def interactive_process(env):- """Process that waits for simulated user input."""- print('Simulation started. Events will occur in real-time.')+## External I/O boundary- yield env.timeout(2)- print(f'[{env.now}] Event 1: System startup')+SimPy itself is single-threaded and does not make external I/O asynchronous.+Integrating devices or services requires an explicit adapter and failure model.+Document:- yield env.timeout(3)- print(f'[{env.now}] Event 2: Initialization complete')+- blocking/nonblocking behavior;+- timeout and retry policy;+- conversion between wall and simulation timestamps;+- thread-safety and event handoff;+- late/out-of-order data behavior;+- shutdown and exception propagation.- yield env.timeout(2)- print(f'[{env.now}] Event 3: Ready for operation')+The bundled skill CLIs intentionally provide no device, network, plugin, or+external-service integration.-# Real-time environment for human-paced demonstration-env = simpy.rt.RealtimeEnvironment(factor=1.0)-env.process(interactive_process(env))-env.run()-```+## Drift measurement-## Monitoring Real-Time Performance+Choose a real origin and compare expected elapsed wall time with actual monotonic+elapsed time:```python-import simpy.rtimport time-class RealTimeMonitor:- def __init__(self):- self.step_times = []- self.drift_values = []-- def record_step(self, sim_time, real_time, expected_real_time):- self.step_times.append(sim_time)- drift = real_time - expected_real_time- self.drift_values.append(drift)-- def report(self):- if self.drift_values:- avg_drift = sum(self.drift_values) / len(self.drift_values)- max_drift = max(abs(d) for d in self.drift_values)- print(f'\nReal-time performance:')- print(f'Average drift: {avg_drift*1000:.2f} ms')- print(f'Maximum drift: {max_drift*1000:.2f} ms')--def monitored_process(env, monitor, start_time, factor):- for i in range(5):- step_start = time.time()- yield env.timeout(1)-- real_elapsed = time.time() - start_time- expected_elapsed = env.now * factor- monitor.record_step(env.now, real_elapsed, expected_elapsed)+origin_real = time.monotonic()+origin_sim = env.now- print(f'Sim time: {env.now}, Real time: {real_elapsed:.2f}s, ' +- f'Expected: {expected_elapsed:.2f}s')--start = time.time()-factor = 1.0-env = simpy.rt.RealtimeEnvironment(factor=factor, strict=False)-monitor = RealTimeMonitor()--env.process(monitored_process(env, monitor, start, factor))-env.run()-monitor.report()+def drift_seconds(env, factor):+ expected = (env.now - origin_sim) * factor+ actual = time.monotonic() - origin_real+ return actual - expected```-## Mixed Real-Time and Fast Simulation+Define sign, sampling instant, percentile, maximum allowed lag, and platform before+testing. A mean near zero can hide large deadline misses.-```python-import simpy.rt--def background_simulation(env):- """Fast background simulation."""- for i in range(100):- yield env.timeout(0.01)- print(f'Background simulation completed at {env.now}')--def real_time_display(env):- """Real-time display updates."""- for i in range(5):- print(f'Display update at {env.now}')- yield env.timeout(1)--# Note: This is conceptual - SimPy doesn't directly support mixed modes-# Consider running separate simulations or using strict=False-env = simpy.rt.RealtimeEnvironment(factor=1.0, strict=False)-env.process(background_simulation(env))-env.process(real_time_display(env))-env.run()-```+## Testing strategy-## Converting Standard to Real-Time+1. Test model logic with normal `Environment`.+2. Test deterministic ordering and interrupts independently of wall time.+3. Keep real-time tests short and separately marked.+4. Use `time.monotonic()` and broad platform-aware bounds.+5. Test both `strict=True` deadline detection and intentional `strict=False` lag.+6. Avoid exact-duration assertions.+7. Record Python/SimPy version, OS, architecture, host load assumptions, and factor.-Converting a standard simulation to real-time is straightforward:+Example tolerant assertion:```python-import simpy-import simpy.rt--def process(env):- print(f'Event at {env.now}')- yield env.timeout(1)- print(f'Event at {env.now}')- yield env.timeout(1)- print(f'Event at {env.now}')--# Standard simulation (runs instantly)-print('Standard simulation:')-env = simpy.Environment()-env.process(process(env))-env.run()--# Real-time simulation (2 real seconds)-print('\nReal-time simulation:')-env_rt = simpy.rt.RealtimeEnvironment(factor=1.0)-env_rt.process(process(env_rt))-env_rt.run()+start = time.monotonic()+env = RealtimeEnvironment(factor=0.02, strict=False)+env.run(until=env.timeout(2))+elapsed = time.monotonic() - start+assert elapsed >= 0.02+assert elapsed < 1.0```-## Best Practices--1. **Factor selection**: Choose factor based on hardware/human constraints- - Human interaction: `factor=1.0` (1:1 time mapping)- - Fast hardware: `factor=0.01` (100x faster)- - Slow processes: `factor=60` (1 sim unit = 1 minute)+The upper bound is deliberately generous; tune it for controlled hardware, not a+busy shared runner.-2. **Strict mode usage**:- - Use `strict=True` for timing validation- - Use `strict=False` for development and variable workloads+## Boundaries and stopping-3. **Computation budget**: Ensure process logic executes faster than timeout duration+Real-time environments inherit `Environment.run()` semantics:-4. **Error handling**: Wrap real-time runs in try-except for timing violations+- no `until` can run forever;+- numeric `until` excludes normal events at the boundary;+- Event `until` returns the Event value;+- `peek()`/`step()` remain available.-5. **Testing strategy**:- - Develop with standard Environment (fast iteration)- - Test with RealtimeEnvironment (validation)- - Deploy with appropriate factor and strict settings+Always bound real-time runs. A tiny factor combined with a huge event count can+still consume substantial CPU, and a huge factor can make a short model wait for a+long wall duration.-6. **Performance monitoring**: Track drift between simulation and real time--7. **Graceful degradation**: Use `strict=False` when timing guarantees aren't critical--## Common Patterns--### Periodic Real-Time Tasks--```python-import simpy.rt--def periodic_task(env, name, period, duration):- """Task that runs periodically in real-time."""- while True:- start = env.now- print(f'{name}: Starting at {start}')-- # Simulate work- yield env.timeout(duration)-- print(f'{name}: Completed at {env.now}')-- # Wait for next period- elapsed = env.now - start- wait_time = period - elapsed- if wait_time > 0:- yield env.timeout(wait_time)--env = simpy.rt.RealtimeEnvironment(factor=1.0)-env.process(periodic_task(env, 'Task', period=2.0, duration=0.5))-env.run(until=6)-```--### Synchronized Multi-Device Control--```python-import simpy.rt--def device_controller(env, device_id, update_rate):- """Control loop for individual device."""- while True:- print(f'Device {device_id}: Update at {env.now}')- yield env.timeout(update_rate)--# All devices synchronized to real-time-env = simpy.rt.RealtimeEnvironment(factor=1.0)+## Limitations-# Different update rates for different devices-env.process(device_controller(env, 'A', 1.0))-env.process(device_controller(env, 'B', 0.5))-env.process(device_controller(env, 'C', 2.0))+- Wall-clock results are not bit-for-bit timing reproducible across hosts.+- Python/OS timer granularity and scheduling affect jitter.+- One slow callback delays all later events.+- Real-time synchronization does not make simulated processes parallel.+- `strict=False` can accumulate unbounded lag.+- Real-time agreement is not model validation.-env.run(until=5)-```--## Limitations+## Sources-1. **Performance**: Real-time simulation adds overhead; not suitable for high-frequency events-2. **Synchronization**: Single-threaded; all processes share same time base-3. **Precision**: Limited by Python's time resolution and system scheduling-4. **Strict mode**: May raise errors frequently with computationally intensive processes-5. **Platform-dependent**: Timing accuracy varies across operating systems+See `sources.md` for the 4.1.2 real-time topical guide and `simpy.rt` API.diff --git a/skills/simpy/references/resources.md b/skills/simpy/references/resources.mdindex 6a12543e..a5c5d9f7 100644--- a/skills/simpy/references/resources.md+++ b/skills/simpy/references/resources.md@@ -1,275 +1,274 @@-# SimPy Shared Resources+# Shared resources-This guide covers all resource types in SimPy for modeling congestion points and resource allocation.+Verified 2026-07-23 against SimPy 4.1.2.-## Resource Types Overview+All resource operations return Events. An operation that cannot complete waits in+the corresponding queue; yielding the Event suspends the process. Resource events+are context managers so exception/interrupt unwinding can release an acquired+request or cancel a pending operation.-SimPy provides three main categories of shared resources:+## Choose by modeled quantity-1. **Resources** - Limited capacity resources (e.g., gas pumps, servers)-2. **Containers** - Homogeneous bulk materials (e.g., fuel tanks, silos)-3. **Stores** - Python object storage (e.g., item queues, warehouses)+| Primitive | Modeled state | Waiting operation |+|---|---|---|+| `Resource` | limited concurrent users | `request()` |+| `PriorityResource` | users plus priority queue | `request(priority=...)` |+| `PreemptiveResource` | priority users that may be displaced | `request(..., preempt=...)` |+| `Container` | homogeneous numeric level | `put(amount)`, `get(amount)` |+| `Store` | FIFO concrete objects | `put(item)`, `get()` |+| `FilterStore` | objects selected by predicate | `get(filter)` |+| `PriorityStore` | comparable/priority-wrapped objects | `put(item)`, `get()` |-## 1. Resources+These primitives implement synchronization and congestion. They do not decide+whether a queue discipline or capacity assumption is valid for the real system.-Model resources that can be used by a limited number of processes at a time.+## Resource-### Resource (Basic)+`Resource(env, capacity=1)` is semaphore-like. `capacity` must be positive.+Observable state:-The basic resource is a semaphore with specified capacity.+- `count`: allocated slots;+- `users`: granted request events;+- `queue`: pending request events;+- `capacity`: maximum simultaneous users.```pythonimport simpy+def user(env, resource, duration):+ with resource.request() as request:+ yield request+ yield env.timeout(duration)+env = simpy.Environment()-resource = simpy.Resource(env, capacity=2)--def process(env, resource, name):- with resource.request() as req:- yield req- print(f'{name} has the resource at {env.now}')- yield env.timeout(5)- print(f'{name} releases the resource at {env.now}')--env.process(process(env, resource, 'Process 1'))-env.process(process(env, resource, 'Process 2'))-env.process(process(env, resource, 'Process 3'))+server = simpy.Resource(env, capacity=2)+for duration in (2, 3, 4):+ env.process(user(env, server, duration))env.run()```-**Key properties:**-- `capacity` - Maximum number of concurrent users (default: 1)-- `count` - Current number of users-- `queue` - List of queued requests--### PriorityResource--Extends basic resource with priority levels (lower numbers = higher priority).+The context manager calls `release(request)` after an acquired request and+`cancel()` for an abandoned pending request. With manual management, always release+the exact request token:```python-import simpy--env = simpy.Environment()-resource = simpy.PriorityResource(env, capacity=1)--def process(env, resource, name, priority):- with resource.request(priority=priority) as req:- yield req- print(f'{name} (priority {priority}) has the resource at {env.now}')- yield env.timeout(5)--env.process(process(env, resource, 'Low priority', priority=10))-env.process(process(env, resource, 'High priority', priority=1))-env.run()+request = resource.request()+try:+ yield request+ yield env.timeout(2)+finally:+ if request in resource.users:+ resource.release(request)+ elif not request.triggered:+ request.cancel()```-**Use cases:**-- Emergency services (ambulances before regular vehicles)-- VIP customer queues-- Job scheduling with priorities+`release()` succeeds immediately, even if passed a request that is not a current+user; such a call does not make the model logically correct. Prefer the context+manager.-### PreemptiveResource+## PriorityResource-Allows high-priority requests to interrupt lower-priority users.+`PriorityResource` orders pending `PriorityRequest`s by smaller numeric priority,+then request time. Equal-priority, equal-time ties use deterministic scheduler/queue+ordering.```python-import simpy+def prioritized(env, resource, name, priority):+ with resource.request(priority=priority) as request:+ yield request+ print(name, "started", env.now)+ yield env.timeout(2)env = simpy.Environment()-resource = simpy.PreemptiveResource(env, capacity=1)--def process(env, resource, name, priority):- with resource.request(priority=priority) as req:- try:- yield req- print(f'{name} acquired resource at {env.now}')- yield env.timeout(10)- print(f'{name} finished at {env.now}')- except simpy.Interrupt:- print(f'{name} was preempted at {env.now}')--env.process(process(env, resource, 'Low priority', priority=10))-env.process(process(env, resource, 'High priority', priority=1))+resource = simpy.PriorityResource(env, capacity=1)+env.process(prioritized(env, resource, "routine", 10))+env.process(prioritized(env, resource, "urgent", 0))env.run()```-**Use cases:**-- Operating system CPU scheduling-- Emergency room triage-- Network packet prioritization+Priority does not preempt a current user. A later high-priority request only+overtakes queued lower-priority requests.++## PreemptiveResource-## 2. Containers+`PreemptiveResource` extends `PriorityResource`. A request accepts:-Model production and consumption of homogeneous bulk materials (continuous or discrete).+- `priority`: lower number means higher priority;+- `preempt=True`: permit displacement of a lower-priority current user.```python-import simpy+def task(env, resource, name, priority, duration):+ with resource.request(priority=priority, preempt=True) as request:+ try:+ yield request+ started = env.now+ yield env.timeout(duration)+ except simpy.Interrupt as interrupt:+ cause = interrupt.cause+ used = env.now - cause.usage_since+ print(name, "preempted by", cause.by.name, "after", used)env = simpy.Environment()-container = simpy.Container(env, capacity=100, init=50)--def producer(env, container):- while True:- yield env.timeout(5)- yield container.put(20)- print(f'Produced 20. Level: {container.level}')--def consumer(env, container):- while True:- yield env.timeout(7)- yield container.get(15)- print(f'Consumed 15. Level: {container.level}')--env.process(producer(env, container))-env.process(consumer(env, container))-env.run(until=50)+cpu = simpy.PreemptiveResource(env, capacity=1)+env.process(task(env, cpu, "background", 5, 10))++def urgent(env):+ yield env.timeout(2)+ yield env.process(task(env, cpu, "urgent", 0, 1))++env.process(urgent(env))+env.run()```-**Key properties:**-- `capacity` - Maximum amount (default: float('inf'))-- `level` - Current amount-- `init` - Initial amount (default: 0)+The preempted process receives `simpy.Interrupt`. Its `cause` is+`simpy.resources.resource.Preempted`:-**Operations:**-- `put(amount)` - Add to container (blocks if full)-- `get(amount)` - Remove from container (blocks if insufficient)+- `cause.by`: Process that made the preempting request;+- `cause.usage_since`: time the displaced request began using the resource;+- `cause.resource`: resource involved.-**Use cases:**-- Gas station fuel tanks-- Buffer storage in manufacturing-- Water reservoirs-- Battery charge levels+The timeout representing interrupted work is not canceled; the process's callback+is removed from it. Track completed work and schedule a new timeout to resume.-## 3. Stores+Priority outranks the preempt flag. A queued request with higher priority and+`preempt=False` can prevent a lower-priority preempting request from displacing a+user. Do not mix policies without a tested discipline specification.-Model production and consumption of Python objects.+## Container-### Store (Basic)+`Container(env, capacity=float("inf"), init=0)` models homogeneous matter. Current+state is `level`.-Generic FIFO object storage.+- `put(amount)` waits until `level + amount <= capacity`;+- `get(amount)` waits until `level >= amount`;+- amounts must be strictly positive;+- `0 <= init <= capacity`.```python-import simpy-env = simpy.Environment()-store = simpy.Store(env, capacity=2)+tank = simpy.Container(env, capacity=100, init=40)-def producer(env, store):- for i in range(5):- yield env.timeout(2)- item = f'Item {i}'- yield store.put(item)- print(f'Produced {item} at {env.now}')--def consumer(env, store):- while True:- yield env.timeout(3)- item = yield store.get()- print(f'Consumed {item} at {env.now}')--env.process(producer(env, store))-env.process(consumer(env, store))+def transfer(env):+ yield tank.put(30)+ assert tank.level == 70+ yield tank.get(20)+ assert tank.level == 50++env.process(transfer(env))env.run()```-**Key properties:**-- `capacity` - Maximum number of items (default: float('inf'))-- `items` - List of stored items+Pending operations are visible through `put_queue` and `get_queue`. A blocked put+or get can deadlock the model if no future process can change the level. Bound+execution and assert conservation:-**Operations:**-- `put(item)` - Add item to store (blocks if full)-- `get()` - Remove and return item (blocks if empty)+`initial + completed_puts - completed_gets == final_level`.-### FilterStore+## Store-Allows retrieval of specific objects based on filter functions.+`Store(env, capacity=float("inf"))` holds concrete Python objects. `put(item)` waits+when full; `get()` waits when empty. Available objects are in `items`; pending+operations are in `put_queue` and `get_queue`.```python-import simpy-env = simpy.Environment()-store = simpy.FilterStore(env, capacity=10)+buffer = simpy.Store(env, capacity=2)-def producer(env, store):- for color in ['red', 'blue', 'green', 'red', 'blue']:- yield env.timeout(1)- yield store.put({'color': color, 'time': env.now})- print(f'Produced {color} item at {env.now}')+def producer(env):+ for item in ("a", "b", "c"):+ yield buffer.put(item)-def consumer(env, store, color):- while True:- yield env.timeout(2)- item = yield store.get(lambda x: x['color'] == color)- print(f'{color} consumer got item from {item["time"]} at {env.now}')+def consumer(env):+ for _ in range(3):+ item = yield buffer.get()+ print(item)-env.process(producer(env, store))-env.process(consumer(env, store, 'red'))-env.process(consumer(env, store, 'blue'))-env.run(until=15)+env.process(producer(env))+env.process(consumer(env))+env.run()```-**Use cases:**-- Warehouse item picking (specific SKUs)-- Job queues with skill matching-- Packet routing by destination+Store is FIFO for available items and ordinary pending requests.-### PriorityStore+## FilterStore-Items retrieved in priority order (lowest first).+`FilterStore.get(predicate)` takes the first available item for which the predicate+returns truthy:```python-import simpy+env = simpy.Environment()+machines = simpy.FilterStore(env, capacity=2)+machines.items = [+ {"id": "small", "size": 1},+ {"id": "large", "size": 2},+]++def borrow_large(env):+ machine = yield machines.get(lambda item: item["size"] >= 2)+ yield env.timeout(1)+ yield machines.put(machine)++env.process(borrow_large(env))+env.run()+```++Unlike a plain FIFO get queue, a later FilterStore request can complete before an+earlier request when only the later predicate matches. Predicates execute inside+resource processing: keep them deterministic, fast, side-effect-free, and defined+in trusted model code. The bundled JSON CLIs do not accept predicate code.-class PriorityItem:- def __init__(self, priority, data):- self.priority = priority- self.data = data+## PriorityStore- def __lt__(self, other):- return self.priority < other.priority+`PriorityStore` returns the smallest item according to comparison. Prefer+`simpy.PriorityItem(priority, item)` so payloads need not be comparable:+```pythonenv = simpy.Environment()-store = simpy.PriorityStore(env, capacity=10)--def producer(env, store):- items = [(10, 'Low'), (1, 'High'), (5, 'Medium')]- for priority, name in items:- yield env.timeout(1)- yield store.put(PriorityItem(priority, name))- print(f'Produced {name} priority item')--def consumer(env, store):- while True:- yield env.timeout(5)- item = yield store.get()- print(f'Retrieved {item.data} priority item')--env.process(producer(env, store))-env.process(consumer(env, store))+work = simpy.PriorityStore(env)++def schedule(env):+ yield work.put(simpy.PriorityItem(10, "routine"))+ yield work.put(simpy.PriorityItem(1, "urgent"))+ first = yield work.get()+ assert first.item == "urgent"++env.process(schedule(env))env.run()```-**Use cases:**-- Task scheduling-- Print job queues-- Message prioritization--## Choosing the Right Resource Type--| Scenario | Resource Type |-|----------|---------------|-| Limited servers/machines | Resource |-| Priority-based queuing | PriorityResource |-| Preemptive scheduling | PreemptiveResource |-| Fuel, water, bulk materials | Container |-| Generic item queue (FIFO) | Store |-| Selective item retrieval | FilterStore |-| Priority-ordered items | PriorityStore |--## Best Practices--1. **Capacity planning**: Set realistic capacities based on system constraints-2. **Request patterns**: Use context managers (`with resource.request()`) for automatic cleanup-3. **Error handling**: Wrap preemptive resources in try-except for Interrupt handling-4. **Monitoring**: Track queue lengths and utilization (see monitoring.md)-5. **Performance**: FilterStore and PriorityStore have O(n) retrieval time; use wisely for large stores+Equal-priority payloads preserve the wrapper's comparison behavior; if business+policy requires a specific tie-breaker, include one explicitly in a comparable+dataclass/tuple and test it.++## Waiting, cancellation, and reneging++Use a condition to race a request against patience:++```python+def customer(env, resource, patience):+ with resource.request() as request:+ result = yield request | env.timeout(patience)+ if request not in result:+ return "reneged" # Pending request canceled on context exit.+ yield env.timeout(2)+ return "served"+```++If retaining resource events outside a context manager:++- re-yield after a temporary interrupt if still waiting;+- call `cancel()` when permanently abandoning a pending put/get/request;+- release only an acquired Resource request;+- account for losing timeouts that remain in the event queue.++## Monitoring caveat++Resource state may change synchronously when an operation is created and again when+its callbacks are processed. Label whether a sample is pre-call, post-call, grant,+release, or final. Time-weight state paths; do not average event samples. See+`monitoring.md`.++## Sources++See `sources.md` for the 4.1.2 shared-resource guide and API reference.diff --git a/skills/simpy/references/simulation-methodology.md b/skills/simpy/references/simulation-methodology.mdnew file mode 100644index 00000000..b4fc1170--- /dev/null+++ b/skills/simpy/references/simulation-methodology.md@@ -0,0 +1,293 @@+# Simulation-study methodology (not SimPy API)++Verified 2026-07-23. This guide applies established discrete-event simulation+methods to SimPy models. SimPy schedules events; it does not perform these study+design decisions automatically.++## 1. Start with the conceptual model++Before code, specify:++- purpose, decision context, stakeholders, and intended domain;+- system boundary, entities, resources, queues, routes, state, and termination;+- input data provenance and fitted/assumed distributions;+- initial conditions and time units;+- performance measures/estimands;+- assumptions, simplifications, exclusions, and known limits;+- required accuracy and validation evidence.++Robinson defines conceptual modeling as abstraction from a real or proposed system+and emphasizes validity, credibility, utility, feasibility, and the simplest model+adequate for purpose. Sargent frames validity relative to the intended application+and domain, not as a universal property.++Use a unit table:++| Quantity | Unit | Convention |+|---|---|---|+| `env.now` | minutes | starts at opening |+| interarrival | minutes/entity | strictly positive |+| service | minutes | sampled at service start |+| throughput | entities/hour | convert from minute horizon |++SimPy time is unitless. Unit inconsistency can produce a perfectly executable but+invalid model.++## 2. Terminating versus steady-state studies++### Terminating++A terminating simulation has a natural, predeclared endpoint: closing time,+completion of an order, end of a mission, or another event relevant to the purpose.+Initial conditions are part of the estimand and should normally be identical across+replications.++Decide how to handle entities still present at a fixed clock horizon:++- stop and report/censor unfinished paths;+- stop arrivals at closing but drain the system;+- terminate on an explicit completion event.++These answer different questions. Numeric `env.run(until=horizon)` is half-open and+does not drain.++### Nonterminating / steady state++A nonterminating system has no natural endpoint and targets a long-run parameter.+Arbitrary initialization creates transient bias. A finite warm-up deletion may+reduce that bias, but neither a warm-up nor a long run proves stationarity or+convergence.++Use a declared replication/deletion design:++1. estimate/justify warm-up in a pilot study;+2. make independent production replications;+3. apply the same deletion rule to each;+4. make the post-deletion run much longer than warm-up;+5. assess sensitivity to longer warm-up and run length.++Do not label a finite-horizon operating-day model "steady state" merely because it+has many events.++## 3. Random seeds and streams++Pseudo-random generation is deterministic given algorithm, state, and consumption+order. Reproducibility requires recording:++- RNG implementation and Python/package versions;+- base seed and derived per-replication seeds;+- mapping of streams to stochastic sources;+- replication index and configuration;+- any common-random-number pairing.++Use separate local RNG objects for distinct sources:++```python+arrival_rng = random.Random(arrival_seed)+service_rng = random.Random(service_seed)+```++Avoid module-global `random.seed()` in reusable models: unrelated code can consume+or reset the shared stream.++L'Ecuyer recommends independent streams/substreams, often one stream per stochastic+source and one substream per replication. Distinct hash-derived seeds, as used by+the bundled scripts, provide deterministic separation for a compact standard-library+example; they do **not** mathematically prove stream independence. For high-stakes+or large parallel experiments, use a generator/package with explicit tested stream+and jump/substream facilities and document it.++### Common random numbers++For paired alternatives, intentionally using the same source-specific random+numbers can reduce variance of differences. Keep replication pairs aligned and use+separate source streams so a demand draw in one alternative does not become a+service draw in another. Analyze paired replication differences. Common random+numbers are a designed variance-reduction method, not independent streams across+alternatives.++## 4. Independent replications++Within-run entity outcomes are usually dependent: customers share queues and system+state. The basic independent unit is a complete replication using an independent+stream set.++For each replication:++- reset model state and statistical counters;+- use the same scenario/configuration and intended initial-condition rule;+- use new independent random streams;+- produce one estimate per performance measure.++Law's output-analysis tutorial stresses that one run does not produce "the answer."+Use at least two replications to estimate variance; practical counts should be+chosen from desired precision, distribution shape, computational cost, and a pilot,+not a universal magic number.++The bundled replication runner caps counts and records every derived seed. It does+not automatically choose a sufficient replication count.++## 5. Confidence intervals++Given independent replication estimates `X_1, ..., X_n`, a common two-sided+Student-t interval for their mean is:++`mean(X) +/- t_(n-1, 1-alpha/2) * s(X) / sqrt(n)`.++State:++- estimand and unit;+- number of independent replications;+- confidence level and method;+- point estimate, interval, and half-width;+- warm-up/run length and missing/unfinished handling.++Conditions and caveats:++- replication estimates must be independent and comparably generated;+- the t interval is exact under normal replication estimates and approximate under+ suitable large-sample behavior;+- a tiny `n` gives unstable variance and distribution diagnostics;+- a narrow interval around a biased/invalid model result is still wrong;+- optional stopping based on observed precision needs a valid sequential procedure.++### Never make a naive single-run CI++Do not feed all customer waits from one run to an IID t interval. Positive serial+dependence can severely understate variance. Law (2020) illustrates dramatic+undercoverage from this approach.++For one long steady-state run, use a justified output-analysis method such as batch+means, spectral methods, or regenerative analysis with diagnostics. The bundled+CLI deliberately implements independent replications, not a naive single-run CI.++## 6. Warm-up and transient bias++Warm-up is an estimand/study-design issue, not an `Environment` option. SimPy has no+automatic steady-state detector.++Good practice:++- reason from initial conditions and system dynamics;+- inspect multiple pilot replications, not one noisy path;+- use an established rule (for example Welch-type graphical analysis or a+ documented method);+- separate pilot selection from production inference;+- use the same declared deletion in production runs;+- examine sensitivity to longer warm-up and run length;+- report discarded observations/time and window membership rule.++Schruben developed tests for initialization bias; Robinson and Hoad et al. developed+warm-up selection procedures. No method makes every model stationary, and visual+flattening is not proof.++Choose the measurement-window rule before analysis:++- arrivals after warm-up;+- departures after warm-up;+- entities entirely contained after warm-up;+- time integral clipped to `[warm_up, horizon)`.++These estimate different quantities. The bundled queue scripts use completed+entities whose arrival is at or after warm-up plus clipped time-weighted resource+metrics, and disclose unfinished entities.++## 7. Verification and validation++Sargent distinguishes:++- **conceptual model validity** — assumptions/theories and representation are+ reasonable for intended purpose;+- **computerized model verification** — implementation matches the conceptual+ model;+- **operational validation** — outputs have sufficient accuracy over the intended+ domain;+- **data validity** — data are adequate and correct for building/testing/running.++### Verification++Use:++- deterministic traces and event-order assertions;+- conservation/balance identities;+- extreme and degenerate cases;+- analytical queue benchmarks where assumptions match;+- independent implementation or hand calculations;+- tests for resource release, cancellation, preemption, and deadlock;+- monitor-on versus monitor-off equivalence.++Passing tests establishes implementation evidence, not real-world validity.++### Validation++Use evidence appropriate to purpose:++- subject-matter expert face validation;+- historical/holdout system data;+- graphical and statistical comparison of system/model behavior;+- predictive validation when future observations become available;+- comparison with accepted models;+- traces/animations for logic review;+- parameter variability and sensitivity analysis.++Predeclare acceptable accuracy where possible. Validation is iterative and+domain-specific; failure in a required operating condition invalidates use there.++## 8. Sensitivity and uncertainty++Vary uncertain inputs, structural assumptions, warm-up, run length, capacities,+queue discipline, and initial conditions over defensible ranges. Preserve paired+random streams for alternative comparisons when intentionally using common random+numbers.++Separate:++- **Monte Carlo uncertainty** — finite replications;+- **parameter uncertainty** — uncertain input values/distributions;+- **structural uncertainty** — alternate model logic/boundaries;+- **validation discrepancy** — model versus system;+- **scenario uncertainty** — different future conditions.++A replication CI addresses only the first under the configured model.++## 9. Reproducibility and reporting++The STRESS-DES guidelines organize complete reporting around objectives, model+logic, data, experimentation, implementation, and code access. At minimum retain:++- conceptual model and assumptions;+- exact config and input-data provenance;+- SimPy/Python versions and environment lock/pin;+- source revision;+- seed/stream manifest;+- warm-up, horizon, entity/event caps, and replications;+- metric definitions and unit conversions;+- validation/sensitivity evidence;+- raw replication-level outputs and analysis code.++Reproducibility of the program is not validity of the model.++## 10. No causal claims from a queue simulation alone++A simulation computes implications of encoded assumptions. Changing a parameter+and observing an output difference is a **model-based scenario contrast**, not an+identified causal effect in the real system. Causal language requires defensible+causal assumptions/design, calibrated interventions, and validation beyond SimPy.++Use phrasing such as:++> Under the specified arrival, service, routing, and capacity assumptions, the+> simulated scenario produced ...++## Primary method sources++- [Law, "Statistical Analysis of Simulation Output Data," WSC 2020](https://informs-sim.org/wsc20papers/134.pdf)+- [L'Ecuyer, "Random Number Generation with Multiple Streams," WSC 2015](https://informs-sim.org/wsc15papers/003.pdf)+- [Sargent, "Verification and Validation of Simulation Models," WSC 2010](https://www.informs-sim.org/wsc10papers/016.pdf)+- [Robinson, "Conceptual Modelling for Simulation Part I," 2008](https://doi.org/10.1057/palgrave.jors.2602368)+- [Schruben, "Detecting Initialization Bias," 1982](https://doi.org/10.1287/opre.30.3.569)+- [Robinson, warm-up selection, 2007](https://ideas.repec.org/a/eee/ejores/v176y2007i1p332-346.html)+- [Hoad, Robinson, Davies, replication selection, 2010](https://doi.org/10.1057/jors.2009.121)+- [Monks et al., STRESS guidelines, 2018](https://doi.org/10.1080/17477778.2018.1442155)++See `sources.md` for full dated notes.diff --git a/skills/simpy/references/sources.md b/skills/simpy/references/sources.mdnew file mode 100644index 00000000..dfc6e60b--- /dev/null+++ b/skills/simpy/references/sources.md@@ -0,0 +1,167 @@+# Sources and verification record++Research completed **2026-07-23** with `parallel-cli search` and+`parallel-cli extract`, then checked against an isolated installation of+`simpy==4.1.2`. Versioned documentation is preferred over the `latest` build,+which showed a 4.1.2 development revision during verification.++## Release, packaging, and source++- [SimPy on PyPI](https://pypi.org/project/simpy/) — **4.1.2**, released+ **2026-05-24**; `Requires-Python >=3.8`; classifiers list Python 3.8-3.14,+ CPython, and PyPy; MIT; no runtime dependencies. Verified 2026-07-23.+- [GitLab source project](https://gitlab.com/team-simpy/simpy/) — canonical+ repository, MIT license, tagged source, tests, and documentation. Accessed+ 2026-07-23.+- [GitLab tag 4.1.2](https://gitlab.com/team-simpy/simpy/-/tags/4.1.2) —+ protected/verified tag, commit `f43816490c6f76f336ad6e457d3cab9f386894af`,+ dated **2026-05-24**.+- [Tagged CHANGES.rst](https://gitlab.com/team-simpy/simpy/-/blob/4.1.2/CHANGES.rst)+ — 4.1.2 entry dated **2026-05-23**: Python 3.13/3.14 support,+ modern-interpreter test/doc fixes, `ConditionValue` explicitly unhashable,+ lint/type cleanup.+- [Tagged pyproject.toml](https://gitlab.com/team-simpy/simpy/-/blob/4.1.2/pyproject.toml)+ — Python requirement/classifiers, no dependencies, setuptools build, pytest,+ mypy, and ruff configuration. Dated 2026-05-23; accessed 2026-07-23.+- [Tagged tox.ini](https://gitlab.com/team-simpy/simpy/-/blob/4.1.2/tox.ini) and+ [tagged tests](https://gitlab.com/team-simpy/simpy/-/tree/4.1.2/tests) —+ upstream test matrix and behavior tests. Accessed 2026-07-23.+- [Tagged `simpy/core.py`](https://gitlab.com/team-simpy/simpy/-/blob/4.1.2/src/simpy/core.py)+ — authoritative `Environment.run()`, `step()`, queue tuple, and+ `StopSimulation` implementation. Accessed 2026-07-23.++PyPI file hashes observed 2026-07-23:++- wheel `simpy-4.1.2-py3-none-any.whl` SHA-256+ `43071f84b6512c9b4fcb33ef057f240ccb1d1f3b263f9b4f9229d072e310b372`;+- sdist `simpy-4.1.2.tar.gz` SHA-256+ `76ef36b71e0436ba94e55febc001c78879e493a323f045bbcfbb0b216e9b1fbc`.++Use the pinned package command in `SKILL.md`; hashes are recorded for provenance,+not embedded into `uv pip install` syntax.++## Official SimPy 4.1.2 documentation++### Entry points++- [4.1.2 documentation contents](https://simpy.readthedocs.io/en/4.1.2/contents.html)+- [4.1.2 tutorial](https://simpy.readthedocs.io/en/4.1.2/simpy_intro/index.html)+- [4.1.2 topical guides](https://simpy.readthedocs.io/en/4.1.2/topical_guides/index.html)+- [4.1.2 examples](https://simpy.readthedocs.io/en/4.1.2/examples/index.html)+- [4.1.2 API reference](https://simpy.readthedocs.io/en/4.1.2/api_reference/index.html)+- [history/change log](https://simpy.readthedocs.io/en/4.1.2/about/history.html)+- [license](https://simpy.readthedocs.io/en/4.1.2/about/license.html)++All accessed 2026-07-23. The examples index covers condition events, interrupts,+Resource, PreemptiveResource, Container, Store, shared events, and process waiting.++### Core topical guides++- [SimPy basics](https://simpy.readthedocs.io/en/4.1.2/topical_guides/simpy_basics.html)+- [Environments](https://simpy.readthedocs.io/en/4.1.2/topical_guides/environments.html)+- [Events](https://simpy.readthedocs.io/en/4.1.2/topical_guides/events.html)+- [Process Interaction](https://simpy.readthedocs.io/en/4.1.2/topical_guides/process_interaction.html)+- [Shared Resources](https://simpy.readthedocs.io/en/4.1.2/topical_guides/resources.html)+- [Monitoring](https://simpy.readthedocs.io/en/4.1.2/topical_guides/monitoring.html)+- [Time and Scheduling](https://simpy.readthedocs.io/en/4.1.2/topical_guides/time_and_scheduling.html)+- [Real-time simulations](https://simpy.readthedocs.io/en/4.1.2/topical_guides/real-time-simulations.html)++All accessed 2026-07-23.++### API pages++- [`simpy.core`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.core.html)+ — `Environment`, `run`, `schedule`, `peek`, `step`, `EmptySchedule`.+- [`simpy.events`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.events.html)+ — `Event`, `Timeout`, `Process`, `Condition`, `AnyOf`, `AllOf`, priorities.+- [`simpy.exceptions`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.exceptions.html)+ — `Interrupt`.+- [`simpy.resources`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.resources.html)+ — Resource/Priority/Preemptive, Container, Store/Filter/Priority, base events.+- [`simpy.rt`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.rt.html)+ — `RealtimeEnvironment`.+- [`simpy.util`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.util.html)+ — helper processes.++All accessed 2026-07-23.++## Source-level semantic finding++The 4.1.2 Environments topical guide informally says Event-based `run()` returns+when the Event has been processed. The 4.1.2 API docstring says "triggered."+Tagged `core.py` is decisive:++- `run(until=event)` appends `StopSimulation.callback`;+- `step()` sets callbacks to `None`, executes them, catches `StopSimulation`,+ restores callbacks remaining after the stopping callback, and reschedules that+ Event at priority `-1`.++Therefore the target value can be returned while `target.processed` is still false,+until one more step processes the rescheduled empty-callback Event. This was+reproduced under the exact PyPI 4.1.2 wheel on Python 3.13 and is covered by+`tests/test_scripts.py`.++Numeric `run(until=time)` creates an urgent internal stop Event, so normal Events at+that exact time are excluded. This was verified from both tagged source and runtime+tests.++## Primary simulation-method sources++These sources describe simulation-study design and output analysis. They are not+SimPy API documentation.++- Averill M. Law, ["Statistical Analysis of Simulation Output Data"](https://informs-sim.org/wsc20papers/134.pdf),+ *Proceedings of the 2020 Winter Simulation Conference*, 2020. Defines+ terminating/nonterminating analyses; independent replications;+ replication/deletion; warm-up/run length; Student-t intervals; and warns against+ naive single-run IID intervals. Accessed 2026-07-23.+- Pierre L'Ecuyer, ["Random Number Generation with Multiple Streams for Sequential and Parallel Computing"](https://informs-sim.org/wsc15papers/003.pdf),+ *Proceedings of the 2015 Winter Simulation Conference*, 2015,+ DOI `10.1109/WSC.2015.7408151`. Covers streams/substreams, one stream per random+ source, replication separation, common random numbers, testing, and exact+ reproducibility. Accessed 2026-07-23.+- Robert G. Sargent, ["Verification and Validation of Simulation Models"](https://www.informs-sim.org/wsc10papers/016.pdf),+ *Proceedings of the 2010 Winter Simulation Conference*, 2010. Defines model+ verification, conceptual/data/operational validity, intended-purpose/domain+ framing, sensitivity analysis, and validation evidence. Accessed 2026-07-23.+- Stewart Robinson, ["Conceptual Modelling for Simulation Part I: Definition and Requirements"](https://doi.org/10.1057/palgrave.jors.2602368),+ *Journal of the Operational Research Society* 59, 278-290, 2008. Identifies+ validity, credibility, utility, feasibility, and simplest-adequate-model+ requirements. Publisher page accessed 2026-07-23.+- Lee W. Schruben, ["Detecting Initialization Bias in Simulation Output"](https://doi.org/10.1287/opre.30.3.569),+ *Operations Research* 30(3), 569-590, **June 1982**. Original initialization-bias+ testing method. Metadata/abstract verified via+ [IDEAS/RePEc](https://ideas.repec.org/a/inm/oropre/v30y1982i3p569-590.html)+ on 2026-07-23.+- Stewart Robinson, ["A Statistical Process Control Approach to Selecting a Warm-up Period for a Discrete-event Simulation"](https://ideas.repec.org/a/eee/ejores/v176y2007i1p332-346.html),+ *European Journal of Operational Research* 176(1), 332-346, **January 2007**.+ Accessed 2026-07-23.+- Kathryn Hoad, Stewart Robinson, Ruth Davies,+ ["Automated Selection of the Number of Replications for a Discrete-event Simulation"](https://doi.org/10.1057/jors.2009.121),+ *Journal of the Operational Research Society* 61(11), 1632-1644,+ **November 2010**. Replication-count/precision methodology; metadata verified+ 2026-07-23.+- Thomas Monks et al.,+ ["Strengthening the Reporting of Empirical Simulation Studies: Introducing the STRESS Guidelines"](https://doi.org/10.1080/17477778.2018.1442155),+ *Journal of Simulation*, 2018/2019 publication record. Reporting checklists for+ objectives, logic, data, experimentation, implementation, and code access.+ [EQUATOR record](https://www.equator-network.org/reporting-guidelines/strengthening-the-reporting-of-empirical-simulation-studies-introducing-the-stress-guidelines/)+ last updated 2021-11-19; both accessed 2026-07-23.+- Averill M. Law and W. David Kelton,+ ["Confidence Intervals for Steady-State Simulations: I. A Survey of Fixed Sample Size Procedures"](https://doi.org/10.1287/opre.32.6.1221),+ *Operations Research* 32(6), 1221-1239, **December 1984**. Surveys replication,+ batch means, autoregressive, spectral, and regenerative fixed-run methods and+ cautions that adequate run length is model-dependent. Accessed 2026-07-23.++## Research queries used++Parallel searches/extractions covered:++- latest SimPy stable version, Python support, PyPI files, GitLab tags/changelog;+- Environment/Event/Process/Timeout/Condition and scheduling;+- all Resource, Container, and Store variants;+- interrupts, monitoring, stepping, real-time, examples, API, and testing config;+- independent replications, confidence intervals, warm-up/transient bias,+ random streams, conceptual modeling, V&V, sensitivity, and reproducibility.++No Parallel JSON artifacts were written into the repository.diff --git a/skills/simpy/scripts/_common.py b/skills/simpy/scripts/_common.pynew file mode 100644index 00000000..a8515938--- /dev/null+++ b/skills/simpy/scripts/_common.py@@ -0,0 +1,473 @@+#!/usr/bin/env python3+"""Shared bounded-I/O and statistical helpers for the SimPy CLIs."""++from __future__ import annotations++import hashlib+import json+import math+import os+import stat+import tempfile+from collections.abc import Iterable, Mapping+from pathlib import Path+from statistics import fmean, stdev+from typing import Any+++SIMPY_VERSION = "4.1.2"+PINNED_INSTALL = 'uv pip install "simpy==4.1.2"'+DEFAULT_SEED = 20_260_723+MAX_CONFIG_BYTES = 64 * 1024+MAX_INPUT_BYTES = 32 * 1024 * 1024+MAX_REPORT_BYTES = 8 * 1024 * 1024+MAX_SIM_TIME = 1_000_000.0+MAX_EVENTS = 1_000_000+MAX_ENTITIES = 100_000+MAX_REPLICATIONS = 1_000+MAX_QUEUE_CAPACITY = 100_000+MAX_TRACE_RECORDS = 1_000_000+++class CliError(ValueError):+ """An expected validation or command-line error."""+++def load_simpy(*, required: bool = True) -> Any | None:+ """Import SimPy on demand or raise a concise installation error."""++ try:+ import simpy+ except ModuleNotFoundError as exc:+ if exc.name != "simpy":+ raise+ if not required:+ return None+ raise CliError(+ f"SimPy {SIMPY_VERSION} is required for simulation execution; "+ f"install it with `{PINNED_INSTALL}`"+ ) from exc+ return simpy+++def _reject_constant(value: str) -> None:+ raise CliError(f"non-standard JSON constant is not allowed: {value}")+++def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise CliError(f"duplicate JSON key is not allowed: {key!r}")+ result[key] = value+ return result+++def checked_input_file(+ value: str | os.PathLike[str],+ *,+ suffixes: Iterable[str],+ max_bytes: int = MAX_INPUT_BYTES,+) -> Path:+ """Return a bounded regular local file, rejecting URLs and symlinks."""++ raw = os.fspath(value)+ if "://" in raw:+ raise CliError("network URLs are not accepted; provide a local file")+ path = Path(raw).expanduser()+ if path.is_symlink():+ raise CliError(f"input must not be a symlink: {path}")+ try:+ info = path.stat()+ except OSError as exc:+ raise CliError(f"cannot access input file {path}: {exc}") from exc+ if not stat.S_ISREG(info.st_mode):+ raise CliError(f"input is not a regular file: {path}")+ if info.st_size > max_bytes:+ raise CliError(f"input is {info.st_size} bytes; limit is {max_bytes}")+ allowed = {suffix.lower() for suffix in suffixes}+ if path.suffix.lower() not in allowed:+ raise CliError(f"input suffix must be one of: {', '.join(sorted(allowed))}")+ return path.resolve()+++def checked_output_file(+ value: str | os.PathLike[str],+ *,+ suffixes: Iterable[str],+ force: bool = False,+) -> Path:+ """Validate an explicit local output without following symlinks."""++ raw = os.fspath(value)+ if "://" in raw:+ raise CliError("network URLs are not accepted as output paths")+ path = Path(raw).expanduser()+ if path.name in {"", ".", ".."}:+ raise CliError("output must name a file")+ if path.is_symlink():+ raise CliError(f"output must not be a symlink: {path}")+ allowed = {suffix.lower() for suffix in suffixes}+ if path.suffix.lower() not in allowed:+ raise CliError(f"output suffix must be one of: {', '.join(sorted(allowed))}")+ parent = path.parent+ if not parent.exists() or not parent.is_dir() or parent.is_symlink():+ raise CliError(f"output parent must be an existing regular directory: {parent}")+ if path.exists():+ if not path.is_file():+ raise CliError(f"output exists and is not a regular file: {path}")+ if not force:+ raise CliError(f"refusing to overwrite existing output: {path}")+ return parent.resolve() / path.name+++def atomic_write_bytes(path: Path, payload: bytes, *, force: bool = False) -> None:+ """Write bytes through a private same-directory temporary file."""++ destination = checked_output_file(path, suffixes={path.suffix}, force=force)+ descriptor, temporary_name = tempfile.mkstemp(+ prefix=f".{destination.name}.", suffix=".tmp", dir=destination.parent+ )+ temporary = Path(temporary_name)+ try:+ with os.fdopen(descriptor, "wb") as handle:+ handle.write(payload)+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temporary, 0o600)+ if destination.exists() and not force:+ raise CliError(f"refusing to overwrite existing output: {destination}")+ os.replace(temporary, destination)+ finally:+ temporary.unlink(missing_ok=True)+++def strict_json_bytes(document: Any) -> bytes:+ """Serialize deterministic RFC-compatible JSON with a size cap."""++ try:+ payload = (+ json.dumps(+ document,+ indent=2,+ sort_keys=True,+ ensure_ascii=False,+ allow_nan=False,+ )+ + "\n"+ ).encode("utf-8")+ except (TypeError, ValueError) as exc:+ raise CliError(f"report is not strict JSON: {exc}") from exc+ if len(payload) > MAX_REPORT_BYTES:+ raise CliError(+ f"report is {len(payload)} bytes; limit is {MAX_REPORT_BYTES} bytes"+ )+ return payload+++def emit_json(+ document: Any,+ *,+ output: str | os.PathLike[str] | None = None,+ force: bool = False,+) -> None:+ """Print deterministic JSON or write it atomically."""++ payload = strict_json_bytes(document)+ if output is None:+ print(payload.decode("utf-8"), end="")+ return+ destination = checked_output_file(output, suffixes={".json"}, force=force)+ atomic_write_bytes(destination, payload, force=force)+++def emit_text(+ text: str,+ *,+ output: str | os.PathLike[str],+ suffixes: Iterable[str],+ force: bool = False,+) -> Path:+ """Write bounded text atomically and return its destination."""++ payload = text.encode("utf-8")+ if len(payload) > MAX_REPORT_BYTES:+ raise CliError(+ f"output is {len(payload)} bytes; limit is {MAX_REPORT_BYTES} bytes"+ )+ destination = checked_output_file(output, suffixes=suffixes, force=force)+ atomic_write_bytes(destination, payload, force=force)+ return destination+++def load_json_object(value: str | os.PathLike[str]) -> dict[str, Any]:+ """Load a bounded strict JSON object from a local file."""++ path = checked_input_file(+ value, suffixes={".json"}, max_bytes=MAX_CONFIG_BYTES+ )+ try:+ with path.open("r", encoding="utf-8") as handle:+ document = json.load(+ handle,+ parse_constant=_reject_constant,+ object_pairs_hook=_unique_object,+ )+ except CliError:+ raise+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ raise CliError(f"cannot read valid JSON from {path.name}: {exc}") from exc+ if not isinstance(document, dict):+ raise CliError("configuration root must be a JSON object")+ return document+++def parse_json_line(line: str, *, line_number: int) -> dict[str, Any]:+ """Parse one strict JSON object from a JSON Lines input."""++ try:+ value = json.loads(+ line,+ parse_constant=_reject_constant,+ object_pairs_hook=_unique_object,+ )+ except CliError:+ raise+ except json.JSONDecodeError as exc:+ raise CliError(f"invalid JSON on line {line_number}: {exc.msg}") from exc+ if not isinstance(value, dict):+ raise CliError(f"line {line_number} must contain a JSON object")+ return value+++def validate_keys(+ value: Mapping[str, Any],+ *,+ allowed: Iterable[str],+ required: Iterable[str] = (),+ context: str = "configuration",+) -> None:+ """Reject unknown keys and report required keys."""++ allowed_set = set(allowed)+ required_set = set(required)+ unknown = sorted(set(value) - allowed_set)+ missing = sorted(required_set - set(value))+ if unknown:+ raise CliError(f"{context} has unknown keys: {', '.join(unknown)}")+ if missing:+ raise CliError(f"{context} is missing keys: {', '.join(missing)}")+++def integer(+ value: Any,+ *,+ name: str,+ minimum: int,+ maximum: int,+) -> int:+ """Validate a bounded JSON integer, rejecting booleans."""++ if isinstance(value, bool) or not isinstance(value, int):+ raise CliError(f"{name} must be an integer")+ if not minimum <= value <= maximum:+ raise CliError(f"{name} must be from {minimum} through {maximum}")+ return value+++def finite_number(+ value: Any,+ *,+ name: str,+ minimum: float | None = None,+ maximum: float | None = None,+ minimum_inclusive: bool = True,+) -> float:+ """Validate a finite JSON number with optional bounds."""++ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise CliError(f"{name} must be a number")+ result = float(value)+ if not math.isfinite(result):+ raise CliError(f"{name} must be finite")+ if minimum is not None:+ valid = result >= minimum if minimum_inclusive else result > minimum+ if not valid:+ qualifier = "at least" if minimum_inclusive else "greater than"+ raise CliError(f"{name} must be {qualifier} {minimum}")+ if maximum is not None and result > maximum:+ raise CliError(f"{name} must be no greater than {maximum}")+ return result+++def derive_seed(base_seed: int, replication: int, stream: str) -> int:+ """Derive a stable 64-bit seed for one replication and random stream."""++ integer(base_seed, name="base_seed", minimum=0, maximum=2**63 - 1)+ integer(+ replication,+ name="replication",+ minimum=0,+ maximum=MAX_REPLICATIONS - 1,+ )+ if not stream or len(stream) > 64 or not stream.isascii():+ raise CliError("stream label must be 1-64 ASCII characters")+ payload = f"simpy-skill-v1|{base_seed}|{replication}|{stream}".encode("ascii")+ return int.from_bytes(hashlib.blake2b(payload, digest_size=8).digest(), "big")+++def _beta_continued_fraction(a: float, b: float, x: float) -> float:+ """Evaluate the continued fraction used by regularized incomplete beta."""++ maximum_iterations = 250+ epsilon = 3.0e-14+ minimum = 1.0e-300+ qab = a + b+ qap = a + 1.0+ qam = a - 1.0+ c = 1.0+ d = 1.0 - qab * x / qap+ if abs(d) < minimum:+ d = minimum+ d = 1.0 / d+ result = d+ for iteration in range(1, maximum_iterations + 1):+ doubled = 2 * iteration+ coefficient = (+ iteration+ * (b - iteration)+ * x+ / ((qam + doubled) * (a + doubled))+ )+ d = 1.0 + coefficient * d+ if abs(d) < minimum:+ d = minimum+ c = 1.0 + coefficient / c+ if abs(c) < minimum:+ c = minimum+ d = 1.0 / d+ result *= d * c+ coefficient = -(+ (a + iteration)+ * (qab + iteration)+ * x+ / ((a + doubled) * (qap + doubled))+ )+ d = 1.0 + coefficient * d+ if abs(d) < minimum:+ d = minimum+ c = 1.0 + coefficient / c+ if abs(c) < minimum:+ c = minimum+ d = 1.0 / d+ delta = d * c+ result *= delta+ if abs(delta - 1.0) <= epsilon:+ return result+ raise CliError("Student-t calculation did not converge")+++def _regularized_incomplete_beta(a: float, b: float, x: float) -> float:+ if not 0.0 <= x <= 1.0:+ raise CliError("internal beta argument is outside [0, 1]")+ if x in {0.0, 1.0}:+ return x+ log_term = (+ math.lgamma(a + b)+ - math.lgamma(a)+ - math.lgamma(b)+ + a * math.log(x)+ + b * math.log1p(-x)+ )+ term = math.exp(log_term)+ if x < (a + 1.0) / (a + b + 2.0):+ return term * _beta_continued_fraction(a, b, x) / a+ return 1.0 - term * _beta_continued_fraction(b, a, 1.0 - x) / b+++def student_t_cdf(value: float, degrees_of_freedom: int) -> float:+ """Return the Student-t CDF using the incomplete-beta identity."""++ integer(+ degrees_of_freedom,+ name="degrees_of_freedom",+ minimum=1,+ maximum=MAX_REPLICATIONS - 1,+ )+ if not math.isfinite(value):+ return 0.0 if value < 0 else 1.0+ if value == 0:+ return 0.5+ ratio = degrees_of_freedom / (degrees_of_freedom + value * value)+ tail = 0.5 * _regularized_incomplete_beta(+ degrees_of_freedom / 2.0, 0.5, ratio+ )+ return 1.0 - tail if value > 0 else tail+++def student_t_quantile(probability: float, degrees_of_freedom: int) -> float:+ """Numerically invert the Student-t CDF for 0.5 < p < 1."""++ if not 0.5 < probability < 1.0:+ raise CliError("Student-t probability must be between 0.5 and 1")+ integer(+ degrees_of_freedom,+ name="degrees_of_freedom",+ minimum=1,+ maximum=MAX_REPLICATIONS - 1,+ )+ lower = 0.0+ upper = 1.0+ while student_t_cdf(upper, degrees_of_freedom) < probability:+ upper *= 2.0+ if upper > 1_000_000:+ raise CliError("Student-t quantile could not be bracketed")+ for _ in range(90):+ midpoint = (lower + upper) / 2.0+ if student_t_cdf(midpoint, degrees_of_freedom) < probability:+ lower = midpoint+ else:+ upper = midpoint+ return (lower + upper) / 2.0+++def mean_confidence_interval(+ values: Iterable[float], *, confidence: float = 0.95+) -> dict[str, float | int]:+ """Return a two-sided Student-t interval across independent estimates."""++ observations = [float(value) for value in values]+ if len(observations) < 2:+ raise CliError(+ "a confidence interval requires at least two independent replications"+ )+ if len(observations) > MAX_REPLICATIONS:+ raise CliError(f"at most {MAX_REPLICATIONS} replications are allowed")+ if any(not math.isfinite(value) for value in observations):+ raise CliError("confidence-interval observations must be finite")+ confidence = finite_number(+ confidence,+ name="confidence",+ minimum=0.50,+ maximum=0.999,+ minimum_inclusive=False,+ )+ count = len(observations)+ estimate = fmean(observations)+ standard_deviation = stdev(observations)+ standard_error = standard_deviation / math.sqrt(count)+ critical = student_t_quantile(+ 0.5 + confidence / 2.0, degrees_of_freedom=count - 1+ )+ half_width = critical * standard_error+ return {+ "confidence": confidence,+ "degrees_of_freedom": count - 1,+ "half_width": half_width,+ "lower": estimate - half_width,+ "mean": estimate,+ "replications": count,+ "standard_deviation": standard_deviation,+ "standard_error": standard_error,+ "upper": estimate + half_width,+ }diff --git a/skills/simpy/scripts/basic_simulation_template.py b/skills/simpy/scripts/basic_simulation_template.pyindex a047fed9..3510a52b 100644--- a/skills/simpy/scripts/basic_simulation_template.py+++ b/skills/simpy/scripts/basic_simulation_template.py@@ -1,193 +1,415 @@#!/usr/bin/env python3-"""-Basic SimPy Simulation Template+"""Bounded, reproducible SimPy queue template with independent random streams."""-This template provides a starting point for building SimPy simulations.-Customize the process functions and parameters for your specific use case.-"""+from __future__ import annotations-import simpy+import argparseimport random+from dataclasses import asdict, dataclass, field+from statistics import fmean+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ import simpy++from _common import (+ DEFAULT_SEED,+ MAX_ENTITIES,+ MAX_EVENTS,+ MAX_QUEUE_CAPACITY,+ MAX_SIM_TIME,+ CliError,+ derive_seed,+ emit_json,+ finite_number,+ integer,+ load_json_object,+ load_simpy,+ validate_keys,+)+from resource_monitor import EventTraceRecorder, ResourceMonitor+++_SIMPY = load_simpy(required=False)+++CONFIG_KEYS = {+ "analysis_mode",+ "base_seed",+ "horizon",+ "max_entities",+ "max_events",+ "mean_interarrival",+ "mean_service",+ "queue_capacity",+ "servers",+ "warm_up",+}+++class EventLimitExceeded(RuntimeError):+ """Raised when a simulation attempts to process too many events."""+++if _SIMPY is not None:++ class BoundedEnvironment(_SIMPY.Environment):+ """Environment that enforces a public, explicit event-processing budget."""++ def __init__(self, *, max_events: int):+ super().__init__()+ self.max_events = max_events+ self.processed_events = 0++ def step(self) -> None:+ if self.processed_events >= self.max_events:+ raise EventLimitExceeded(+ f"simulation reached the max_events limit ({self.max_events})"+ )+ super().step()+ self.processed_events += 1++else:++ class BoundedEnvironment:+ """Unavailable placeholder used only when SimPy is not installed."""++ def __init__(self, *, max_events: int):+ del max_events+ load_simpy()+ raise AssertionError("unreachable")+++@dataclass(frozen=True)+class QueueConfig:+ """Validated configuration for a finite-horizon multi-server queue."""++ analysis_mode: str = "terminating"+ horizon: float = 480.0+ warm_up: float = 0.0+ servers: int = 2+ queue_capacity: int = 20+ mean_interarrival: float = 4.0+ mean_service: float = 6.0+ base_seed: int = DEFAULT_SEED+ max_entities: int = 10_000+ max_events: int = 200_000++ @classmethod+ def from_mapping(cls, value: dict[str, Any] | None) -> "QueueConfig":+ """Build a strict configuration; unknown JSON keys are rejected."""++ value = {} if value is None else dict(value)+ validate_keys(value, allowed=CONFIG_KEYS, context="queue configuration")+ defaults = cls()+ analysis_mode = value.get("analysis_mode", defaults.analysis_mode)+ if analysis_mode not in {"terminating", "steady_state"}:+ raise CliError(+ "analysis_mode must be either 'terminating' or 'steady_state'"+ )+ horizon = finite_number(+ value.get("horizon", defaults.horizon),+ name="horizon",+ minimum=0.0,+ maximum=MAX_SIM_TIME,+ minimum_inclusive=False,+ )+ warm_up = finite_number(+ value.get("warm_up", defaults.warm_up),+ name="warm_up",+ minimum=0.0,+ maximum=horizon,+ )+ if warm_up >= horizon:+ raise CliError("warm_up must be strictly less than horizon")+ if analysis_mode == "terminating" and warm_up != 0:+ raise CliError("terminating analyses must use warm_up=0")+ if analysis_mode == "steady_state" and warm_up <= 0:+ raise CliError("steady_state analyses require a positive warm_up")+ return cls(+ analysis_mode=analysis_mode,+ horizon=horizon,+ warm_up=warm_up,+ servers=integer(+ value.get("servers", defaults.servers),+ name="servers",+ minimum=1,+ maximum=10_000,+ ),+ queue_capacity=integer(+ value.get("queue_capacity", defaults.queue_capacity),+ name="queue_capacity",+ minimum=0,+ maximum=MAX_QUEUE_CAPACITY,+ ),+ mean_interarrival=finite_number(+ value.get("mean_interarrival", defaults.mean_interarrival),+ name="mean_interarrival",+ minimum=0.0,+ maximum=MAX_SIM_TIME,+ minimum_inclusive=False,+ ),+ mean_service=finite_number(+ value.get("mean_service", defaults.mean_service),+ name="mean_service",+ minimum=0.0,+ maximum=MAX_SIM_TIME,+ minimum_inclusive=False,+ ),+ base_seed=integer(+ value.get("base_seed", defaults.base_seed),+ name="base_seed",+ minimum=0,+ maximum=2**63 - 1,+ ),+ max_entities=integer(+ value.get("max_entities", defaults.max_entities),+ name="max_entities",+ minimum=1,+ maximum=MAX_ENTITIES,+ ),+ max_events=integer(+ value.get("max_events", defaults.max_events),+ name="max_events",+ minimum=10,+ maximum=MAX_EVENTS,+ ),+ )+++@dataclass+class QueueStatistics:+ """Per-run counters and post-warm-up observations."""++ arrivals: int = 0+ admitted: int = 0+ rejected: int = 0+ completed: int = 0+ observed_completed: int = 0+ wait_times: list[float] = field(default_factory=list)+ service_times: list[float] = field(default_factory=list)+ system_times: list[float] = field(default_factory=list)+ entity_limit_hit: bool = False+++def _optional_mean(values: list[float]) -> float | None:+ return fmean(values) if values else None+++def _customer(+ env: BoundedEnvironment,+ *,+ resource: simpy.Resource,+ stats: QueueStatistics,+ service_rng: random.Random,+ mean_service: float,+ arrival_time: float,+ warm_up: float,+) -> Any:+ """Request one server, receive service, and record a completed observation."""--class SimulationConfig:- """Configuration parameters for the simulation."""-- def __init__(self):- self.random_seed = 42- self.num_resources = 2- self.num_processes = 10- self.sim_time = 100- self.arrival_rate = 5.0 # Average time between arrivals- self.service_time_mean = 3.0 # Average service time- self.service_time_std = 1.0 # Service time standard deviation---class SimulationStats:- """Collect and report simulation statistics."""-- def __init__(self):- self.arrival_times = []- self.service_start_times = []- self.departure_times = []- self.wait_times = []- self.service_times = []-- def record_arrival(self, time):- self.arrival_times.append(time)-- def record_service_start(self, time):- self.service_start_times.append(time)-- def record_departure(self, time):- self.departure_times.append(time)-- def record_wait_time(self, wait_time):- self.wait_times.append(wait_time)-- def record_service_time(self, service_time):- self.service_times.append(service_time)-- def report(self):- print("\n" + "=" * 50)- print("SIMULATION STATISTICS")- print("=" * 50)-- if self.wait_times:- print(f"Total customers: {len(self.wait_times)}")- print(f"Average wait time: {sum(self.wait_times) / len(self.wait_times):.2f}")- print(f"Max wait time: {max(self.wait_times):.2f}")- print(f"Min wait time: {min(self.wait_times):.2f}")-- if self.service_times:- print(f"Average service time: {sum(self.service_times) / len(self.service_times):.2f}")-- if self.arrival_times and self.departure_times:- throughput = len(self.departure_times) / max(self.departure_times)- print(f"Throughput: {throughput:.2f} customers/time unit")-- print("=" * 50)---def customer_process(env, name, resource, stats, config):- """- Simulate a customer process.-- Args:- env: SimPy environment- name: Customer identifier- resource: Shared resource (e.g., server, machine)- stats: Statistics collector- config: Simulation configuration- """- # Record arrival- arrival_time = env.now- stats.record_arrival(arrival_time)- print(f"{name} arrived at {arrival_time:.2f}")-- # Request resourcewith resource.request() as request:yield request-- # Record service start and calculate wait timeservice_start = env.now- wait_time = service_start - arrival_time- stats.record_service_start(service_start)- stats.record_wait_time(wait_time)- print(f"{name} started service at {service_start:.2f} (waited {wait_time:.2f})")-- # Service time (normally distributed)- service_time = max(0.1, random.gauss(- config.service_time_mean,- config.service_time_std- ))- stats.record_service_time(service_time)-+ service_time = service_rng.expovariate(1.0 / mean_service)yield env.timeout(service_time)-- # Record departure- departure_time = env.now- stats.record_departure(departure_time)- print(f"{name} departed at {departure_time:.2f}")---def customer_generator(env, resource, stats, config):- """- Generate customers arriving at random intervals.-- Args:- env: SimPy environment- resource: Shared resource- stats: Statistics collector- config: Simulation configuration- """- customer_count = 0-- while True:- # Wait for next customer arrival (exponential distribution)- inter_arrival_time = random.expovariate(1.0 / config.arrival_rate)- yield env.timeout(inter_arrival_time)-- # Create new customer process- customer_count += 1- customer_name = f"Customer {customer_count}"- env.process(customer_process(env, customer_name, resource, stats, config))---def run_simulation(config):- """- Run the simulation with given configuration.-- Args:- config: SimulationConfig object with simulation parameters-- Returns:- SimulationStats object with collected statistics- """- # Set random seed for reproducibility- random.seed(config.random_seed)-- # Create environment- env = simpy.Environment()-- # Create shared resource- resource = simpy.Resource(env, capacity=config.num_resources)-- # Create statistics collector- stats = SimulationStats()-- # Start customer generator- env.process(customer_generator(env, resource, stats, config))-- # Run simulation- print(f"Starting simulation for {config.sim_time} time units...")- print(f"Resources: {config.num_resources}")- print(f"Average arrival rate: {config.arrival_rate:.2f}")- print(f"Average service time: {config.service_time_mean:.2f}")- print("-" * 50)-- env.run(until=config.sim_time)-- return stats---def main():- """Main function to run the simulation."""- # Create configuration- config = SimulationConfig()-- # Customize configuration if needed- config.num_resources = 2- config.sim_time = 50- config.arrival_rate = 2.0- config.service_time_mean = 3.0-- # Run simulation- stats = run_simulation(config)-- # Report statistics- stats.report()+ stats.completed += 1+ if arrival_time >= warm_up:+ stats.observed_completed += 1+ stats.wait_times.append(service_start - arrival_time)+ stats.service_times.append(service_time)+ stats.system_times.append(env.now - arrival_time)++def _arrivals(+ env: BoundedEnvironment,+ *,+ resource: simpy.Resource,+ config: QueueConfig,+ stats: QueueStatistics,+ arrival_rng: random.Random,+ service_rng: random.Random,+) -> Any:+ """Generate at most max_entities arrivals strictly before the horizon."""++ while stats.arrivals < config.max_entities:+ delay = arrival_rng.expovariate(1.0 / config.mean_interarrival)+ if env.now + delay >= config.horizon:+ return+ yield env.timeout(delay)+ stats.arrivals += 1+ system_capacity = config.servers + config.queue_capacity+ if resource.count + len(resource.queue) >= system_capacity:+ stats.rejected += 1+ continue+ stats.admitted += 1+ env.process(+ _customer(+ env,+ resource=resource,+ stats=stats,+ service_rng=service_rng,+ mean_service=config.mean_service,+ arrival_time=env.now,+ warm_up=config.warm_up,+ )+ )+ stats.entity_limit_hit = True+++def run_simulation(+ config: QueueConfig,+ *,+ replication: int = 0,+ trace_max_records: int | None = None,+) -> dict[str, Any]:+ """Run one bounded replication and return a strict-JSON-compatible report."""++ simpy_module = load_simpy()+ replication = integer(+ replication,+ name="replication",+ minimum=0,+ maximum=999,+ )+ arrival_seed = derive_seed(config.base_seed, replication, "arrivals")+ service_seed = derive_seed(config.base_seed, replication, "service")+ arrival_rng = random.Random(arrival_seed)+ service_rng = random.Random(service_seed)+ env = BoundedEnvironment(max_events=config.max_events)+ trace = (+ EventTraceRecorder(env, max_records=trace_max_records)+ if trace_max_records is not None+ else None+ )+ resource = simpy_module.Resource(env, capacity=config.servers)+ monitor = ResourceMonitor(env, resource, name="server")+ stats = QueueStatistics()+ env.process(+ _arrivals(+ env,+ resource=resource,+ config=config,+ stats=stats,+ arrival_rng=arrival_rng,+ service_rng=service_rng,+ )+ )+ try:+ env.run(until=config.horizon)+ except EventLimitExceeded as exc:+ raise CliError(str(exc)) from exc+ if trace is not None:+ trace.detach()+ monitor.finalize(at=config.horizon)++ observed_duration = config.horizon - config.warm_up+ warnings: list[str] = []+ unfinished = stats.admitted - stats.completed+ if stats.entity_limit_hit:+ warnings.append(+ "max_entities was reached before the horizon; arrivals were truncated"+ )+ if unfinished:+ warnings.append(+ "some admitted entities were unfinished at the horizon; completed-customer "+ "metrics exclude those right-censored paths"+ )+ if stats.observed_completed == 0:+ warnings.append("no completed entities were observed in the analysis window")+ if config.analysis_mode == "steady_state":+ warnings.append(+ "warm-up deletion is user-specified and does not prove steady state"+ )++ loss_probability = (+ stats.rejected / stats.arrivals if stats.arrivals else None+ )+ report = {+ "config": asdict(config),+ "counters": {+ "admitted": stats.admitted,+ "arrivals": stats.arrivals,+ "completed": stats.completed,+ "observed_completed": stats.observed_completed,+ "rejected": stats.rejected,+ "unfinished_at_horizon": unfinished,+ },+ "event_processing": {+ "limit": config.max_events,+ "processed": env.processed_events,+ },+ "metrics": {+ "average_queue_length": monitor.average_queue_length(+ start=config.warm_up, end=config.horizon+ ),+ "average_system_time": _optional_mean(stats.system_times),+ "average_wait": _optional_mean(stats.wait_times),+ "loss_probability": loss_probability,+ "mean_service_time": _optional_mean(stats.service_times),+ "server_utilization": monitor.average_utilization(+ start=config.warm_up, end=config.horizon+ ),+ "throughput_per_time_unit": (+ stats.observed_completed / observed_duration+ ),+ },+ "replication": replication,+ "schema_version": "1.1",+ "seed_manifest": {+ "algorithm": "BLAKE2b-derived Python random.Random streams",+ "arrival_seed": arrival_seed,+ "base_seed": config.base_seed,+ "service_seed": service_seed,+ },+ "warnings": warnings,+ }+ if trace is not None:+ report["event_trace"] = {+ "records": trace.records,+ "truncated": trace.truncated,+ }+ return report+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Run a deterministic, finite-horizon queue template. JSON input is "+ "allowlisted and all time, event, entity, and queue bounds are enforced."+ )+ )+ parser.add_argument(+ "--config",+ help="Optional local .json queue configuration; URLs and symlinks are rejected",+ )+ parser.add_argument(+ "--replication",+ type=int,+ default=0,+ help="Deterministic replication index from 0 through 999 (default: 0)",+ )+ parser.add_argument("--output", help="Optional local .json report")+ parser.add_argument("--force", action="store_true", help="Replace explicit output")+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ config = QueueConfig.from_mapping(+ load_json_object(args.config) if args.config else None+ )+ report = run_simulation(config, replication=args.replication)+ report["source"] = {+ "config": None if args.config is None else "local_json",+ "network_used": False,+ }+ emit_json(report, output=args.output, force=args.force)+ except CliError as exc:+ parser.error(str(exc))+ return 0if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/skills/simpy/scripts/bounded_queue_scenario.py b/skills/simpy/scripts/bounded_queue_scenario.pynew file mode 100644index 00000000..8fe6fedd--- /dev/null+++ b/skills/simpy/scripts/bounded_queue_scenario.py@@ -0,0 +1,126 @@+#!/usr/bin/env python3+"""Run a bounded finite-horizon queue scenario from allowlisted JSON."""++from __future__ import annotations++import argparse+import json+from pathlib import Path+from typing import Any++from _common import (+ MAX_TRACE_RECORDS,+ CliError,+ emit_json,+ emit_text,+ integer,+ load_json_object,+)+from basic_simulation_template import QueueConfig, run_simulation+++def _trace_text(records: list[dict[str, Any]]) -> str:+ return "".join(+ json.dumps(+ record,+ sort_keys=True,+ ensure_ascii=False,+ allow_nan=False,+ separators=(",", ":"),+ )+ + "\n"+ for record in records+ )+++def run_scenario(+ config: QueueConfig,+ *,+ trace_max_records: int | None = None,+) -> dict[str, Any]:+ """Run the built-in loss/queue scenario; no plugin or Python code is loaded."""++ return run_simulation(+ config,+ replication=0,+ trace_max_records=trace_max_records,+ )+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Run the built-in bounded M/M/c/K-style queue scenario. The local "+ "JSON configuration has a fixed allowlist; no code, plugin, eval, "+ "network resource, or unbounded simulation is accepted."+ )+ )+ parser.add_argument(+ "--config",+ help="Optional local .json queue configuration; URLs and symlinks are rejected",+ )+ parser.add_argument("--output", help="Optional local .json scenario report")+ parser.add_argument(+ "--trace-output",+ help="Optional local .jsonl deterministic event trace",+ )+ parser.add_argument(+ "--trace-max-records",+ type=int,+ default=100_000,+ help="Trace cap from 1 through 1,000,000 (default: 100000)",+ )+ parser.add_argument("--force", action="store_true", help="Replace explicit outputs")+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ config = QueueConfig.from_mapping(+ load_json_object(args.config) if args.config else None+ )+ trace_limit = (+ integer(+ args.trace_max_records,+ name="trace_max_records",+ minimum=1,+ maximum=MAX_TRACE_RECORDS,+ )+ if args.trace_output+ else None+ )+ report = run_scenario(config, trace_max_records=trace_limit)+ trace = report.pop("event_trace", None)+ if trace is not None:+ records = trace["records"]+ emit_text(+ _trace_text(records),+ output=args.trace_output,+ suffixes={".jsonl"},+ force=args.force,+ )+ report["trace"] = {+ "file": Path(args.trace_output).name,+ "records": len(records),+ "truncated": trace["truncated"],+ }+ else:+ report["trace"] = None+ report["safety"] = {+ "config_allowlist": True,+ "entity_limit": config.max_entities,+ "event_limit": config.max_events,+ "network_used": False,+ "plugin_loading": False,+ "time_limit": config.horizon,+ }+ emit_json(report, output=args.output, force=args.force)+ except CliError as exc:+ parser.error(str(exc))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/simpy/scripts/event_trace_summary.py b/skills/simpy/scripts/event_trace_summary.pynew file mode 100644index 00000000..cae7e043--- /dev/null+++ b/skills/simpy/scripts/event_trace_summary.py@@ -0,0 +1,296 @@+#!/usr/bin/env python3+"""Summarize bounded event-trace JSONL or ResourceMonitor CSV artifacts."""++from __future__ import annotations++import argparse+import csv+from collections import Counter+from pathlib import Path+from typing import Any++from _common import (+ MAX_TRACE_RECORDS,+ CliError,+ checked_input_file,+ emit_json,+ finite_number,+ integer,+ parse_json_line,+ validate_keys,+)+++EVENT_FIELDS = {+ "event_id",+ "event_type",+ "priority",+ "queue_size_before",+ "time",+}+RESOURCE_FIELDS = {+ "count",+ "event",+ "queue_length",+ "time",+ "utilization",+}+++def _csv_number(value: str | None, *, name: str) -> float:+ if value is None:+ raise CliError(f"{name} is missing")+ try:+ parsed = float(value)+ except ValueError as exc:+ raise CliError(f"{name} must be numeric") from exc+ return finite_number(parsed, name=name)+++def summarize_event_trace(path: Path, *, max_records: int) -> dict[str, Any]:+ """Validate and summarize deterministic JSONL event records."""++ counts: Counter[str] = Counter()+ first_time: float | None = None+ last_time: float | None = None+ previous_key: tuple[float, int, int] | None = None+ ordering_violations = 0+ maximum_queue_size = 0+ records = 0+ try:+ with path.open("r", encoding="utf-8") as handle:+ for line_number, raw_line in enumerate(handle, start=1):+ if not raw_line.strip():+ raise CliError(f"blank JSONL record on line {line_number}")+ records += 1+ if records > max_records:+ raise CliError(+ f"trace exceeds the configured record limit ({max_records})"+ )+ record = parse_json_line(raw_line, line_number=line_number)+ validate_keys(+ record,+ allowed=EVENT_FIELDS,+ required=EVENT_FIELDS,+ context=f"trace line {line_number}",+ )+ time = finite_number(+ record["time"], name=f"line {line_number} time", minimum=0+ )+ priority = integer(+ record["priority"],+ name=f"line {line_number} priority",+ minimum=-1_000_000,+ maximum=1_000_000,+ )+ event_id = integer(+ record["event_id"],+ name=f"line {line_number} event_id",+ minimum=0,+ maximum=2**63 - 1,+ )+ queue_size = integer(+ record["queue_size_before"],+ name=f"line {line_number} queue_size_before",+ minimum=1,+ maximum=MAX_TRACE_RECORDS,+ )+ event_type = record["event_type"]+ if (+ not isinstance(event_type, str)+ or not event_type.isidentifier()+ or len(event_type) > 128+ ):+ raise CliError(+ f"line {line_number} event_type must be a short identifier"+ )+ key = (time, priority, event_id)+ if previous_key is not None and key < previous_key:+ ordering_violations += 1+ previous_key = key+ first_time = time if first_time is None else first_time+ last_time = time+ maximum_queue_size = max(maximum_queue_size, queue_size)+ counts[event_type] += 1+ except (OSError, UnicodeError) as exc:+ raise CliError(f"cannot read trace {path.name}: {exc}") from exc+ if records == 0:+ raise CliError("event trace contains no records")+ return {+ "event_type_counts": dict(sorted(counts.items())),+ "first_time": first_time,+ "last_time": last_time,+ "maximum_queue_size_before_step": maximum_queue_size,+ "ordering_violations": ordering_violations,+ "records": records,+ "semantics": (+ "Each row is the next private event-queue entry immediately before "+ "Environment.step(); ordering is checked by (time, priority, event_id)."+ ),+ }+++def summarize_resource_csv(path: Path, *, max_records: int) -> dict[str, Any]:+ """Validate and summarize ResourceMonitor state-change samples."""++ samples: list[dict[str, Any]] = []+ event_counts: Counter[str] = Counter()+ try:+ with path.open("r", encoding="utf-8", newline="") as handle:+ reader = csv.DictReader(handle)+ if reader.fieldnames is None:+ raise CliError("resource CSV has no header")+ if len(reader.fieldnames) != len(set(reader.fieldnames)):+ raise CliError("resource CSV has duplicate columns")+ if set(reader.fieldnames) != RESOURCE_FIELDS:+ raise CliError(+ "resource CSV columns must be exactly: "+ + ", ".join(sorted(RESOURCE_FIELDS))+ )+ previous_time: float | None = None+ for row_number, row in enumerate(reader, start=2):+ if len(samples) >= max_records:+ raise CliError(+ f"resource CSV exceeds the record limit ({max_records})"+ )+ time = finite_number(+ _csv_number(row["time"], name=f"row {row_number} time"),+ name=f"row {row_number} time",+ minimum=0,+ )+ if previous_time is not None and time < previous_time:+ raise CliError("resource sample times must be nondecreasing")+ previous_time = time+ count = integer(+ int(row["count"]),+ name=f"row {row_number} count",+ minimum=0,+ maximum=MAX_TRACE_RECORDS,+ )+ queue_length = integer(+ int(row["queue_length"]),+ name=f"row {row_number} queue_length",+ minimum=0,+ maximum=MAX_TRACE_RECORDS,+ )+ utilization = finite_number(+ _csv_number(+ row["utilization"],+ name=f"row {row_number} utilization",+ ),+ name=f"row {row_number} utilization",+ minimum=0,+ maximum=1,+ )+ event = row["event"]+ if (+ not event+ or len(event) > 64+ or any(character in "\r\n," for character in event)+ ):+ raise CliError(f"row {row_number} has an invalid event label")+ samples.append(+ {+ "count": count,+ "event": event,+ "queue_length": queue_length,+ "time": time,+ "utilization": utilization,+ }+ )+ event_counts[event] += 1+ except ValueError as exc:+ raise CliError(f"resource CSV contains an invalid integer: {exc}") from exc+ except (OSError, UnicodeError, csv.Error) as exc:+ raise CliError(f"cannot read resource CSV {path.name}: {exc}") from exc+ if len(samples) < 2:+ raise CliError("resource CSV needs at least an initial and final sample")+ start = samples[0]["time"]+ end = samples[-1]["time"]+ if end <= start:+ raise CliError("resource CSV must span positive simulation time")+ queue_area = 0.0+ utilization_area = 0.0+ for current, following in zip(samples, samples[1:]):+ duration = following["time"] - current["time"]+ queue_area += current["queue_length"] * duration+ utilization_area += current["utilization"] * duration+ return {+ "average_queue_length": queue_area / (end - start),+ "average_utilization": utilization_area / (end - start),+ "end": end,+ "event_counts": dict(sorted(event_counts.items())),+ "maximum_count": max(sample["count"] for sample in samples),+ "maximum_queue_length": max(+ sample["queue_length"] for sample in samples+ ),+ "records": len(samples),+ "start": start,+ "semantics": (+ "Time-weighted values treat each sampled state as left-continuous "+ "until the next sample. Same-time pre/post samples have zero duration."+ ),+ }+++def summarize(path: Path, *, max_records: int) -> dict[str, Any]:+ if path.suffix.lower() == ".jsonl":+ kind = "event_trace"+ summary = summarize_event_trace(path, max_records=max_records)+ elif path.suffix.lower() == ".csv":+ kind = "resource_monitor"+ summary = summarize_resource_csv(path, max_records=max_records)+ else:+ raise CliError("input must end in .jsonl or .csv")+ return {+ "input": {"kind": kind, "name": path.name},+ "network_used": False,+ "schema_version": "1.1",+ "summary": summary,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Summarize a local event-trace .jsonl or ResourceMonitor .csv file. "+ "Inputs are bounded and validated; no model code is executed."+ )+ )+ parser.add_argument("input", help="Local .jsonl or .csv input")+ parser.add_argument(+ "--max-records",+ type=int,+ default=100_000,+ help="Input record cap from 1 through 1,000,000 (default: 100000)",+ )+ parser.add_argument("--output", help="Optional local .json summary")+ parser.add_argument("--force", action="store_true", help="Replace explicit output")+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ max_records = integer(+ args.max_records,+ name="max_records",+ minimum=1,+ maximum=MAX_TRACE_RECORDS,+ )+ path = checked_input_file(+ args.input, suffixes={".csv", ".jsonl"}+ )+ emit_json(+ summarize(path, max_records=max_records),+ output=args.output,+ force=args.force,+ )+ except CliError as exc:+ parser.error(str(exc))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/simpy/scripts/replication_runner.py b/skills/simpy/scripts/replication_runner.pynew file mode 100644index 00000000..f065623b--- /dev/null+++ b/skills/simpy/scripts/replication_runner.py@@ -0,0 +1,194 @@+#!/usr/bin/env python3+"""Run independent bounded replications and compute Student-t intervals."""++from __future__ import annotations++import argparse+from dataclasses import dataclass+from typing import Any++from _common import (+ MAX_REPLICATIONS,+ CliError,+ emit_json,+ finite_number,+ integer,+ load_json_object,+ mean_confidence_interval,+ validate_keys,+)+from basic_simulation_template import QueueConfig, run_simulation+++MAX_TOTAL_EVENT_BUDGET = 5_000_000+MAX_TOTAL_ENTITY_BUDGET = 2_000_000+EXPERIMENT_KEYS = {"confidence", "model", "replications"}+++@dataclass(frozen=True)+class ExperimentConfig:+ model: QueueConfig+ replications: int = 20+ confidence: float = 0.95++ @classmethod+ def from_mapping(cls, value: dict[str, Any] | None) -> "ExperimentConfig":+ value = {} if value is None else dict(value)+ validate_keys(+ value, allowed=EXPERIMENT_KEYS, context="replication configuration"+ )+ model_value = value.get("model", {})+ if not isinstance(model_value, dict):+ raise CliError("model must be a JSON object")+ model = QueueConfig.from_mapping(model_value)+ replications = integer(+ value.get("replications", 20),+ name="replications",+ minimum=2,+ maximum=MAX_REPLICATIONS,+ )+ confidence = finite_number(+ value.get("confidence", 0.95),+ name="confidence",+ minimum=0.50,+ maximum=0.999,+ minimum_inclusive=False,+ )+ if replications * model.max_events > MAX_TOTAL_EVENT_BUDGET:+ raise CliError(+ "replications * model.max_events exceeds the total event budget "+ f"({MAX_TOTAL_EVENT_BUDGET})"+ )+ if replications * model.max_entities > MAX_TOTAL_ENTITY_BUDGET:+ raise CliError(+ "replications * model.max_entities exceeds the total entity budget "+ f"({MAX_TOTAL_ENTITY_BUDGET})"+ )+ return cls(+ model=model,+ replications=replications,+ confidence=confidence,+ )+++def _interval_or_unavailable(+ reports: list[dict[str, Any]],+ *,+ metric: str,+ confidence: float,+) -> dict[str, Any]:+ values = [report["metrics"][metric] for report in reports]+ missing = sum(value is None for value in values)+ if missing:+ return {+ "missing_replications": missing,+ "reason": "metric was undefined in one or more replications",+ "status": "unavailable",+ }+ interval = mean_confidence_interval(values, confidence=confidence)+ interval["status"] = "ok"+ return interval+++def run_experiment(config: ExperimentConfig) -> dict[str, Any]:+ """Run independent replication streams and summarize replication estimates."""++ reports = [+ run_simulation(config.model, replication=index)+ for index in range(config.replications)+ ]+ metrics = (+ "average_queue_length",+ "average_system_time",+ "average_wait",+ "loss_probability",+ "server_utilization",+ "throughput_per_time_unit",+ )+ intervals = {+ metric: _interval_or_unavailable(+ reports, metric=metric, confidence=config.confidence+ )+ for metric in metrics+ }+ compact_runs = [+ {+ "counters": report["counters"],+ "metrics": report["metrics"],+ "replication": report["replication"],+ "seed_manifest": report["seed_manifest"],+ "warnings": report["warnings"],+ }+ for report in reports+ ]+ return {+ "analysis": {+ "analysis_mode": config.model.analysis_mode,+ "confidence_method": (+ "two-sided Student-t interval across independent "+ "replication-level estimates"+ ),+ "confidence_level": config.confidence,+ "independence_unit": "replication",+ "single_run_interval": False,+ "warm_up": config.model.warm_up,+ },+ "intervals": intervals,+ "model": {+ key: getattr(config.model, key)+ for key in config.model.__dataclass_fields__+ },+ "replications": compact_runs,+ "safety": {+ "network_used": False,+ "replication_limit": MAX_REPLICATIONS,+ "total_entity_budget": MAX_TOTAL_ENTITY_BUDGET,+ "total_event_budget": MAX_TOTAL_EVENT_BUDGET,+ },+ "schema_version": "1.1",+ "warnings": [+ "Intervals quantify Monte Carlo uncertainty under the configured model; "+ "they do not validate the model or establish causality.",+ "For steady-state analysis, warm-up and run length require a separate "+ "transient-bias assessment and sensitivity analysis.",+ "Do not treat within-run customer observations as independent replications.",+ ],+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Run 2-1000 deterministic, independent queue replications from an "+ "allowlisted local JSON configuration and report Student-t confidence "+ "intervals across replication estimates."+ )+ )+ parser.add_argument(+ "--config",+ help="Optional local .json experiment configuration; URLs/symlinks rejected",+ )+ parser.add_argument("--output", help="Optional local .json report")+ parser.add_argument("--force", action="store_true", help="Replace explicit output")+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ config = ExperimentConfig.from_mapping(+ load_json_object(args.config) if args.config else None+ )+ emit_json(+ run_experiment(config),+ output=args.output,+ force=args.force,+ )+ except CliError as exc:+ parser.error(str(exc))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/simpy/scripts/resource_monitor.py b/skills/simpy/scripts/resource_monitor.pyindex e2f623dc..b56b8155 100644--- a/skills/simpy/scripts/resource_monitor.py+++ b/skills/simpy/scripts/resource_monitor.py@@ -1,345 +1,474 @@#!/usr/bin/env python3-"""-SimPy Resource Monitoring Utilities+"""Bounded resource monitoring and deterministic event tracing for SimPy."""-This module provides reusable classes and functions for monitoring-SimPy resources during simulation. Includes utilities for tracking-queue lengths, utilization, wait times, and generating reports.-"""+from __future__ import annotations-import simpy-from collections import defaultdict-from typing import List, Tuple, Dict, Any+import argparse+import csv+import io+import json+from dataclasses import asdict, dataclass+from functools import wraps+from typing import TYPE_CHECKING, Any, Callable+if TYPE_CHECKING:+ import simpy-class ResourceMonitor:- """- Monitor resource usage with detailed statistics tracking.-- Tracks:- - Queue lengths over time- - Resource utilization- - Wait times for requests- - Request and release events- """-- def __init__(self, env: simpy.Environment, resource: simpy.Resource, name: str = "Resource"):- """- Initialize the resource monitor.-- Args:- env: SimPy environment- resource: Resource to monitor- name: Name for the resource (for reporting)- """- self.env = env- self.resource = resource- self.name = name-- # Data storage- self.queue_data: List[Tuple[float, int]] = [(0, 0)]- self.utilization_data: List[Tuple[float, float]] = [(0, 0.0)]- self.request_times: Dict[Any, float] = {}- self.wait_times: List[float] = []- self.events: List[Tuple[float, str, Dict]] = []-- # Patch the resource- self._patch_resource()-- def _patch_resource(self):- """Patch resource methods to intercept requests and releases."""- original_request = self.resource.request- original_release = self.resource.release-- def monitored_request(*args, **kwargs):- req = original_request(*args, **kwargs)-- # Record request event- queue_length = len(self.resource.queue)- utilization = self.resource.count / self.resource.capacity-- self.queue_data.append((self.env.now, queue_length))- self.utilization_data.append((self.env.now, utilization))- self.events.append((self.env.now, 'request', {- 'queue_length': queue_length,- 'utilization': utilization- }))+from _common import (+ MAX_TRACE_RECORDS,+ CliError,+ emit_json,+ emit_text,+ integer,+ load_simpy,+)- # Store request time for wait time calculation- self.request_times[req] = self.env.now- # Add callback to record when request is granted- def on_granted(event):- if req in self.request_times:- wait_time = self.env.now - self.request_times[req]- self.wait_times.append(wait_time)- del self.request_times[req]+@dataclass(frozen=True)+class ResourceSample:+ """One resource state observed at a simulation timestamp."""- req.callbacks.append(on_granted)- return req+ time: float+ event: str+ count: int+ queue_length: int+ utilization: float- def monitored_release(*args, **kwargs):- result = original_release(*args, **kwargs)- # Record release event- queue_length = len(self.resource.queue)- utilization = self.resource.count / self.resource.capacity-- self.queue_data.append((self.env.now, queue_length))- self.utilization_data.append((self.env.now, utilization))- self.events.append((self.env.now, 'release', {- 'queue_length': queue_length,- 'utilization': utilization- }))-- return result+class ResourceMonitor:+ """Monitor one Resource/PriorityResource/PreemptiveResource instance."""++ def __init__(+ self,+ env: simpy.Environment,+ resource: simpy.Resource,+ name: str = "resource",+ ):+ simpy_module = load_simpy()+ if not isinstance(+ resource,+ (+ simpy_module.Resource,+ simpy_module.PriorityResource,+ simpy_module.PreemptiveResource,+ ),+ ):+ raise CliError("ResourceMonitor requires a SimPy Resource-like object")+ if getattr(resource, "_simpy_skill_monitor_attached", False):+ raise CliError("this resource already has a ResourceMonitor")+ self.env = env+ self.resource = resource+ self.name = name+ self.samples: list[ResourceSample] = []+ self.wait_times: list[float] = []+ self._request_times: dict[Any, float] = {}+ self._original_request = resource.request+ self._original_release = resource.release+ setattr(resource, "_simpy_skill_monitor_attached", True)+ self._record("initial")+ self._patch()++ def _record(self, event: str, *, at: float | None = None) -> None:+ time = float(self.env.now if at is None else at)+ self.samples.append(+ ResourceSample(+ time=time,+ event=event,+ count=int(self.resource.count),+ queue_length=len(self.resource.queue),+ utilization=float(self.resource.count / self.resource.capacity),+ )+ )++ def _patch(self) -> None:+ @wraps(self._original_request)+ def monitored_request(*args: Any, **kwargs: Any) -> Any:+ requested_at = float(self.env.now)+ request = self._original_request(*args, **kwargs)+ self._request_times[request] = requested_at+ self._record("request")++ def granted(_: Any) -> None:+ start = self._request_times.pop(request, None)+ if start is not None:+ self.wait_times.append(float(self.env.now) - start)+ self._record("grant")++ if request.callbacks is not None:+ request.callbacks.append(granted)++ original_cancel = request.cancel++ @wraps(original_cancel)+ def monitored_cancel() -> None:+ original_cancel()+ self._request_times.pop(request, None)+ self._record("cancel")++ try:+ request.cancel = monitored_cancel+ except (AttributeError, TypeError):+ # Current SimPy events allow instance wrappers. If a future release+ # changes that implementation, later state samples remain valid but+ # cancellation instants may need explicit user instrumentation.+ pass+ return request++ @wraps(self._original_release)+ def monitored_release(*args: Any, **kwargs: Any) -> Any:+ released = self._original_release(*args, **kwargs)+ self._record("release")+ return releasedself.resource.request = monitored_requestself.resource.release = monitored_release- def average_queue_length(self) -> float:- """Calculate time-weighted average queue length."""- if len(self.queue_data) < 2:- return 0.0-- total_time = 0.0- weighted_sum = 0.0-- for i in range(len(self.queue_data) - 1):- time1, length1 = self.queue_data[i]- time2, length2 = self.queue_data[i + 1]- duration = time2 - time1- total_time += duration- weighted_sum += length1 * duration-- return weighted_sum / total_time if total_time > 0 else 0.0-- def average_utilization(self) -> float:- """Calculate time-weighted average utilization."""- if len(self.utilization_data) < 2:- return 0.0-- total_time = 0.0- weighted_sum = 0.0-- for i in range(len(self.utilization_data) - 1):- time1, util1 = self.utilization_data[i]- time2, util2 = self.utilization_data[i + 1]- duration = time2 - time1- total_time += duration- weighted_sum += util1 * duration-- return weighted_sum / total_time if total_time > 0 else 0.0-- def average_wait_time(self) -> float:- """Calculate average wait time for requests."""- return sum(self.wait_times) / len(self.wait_times) if self.wait_times else 0.0-- def max_queue_length(self) -> int:- """Get maximum queue length observed."""- return max(length for _, length in self.queue_data) if self.queue_data else 0-- def report(self):- """Print detailed statistics report."""- print(f"\n{'=' * 60}")- print(f"RESOURCE MONITOR REPORT: {self.name}")- print(f"{'=' * 60}")- print(f"Simulation time: 0.00 to {self.env.now:.2f}")- print(f"Capacity: {self.resource.capacity}")- print(f"\nUtilization:")- print(f" Average: {self.average_utilization():.2%}")- print(f" Final: {self.resource.count / self.resource.capacity:.2%}")- print(f"\nQueue Statistics:")- print(f" Average length: {self.average_queue_length():.2f}")- print(f" Max length: {self.max_queue_length()}")- print(f" Final length: {len(self.resource.queue)}")- print(f"\nWait Time Statistics:")- print(f" Total requests: {len(self.wait_times)}")- if self.wait_times:- print(f" Average wait: {self.average_wait_time():.2f}")- print(f" Max wait: {max(self.wait_times):.2f}")- print(f" Min wait: {min(self.wait_times):.2f}")- print(f"\nEvent Summary:")- print(f" Total events: {len(self.events)}")- request_count = sum(1 for _, event_type, _ in self.events if event_type == 'request')- release_count = sum(1 for _, event_type, _ in self.events if event_type == 'release')- print(f" Requests: {request_count}")- print(f" Releases: {release_count}")- print(f"{'=' * 60}")-- def export_csv(self, filename: str):- """- Export monitoring data to CSV file.-- Args:- filename: Output CSV filename- """- import csv-- with open(filename, 'w', newline='') as f:- writer = csv.writer(f)- writer.writerow(['Time', 'Event', 'Queue Length', 'Utilization'])-- for time, event_type, data in self.events:- writer.writerow([- time,- event_type,- data['queue_length'],- data['utilization']- ])-- print(f"Data exported to {filename}")+ def detach(self) -> None:+ """Restore the resource methods patched by this monitor."""++ self.resource.request = self._original_request+ self.resource.release = self._original_release+ setattr(self.resource, "_simpy_skill_monitor_attached", False)++ def finalize(self, *, at: float | None = None) -> None:+ """Close the final time interval with the resource's current state."""++ final_time = float(self.env.now if at is None else at)+ if final_time < self.samples[-1].time:+ raise CliError("monitor final time cannot precede its latest sample")+ self._record("final", at=final_time)++ def _time_weighted(+ self,+ attribute: str,+ *,+ start: float,+ end: float,+ ) -> float:+ if start < self.samples[0].time:+ raise CliError("monitor window starts before monitoring began")+ if end <= start:+ raise CliError("monitor window end must be greater than start")+ if end > self.samples[-1].time:+ raise CliError("call finalize() through the requested window end first")++ current = self.samples[0]+ for sample in self.samples:+ if sample.time <= start:+ current = sample+ else:+ break+ cursor = start+ weighted = 0.0+ for sample in self.samples:+ if sample.time <= start:+ continue+ if sample.time >= end:+ break+ weighted += float(getattr(current, attribute)) * (sample.time - cursor)+ cursor = sample.time+ current = sample+ weighted += float(getattr(current, attribute)) * (end - cursor)+ return weighted / (end - start)++ def average_queue_length(+ self, *, start: float = 0.0, end: float | None = None+ ) -> float:+ """Return the time-weighted queue length over [start, end)."""++ final = self.samples[-1].time if end is None else float(end)+ return self._time_weighted(+ "queue_length", start=float(start), end=final+ )++ def average_utilization(+ self, *, start: float = 0.0, end: float | None = None+ ) -> float:+ """Return time-weighted allocated capacity over [start, end)."""++ final = self.samples[-1].time if end is None else float(end)+ return self._time_weighted("utilization", start=float(start), end=final)++ def summary(+ self, *, start: float = 0.0, end: float | None = None+ ) -> dict[str, Any]:+ """Return a JSON-compatible summary of this monitor."""++ final = self.samples[-1].time if end is None else float(end)+ return {+ "average_queue_length": self.average_queue_length(+ start=start, end=final+ ),+ "average_utilization": self.average_utilization(+ start=start, end=final+ ),+ "capacity": self.resource.capacity,+ "end": final,+ "final_count": self.resource.count,+ "final_queue_length": len(self.resource.queue),+ "granted_requests": len(self.wait_times),+ "maximum_queue_length": max(+ sample.queue_length for sample in self.samples+ ),+ "mean_wait": (+ sum(self.wait_times) / len(self.wait_times)+ if self.wait_times+ else None+ ),+ "name": self.name,+ "pending_requests": len(self._request_times),+ "samples": len(self.samples),+ "start": start,+ }++ def export_csv(self, output: str, *, force: bool = False) -> None:+ """Write state samples to a bounded, private local CSV."""++ buffer = io.StringIO(newline="")+ writer = csv.DictWriter(+ buffer,+ fieldnames=[+ "time",+ "event",+ "count",+ "queue_length",+ "utilization",+ ],+ )+ writer.writeheader()+ for sample in self.samples:+ writer.writerow(asdict(sample))+ emit_text(buffer.getvalue(), output=output, suffixes={".csv"}, force=force)class MultiResourceMonitor:- """Monitor multiple resources simultaneously."""+ """Manage uniquely named ResourceMonitor instances in one environment."""def __init__(self, env: simpy.Environment):- """- Initialize multi-resource monitor.-- Args:- env: SimPy environment- """+ load_simpy()self.env = env- self.monitors: Dict[str, ResourceMonitor] = {}-- def add_resource(self, resource: simpy.Resource, name: str):- """- Add a resource to monitor.+ self.monitors: dict[str, ResourceMonitor] = {}- Args:- resource: SimPy resource to monitor- name: Name for the resource- """+ def add_resource(+ self, resource: simpy.Resource, name: str+ ) -> ResourceMonitor:+ if not name or name in self.monitors:+ raise CliError("resource monitor names must be non-empty and unique")monitor = ResourceMonitor(self.env, resource, name)self.monitors[name] = monitorreturn monitor- def report_all(self):- """Generate reports for all monitored resources."""- for name, monitor in self.monitors.items():- monitor.report()-- def summary(self):- """Print summary statistics for all resources."""- print(f"\n{'=' * 60}")- print("MULTI-RESOURCE SUMMARY")- print(f"{'=' * 60}")- print(f"{'Resource':<20} {'Avg Util':<12} {'Avg Queue':<12} {'Avg Wait':<12}")- print(f"{'-' * 20} {'-' * 12} {'-' * 12} {'-' * 12}")-- for name, monitor in self.monitors.items():- print(f"{name:<20} {monitor.average_utilization():<12.2%} "- f"{monitor.average_queue_length():<12.2f} "- f"{monitor.average_wait_time():<12.2f}")+ def finalize(self, *, at: float | None = None) -> None:+ for monitor in self.monitors.values():+ monitor.finalize(at=at)- print(f"{'=' * 60}")+ def summaries(+ self, *, start: float = 0.0, end: float | None = None+ ) -> dict[str, dict[str, Any]]:+ return {+ name: monitor.summary(start=start, end=end)+ for name, monitor in self.monitors.items()+ }class ContainerMonitor:- """Monitor Container resources (for tracking level changes)."""-- def __init__(self, env: simpy.Environment, container: simpy.Container, name: str = "Container"):- """- Initialize container monitor.-- Args:- env: SimPy environment- container: Container to monitor- name: Name for the container- """+ """Record completed put/get operations and time-weighted Container level."""++ def __init__(+ self,+ env: simpy.Environment,+ container: simpy.Container,+ name: str = "container",+ ):+ load_simpy()+ if getattr(container, "_simpy_skill_monitor_attached", False):+ raise CliError("this container already has a ContainerMonitor")self.env = envself.container = containerself.name = name- self.level_data: List[Tuple[float, float]] = [(0, container.level)]-- self._patch_container()-- def _patch_container(self):- """Patch container methods to track level changes."""- original_put = self.container.put- original_get = self.container.get-- def monitored_put(amount):- result = original_put(amount)-- def on_put(event):- self.level_data.append((self.env.now, self.container.level))-- result.callbacks.append(on_put)- return result-- def monitored_get(amount):- result = original_get(amount)-- def on_get(event):- self.level_data.append((self.env.now, self.container.level))-- result.callbacks.append(on_get)- return result-- self.container.put = monitored_put- self.container.get = monitored_get-- def average_level(self) -> float:- """Calculate time-weighted average level."""- if len(self.level_data) < 2:- return self.level_data[0][1] if self.level_data else 0.0-- total_time = 0.0- weighted_sum = 0.0-- for i in range(len(self.level_data) - 1):- time1, level1 = self.level_data[i]- time2, level2 = self.level_data[i + 1]- duration = time2 - time1- total_time += duration- weighted_sum += level1 * duration-- return weighted_sum / total_time if total_time > 0 else 0.0-- def report(self):- """Print container statistics."""- print(f"\n{'=' * 60}")- print(f"CONTAINER MONITOR REPORT: {self.name}")- print(f"{'=' * 60}")- print(f"Capacity: {self.container.capacity}")- print(f"Current level: {self.container.level:.2f}")- print(f"Average level: {self.average_level():.2f}")- print(f"Utilization: {self.average_level() / self.container.capacity:.2%}")-- if self.level_data:- levels = [level for _, level in self.level_data]- print(f"Max level: {max(levels):.2f}")- print(f"Min level: {min(levels):.2f}")-- print(f"{'=' * 60}")+ self.samples: list[tuple[float, str, float]] = [+ (float(env.now), "initial", float(container.level))+ ]+ self._original_put = container.put+ self._original_get = container.get+ setattr(container, "_simpy_skill_monitor_attached", True)+ self._patch()++ def _record(self, event: str, *, at: float | None = None) -> None:+ self.samples.append(+ (+ float(self.env.now if at is None else at),+ event,+ float(self.container.level),+ )+ )++ def _patch_operation(+ self, operation: Callable[..., Any], event_name: str+ ) -> Callable[..., Any]:+ @wraps(operation)+ def wrapper(*args: Any, **kwargs: Any) -> Any:+ event = operation(*args, **kwargs)+ if event.callbacks is not None:+ event.callbacks.append(lambda _: self._record(event_name))+ return event++ return wrapper++ def _patch(self) -> None:+ self.container.put = self._patch_operation(self._original_put, "put")+ self.container.get = self._patch_operation(self._original_get, "get")++ def finalize(self, *, at: float | None = None) -> None:+ final_time = float(self.env.now if at is None else at)+ if final_time < self.samples[-1][0]:+ raise CliError("monitor final time cannot precede its latest sample")+ self._record("final", at=final_time)++ def average_level(+ self, *, start: float = 0.0, end: float | None = None+ ) -> float:+ final = self.samples[-1][0] if end is None else float(end)+ if final <= start:+ raise CliError("monitor window end must be greater than start")+ if final > self.samples[-1][0]:+ raise CliError("call finalize() through the requested window end first")+ current = self.samples[0]+ for sample in self.samples:+ if sample[0] <= start:+ current = sample+ else:+ break+ cursor = start+ weighted = 0.0+ for sample in self.samples:+ if sample[0] <= start:+ continue+ if sample[0] >= final:+ break+ weighted += current[2] * (sample[0] - cursor)+ cursor = sample[0]+ current = sample+ weighted += current[2] * (final - cursor)+ return weighted / (final - start)+++class EventTraceRecorder:+ """Trace the next queued event before each Environment.step() call."""++ def __init__(+ self,+ env: simpy.Environment,+ *,+ max_records: int = 100_000,+ ):+ load_simpy()+ self.env = env+ self.max_records = integer(+ max_records,+ name="max_records",+ minimum=1,+ maximum=MAX_TRACE_RECORDS,+ )+ self.records: list[dict[str, Any]] = []+ self.truncated = False+ self._original_step = env.step+ self._patch()++ def _patch(self) -> None:+ @wraps(self._original_step)+ def tracing_step() -> None:+ queue = getattr(self.env, "_queue", None)+ if queue:+ if len(self.records) < self.max_records:+ time, priority, event_id, event = queue[0]+ self.records.append(+ {+ "event_id": int(event_id),+ "event_type": type(event).__name__,+ "priority": int(priority),+ "queue_size_before": len(queue),+ "time": float(time),+ }+ )+ else:+ self.truncated = True+ self._original_step()++ self.env.step = tracing_step++ def detach(self) -> None:+ self.env.step = self._original_step++ def export_jsonl(self, output: str, *, force: bool = False) -> None:+ """Write deterministic JSON Lines without object repr or memory addresses."""++ text = "".join(+ json.dumps(+ record,+ sort_keys=True,+ ensure_ascii=False,+ allow_nan=False,+ separators=(",", ":"),+ )+ + "\n"+ for record in self.records+ )+ emit_text(text, output=output, suffixes={".jsonl"}, force=force)+++def _demo() -> tuple[dict[str, Any], ResourceMonitor]:+ simpy_module = load_simpy()+ env = simpy_module.Environment()+ resource = simpy_module.Resource(env, capacity=2)+ monitor = ResourceMonitor(env, resource, "demo_server")++ def user(identifier: int) -> Any:+ yield env.timeout(identifier * 0.5)+ with resource.request() as request:+ yield request+ yield env.timeout(1.0 + identifier * 0.1)++ for index in range(8):+ env.process(user(index))+ env.run(until=10)+ monitor.finalize(at=10)+ return monitor.summary(start=0, end=10), monitor+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Run a finite synthetic Resource-monitor demonstration and emit a "+ "time-weighted summary. No network or external service is used."+ )+ )+ parser.add_argument("--output", help="Optional local .json summary")+ parser.add_argument("--samples", help="Optional local .csv state samples")+ parser.add_argument("--force", action="store_true", help="Replace explicit outputs")+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ summary, monitor = _demo()+ if args.samples:+ monitor.export_csv(args.samples, force=args.force)+ emit_json(+ {+ "monitor": summary,+ "network_used": False,+ "schema_version": "1.1",+ },+ output=args.output,+ force=args.force,+ )+ except CliError as exc:+ parser.error(str(exc))+ return 0-# Example usageif __name__ == "__main__":- def example_process(env, name, resource, duration):- """Example process using a resource."""- with resource.request() as req:- yield req- print(f"{name} started at {env.now}")- yield env.timeout(duration)- print(f"{name} finished at {env.now}")-- # Create environment and resource- env = simpy.Environment()- resource = simpy.Resource(env, capacity=2)-- # Create monitor- monitor = ResourceMonitor(env, resource, "Example Resource")-- # Start processes- for i in range(5):- env.process(example_process(env, f"Process {i}", resource, 3 + i))-- # Run simulation- env.run()-- # Generate report- monitor.report()+ raise SystemExit(main())diff --git a/skills/simpy/scripts/validate_simulation_config.py b/skills/simpy/scripts/validate_simulation_config.pynew file mode 100644index 00000000..1d98510a--- /dev/null+++ b/skills/simpy/scripts/validate_simulation_config.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""Validate bounded queue or replication JSON without running a simulation."""++from __future__ import annotations++import argparse+from dataclasses import asdict+from typing import Any++from _common import CliError, emit_json, load_json_object+from basic_simulation_template import QueueConfig+from replication_runner import (+ MAX_TOTAL_ENTITY_BUDGET,+ MAX_TOTAL_EVENT_BUDGET,+ ExperimentConfig,+)+++def infer_schema(document: dict[str, Any]) -> str:+ """Infer only the two bundled schemas; never resolve a plugin or import path."""++ replication_markers = {"model", "replications", "confidence"}+ return "replication" if set(document) & replication_markers else "queue"+++def validate_document(+ document: dict[str, Any], *, schema: str = "auto"+) -> dict[str, Any]:+ """Return normalized validated configuration metadata."""++ if schema not in {"auto", "queue", "replication"}:+ raise CliError("schema must be auto, queue, or replication")+ resolved = infer_schema(document) if schema == "auto" else schema+ if resolved == "queue":+ queue = QueueConfig.from_mapping(document)+ normalized: dict[str, Any] = asdict(queue)+ budgets = {+ "entities": queue.max_entities,+ "events": queue.max_events,+ "replications": 1,+ "time": queue.horizon,+ }+ else:+ experiment = ExperimentConfig.from_mapping(document)+ normalized = {+ "confidence": experiment.confidence,+ "model": asdict(experiment.model),+ "replications": experiment.replications,+ }+ budgets = {+ "entities": experiment.model.max_entities+ * experiment.replications,+ "events": experiment.model.max_events * experiment.replications,+ "replications": experiment.replications,+ "time_per_replication": experiment.model.horizon,+ }+ return {+ "budgets": budgets,+ "limits": {+ "total_entities_for_replication_schema": MAX_TOTAL_ENTITY_BUDGET,+ "total_events_for_replication_schema": MAX_TOTAL_EVENT_BUDGET,+ },+ "network_used": False,+ "normalized": normalized,+ "schema": resolved,+ "schema_version": "1.1",+ "validation": {+ "config_allowlist": True,+ "finite_numeric_values": True,+ "no_code_execution": True,+ "valid": True,+ },+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate and normalize an allowlisted local queue or replication "+ "JSON configuration. This command does not execute a simulation."+ )+ )+ parser.add_argument("config", help="Local .json input; URLs and symlinks rejected")+ parser.add_argument(+ "--schema",+ choices=("auto", "queue", "replication"),+ default="auto",+ help="Configuration schema (default: auto)",+ )+ parser.add_argument("--output", help="Optional local .json validation report")+ parser.add_argument("--force", action="store_true", help="Replace explicit output")+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ document = load_json_object(args.config)+ emit_json(+ validate_document(document, schema=args.schema),+ output=args.output,+ force=args.force,+ )+ except CliError as exc:+ parser.error(str(exc))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/simpy/tests/test_scripts.py b/skills/simpy/tests/test_scripts.pynew file mode 100644index 00000000..8faf8234--- /dev/null+++ b/skills/simpy/tests/test_scripts.py@@ -0,0 +1,454 @@+#!/usr/bin/env python3+"""Synthetic, network-free tests for the SimPy skill scripts."""++from __future__ import annotations++import ast+import json+import math+import stat+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++import simpy+++SKILL_ROOT = Path(__file__).resolve().parents[1]+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import _common # noqa: E402+import basic_simulation_template # noqa: E402+import bounded_queue_scenario # noqa: E402+import event_trace_summary # noqa: E402+import replication_runner # noqa: E402+import resource_monitor # noqa: E402+import validate_simulation_config # noqa: E402+++class SafetyTests(unittest.TestCase):+ def test_scripts_parse_and_do_not_use_dangerous_features(self) -> None:+ banned_imports = {+ "aiohttp",+ "httpx",+ "importlib",+ "requests",+ "socket",+ "subprocess",+ "urllib",+ }+ banned_calls = {"eval", "exec", "compile", "__import__"}+ for path in sorted(SCRIPTS.glob("*.py")):+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ roots = {alias.name.split(".", 1)[0] for alias in node.names}+ self.assertFalse(roots & banned_imports, path.name)+ if isinstance(node, ast.ImportFrom) and node.module:+ self.assertNotIn(+ node.module.split(".", 1)[0], banned_imports, path.name+ )+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):+ self.assertNotIn(node.func.id, banned_calls, path.name)+ if isinstance(node, ast.Attribute):+ self.assertFalse(+ isinstance(node.value, ast.Name)+ and node.value.id == "os"+ and node.attr in {"environ", "getenv"},+ path.name,+ )++ def test_local_json_rejects_urls_symlinks_duplicates_and_nan(self) -> None:+ with self.assertRaises(_common.CliError):+ _common.load_json_object("https://example.invalid/config.json")+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ duplicate = root / "duplicate.json"+ duplicate.write_text('{"horizon": 1, "horizon": 2}', encoding="utf-8")+ with self.assertRaises(_common.CliError):+ _common.load_json_object(duplicate)+ nonstandard = root / "nan.json"+ nonstandard.write_text('{"horizon": NaN}', encoding="utf-8")+ with self.assertRaises(_common.CliError):+ _common.load_json_object(nonstandard)+ real = root / "real.json"+ real.write_text("{}", encoding="utf-8")+ link = root / "link.json"+ try:+ link.symlink_to(real)+ except OSError:+ self.skipTest("symlinks unavailable")+ with self.assertRaises(_common.CliError):+ _common.load_json_object(link)++ def test_private_output_refuses_overwrite(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ output = Path(directory) / "report.json"+ _common.emit_json({"ok": True}, output=output)+ self.assertEqual(json.loads(output.read_text()), {"ok": True})+ self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)+ with self.assertRaises(_common.CliError):+ _common.emit_json({"ok": False}, output=output)++ def test_every_cli_has_side_effect_free_help(self) -> None:+ modules = (+ basic_simulation_template,+ bounded_queue_scenario,+ event_trace_summary,+ replication_runner,+ resource_monitor,+ validate_simulation_config,+ )+ for module in modules:+ with self.subTest(module=module.__name__):+ help_text = module.build_parser().format_help()+ self.assertIn("usage:", help_text)+ self.assertIn("--help", help_text)++ def test_every_script_help_succeeds_without_site_packages(self) -> None:+ for path in sorted(SCRIPTS.glob("*.py")):+ with self.subTest(script=path.name):+ result = subprocess.run(+ [sys.executable, "-S", str(path), "--help"],+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertNotIn("Traceback", result.stderr)+ if path.name != "_common.py":+ self.assertIn("usage:", result.stdout)++ def test_simulation_clis_report_missing_dependency_without_traceback(self) -> None:+ for name in (+ "basic_simulation_template.py",+ "bounded_queue_scenario.py",+ "replication_runner.py",+ "resource_monitor.py",+ ):+ with self.subTest(script=name):+ result = subprocess.run(+ [sys.executable, "-S", str(SCRIPTS / name)],+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(_common.PINNED_INSTALL, result.stderr)+ self.assertIn("SimPy 4.1.2 is required", result.stderr)+ self.assertNotIn("Traceback", result.stderr)+++class CoreSemanticsTests(unittest.TestCase):+ def test_same_time_events_are_fifo_deterministic(self) -> None:+ env = simpy.Environment()+ order: list[str] = []++ def process(label: str):+ yield env.timeout(1)+ order.append(label)++ env.process(process("first"))+ env.process(process("second"))+ env.run()+ self.assertEqual(order, ["first", "second"])++ def test_numeric_until_excludes_boundary_and_event_until_returns_value(self) -> None:+ env = simpy.Environment()+ boundary = env.timeout(5, value="done")+ env.run(until=5)+ self.assertEqual(env.now, 5)+ self.assertFalse(boundary.processed)++ event_env = simpy.Environment()+ target = event_env.timeout(5, value="done")+ self.assertEqual(event_env.run(until=target), "done")+ self.assertEqual(event_env.now, 5)+ # SimPy 4.1.2 preserves remaining callbacks by rescheduling the target;+ # the run criterion has fired, but one more step marks it processed.+ self.assertFalse(target.processed)+ event_env.step()+ self.assertTrue(target.processed)++ def test_process_return_and_condition_mapping(self) -> None:+ env = simpy.Environment()++ def worker():+ yield env.timeout(1)+ return 7++ process = env.process(worker())+ first = env.timeout(2, value="a")+ second = env.timeout(3, value="b")++ def coordinator():+ process_value = yield process+ condition_value = yield first & second+ return process_value, list(condition_value.items())++ result = env.run(until=env.process(coordinator()))+ self.assertEqual(result[0], 7)+ self.assertEqual(result[1], [(first, "a"), (second, "b")])++ def test_preemption_interrupt_cause_identifies_request_and_usage(self) -> None:+ env = simpy.Environment()+ resource = simpy.PreemptiveResource(env, capacity=1)+ observed: dict[str, object] = {}++ def low_priority():+ with resource.request(priority=5) as request:+ try:+ yield request+ yield env.timeout(10)+ except simpy.Interrupt as interrupt:+ observed["by"] = interrupt.cause.by+ observed["usage_since"] = interrupt.cause.usage_since++ def high_priority():+ yield env.timeout(2)+ with resource.request(priority=0, preempt=True) as request:+ yield request+ yield env.timeout(1)++ low = env.process(low_priority())+ high = env.process(high_priority())+ env.run()+ self.assertIs(observed["by"], high)+ self.assertEqual(observed["usage_since"], 0)+ self.assertTrue(low.processed)++ def test_priority_resource_orders_queued_requests(self) -> None:+ env = simpy.Environment()+ resource = simpy.PriorityResource(env, capacity=1)+ order: list[str] = []++ def user(name: str, priority: int, delay: float, duration: float):+ yield env.timeout(delay)+ with resource.request(priority=priority) as request:+ yield request+ order.append(name)+ yield env.timeout(duration)++ env.process(user("holder", 0, 0, 3))+ env.process(user("routine", 10, 1, 1))+ env.process(user("urgent", 1, 1, 1))+ env.run()+ self.assertEqual(order, ["holder", "urgent", "routine"])++ def test_container_and_store_variants(self) -> None:+ env = simpy.Environment()+ container = simpy.Container(env, capacity=10, init=5)+ store = simpy.Store(env, capacity=2)+ filtered = simpy.FilterStore(env, capacity=2)+ priority = simpy.PriorityStore(env)+ observed: list[object] = []++ def exercise():+ yield container.put(3)+ observed.append((yield container.get(4)))+ yield store.put("fifo")+ observed.append((yield store.get()))+ yield filtered.put({"kind": "keep"})+ observed.append(+ (yield filtered.get(lambda item: item["kind"] == "keep"))+ )+ yield priority.put(simpy.PriorityItem(2, "later"))+ yield priority.put(simpy.PriorityItem(1, "first"))+ observed.append((yield priority.get()).item)++ env.process(exercise())+ env.run()+ self.assertEqual(container.level, 4)+ self.assertEqual(observed, [None, "fifo", {"kind": "keep"}, "first"])+++class MonitoringTests(unittest.TestCase):+ def test_resource_monitor_uses_time_weighting(self) -> None:+ env = simpy.Environment()+ resource = simpy.Resource(env, capacity=1)+ monitor = resource_monitor.ResourceMonitor(env, resource)++ def user(delay: float, duration: float):+ yield env.timeout(delay)+ with resource.request() as request:+ yield request+ yield env.timeout(duration)++ env.process(user(0, 2))+ env.process(user(1, 1))+ env.run(until=4)+ monitor.finalize(at=4)+ self.assertAlmostEqual(+ monitor.average_utilization(start=0, end=4), 0.75+ )+ self.assertAlmostEqual(+ monitor.average_queue_length(start=0, end=4), 0.25+ )+ self.assertEqual(len(monitor.wait_times), 2)++ def test_pending_request_cancellation_is_recorded(self) -> None:+ env = simpy.Environment()+ resource = simpy.Resource(env, capacity=1)+ monitor = resource_monitor.ResourceMonitor(env, resource)++ def holder():+ with resource.request() as request:+ yield request+ yield env.timeout(3)++ def impatient():+ yield env.timeout(0.5)+ with resource.request() as request:+ result = yield request | env.timeout(0.5)+ self.assertNotIn(request, result)++ env.process(holder())+ env.process(impatient())+ env.run(until=4)+ monitor.finalize(at=4)+ self.assertEqual(len(resource.queue), 0)+ self.assertEqual(monitor.summary(end=4)["pending_requests"], 0)+ self.assertIn("cancel", [sample.event for sample in monitor.samples])++ def test_trace_round_trip_and_order_summary(self) -> None:+ env = simpy.Environment()+ trace = resource_monitor.EventTraceRecorder(env, max_records=20)+ env.timeout(2)+ env.timeout(1)+ env.run()+ with tempfile.TemporaryDirectory() as directory:+ output = Path(directory) / "trace.jsonl"+ trace.export_jsonl(str(output))+ summary = event_trace_summary.summarize_event_trace(+ output, max_records=20+ )+ self.assertEqual(summary["records"], 2)+ self.assertEqual(summary["ordering_violations"], 0)+ self.assertEqual(summary["first_time"], 1)+++class ScenarioTests(unittest.TestCase):+ def test_queue_run_is_reproducible_and_bounded(self) -> None:+ config = basic_simulation_template.QueueConfig.from_mapping(+ {+ "horizon": 80,+ "max_entities": 200,+ "max_events": 5000,+ "mean_interarrival": 1,+ "mean_service": 3,+ "queue_capacity": 2,+ "servers": 1,+ }+ )+ first = basic_simulation_template.run_simulation(config)+ second = basic_simulation_template.run_simulation(config)+ self.assertEqual(first, second)+ self.assertGreater(first["counters"]["rejected"], 0)+ self.assertLessEqual(first["event_processing"]["processed"], 5000)+ self.assertLessEqual(first["counters"]["arrivals"], 200)++ def test_unknown_config_and_invalid_modes_are_rejected(self) -> None:+ with self.assertRaises(_common.CliError):+ basic_simulation_template.QueueConfig.from_mapping(+ {"plugin": "untrusted.module"}+ )+ with self.assertRaises(_common.CliError):+ basic_simulation_template.QueueConfig.from_mapping(+ {"analysis_mode": "steady_state", "warm_up": 0}+ )+ with self.assertRaises(_common.CliError):+ basic_simulation_template.QueueConfig.from_mapping(+ {"analysis_mode": "terminating", "warm_up": 1}+ )++ def test_event_limit_stops_run(self) -> None:+ config = basic_simulation_template.QueueConfig.from_mapping(+ {+ "horizon": 100,+ "max_entities": 100,+ "max_events": 10,+ "mean_interarrival": 0.1,+ "mean_service": 1,+ }+ )+ with self.assertRaises(_common.CliError):+ basic_simulation_template.run_simulation(config)+++class ReplicationTests(unittest.TestCase):+ def test_student_t_interval_and_quantile(self) -> None:+ interval = _common.mean_confidence_interval(+ [1.0, 2.0, 3.0, 4.0], confidence=0.95+ )+ self.assertAlmostEqual(interval["mean"], 2.5)+ self.assertAlmostEqual(+ _common.student_t_quantile(0.975, 3), 3.182446, places=5+ )+ self.assertGreater(interval["upper"], interval["mean"])+ self.assertLess(interval["lower"], interval["mean"])+ with self.assertRaises(_common.CliError):+ _common.mean_confidence_interval([1.0])++ def test_replication_config_requires_multiple_bounded_runs(self) -> None:+ with self.assertRaises(_common.CliError):+ replication_runner.ExperimentConfig.from_mapping(+ {"replications": 1}+ )+ with self.assertRaises(_common.CliError):+ replication_runner.ExperimentConfig.from_mapping(+ {+ "replications": 1000,+ "model": {"max_events": 1_000_000},+ }+ )++ def test_small_replication_experiment_has_replication_level_ci(self) -> None:+ config = replication_runner.ExperimentConfig.from_mapping(+ {+ "confidence": 0.9,+ "model": {+ "horizon": 60,+ "max_entities": 100,+ "max_events": 5000,+ },+ "replications": 4,+ }+ )+ report = replication_runner.run_experiment(config)+ self.assertFalse(report["analysis"]["single_run_interval"])+ self.assertEqual(+ report["intervals"]["throughput_per_time_unit"]["replications"], 4+ )+ seeds = {+ run["seed_manifest"]["arrival_seed"]+ for run in report["replications"]+ }+ self.assertEqual(len(seeds), 4)+++class ValidatorTests(unittest.TestCase):+ def test_validator_normalizes_both_schemas_without_running(self) -> None:+ queue = validate_simulation_config.validate_document(+ {"horizon": 12}, schema="queue"+ )+ self.assertEqual(queue["schema"], "queue")+ self.assertTrue(queue["validation"]["no_code_execution"])+ replication = validate_simulation_config.validate_document(+ {+ "model": {+ "horizon": 12,+ "max_entities": 20,+ "max_events": 100,+ },+ "replications": 3,+ }+ )+ self.assertEqual(replication["schema"], "replication")+ self.assertEqual(replication["budgets"]["events"], 300)+++if __name__ == "__main__":+ unittest.main()