mirror of
https://github.com/ruvnet/RuView
synced 2026-08-10 20:31:42 +00:00
fix: resolve all 10 confirmed code-review findings (7-angle review, 20/20 verified)
wiflow_std: min_feature_width (default 15) replaces the keypoints->stride coupling — for_keypoints(17) now provably builds the trained [2,2,2,2] graph and pools 15->17, matching the validated Python protocol (pinned by tests); param_count() total on invalid configs; random_mask returns Result and rejects non-finite/out-of-range ratios; trainer checkpoints switched to safetensors (.pt VarStore roundtrip broken on Windows torch 2.11). ieee80211bf: SBP proxy now re-triggers instances and relays reports via Action::RelaySbpReport -> SensingFrame::SbpReport (clients consume via their existing path); missed_instances reset on success = consecutive semantics; SessionTable gains a guarded SBP entry point + unknown-id drop counter; initiator-role sessions reject inbound setup/SBP requests (RejectedNotSupported) closing the idle hijack; StartSetup/StartSbp outside Idle return InvalidStateForCommand; SBP validation unified through evaluate_setup with a 1:1 SetupStatus->SbpStatus mapping. events.rs split out to honor the 500-line cap. calibration/cli: enrollment geometry now actually reaches trained banks — both production call sites attach .with_geometry; --geometry flag on train-room and POST /enroll/geometry + train-body geometry on calibrate-serve give production a recording surface; geometry-free banks log the ADR-152 §2.1.2 note. benchmarks: corruption masks committed as ground truth (unregenerable after in-place cleaning; verified bit-identical regeneration from the pristine copy) + generate_corruption_masks.py producer; _bench_common.py dedups the 5x-copied shim/evaluate/seed/remap (post-refactor PCK@20 re-verified equal to the last digit); remote scripts get the mmap patch; tiny_edge --calib validated multiple-of-64; onnx_bench --help no longer executes (and overwrote) the export — artifact restored byte-exact. Workspace: 2,963 tests passed, 0 failed; Python proof PASS. Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
@@ -39,7 +39,8 @@ use tokio::sync::{mpsc, oneshot, RwLock};
|
||||
use tower_http::cors::CorsLayer;
|
||||
use wifi_densepose_calibration::extract::{AnchorFeature, Features};
|
||||
use wifi_densepose_calibration::{
|
||||
AnchorLabel, AnchorQualityGate, AnchorRecorder, MixtureOfSpecialists, SpecialistBank,
|
||||
AnchorLabel, AnchorQualityGate, AnchorRecorder, MixtureOfSpecialists, NodeGeometry,
|
||||
SpecialistBank,
|
||||
};
|
||||
use wifi_densepose_core::types::CsiFrame;
|
||||
use wifi_densepose_signal::{BaselineCalibration, CalibrationRecorder};
|
||||
@@ -207,6 +208,9 @@ struct RoomEnroll {
|
||||
baseline_id: String,
|
||||
fs_hz: f32,
|
||||
anchors: Vec<AnchorFeature>,
|
||||
/// Transceiver geometry recorded via `POST /enroll/geometry` (ADR-152
|
||||
/// §2.1.1); latest recording wins. Snapshotted into the bank at train time.
|
||||
geometry: Vec<NodeGeometry>,
|
||||
}
|
||||
|
||||
/// Result of capturing one anchor (`POST /enroll/anchor`).
|
||||
@@ -299,6 +303,7 @@ fn build_router(state: ApiState) -> Router {
|
||||
.route("/api/v1/room/state", get(room_state))
|
||||
.route("/api/v1/room/train", post(train_room))
|
||||
.route("/api/v1/enroll/anchor", post(enroll_anchor))
|
||||
.route("/api/v1/enroll/geometry", post(enroll_geometry))
|
||||
.route("/api/v1/enroll/status", get(enroll_status))
|
||||
.layer(CorsLayer::permissive())
|
||||
.with_state(state)
|
||||
@@ -670,8 +675,9 @@ async fn descriptor() -> impl IntoResponse {
|
||||
"GET /api/v1/calibration/result": "last finalized baseline summary",
|
||||
"GET /api/v1/calibration/baselines": "list persisted baseline files",
|
||||
"GET /api/v1/room/state?bank=<name>": "live mixture-of-specialists RoomState over the CSI window",
|
||||
"POST /api/v1/room/train": "{ room_id, baseline_id, anchors[]? } → train + persist a specialist bank (anchors[] optional if enrolled in-server)",
|
||||
"POST /api/v1/room/train": "{ room_id, baseline_id, anchors[]?, geometry[]? } → train + persist a specialist bank (anchors[]/geometry[] optional if enrolled in-server)",
|
||||
"POST /api/v1/enroll/anchor": "{ room_id, baseline, label, duration_s? } → capture one guided anchor (blocks for the capture)",
|
||||
"POST /api/v1/enroll/geometry": "{ room_id, geometry: [NodeGeometry…] } → record transceiver geometry for the room (ADR-152 §2.1.1; latest wins)",
|
||||
"GET /api/v1/enroll/status?room=<id>": "enrollment progress (accepted anchors, next, complete)"
|
||||
}
|
||||
}))
|
||||
@@ -740,11 +746,18 @@ struct TrainRequest {
|
||||
baseline_id: String,
|
||||
#[serde(default)]
|
||||
anchors: Vec<AnchorFeature>,
|
||||
/// Optional transceiver geometry (ADR-152 §2.1.1). Falls back to the
|
||||
/// geometry recorded in-server via `POST /enroll/geometry`; absent both,
|
||||
/// the bank trains geometry-free (valid, but no geometry conditioning).
|
||||
#[serde(default)]
|
||||
geometry: Vec<NodeGeometry>,
|
||||
}
|
||||
|
||||
/// Train a per-room specialist bank and persist it as `<output_dir>/<room_id>.json`
|
||||
/// (the name `room-state` reads back). Uses the posted `anchors` if present, else
|
||||
/// falls back to the in-server enrollment accumulated via `POST /enroll/anchor`.
|
||||
/// The enrollment's transceiver-geometry snapshot (posted `geometry` or the
|
||||
/// `POST /enroll/geometry` record) is threaded into the bank (ADR-152 §2.1.1).
|
||||
async fn train_room(State(st): State<ApiState>, Json(req): Json<TrainRequest>) -> impl IntoResponse {
|
||||
let (anchors, baseline_id) = if !req.anchors.is_empty() {
|
||||
(req.anchors.clone(), req.baseline_id.clone())
|
||||
@@ -756,11 +769,25 @@ async fn train_room(State(st): State<ApiState>, Json(req): Json<TrainRequest>) -
|
||||
}
|
||||
}
|
||||
};
|
||||
let geometry = if !req.geometry.is_empty() {
|
||||
req.geometry.clone()
|
||||
} else {
|
||||
st.enroll.read().await.get(&req.room_id).map(|re| re.geometry.clone()).unwrap_or_default()
|
||||
};
|
||||
let at = (unix_ms() / 1000) as i64;
|
||||
let bank = match SpecialistBank::train(&req.room_id, &baseline_id, &anchors, at) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": format!("training failed: {e}")}))).into_response(),
|
||||
};
|
||||
let bank = if geometry.is_empty() {
|
||||
eprintln!(
|
||||
"[calibrate-serve] no transceiver geometry recorded for room '{}' — bank will not support geometry conditioning (ADR-152 §2.1.2)",
|
||||
req.room_id
|
||||
);
|
||||
bank
|
||||
} else {
|
||||
bank.with_geometry(geometry)
|
||||
};
|
||||
let name = sanitize_room_id(&req.room_id);
|
||||
let dir = { st.status.read().await.output_dir.clone() };
|
||||
let path = format!("{dir}/{name}.json");
|
||||
@@ -777,10 +804,37 @@ async fn train_room(State(st): State<ApiState>, Json(req): Json<TrainRequest>) -
|
||||
"bank": name, // pass as ?bank=<name> to /room/state
|
||||
"anchor_count": bank.anchor_count,
|
||||
"specialists": kinds,
|
||||
"geometry_nodes": bank.geometry.len(),
|
||||
"path": path,
|
||||
}))).into_response()
|
||||
}
|
||||
|
||||
/// Body for `POST /api/v1/enroll/geometry`.
|
||||
#[derive(Deserialize)]
|
||||
struct EnrollGeometryBody {
|
||||
room_id: String,
|
||||
/// Per-node transceiver geometry records (ADR-152 §2.1.1).
|
||||
geometry: Vec<NodeGeometry>,
|
||||
}
|
||||
|
||||
/// Record the room's transceiver geometry (ADR-152 §2.1.1) into the in-server
|
||||
/// enrollment; the next `POST /room/train` snapshots it into the bank. A later
|
||||
/// POST supersedes an earlier one (latest wins), mirroring
|
||||
/// `EnrollmentSession::record_geometry`.
|
||||
async fn enroll_geometry(State(st): State<ApiState>, Json(b): Json<EnrollGeometryBody>) -> impl IntoResponse {
|
||||
if b.geometry.is_empty() {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":"geometry must be a non-empty array of NodeGeometry records"}))).into_response();
|
||||
}
|
||||
let nodes = b.geometry.len();
|
||||
{
|
||||
let mut map = st.enroll.write().await;
|
||||
let re = map.entry(b.room_id.clone()).or_insert_with(RoomEnroll::default);
|
||||
re.geometry = b.geometry;
|
||||
}
|
||||
eprintln!("[calibrate-serve] enroll geometry room={} nodes={nodes}", b.room_id);
|
||||
(StatusCode::OK, Json(serde_json::json!({"room_id": b.room_id, "geometry_nodes": nodes}))).into_response()
|
||||
}
|
||||
|
||||
/// Body for `POST /api/v1/enroll/anchor`.
|
||||
#[derive(Deserialize)]
|
||||
struct EnrollAnchorBody {
|
||||
@@ -1086,6 +1140,59 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// ADR-152 §2.1.1: geometry threads into the trained bank through both API
|
||||
/// paths — inline in the train request, or recorded via /enroll/geometry —
|
||||
/// and a geometry-free train still produces a valid (unconditioned) bank.
|
||||
#[tokio::test]
|
||||
async fn train_threads_geometry_into_bank() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app = build_router(test_state(dir.path().to_str().unwrap()));
|
||||
let anchors = r#"[
|
||||
{"room_id":"g","label":"empty","features":{"mean":1.0,"variance":1.0,"motion":0.1,"breathing_score":0.0,"breathing_hz":0.0,"heart_score":0.0,"heart_hz":0.0}},
|
||||
{"room_id":"g","label":"stand_still","features":{"mean":1.0,"variance":10.0,"motion":0.2,"breathing_score":0.0,"breathing_hz":0.0,"heart_score":0.0,"heart_hz":0.0}}
|
||||
]"#;
|
||||
let load_bank = |name: &str| {
|
||||
let raw = std::fs::read_to_string(dir.path().join(format!("{name}.json"))).unwrap();
|
||||
SpecialistBank::from_json(&raw).unwrap()
|
||||
};
|
||||
|
||||
// (1) geometry inline in the train request.
|
||||
let body = format!(
|
||||
r#"{{"room_id":"g1","baseline_id":"b","anchors":{anchors},
|
||||
"geometry":[{{"node_id":1,"position":{{"x_m":0.0,"y_m":0.0,"z_m":1.0}},"method":"tape-measure"}},{{"node_id":2}}]}}"#
|
||||
);
|
||||
assert_eq!(req(app.clone(), "POST", "/api/v1/room/train", Some(&body)).await, StatusCode::OK);
|
||||
let bank = load_bank("g1");
|
||||
assert_eq!(bank.geometry.len(), 2);
|
||||
assert_eq!(bank.geometry[0].method, "tape-measure");
|
||||
assert_eq!(bank.geometry[1].node_id, 2);
|
||||
|
||||
// (2) geometry recorded via /enroll/geometry; train body omits it.
|
||||
assert_eq!(
|
||||
req(app.clone(), "POST", "/api/v1/enroll/geometry",
|
||||
Some(r#"{"room_id":"g2","geometry":[{"node_id":7,"method":"floor-plan"}]}"#)).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
let body2 = format!(r#"{{"room_id":"g2","baseline_id":"b","anchors":{anchors}}}"#);
|
||||
assert_eq!(req(app.clone(), "POST", "/api/v1/room/train", Some(&body2)).await, StatusCode::OK);
|
||||
let bank2 = load_bank("g2");
|
||||
assert_eq!(bank2.geometry.len(), 1);
|
||||
assert_eq!(bank2.geometry[0].node_id, 7);
|
||||
|
||||
// (3) no geometry anywhere → valid geometry-free bank (note logged).
|
||||
let body3 = format!(r#"{{"room_id":"g3","baseline_id":"b","anchors":{anchors}}}"#);
|
||||
assert_eq!(req(app.clone(), "POST", "/api/v1/room/train", Some(&body3)).await, StatusCode::OK);
|
||||
let bank3 = load_bank("g3");
|
||||
assert!(bank3.geometry.is_empty());
|
||||
assert!(bank3.presence.is_some(), "bank still trains without geometry");
|
||||
|
||||
// (4) empty geometry array is rejected.
|
||||
assert_eq!(
|
||||
req(app, "POST", "/api/v1/enroll/geometry", Some(r#"{"room_id":"g4","geometry":[]}"#)).await,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enroll_status_empty_and_bad_label() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::UdpSocket;
|
||||
use wifi_densepose_calibration::{
|
||||
Anchor, AnchorLabel, AnchorQualityGate, AnchorRecorder, EnrollmentEvent, EnrollmentSession,
|
||||
MixtureOfSpecialists, MultiNodeMixture, SpecialistBank,
|
||||
MixtureOfSpecialists, MultiNodeMixture, NodeGeometry, SpecialistBank,
|
||||
};
|
||||
use wifi_densepose_calibration::extract::{AnchorFeature, Features};
|
||||
use wifi_densepose_core::types::CsiFrame;
|
||||
@@ -226,20 +226,50 @@ pub struct TrainRoomArgs {
|
||||
/// Output specialist-bank file.
|
||||
#[arg(long, default_value = "./room-bank.json")]
|
||||
pub output: String,
|
||||
/// Optional transceiver-geometry file: a JSON array of `NodeGeometry`
|
||||
/// records (ADR-152 §2.1.1). Recorded into the enrollment session before
|
||||
/// training so the bank carries the layout it was trained under.
|
||||
#[arg(long)]
|
||||
pub geometry: Option<String>,
|
||||
}
|
||||
|
||||
/// Execute `train-room`.
|
||||
///
|
||||
/// If the enrollment session carries a transceiver-geometry snapshot (recorded
|
||||
/// at enroll time or supplied here via `--geometry`), it is threaded into the
|
||||
/// bank (ADR-152 §2.1.1); a geometry-free enrollment still trains a valid bank.
|
||||
pub async fn train_room(args: TrainRoomArgs) -> Result<()> {
|
||||
let raw = std::fs::read_to_string(&args.enrollment)
|
||||
.map_err(|e| anyhow::anyhow!("cannot read {}: {e} — run `enroll` first", args.enrollment))?;
|
||||
let data: EnrollmentData =
|
||||
let mut data: EnrollmentData =
|
||||
serde_json::from_str(&raw).map_err(|e| anyhow::anyhow!("invalid enrollment: {e}"))?;
|
||||
if data.anchors.is_empty() {
|
||||
bail!("no accepted anchors in {} — re-run enroll", args.enrollment);
|
||||
}
|
||||
|
||||
let bank = SpecialistBank::train(&data.room_id, &data.baseline_id, &data.anchors, now_unix())
|
||||
if let Some(path) = &args.geometry {
|
||||
let graw = std::fs::read_to_string(path)
|
||||
.map_err(|e| anyhow::anyhow!("cannot read geometry {path}: {e}"))?;
|
||||
let geometry: Vec<NodeGeometry> = serde_json::from_str(&graw).map_err(|e| {
|
||||
anyhow::anyhow!("invalid geometry {path}: {e} (expected a JSON array of NodeGeometry records)")
|
||||
})?;
|
||||
data.session.record_geometry(geometry, now_unix());
|
||||
}
|
||||
|
||||
let mut bank = SpecialistBank::train(&data.room_id, &data.baseline_id, &data.anchors, now_unix())
|
||||
.map_err(|e| anyhow::anyhow!("training failed: {e}"))?;
|
||||
match data.session.geometry() {
|
||||
Some(g) if !g.is_empty() => {
|
||||
bank = bank.with_geometry(g.to_vec());
|
||||
eprintln!(
|
||||
"[train-room] geometry: {} node(s) snapshotted into the bank (ADR-152 §2.1.1)",
|
||||
bank.geometry.len()
|
||||
);
|
||||
}
|
||||
_ => eprintln!(
|
||||
"[train-room] no transceiver geometry recorded — bank will not support geometry conditioning (ADR-152 §2.1.2)"
|
||||
),
|
||||
}
|
||||
std::fs::write(&args.output, bank.to_json().map_err(|e| anyhow::anyhow!("{e}"))?)
|
||||
.map_err(|e| anyhow::anyhow!("cannot write {}: {e}", args.output))?;
|
||||
|
||||
@@ -456,3 +486,141 @@ async fn room_watch_multi(args: RoomWatchArgs) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn feature(label: AnchorLabel, variance: f32, motion: f32) -> AnchorFeature {
|
||||
AnchorFeature {
|
||||
room_id: "t".into(),
|
||||
label,
|
||||
features: Features {
|
||||
mean: 1.0,
|
||||
variance,
|
||||
motion,
|
||||
breathing_score: 0.0,
|
||||
breathing_hz: 0.0,
|
||||
heart_score: 0.0,
|
||||
heart_hz: 0.0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a minimal valid enrollment file (two anchors, no geometry event).
|
||||
fn write_enrollment(dir: &std::path::Path) -> String {
|
||||
let data = EnrollmentData {
|
||||
room_id: "t".into(),
|
||||
baseline_id: "base-1".into(),
|
||||
fs_hz: 15.0,
|
||||
anchors: vec![
|
||||
feature(AnchorLabel::Empty, 1.0, 0.1),
|
||||
feature(AnchorLabel::StandStill, 10.0, 0.2),
|
||||
],
|
||||
session: EnrollmentSession::new("t", "base-1", 1000),
|
||||
};
|
||||
let path = dir.join("enrollment.json");
|
||||
std::fs::write(&path, serde_json::to_string(&data).unwrap()).unwrap();
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn trained_bank(out: &std::path::Path) -> SpecialistBank {
|
||||
SpecialistBank::from_json(&std::fs::read_to_string(out).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// ADR-152 §2.1.1: `--geometry` records into the session and the bank
|
||||
/// snapshots it — enrollment geometry reaches the trained bank.
|
||||
#[tokio::test]
|
||||
async fn train_room_threads_geometry_when_provided() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let enrollment = write_enrollment(dir.path());
|
||||
let geometry = vec![
|
||||
NodeGeometry::new(1, "tape-measure").with_position(0.0, 0.0, 1.0),
|
||||
NodeGeometry::unknown(2),
|
||||
];
|
||||
let gpath = dir.path().join("geometry.json");
|
||||
std::fs::write(&gpath, serde_json::to_string(&geometry).unwrap()).unwrap();
|
||||
let out = dir.path().join("bank.json");
|
||||
|
||||
train_room(TrainRoomArgs {
|
||||
enrollment,
|
||||
output: out.to_string_lossy().into_owned(),
|
||||
geometry: Some(gpath.to_string_lossy().into_owned()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(trained_bank(&out).geometry, geometry);
|
||||
}
|
||||
|
||||
/// A geometry-free enrollment still trains a valid bank (optional by
|
||||
/// design) — it just carries no snapshot.
|
||||
#[tokio::test]
|
||||
async fn train_room_without_geometry_yields_geometry_free_bank() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let enrollment = write_enrollment(dir.path());
|
||||
let out = dir.path().join("bank.json");
|
||||
|
||||
train_room(TrainRoomArgs {
|
||||
enrollment,
|
||||
output: out.to_string_lossy().into_owned(),
|
||||
geometry: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let bank = trained_bank(&out);
|
||||
assert!(bank.geometry.is_empty());
|
||||
assert!(bank.presence.is_some(), "bank still trains without geometry");
|
||||
}
|
||||
|
||||
/// Geometry recorded at enroll time (in the session event log) is picked up
|
||||
/// without the `--geometry` flag.
|
||||
#[tokio::test]
|
||||
async fn train_room_uses_session_geometry() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let geometry = vec![NodeGeometry::new(3, "floor-plan").with_position(1.0, 2.0, 1.5)];
|
||||
let mut session = EnrollmentSession::new("t", "base-1", 1000);
|
||||
session.record_geometry(geometry.clone(), 1000);
|
||||
let data = EnrollmentData {
|
||||
room_id: "t".into(),
|
||||
baseline_id: "base-1".into(),
|
||||
fs_hz: 15.0,
|
||||
anchors: vec![
|
||||
feature(AnchorLabel::Empty, 1.0, 0.1),
|
||||
feature(AnchorLabel::StandStill, 10.0, 0.2),
|
||||
],
|
||||
session,
|
||||
};
|
||||
let epath = dir.path().join("enrollment.json");
|
||||
std::fs::write(&epath, serde_json::to_string(&data).unwrap()).unwrap();
|
||||
let out = dir.path().join("bank.json");
|
||||
|
||||
train_room(TrainRoomArgs {
|
||||
enrollment: epath.to_string_lossy().into_owned(),
|
||||
output: out.to_string_lossy().into_owned(),
|
||||
geometry: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(trained_bank(&out).geometry, geometry);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn train_room_rejects_invalid_geometry_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let enrollment = write_enrollment(dir.path());
|
||||
let gpath = dir.path().join("geometry.json");
|
||||
std::fs::write(&gpath, r#"{"not":"an array"}"#).unwrap();
|
||||
|
||||
let err = train_room(TrainRoomArgs {
|
||||
enrollment,
|
||||
output: dir.path().join("bank.json").to_string_lossy().into_owned(),
|
||||
geometry: Some(gpath.to_string_lossy().into_owned()),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("invalid geometry"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user