smolpy 1.9.1.dev4__tar.gz → 1.9.1.dev8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/PKG-INFO +2 -2
  2. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/README.md +1 -1
  3. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0004-execution-backends.md +63 -7
  4. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0009-batch-execution-and-cross-backend-validation.md +1 -1
  5. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/dsl-reference.md +1 -1
  6. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/roadmap.md +9 -4
  7. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/backends.py +10 -18
  8. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/model/frames.py +21 -8
  9. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/ns3/__init__.py +128 -15
  10. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/ns3/cpp/smol-ns3.cc +570 -44
  11. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/equivalence/harness.py +27 -0
  12. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/equivalence/test_equivalence.py +45 -2
  13. smolpy-1.9.1.dev8/tests/test_ns3.py +319 -0
  14. smolpy-1.9.1.dev4/tests/test_ns3.py +0 -127
  15. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/ci.yml +0 -0
  16. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/dev-build.yml +0 -0
  17. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/docker-image.yml +0 -0
  18. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/docs.yml +0 -0
  19. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/github-release.yml +0 -0
  20. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/ns3-base.yml +0 -0
  21. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/publish.yml +0 -0
  22. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/release.yml +0 -0
  23. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.github/workflows/rust-wheels.yml +0 -0
  24. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/.gitignore +0 -0
  25. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/LICENSE +0 -0
  26. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/__init__.py +0 -0
  27. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/__main__.py +0 -0
  28. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/results/2026-11-13-0921-simpy-jaws-zbook-baseline.json +0 -0
  29. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/results/2026-11-13-1527-simpy-jaws-zbook-optimised.json +0 -0
  30. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/results/2026-11-13-2116-simpy-jaws-zbook-research-batch.json +0 -0
  31. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/results/2026-11-13-2119-simpy-jaws-zbook-research-b4.json +0 -0
  32. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/results/2026-11-15-1255-rust-jaws-zbook-stop-criterion.json +0 -0
  33. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/results/2026-11-15-1333-rust-jaws-zbook-research-b4.json +0 -0
  34. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/results/2026-11-15-1346-rust-jaws-zbook-research-batch.json +0 -0
  35. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/runner.py +0 -0
  36. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/scenarios.py +0 -0
  37. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/benchmarks/worker.py +0 -0
  38. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docker/Dockerfile +0 -0
  39. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docker/Dockerfile.dockerignore +0 -0
  40. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docker/ns3-base/Dockerfile +0 -0
  41. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docker/ns3-base/smoke.cc +0 -0
  42. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docker/smoke.smol +0 -0
  43. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0001-protocol-package-structure.md +0 -0
  44. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0002-modbus-tcp-implementation.md +0 -0
  45. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0003-smol-external-dsl.md +0 -0
  46. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0005-profinet-rt.md +0 -0
  47. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0006-profiling-and-baseline-benchmark.md +0 -0
  48. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0007-execution-independent-scenario-model.md +0 -0
  49. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0008-rust-des-engine-mvp.md +0 -0
  50. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/adr/0010-ethernet-frames-on-the-wire.md +0 -0
  51. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/benchmarks.md +0 -0
  52. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/dashboard.md +0 -0
  53. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/examples.md +0 -0
  54. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/index.md +0 -0
  55. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/language-reference.md +0 -0
  56. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/modbus.md +0 -0
  57. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/model-semantics.md +0 -0
  58. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/mqtt.md +0 -0
  59. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/profinet.md +0 -0
  60. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/scenario-model.md +0 -0
  61. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/docs/simulation-engine.md +0 -0
  62. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/README.md +0 -0
  63. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example.py +0 -0
  64. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example.smol +0 -0
  65. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_10_clients.py +0 -0
  66. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_12_clients.py +0 -0
  67. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_20_clients.py +0 -0
  68. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_file_transfer.py +0 -0
  69. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_modbus.py +0 -0
  70. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_mqtt.py +0 -0
  71. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_profinet.py +0 -0
  72. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_profinet.smol +0 -0
  73. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_staggered_transfer.py +0 -0
  74. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/examples/example_two_tier.py +0 -0
  75. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/mkdocs.yml +0 -0
  76. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/pyproject.toml +0 -0
  77. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/Cargo.lock +0 -0
  78. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/Cargo.toml +0 -0
  79. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smol-engine/Cargo.toml +0 -0
  80. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smol-engine/src/frames.rs +0 -0
  81. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smol-engine/src/lib.rs +0 -0
  82. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smol-engine/src/rng.rs +0 -0
  83. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smol-engine/src/scenario.rs +0 -0
  84. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smol-engine/src/sim.rs +0 -0
  85. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smol-engine/src/timebase.rs +0 -0
  86. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smolpy-engine-rs/Cargo.toml +0 -0
  87. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smolpy-engine-rs/README.md +0 -0
  88. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smolpy-engine-rs/pyproject.toml +0 -0
  89. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smolpy-engine-rs/smoke_test.py +0 -0
  90. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/rust/smolpy-engine-rs/src/lib.rs +0 -0
  91. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/__init__.py +0 -0
  92. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/_worker.py +0 -0
  93. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/batch.py +0 -0
  94. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/cli.py +0 -0
  95. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/core/__init__.py +0 -0
  96. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/core/adapter.py +0 -0
  97. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/core/batch.py +0 -0
  98. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/core/link.py +0 -0
  99. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/core/network.py +0 -0
  100. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/core/node.py +0 -0
  101. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/core/observation.py +0 -0
  102. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/ethernet/__init__.py +0 -0
  103. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/ethernet/switch.py +0 -0
  104. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/lang/__init__.py +0 -0
  105. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/lang/ast.py +0 -0
  106. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/lang/errors.py +0 -0
  107. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/lang/grammar.lark +0 -0
  108. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/lang/interpreter.py +0 -0
  109. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/lang/transformer.py +0 -0
  110. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/modbus/__init__.py +0 -0
  111. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/modbus/slave.py +0 -0
  112. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/model/__init__.py +0 -0
  113. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/model/scenario.py +0 -0
  114. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/model/streams.py +0 -0
  115. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/model/timebase.py +0 -0
  116. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/model/validate.py +0 -0
  117. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/mqtt/__init__.py +0 -0
  118. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/mqtt/broker.py +0 -0
  119. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/profinet/__init__.py +0 -0
  120. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/profinet/device.py +0 -0
  121. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/sim/__init__.py +0 -0
  122. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/sim/engine.py +0 -0
  123. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/stats.py +0 -0
  124. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/viz/__init__.py +0 -0
  125. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/viz/dashboard.py +0 -0
  126. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/src/smolpy/viz/text_dashboard.py +0 -0
  127. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/__init__.py +0 -0
  128. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/equivalence/__init__.py +0 -0
  129. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/equivalence/scenarios.py +0 -0
  130. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/equivalence/test_rust_timebase.py +0 -0
  131. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_backends.py +0 -0
  132. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_batch.py +0 -0
  133. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_benchmarks.py +0 -0
  134. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_cli.py +0 -0
  135. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_dsl.py +0 -0
  136. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_engine_ir.py +0 -0
  137. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_lang.py +0 -0
  138. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_model.py +0 -0
  139. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_profinet.py +0 -0
  140. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_semantics.py +0 -0
  141. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_simulation.py +0 -0
  142. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_stats.py +0 -0
  143. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_sweep.py +0 -0
  144. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_timebase.py +0 -0
  145. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/tests/test_validate.py +0 -0
  146. {smolpy-1.9.1.dev4 → smolpy-1.9.1.dev8}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: smolpy
3
- Version: 1.9.1.dev4
3
+ Version: 1.9.1.dev8
4
4
  Summary: Network simulation DSL and discrete-event simulator
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -482,7 +482,7 @@ Every simulation goes through the same path. The Python API and `.smol` files bu
482
482
  |---|---|---|---|---|
483
483
  | `simpy` (default) | Python, SimPy | the whole model, the live and text dashboards | reference | included |
484
484
  | `rust` | Rust, through PyO3 | the whole model, headless: Ethernet, Modbus TCP, MQTT and PROFINET RT, every metric | about **40× faster**: B1 at 10 M frames in 4.9 s, not 200.8 s | `pip install smolpy[rust]` (since v1.8.0) |
485
- | `ns3` (in progress) | ns-3's IPv4/UDP stack, from C++ | Ethernet so far: adapters, switches, constant flows without priorities; bit-exact with SimPy there | slower: each run is an ns-3 process | an ns-3 3.49 build in `NS3_HOME`, e.g. the image `ghcr.io/jwszolek/smolpy-ns3-base:3.49` |
485
+ | `ns3` (in progress) | ns-3's IPv4 stack, from C++ | Ethernet over UDP, bit-exact with SimPy: adapters, switches, every traffic pattern, IMIX, priorities. Modbus TCP and MQTT over ns-3's TCP, which adds connection setup and acknowledgements. PROFINET not yet | slower: each run is an ns-3 process | an ns-3 3.49 build in `NS3_HOME`, e.g. the image `ghcr.io/jwszolek/smolpy-ns3-base:3.49` |
486
486
 
487
487
  ```python
488
488
  result = net.simulate(duration=60_000, backend="rust") # one run
@@ -454,7 +454,7 @@ Every simulation goes through the same path. The Python API and `.smol` files bu
454
454
  |---|---|---|---|---|
455
455
  | `simpy` (default) | Python, SimPy | the whole model, the live and text dashboards | reference | included |
456
456
  | `rust` | Rust, through PyO3 | the whole model, headless: Ethernet, Modbus TCP, MQTT and PROFINET RT, every metric | about **40× faster**: B1 at 10 M frames in 4.9 s, not 200.8 s | `pip install smolpy[rust]` (since v1.8.0) |
457
- | `ns3` (in progress) | ns-3's IPv4/UDP stack, from C++ | Ethernet so far: adapters, switches, constant flows without priorities; bit-exact with SimPy there | slower: each run is an ns-3 process | an ns-3 3.49 build in `NS3_HOME`, e.g. the image `ghcr.io/jwszolek/smolpy-ns3-base:3.49` |
457
+ | `ns3` (in progress) | ns-3's IPv4 stack, from C++ | Ethernet over UDP, bit-exact with SimPy: adapters, switches, every traffic pattern, IMIX, priorities. Modbus TCP and MQTT over ns-3's TCP, which adds connection setup and acknowledgements. PROFINET not yet | slower: each run is an ns-3 process | an ns-3 3.49 build in `NS3_HOME`, e.g. the image `ghcr.io/jwszolek/smolpy-ns3-base:3.49` |
458
458
 
459
459
  ```python
460
460
  result = net.simulate(duration=60_000, backend="rust") # one run
@@ -106,7 +106,9 @@ smolpy backends # list backends and their capabiliti
106
106
 
107
107
  **Results interchange.** ~~Samplers in the C++ module write the same long CSV format that `SimulationResult.export()` already produces (`time_ms,metric,value`).~~ *As built:* at each sample instant, the samplers write raw integer counters: bytes, bits and frames, the sum and count of latencies, and queue lengths. The Python side computes every metric from them with the reference engine's formulas, so each value is rounded once, as there. The backend loads the result into a regular `SimulationResult`, so `report()`, `export()` and `--output` work identically for both backends.
108
108
 
109
- **Seed.** The `simulate` statement's `seed` maps to ns-3's RNG seed/run configuration, so seeded runs are reproducible on both backends.
109
+ **Seed.** ~~The `simulate` statement's `seed` maps to ns-3's RNG seed/run configuration, so seeded runs are reproducible on both backends.~~ *As built (2026-11-16):* random traffic is not drawn by ns-3's generators. The Python side draws every frame of a random flow from the flow's own stream, the one Model Semantics §6 seeds from the run seed and its source id. It uses the reference engine's generator, order of draws and formulas, so the instants and sizes are the same as SimPy's. ns-3 sends the listed frames.
110
+ - **Why.** With the same seed, a stochastic scenario is the same run on SimPy and ns-3. Any difference is then the network's, not the traffic's, and the comparison is exact rather than statistical.
111
+ - **Cost.** Constant flows of fixed-size frames are still generated in C++. Only random flows and IMIX sizes are listed, one pair of integers per frame.
110
112
 
111
113
  **Time.** *Added by the ADR-0007 revision of 2026-11-14.* The generator keeps ns-3's `Time` resolution at 1 ns and writes every time as integer nanoseconds, rounded by the rules of [Model Semantics §1](../model-semantics.md#1-time-and-units): delays, cycles, sampling instants and the end of the run. So ns-3 and the other engines share one clock. Timings that ns-3's own device and TCP/IP models compute are ns-3's, which is why ns-3 is compared under ADR-0009's high-fidelity rules.
112
114
 
@@ -120,8 +122,8 @@ smolpy backends # list backends and their capabiliti
120
122
  | `hub` | Shared CSMA channel *(hubs and `collision_rate` were later removed; see [Model Semantics](../model-semantics.md#open-issues), open issue 3)* |
121
123
  | `link speed= length=` | *Amended 2026-11-16: SMOL's own full-duplex Ethernet device and channel, not CSMA; see "Link model on ns-3" below.* Device data rate = `speed`; channel delay = `length / 2·10⁸ m/s` (same propagation constant as `core/link.py`). *Since ADR-0010:* inter-frame gap = the time of 20 B at `speed` (preamble, SFD and gap, which CSMA does not model otherwise); CSMA adds the Ethernet header and FCS itself. *In ns-3.49 the gap is not an attribute: `Attach()` sets 12 B, so the generator calls `CsmaNetDevice::SetInterframeGap()` on each device after installing it.* |
122
124
  | `flow` | UDP application; payload sized so the on-wire frame matches `size` (constant, Poisson, bursty patterns; `imix` sizes). *As built:* the payload is `size` minus 46 B (Ethernet 18, IPv4 20, UDP 8), sent to port 9 of the destination, where a socket discards it. |
123
- | `publish` / `route` | MQTT publisher / broker Applications over one persistent TCP connection per client; QoS 1 sends PUBACK |
124
- | `poll` | Modbus TCP master / slave Applications over one persistent TCP connection per master–slave pair (port 502), MBAP transaction IDs, Read Holding Registers (FC 03) |
125
+ | `publish` / `route` | MQTT publisher / broker Applications over one persistent TCP connection per client; QoS 1 sends PUBACK. *As built:* port 1883; subscribers connect to the broker as clients, and one connection carries all of a client's PUBLISH messages and copies (see "Modbus and MQTT over TCP" below). |
126
+ | `poll` | Modbus TCP master / slave Applications over one persistent TCP connection per master–slave pair (port 502), MBAP transaction IDs, Read Holding Registers (FC 03). *As built:* without transaction IDs. Responses come back in order on the connection, so the master pairs them with its requests in that order. |
125
127
  | `observe` | Periodic sampler writing CSV rows |
126
128
  | `simulate mode=` | `headless` only; `text`/`live` are capability errors (results are post-processed after the run) |
127
129
 
@@ -148,11 +150,11 @@ smolpy backends # list backends and their capabiliti
148
150
  | `throughput`, `bytes_received` | frames addressed to the node, received by its device: frame bytes, header to FCS (`MacRx`) |
149
151
  | `bytes_sent` | frames whose transmission on the node's device has completed (`PhyTxEnd`), frame bytes |
150
152
  | `latency` | from the origin time, carried in a packet tag set when the data is created, to reception by the device. Queueing at the sender is included, as in SimPy. |
151
- | `modbus_latency` | the same, with the request's origin tag copied into the response |
153
+ | `modbus_latency` | the same, with the request's origin tag copied into the response. *As built:* measured when the master has the whole response. |
152
154
  | `pn_latency`, `pn_jitter`, `pn_watchdog_expiries` | the SMOL PROFINET consumer application, with the definitions of Model Semantics §7 |
153
155
  | `queue_depth` | frames waiting in the egress queues of the switch's devices, not counting the frame in transmission |
154
156
  | `utilization` | frame + 20 B per frame completed on the links into the node, as a share of their capacity (ADR-0010) |
155
- | `broker_queue` | the queue of the broker application |
157
+ | `broker_queue` | the queue of the broker application. *As built:* messages waiting for a subscriber's connection, which the subscriber has not yet opened. The broker handles a message at once, as on SimPy, so the queue is otherwise empty. |
156
158
 
157
159
  - **How FlowMonitor differs.** This is for comparisons with ns-3 literature, and is to be checked against the pinned release. FlowMonitor's statistics:
158
160
  - are per flow (IP 5-tuple), not per node and window;
@@ -216,12 +218,66 @@ ns-3.49's CSMA is a shared bus: the two ends of a link wait for each other, and
216
218
  - It occupies the wire for preamble, SFD and frame, and the next frame waits for the 12 B gap (ADR-0010).
217
219
  - Times are rounded as in Model Semantics §1.
218
220
  - **IP on top.** IPv4 runs on the device with a /32 address and every destination on the link. IPv6 is not installed, so there are no router solicitations or other IPv6 traffic. The neighbour caches start full, because SMOL models no ARP.
219
- - **What ns-3 contributes** is its IPv4/UDP stack now, and its TCP stack for Modbus and MQTT later. The differences that remain between engines are the protocol stack's, which is what the comparison is for.
221
+ - **What ns-3 contributes** is its IPv4/UDP stack, and its TCP stack for Modbus and MQTT ("Modbus and MQTT over TCP" below). The differences that remain between engines are the protocol stack's, which is what the comparison is for.
220
222
  - **Options rejected.**
221
223
  - **CSMA as planned.** Its differences from the other engines would come from half duplex.
222
224
  - **`SimpleNetDevice`.** It is full duplex, but it counts neither the Ethernet header and FCS nor the preamble and gap: about 38 B per frame too few.
223
225
 
224
- **First results** *(2026-11-16)*. Constant flows of fixed-size frames without priorities are in scope so far. The `line` and `bridging` scenarios, and `switching` with its priorities set to 0, give SimPy's results bit for bit, through ns-3's IPv4/UDP stack. `bridging` has a flooding learning core, a hairpin at a converged switch, jumbo frames and a saturated 10 Mb/s link. So the deterministic suite compares ns-3 exactly, like Rust. ADR-0009's high-fidelity rules remain for TCP.
226
+ **First results** *(2026-11-16)*. Everything Ethernet is in scope: adapters, switches and flows with every pattern, IMIX sizes and 802.1Q priorities.
227
+ - **Deterministic scenarios.** `line`, `switching` and `bridging` give SimPy's results bit for bit, through ns-3's IPv4/UDP stack. `bridging` has a flooding learning core, a hairpin at a converged switch, jumbo frames and a saturated 10 Mb/s link.
228
+ - **Stochastic scenarios.** `random-load` and `groups`, with Poisson, bursty and batch arrivals, IMIX and priorities, are bit for bit the same as SimPy's with the same seed, because the frames are drawn from the same streams. With other seeds they agree statistically.
229
+ - **Consequence.** The suite compares ns-3 exactly, like Rust. ADR-0009's high-fidelity rules remain for TCP.
230
+
231
+ ns-3 adds a priority to a frame as a packet tag. Its device then adds the 802.1Q tag's 4 B and serves its egress queue strictly by priority, or FIFO on a switch with `qos="fifo"`.
232
+
233
+ **Modbus and MQTT over TCP** *(decided and built 2026-11-16)*
234
+
235
+ What ns-3 is there for is its TCP. The backend therefore keeps everything else as on the other engines, so that the differences that remain are TCP's.
236
+ - **Connections.**
237
+ - One persistent connection per Modbus master and slave (port 502), and one per MQTT client and broker (port 1883).
238
+ - A client that publishes to a broker and subscribes to it uses one connection.
239
+ - Every connection is opened at the start of the run. The first messages come later.
240
+ - **Messages, not bytes.**
241
+ - The applications send whole protocol messages, sized in TCP payload bytes with SMOL's formulas (`frames.py`: `mqtt_publish_message_bytes`, `modbus_response_message_bytes`, ...).
242
+ - The bytes carry nothing. Each connection keeps, per direction, the messages whose bytes are on the way. TCP delivers bytes in order, so a message has arrived when all of its bytes have.
243
+ - Each message's bytes carry its origin time as a byte tag. So `latency` is measured per frame for TCP data as for UDP. Segments without data, such as acknowledgements and the handshake, have no origin and do not count in `latency`.
244
+ - **SMOL's frame sizes.**
245
+ - Every segment has a 20 B TCP header, as SMOL sizes Modbus and MQTT frames: the timestamp option is off. Window scaling and SACK stay on. They add 8 B to the SYN and SYN-ACK, and SACK blocks only to the acknowledgements of a loss, which SMOL's unbounded queues do not cause.
246
+ - The segment size is Ethernet's 1460 B, not ns-3's default of 536 B.
247
+ - **ns-3's defaults otherwise.** Congestion control is CUBIC. Delayed acknowledgements are every second segment or after 200 ms. Nagle is off (`TcpNoDelay`). The minimum RTO is 1 s.
248
+ - **Applications.**
249
+ - They act at the instant a message arrives, as on SimPy.
250
+ - They never block: the send buffer (1 GiB) holds what TCP cannot send yet.
251
+ - A broker sends its copies to subscribers first and then the PUBACK, as on SimPy.
252
+ - **Options rejected.**
253
+ - **Parsing real MQTT and MBAP bytes in the stream.** SMOL's sizes are not real encodings: for example, MQTT's remaining length takes 2 B above 127 B. Real encodings would change the frame sizes.
254
+ - **ns-3's timestamp option.** It is on in Linux, but it would make every frame 12 B larger than SMOL's. That difference would come from sizing, not from TCP's behaviour.
255
+
256
+ **What TCP changes, to the nanosecond** (tests in `tests/test_ns3.py`):
257
+ - **1 ns per send.** ns-3 sends an application's data one time step after the call, which is 1 ns here. So a Modbus round trip and a PUBLISH from publisher to subscriber both take SimPy's time plus 2 ns. A broker's or slave's reply would otherwise leave at once, ahead of other data: `Send()` on the connection that has just received data is flushed in the same event. Replies are therefore scheduled as events of their own, in the order the application makes them.
258
+ - **The handshake.** Each client receives a SYN-ACK of 66 B at the start, and switches learn the stations from it.
259
+ - **The first data segment** of a connection is acknowledged at once. ns-3 counts the handshake as a full delayed-ACK count. The reply waits behind that frame, 6.72 µs at 100 Mb/s.
260
+ - **Acknowledgements.**
261
+ - **Request and response (Modbus, MQTT QoS 1).** Each reply carries the acknowledgement of the request, and the next request carries the acknowledgement of the reply. No extra frames.
262
+ - **One-way PUBLISH (QoS 0, and copies to subscribers).** The receiver sends a 64 B acknowledgement for every second segment. At a broker, that frame leaves just before the copies and delays them by its transmission time.
263
+
264
+ **First results over TCP** *(2026-11-16)*. The suite's TCP scenarios sample the same metrics at the same instants as SimPy (`test_over_tcp`). The table gives the means of their values over the run:
265
+
266
+ | Scenario | Metric | SimPy | ns-3 | Why |
267
+ |---|---|---|---|---|
268
+ | `protocols` | `modbus_latency:scada` | 43.76 µs | 44.37 µs | +2 ns per round trip; +6.72 µs on the first one |
269
+ | | `latency:hmi` | 47.12 µs | 49.26 µs | copies behind the broker's acknowledgements of the QoS 0 topic |
270
+ | | `bytes_received:scada` | 3.19 kB | 3.38 kB | SYN-ACKs and the first acknowledgements |
271
+ | `polling` | `modbus_latency:scada` | 123.21 µs | 131.05 µs | the first window: the handshakes on the 10 Mb/s link; then +2 ns |
272
+ | | `bytes_received:plc` | 1.06 kB | 1.30 kB | SYN-ACKs and the first acknowledgements |
273
+ | | `utilization:edge` | 0.40 % | 0.48 % | the handshakes, in the first windows |
274
+ | `messaging` (loaded uplink) | `bytes_received:hall`, `:cell` | 0.48 kB, 0.31 kB | 0.86 kB, 0.61 kB | a 64 B acknowledgement for every second QoS 0 PUBLISH |
275
+ | | `utilization:plant` | 1.07 % | 1.67 % | the acknowledgements sent to the broker |
276
+ | | `latency:hmi`, `:scada`, `:historian` | 291, 266, 119 µs | 289, 259, 115 µs | acknowledgements change the order of frames in the FIFO queues, both ways |
277
+ | | `queue_depth:edge` | 0.0175 | 0.0063 | the same |
278
+
279
+ - **Low load.** After the first messages, ns-3 is SimPy plus 2 ns per message. The remaining differences are the handshake, the first acknowledgement, and the acknowledgements of one-way traffic.
280
+ - **Loaded.** The acknowledgements reorder frames in shared queues, so differences remain throughout the run. They are reported, not asserted (ADR-0009). Quantifying them under heavier load, where TCP's flow and congestion control act, is the next part of this research.
225
281
 
226
282
  **The ns-3 base image, as built** *(2026-11-16)*:
227
283
  - `ghcr.io/jwszolek/smolpy-ns3-base:3.49`, built by `.github/workflows/ns3-base.yml` from `docker/ns3-base/Dockerfile`, for `linux/amd64` only for now. It is rebuilt when that Dockerfile changes, and pushed after the merge to `main`.
@@ -87,7 +87,7 @@ The suite lives in `tests/equivalence/`. It runs a fixed set of reference scenar
87
87
  |---|---|
88
88
  | **Deterministic** (constant patterns, fixed sizes, no randomness) | ~~Per metric window: \|a − b\| ≤ abs_tol + rel_tol·\|b\|. The tolerance only covers time representation (SimPy float µs vs Rust integer ns); default `rel_tol = 1e-6`, `abs_tol` = 1 ns-equivalent in the metric's unit.~~ *Amended by the ADR-0007 revision of 2026-11-14 ([integer nanoseconds](0007-execution-independent-scenario-model.md#simulated-time-integer-nanoseconds)):* every metric window must match exactly, sample times and values bit for bit (in place since ADR-0007 step 8). |
89
89
  | **Stochastic** | 30 replications per backend. For each metric's per-run scalar, the ~~95 %~~ confidence interval of the difference of means must contain 0, and the relative difference of means must be under 2 %. *Amended 2026-11-15:* with *k* metrics in a scenario, each interval is at the Bonferroni level `1 − 0.05/k`, e.g. 98.75 % for 4 metrics. Two equivalent backends then fail a scenario by chance at most 5 % of the time. With 95 % per metric they failed about one seed block in ten, and now one in forty (measured over 20 blocks per scenario). |
90
- | **High-fidelity backends** (ns-3) | Low-load scenarios: same rules as stochastic. Loaded scenarios: differences are **reported, not asserted** (ADR-0004). Quantifying them is a research result. *Amended 2026-11-16:* on SMOL's own Ethernet with UDP, ns-3 gives SimPy's results bit for bit, so the deterministic scenarios in its scope are compared exactly, as for Rust. These rules remain for TCP, where ns-3's stack is meant to differ. |
90
+ | **High-fidelity backends** (ns-3) | Low-load scenarios: same rules as stochastic. Loaded scenarios: differences are **reported, not asserted** (ADR-0004). Quantifying them is a research result. *Amended 2026-11-16:* on SMOL's own Ethernet with UDP, ns-3 gives SimPy's results bit for bit, so the deterministic scenarios in its scope are compared exactly, as for Rust. ns-3 draws random traffic from the reference engine's streams, so a stochastic scenario with the same seed must also match bit for bit (`test_same_streams_give_the_same_run`), besides the statistical comparison. These rules remain for TCP, where ns-3's stack is meant to differ. *Amended 2026-11-16:* ns-3 runs Modbus and MQTT over TCP. For a scenario with that traffic, the suite checks that ns-3 samples the same metrics at the same instants, and reports the differences in their means (`test_over_tcp`). Tests of small scenarios check what TCP adds to the nanosecond (ADR-0004). |
91
91
 
92
92
  - Backends that are not installed are skipped.
93
93
  - **CI:** SimPy against itself (a sanity check of the harness) and Rust against SimPy when the Rust package is available.
@@ -165,7 +165,7 @@ result.export("out.csv", format="csv") # explicit format override
165
165
  |---|---|
166
166
  | `"simpy"` | The reference implementation. It is the default, always installed, and runs the whole model, including the live and text dashboards. |
167
167
  | `"rust"` | The native engine of [ADR-0008](adr/0008-rust-des-engine-mvp.md), from the optional package `smolpy-engine-rs` (`pip install smolpy[rust]`). It runs headless. |
168
- | `"ns3"` | ns-3 ([ADR-0004](adr/0004-execution-backends.md)), in progress: so far adapters, switches and constant flows of fixed-size frames without 802.1Q priorities, with the Ethernet metrics, on ns-3's IPv4/UDP stack. It needs `NS3_HOME`, naming a built ns-3 3.49 tree, and a C++ compiler; the image `ghcr.io/jwszolek/smolpy-ns3-base:3.49` has both. It runs headless. |
168
+ | `"ns3"` | ns-3 ([ADR-0004](adr/0004-execution-backends.md)), in progress: so far Ethernet (adapters, switches, flows with every pattern, IMIX and 802.1Q priorities, the Ethernet metrics) on ns-3's IPv4/UDP stack, with random traffic drawn from SimPy's streams; and Modbus TCP and MQTT on ns-3's TCP, with `modbus_latency` and `broker_queue`. TCP's connection setup and acknowledgements make those results differ from SimPy's. PROFINET is not supported yet. It needs `NS3_HOME`, naming a built ns-3 3.49 tree, and a C++ compiler; the image `ghcr.io/jwszolek/smolpy-ns3-base:3.49` has both. It runs headless. |
169
169
 
170
170
  - **What a backend can run is checked before the run.** Every backend declares what it supports: node kinds, traffic kinds, patterns and metrics. A scenario that uses anything else is rejected with a `ScenarioError` naming the element. A dashboard (`live=True` or `text=True`) on a headless backend is a `ValueError`.
171
171
  - **A missing backend is an error.** When a backend is not installed, selecting it raises `BackendUnavailable` with the install command.
@@ -172,15 +172,20 @@ A code-generated ns-3 scenario from the Scenario IR. Gives a realistic TCP/IP st
172
172
 
173
173
  ns-3 cannot be installed with `pip`, so the backend ships as a container image, `ghcr.io/jwszolek/smolpy:<version>-ns3`. It holds the pinned ns-3 release built once, and CI runs the ns-3 equivalence suite in it ([ADR-0004 — Container images](adr/0004-execution-backends.md#container-images)). A lighter image with SMOLPy and the Rust engine, without ns-3, can be published from the first release of `smolpy-engine-rs`.
174
174
 
175
- **Status:** steps 1 and 2 of 3 done, and step 3 has begun.
175
+ **Status:** steps 1 and 2 of 3 done, and step 3 is under way.
176
176
  1. **The image without ns-3: done.** `ghcr.io/jwszolek/smolpy:<version>` holds SMOLPy and the Rust engine, for `linux/amd64` and `linux/arm64`. It is built, tested and pushed at each release.
177
177
  2. **The ns-3 base image: done.** `ghcr.io/jwszolek/smolpy-ns3-base:3.49` holds ns-3.49, built once, for `linux/amd64`. `arm64` follows on a native runner.
178
178
  3. **The ns-3 backend.**
179
- - **Ethernet: done.** `backend="ns3"` runs adapters, switches and constant flows of fixed-size frames without priorities, with the six Ethernet metrics, on ns-3's IPv4/UDP stack.
179
+ - **Ethernet: done.** `backend="ns3"` runs adapters, switches and flows with every pattern, IMIX and 802.1Q priorities, with the six Ethernet metrics, on ns-3's IPv4/UDP stack.
180
180
  - It runs over SMOL's own full-duplex Ethernet device, because ns-3's CSMA is half duplex (ADR-0004).
181
- - `line`, `bridging` and `switching` without priorities are bit-exact with SimPy.
181
+ - Random traffic is drawn from the reference engine's streams.
182
+ - Every Ethernet scenario of the suite is bit-exact with SimPy. For the stochastic ones that holds with the same seed.
182
183
  - CI runs the backend in the base image.
183
- - **Next:** 802.1Q priorities, random patterns and IMIX, then Modbus and MQTT over TCP, then PROFINET.
184
+ - **Modbus and MQTT: done.** They run over ns-3's TCP, with one persistent connection per master and slave, or per client and broker (ADR-0004).
185
+ - Their frames have SMOL's sizes. What TCP adds is the handshake, acknowledgements and, under load, its flow and congestion control.
186
+ - At low load, after the first messages, every Modbus round trip and MQTT delivery is SimPy's plus 2 ns. Tests check this to the nanosecond.
187
+ - The suite checks that the TCP scenarios sample the same metrics at the same instants as SimPy, and reports how their values differ.
188
+ - **Next:** PROFINET.
184
189
 
185
190
  **Exit criteria:**
186
191
 
@@ -160,8 +160,9 @@ class RustBackend:
160
160
  class Ns3Backend:
161
161
  """ns-3 (ADR-0004, ``smolpy.ns3``), where ``NS3_HOME`` names an ns-3 build.
162
162
 
163
- So far it runs Ethernet with constant flows of fixed-size frames, without
164
- 802.1Q priorities; the protocols and random traffic follow in Phase 6.
163
+ So far it runs Ethernet (adapters, switches and flows with every pattern,
164
+ IMIX and 802.1Q priorities) over UDP, and Modbus TCP and MQTT over ns-3's
165
+ TCP. PROFINET follows in Phase 6.
165
166
  """
166
167
 
167
168
  name = "ns3"
@@ -191,9 +192,9 @@ class Ns3Backend:
191
192
  self._locate()
192
193
  later = "planned for Phase 6"
193
194
  return Capabilities(
194
- nodes=frozenset({"adapter", "switch"}),
195
- traffic=frozenset({"flow"}),
196
- patterns=frozenset({"constant"}),
195
+ nodes=frozenset({"adapter", "switch", "mqtt_broker", "modbus_slave"}),
196
+ traffic=frozenset({"flow", "publish", "route", "poll"}),
197
+ patterns=_PATTERNS,
197
198
  metrics=frozenset(
198
199
  {
199
200
  "throughput",
@@ -202,21 +203,12 @@ class Ns3Backend:
202
203
  "bytes_received",
203
204
  "queue_depth",
204
205
  "utilization",
206
+ "modbus_latency",
207
+ "broker_queue",
205
208
  }
206
209
  ),
207
- priorities=False,
208
- notes={
209
- kind: later
210
- for kind in (
211
- "mqtt_broker",
212
- "modbus_slave",
213
- "profinet_device",
214
- "publish",
215
- "route",
216
- "poll",
217
- "profinet_ar",
218
- )
219
- },
210
+ features=frozenset({"imix"}),
211
+ notes={kind: later for kind in ("profinet_device", "profinet_ar")},
220
212
  )
221
213
 
222
214
  def run(self, scenario: Scenario) -> SimulationResult:
@@ -28,9 +28,15 @@ PN_RT_PRIORITY = 6 # 802.1Q PCP carried by PROFINET RT cyclic frames
28
28
  PN_CYCLES_MS = tuple(2**n for n in range(10)) # 1, 2, 4, ... 512 ms
29
29
  PN_MAX_IO_BYTES = 1440
30
30
 
31
- MQTT_PUBACK_BYTES = max(MIN_FRAME_BYTES, ETHERNET_IP_TCP_BYTES + 4) # 62 B, padded to 64
31
+ # The protocol messages below are the TCP payload of one frame each; their
32
+ # frames add ETHERNET_IP_TCP_BYTES. The ns-3 backend sends the messages
33
+ # themselves over TCP.
32
34
 
33
- MODBUS_REQUEST_BYTES = ETHERNET_IP_TCP_BYTES + 6 + 1 + 2 + 2 # 69: MBAP, FC, addr, quantity
35
+ MQTT_PUBACK_MESSAGE_BYTES = 4
36
+ MQTT_PUBACK_BYTES = max(MIN_FRAME_BYTES, ETHERNET_IP_TCP_BYTES + MQTT_PUBACK_MESSAGE_BYTES) # 64
37
+
38
+ MODBUS_REQUEST_MESSAGE_BYTES = 6 + 1 + 2 + 2 # MBAP, FC, address, quantity
39
+ MODBUS_REQUEST_BYTES = ETHERNET_IP_TCP_BYTES + MODBUS_REQUEST_MESSAGE_BYTES # 69
34
40
 
35
41
 
36
42
  def padded(frame_bytes: int) -> int:
@@ -44,16 +50,23 @@ def flow_frame_size(size: int, priority: int) -> int:
44
50
  return size + (VLAN_TAG_BYTES if priority > 0 else 0)
45
51
 
46
52
 
53
+ def mqtt_publish_message_bytes(topic: str, payload_bytes: int, qos: int) -> int:
54
+ """MQTT PUBLISH: fixed header (2) + topic length (2) + topic + packet id (QoS > 0)
55
+ + payload. The topic's length counts characters."""
56
+ return 2 + 2 + len(topic) + (2 if qos > 0 else 0) + payload_bytes
57
+
58
+
47
59
  def mqtt_publish_frame_size(topic: str, payload_bytes: int, qos: int) -> int:
48
- """MQTT PUBLISH: fixed header (2) + topic length (2) + topic + packet id (QoS > 0)."""
49
- return padded(
50
- ETHERNET_IP_TCP_BYTES + 2 + 2 + len(topic) + (2 if qos > 0 else 0) + payload_bytes
51
- )
60
+ return padded(ETHERNET_IP_TCP_BYTES + mqtt_publish_message_bytes(topic, payload_bytes, qos))
52
61
 
53
62
 
54
- def modbus_response_frame_size(count: int) -> int:
63
+ def modbus_response_message_bytes(count: int) -> int:
55
64
  """Read Holding Registers response: MBAP (6) + FC (1) + byte count (1) + 2 B per register."""
56
- return padded(ETHERNET_IP_TCP_BYTES + 6 + 1 + 1 + 2 * count)
65
+ return 6 + 1 + 1 + 2 * count
66
+
67
+
68
+ def modbus_response_frame_size(count: int) -> int:
69
+ return padded(ETHERNET_IP_TCP_BYTES + modbus_response_message_bytes(count))
57
70
 
58
71
 
59
72
  def pn_frame_size(io_bytes: int) -> int:
@@ -1,4 +1,5 @@
1
- """The ns-3 backend (ADR-0004): SMOLPy scenarios on ns-3's IPv4/UDP stack.
1
+ """The ns-3 backend (ADR-0004): SMOLPy scenarios on ns-3's IPv4 stack, with
2
+ UDP for flows and TCP for Modbus and MQTT.
2
3
 
3
4
  A scenario is lowered to plain lines of integers (every time in integer
4
5
  nanoseconds, every speed and period an exact rational) and run by
@@ -20,10 +21,12 @@ from __future__ import annotations
20
21
  import glob
21
22
  import hashlib
22
23
  import os
24
+ import random
23
25
  import shutil
24
26
  import subprocess
25
27
  import tempfile
26
28
  import time
29
+ from collections.abc import Iterator
27
30
  from dataclasses import dataclass
28
31
  from fractions import Fraction
29
32
  from importlib import resources
@@ -32,7 +35,13 @@ from typing import TYPE_CHECKING
32
35
 
33
36
  from smolpy import model
34
37
  from smolpy.model import timebase as tb
35
- from smolpy.model.frames import IFG_BYTES
38
+ from smolpy.model.frames import (
39
+ IFG_BYTES,
40
+ MODBUS_REQUEST_MESSAGE_BYTES,
41
+ modbus_response_message_bytes,
42
+ mqtt_publish_message_bytes,
43
+ )
44
+ from smolpy.model.streams import source_ids, stream_seed
36
45
 
37
46
  if TYPE_CHECKING:
38
47
  from smolpy.core.network import SimulationResult
@@ -41,6 +50,8 @@ FORMAT_VERSION = 1
41
50
  UDP_IP_BYTES = 8 + 20
42
51
  ETHERNET_BYTES = 14 + 4 # header and FCS
43
52
  PROGRAM = "smol-ns3"
53
+ MODBUS_PORT = 502
54
+ MQTT_PORT = 1883
44
55
 
45
56
 
46
57
  class Ns3Unavailable(RuntimeError):
@@ -142,6 +153,59 @@ class _Sampler:
142
153
  speed: Fraction = Fraction(0) # utilization: Mb/s into the target
143
154
 
144
155
 
156
+ def _strict(node: model.NodeSpec) -> bool:
157
+ """Whether a node's egress queues serve priorities strictly."""
158
+ return not (isinstance(node, model.SwitchNode) and node.qos == "fifo")
159
+
160
+
161
+ def _sends(
162
+ flow: model.Flow, rng: random.Random, delay_ns: int, duration_ns: int
163
+ ) -> Iterator[tuple[int, int]]:
164
+ """Every frame of *flow* before *duration_ns*: its instant and size
165
+ (untagged, FCS included), drawn from *rng* in the order and with the
166
+ formulas of the reference engine's ``_traffic_gen``, so the frames are
167
+ the same as there."""
168
+ from smolpy.sim.engine import _resolve_size
169
+
170
+ def size() -> int:
171
+ return _resolve_size(flow.size, rng)
172
+
173
+ now = delay_ns
174
+ period = tb.interval_ns(flow.rate)
175
+ mean_ns = float(period)
176
+ if flow.pattern == "constant":
177
+ for at in tb.instants(delay_ns, period):
178
+ if at >= duration_ns:
179
+ return
180
+ yield at, size()
181
+ elif flow.pattern == "poisson":
182
+ while True:
183
+ now += tb.draw_ns(rng.expovariate(1.0 / mean_ns))
184
+ if now >= duration_ns:
185
+ return
186
+ yield now, size()
187
+ elif flow.pattern == "batch":
188
+ assert flow.batch is not None
189
+ group_ns = mean_ns * flow.batch.mean()
190
+ while True:
191
+ now += tb.draw_ns(rng.expovariate(1.0 / group_ns))
192
+ if now >= duration_ns:
193
+ return
194
+ for _ in range(flow.batch.draw(rng)):
195
+ yield now, size()
196
+ else: # bursty
197
+ quarter = Fraction(period) / 4
198
+ while True:
199
+ burst_len = max(1, int(rng.paretovariate(1.5)))
200
+ in_burst = tb.instants(now, quarter)
201
+ for _ in range(burst_len):
202
+ now = next(in_burst)
203
+ if now >= duration_ns:
204
+ return
205
+ yield now, size()
206
+ now += tb.draw_ns(mean_ns * burst_len * rng.uniform(0.3, 1.2))
207
+
208
+
145
209
  def lower(scenario: model.Scenario) -> tuple[str, list[_Sampler]]:
146
210
  """The input of ``smol-ns3``, and the samplers its output feeds."""
147
211
  from smolpy.sim.engine import _topology_mac_table
@@ -151,8 +215,8 @@ def lower(scenario: model.Scenario) -> tuple[str, list[_Sampler]]:
151
215
  index = {n.name: i for i, n in enumerate(scenario.nodes)}
152
216
  lines = [f"smol-ns3 {FORMAT_VERSION}", f"duration {tb.ms_to_ns(scenario.run.duration_ms)}"]
153
217
  for n in scenario.nodes:
154
- if isinstance(n, model.AdapterNode):
155
- lines.append(f"adapter {n.mac} {n.ip}")
218
+ if isinstance(n, model.AdapterNode | model.MqttBrokerNode | model.ModbusSlaveNode):
219
+ lines.append(f"adapter {n.mac} {n.ip}") # an IPv4 host
156
220
  elif isinstance(n, model.SwitchNode):
157
221
  lines.append("switch")
158
222
  else: # the capabilities exclude it
@@ -173,6 +237,7 @@ def lower(scenario: model.Scenario) -> tuple[str, list[_Sampler]]:
173
237
  lines.append(
174
238
  f"link {index[a.name]} {index[b.name]} {num} {den}"
175
239
  f" {tb.propagation_ns(link.length_m)} {tb.transmission_ns(IFG_BYTES, link.speed_mbps)}"
240
+ f" {int(_strict(a))} {int(_strict(b))}"
176
241
  )
177
242
  neighbours[a.name].append((port_a, b.name))
178
243
  neighbours[b.name].append((port_b, a.name))
@@ -181,7 +246,7 @@ def lower(scenario: model.Scenario) -> tuple[str, list[_Sampler]]:
181
246
  into.setdefault(b.name, []).append((2 * i, speed))
182
247
  # a switch knows the stations wired to it from the start
183
248
  for end, other, port in ((a, b, port_b), (b, a, port_a)):
184
- if isinstance(end, model.AdapterNode) and isinstance(other, model.SwitchNode):
249
+ if not isinstance(end, model.SwitchNode) and isinstance(other, model.SwitchNode):
185
250
  static.setdefault(other.name, {})[end.mac] = port
186
251
  for n in scenario.nodes:
187
252
  if isinstance(n, model.SwitchNode) and n.mac_table == "topology":
@@ -192,18 +257,64 @@ def lower(scenario: model.Scenario) -> tuple[str, list[_Sampler]]:
192
257
  lines.extend(f"static {index[name]} {mac} {port}" for mac, port in table.items())
193
258
 
194
259
  sinks: list[str] = []
195
- for t in scenario.traffic:
260
+ duration_ns = tb.ms_to_ns(scenario.run.duration_ms)
261
+ connections: dict[tuple[str, str], int] = {} # one per client and server
262
+ topics: dict[str, int] = {}
263
+
264
+ def connection(client: str, server: str, port: int) -> int:
265
+ if (client, server) not in connections:
266
+ connections[client, server] = len(connections)
267
+ lines.append(f"connect {index[client]} {index[server]} {port}")
268
+ return connections[client, server]
269
+
270
+ def periodic(rate: float, delay_ms: float) -> str:
271
+ num, den = _ratio(tb.interval_ns(rate))
272
+ return f"{tb.ms_to_ns(delay_ms)} {num} {den}"
273
+
274
+ for t, source_id in zip(scenario.traffic, source_ids(scenario), strict=True):
275
+ if isinstance(t, model.Poll):
276
+ if t.source in has_link:
277
+ c = connection(t.source, t.slave, MODBUS_PORT)
278
+ response = modbus_response_message_bytes(t.count)
279
+ lines.append(
280
+ f"poll {c} {MODBUS_REQUEST_MESSAGE_BYTES} {response}"
281
+ f" {periodic(t.rate, t.delay_ms)}"
282
+ )
283
+ continue
284
+ if isinstance(t, model.Publish):
285
+ if t.source in has_link:
286
+ c = connection(t.source, t.broker, MQTT_PORT)
287
+ topic = topics.setdefault(t.topic, len(topics))
288
+ message = mqtt_publish_message_bytes(t.topic, t.payload, t.qos)
289
+ lines.append(
290
+ f"publish {c} {message} {t.qos} {topic} {periodic(t.rate, t.delay_ms)}"
291
+ )
292
+ continue
293
+ if isinstance(t, model.Route):
294
+ topic = topics.setdefault(t.topic, len(topics))
295
+ subscribers = [
296
+ connection(sub, t.broker, MQTT_PORT) for sub in t.subscribers if sub in has_link
297
+ ]
298
+ listed = " ".join(str(c) for c in subscribers)
299
+ lines.append(f"route {index[t.broker]} {topic} {listed}".rstrip())
300
+ continue
196
301
  if not isinstance(t, model.Flow):
197
302
  raise ValueError(f"the ns3 backend does not support {t.kind} traffic")
198
303
  if t.source not in has_link:
199
304
  continue
200
305
  dst = nodes[t.destination]
201
- assert isinstance(dst, model.AdapterNode) and isinstance(t.size, int)
202
- num, den = _ratio(tb.interval_ns(t.rate))
203
- payload = t.size - ETHERNET_BYTES - UDP_IP_BYTES
204
- lines.append(
205
- f"flow {index[t.source]} {dst.ip} {payload} {tb.ms_to_ns(t.delay_ms)} {num} {den}"
206
- )
306
+ assert isinstance(dst, model.AdapterNode)
307
+ delay_ns = tb.ms_to_ns(t.delay_ms)
308
+ ends = f"{index[t.source]} {dst.ip}"
309
+ if t.pattern == "constant" and isinstance(t.size, int):
310
+ num, den = _ratio(tb.interval_ns(t.rate))
311
+ payload = t.size - ETHERNET_BYTES - UDP_IP_BYTES
312
+ lines.append(f"flow {ends} {payload} {t.priority} {delay_ns} {num} {den}")
313
+ else:
314
+ rng = random.Random(stream_seed(scenario.run.seed, source_id))
315
+ sends = list(_sends(t, rng, delay_ns, duration_ns))
316
+ listed = " ".join(f"{at} {size - ETHERNET_BYTES - UDP_IP_BYTES}" for at, size in sends)
317
+ lines.append(f"sends {ends} {t.priority} {len(sends)} {listed}".rstrip())
207
318
  if dst.name not in sinks:
208
319
  sinks.append(dst.name)
209
320
  lines.extend(f"sink {index[name]}" for name in sinks)
@@ -216,8 +327,10 @@ def lower(scenario: model.Scenario) -> tuple[str, list[_Sampler]]:
216
327
  devices = ""
217
328
  speed = Fraction(0)
218
329
  metric = obs.metric
219
- if metric in ("throughput", "latency", "bytes_received"):
330
+ if metric in ("throughput", "latency", "bytes_received", "modbus_latency"):
220
331
  ok = adapter and target.name in has_link
332
+ elif metric == "broker_queue":
333
+ ok = isinstance(target, model.MqttBrokerNode)
221
334
  elif metric == "bytes_sent":
222
335
  ok = adapter and target.name in has_link
223
336
  elif metric == "queue_depth":
@@ -261,14 +374,14 @@ def _metrics(
261
374
  t_ms = tb.ns_to_ms(t)
262
375
  if s.metric == "throughput":
263
376
  out.append((t_ms, (a - last) * 8 * tb.NS_PER_US / (t - last_t)))
264
- elif s.metric == "latency":
377
+ elif s.metric in ("latency", "modbus_latency"):
265
378
  if b:
266
379
  out.append((t_ms, a / (b * tb.NS_PER_US)))
267
380
  elif s.metric == "bytes_received":
268
381
  out.append((t_ms, a / 1_000_000))
269
382
  elif s.metric == "bytes_sent":
270
383
  out.append((t_ms, a // 8 / 1_000_000))
271
- elif s.metric == "queue_depth":
384
+ elif s.metric in ("queue_depth", "broker_queue"):
272
385
  out.append((t_ms, float(a)))
273
386
  elif s.metric == "utilization":
274
387
  out.append((t_ms, tb.quotient((a - last) * 100_000, s.speed * (t - last_t))))