From 506f4985afa4d89ea8348c19744d1adb64e5de64 Mon Sep 17 00:00:00 2001 From: Mathew Beane Date: Mon, 16 Nov 2026 07:34:18 -0500 Subject: [PATCH 1/2] feat(worldgraph): serve the managed room as an engine v2 snapshot on its own route Adds GET /api/v1/worldgraph/engine. It returns the protocol 1 envelope with a schema_version 2 engine snapshot (next_edge_id, WorldEdgeRecord edges) projected from the same validated managed topology as /snapshot, behind the same read policy. /snapshot is unchanged. --- .../src/companion_integration.rs | 3 + .../src/companion_room.rs | 6 ++ .../wifi-densepose-sensing-server/src/main.rs | 1 + .../src/managed_worldgraph.rs | 90 ++++++++++++++++++- .../managed-worldgraph-engine-v2.json | 26 ++++++ 5 files changed, 124 insertions(+), 2 deletions(-) create mode 100644 v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json diff --git a/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs b/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs index fa5183b5cd..77b0d1f455 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs @@ -260,6 +260,7 @@ fn policy(method: &axum::http::Method, path: &str) -> Option { | "/api/v1/room-learner/selection" | "/api/v1/room-learner/progress" | "/api/v1/worldgraph/snapshot" + | "/api/v1/worldgraph/engine" | "/api/v1/calibration/status" | "/api/v1/pose/calibration/status" | "/ws/sensing" @@ -389,6 +390,8 @@ mod tests { assert_eq!(policy(&Method::GET, "/api/v1/room-learner/selection"), Some(false)); assert_eq!(policy(&Method::GET, "/api/v1/worldgraph/snapshot"), Some(false)); assert_eq!(policy(&Method::POST, "/api/v1/worldgraph/snapshot"), None); + assert_eq!(policy(&Method::GET, "/api/v1/worldgraph/engine"), Some(false)); + assert_eq!(policy(&Method::POST, "/api/v1/worldgraph/engine"), None); assert_eq!(policy(&Method::HEAD, "/api/v1/room-learner/selection"), Some(false)); assert_eq!(policy(&Method::GET, "/api/v1/room-learner/status"), None); assert_eq!(policy(&Method::GET, "/api/v1/room-learner/progress"), Some(false)); diff --git a/v2/crates/wifi-densepose-sensing-server/src/companion_room.rs b/v2/crates/wifi-densepose-sensing-server/src/companion_room.rs index 66f9d9d73a..8c5233863b 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/companion_room.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/companion_room.rs @@ -250,6 +250,12 @@ impl SharedRoomStore { self.worldgraph_cursor.lock().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.project(&room, privacy_denied) } + /// Same locking order as `worldgraph_snapshot`; shares its cursor. + pub fn worldgraph_engine_snapshot(&self, privacy_denied: bool) -> Result { + let room = self.current.lock().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + self.worldgraph_cursor.lock().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.project_engine(&room, privacy_denied) + } + pub fn snapshot(&self) -> Option { self.current.lock().ok().map(|v| v.clone()) } pub fn matches_binding(&self, binding: &str, node_ids: &[u8]) -> bool { let Ok(e) = self.current.lock() else { diff --git a/v2/crates/wifi-densepose-sensing-server/src/main.rs b/v2/crates/wifi-densepose-sensing-server/src/main.rs index 79bda2defb..bfb78fb244 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/main.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/main.rs @@ -16817,6 +16817,7 @@ async fn main() { // Per-node health endpoint .route("/api/v1/nodes", get(nodes_endpoint)) .route("/api/v1/worldgraph/snapshot", get(managed_worldgraph::snapshot)) + .route("/api/v1/worldgraph/engine", get(managed_worldgraph::engine_snapshot)) // ADR-110 iter 29 — per-node mesh sync state for HTTP clients. .route("/api/v1/nodes/:id/sync", get(node_sync_endpoint)) .route("/api/v1/mesh", get(mesh_endpoint)) diff --git a/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs b/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs index 449d6827b8..c2769196c0 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs @@ -14,15 +14,57 @@ impl Default for Cursor { } } impl Cursor { - pub fn project(&mut self, envelope: &Envelope, privacy_denied: bool) -> Result { + /// Advances the cursor only when the projected content changed, and returns that content. + fn advance(&mut self, envelope: &Envelope, privacy_denied: bool) -> Result { let content = topology(envelope, privacy_denied)?; if self.content.as_ref() != Some(&content) { if self.sequence >= MAX_SAFE { return Err(StatusCode::SERVICE_UNAVAILABLE); } self.sequence += 1; self.content = Some(content.clone()); } + Ok(content) + } + pub fn project(&mut self, envelope: &Envelope, privacy_denied: bool) -> Result { + let content = self.advance(envelope, privacy_denied)?; Ok(json!({"protocol_version":2,"stream_epoch":self.epoch,"seq":self.sequence,"topology":content})) } + /// The same configured room as an engine snapshot, schema version 2, in the protocol 1 envelope + /// (`graph`) that WorldGraph clients already parse. It shares this cursor, so `seq` moves with the topology. + pub fn project_engine(&mut self, envelope: &Envelope, privacy_denied: bool) -> Result { + let content = self.advance(envelope, privacy_denied)?; + let graph = engine_v2(&content)?; + Ok(json!({"protocol_version":1,"stream_epoch":self.epoch,"seq":self.sequence,"graph":graph})) + } +} + +/// Engine snapshot schema v2 derived only from the already-validated managed topology, so it carries +/// nothing the topology route does not: no tracks, semantic state or learned history. +/// This is a projection with the engine's v2 wire shape, not the output of the engine's own graph writer. +/// Frame: the topology is x right, y down, from the room's top-left corner. The engine frame is ENU from the +/// room's south-west corner, so `east_m = x_m` and `north_m = length_m - y_m`. +/// Values the managed room cannot supply are fixed placeholders, not measurements: `registration` (no +/// geographic origin exists; the topology says `registration: null`), sensor `up_m` (height is null), the +/// `located_in` `since_unix_ms` (no timestamp is kept) and the room `floor`. +fn engine_v2(topology: &Value) -> Result { + let mut nodes: Vec = Vec::new(); + if topology["status"] == "configured" { + let room = &topology["room"]; + let (width, length) = (room["width_m"].as_f64(), room["length_m"].as_f64()); + let (Some(width), Some(length)) = (width, length) else { return Err(StatusCode::INTERNAL_SERVER_ERROR); }; + nodes.push(json!({"kind":"room","id":1,"area_id":null,"name":room["name"], + "bounds_enu":{"shape":"rectangle","min_e":0.0,"min_n":0.0,"max_e":width,"max_n":length},"floor":0})); + for n in topology["nodes"].as_array().into_iter().flatten() { + let (Some(x), Some(y)) = (n["x_m"].as_f64(), n["y_m"].as_f64()) else { return Err(StatusCode::INTERNAL_SERVER_ERROR); }; + nodes.push(json!({"kind":"sensor","id":n["id"],"device_id":format!("node-{}", n["node_id"]), + "position":{"east_m":x,"north_m":length - y,"up_m":0.0},"modality":"wifi_csi"})); + } + } + let edges: Vec = topology["edges"].as_array().into_iter().flatten().enumerate().map(|(i, e)| json!({ + "id": i as u64 + 1, "from": e["from"], "to": e["to"], "edge": {"rel": e["rel"], "since_unix_ms": 0} + })).collect(); + let next_id = nodes.iter().filter_map(|n| n["id"].as_u64()).max().unwrap_or(0) + 1; + Ok(json!({"schema_version":2,"registration":{"origin":{"lat":0.0,"lon":0.0,"alt":0.0},"heading_deg":0.0,"scale":1.0}, + "next_id":next_id,"next_edge_id":edges.len() as u64 + 1,"nodes":nodes,"edges":edges})) } fn topology(envelope: &Envelope, privacy_denied: bool) -> Result { @@ -67,6 +109,13 @@ pub async fn snapshot(State(state): State) -> Result) -> Result { + let state = state.read().await; + let store = state.current_room_store.as_ref().ok_or(StatusCode::NOT_IMPLEMENTED)?; + let value = store.worldgraph_engine_snapshot(state.privacy_mode)?; + Ok(([(header::CACHE_CONTROL, "private, no-store")], Json(value)).into_response()) +} + #[cfg(test)] mod tests { use super::*; @@ -118,6 +167,35 @@ mod tests { let fixture: Value = serde_json::from_str(include_str!("../tests/fixtures/managed-worldgraph-v1.json")).unwrap(); assert_eq!(wire, fixture); } + #[test] + fn engine_projection_matches_fixture_and_flips_y_to_north() { + let mut cursor = Cursor { epoch: format!("wg-{}", "1".repeat(64)), sequence: 0, content: None }; + let wire = cursor.project_engine(&envelope(), false).unwrap(); + let fixture: Value = serde_json::from_str(include_str!("../tests/fixtures/managed-worldgraph-engine-v2.json")).unwrap(); + assert_eq!(wire, fixture); + // y_m = 2.0 down from the top of a 3.0 m room is 1.0 m north of the south wall. + assert_eq!(wire["graph"]["nodes"][1]["position"]["north_m"], 1.0); + } + #[test] + fn engine_projection_is_empty_unless_configured_and_shares_the_cursor() { + let mut cursor = Cursor::default(); + let empty = Envelope { installation_id: "i".into(), revision: 1, binding_digest: None, room: None }; + let g = cursor.project_engine(&empty, false).unwrap(); + assert_eq!((g["graph"]["nodes"].clone(), g["graph"]["edges"].clone(), g["graph"]["next_id"].clone(), g["graph"]["next_edge_id"].clone()), (json!([]), json!([]), json!(1), json!(1))); + assert_eq!(g["seq"], 1); + // Same content through either projection never advances seq; a changed room advances it once. + assert_eq!(cursor.project(&empty, false).unwrap()["seq"], 1); + assert_eq!(cursor.project_engine(&envelope(), false).unwrap()["seq"], 2); + assert_eq!(cursor.project(&envelope(), false).unwrap()["seq"], 2); + let denied = cursor.project_engine(&envelope(), true).unwrap(); + assert_eq!(denied["graph"]["nodes"], json!([])); + assert_eq!(denied["seq"], 3); + } + #[test] + fn engine_projection_never_serialises_forbidden_fields() { + let text = Cursor::default().project_engine(&envelope(), false).unwrap().to_string(); + for forbidden in ["raw_csi", "person_track", "forbidden", "installation-1", "binding"] { assert!(!text.contains(forbidden), "{forbidden}"); } + } #[tokio::test] async fn real_route_requires_read_authority_and_never_publishes_or_selects() { use wifi_densepose_sensing_server::bearer_auth::{AuthState, require_bearer}; @@ -134,7 +212,7 @@ mod tests { let original = store.snapshot().unwrap(); let mut inner = crate::AppStateInner::minimal(); inner.current_room_store = Some(store.clone()); let state = std::sync::Arc::new(tokio::sync::RwLock::new(inner)); - let app = Router::new().route("/api/v1/worldgraph/snapshot", get(snapshot)).with_state(state.clone()) + let app = Router::new().route("/api/v1/worldgraph/snapshot", get(snapshot)).route("/api/v1/worldgraph/engine", get(engine_snapshot)).with_state(state.clone()) .layer(axum::middleware::from_fn_with_state(AuthState::from_token("owner-test-token"), require_bearer)); let request = || Request::builder().uri("/api/v1/worldgraph/snapshot").header("authorization","Bearer owner-test-token").body(Body::empty()).unwrap(); let denied = app.clone().oneshot(Request::builder().uri("/api/v1/worldgraph/snapshot").body(Body::empty()).unwrap()).await.unwrap(); @@ -145,6 +223,14 @@ mod tests { assert_eq!(first["topology"]["status"],"configured"); assert_eq!(store.snapshot().unwrap().revision, original.revision); assert_eq!(store.snapshot().unwrap().binding_digest, original.binding_digest); + let engine_request = || Request::builder().uri("/api/v1/worldgraph/engine").header("authorization","Bearer owner-test-token").body(Body::empty()).unwrap(); + let engine_denied = app.clone().oneshot(Request::builder().uri("/api/v1/worldgraph/engine").body(Body::empty()).unwrap()).await.unwrap(); + assert_eq!(engine_denied.status(), StatusCode::UNAUTHORIZED); + let engine_response = app.clone().oneshot(engine_request()).await.unwrap(); + assert_eq!(engine_response.status(), StatusCode::OK); assert_eq!(engine_response.headers()[header::CACHE_CONTROL], "private, no-store"); + let engine: Value = serde_json::from_slice(&to_bytes(engine_response.into_body(), 16_384).await.unwrap()).unwrap(); + assert_eq!((engine["protocol_version"].clone(), engine["graph"]["schema_version"].clone(), engine["seq"].clone()), (json!(1), json!(2), first["seq"].clone())); + assert_eq!(store.snapshot().unwrap().revision, original.revision); state.write().await.privacy_mode = true; let response = app.oneshot(request()).await.unwrap(); let privacy: Value = serde_json::from_slice(&to_bytes(response.into_body(), 16_384).await.unwrap()).unwrap(); diff --git a/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json b/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json new file mode 100644 index 0000000000..7e36135d6b --- /dev/null +++ b/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json @@ -0,0 +1,26 @@ +{ + "protocol_version": 1, + "stream_epoch": "wg-1111111111111111111111111111111111111111111111111111111111111111", + "seq": 1, + "graph": { + "schema_version": 2, + "registration": { "origin": { "lat": 0.0, "lon": 0.0, "alt": 0.0 }, "heading_deg": 0.0, "scale": 1.0 }, + "next_id": 273, + "next_edge_id": 2, + "nodes": [ + { + "kind": "room", "id": 1, "area_id": null, "name": "Configured room", + "bounds_enu": { "shape": "rectangle", "min_e": 0.0, "min_n": 0.0, "max_e": 2.5, "max_n": 3.0 }, + "floor": 0 + }, + { + "kind": "sensor", "id": 272, "device_id": "node-15", + "position": { "east_m": 1.25, "north_m": 1.0, "up_m": 0.0 }, + "modality": "wifi_csi" + } + ], + "edges": [ + { "id": 1, "from": 272, "to": 1, "edge": { "rel": "located_in", "since_unix_ms": 0 } } + ] + } +} From 9f18fb9ef5e1913d38e6511728e2262768d82427 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Thu, 19 Nov 2026 13:39:12 +0100 Subject: [PATCH 2/2] fix(worldgraph): preserve unknowns in an explicit managed projection contract --- .../worldgraph-managed-projection.md | 77 +++++++ .../src/companion_integration.rs | 1 + .../src/managed_worldgraph.rs | 213 ++++++++++++++---- ...naged-worldgraph-engine-projection-v1.json | 53 +++++ .../managed-worldgraph-engine-v2.json | 26 --- 5 files changed, 306 insertions(+), 64 deletions(-) create mode 100644 docs/integrations/worldgraph-managed-projection.md create mode 100644 v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-projection-v1.json delete mode 100644 v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json diff --git a/docs/integrations/worldgraph-managed-projection.md b/docs/integrations/worldgraph-managed-projection.md new file mode 100644 index 0000000000..75040c274b --- /dev/null +++ b/docs/integrations/worldgraph-managed-projection.md @@ -0,0 +1,77 @@ +# Managed WorldGraph projection contract + +`GET /api/v1/worldgraph/engine` projects the configured managed room into a local +Cartesian layout. It does not read the engine graph writer or report perception, +measured occupancy, calibrated height, geographic registration or live RF links. +The endpoint is read-only and requires the same read authority as `/snapshot`. + +## Wire identity and compatibility + +The response has exactly `protocol_version`, `stream_epoch`, `seq`, `projection`. +`protocol_version` is3. `projection.schema` is +`ruview.worldgraph.managed-engine-projection.v1`. This is a new managed projection, +not an upstream WorldGraph schema-v2 snapshot. Do not remove that identity and +feed its contents into an engine-snapshot parser. + +Existing `/api/v1/worldgraph/snapshot` retains protocol2 and its managed-topology +schema and fields. Its cursor is shared with this projection: repeated reads of +unchanged content through either route do not advance the sequence; source room +or privacy changes advance it once. Restarts use a new random epoch. These are +publication cursors, not measurement timestamps or proof of fresh sensor data. + +Current mobile clients continue to request `/snapshot`; their strict legacy +engine/envelope parsers must reject protocol3. A future projection-aware consumer +must be separately implemented and qualified. This server PR does not switch a +mobile URL, activate a new layer or qualify a packaged helper. + +## Projection fields + +| Field | Meaning | +|---|---| +| `schema` | Explicit managed-projection schema above | +| `provenance` | `operator_entered`; no measurement authority is implied | +| `status` | `configured`, `not_configured` or `privacy_denied` | +| `coordinate_frame` | `managed_room_local`; no geographic origin is known | +| `axis_convention` | `x_right_y_up_metres` | +| `registration` | Always null: geographic origin, scale and heading are unknown | +| `next_id`, `next_edge_id` | Bounded local identifier allocators, not evidence | +| `nodes`, `edges` | Allowlisted room/sensor placement records and membership | + +The node/edge field names resemble the engine layout for future adaptation, but +nullable fields intentionally differ from its mandatory numeric values: + +- A room has rectangular `bounds_enu` and `floor:null`; a configured room does + not establish its floor number. +- A sensor position retains `east_m=x_m`, `north_m=room_length_m-y_m` and + `up_m:null`. The source origin is the room's top-left and y points down; the + projection origin is its bottom-left and y points up. `east_m`/`north_m` are + local axis names here, not measured global east/north. Valid planar zero + coordinates remain zero; unknown height is not converted to ground level. +- `located_in` edges retain `since_unix_ms:null`: the source keeps no timestamp + for the relationship. Sequence numbers do not supply one. + +No generic engine `schema_version:2`, identity geographic registration, invented +floor0, height0 or Unix epoch0 is emitted. This prevents an unaware strict parser +from accepting configured layout as ordinary engine evidence. Projection-aware +consumers must preserve nulls and provenance through display, storage and export; +no inference authority follows from successful parsing. + +When not configured or privacy-denied, nodes/edges are empty and both next IDs +are1. Privacy-denied responses reveal no room name, dimensions, sensor identifiers, +raw source records, binding digest, installation ID, tracks or semantic history. +The status distinguishes withheld geometry from an empty configured graph. + +## Transport and failure behavior + +Responses are `private, no-store`. GET/HEAD do not publish a room, change its +revision/binding, select a learner, write a baseline or start a sensor. POST and +other writes are unsupported. Missing read authorization is rejected. If the +store is unavailable, the endpoint returns501; invalid internal projection input +or poisoned locks return500; sequence exhaustion on a changed publication +returns503. Projection validation happens before cursor mutation so a failed +projection cannot make the next valid read appear newer than its source change. + +The repository fixture `managed-worldgraph-engine-projection-v1.json` is the +configured example. Tests cover unknowns, valid planar zeros/bounds, privacy, +not-configured, cursor stability/failure, route authorization and legacy snapshot +compatibility. Physical registration or sensing accuracy is outside this contract. diff --git a/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs b/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs index 77b0d1f455..490b1d8b3a 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/companion_integration.rs @@ -392,6 +392,7 @@ mod tests { assert_eq!(policy(&Method::POST, "/api/v1/worldgraph/snapshot"), None); assert_eq!(policy(&Method::GET, "/api/v1/worldgraph/engine"), Some(false)); assert_eq!(policy(&Method::POST, "/api/v1/worldgraph/engine"), None); + assert_eq!(policy(&Method::HEAD, "/api/v1/worldgraph/engine"), Some(false)); assert_eq!(policy(&Method::HEAD, "/api/v1/room-learner/selection"), Some(false)); assert_eq!(policy(&Method::GET, "/api/v1/room-learner/status"), None); assert_eq!(policy(&Method::GET, "/api/v1/room-learner/progress"), Some(false)); diff --git a/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs b/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs index c2769196c0..216f79d56a 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/managed_worldgraph.rs @@ -15,8 +15,7 @@ impl Default for Cursor { } impl Cursor { /// Advances the cursor only when the projected content changed, and returns that content. - fn advance(&mut self, envelope: &Envelope, privacy_denied: bool) -> Result { - let content = topology(envelope, privacy_denied)?; + fn advance(&mut self, content: Value) -> Result { if self.content.as_ref() != Some(&content) { if self.sequence >= MAX_SAFE { return Err(StatusCode::SERVICE_UNAVAILABLE); } self.sequence += 1; @@ -25,46 +24,98 @@ impl Cursor { Ok(content) } pub fn project(&mut self, envelope: &Envelope, privacy_denied: bool) -> Result { - let content = self.advance(envelope, privacy_denied)?; + let content = self.advance(topology(envelope, privacy_denied)?)?; Ok(json!({"protocol_version":2,"stream_epoch":self.epoch,"seq":self.sequence,"topology":content})) } - /// The same configured room as an engine snapshot, schema version 2, in the protocol 1 envelope - /// (`graph`) that WorldGraph clients already parse. It shares this cursor, so `seq` moves with the topology. + /// A typed managed-room projection, never an ordinary engine snapshot. + /// Validate before committing the shared cursor; failed reads do not freshen it. pub fn project_engine(&mut self, envelope: &Envelope, privacy_denied: bool) -> Result { - let content = self.advance(envelope, privacy_denied)?; - let graph = engine_v2(&content)?; - Ok(json!({"protocol_version":1,"stream_epoch":self.epoch,"seq":self.sequence,"graph":graph})) + let content = topology(envelope, privacy_denied)?; + let projection = engine_projection(&content)?; + self.advance(content)?; + Ok(json!({"protocol_version":3,"stream_epoch":self.epoch,"seq":self.sequence,"projection":projection})) } } -/// Engine snapshot schema v2 derived only from the already-validated managed topology, so it carries -/// nothing the topology route does not: no tracks, semantic state or learned history. -/// This is a projection with the engine's v2 wire shape, not the output of the engine's own graph writer. -/// Frame: the topology is x right, y down, from the room's top-left corner. The engine frame is ENU from the -/// room's south-west corner, so `east_m = x_m` and `north_m = length_m - y_m`. -/// Values the managed room cannot supply are fixed placeholders, not measurements: `registration` (no -/// geographic origin exists; the topology says `registration: null`), sensor `up_m` (height is null), the -/// `located_in` `since_unix_ms` (no timestamp is kept) and the room `floor`. -fn engine_v2(topology: &Value) -> Result { - let mut nodes: Vec = Vec::new(); - if topology["status"] == "configured" { +/// A configured layout projection, deliberately distinct from an engine snapshot. +/// Engine schema v2 requires numbers where this source has unknown values. +#[derive(serde::Serialize)] +struct ManagedEngineProjection { + schema: &'static str, + provenance: &'static str, + coordinate_frame: &'static str, + axis_convention: &'static str, + status: ProjectionStatus, + registration: (), + next_id: u64, + next_edge_id: u64, + nodes: Vec, + edges: Vec, +} +#[derive(serde::Serialize)] +#[serde(rename_all = "snake_case")] +enum ProjectionStatus { Configured, NotConfigured, PrivacyDenied } +#[derive(serde::Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +enum ProjectedNode { + Room { id: u64, area_id: Option, name: String, bounds_enu: ProjectedBounds, floor: Option }, + Sensor { id: u64, device_id: String, position: ProjectedPosition, modality: &'static str }, +} +impl ProjectedNode { + fn id(&self) -> u64 { match self { Self::Room { id, .. } | Self::Sensor { id, .. } => *id } } +} +#[derive(serde::Serialize)] +struct ProjectedBounds { shape: &'static str, min_e: f64, min_n: f64, max_e: f64, max_n: f64 } +#[derive(serde::Serialize)] +struct ProjectedPosition { east_m: f64, north_m: f64, up_m: Option } +#[derive(serde::Serialize)] +struct ProjectedEdge { id: u64, from: u64, to: u64, edge: ProjectedMembership } +#[derive(serde::Serialize)] +struct ProjectedMembership { rel: &'static str, since_unix_ms: Option } + +fn engine_projection(topology: &Value) -> Result { + let status = match topology["status"].as_str() { + Some("configured") => ProjectionStatus::Configured, + Some("not_configured") => ProjectionStatus::NotConfigured, + Some("privacy_denied") => ProjectionStatus::PrivacyDenied, + _ => return Err(StatusCode::INTERNAL_SERVER_ERROR), + }; + let mut nodes = Vec::new(); + let mut edges = Vec::new(); + if matches!(status, ProjectionStatus::Configured) { let room = &topology["room"]; - let (width, length) = (room["width_m"].as_f64(), room["length_m"].as_f64()); - let (Some(width), Some(length)) = (width, length) else { return Err(StatusCode::INTERNAL_SERVER_ERROR); }; - nodes.push(json!({"kind":"room","id":1,"area_id":null,"name":room["name"], - "bounds_enu":{"shape":"rectangle","min_e":0.0,"min_n":0.0,"max_e":width,"max_n":length},"floor":0})); - for n in topology["nodes"].as_array().into_iter().flatten() { - let (Some(x), Some(y)) = (n["x_m"].as_f64(), n["y_m"].as_f64()) else { return Err(StatusCode::INTERNAL_SERVER_ERROR); }; - nodes.push(json!({"kind":"sensor","id":n["id"],"device_id":format!("node-{}", n["node_id"]), - "position":{"east_m":x,"north_m":length - y,"up_m":0.0},"modality":"wifi_csi"})); + let (Some(width), Some(length), Some(name)) = + (room["width_m"].as_f64(), room["length_m"].as_f64(), room["name"].as_str()) + else { return Err(StatusCode::INTERNAL_SERVER_ERROR); }; + if !width.is_finite() || !length.is_finite() || width <= 0.0 || length <= 0.0 { + return Err(StatusCode::INTERNAL_SERVER_ERROR); + } + nodes.push(ProjectedNode::Room { + id: 1, area_id: None, name: name.to_owned(), floor: None, + bounds_enu: ProjectedBounds { shape: "rectangle", min_e: 0.0, min_n: 0.0, max_e: width, max_n: length }, + }); + let source_nodes = topology["nodes"].as_array().ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; + for n in source_nodes { + let (Some(id), Some(node_id), Some(x), Some(y)) = + (n["id"].as_u64(), n["node_id"].as_u64(), n["x_m"].as_f64(), n["y_m"].as_f64()) + else { return Err(StatusCode::INTERNAL_SERVER_ERROR); }; + if !x.is_finite() || !y.is_finite() || !(0.0..=width).contains(&x) || !(0.0..=length).contains(&y) { + return Err(StatusCode::INTERNAL_SERVER_ERROR); + } + nodes.push(ProjectedNode::Sensor { id, device_id: format!("node-{node_id}"), + position: ProjectedPosition { east_m: x, north_m: length - y, up_m: None }, modality: "wifi_csi" }); + // This is configured membership, not an observed relationship time. + edges.push(ProjectedEdge { id: edges.len() as u64 + 1, from: id, to: 1, + edge: ProjectedMembership { rel: "located_in", since_unix_ms: None } }); } } - let edges: Vec = topology["edges"].as_array().into_iter().flatten().enumerate().map(|(i, e)| json!({ - "id": i as u64 + 1, "from": e["from"], "to": e["to"], "edge": {"rel": e["rel"], "since_unix_ms": 0} - })).collect(); - let next_id = nodes.iter().filter_map(|n| n["id"].as_u64()).max().unwrap_or(0) + 1; - Ok(json!({"schema_version":2,"registration":{"origin":{"lat":0.0,"lon":0.0,"alt":0.0},"heading_deg":0.0,"scale":1.0}, - "next_id":next_id,"next_edge_id":edges.len() as u64 + 1,"nodes":nodes,"edges":edges})) + let next_id = nodes.iter().map(ProjectedNode::id).max().unwrap_or(0) + .checked_add(1).ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(ManagedEngineProjection { + schema: "ruview.worldgraph.managed-engine-projection.v1", provenance: "operator_entered", + coordinate_frame: "managed_room_local", axis_convention: "x_right_y_up_metres", status, + registration: (), next_id, next_edge_id: edges.len() as u64 + 1, nodes, edges, + }) } fn topology(envelope: &Envelope, privacy_denied: bool) -> Result { @@ -129,6 +180,81 @@ mod tests { })) } } #[test] + fn engine_projection_preserves_unknown_registration() { + let wire = Cursor::default().project_engine(&envelope(), false).unwrap(); + assert_eq!(wire["protocol_version"], 3); + assert!(wire.get("graph").is_none()); + assert_eq!(wire["projection"]["schema"], "ruview.worldgraph.managed-engine-projection.v1"); + assert!(wire["projection"].get("registration").unwrap().is_null()); + } + #[test] + fn engine_projection_preserves_unknown_vertical_and_time_values() { + let wire = Cursor::default().project_engine(&envelope(), false).unwrap(); + let projection = &wire["projection"]; + assert!(projection["nodes"][0].get("floor").unwrap().is_null()); + assert!(projection["nodes"][1]["position"].get("up_m").unwrap().is_null()); + assert!(projection["edges"][0]["edge"].get("since_unix_ms").unwrap().is_null()); + } + #[test] + fn failed_engine_projection_does_not_advance_the_shared_cursor() { + let mut cursor = Cursor::default(); + let mut malformed = envelope(); + malformed.room.as_mut().unwrap()["widthM"] = json!("invalid"); + assert!(cursor.project_engine(&malformed, false).is_err()); + assert_eq!(cursor.project_engine(&envelope(), false).unwrap()["seq"], 1); + } + #[test] + fn planar_projection_retains_valid_zero_and_room_boundaries() { + let mut room = envelope(); + room.room.as_mut().unwrap()["nodes"][0]["xM"] = json!(0.0); + room.room.as_mut().unwrap()["nodes"][0]["yM"] = json!(3.0); + let p = Cursor::default().project_engine(&room, false).unwrap(); + assert_eq!(p["projection"]["nodes"][1]["position"], json!({"east_m":0.0,"north_m":0.0,"up_m":null})); + room.room.as_mut().unwrap()["nodes"][0]["xM"] = json!(2.5); + room.room.as_mut().unwrap()["nodes"][0]["yM"] = json!(0.0); + let p = Cursor::default().project_engine(&room, false).unwrap(); + assert_eq!(p["projection"]["nodes"][1]["position"]["north_m"], 3.0); + assert_eq!(p["projection"]["nodes"][1]["position"]["east_m"], 2.5); + } + #[test] + fn invalid_planar_projection_does_not_issue_a_cursor() { + for (field, value) in [("xM", json!(-0.1)), ("xM", json!(2.6)), ("yM", json!(3.1)), ("yM", Value::Null)] { + let mut malformed = envelope(); + malformed.room.as_mut().unwrap()["nodes"][0][field] = value; + let mut cursor = Cursor::default(); + assert!(cursor.project_engine(&malformed, false).is_err()); + assert_eq!(cursor.project_engine(&envelope(), false).unwrap()["seq"], 1); + } + } + #[test] + fn projection_announces_source_status_and_withholds_private_geometry() { + let original = envelope(); + for (private, missing, status) in [(false, false, "configured"), (false, true, "not_configured"), (true, false, "privacy_denied")] { + let mut source = original.clone(); + if missing { source.room = None; source.binding_digest = None; } + let p = Cursor::default().project_engine(&source, private).unwrap(); + let p = &p["projection"]; + assert_eq!(p["status"], status); + assert_eq!(p["provenance"], "operator_entered"); + assert_eq!(p["coordinate_frame"], "managed_room_local"); + assert_eq!(p["axis_convention"], "x_right_y_up_metres"); + if private || missing { + assert_eq!(p["nodes"], json!([])); assert_eq!(p["edges"], json!([])); + assert_eq!(p["next_id"], 1); assert_eq!(p["next_edge_id"], 1); + assert!(!p.to_string().contains("Configured room")); + } + } + } + #[test] + fn projection_keeps_stable_reads_at_sequence_limit_but_refuses_changed_content() { + let mut cursor = Cursor::default(); + cursor.project_engine(&envelope(), false).unwrap(); + cursor.sequence = MAX_SAFE; + assert_eq!(cursor.project_engine(&envelope(), false).unwrap()["seq"], MAX_SAFE); + assert!(cursor.project_engine(&envelope(), true).is_err()); + assert_eq!(cursor.project_engine(&envelope(), false).unwrap()["seq"], MAX_SAFE); + } + #[test] fn configured_projection_is_planar_and_allowlisted() { let value = topology(&envelope(), false).unwrap(); assert_eq!(value["room"]["width_m"], 2.5); @@ -171,24 +297,24 @@ mod tests { fn engine_projection_matches_fixture_and_flips_y_to_north() { let mut cursor = Cursor { epoch: format!("wg-{}", "1".repeat(64)), sequence: 0, content: None }; let wire = cursor.project_engine(&envelope(), false).unwrap(); - let fixture: Value = serde_json::from_str(include_str!("../tests/fixtures/managed-worldgraph-engine-v2.json")).unwrap(); + let fixture: Value = serde_json::from_str(include_str!("../tests/fixtures/managed-worldgraph-engine-projection-v1.json")).unwrap(); assert_eq!(wire, fixture); // y_m = 2.0 down from the top of a 3.0 m room is 1.0 m north of the south wall. - assert_eq!(wire["graph"]["nodes"][1]["position"]["north_m"], 1.0); + assert_eq!(wire["projection"]["nodes"][1]["position"]["north_m"], 1.0); } #[test] fn engine_projection_is_empty_unless_configured_and_shares_the_cursor() { let mut cursor = Cursor::default(); let empty = Envelope { installation_id: "i".into(), revision: 1, binding_digest: None, room: None }; let g = cursor.project_engine(&empty, false).unwrap(); - assert_eq!((g["graph"]["nodes"].clone(), g["graph"]["edges"].clone(), g["graph"]["next_id"].clone(), g["graph"]["next_edge_id"].clone()), (json!([]), json!([]), json!(1), json!(1))); + assert_eq!((g["projection"]["nodes"].clone(), g["projection"]["edges"].clone(), g["projection"]["next_id"].clone(), g["projection"]["next_edge_id"].clone()), (json!([]), json!([]), json!(1), json!(1))); assert_eq!(g["seq"], 1); // Same content through either projection never advances seq; a changed room advances it once. assert_eq!(cursor.project(&empty, false).unwrap()["seq"], 1); assert_eq!(cursor.project_engine(&envelope(), false).unwrap()["seq"], 2); assert_eq!(cursor.project(&envelope(), false).unwrap()["seq"], 2); let denied = cursor.project_engine(&envelope(), true).unwrap(); - assert_eq!(denied["graph"]["nodes"], json!([])); + assert_eq!(denied["projection"]["nodes"], json!([])); assert_eq!(denied["seq"], 3); } #[test] @@ -229,8 +355,19 @@ mod tests { let engine_response = app.clone().oneshot(engine_request()).await.unwrap(); assert_eq!(engine_response.status(), StatusCode::OK); assert_eq!(engine_response.headers()[header::CACHE_CONTROL], "private, no-store"); let engine: Value = serde_json::from_slice(&to_bytes(engine_response.into_body(), 16_384).await.unwrap()).unwrap(); - assert_eq!((engine["protocol_version"].clone(), engine["graph"]["schema_version"].clone(), engine["seq"].clone()), (json!(1), json!(2), first["seq"].clone())); + assert_eq!((engine["protocol_version"].clone(), engine["projection"]["schema"].clone(), engine["seq"].clone()), (json!(3), json!("ruview.worldgraph.managed-engine-projection.v1"), first["seq"].clone())); assert_eq!(store.snapshot().unwrap().revision, original.revision); + let head = app.clone().oneshot(Request::builder().method("HEAD").uri("/api/v1/worldgraph/engine") + .header("authorization", "Bearer owner-test-token").body(Body::empty()).unwrap()).await.unwrap(); + assert_eq!(head.status(), StatusCode::OK); + assert_eq!(head.headers()[header::CACHE_CONTROL], "private, no-store"); + assert!(to_bytes(head.into_body(), 16_384).await.unwrap().is_empty()); + let post = app.clone().oneshot(Request::builder().method("POST").uri("/api/v1/worldgraph/engine") + .header("authorization", "Bearer owner-test-token").body(Body::empty()).unwrap()).await.unwrap(); + assert_eq!(post.status(), StatusCode::METHOD_NOT_ALLOWED); + let unchanged = app.clone().oneshot(request()).await.unwrap(); + let unchanged: Value = serde_json::from_slice(&to_bytes(unchanged.into_body(), 16_384).await.unwrap()).unwrap(); + assert_eq!(unchanged, first); state.write().await.privacy_mode = true; let response = app.oneshot(request()).await.unwrap(); let privacy: Value = serde_json::from_slice(&to_bytes(response.into_body(), 16_384).await.unwrap()).unwrap(); diff --git a/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-projection-v1.json b/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-projection-v1.json new file mode 100644 index 0000000000..151ce95474 --- /dev/null +++ b/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-projection-v1.json @@ -0,0 +1,53 @@ +{ + "protocol_version": 3, + "stream_epoch": "wg-1111111111111111111111111111111111111111111111111111111111111111", + "seq": 1, + "projection": { + "registration": null, + "next_id": 273, + "next_edge_id": 2, + "nodes": [ + { + "kind": "room", + "id": 1, + "area_id": null, + "name": "Configured room", + "bounds_enu": { + "shape": "rectangle", + "min_e": 0.0, + "min_n": 0.0, + "max_e": 2.5, + "max_n": 3.0 + }, + "floor": null + }, + { + "kind": "sensor", + "id": 272, + "device_id": "node-15", + "position": { + "east_m": 1.25, + "north_m": 1.0, + "up_m": null + }, + "modality": "wifi_csi" + } + ], + "edges": [ + { + "id": 1, + "from": 272, + "to": 1, + "edge": { + "rel": "located_in", + "since_unix_ms": null + } + } + ], + "schema": "ruview.worldgraph.managed-engine-projection.v1", + "provenance": "operator_entered", + "coordinate_frame": "managed_room_local", + "axis_convention": "x_right_y_up_metres", + "status": "configured" + } +} diff --git a/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json b/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json deleted file mode 100644 index 7e36135d6b..0000000000 --- a/v2/crates/wifi-densepose-sensing-server/tests/fixtures/managed-worldgraph-engine-v2.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "protocol_version": 1, - "stream_epoch": "wg-1111111111111111111111111111111111111111111111111111111111111111", - "seq": 1, - "graph": { - "schema_version": 2, - "registration": { "origin": { "lat": 0.0, "lon": 0.0, "alt": 0.0 }, "heading_deg": 0.0, "scale": 1.0 }, - "next_id": 273, - "next_edge_id": 2, - "nodes": [ - { - "kind": "room", "id": 1, "area_id": null, "name": "Configured room", - "bounds_enu": { "shape": "rectangle", "min_e": 0.0, "min_n": 0.0, "max_e": 2.5, "max_n": 3.0 }, - "floor": 0 - }, - { - "kind": "sensor", "id": 272, "device_id": "node-15", - "position": { "east_m": 1.25, "north_m": 1.0, "up_m": 0.0 }, - "modality": "wifi_csi" - } - ], - "edges": [ - { "id": 1, "from": 272, "to": 1, "edge": { "rel": "located_in", "since_unix_ms": 0 } } - ] - } -}