<After workshopping the specs/requirements for a while...>
Write an extremely detailed implementation doc for the streaming version and th apis . We are only looking at geometry rf engine right now . We need to be able to hand the doc you make off to an LLM to code the geometry enginer API up from the existing python code. Make it so . Extremely detailed. Markdown checkboxes for each discrete task - [ ] so the AI can mark them off with an X as they complete
The codex-cli can start working on the output TASKS_GEOENGINE.md.
Implementing component 3 (of 4):
ChatGPT Web:
I pasted in all the TASKS_*.md the AI coder has produced so far, so the web planner has an idea of what was done. (If we didn't have access restrictions, the web version could just access the git repo).
Okay, here are the markdown taskfiles of what we've got done so far. We build geo engine and orchestrator . I need you to write a very detailed TASKS_IMNET.md file that deals with the imnet++ inet part and how it interacts with the other two systems as they exist . Write it as a markdown checklist - [ ] so the ai can cross items off as it writes them . Go .
This produces TASKS_ORCHESTRATOR.md
Codex CLI:
Check over TASKS_ORCHESTRATOR.md It was written without knowledg of the actual current implementation. Let me know if it looks good for ARCHITECTURE.md and if it is compatible with what has been done so far in TASKS_GEO_ENGINE.md We have only tried to make a gEO
engine so far. no edits ,just check the TASKS_ORCHESTRATOR.md makes sense.
Overall verdict: it is mostly aligned with ARCHITECTURE.md and broadly compatible with the Geo engine work, but the 3 medium/high items above should be clarified before implementation so the orchs estrator doesn’t encode wrong assumptions.
This step is super important! I need to make sure the plan we thought of actually makes sense with what is happening on the ground.
Can the misaligned items be easily solved? Is there a moslty obvisous right answer to them ? If so tell me the gravious solutions, or show me my optiosn if there s a fork or hard choice
<More workshopping of differenes between web and implementation. The web has the pdf source documents and better web search, and has unlimited usage, so I did planning there>
Codex CLI:
@AGENTS.md You task is to implement the geometry engine defined in @TASKS_GEO_ENGINE.md . After completing each task, mark it off with an x (- [x]) so its markdown checkbox so there is an external record of what has been done. If plans change, then modify the task list appropriately. The overall high level architecture of the program is in @ARCHITECTURE.md . Go .
This is where the magic happens! We have thought through our API and have developed a test plan, and a development plan. Now the AI can develop the code and test the API via the test suite to ensure its correct.
Overall Advice:
Think about your inputs/outputs/dependencies beforehand.
When the AI screw ups hallucinates, or does something silly, you can make a note in AGENTS.md to do the right thing instead.
Force the AI to use as many deterministic static tools as possible:
Strict Type Checking (Use Rust instead of C, Typescript instead of Javascript, Python with Type Annotations instead of without)
Linters
Code Format Tools
Unit/Integration tests
Have the AI write as many tests as possible of what you want the program to do
If you want the AI to "one-shot" (i.e., autonomously code something complex for a while without supervision and get a good result), then you need to give it as much test input/output behaviour as possible, so it can keep checking against the "proper" results without your guidance.
Use uv for all Python workflows in this repository.
Rules
Always run Python commands with uv run.
Always add dependencies with uv add.
Use uv venv for virtual environment setup/management.
Do not use pip, pip3, python -m pip, virtualenv, or python -m venv.
Do not install dependencies outside uv.
Examples
Run app: uv run python main.py
Add runtime dependency: uv add requests
Add dev dependency: uv add --dev pytest
Test Coverage Policy
Use pytest-cov via uv for coverage checks.
Rules
If coverage flags are needed and pytest-cov is missing, install it with uv add --dev pytest-cov.
For the workspace package, install coverage tooling with uv add --package geomrf-engine --dev pytest-cov.
Run coverage with uv run pytest ... --cov=....
Because both root and geomrf-engine use a tests package name, run coverage in two passes and combine reports instead of a single mixed pytest invocation.
Coverage command pattern
Orchestrator pass: COVERAGE_FILE=.coverage.orch uv run pytest tests --cov=satsim_orch --cov-report=
# ARCHITECTURE.md — SatSim System Overview
This document gives the **system-level architecture** for SatSim. It is intended to provide a complete “sight picture” for anyone implementing a subproject (e.g., the Geometry/RF Engine) so they understand how their component fits into the larger simulator.
---
## 1) Purpose and guiding idea
SatSim is a **hybrid satellite networking simulator** that combines:
1) A swappable **Geometry/RF/Link-Budget Engine** (physics + propagation + link feasibility)
2) A **packet-level discrete-event simulation lane 'OMNeT++/INET'** (scale + protocol behavior)
3) A **real SDN emulation lane 'Mininet/OVS'** (controller-in-the-loop + real Linux networking)
4) An **Orchestrator** that provides a single scenario/timebase and keeps all parts consistent
The fundamental design choice is that SatSim is **layered and composable**: we reuse mature simulators/emulators and treat satellite physics as an external service with a stable interface.
---
## 2) Key design decisions (why this looks the way it does)
### 2.1 Why two lanes (simulation vs emulation)
We intentionally run two different lanes because they answer different questions:
- **OMNeT++/INET lane (Discrete-Event Simulation)**
- Best for: scaling up to many nodes, protocol studies, routing and congestion behavior, reproducibility.
- Not best for: running real SDN controllers and real Linux TCP stacks.
- **Mininet/OVS lane (Network Emulation)**
- Best for: real SDN controllers (ONOS/Ryu), real forwarding behavior (OpenFlow/OVS), real apps/traffic tools.
- Not best for: scaling to thousands of nodes with full protocol stacks.
Trying to “pipe packets” between them is possible but usually not worth it early, because it introduces hard time synchronization problems (DES time vs wall-clock time) and packet bridging complexity. Instead we connect both lanes to the same **state oracle** (the Geo/RF engine) through the Orchestrator.
### 2.2 Where the lanes *do* meet today
They meet at:
- **Scenario definition** (same nodes, same constraints, same time window)
- **LinkState/Event timeline** (same “truth” about which links exist and their properties)
- **Metrics and artifacts** (comparable outputs; shared logging/PCAP strategy)
Optionally, they also meet via:
- **Shared SDN decision logic** (same ONOS/Ryu app used to compute routes, then applied in both lanes through adapters)
### 2.3 Future “stacking” (OMNeT++ feeding Mininet)
In the future, OMNeT++ may “feed” Mininet in two practical ways:
1) **Trace-driven replay (recommended future path)**- OMNeT++ generates a curated set of traces (topology/failure schedules, traffic demands, baseline routing decisions).
- Mininet replays those traces in real-time to validate controller behavior under identical conditions.
2) **Hard co-simulation / packet bridging (advanced, optional)**- Some nodes simulated in OMNeT++, others emulated in Mininet at the same time.
- Requires strict time coupling and a gateway that transforms/timeshifts packets.
- Not a v1 target.
### 2.4 Locked decisions (2026-02-18)
- **Tick authority:** `StreamLinkDeltas` is the control-plane source of truth for lane updates.
- **Events contract:** event streaming is retained, but aligned to the same requested `dt` and `selector`, and each event carries `tick_index`.
- **Orchestrator behavior:** streaming-driven execution is canonical; any scheduler is pacing-only.
- **Scenario translation:** orchestrator must fail-fast when it cannot produce a valid Geo/RF `ScenarioSpec`.
- **Python tooling:** Python workflows use `uv`; OMNeT++/INET workflows use `opp_env`.
---
## 3) Top-level components
### 3.1 Geometry/RF/Link-Budget Engine (black box, replaceable)
**Role:** The authoritative “physics layer” that translates orbital/propagation reality into network-usable link state.
**Key properties**- Replaceable implementation (Skyfield + ITU-R today, could be STK import or other later)
- Stable interface (the rest of SatSim depends only on its API)
- Produces time-indexed:
- Link feasibility (up/down)
- Link properties (delay/capacity/loss proxies)
- Discrete events (link up/down, handover, failures if modeled)
**Location:**`geomrf-engine/`---
### 3.2 Orchestrator (system conductor)
**Role:** Owns the simulation lifecycle and timebase. It is the “brain” that coordinates all lanes.
**Responsibilities**- Load scenario config → create/initialize the Geo/RF engine scenario
- Choose execution mode:
- OMNeT-only, Mininet-only, or both in parallel
- Drive execution pacing:
- offline apply-fast or real-time apply-paced, while consuming authoritative engine stream ticks
- Consume Geo/RF LinkState stream and distribute it to:
- OMNeT adapter
- Mininet adapter
- logging/metrics
- Collect artifacts (PCAPs, timeseries metrics, configs, run manifests)
- Provide reproducible run IDs and version stamping
**Location:**`orchestrator/`---
### 3.3 OMNeT++/INET Lane (packet-level discrete-event)
**Role:** Packet-level simulation of protocols, queuing, routing, traffic at scale.
**Responsibilities**- Build the network node models (routers, hosts, queues) using INET components
- Apply dynamic link updates (delay/capacity/loss/up-down) based on Geo/RF output
- Run deterministic experiments rapidly (sweeps)
- Export artifacts:
- logs + metrics
- optional PCAP outputs (where supported)
**Custom SatSim additions**- A lightweight **LinkState Adapter Module** that subscribes to orchestrator/Geo output
- A mechanism to apply link changes at simulation timestamps
**Environment and install management**- Use `opp_env` as the standard way to install/manage OMNeT++ and INET.
- Avoid ad-hoc/manual OMNeT++/INET installs in project workflows.
**Location:**`lanes/omnet/`---
### 3.4 Mininet/OVS Lane (SDN emulation)
**Role:** Real SDN controller + real forwarding plane under dynamic link conditions.
**Responsibilities**- Build an emulated topology with Mininet (or Containernet)
- Use OVS as the dataplane switch/router substrate
- Run a real SDN controller (ONOS or Ryu)
- Apply dynamic link shaping based on Geo/RF output:
-`tc/netem` for delay/loss/jitter
-`tbf/htb` for rate control
- interface up/down to emulate link drops
- Generate traffic using real tools:
- iperf3, D-ITG, SIPp, tcpreplay, custom apps
**Location:**`lanes/mininet/`---
### 3.5 Observability, artifacts, and visualization
**Role:** Make runs inspectable, comparable, and reproducible.
**Artifacts**- Scenario config snapshot + run manifest (versions, seeds, git SHAs)
- LinkState/Event traces (optional export)
- Metrics time-series (throughput/delay/loss/path changes)
- PCAP captures (Mininet tcpdump; OMNeT if enabled)
**Tools**- Prometheus + Grafana for dashboards
- Wireshark for PCAP analysis
**Location:**`observability/` and `artifacts/`---
## 4) System boundaries and data ownership
### 4.1 The Geo/RF engine owns *physics truth*
- It is the source of truth for which links can exist and their physical/network properties.
- Other components must not invent geometry/rf; they only consume the engine’s output.
### 4.2 The Orchestrator owns *time and execution*
- It defines run window requests, pacing mode, and synchronization rules.
- For v1/v1.1, tick production comes from Geo/RF stream output rather than orchestrator-generated ticks.
- It routes updates to the lanes and standardizes artifacts.
### 4.3 Each lane owns *packet/control behavior*
- OMNeT owns packet-level behavior inside DES.
- Mininet owns real SDN and Linux networking behavior.
---
## 5) Core data flows (end-to-end)
### 5.1 Initialization flow
1. User provides `ScenarioConfig` (YAML/JSON).
2. Orchestrator validates config and creates a new run ID.
3. Orchestrator calls Geo/RF engine:
-`CreateScenario` (returns scenario ref)
4. Orchestrator initializes selected lane(s):
- OMNeT: compile/load model, start run
- Mininet: build topology, start controller
5. Orchestrator subscribes to Geo/RF streaming output for LinkState and Events.
### 5.2 Runtime (parallel lane mode)
At each time tick:
1. Geo/RF produces `LinkDeltaBatch` + optional events.
2. Orchestrator receives it and distributes:
- OMNeT adapter: update channel/link state in simulator time
- Mininet adapter: apply tc/netem shaping and link toggles
- (optional) Event recorder: store aligned `EngineEvent` stream for analysis/observability
- Observability: record metrics and store link traces
3. Lanes generate traffic and produce metrics/PCAPs.
### 5.3 Completion flow
1. Orchestrator stops lane processes.
2. Orchestrator closes the Geo/RF scenario.
3. All artifacts are written under the run ID.
---
## 6) Timebase and execution modes
SatSim supports multiple execution modes, controlled by the Orchestrator:
### Mode A — OMNeT-only (offline DES)
- Orchestrator consumes Geo/RF ticks and applies them to OMNeT without wall-clock pacing.
- Highest scalability and repeatability.
### Mode B — Mininet-only (real-time emulation)
- Orchestrator consumes Geo/RF ticks and applies wall-clock pacing while updating Mininet shaping.
- Best for SDN/controller realism and app-level testing.
### Mode C — Parallel (OMNeT + Mininet simultaneously)
- Both lanes consume the same LinkState stream.
- Used to compare “simulated protocol outcomes” vs “real controller outcomes” under the same link dynamics.
### Mode D — Trace-driven replay (future/optional)
- Geo/RF and/or OMNeT exports a trace.
- Mininet replays trace deterministically.
---
## 7) Interfaces between components (high-level)
### 7.1 Geo/RF Engine interface (v1)
- gRPC service, Protobuf messages
- Scenario lifecycle + streaming link deltas/events
- Output is **NetworkView** link properties (up/down, delay, capacity, loss proxy)
- Optional debug scalars for validation (SNR margin, elevation, range)
- Event-stream alignment target: events use same requested window/selector/dt semantics as deltas and expose `tick_index`.
### 7.2 Orchestrator ↔ OMNeT interface
- OMNeT subscribes to orchestrator updates via:
- gRPC client inside a C++ adapter module, OR
- file/trace ingestion for offline runs
- Applies updates to INET channel/link parameters and toggles connectivity
### 7.3 Orchestrator ↔ Mininet interface
- Orchestrator controls Mininet via:
- Python Mininet API calls
- Linux `tc` and interface management commands
- SDN controller is external (ONOS/Ryu), connected in the standard Mininet way
---
## 8) Reproducibility rules
Each run must record:
- ScenarioConfig snapshot
- Seeds
- Engine versions:
- Geo/RF engine version + schema version
- orchestrator version
- OMNeT/INET versions and model git SHA
-`opp_env` environment definition/metadata used for OMNeT/INET
- controller version and app git SHA
- LinkState trace hash (if stored)
- Toolchain/container image tags (if containerized)
---
## 9) Suggested monorepo layout
satsim/
ARCHITECTURE.md
orchestrator/
...
subprojects/
geomrf-engine/
ARCHITECTURE.md # subproject-specific (the streaming API spec lives here)
proto/
src/
tests/
---
## 10) What an implementer of the Geo/RF engine must know
- The Geo/RF engine must be treated as **the physics oracle**.
- Its output must be:
- time-indexed
- sparse (selector-driven)
- stable and deterministic
- expressed in consistent units
- The Orchestrator will use it in both:
- offline sampling (for OMNeT)
- real-time streaming (for Mininet)
- The lanes do not need to know how link budgets are computed—only how to consume the streaming LinkDelta/Event outputs.
---
## 11) Roadmap hooks (explicit future extensions)
- Add a richer PHY view (optional fields) without breaking NetworkView consumers.
- Add trace import/replay for deterministic mininet runs.
- Add “shared SDN decision interface” so ONOS/Ryu path computation can be applied inside OMNeT.
- Add advanced co-simulation only if required (packet bridging).
---
Geometry/RF Engine v1/v1.1 Streaming API — Implementation Specification
This document specifies a complete, implementable Geometry/RF Engine API and server for streaming link-state deltas + events. It is written so another LLM can generate the code from existing Python geometry/RF/link-budget code (Skyfield + ITU-R + your models) with minimal guesswork.
Status note:
v1 baseline is implemented.
v1.1 alignment updates (for orchestrator compatibility) are now specified below, especially for StreamEvents tick alignment.
0) Deliverables
What must exist at the end
A runnable Python gRPC server that implements:
Scenario creation/closure
Capabilities/version endpoints
Streaming link deltas
Streaming events
A Protobuf schema with:
Stable IDs, time semantics, units
Selector logic (which links/nodes to compute)
Delta semantics (what counts as a “change”)
A reference Python client demonstrating:
Create scenario → stream deltas/events → close scenario
1) Core design constraints
1.1 Contract invariants
Scenario-scoped: All computation happens inside a ScenarioRef.
Time-indexed: All output is keyed by a timestamp and tick index.
Selector-driven: Never compute “all links” unless explicitly requested.
Streaming-first: Primary runtime interface is server→client stream.
Deterministic: Given identical inputs (scenario + seed + engine version), output is replayable.
1.2 What the engine outputs (NetworkView)
For each directed link (src → dst) at each tick, the engine provides:
up (boolean)
one_way_delay_s (float; seconds)
capacity_bps (float; bits per second)
loss_rate (float; [0,1] packet loss proxy OR PER proxy)
Determinism test (same scenario+seed → identical deltas)
Selector test (only requested links computed)
Threshold test (small changes suppressed)
Example client script (prints updates, counts links)
4) gRPC/Protobuf specification (v1)
4.1 .proto (authoritative spec)
Create proto/geomrf/v1/geomrf.proto:
syntax="proto3";packagegeomrf.v1;import"google/protobuf/timestamp.proto";import"google/protobuf/duration.proto";optiongo_package="geomrf/v1;geomrfv1";// harmless for other langs
// ---------------------------
// Service
// ---------------------------
serviceGeometryRfEngine{rpcGetVersion(GetVersionRequest)returns(GetVersionResponse);rpcGetCapabilities(GetCapabilitiesRequest)returns(GetCapabilitiesResponse);rpcCreateScenario(CreateScenarioRequest)returns(CreateScenarioResponse);rpcCloseScenario(CloseScenarioRequest)returns(CloseScenarioResponse);// Primary: stream sparse deltas per tick.
rpcStreamLinkDeltas(StreamLinkDeltasRequest)returns(streamLinkDeltaBatch);// Primary: stream discrete events (optional separate channel for clean consumers).
rpcStreamEvents(StreamEventsRequest)returns(streamEngineEvent);}// ---------------------------
// Version / capabilities
// ---------------------------
messageGetVersionRequest{}messageGetVersionResponse{stringengine_name=1;// e.g., "geomrf-engine"
stringengine_version=2;// semver, e.g., "1.0.0"
stringschema_version=3;// e.g., "geomrf.v1"
stringbuild_git_sha=4;// optional
}messageGetCapabilitiesRequest{}messageGetCapabilitiesResponse{stringschema_version=1;// Limits
uint32max_links_per_tick=2;uint32max_nodes=3;uint32max_streams_per_scenario=4;google.protobuf.durationmin_dt=5;google.protobuf.durationmax_dt=6;// Supported outputs
boolsupports_loss_rate=10;boolsupports_capacity_bps=11;boolsupports_delay_s=12;boolsupports_snr_margin_db=13;// Supported selectors/features (advertise so clients can adapt)
boolsupports_only_visible=20;boolsupports_min_elevation_deg=21;boolsupports_max_degree=22;boolsupports_link_types=23;// GS-SAT, SAT-SAT, etc.
}// ---------------------------
// Scenario lifecycle
// ---------------------------
messageCreateScenarioRequest{ScenarioSpecspec=1;}messageCreateScenarioResponse{stringscenario_ref=1;// UUID string
stringschema_version=2;}messageCloseScenarioRequest{stringscenario_ref=1;}messageCloseScenarioResponse{boolok=1;}// ---------------------------
// Scenario specification (v1)
// ---------------------------
messageScenarioSpec{// Reproducibility
uint64seed=1;// Time model
google.protobuf.timestampt0=2;// UTC
google.protobuf.timestampt1=3;// UTC
google.protobuf.durationdefault_dt=4;// Nodes
repeatedNodeSpecnodes=10;// Eligibility rules (which links can exist)
LinkPolicylink_policy=20;// Mapping PHY -> network outputs (can be simplistic in v1)
AdaptationPolicyadaptation=30;// Optional: engine-side caching hints
CacheHintscache_hints=40;}enumNodeRole{NODE_ROLE_UNSPECIFIED=0;SATELLITE=1;GROUND_STATION=2;USER_TERMINAL=3;}messageNodeSpec{stringnode_id=1;// stable ID used everywhere
NodeRolerole=2;// One of the following depending on role
SatelliteOrbitorbit=10;GroundFixedSitefixed_site=11;// Radio/terminal model parameters (minimal v1)
TerminalModelterminal=20;// Arbitrary tags for selectors/grouping
map<string,string>tags=30;}messageSatelliteOrbit{// v1: only TLE supported. Later: OEM/SP3/etc.
stringtle_line1=1;stringtle_line2=2;}messageGroundFixedSite{doublelat_deg=1;doublelon_deg=2;doublealt_m=3;}messageTerminalModel{// Minimal knobs to compute link budgets consistently.
// Units: dBW, dBi, Hz, K, etc.
doubletx_power_dbw=1;doubletx_gain_dbi=2;// can be treated as peak gain in v1
doublerx_gain_dbi=3;// can be treated as peak gain in v1
doublerx_noise_temp_k=4;doublebandwidth_hz=5;doublefrequency_hz=6;// Optional: simple pointing/antenna pattern loss approximation
doublepointing_loss_db=10;// default constant loss if you don’t model patterns yet
}enumLinkType{LINK_TYPE_UNSPECIFIED=0;GS_TO_SAT=1;SAT_TO_GS=2;SAT_TO_SAT=3;UT_TO_SAT=4;SAT_TO_UT=5;}messageLinkPolicy{// Which link types are allowed at all
repeatedLinkTypeallowed_types=1;// Dynamic feasibility thresholds
doublemin_elevation_deg=2;// default 0 if unused
boolonly_visible=3;// if true, return only visible/feasible links
// Degree constraints (optional)
uint32max_out_degree=10;// 0 means unlimited
uint32max_in_degree=11;// 0 means unlimited
// Optional: limit candidates by distance for scalability
doublemax_range_m=20;// 0 means unlimited
}messageAdaptationPolicy{// v1: a simple mapping mode.
// Future: full MCS tables, ACM, coding gains, etc.
enumMode{MODE_UNSPECIFIED=0;FIXED_RATE=1;// constant capacity if link is up, else 0
SNR_TO_RATE=2;// rate from snr_margin (simple piecewise)
SNR_TO_LOSS=3;// loss from snr_margin (simple logistic)
SNR_TO_BOTH=4;}Modemode=1;// v1 defaults
doublefixed_capacity_bps=2;doublefixed_loss_rate=3;// Parameters for simple SNR->rate/loss mappings (implementation defined but deterministic)
doublesnr_margin_min_db=10;doublesnr_margin_max_db=11;}messageCacheHints{boolprecompute_positions=1;boolprecompute_visibility=2;uint32max_cache_ticks=3;// 0 = engine default
}// ---------------------------
// Streaming requests
// ---------------------------
messageStreamLinkDeltasRequest{stringscenario_ref=1;// Time range for this stream. If empty, use scenario t0..t1.
google.protobuf.timestampt_start=2;google.protobuf.timestampt_end=3;// If unset, use scenario default_dt.
google.protobuf.durationdt=4;// Which links to consider/return.
LinkSelectorselector=10;// Delta emission thresholds
DeltaThresholdsthresholds=20;// Behavior knobs
boolemit_full_snapshot_first=30;// recommended true for simpler clients
boolinclude_debug_fields=31;// if true, fill debug fields in updates
}messageStreamEventsRequest{stringscenario_ref=1;google.protobuf.timestampt_start=2;google.protobuf.timestampt_end=3;// If unset, use scenario default_dt. Must satisfy capabilities bounds.
google.protobuf.durationdt=4;EventFilterfilter=10;// Apply the same selection surface as StreamLinkDeltas for deterministic alignment.
LinkSelectorselector=11;}messageLinkSelector{// v1 supports:
// - explicit pairs
// - by link type
// - by node role sets
repeatedLinkPairexplicit_pairs=1;repeatedLinkTypelink_types=2;// If non-empty, only consider links where src in set AND dst in set
repeatedstringsrc_node_ids=10;repeatedstringdst_node_ids=11;// Optional tag filters (exact match)
map<string,string>src_tags=12;map<string,string>dst_tags=13;// If true, apply scenario LinkPolicy.only_visible behavior
boolonly_visible=20;// Optional override thresholds (0 uses scenario policy)
doublemin_elevation_deg=21;doublemax_range_m=22;}messageDeltaThresholds{// Only emit update if absolute change exceeds threshold.
// 0 means "emit on any change" for that field.
doubledelay_s=1;doublecapacity_bps=2;doubleloss_rate=3;doublesnr_margin_db=4;// Emit if link up/down changes always (implicit).
}// ---------------------------
// Streaming output
// ---------------------------
messageLinkDeltaBatch{stringscenario_ref=1;stringschema_version=2;google.protobuf.timestamptime=3;// tick time
uint64tick_index=4;// If emit_full_snapshot_first=true, first batch may be a full snapshot.
boolis_full_snapshot=5;// Sparse updates (add/update)
repeatedLinkUpdateupdates=10;// Links to remove from active set (no longer selected/visible/allowed)
repeatedLinkKeyremovals=11;// Optional: server stats
TickStatsstats=20;}messageLinkUpdate{LinkKeykey=1;// Core NetworkView outputs
boolup=2;doubleone_way_delay_s=3;doublecapacity_bps=4;doubleloss_rate=5;// Optional debug fields (filled if include_debug_fields=true)
doublesnr_margin_db=10;doubleelevation_deg=11;doublerange_m=12;// Extension space for later (avoid breaking schema)
map<string,string>extra=30;}messageLinkKey{stringsrc=1;stringdst=2;LinkTypetype=3;}messageLinkPair{stringsrc=1;stringdst=2;LinkTypetype=3;}messageTickStats{uint32links_computed=1;uint32links_emitted=2;doublecompute_ms=3;}// ---------------------------
// Events
// ---------------------------
enumEventType{EVENT_TYPE_UNSPECIFIED=0;LINK_UP=1;LINK_DOWN=2;HANDOVER_START=3;HANDOVER_COMPLETE=4;NODE_FAILURE=5;NODE_RECOVERY=6;}messageEngineEvent{stringscenario_ref=1;stringschema_version=2;EventTypetype=3;google.protobuf.timestamptime=4;uint64tick_index=5;// Which entities are involved (optional depending on event)
stringnode_id=10;LinkKeylink=11;map<string,string>meta=20;}messageEventFilter{repeatedEventTypetypes=1;repeatedstringnode_ids=2;}
5) Server behavior specification (streaming semantics)
5.1 Timebase rules
ScenarioSpec.t0/t1 define the canonical simulation window.
Stream requests may override with t_start/t_end:
If unset → default to scenario window.
Engine must clamp requests to [t0, t1] unless explicitly configured otherwise.
dt:
If unset → use ScenarioSpec.default_dt.
Must be within [Capabilities.min_dt, Capabilities.max_dt]; otherwise return INVALID_ARGUMENT.
5.2 Tick indexing
Tick 0 corresponds to t_start.
Tick k corresponds to t_start + k*dt.
Engine must emit tick_index and time on every batch.
5.3 Active link set and removals
The stream maintains a client-side “active link table”.
updates[] means: create or replace link entry keyed by (src,dst,type).
removals[] means: delete that link entry (no longer in selection or no longer feasible under policy).
This is required for sparse streams when visibility causes links to appear/disappear.
5.4 First message behavior
If emit_full_snapshot_first=true:
The first emitted LinkDeltaBatch at tick 0 must have:
is_full_snapshot=true
updates[] containing all currently selected/feasible links
removals[] empty
This drastically simplifies consumers (no special “initialization” logic).
5.5 Delta emission thresholds
For ticks after the initial snapshot:
A link is emitted in updates[] if:
it is newly added, OR
its up changed, OR
abs(new.delay - old.delay) > thresholds.delay_s (if threshold > 0), OR
abs(new.capacity - old.capacity) > thresholds.capacity_bps (if threshold > 0), OR
abs(new.loss - old.loss) > thresholds.loss_rate (if threshold > 0), OR
(optional debug) changes exceed debug thresholds if included.
If a threshold is 0, treat it as “emit on any change”.
5.6 Event stream behavior (v1.1 alignment)
StreamEvents emits events in chronological order within [t_start, t_end]:
Minimum set in v1:
LINK_UP, LINK_DOWN
Optional:
HANDOVER_START, HANDOVER_COMPLETE if you can detect “best-sat changed” for a GS/UT.
Alignment requirements:
StreamEventsRequest.dt must use the same semantics/rules as delta streams (default_dt when unset, cap-validated).
StreamEventsRequest.selector must use the same link candidate filtering semantics as delta streams.
Every emitted event includes tick_index, where tick k = t_start + k*dt.
Events should be consistent with LinkDelta stream:
If link transitions from up=false to up=true at tick k, emit a LINK_UP event at that tick’s time.
5.7 Backpressure and cancellation
Use grpc.aio streaming and yield messages.
If the client is slow, await on send; do not build unbounded queues.
On cancellation (context.cancelled()):
stop computation promptly
release scenario references held by the stream
record a log entry with reason
6) Internal engine architecture (recommended)
6.1 Modules and responsibilities
scenario_store.py
Holds ScenarioRuntime objects keyed by scenario_ref
Contains:
validated ScenarioSpec
pre-parsed skyfield satellite objects
node dictionaries and role sets
cached computed data (positions/visibility per tick if enabled)
RNG seeded from ScenarioSpec.seed
timebase.py
Converts timestamps to ticks and vice versa
Handles rounding rules (recommend: tick times exactly t_start + k*dt)
selectors.py
Applies LinkSelector + LinkPolicy to yield candidate link pairs
Must support:
explicit pairs (exact)
link types
src/dst id filters
tag filters
only_visible/min_elevation/max_range constraints
compute/ephemeris.py
Builds skyfield EarthSatellite objects from TLE
Provides get_sat_ecef(t) or get_sat_eci(t) depending on your implementation
compute/geometry.py
Computes:
range (m)
elevation (deg) from ground site to satellite (and vice versa if needed)
visibility boolean: elevation >= min_elev, range <= max_range
compute/link_budget.py
Computes:
FSPL from range + frequency
atmospheric attenuation (via ITU-R), optional
noise power from bandwidth + noise temp
received power, C/N0, SNR margin, etc.
Returns a PhySummary (internal dataclass)
compute/adaptation.py
Maps PhySummary → NetworkLinkState:
capacity_bps and/or loss_rate
If v1, implement a deterministic piecewise mapping:
clamp snr_margin_db into [min,max]
map linearly to capacity between [0, terminal.bandwidth * eff_max] (or use fixed)
map snr_margin_db to loss via logistic or fixed thresholds
streaming/delta.py
Maintains per-stream “previous link table”
Computes updates and removals each tick
streaming/events.py
Detects link up/down transitions and yields EngineEvent
7) Scenario validation rules (must be enforced)
t0 < t1
default_dt > 0
Node IDs unique
Satellites must include valid TLE lines
Fixed sites must have valid lat/lon ranges
Terminal model must include:
frequency_hz > 0
bandwidth_hz > 0
rx_noise_temp_k > 0
LinkPolicy.allowed_types must be non-empty OR default to all valid types for provided roles
Return gRPC status INVALID_ARGUMENT with a descriptive error message if validation fails.
8) Performance requirements (practical targets)
These are engineering targets; adjust later.
Tick compute should scale with number of candidate links, not N² nodes.
Implement at least one of:
pre-filter by link type and role sets
max_range cutoff
max_degree pruning (keep best K neighbors by range or SNR)
Recommended optimizations (v1)
Cache satellite positions per tick if precompute_positions=true.
Cache ground station ECEF once.
Vectorize range computations where possible (NumPy arrays).
9) Determinism requirements
Determinism must include:
Ordering: Always sort link keys before emitting for stable output
sort by (src, dst, type)
RNG: Use numpy.random.Generator(PCG64(seed)) attached to scenario
Floating rounding: Do not over-round; but be consistent in computations (same order of ops)
Test: Run the same stream twice and ensure byte-equivalent serialized output (or field-wise equal within tolerance where appropriate).
10) Error handling (gRPC status codes)
Implement these consistent statuses:
NOT_FOUND: unknown scenario_ref
INVALID_ARGUMENT: bad time range, dt, selector, scenario validation failure
RESOURCE_EXHAUSTED: too many active streams for a scenario; or too many links per tick requested
ORCHESTRATOR_IMPLEMENTATION.md — SatSim Orchestrator (Python) Detailed Plan
This document is a task-driven implementation plan for the SatSim Orchestrator. It is intended to be handed to an LLM to implement the orchestrator in Python. It focuses on architecture, module boundaries, data flow, and concrete tasks (not deep RPC wire details).
The orchestrator is responsible for:
Loading a scenario
Starting and coordinating subcomponents (Geo/RF engine, OMNeT++ lane, Mininet lane)
Driving a unified timebase
Fanning out LinkState/Event updates to lane adapters
These ambiguities are now resolved and should be treated as fixed v1 design:
Authoritative tick source: StreamLinkDeltas is the only control-plane tick source. Lanes apply link state from deltas, not from events.
Event stream alignment (Option B accepted): evolve Geo/RF event API so StreamEventsRequest carries dt + selector, and EngineEvent carries tick_index, aligned to the same tick grid as deltas.
Error contract handling: orchestrator must handle NOT_FOUND, INVALID_ARGUMENT, FAILED_PRECONDITION, and RESOURCE_EXHAUSTED as first-class engine responses.
Scenario translation strictness: translation to Geo/RF ScenarioSpec is fail-fast and must satisfy all required engine fields/constraints.
Tooling policy: Python workflows use uv (uv run, uv add); do not rely on pip.
Comments 0
Log in to leave a comment