Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ jobs:
- run: cargo build --locked --verbose
- run: cargo test --locked --verbose
- run: cargo test --locked --features latentmesh --verbose
- run: cargo clippy --locked --features latentmesh --all-targets -- -D warnings
- run: cargo test --locked --features ruforecast --all-targets --verbose
- run: cargo test --locked --features latentmesh,ruforecast --all-targets --verbose
- run: cargo clippy --locked --features latentmesh,ruforecast --all-targets -- -D warnings
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@ ros2-dds = []
onnx = ["dep:ort"]
simulation = []
demo = ["simulation"]
full = ["mavlink", "onnx", "demo", "latentmesh"]
full = ["mavlink", "onnx", "demo", "latentmesh", "ruforecast"]
ruflo = ["dep:reqwest", "dep:serde_json"]
# Deterministic LatentMesh Air semantic state transport. Pinned to an audited
# upstream commit so the cross-repository wire contract cannot drift silently.
latentmesh = ["dep:latentmesh-air-core", "dep:ed25519-dalek"]
# Baseline-first predictive advisory. The backend-neutral core is pinned to an
# audited revision; learned-model runtimes are intentionally not linked.
ruforecast = ["dep:ruforecast-core"]
# Heavy GPU-capable MARL training (real Candle autodiff PPO). Off by default so
# the default build stays light and the existing test suite keeps passing.
train = ["dep:candle-core", "dep:candle-nn"]
Expand Down Expand Up @@ -63,6 +66,7 @@ hmac = "0.12"
sha2 = "0.10"
ed25519-dalek = { version = "2", default-features = false, features = ["std"], optional = true }
latentmesh-air-core = { git = "https://github.com/ruvnet/LatentMesh.git", rev = "1ff7332c17798eec3b42da5c6f1c271f355fa806", optional = true }
ruforecast-core = { git = "https://github.com/ruvnet/RuForecast.git", rev = "59173b55ef51a122db222c9902aeae521713d0a5", optional = true }

# Error handling
thiserror = "2.0"
Expand All @@ -87,6 +91,11 @@ name = "latentmesh_bench"
harness = false
required-features = ["latentmesh"]

[[bench]]
name = "ruforecast_bench"
harness = false
required-features = ["ruforecast"]

[[example]]
name = "latentmesh_loopback"
required-features = ["latentmesh"]
Expand Down
45 changes: 42 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ rather than replaces, your autopilot and transport:
- **MAPPO multi-agent RL** — 64-dim local observation, CTDE training, optional INT8 (ONNX) inference; real Candle PPO under the `train` feature
- **Security hardening** — MAVLink v2 signing, UWB GPS anti-spoofing, onboard geofencing, Remote ID
- **LatentMesh advisory plane** — signed deterministic peer-state deltas, bounded multi-profile framing, replay defense, and default-deny mission coordination with no flight authority
- **RuForecast advisory** — bounded local battery/link/progress forecasting with receipts, abstention, shadow-first rollout, and reduce-only assignment gates
- **Fail-safe state machine** — 10-state, GCS-independent onboard safety
- **Sim & training** — synthetic CSI generation, Gazebo / PX4 SITL interface, TOML mission configs

Expand All @@ -81,7 +82,7 @@ let estimated_secs = scenario.estimate_coverage_time_secs();

```bash
cargo build # core coordination layer
cargo build --features full # + mavlink, onnx, demo, latentmesh
cargo build --features full # + mavlink, onnx, demo, latentmesh, ruforecast
cargo test
```

Expand All @@ -107,7 +108,38 @@ cargo test
| `train` / `cuda` | Real Candle autodiff PPO training (GPU optional) |
| `ruflo` | Ruflo AI-agent HTTP backend integration |
| `latentmesh` | Authenticated LatentMesh Air advisory telemetry and governed mission-coordination policy |
| `full` | `mavlink` + `onnx` + `demo` + `latentmesh` |
| `ruforecast` | Baseline-first, receipt-bound local predictive advisory (shadow by default) |
| `full` | `mavlink` + `onnx` + `demo` + `latentmesh` + `ruforecast` |

## RuForecast predictive advisory

The optional `ruforecast` feature pins the backend-neutral
`ruforecast-core` contract at an exact reviewed commit. Each drone retains at
most 128 local observations of battery percentage, link quality, and aggregate
mission progress. It produces deterministic last-value baseline forecasts with
request/output receipts and explicit expiry. Position, velocity, identity,
raw sensor data, and model weights never enter the forecast series.

```bash
cargo test --locked --features ruforecast --all-targets
cargo test --locked --features latentmesh,ruforecast --all-targets
cargo bench --locked --features ruforecast --bench ruforecast_bench
```

The default rollout is **shadow**: results are measured but cannot change any
decision. An explicit canary policy can only return “do not assign this drone
new cooperative work” when a fresh forecast crosses a local battery or link
threshold. Missing, invalid, stale, disabled, or abstaining forecasts preserve
existing behavior. Forecasting cannot actuate, modify topology, create tasks,
or enter/clear a fail-safe.

RuForecast currently reports that no learned configuration has reliably beaten
last-value and seasonal-naive baselines out of sample. For that reason this
release does not link `ruforecast-model` or claim learned predictive lift.
Learned activation requires the promotion evidence in
[ADR-174](./docs/adr/ADR-174-ruforecast-predictive-advisory.md). See the
[operator guide](./docs/ruforecast-user-guide.md), [threat model](./docs/security/ruforecast-threat-model.md),
and [benchmark protocol](./docs/benchmarks/ruforecast-integration.md).

## LatentMesh advisory communications

Expand Down Expand Up @@ -144,9 +176,14 @@ shows this boundary visually on desktop and mobile.

| Evidence | Result |
|----------|--------|
| Default workspace tests | 167 passed |
| Default feature tests | 136 passed |
| LatentMesh feature tests | 191 passed |
| RuForecast feature tests | 143 passed |
| LatentMesh + RuForecast tests | 198 passed |
| No-default-feature tests | 136 passed |
| Cadence-limited 128-row observation | 183.96–235.14 ns |
| 128-row baseline forecast refresh | 11.385–12.003 µs |
| Reduce-only policy query | 690.74–764.99 ps |
| Local state projection | 386.62–397.98 ns |
| Sign and fragment at 64-byte MTU | 38.677–39.616 µs |
| Reassemble, verify, and admit | 47.952–51.988 µs |
Expand Down Expand Up @@ -174,6 +211,7 @@ src/
├── config/ — TOML SwarmConfig with mission presets
├── demo/ — synthetic CSI, DemoScenario runners
├── latentmesh/ — Authenticated advisory state, transport, policy, and metrics
├── forecast/ — Bounded RuForecast history, receipts, shadow/canary policy
└── integration/ — FlightController trait (PX4 / ArduPilot / sim)
```

Expand All @@ -197,6 +235,7 @@ cargo test -p ruv-jellyfish # the companion crate builds/tests standalone
| ADR-148 | Drone Swarm Control System | This crate |
| ADR-172 | Jellyfish-Inspired Swarm Behaviors | Energy-efficient loiter/aggregation — [`crates/ruv-jellyfish`](./crates/ruv-jellyfish) |
| ADR-173 | LatentMesh Communications and Advisory Orchestration | Signed sparse peer state with a hard flight-authority boundary — [`docs/adr/ADR-173-latentmesh-comms-orchestration.md`](./docs/adr/ADR-173-latentmesh-comms-orchestration.md) |
| ADR-174 | RuForecast Predictive Advisory | Baseline-first local forecasting with shadow promotion and reduce-only authority — [`docs/adr/ADR-174-ruforecast-predictive-advisory.md`](./docs/adr/ADR-174-ruforecast-predictive-advisory.md) |
| ADR-147 | OccWorld Occupancy World Model | Environment prior via `sensing::occworld_bridge` |
| ADR-134 | CSI→CIR ISTA Sparse Recovery | Drone payload sensing |
| ADR-146 | RF Encoder Multitask Heads | Drone payload inference |
Expand Down
51 changes: 51 additions & 0 deletions benches/ruforecast_bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion};
use ruview_swarm::forecast::{ForecastEngine, ForecastPolicy, ForecastRolloutMode};

fn primed_engine(rollout: ForecastRolloutMode) -> ForecastEngine {
let policy = ForecastPolicy {
rollout,
..ForecastPolicy::default()
};
let mut engine = ForecastEngine::new(policy);
for step in 1..=128 {
engine.observe_and_forecast(
step * 1_000,
100.0 - step as f32 * 0.1,
0.9,
step as f32 / 128.0,
);
}
engine
}

fn ruforecast_benchmarks(c: &mut Criterion) {
c.bench_function("ruforecast/observe_cadence_limited_128_rows", |b| {
b.iter_batched(
|| primed_engine(ForecastRolloutMode::Shadow),
|mut engine| {
engine.observe_and_forecast(128_100, 87.1, 0.9, 1.0);
black_box(engine.history_len());
},
BatchSize::SmallInput,
)
});

c.bench_function("ruforecast/observe_and_forecast_128_rows", |b| {
b.iter_batched(
|| primed_engine(ForecastRolloutMode::Shadow),
|mut engine| {
engine.observe_and_forecast(129_000, 87.1, 0.9, 1.0);
black_box(engine.last_advisory());
},
BatchSize::SmallInput,
)
});

let engine = primed_engine(ForecastRolloutMode::CanaryReduceOnly);
c.bench_function("ruforecast/reduce_only_policy", |b| {
b.iter(|| black_box(engine.is_eligible_for_new_work(black_box(128_000))))
});
}

criterion_group!(benches, ruforecast_benchmarks);
criterion_main!(benches);
108 changes: 108 additions & 0 deletions docs/adr/ADR-174-ruforecast-predictive-advisory.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# ADR-174: RuForecast predictive advisory

| | |
|---|---|
| **Status** | Accepted; baseline shadow integration implemented behind an opt-in feature |
| **Date** | 2026-09-02 |
| **Deciders** | ruv-drone maintainers |
| **Security review** | [RuForecast integration threat model](../security/ruforecast-threat-model.md) |
| **Upstream pin** | `ruvnet/RuForecast@59173b55ef51a122db222c9902aeae521713d0a5` |

## Decision

Integrate only `ruforecast-core` as an optional exact-revision dependency. The
first release uses its deterministic last-value baseline, validated time-series
contract, quantiles, provenance, privacy policy, abstention, and content
receipts. It does not link the Burn model or a hosted training runtime.

The forecast module observes only local battery percentage, normalized link
quality, and aggregate mission progress. History is a fixed-capacity queue,
128 rows by default. Forecast refresh is cadence-limited. Output is an expiring
summary bound to the request and output digests.

The authority invariant is:

> A forecast may reduce eligibility for new cooperative work only. It cannot
> create work, control flight, change topology, override a geofence, or enter,
> leave, or clear a fail-safe.

`Shadow` is the default and never reduces eligibility. `CanaryReduceOnly` is a
local opt-in. Missing, invalid, stale, abstaining, or disabled output preserves
existing behavior. This availability choice is safe because existing onboard
fail-safes remain authoritative and independent.

## Context and evidence

The practical use cases are predicting battery margin before another task,
detecting a weakening link before assigning relay work, and estimating mission
progress. Forecasting position or velocity is excluded because it could be
mistaken for collision-avoidance or control evidence.

RuForecast's own evidence ledger states that no learned configuration has yet
reliably beaten last-value and seasonal-naive baselines out of sample. Two
search winners failed independent verification. Treating an unproven network
as an operational improvement would be less capable than an honest baseline.
This ADR therefore makes baseline comparison and abstention prerequisites for
future model activation.

## Component contract

| Component | Input | Output | Authority |
|---|---|---|---|
| Bounded history | Three finite, range-checked local values and monotonic time | Up to 128 observations | None |
| RuForecast core | Typed series, policy, horizon, cadence, quantiles | Forecast or abstention with receipts | None |
| Shadow evaluator | Forecast summary and counters | Evidence only | None |
| Canary gate | Fresh summary and local thresholds | Eligible / ineligible for new work | Reduce only |
| Flight and safety code | Existing authoritative state | Existing control and fail-safe behavior | Unchanged |

The module owns no flight-controller, geofence, task-allocation mutation,
`peer_states`, or fail-safe mutation handle. Its orchestrator call occurs after
normal safety and mission processing. The only consumer method is explicitly
named `forecast_is_eligible_for_new_work`.

## Validation and promotion gates

A learned artifact remains shadow-only until all gates pass on independent,
out-of-search, temporally split data:

1. Beat both last-value and seasonal-naive weighted quantile loss on every
approved corpus by a predeclared margin; no averaged-away corpus failures.
2. Meet per-horizon loss and interval-coverage calibration bounds, including
missingness, stale input, and distribution-shift slices.
3. Carry an immutable artifact digest, exact feature schema, training-policy
receipt, dataset provenance, and independent evaluation receipt.
4. Pass activation allowlisting, resource limits, malformed-output tests,
restart/rollback tests, security review, and flight-authority regression.
5. Meet a declared p50/p95/p99 latency, memory, and energy budget on target
companion hardware under concurrent mission load.

Promotion stages are `Disabled` → `Shadow baseline` → `Shadow learned
candidate` → `Canary reduce-only` → `Fleet reduce-only`. Every stage has an
immediate local rollback to `Disabled` or a build without the feature.

## LatentMesh relationship

This release keeps forecasts local. A later ADR may define a signed,
versioned, compact LatentMesh advisory containing only horizon, quantiles,
expiry, source-state digest, artifact digest, request digest, and output digest.
The receiver must treat it as an untrusted peer claim with the same reduce-only
authority. Learned residuals and raw history remain forbidden on the wire.

## Alternatives rejected

- **Activate `ruforecast-model` now:** rejected because current upstream
evidence does not show reliable baseline lift.
- **Forecast kinematics:** rejected to protect the collision/control boundary.
- **Send raw histories through LatentMesh:** rejected for privacy, bandwidth,
replay surface, and unclear operational benefit.
- **Fail closed on forecast outage:** rejected because forecast availability
must not disable an otherwise safe drone; onboard safety already fails closed
at the appropriate control boundary.

## Consequences

The integration is useful immediately for contract validation, telemetry
collection, rollout plumbing, and operational baselines without overstating AI
capability. It adds bounded allocation and hashing cost only when enabled.
Materializing the typed series remains the primary measured optimization target;
forecast refresh is cadence-limited to avoid doing that work every control tick.
69 changes: 69 additions & 0 deletions docs/benchmarks/ruforecast-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# RuForecast integration benchmark and validation protocol

## Questions

1. What CPU time and allocation cost does one 128-row observation/forecast add?
2. What does the reduce-only policy query cost?
3. Does cadence limiting prevent forecast construction on every control tick?
4. Can a candidate beat both last-value and seasonal-naive on unseen data?

## Reproducer

```bash
cargo bench --locked --features ruforecast --bench ruforecast_bench
cargo test --locked --features ruforecast --all-targets
cargo test --locked --features latentmesh,ruforecast --all-targets
```

Record CPU, OS, Rust version, git commit, build profile, p50 estimate and
Criterion confidence interval. Results are software measurements, not radio,
energy, prediction-accuracy, or end-to-end flight claims.

## Performance gates

The initial engineering budgets on representative companion hardware are:

| Operation | Gate |
|---|---:|
| Reduce-only eligibility query | p99 ≤ 10 µs |
| 128-row baseline refresh | p99 ≤ 1 ms |
| Forecast history | ≤ 128 rows by default |
| Added control-tick work before cadence | range check + bounded queue only |

Criterion measures central tendency and confidence intervals, not p99. A
target-hardware load harness must verify p99 before canary promotion.

## Accuracy gate for a learned candidate

Use temporally separated, out-of-search corpora with frozen preprocessing.
Report weighted quantile loss overall and at each horizon, 80% interval
coverage, missingness slices, calibration, abstention rate, and both baseline
scores. Predeclare margins and seeds. A candidate fails if it loses to either
baseline on any required corpus, even when its average looks better.

## Optimization record

The first code-level optimization is cadence limiting: the bounded queue is
updated at observation rate, but series materialization, canonical hashing,
and inference run no more frequently than `step_ms`. This avoids repeated heap
allocation and SHA-256 work when the control loop runs faster than the forecast
cadence. Further optimization requires profiler or benchmark evidence; do not
weaken validation, receipts, bounds, or the flight-authority separation.

## Branch measurements

Measured 2026-09-02 on an x86_64 Intel Xeon Platinum 8573C runner with
`rustc 1.98.0`, optimized Criterion profile, 1-second warm-up, 2-second
measurement, and 30 samples:

| Operation | Criterion estimate (95% confidence interval) |
|---|---:|
| Cadence-limited observation, 128-row queue | 183.96–235.14 ns |
| Observation plus 128-row baseline refresh | 11.385–12.003 µs |
| Fresh reduce-only eligibility query | 690.74–764.99 ps |

The policy query is small enough for the optimizer to reduce to a few loads and
comparisons; treat the sub-nanosecond result as a microbenchmark lower bound,
not an end-to-end latency claim. Cadence limiting makes the usual observation
path roughly 50 times cheaper than a refresh on this runner. These values
should not be copied to other hardware as a guarantee.
Loading
Loading