diff --git a/docs/adr/ADR-420-managed-source-aware-room-learner.md b/docs/adr/ADR-420-managed-source-aware-room-learner.md index 162eae24f5..ef7dbd6f05 100644 --- a/docs/adr/ADR-420-managed-source-aware-room-learner.md +++ b/docs/adr/ADR-420-managed-source-aware-room-learner.md @@ -428,3 +428,52 @@ replaced. Existing recovery descriptor/checkpoint versions and expiry semantics unchanged. This is proposed source work, not protection of a currently running older helper: installing it would require stopping that helper, so live volatile cohorts must not be sacrificed to obtain this capability. + + +## November 11, 2026: proposed variable-source receiver profile + +Dragan requested that the room learner retain every configured source rather than +requiring exactly three. The local candidate adds the explicitly versioned +`native-2s-variable-source-56bin-receiver20-operator-eight-step-v2` profile. Earlier +three-source profiles, schedule hashes, recovery data and key derivations remain +unchanged. This amendment describes an engineering candidate, not physical +qualification or a change to the default operating detector. + +The candidate supports 2–8 source-bound views of 56 canonical features (C5 keeps +its 53 native IQ positions before the existing projection) and retains the existing +eight operator episodes: 64 training windows and 16 reserved check windows. +Resource preflight remains below two million numeric values and a 64 MiB +serialized-checkpoint estimate. Every source participates in every accepted +window; adding/removing a source changes context/model identity and requires a +new run. No source is silently removed or padded. Recovery has a separate +account/installation-bound encryption purpose and directory; pending older +recovery stays discoverable under its original profile. + +The receiver policy is explicitly distinct from a sensor measurement clock. +The November 10 executed metadata-only C5 read-loop sample reported means of +20.42–20.62 packets/s, minimum observed intervals of 7.7–20.8 microseconds and +maximum gaps of 131–137 milliseconds. It did not distinguish radio delivery +from host scheduling, establish source measurement time, or qualify sensing. +An instantaneous inverse arrival interval therefore cannot establish a +20 Hz sensor sample rate. + +`Arrival18To22Burst200MsV1` retains every admitted retained-window frame identity +and receiver timestamp with its existing canonical feature values; the native-to-feature +projection is unchanged. It bounds observed window and whole-period rates +to 18–22 packets/s. Whole-period rate is checked only at the completed episode +frontier/seal, summing each positive resumed part’s packet intervals and receiver +span while excluding paused gaps; partial durable prefixes keep structural, +sequence, gap and retained-window checks without an aggregate-rate veto. It bounds +maximum gaps to 200 ms, and requires strictly increasing receiver timestamps. +Native windows retain a two-second target, at most 2.2 seconds observed span, +200 ms first-arrival/skew bounds and at most 52 rows per source. There is no +synthetic clock, temporal resampling to hide a gap, dropping within admitted retained windows, or source-clock / +phase / accuracy claim. Excess density, long gaps, missing sources, duplicates +and changed input/context still reject. Older interval-strict profiles keep +their exact original rules. + +Synthetic checks exercise source-count bounds, bursty four-C5 native input, +rejected gaps/floods, whole four-source training with reserved checks excluded, +model export/import identity, durable genesis and recovery isolation. Physical +four-C5 capture, independent checks, qualification, explicit selection and Room +Save remain required before describing this installation as qualified. diff --git a/docs/validation/2026-11-10-c5-native-lltf8-contract.md b/docs/validation/2026-11-10-c5-native-lltf8-contract.md new file mode 100644 index 0000000000..18d894214c --- /dev/null +++ b/docs/validation/2026-11-10-c5-native-lltf8-contract.md @@ -0,0 +1,118 @@ +# Managed C5 L-LTF8 format contract v1 + +This software contract does not qualify hardware, sensing accuracy or phase. +The existing C5 producer zero-initializes `lltf_bit_mode`; ESP-IDF6.0.2 defines +that as12-bit components. An old106-byte callback is therefore not evidence +of53 signed-int8 complex samples. Bare53-slot ADR-018 input stays rejected. + +Primary references: [SDKv6.0.2 CSI fields](https://github.com/espressif/esp-idf/blob/v6.0.2/components/esp_wifi/include/esp_wifi_he_types.h), +[SDKvendor features](https://github.com/espressif/esp-idf/blob/v6.0.2/docs/en/api-guides/wifi-driver/wifi-vendor-features.rst), +and [Espressif packing clarification](https://github.com/espressif/esp-idf/issues/18982#issuecomment-5420118269). + +## Producer claim and exact wire extent + +The separate local producer opts into8-bit legacy/forcedL-LTF only and checks +actual CSI-format fields/zero scaling through SDK configuration readback. +STA bandwidth is explicitly set and read back as20MHz; it is a configured +interface/acquisition constraint, not a measurement of full PPDU occupied +bandwidth. Only original non-HT OFDMBB1 (11g/11a), secondary-none, +valid-estimate and106-byte callbacks carry this format claim. Other +metadata is withheld and reported without raw samples. The producer and its +physical callback packing/shape must be validated on one board before +managed capture is attempted; a software test or marker alone is not that +validation. The claim does not raise the existing provenance/trust grade. + +A valid datagram has20bytesADR-018 header +106bytesdeclaredIQ +16bytesexact +suffix. The suffix fields are: ASCII C5L8; version1; componentbits8; +SDK-documented imaginary/real byte-order ID1; LLTF53tone-order ID1; +matched-format-readback1; originalBB1; originalsecondary0; STAbandwidth +readback20MHz; originalestimate-valid1; first-word-invalid0/1; +originalbyte-count106little-endian. Unsupported version, order, packing, +readback, PHY, length, flag or trailing byte is refused before readiness. +The first-word flag must agree with ADR-018 bit5 and with the actual zeroed +four-byte prefix. No HE-invalid flag reinterpretation occurs; HE/HT/VHT and +unproven variants are outside this new profile. Existing64/256 paths retain +their old grid IDs, complex-component convention and magnitude mathematics. + +Newv1 only admits IEEE20MHz5GHz primary channels36–64 (step4),100–144 +(step4, including112),149–177 (step4). This is a bounded format/channel set, +not physical qualification of every channel or regulatory authorization. +The local firmware driver/AP remains responsible for lawful association. +2.4/6GHz and off-grid5MHz values are not silently broadened into this profile. + +## Native representation and fixed derived features + +Original received IQ bytes are retained privately/losslessly; native shape +remains[1,53,1]. The explicit SDK-documented signed-int8 imaginary/real +interpretation uses complexre=byte1,im=byte0 for this new format only. +Raw phase remains unqualified and is not consumed. Native carrier indices +remain `[0..26,-26..-1]`; they are stored explicitly, not represented as53 +uniform FFT bins or padded into64. DC slot0 is always invalid; SDK's invalid +first four bytes additionally invalidate slot1. No slots are deleted or +renumbered, and sanitized wire bytes stay as received. + +The derived amplitude-only feature recipe is intentionally conservative: +exclude native positions0and1 on every packet, then pass those51magnitudes +in original SDK order through the existing length-only56feature resampler. +The discontinuity from+26to-26 is not a uniform physical-frequency axis. +This interpolation creates features, not additional measured carriers; +there is no gain/DC normalization or invented padded IQ. Its separate ID is +`ant1-bins53-ppdu0-c5lltf8-keep53-drop2-linear-v3`. Existing64/256v2IDs and +fixtures remain unchanged. The validated claim binds the original header's +node, sequence and frequency to the canonicalizer input. Per-source cache +keys bind format, native grid, PPDU, frequency and bandwidth; normal existing +freshness/cadence/room/model/selection gates remain authoritative. + +## Read-only rejection diagnostics + +Only an explicit read-only `include_native_diagnostics=1` query on the +existing room-learner status adds `native_source_diagnostics` (with or +without its existing temporal schema query). Default status, `=0` and mutation +ACKs omit that key entirely, preserving older clients' exact-key schemas. +Values other than0/1 are refused; authorization and mutation semantics are +unchanged. A newer client may fall back once to ordinary status on an older +helper's unsupported-query400/422, never on authentication or parse failure. +The optional field is +for the last rejected packet, never a source-ready or admission verdict. +Storage is bounded by256u8nodeIDs; replies cap32fresh records, prioritize +selected sources, expose total/truncation and expire by receiver-monotonic +age after5seconds. Reasons are static whitelist strings; no IQ, amplitudes, +absolute timestamps or credentials are stored or returned. A rare bad +packet cannot evict/invalidate an otherwise ready cohort, while normal +exact source/grid/frequency withdrawal rules are unchanged. Old app readers +may ignore this new optional status field. + +## Verification boundary + +Synthetic regressions cover exact decoder metadata mutants, lossless native +bytes/order/masks, no unclaimed53admission, original64/256 behavior, +three independent20/21/22sources through actual UDP parser and ingress, +malformed/unsupportedPHY refusal, changedfrequency/grid/model bindings, +and bounded diagnostic expiry/privacy. Physical source/callback and the +separate producer commit/artifact receipts must be recorded independently. +No source changes are applied to the frozen server#2513b8review branch. + +## Existing ADR-018 advisory sync metadata + +The first metadata-only Node23 wire probe observed290 packets, all142bytes, +53slots, PPDU0,5240MHz, with the exact C5L8/v1 suffix and header flag0x10. +The strict8930 decoder rejected this known flag. The producer serializer sets +bit4 when its ESP-NOW or802.15.4 cross-node synchronization helper reports valid; +the historical host field name is `ieee802154_sync_valid`. This bit does not +select IQ packing, bandwidth, sanitation or calibrated timing. + +The corrected C5 decoder accepts exactly flags0x00/0x10/0x20/0x30, with0x20 +still required to agree with suffix sanitation and zeroed prefix bytes. All +other flag bits reject. The complete parsed flag metadata is bound to the +validated token and retained in the private canonical packet. Flipping sync +between the validated header and canonicalization input rejects. The bit does +not change grid/projection/IQ/masks, receiver-only clock, unknown source sample +rate, gain/phase qualification, capture authority or provenance. + +`tests/fixtures/c5-node23-wire-metadata-20261110.json` contains the actual +metadata-only receipt and no IQ. The corresponding native test combines those +observed header/suffix facts with explicitly **synthetic IQ**, not a captured +wire replay. Exhaustive256-byte flag controls and real ingress/readiness +regressions are synthetic contract evidence; physical admission requires a +new wire probe against the corrected helper. Legacy64/256 math and IDs stay +unchanged. No firmware change is required for this existing metadata bit. diff --git a/scripts/ci/temporal_test_profiles.py b/scripts/ci/temporal_test_profiles.py index 285c158cca..4486c105d8 100644 --- a/scripts/ci/temporal_test_profiles.py +++ b/scripts/ci/temporal_test_profiles.py @@ -7,6 +7,7 @@ C2 = PREFIX + 'tests::c2_all_seven_train_phases_use_actual_async_runtime_and_durable_seals_without_fit' # Exact C4C declaration; the author must verify this name in the actual Rust registry. C4C = PREFIX + 'public_workflow::acceptance::c4c_default48_public_operator_workflow_native128_and_cold_selection' +VARIABLE_RETRY = PREFIX + 'tests::variable_retry_after_actual_window_cadence_failure_keeps_sixteen_windows_and_seal' BUDGET = [PREFIX + 'tests::legacy_329_actual_runtime_saturation_retires_and_explicit_fresh_train_chains_343', PREFIX + 'tests::fresh_343_actual_runtime_all_128_gaps_seven_terminal_pauses_and_retirement_fit_budget'] # This initial policy is populated below from reviewed source call sites. C3 = ['room_learner::lifecycle::temporal_control::fit_control::tests::c3_actual_native_train_fit_and_same_store_cold_report_keep_whole_model_diagnostic', @@ -44,6 +45,7 @@ def policy(root): if not c_marker.is_file(): raise ValueError('C4C acceptance source marker is required; missing source is not coverage') components += [('C4C', c_marker, [C4C], [(C4C, True, 1)])] + components += [('variableRetry', source / 'lifecycle_temporal_tests.rs', [VARIABLE_RETRY], [(VARIABLE_RETRY, True, 1)])] active = [item for item in components if item[1].is_file()] if not active or active[0][0] != 'C2': raise ValueError('C2 classification/source must exist; zero selected tests is not coverage') @@ -147,6 +149,29 @@ def compile_binary(root, release): raise ValueError('Cargo lib-test compilation failed with exit ' + str(result.returncode)) return validate_cargo_artifacts(root, metadata, artifacts, release) +def execute_batch(command, cwd, log_path): + """Forward progress immediately and keep the same output for count checks.""" + with log_path.open('w', encoding='utf-8') as log: + process = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, bufsize=1) + try: + for line in process.stdout: + log.write(line) + log.flush() + sys.stdout.write(line) + sys.stdout.flush() + return process.wait() + finally: + # A failed log/console sink must not strand the verified child. + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + process.stdout.close() + def main(): parser = argparse.ArgumentParser() parser.add_argument('mode', choices=['debug-check', 'release-run']) @@ -182,12 +207,11 @@ def main(): for index, batch in enumerate(batches): verify_selected_executable(selected, binary_sha256) command = [str(binary), batch['selector'], '--nocapture', '--test-threads=1'] + (['--exact'] if batch['exact'] else []) - result = subprocess.run(command, cwd=root/'v2', capture_output=True, text=True) - output = result.stdout + result.stderr - (args.evidence_dir / f'{index}-{batch["component"]}.log').write_text(output) - print(output, flush=True) + log_path = args.evidence_dir / f'{index}-{batch["component"]}.log' + returncode = execute_batch(command, root/'v2', log_path) + output = log_path.read_text(encoding='utf-8') counts = re.findall(r'^test result: ok\. (\d+) passed; (\d+) failed; (\d+) ignored;', output, re.M) - if result.returncode or not counts or tuple(map(int, counts[-1])) != (len(batch['names']), 0, 0): + if returncode or not counts or tuple(map(int, counts[-1])) != (len(batch['names']), 0, 0): raise ValueError('Release batch failed or nonzero/exact-count verification failed: ' + batch['selector']) batch['passed'] = len(batch['names']) receipt['status'] = 'passed' diff --git a/scripts/ci/test_temporal_test_profiles.py b/scripts/ci/test_temporal_test_profiles.py index 5290aba5ac..795a24846e 100644 --- a/scripts/ci/test_temporal_test_profiles.py +++ b/scripts/ci/test_temporal_test_profiles.py @@ -159,8 +159,8 @@ def test_missing_c4c_source_marker_cannot_silently_drop_release_batch(self): profiles.policy(root) def test_current_policy_registers_exact_c4c_and_preserves_existing_components(self): components = profiles.policy(pathlib.Path(__file__).resolve().parents[2]) - self.assertEqual([c[0] for c in components], ['C2', 'C1', 'C3', 'C4', 'budget343', 'C4B', 'C4C']) - current = components[-1] + self.assertEqual([c[0] for c in components], ['C2', 'C1', 'C3', 'C4', 'budget343', 'C4B', 'C4C', 'variableRetry']) + current = next(c for c in components if c[0] == 'C4C') self.assertEqual(current[1].name, 'lifecycle_temporal_public_acceptance_tests.rs') self.assertEqual(current[2:], ([profiles.C4C], [(profiles.C4C, True, 1)])) self.assertEqual(components[0][3], [(profiles.C2, True, 1)]) @@ -188,4 +188,107 @@ def test_actual_policy_carries_operator_case_in_cached_c4_batch(self): c4=next(c for c in profiles.policy(pathlib.Path(__file__).resolve().parents[2]) if c[0]=='C4') self.assertIn(profiles.OPERATOR8,c4[2]);self.assertEqual(c4[3],[(profiles.PREFIX+'full_run_tests::',False,9)]) +class VariableRetryClassificationTests(unittest.TestCase): + def component(self): + root = pathlib.Path(__file__).resolve().parents[2] + return [next(c for c in profiles.policy(root) if c[0] == 'variableRetry')] + + def test_current_policy_requires_exact_native_retry_case(self): + c = self.component()[0] + self.assertEqual(c[1].name, 'lifecycle_temporal_tests.rs') + self.assertEqual(c[2:], ([profiles.VARIABLE_RETRY], [(profiles.VARIABLE_RETRY, True, 1)])) + self.assertIn('fn variable_retry_after_actual_window_cadence_failure_keeps_sixteen_windows_and_seal()', c[1].read_text()) + + def test_debug_keeps_the_case_registered_and_transparently_ignored(self): + result = profiles.validate(self.component(), {profiles.VARIABLE_RETRY}, {profiles.VARIABLE_RETRY}, 'debug-check') + self.assertEqual(result[0]['names'], [profiles.VARIABLE_RETRY]) + + def test_debug_cannot_run_the_native_persistence_case_unclassified(self): + with self.assertRaises(ValueError): + profiles.validate(self.component(), {profiles.VARIABLE_RETRY}, set(), 'debug-check') + + def test_release_requires_one_active_case_and_does_not_sweep_siblings(self): + sibling = profiles.VARIABLE_RETRY + '_manual_performance' + result = profiles.validate(self.component(), {profiles.VARIABLE_RETRY, sibling}, {sibling}, 'release-run') + self.assertEqual(result, [{'component': 'variableRetry', 'selector': profiles.VARIABLE_RETRY, 'exact': True, 'names': [profiles.VARIABLE_RETRY]}]) + + def test_missing_or_lookalike_case_cannot_satisfy_release_coverage(self): + for registered in [set(), {profiles.VARIABLE_RETRY + '_lookalike'}]: + with self.assertRaises(ValueError): + profiles.validate(self.component(), registered, set(), 'release-run') + + def test_ignored_release_case_cannot_be_counted_as_passed(self): + with self.assertRaises(ValueError): + profiles.validate(self.component(), {profiles.VARIABLE_RETRY}, {profiles.VARIABLE_RETRY}, 'release-run') + + def test_wrong_module_cannot_substitute_the_same_leaf(self): + wrong = profiles.VARIABLE_RETRY.replace('tests::', 'wrong_module::') + with self.assertRaises(ValueError): + profiles.validate(self.component(), {wrong}, set(), 'release-run') + + +class LiveBatchEvidenceTests(unittest.TestCase): + def test_stdout_and_stderr_are_retained_and_nonzero_exit_is_not_hidden(self): + import contextlib, io, sys, tempfile + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + log = root / 'batch.log' + console = io.StringIO() + command = [sys.executable, '-u', '-c', + 'import sys; print("stdout-progress"); print("stderr-progress", file=sys.stderr); sys.exit(7)'] + with contextlib.redirect_stdout(console): + code = profiles.execute_batch(command, root, log) + self.assertEqual(code, 7) + self.assertEqual(log.read_text(), 'stdout-progress\nstderr-progress\n') + self.assertEqual(console.getvalue(), log.read_text()) + + def test_progress_is_visible_before_child_exit(self): + import concurrent.futures, contextlib, io, sys, tempfile, time + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + log, release = root / 'batch.log', root / 'release' + child = ('import pathlib,sys,time; print("still-running", flush=True); ' + 'release=pathlib.Path(sys.argv[1]); deadline=time.monotonic()+10\n' + 'while not release.exists() and time.monotonic(), room_learning: Option>, room_learning_sources: HashMap, + room_learning_rejections: HashMap, current_room_store: Option>, /// Stable installation identity used only to bind local persisted state. installation_id: Option, @@ -3492,6 +3493,7 @@ impl AppStateInner { source_bank_shadow: None, room_learning: None, room_learning_sources: HashMap::new(), + room_learning_rejections: HashMap::new(), current_room_store: None, installation_id: None, bootstrap_baseline: None, @@ -16412,6 +16414,7 @@ async fn main() { source_bank_shadow: None, room_learning, room_learning_sources: HashMap::new(), + room_learning_rejections: HashMap::new(), current_room_store: None, installation_id: args.installation_id.clone(), bootstrap_baseline: bootstrap_metadata.clone(), diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle.rs index 2b47d522eb..01b40d49ee 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle.rs @@ -93,6 +93,8 @@ pub struct RoomLearningRuntime { recovery_store: Option>, operator_recovery_store: Option>, operator_profile_selected: AtomicBool, + variable_profile_selected: AtomicBool, + variable_recovery_store: Option>, operator_profile_initialized: AtomicBool, status_reader: Arc, inner: Mutex, @@ -193,6 +195,7 @@ impl RoomLearningRuntime { .try_into() .map_err(|_| "receiver clock outside bounds")?; let operator_recovery_store = recovery_store.as_ref().map(|store| store.operator_eight_scope()).transpose()?.map(Arc::new); + let variable_recovery_store = recovery_store.as_ref().map(|store| store.variable_sources_scope()).transpose()?.map(Arc::new); let runtime = Self { clock_origin, clock_epoch_ns, @@ -203,6 +206,8 @@ impl RoomLearningRuntime { recovery_store: recovery_store.map(std::sync::Arc::new), operator_recovery_store, operator_profile_selected: AtomicBool::new(false), + variable_profile_selected: AtomicBool::new(false), + variable_recovery_store, operator_profile_initialized: AtomicBool::new(false), status_reader: Arc::new(tokio::sync::Semaphore::new(1)), #[cfg(test)] reclamation_probe:Mutex::new(None), diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal.rs index aa9fb2e95d..634bf84933 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal.rs @@ -224,11 +224,11 @@ impl RoomLearningRuntime { pub(super) fn temporal_store( &self, ) -> Result<&super::super::recovery_store::RecoveryStore, String> { - if self.operator_profile_selected.load(Ordering::Acquire) { self.operator_recovery_store.as_deref() } else { self.recovery_store.as_deref() } + if self.variable_profile_selected.load(Ordering::Acquire) { self.variable_recovery_store.as_deref() } else if self.operator_profile_selected.load(Ordering::Acquire) { self.operator_recovery_store.as_deref() } else { self.recovery_store.as_deref() } .ok_or("temporal_recovery_unavailable".into()) } fn temporal_store_arc(&self) -> Result, String> { - if self.operator_profile_selected.load(Ordering::Acquire) { self.operator_recovery_store.clone() } else { self.recovery_store.clone() }.ok_or("temporal_recovery_unavailable".into()) + if self.variable_profile_selected.load(Ordering::Acquire) { self.variable_recovery_store.clone() } else if self.operator_profile_selected.load(Ordering::Acquire) { self.operator_recovery_store.clone() } else { self.recovery_store.clone() }.ok_or("temporal_recovery_unavailable".into()) } /// Deliberately PRIVATE: current public configure always constructs Legacy. /// Refuses to discard existing capture/candidate/selection/recovery state. @@ -298,7 +298,7 @@ impl RoomLearningRuntime { { return Err("temporal_context_owner_or_clock".into()); } - let schedule = ManagedScheduleContract::build(context.clone(), if self.operator_profile_selected.load(Ordering::Acquire) { LeadInPolicy::OperatorEightStepV1 } else { LeadInPolicy::Train5HeldOut15EngineeringV1 })?; + let schedule = ManagedScheduleContract::build(context.clone(), if self.variable_profile_selected.load(Ordering::Acquire) { LeadInPolicy::OperatorVariableSourcesV2 } else if self.operator_profile_selected.load(Ordering::Acquire) { LeadInPolicy::OperatorEightStepV1 } else { LeadInPolicy::Train5HeldOut15EngineeringV1 })?; let fit = FitConfig::for_source_count(context.sources.len()); fit.validate_context(&context)?; let mut state = self.command_state(expected)?; diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_public.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_public.rs index 1e1d779a23..1945007687 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_public.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_public.rs @@ -26,8 +26,8 @@ impl RoomLearningRuntime { if !recovery_consent { return Err("recovery_consent_required".into()); } - if context.sources.len() != 3 { - return Err("learner_temporal_three_sources_required".into()); + if (if self.variable_profile_selected.load(Ordering::Acquire) { !(2..=8).contains(&context.sources.len()) } else { context.sources.len() != 3 }) { + return Err(if self.variable_profile_selected.load(Ordering::Acquire) { "learner_temporal_requires_two_to_eight_sources" } else { "learner_temporal_three_sources_required" }.into()); } let store = self.temporal_store_arc()?.clone(); if !store.available(){return Err("recovery_unavailable".into());} @@ -46,16 +46,21 @@ impl RoomLearningRuntime { ) } fn validate_profile_selection(&self,state:&Inner,profile:Option<&str>)->Result{ - let operator=match profile {Some(crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE)=>true,Some("native-2s-three-source-56bin-option-a-engineering-v1")|None=>false,_=>return Err("learner_unsupported_profile".into())}; + let operator=match profile {Some(crate::room_learner::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE)=>true,Some(crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE)=>true,Some("native-2s-three-source-56bin-option-a-engineering-v1")|None=>false,_=>return Err("learner_unsupported_profile".into())}; if let Some(CaptureWorkflow::Temporal(c))=state.capture.as_ref(){ - if c.core.as_ref().is_none_or(|core|core.public_profile().profile_id.eq(crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE)!=operator){return Err("temporal_previous_plan_loaded".into());} + if c.core.as_ref().is_none_or(|core|core.public_profile().profile_id != profile.unwrap_or("native-2s-three-source-56bin-option-a-engineering-v1")){return Err("temporal_previous_plan_loaded".into());} } Ok(operator) } pub fn temporal_select_profile_guarded_v2(&self,profile:Option<&str>,expected:&MutationGuard)->Result{ let mut state=self.command_state(expected)?; let operator=self.validate_profile_selection(&state,profile)?; + let variable = profile == Some(crate::room_learner::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE); + if self.operator_profile_selected.load(Ordering::Acquire) != operator || self.variable_profile_selected.load(Ordering::Acquire) != variable || !self.operator_profile_initialized.load(Ordering::Acquire) { + state.workflow_revision = state.workflow_revision.checked_add(1).ok_or("learner command revision exhausted")?; + } self.operator_profile_selected.store(operator,Ordering::Release); + self.variable_profile_selected.store(variable,Ordering::Release); self.operator_profile_initialized.store(true,Ordering::Release); Ok(self.guard_for(&state)) } @@ -63,11 +68,27 @@ impl RoomLearningRuntime { pub(super) fn temporal_select_profile_v2(&self,profile:Option<&str>)->Result<(),String>{ let guard=self.mutation_guard()?;self.temporal_select_profile_guarded_v2(profile,&guard).map(|_|()) } - pub fn temporal_default_operator_profile_v2(&self)->Result<(),String>{ + pub fn temporal_default_operator_profile_v2(&self,now:u64)->Result<(),String>{ + // Discover old pending runs before choosing a fresh default. No stored + // run is migrated or hidden behind the new profile's recovery namespace. + { + let state=self.inner.lock().map_err(|_|"learner state unavailable")?; + if state.capture.is_some() || self.operator_profile_initialized.load(Ordering::Acquire) { return Ok(()); } + } + let pending=|store:&Option>|->Result{ + Ok(store.as_ref().map(|s|s.inspect_temporal_read_only(now)).transpose()?.flatten() + .is_some_and(|head|!head.retired())) + }; + let variable_pending = pending(&self.variable_recovery_store)?; + let operator_pending = !variable_pending && pending(&self.operator_recovery_store)?; + let legacy_pending = !variable_pending && !operator_pending && pending(&self.recovery_store)?; + let variable = variable_pending || (!operator_pending && !legacy_pending); + let operator = variable || operator_pending; let mut state=self.inner.lock().map_err(|_|"learner state unavailable")?; if state.capture.is_none()&&!self.operator_profile_initialized.load(Ordering::Acquire){ state.workflow_revision=state.workflow_revision.checked_add(1).ok_or("learner command revision exhausted")?; - self.operator_profile_selected.store(true,Ordering::Release); + self.operator_profile_selected.store(operator,Ordering::Release); + self.variable_profile_selected.store(variable,Ordering::Release); self.operator_profile_initialized.store(true,Ordering::Release); } Ok(()) @@ -451,17 +472,17 @@ impl RoomLearningRuntime { /// Read-only recovery discovery may wait for a durable writer. Callers /// must not hold the shared RF ingress lock across this operation. pub fn temporal_status_snapshot_v2(self: &Arc, now: u64) -> Result { - let (generation,workflow_revision,operator_profile) = { + let (generation,workflow_revision,operator_profile,variable_profile) = { let state=self.inner.lock().map_err(|_| "learner state unavailable")?; - (state.generation,state.workflow_revision,self.operator_profile_selected.load(Ordering::Acquire)) + (state.generation,state.workflow_revision,self.operator_profile_selected.load(Ordering::Acquire),self.variable_profile_selected.load(Ordering::Acquire)) }; - let recovery_store=if operator_profile{self.operator_recovery_store.as_ref()}else{self.recovery_store.as_ref()}; + let recovery_store=if variable_profile { self.variable_recovery_store.as_ref() } else if operator_profile{self.operator_recovery_store.as_ref()}else{self.recovery_store.as_ref()}; let recovery=recovery_store.and_then(|store|TemporalTrainCapture::recovery_discovery(store,now)); #[cfg(test)] if let Some(hook)=self.temporal_status_profile_hook.lock().unwrap().take(){hook();} let mut response = { let state = self.inner.lock().map_err(|_| "learner state unavailable")?; - if state.generation != generation || state.workflow_revision!=workflow_revision || self.operator_profile_selected.load(Ordering::Acquire)!=operator_profile { + if state.generation != generation || state.workflow_revision!=workflow_revision || self.operator_profile_selected.load(Ordering::Acquire)!=operator_profile || self.variable_profile_selected.load(Ordering::Acquire)!=variable_profile { return Err("learner_state_changed".into()); } let capture = match state.capture.as_ref() { @@ -469,7 +490,7 @@ impl RoomLearningRuntime { _ => None, }; let context = state.capture_context().cloned(); - let mut profile = if operator_profile{TemporalProfileWire::operator_eight_step()}else{TemporalProfileWire::engineering()}; + let mut profile = if variable_profile { TemporalProfileWire::variable_sources() } else if operator_profile{TemporalProfileWire::operator_eight_step()}else{TemporalProfileWire::engineering()}; let mut wire_capture = None; let mut candidate = None; let mut train_proof = None; diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_tests.rs index f33bc3042c..01508e759e 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/lifecycle_temporal_tests.rs @@ -1475,14 +1475,14 @@ fn retry_cannot_reconcile_a_writer_after_terminal_owner_drain(){ fn profile_namespace_selection_is_guarded_and_default_reads_cannot_undo_explicit_choice(){ let directory=tempfile::tempdir().unwrap();let rt=runtime(directory.path(),START); let old_guard=rt.mutation_guard().unwrap(); - rt.temporal_default_operator_profile_v2().unwrap(); + rt.temporal_default_operator_profile_v2(START).unwrap(); assert!(rt.operator_profile_selected.load(Ordering::Acquire)); assert!(rt.temporal_select_profile_guarded_v2(None,&old_guard).is_err()); assert!(rt.operator_profile_selected.load(Ordering::Acquire)); let guard=rt.mutation_guard().unwrap(); let after=rt.temporal_select_profile_guarded_v2(None,&guard).unwrap(); assert!(!rt.operator_profile_selected.load(Ordering::Acquire)); - rt.temporal_default_operator_profile_v2().unwrap(); + rt.temporal_default_operator_profile_v2(START).unwrap(); assert!(!rt.operator_profile_selected.load(Ordering::Acquire),"read must not race an explicit old-plan restore"); assert_eq!(rt.mutation_guard().unwrap(),after); } @@ -1526,3 +1526,170 @@ fn status_refuses_profile_and_recovery_snapshot_mixed_across_a_guarded_selection assert_eq!(coherent["temporal_profile"]["profile_id"],crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE); assert!(coherent["recovery"].is_null(),"new namespace cannot show the old plan recovery ID"); } + +#[test] +fn variable_profile_configures_and_retains_four_sources_through_durable_genesis() { + let directory=tempfile::tempdir().unwrap();let rt=Arc::new(runtime(directory.path(),START)); + rt.temporal_default_operator_profile_v2(START).unwrap(); + assert!(rt.variable_profile_selected.load(Ordering::Acquire)); + let mut c=context();let mut fourth=c.sources[2].clone();fourth.source_id=18;fourth.device_id="esp32-node-18".into();fourth.link_id="native-18".into();c.sources.push(fourth); + rt.temporal_configure_v2(&rt.mutation_guard().unwrap(),c,"synthetic-four-source-genesis".into(),true,START).unwrap(); + let now=settle_async_boundary(&rt,START); + let status=rt.temporal_status_snapshot_v2(now).unwrap(); + assert_eq!(status["source_node_ids"],serde_json::json!([1,2,3,18])); + assert_eq!(status["temporal_profile"]["profile_id"],crate::room_learner::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE); + assert_eq!(status["capture"]["stage"],"ready"); + assert_eq!(status["capture"]["durable_windows"],0); + assert!(rt.temporal_select_profile_v2(Some(crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE)).is_err()); +} + +fn recovery_files(root:&Path)->Vec<(std::path::PathBuf,Vec)> { + let mut files=Vec::new(); + for entry in std::fs::read_dir(root).unwrap() { + let entry=entry.unwrap();let path=entry.path(); + if entry.file_type().unwrap().is_dir(){files.extend(recovery_files(&path));} + else {files.push((path.clone(),std::fs::read(path).unwrap()));} + } + files.sort_by(|a,b|a.0.cmp(&b.0));files +} +fn actual_old_temporal_genesis(root:&Path,operator:bool,now:u64)->u64 { + let rt=Arc::new(runtime(root,now)); + rt.temporal_select_profile_v2(if operator {Some(crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE)}else{None}).unwrap(); + rt.temporal_configure_v2(&rt.mutation_guard().unwrap(),context(),"synthetic-real-old-profile-genesis".into(),true,now).unwrap(); + let settled=settle_async_boundary(&rt,now); + assert_eq!(snapshot(&rt,settled)["durable_windows"],0); + drop(rt);settled +} +#[test] +fn variable_profile_default_keeps_pending_older_recovery_discoverable() { + for operator in [false,true] {for expired in [false,true] { + let directory=tempfile::tempdir().unwrap();let settled=actual_old_temporal_genesis(directory.path(),operator,START); + let rt=Arc::new(runtime(directory.path(),settled+1)); + let store=if operator {rt.operator_recovery_store.as_ref().unwrap()}else{rt.recovery_store.as_ref().unwrap()}; + let original=store.inspect_temporal_read_only(settled+1).unwrap().unwrap().descriptor().clone(); + let now=if expired {original.expires_at_ms*1_000_000+1}else{settled+2}; + let before=recovery_files(directory.path()); + assert!(before.iter().any(|(p,_)|p.file_name().unwrap()=="temporal-head.bin")); + assert!(!before.iter().any(|(p,_)|p.file_name().unwrap()=="capture-recovery-v1.bin")); + rt.temporal_default_operator_profile_v2(now).unwrap(); + assert!(!rt.variable_profile_selected.load(Ordering::Acquire)); + assert_eq!(rt.operator_profile_selected.load(Ordering::Acquire),operator); + let status=rt.temporal_status_snapshot_v2(now).unwrap(); + assert_eq!(status["temporal_profile"]["profile_id"],if operator {crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE}else{"native-2s-three-source-56bin-option-a-engineering-v1"}); + assert_eq!(status["recovery"]["state"],if expired {"expired"}else{"available"}); + assert!(status["recovery"]["capture_generation_id"].as_str().is_some()); + assert_eq!(status["recovery"]["original_deadline"]["expires_at_unix_ms"],original.expires_at_ms); + assert_eq!(store.inspect_temporal_read_only(now).unwrap().unwrap().descriptor(),&original); + assert_eq!(recovery_files(directory.path()),before,"default/status discovery must not repair, renew or rewrite journals"); + }} +} +#[test] +fn retired_variable_temporal_head_does_not_mask_an_active_old_profile_after_cold_runtime() { + for operator in [false,true] { + let directory=tempfile::tempdir().unwrap();let variable=Arc::new(runtime(directory.path(),START)); + variable.temporal_select_profile_v2(Some(crate::room_learner::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE)).unwrap(); + variable.temporal_configure_v2(&variable.mutation_guard().unwrap(),context(),"synthetic-retired-variable".into(),true,START).unwrap(); + let now=settle_async_boundary(&variable,START); + variable.cancel_temporal_durability(&variable.mutation_guard().unwrap()).unwrap(); + let store=variable.variable_recovery_store.as_ref().unwrap();let loaded=store.load_temporal(now).unwrap().unwrap(); + let intent=store.prepare_retire_temporal(&loaded.token,now+1,false).unwrap(); + store.publish_temporal(&intent,None,now+1).unwrap(); + assert!(store.inspect_temporal_read_only(now+1).unwrap().unwrap().retired());drop(variable); + let settled=actual_old_temporal_genesis(directory.path(),operator,now+2); + let rt=Arc::new(runtime(directory.path(),settled+1));let before=recovery_files(directory.path()); + rt.temporal_default_operator_profile_v2(settled+2).unwrap(); + assert!(!rt.variable_profile_selected.load(Ordering::Acquire)); + assert_eq!(rt.operator_profile_selected.load(Ordering::Acquire),operator); + assert_eq!(rt.temporal_status_snapshot_v2(settled+2).unwrap()["recovery"]["state"],"available"); + assert_eq!(recovery_files(directory.path()),before); + } +} + +/// SYNTHETIC real Runtime/durable journals, never a user-owned capture. +#[test] +#[cfg_attr(debug_assertions, ignore = "native-persistence Retry journey requires Release; CI explicitly executes and counts it")] +fn variable_retry_after_actual_window_cadence_failure_keeps_sixteen_windows_and_seal() { + assert!(!cfg!(debug_assertions), "native-persistence Retry acceptance requires Release"); + let directory=tempfile::tempdir().unwrap();let rt=Arc::new(runtime(directory.path(),START)); + rt.temporal_select_profile_v2(Some(crate::room_learner::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE)).unwrap(); + let mut c=context();let mut extra=c.sources[2].clone();extra.source_id=4;extra.device_id="esp32-node-4".into();extra.link_id="native-4".into();c.sources.push(extra); + rt.temporal_configure_v2(&rt.mutation_guard().unwrap(),c.clone(),"synthetic-actual-cadence-retry".into(),true,START).unwrap(); + let mut now=settle_async_boundary(&rt,START);let mut sequence=0u32; + let supervision=std::time::Instant::now(); + loop { + let progress=snapshot(&rt,now); + match progress["stage"].as_str().unwrap() { + "ready"|"paused"=>{now=async_lead_end(&rt,now);rt.tick_temporal_capture(&rt.mutation_guard().unwrap(),now).unwrap();}, + "needs_confirmation"=>{now=settle_async_boundary(&rt,now);break;}, + "failed"=>panic!("synthetic first episode failed before retry fixture: {}",progress["failure"]), + _=>{} + } + sequence+=1; + for source in 1..=4 {match rt.ingest_native(&packet(source,sequence,now),now) { + Ok(())=>{},Err(e)if e=="temporal_storage_busy_pause"=>break,Err(e)=>panic!("synthetic episode ingest: {e}"), + }} + now+=50_000_000; + if snapshot(&rt,now)["durability_pending"]==true {std::thread::sleep(std::time::Duration::from_millis(50));} + assert!(supervision.elapsed()Value { + let loaded=rt.temporal_store().unwrap().load_temporal(at).unwrap().unwrap(); + let value:Value=serde_json::from_slice(loaded.prefix.unwrap().bytes()).unwrap(); + let p=&value["payload"]; + let digest=|v:&Value|format!("{:x}",::digest(serde_json::to_vec(v).unwrap())); + let first=|v:&Value,n|{let a=v.as_array().unwrap();assert!(a.len()>=n);Value::Array(a[..n].to_vec())}; + serde_json::json!({"rows":digest(&first(&p["accepted"]["rows"],16)),"evidence":digest(&first(&p["accepted"]["evidence"],16)),"identities":digest(&first(&p["accepted"]["identities"],16)),"spans":digest(&first(&p["common"]["ledger"]["spans"],16)),"seals":digest(&first(&p["stage"]["bridge"]["seals"],1))}) + } + let protected_prefix=prefix(&rt,now); + let start=async_lead_end(&rt,now);rt.tick_temporal_capture(&rt.mutation_guard().unwrap(),start).unwrap(); + let mut next=[start+1000,start+2000,start+3000,start+4000];let mut seq=[sequence;4]; + let periods=[1_000_000_000u64.div_ceil(23),50_000_000,50_000_000,50_000_000]; + let mut failed=None;let mut failed_window_first=None; + for _ in 0..300 { + let index=(0..4).min_by_key(|i|next[*i]).unwrap();let at=next[index];seq[index]+=1; + if failed_window_first.is_none(){failed_window_first=Some((index as u8+1,seq[index],at));} + match rt.ingest_native(&packet(index as u8+1,seq[index],at),at) { + Ok(())=>{},Err(e)=>{assert_eq!(e,"acquisition_observed_cadence");failed=Some(at);break;}, + } + next[index]+=periods[index]; + } + let failed_at=failed.expect("actual four-source window must fail only its observed rate"); + let before=rt.temporal_status_v2(failed_at).unwrap(); + assert_eq!(before["capture"]["stage"],"failed");assert_eq!(before["capture"]["durable_windows"],16);assert_eq!(before["capture"]["sealed_train_episodes"],1); + let counts=|rt:&RoomLearningRuntime|{let state=rt.inner.lock().unwrap();let Some(CaptureWorkflow::Temporal(c))=&state.capture else{panic!()};c.core.as_ref().unwrap().c4b_test_custody().3}; + let failed_fences=counts(&rt);assert!(failed_fences.3,"the REAL assembler, not only the outer capture, must be failed"); + println!("SYNTHETIC_ACTUAL_RETRY_BOUNDARY error=acquisition_observed_cadence durable=16 seals=1"); + let id=before["capture"]["capture_generation_id"].as_str().unwrap();let guard=rt.mutation_guard().unwrap();now=failed_at+1_000_000_000; + // RED on unmodified515a: temporal_failed_fences, before any restore occurs. + rt.retry_failed_temporal_capture(&guard,id,now).unwrap(); + let after=rt.temporal_status_v2(now).unwrap();assert_eq!(after["capture"]["stage"],"paused");assert!(after["capture"]["failure"].is_null()); + let restored_fences=counts(&rt);assert!(!restored_fences.3);assert_eq!(restored_fences.1,failed_fences.1,"retry must retain all admitted failed-window frame IDs"); + for field in ["capture_generation_id","schedule_sha256","original_deadline","durable_windows","sealed_train_episodes","current_episode"] {assert_eq!(after["capture"][field],before["capture"][field],"{field}");} + assert_eq!(prefix(&rt,now),protected_prefix); + assert!(rt.retry_failed_temporal_capture(&guard,id,now+1).is_err()); + sequence=*seq.iter().max().unwrap()+100;now+=50_000_000; + rt.ingest_native(&packet(1,sequence,now),now).unwrap(); + assert_eq!(snapshot(&rt,now)["stage"],"paused");assert_eq!(snapshot(&rt,now)["durable_windows"],16,"fresh non-observing priming is not recording"); + now=async_lead_end(&rt,now);rt.tick_temporal_capture(&rt.mutation_guard().unwrap(),now).unwrap(); + for _ in 0..100 { + sequence+=1;for source in 1..=4 {match rt.ingest_native(&packet(source,sequence,now),now) {Ok(())=>{},Err(e)if e=="temporal_storage_busy_pause"=>break,Err(e)=>panic!("fresh retry window failed: {e}")}} + now+=50_000_000; + if snapshot(&rt,now)["durability_pending"]==true {std::thread::sleep(std::time::Duration::from_millis(50));} + if snapshot(&rt,now)["durable_windows"]==17 {break;} + } + assert_eq!(snapshot(&rt,now)["durable_windows"],17);assert_eq!(prefix(&rt,now),protected_prefix); + rt.cancel_temporal_durability(&rt.mutation_guard().unwrap()).unwrap();drop(rt);now+=1_000_000_000; + let cold=Arc::new(runtime(directory.path(),now));cold.temporal_select_profile_v2(Some(crate::room_learner::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE)).unwrap(); + cold.restore_temporal_full_run(&cold.mutation_guard().unwrap(),&c,now).unwrap(); + let restarted=cold.temporal_status_v2(now).unwrap();assert_eq!(restarted["capture"]["stage"],"paused");assert_eq!(restarted["capture"]["durable_windows"],17);assert_eq!(restarted["capture"]["sealed_train_episodes"],1); + assert_eq!(restarted["capture"]["original_deadline"],protected["capture"]["original_deadline"]);assert_eq!(prefix(&cold,now),protected_prefix); + let (replay_source,replay_sequence,_)=failed_window_first.unwrap();now+=50_000_000; + let error=cold.ingest_native(&packet(replay_source,replay_sequence,now),now).unwrap_err(); + assert_eq!(error,"temporal_priming_source_or_fence","failed-window replay must reject after checkpoint/restart"); + assert_eq!(snapshot(&cold,now)["durable_windows"],17); +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract.rs index 1392863653..274f0e0c0c 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract.rs @@ -12,6 +12,7 @@ use sha2::{Digest, Sha256}; const SCHEMA: &str = "ruview.room-learner.trial-schedule.v2"; const PROFILE: &str = "native-2s-three-source-56bin-option-a-engineering-v1"; pub(crate) const OPERATOR_EIGHT_PROFILE: &str = "native-2s-three-source-56bin-operator-eight-step-v1"; +pub(crate) const OPERATOR_VARIABLE_PROFILE: &str = "native-2s-variable-source-56bin-receiver20-operator-eight-step-v2"; const MAX_BYTES: usize = 65_536; const MAX_PROFILE_ROWS: usize = 77; const MAX_TRAIN_WINDOWS: usize = 64; @@ -22,10 +23,12 @@ const MAX_TRAIN_WINDOWS: usize = 64; pub enum LeadInPolicy { Train5HeldOut15EngineeringV1, OperatorEightStepV1, + OperatorVariableSourcesV2, } impl LeadInPolicy { + pub(crate) fn is_operator(self) -> bool { matches!(self, Self::OperatorEightStepV1 | Self::OperatorVariableSourcesV2) } fn milliseconds(self, role: DataRole, condition: RoomLabel) -> u64 { - if self == Self::OperatorEightStepV1 { + if self.is_operator() { return if matches!(condition, RoomLabel::Empty | RoomLabel::AdjacentOnly) { 15_000 } else { 5_000 }; } match role { @@ -231,27 +234,28 @@ impl ManagedScheduleContract { context.validate()?; // Reuse the existing actual-native 2s validators/capacity calculation, // but NEVER its different schedule, serialized plan or plan hash. + let variable = lead_in_policy == LeadInPolicy::OperatorVariableSourcesV2; let bands = context .sources .iter() - .map(|source| (source.source_id, ReceiverCadenceBand::Hz30To36)) + .map(|source| (source.source_id, if variable { ReceiverCadenceBand::Arrival18To22Burst200MsV1 } else { ReceiverCadenceBand::Hz30To36 })) .collect::>(); let native = AcquisitionPlan::build( context.clone(), - ExperimentalPlanId::Native2000msSlots8, + if variable { ExperimentalPlanId::Native2000msSlots4 } else { ExperimentalPlanId::Native2000msSlots8 }, &bands, )?; - if context.sources.len() != 3 + if (if variable { !(2..=8).contains(&context.sources.len()) } else { context.sources.len() != 3 }) || context .sources .iter() .any(|source| source.feature_count != 56) { - return Err("managed_schedule_profile_supports_three_native56_sources".into()); + return Err(if variable { "managed_schedule_profile_source_count_or_format" } else { "managed_schedule_profile_supports_three_native56_sources" }.into()); } let reserved = native.max_observed_span_ms() + native.max_first_packet_delay_ms(); let mut episodes = Vec::new(); - if lead_in_policy == LeadInPolicy::OperatorEightStepV1 { + if lead_in_policy.is_operator() { for condition in [RoomLabel::Empty, RoomLabel::OccupiedStatic, RoomLabel::OccupiedMoving, RoomLabel::AdjacentOnly] { for role in [DataRole::Train, DataRole::Validation] { let duration = if role == DataRole::Validation { 15_000 } else if condition == RoomLabel::Empty { 600_000 } else { 60_000 }; @@ -325,15 +329,18 @@ impl ManagedScheduleContract { .sum::() }; let train = role_windows(DataRole::Train); - let check_role = if lead_in_policy == LeadInPolicy::OperatorEightStepV1 { DataRole::Validation } else { DataRole::HeldOut }; + let check_role = if lead_in_policy.is_operator() { DataRole::Validation } else { DataRole::HeldOut }; let held = role_windows(check_role); let total = add(train, held)?; let (rows, values) = capacity(&context, native.source_policies(), train, total)?; - let resources = if lead_in_policy == LeadInPolicy::OperatorEightStepV1 { + let resources = if lead_in_policy.is_operator() { let views = mul(total, context.sources.len())?; let serialized = add(add(add(mul(values, 25)?, mul(rows, 86)?)?, mul(views, 4096)?)?, add(mul(total, 4096)?, 8 * 1024 * 1024)?)?; ResourcePreflight { cohorts: total, source_views: views, max_retained_rows: rows, max_numeric_values: values, serialized_upper_bound_bytes: serialized } } else { native.resources().clone() }; + if variable && resources.serialized_upper_bound_bytes > 64 * 1024 * 1024 { + return Err("managed_schedule_serialized_capacity".into()); + } if resources.cohorts != total || resources.max_retained_rows != rows || resources.max_numeric_values != values @@ -362,11 +369,11 @@ impl ManagedScheduleContract { verified_independent_trial_count: None, }; let body = Body { - profile_id: if lead_in_policy == LeadInPolicy::OperatorEightStepV1 { OPERATOR_EIGHT_PROFILE } else { PROFILE }, + profile_id: if variable { OPERATOR_VARIABLE_PROFILE } else if lead_in_policy.is_operator() { OPERATOR_EIGHT_PROFILE } else { PROFILE }, context, lead_in_policy, native_input: NativeInputPolicy { - id: "existing-native-2s-56bin-receiver-30to36-v2", + id: if variable { "native-2s-56bin-receiver-arrival18to22-burst200-v1" } else { "existing-native-2s-56bin-receiver-30to36-v2" }, original_frame_identity: "existing-esp32-receiver-ns-node-u32-sequence-v1", projection: "native-esp32-drop2-linear56-ordered-magnitude-v2-experimental", target_span_ms: native.target_span_ms(), @@ -384,7 +391,7 @@ impl ManagedScheduleContract { full_episode_quality_monitoring_implemented: false, independence_verified: false, scientific_adequacy_claimed: false, - user_facing_default: lead_in_policy == LeadInPolicy::OperatorEightStepV1, + user_facing_default: lead_in_policy.is_operator(), }, }; let result = Self { @@ -412,7 +419,7 @@ impl ManagedScheduleContract { } let value: Import = serde_json::from_slice(bytes).map_err(|_| "managed_schedule_invalid_schema")?; - if value.schema != SCHEMA || (value.body["profile_id"] != PROFILE && value.body["profile_id"] != OPERATOR_EIGHT_PROFILE) { + if value.schema != SCHEMA || (value.body["profile_id"] != PROFILE && value.body["profile_id"] != OPERATOR_EIGHT_PROFILE && value.body["profile_id"] != OPERATOR_VARIABLE_PROFILE) { return Err("managed_schedule_unsupported_profile".into()); } let context = serde_json::from_value(value.body["context"].clone()) @@ -436,7 +443,8 @@ impl ManagedScheduleContract { let model=bound.frozen_artifact_sha256.as_ref().and_then(|sha|FrozenModelIdentity::from_runtime_verified_artifact(self,sha.clone()).ok()); self.bind_episode_start(run,bound.episode.index,bound.attempt_ordinal,bound.segment_ordinal,model.as_ref()).ok().is_some_and(|expected|serde_json::to_vec(&expected).ok()==serde_json::to_vec(bound).ok()) } - pub fn is_operator_eight_step(&self) -> bool { self.body.profile_id == OPERATOR_EIGHT_PROFILE } + pub fn is_operator_eight_step(&self) -> bool { self.body.lead_in_policy.is_operator() } + pub fn is_variable_sources(&self) -> bool { self.body.profile_id == OPERATOR_VARIABLE_PROFILE } pub fn profile_id(&self) -> &str { self.body.profile_id } pub fn sha256(&self) -> &str { &self.sha256 diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract_tests.rs index 20e63bb87f..61f56ac191 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/managed_schedule_contract_tests.rs @@ -389,3 +389,30 @@ fn operator_default_is_explicit_and_rehashed_authority_claims_stay_rejected(){ let mut forged=plan();forged.body.claims.user_facing_default=true;forged.sha256=hash(&forged.body).unwrap(); assert!(ManagedScheduleContract::import(&forged.export().unwrap()).is_err()); } + +#[test] +fn variable_profile_retains_every_source_with_bounded_resources_and_roundtrip() { + for count in 2..=8 { + let p = ManagedScheduleContract::build(context(count), LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + assert_eq!(p.context().sources.len(), usize::from(count)); + assert_eq!(p.profile_id(), OPERATOR_VARIABLE_PROFILE); + assert_eq!(p.counts().total_windows, 80); + assert_eq!(p.resources().source_views, 80 * usize::from(count)); + assert!(p.resources().max_numeric_values <= 2_000_000); + assert!(p.resources().serialized_upper_bound_bytes <= 64 * 1024 * 1024); + let wire = p.export().unwrap(); + assert_eq!(ManagedScheduleContract::import(&wire).unwrap().export().unwrap(), wire); + } +} +#[test] +fn variable_profile_rejects_out_of_range_counts_and_cannot_relabel_old_contract() { + for count in [0, 1, 9] { + assert!(ManagedScheduleContract::build(context(count), LeadInPolicy::OperatorVariableSourcesV2).is_err()); + } + let old = ManagedScheduleContract::build(context(3), LeadInPolicy::OperatorEightStepV1).unwrap(); + let new = ManagedScheduleContract::build(context(3), LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + assert_ne!(old.sha256(), new.sha256()); + let mut tampered: serde_json::Value = serde_json::from_slice(&old.export().unwrap()).unwrap(); + tampered["body"]["profile_id"] = OPERATOR_VARIABLE_PROFILE.into(); + assert!(ManagedScheduleContract::import(&serde_json::to_vec(&tampered).unwrap()).is_err()); +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/native.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/native.rs index 862f2d02c7..3b9403aec6 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/native.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/native.rs @@ -9,6 +9,10 @@ use ruview_unified::RfModality; use serde::Serialize; use wifi_densepose_hardware::{Adr018Flags, PpduType}; use wifi_densepose_signal::hardware_norm::HardwareNormalizer; +#[path = "native_c5.rs"] +mod c5; +pub use c5::{validate_adr018_native_format, NativeFormatId, ValidatedNativeFormat, + C5_LLTF53_TONES, C5_LLTF8_V1_GRID}; pub const CANONICAL_PACKET_BINS: usize = 56; @@ -37,7 +41,14 @@ pub struct NativePacketInput<'a> { /// fn export(packet: &CanonicalPacket) { let _ = serde_json::to_string(packet); } /// ``` pub struct CanonicalPacket { + /// Original bounded ADR-018 metadata. Sync-valid is advisory only; never + /// changes receiver-only timing, calibration, provenance or qualification. + pub adr018_flags: Adr018Flags, pub native_frame: RfFrameV2, + /// Present only for the explicitly claimed C5 format. Never serialized or + /// exposed by Debug; original signed wire bytes and nonuniform SDK order. + pub native_iq_wire: Option>, + pub native_tone_indices: Option<&'static [i16]>, pub source_id: u8, pub grid_id: String, pub sequence: u32, @@ -95,6 +106,24 @@ pub fn grid_id(n_antennas: usize, raw_bins: usize, ppdu_type: PpduType) -> Resul Ok(format!("ant{n_antennas}-bins{raw_bins}-ppdu{}-usable-drop2-linear-v2", ppdu_type.to_byte())) } +pub fn grid_id_for_format(n_antennas: usize, raw_bins: usize, ppdu_type: PpduType, + format: NativeFormatId) -> Result { + if format == NativeFormatId::C5Lltf8V1 { + return if n_antennas == 1 && raw_bins == 53 && ppdu_type == PpduType::HtLegacy { + Ok(C5_LLTF8_V1_GRID.into()) + } else { Err("C5L8/v1 grid does not match its native format".into()) }; + } + grid_id(n_antennas, raw_bins, ppdu_type) +} + +/// Context-only whitelist; actual C5 packets still require the validated wire +/// claim. A grid name is not packet evidence or hardware qualification. +pub fn supported_feature_grid(grid:&str,frequency_hz:u64)->bool { + if grid==C5_LLTF8_V1_GRID {return c5::supported_frequency_hz(frequency_hz);} + is_supported_frequency_hz(frequency_hz) && (0..=3).any(|ppdu| + grid==format!("ant1-bins{}-ppdu{ppdu}-usable-drop2-linear-v2",if ppdu==0 {64}else{256})) +} + pub fn is_supported_frequency_hz(frequency_hz: u64) -> bool { let mhz = frequency_hz / 1_000_000; frequency_hz % 1_000_000 == 0 @@ -106,7 +135,12 @@ pub fn is_supported_frequency_hz(frequency_hz: u64) -> bool { /// length-only normalizer for the derived magnitude features. Never calls /// `normalize()` or `RfFrameV2::to_canonical()` (both remove amplitude gain). pub fn canonicalize_esp32(input: NativePacketInput<'_>) -> Result { - let grid_id = grid_id(input.n_antennas, input.raw_bins, input.ppdu_type)?; + canonicalize_esp32_with_format(input, ValidatedNativeFormat::legacy()) +} + +pub fn canonicalize_esp32_with_format(input: NativePacketInput<'_>, format: ValidatedNativeFormat) + -> Result { + let grid_id = grid_id_for_format(input.n_antennas, input.raw_bins, input.ppdu_type, format.id())?; if input.flags.bw40 { return Err("native capture does not support the reported 40 MHz bandwidth".into()); } if input.received_at_ns == 0 { return Err("native receiver time is unavailable".into()); } if !input.receiver_sample_rate_hz.is_finite() || input.receiver_sample_rate_hz <= 0.0 { @@ -124,8 +158,32 @@ pub fn canonicalize_esp32(input: NativePacketInput<'_>) -> Result = input.iq_bytes.chunks_exact(2).map(|pair| - Complex64::new(f64::from(pair[0] as i8), f64::from(pair[1] as i8))).collect(); + let c5 = format.id() == NativeFormatId::C5Lltf8V1; + if c5 { + if input.flags.stbc || input.flags.ldpc { + return Err("C5L8/v1 input contains unsupported PHY flags".into()); + } + if !format.flags_match(input.flags) { + return Err("C5L8/v1 format claim belongs to different ADR-018 flags".into()); + } + if !format.header_matches(input.node_id,input.sequence,input.frequency_hz) { + return Err("C5L8/v1 format claim belongs to a different source/sequence/frequency header".into()); + } + if format.first_word_invalid() != input.flags.first_word_sanitized { + return Err("C5L8/v1 format and input invalid-prefix metadata differ".into()); + } + if input.flags.first_word_sanitized && input.iq_bytes[..4] != [0, 0, 0, 0] { + return Err("C5L8/v1 sanitized prefix bytes are not zero".into()); + } + valid_mask[0] = false; // SDK L-LTF DC slot is not a valid carrier. + } + let iq: Vec<_> = input.iq_bytes.chunks_exact(2).map(|pair| { + if c5 { + // The explicit new format follows SDK-documented imag/real order. + // Do not change the existing 64/256 convention or consume phase. + Complex64::new(f64::from(pair[1] as i8), f64::from(pair[0] as i8)) + } else { Complex64::new(f64::from(pair[0] as i8), f64::from(pair[1] as i8)) } + }).collect(); let frame_id = (u128::from(input.received_at_ns) << 40) | (u128::from(input.node_id) << 32) | u128::from(input.sequence); let (class, evidence) = match input.provenance { @@ -154,7 +212,9 @@ pub fn canonicalize_esp32(input: NativePacketInput<'_>) -> Result bool { + if !(5180..=5885).contains(&mhz) || (mhz-5000)%5 != 0 {return false;} + let channel=(mhz-5000)/5; + ((36..=64).contains(&channel) || (100..=144).contains(&channel)) && channel%4==0 + || (149..=177).contains(&channel) && (channel-149)%4==0 +} +pub(super) fn supported_frequency_hz(hz:u64)->bool { + hz%1_000_000==0 && u32::try_from(hz/1_000_000).is_ok_and(supported_5ghz_primary_mhz) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum NativeFormatId { + LegacyV2, + C5Lltf8V1, +} + +/// Private fields prevent callers from constructing a C5 claim without the +/// bounded decoder. The claim only identifies packing and acquisition metadata. +#[derive(Debug, Clone, Copy)] +pub struct ValidatedNativeFormat { + id: NativeFormatId, + first_word_invalid: bool, + adr018_flags: Adr018Flags, + header_binding: Option<(u8, u32, u64)>, +} +impl ValidatedNativeFormat { + pub(super) fn legacy() -> Self { + Self { id: NativeFormatId::LegacyV2, first_word_invalid: false, adr018_flags: Adr018Flags::default(), header_binding: None } + } + pub fn id(self) -> NativeFormatId { self.id } + pub(super) fn first_word_invalid(self) -> bool { self.first_word_invalid } + pub(super) fn flags_match(self, flags: Adr018Flags) -> bool { self.adr018_flags == flags } + pub(super) fn header_matches(self, node: u8, sequence: u32, frequency_hz: u64) -> bool { + self.header_binding == Some((node, sequence, frequency_hz)) + } +} + +/// Decode the exact C5L8/v1 suffix after the declared ADR-018 IQ bytes. No +/// unknown/trailing metadata is accepted for managed input. Original ADR-018 +/// live ingestion is a separate caller and is not modified by this decoder. +pub fn validate_adr018_native_format( + packet: &[u8], antennas: usize, bins: usize, ppdu: PpduType, flags: Adr018Flags, +) -> Result { + if packet.len() < 20 || packet[..4] != 0xC5110001u32.to_le_bytes() + || usize::from(packet[5]) != antennas + || usize::from(u16::from_le_bytes([packet[6],packet[7]])) != bins + || PpduType::from_byte(packet[18]) != ppdu + || Adr018Flags::from_byte(packet[19]) != flags { + return Err("native format inputs contradict the original ADR-018 header"); + } + let payload = antennas.checked_mul(bins).and_then(|n| n.checked_mul(2)) + .and_then(|n| n.checked_add(20)).ok_or("native payload extent overflow")?; + if packet.len() == payload { + if bins == 53 { + return Err("C5 53-slot native input requires an explicit verified 8-bit C5L8/v1 format claim; legacy 106 bytes may be 12-bit packed"); + } + return Ok(ValidatedNativeFormat::legacy()); + } + let suffix = packet.get(payload..).ok_or("native payload is truncated")?; + if suffix.len() != C5_LLTF8_V1_SUFFIX_BYTES || &suffix[..4] != b"C5L8" { + return Err("native payload has unknown or ambiguous trailing metadata"); + } + if antennas != 1 || bins != 53 || ppdu != PpduType::HtLegacy || flags.bw40 { + return Err("C5L8/v1 requires one antenna, 53 native slots, non-HT OFDM and 20 MHz"); + } + // ADR-018 bit4 is the producer's advisory cross-node sync-valid flag + // (ESP-NOW or 802.15.4), not a packing variant or source-clock proof. + // Bit5 retains its exact invalid-prefix meaning. All other bits reject. + if packet[19] & !0x30 != 0 { + return Err("C5L8/v1 contains unsupported ADR-018 flag variants"); + } + let frequency_mhz=u32::from_le_bytes(packet[8..12].try_into().expect("bounded header")); + if !supported_5ghz_primary_mhz(frequency_mhz) { + return Err("C5L8/v1 is limited to the explicit 5 GHz producer profile"); + } + // Version, component bits/order, tone order, SDK readback, raw BB format + // (11g/11a=1), secondary channel, STA bandwidth readback in MHz and + // estimator validity. C5 has no per-frame cwb field. + if suffix[4..13] != [1, 8, 1, 1, 1, 1, 0, 20, 1] { + return Err("C5L8/v1 packing, SDK readback or original PHY validity metadata is unsupported"); + } + if suffix[13] > 1 || u16::from_le_bytes([suffix[14], suffix[15]]) != 106 { + return Err("C5L8/v1 invalid-prefix or byte-count metadata is malformed"); + } + let first_word_invalid = suffix[13] == 1; + if first_word_invalid != flags.first_word_sanitized { + return Err("C5L8/v1 invalid-prefix metadata contradicts ADR-018 sanitation"); + } + if first_word_invalid && packet.get(20..24) != Some(&[0, 0, 0, 0]) { + return Err("C5L8/v1 sanitized prefix bytes are not zero"); + } + Ok(ValidatedNativeFormat { id: NativeFormatId::C5Lltf8V1, first_word_invalid, adr018_flags: flags, + header_binding: Some((packet[4],u32::from_le_bytes(packet[12..16].try_into().expect("bounded header")),u64::from(frequency_mhz)*1_000_000)) }) +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/native_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/native_tests.rs index 1a49f5a9c4..ce7a431673 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/native_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/native_tests.rs @@ -174,3 +174,202 @@ fn valid_native_spectral_nulls_are_admitted_without_negative_projected_magnitude } } } + +fn c5_datagram(payload: &[u8], first_word_invalid: bool) -> Vec { + let mut packet = vec![0;20]; + packet[..4].copy_from_slice(&0xC5110001u32.to_le_bytes()); + packet[4]=20;packet[5]=1;packet[6..8].copy_from_slice(&53u16.to_le_bytes()); + packet[8..12].copy_from_slice(&5180u32.to_le_bytes()); + packet[12..16].copy_from_slice(&23u32.to_le_bytes()); + packet[18]=0;packet[19]=if first_word_invalid {0x20}else{0}; + packet.extend(payload); + packet.extend([b'C',b'5',b'L',b'8',1,8,1,1,1,1,0,20,1,u8::from(first_word_invalid),106,0]); + packet +} +fn c5_input(payload: &[u8], sanitized: bool) -> NativePacketInput<'_> { + NativePacketInput {node_id:20,n_antennas:1,raw_bins:53,frequency_hz:5_180_000_000, + ppdu_type:PpduType::HtLegacy,sequence:23,received_at_ns:1_234_000_000, + receiver_sample_rate_hz:10.,iq_bytes:payload, + flags:Adr018Flags{first_word_sanitized:sanitized,..Adr018Flags::default()}, + provenance:CaptureProvenance::Synthetic} +} +#[test] +fn c5_lltf8_claim_retains_original_bytes_slots_order_dc_mask_and_feature_identity() { + let payload:Vec=(0..53).flat_map(|n|[(n as i8-30) as u8,(53-n as i8) as u8]).collect(); + let wire=c5_datagram(&payload,false);let i=c5_input(&payload,false); + let format=validate_adr018_native_format(&wire,1,53,i.ppdu_type,i.flags).unwrap(); + let packet=canonicalize_esp32_with_format(i,format).unwrap(); + assert_eq!(packet.native_iq_wire.as_deref(),Some(payload.as_slice())); + assert_eq!(packet.native_frame.native_shape,vec![1,53,1]); + for (native,raw) in packet.native_frame.native_iq.iter().zip(payload.chunks_exact(2)) { + assert_eq!((native.im,native.re),(f64::from(raw[0] as i8),f64::from(raw[1] as i8))); + } + assert!(!packet.native_frame.valid_mask[0]); + assert!(packet.native_frame.valid_mask[1..].iter().all(|x|*x)); + assert_eq!(packet.native_tone_indices.unwrap(),&C5_LLTF53_TONES); + assert_eq!(&C5_LLTF53_TONES[..27],&(0..=26).collect::>()); + assert_eq!(&C5_LLTF53_TONES[27..],&(-26..=-1).collect::>()); + let magnitudes:Vec<_>=payload.chunks_exact(2).skip(2).map(|p| + f64::from(p[0] as i8).hypot(f64::from(p[1] as i8))).collect(); + assert_eq!(packet.amplitudes,HardwareNormalizer::new().resample_magnitude_to_canonical(&magnitudes).unwrap()); + assert_eq!(packet.grid_id,C5_LLTF8_V1_GRID); + assert_eq!((packet.frequency_hz,packet.bandwidth_hz),(5_180_000_000,20_000_000)); + assert!(!packet.phase_consumed && !packet.temporal_sample_rate_known && !packet.signal_quality_known); + assert_eq!(packet.clock.kind,ClockKind::ReceiverOnly); + assert_eq!(packet.native_frame.provenance.class,ProvenanceClass::Synthetic); + assert!(packet.native_frame.transmitter_pose.is_none() && packet.native_frame.receiver_pose.is_none()); + let public=serde_json::to_string(&packet.summary()).unwrap();let debug=format!("{packet:?}"); + for raw in ["native_iq","native_iq_wire","native_tone_indices","amplitudes","valid_mask"] { + assert!(!public.contains(raw) && !debug.contains(raw)); + } +} +#[test] +fn c5_lltf8_invalid_first_word_keeps_two_masked_complex_slots_without_renumbering() { + let payload=bytes(53,-3,4);let mut sanitized=payload.clone();sanitized[..4].fill(0); + let wire=c5_datagram(&sanitized,true);let i=c5_input(&sanitized,true); + let format=validate_adr018_native_format(&wire,1,53,i.ppdu_type,i.flags).unwrap(); + let packet=canonicalize_esp32_with_format(i,format).unwrap(); + assert_eq!(&packet.native_frame.valid_mask[..2],&[false,false]); + assert!(packet.native_frame.valid_mask[2..].iter().all(|x|*x)); + assert_eq!(packet.native_iq_wire.as_deref(),Some(sanitized.as_slice())); + assert_eq!(packet.native_frame.native_iq.len(),53); + assert!(packet.amplitudes.iter().all(|x|*x==5.)); + assert_eq!(packet.grid_id,C5_LLTF8_V1_GRID); +} +#[test] +fn c5_lltf8_missing_wrong_or_ambiguous_claim_never_becomes_a_supported_grid() { + let payload=bytes(53,-3,4);let wire=c5_datagram(&payload,false);let i=c5_input(&payload,false); + assert!(grid_id(1,53,PpduType::HtLegacy).is_err()); + assert!(canonicalize_esp32(c5_input(&payload,false)).is_err()); + assert!(validate_adr018_native_format(&wire[..126],1,53,i.ppdu_type,i.flags).is_err()); + for field in 0..16 { + let mut changed=wire.clone();changed[126+field]^=1; + assert!(validate_adr018_native_format(&changed,1,53,i.ppdu_type,i.flags).is_err(),"field {field}"); + } + let mut trailing=wire.clone();trailing.push(0); + assert!(validate_adr018_native_format(&trailing,1,53,i.ppdu_type,i.flags).is_err()); + for ppdu in [PpduType::HeSu,PpduType::HeMu,PpduType::HeTb,PpduType::Unknown] { + assert!(validate_adr018_native_format(&wire,1,53,ppdu,i.flags).is_err()); + } + assert!(validate_adr018_native_format(&wire,1,53,i.ppdu_type,Adr018Flags{bw40:true,..i.flags}).is_err()); + assert!(validate_adr018_native_format(&wire,2,53,i.ppdu_type,i.flags).is_err()); + for bit in [0x01,0x02,0x04,0x08,0x40,0x80] { + let mut changed=wire.clone();changed[19]|=bit; + assert!(validate_adr018_native_format(&changed,1,53,i.ppdu_type,Adr018Flags::from_byte(changed[19])).is_err()); + } + for mhz in [2437u32,5185,5470,5730,5955] { + let mut changed=wire.clone();changed[8..12].copy_from_slice(&mhz.to_le_bytes()); + assert!(validate_adr018_native_format(&changed,1,53,i.ppdu_type,i.flags).is_err()); + } + let mut channel112=wire.clone();channel112[8..12].copy_from_slice(&5560u32.to_le_bytes()); + assert!(validate_adr018_native_format(&channel112,1,53,i.ppdu_type,i.flags).is_ok()); +} +#[test] +fn c5_lltf8_format_token_cannot_bypass_exact_iq_width_or_supported_frequency() { + let payload=bytes(53,-3,4);let wire=c5_datagram(&payload,false);let i=c5_input(&payload,false); + let format=validate_adr018_native_format(&wire,1,53,i.ppdu_type,i.flags).unwrap(); + for size in [0,1,104,105,107,108,128] { + let wrong=vec![1;size];assert!(canonicalize_esp32_with_format(c5_input(&wrong,false),format).is_err()); + } + for frequency in [0,5_180_000_001,8_000_000_000] { + let mut input=c5_input(&payload,false);input.frequency_hz=frequency; + assert!(canonicalize_esp32_with_format(input,format).is_err()); + } + let mut foreign=c5_input(&payload,false);foreign.node_id=21; + assert!(canonicalize_esp32_with_format(foreign,format).is_err()); + let mut foreign=c5_input(&payload,false);foreign.sequence+=1; + assert!(canonicalize_esp32_with_format(foreign,format).is_err()); + let mut foreign=c5_input(&payload,false);foreign.frequency_hz=5_200_000_000; + assert!(canonicalize_esp32_with_format(foreign,format).is_err()); + let mut foreign=c5_input(&payload,false);foreign.flags.ieee802154_sync_valid=true; + assert!(canonicalize_esp32_with_format(foreign,format).is_err()); +} + +#[test] +fn c5_advisory_sync_bit_preserves_iq_masks_features_and_receiver_only_authority() { + for sanitized in [false,true] { + let mut payload=bytes(53,-3,4);if sanitized {payload[..4].fill(0);} + let plain_wire=c5_datagram(&payload,sanitized);let plain_input=c5_input(&payload,sanitized); + let plain_format=validate_adr018_native_format(&plain_wire,1,53,plain_input.ppdu_type,plain_input.flags).unwrap(); + let plain=canonicalize_esp32_with_format(plain_input,plain_format).unwrap(); + let mut wire=plain_wire.clone();wire[19]|=0x10; + let mut input=c5_input(&payload,sanitized);input.flags=Adr018Flags::from_byte(wire[19]); + let format=validate_adr018_native_format(&wire,1,53,input.ppdu_type,input.flags).unwrap(); + let packet=canonicalize_esp32_with_format(input,format).unwrap(); + assert!(packet.adr018_flags.ieee802154_sync_valid); + assert_eq!(packet.adr018_flags.first_word_sanitized,sanitized); + assert_eq!(packet.native_iq_wire,plain.native_iq_wire); + assert_eq!(packet.native_frame.native_iq,plain.native_frame.native_iq); + assert_eq!(packet.native_frame.valid_mask,plain.native_frame.valid_mask); + assert_eq!(packet.amplitudes,plain.amplitudes);assert_eq!(packet.grid_id,plain.grid_id); + assert_eq!(packet.clock,ClockInfo{kind:ClockKind::ReceiverOnly,uncertainty_ns:u64::MAX}); + assert!(!packet.temporal_sample_rate_known && !packet.phase_consumed && !packet.signal_quality_known); + assert!(!packet.native_frame.calibration.gain_calibrated); + assert_eq!(packet.native_frame.provenance.class,ProvenanceClass::Synthetic); + let foreign=c5_input(&payload,sanitized); + assert!(canonicalize_esp32_with_format(foreign,format).is_err()); + for forbidden in [0x01,0x02,0x04,0x08,0x40,0x80] { + let mut mutant=wire.clone();mutant[19]|=forbidden; + assert!(validate_adr018_native_format(&mutant,1,53,PpduType::HtLegacy,Adr018Flags::from_byte(mutant[19])).is_err()); + } + } +} +#[test] +fn c5_actual_wire_metadata_with_explicitly_synthetic_iq_accepts_advisory_sync() { + // Physical receipt: 2026-11-10 Node23, 142B, 53slots, 5240MHz, PPDU0, + // flags0x10, first_word_invalid0, exact C5L8/v1 suffix. IQ BELOW IS + // SYNTHETIC; no captured IQ existed or is represented as a wire replay. + let receipt:serde_json::Value=serde_json::from_str(include_str!("../../tests/fixtures/c5-node23-wire-metadata-20261110.json")).unwrap(); + let metadata=&receipt["variants"][0]["metadata"]; + assert_eq!(metadata["wire_bytes"],142);assert_eq!(metadata["flags_byte"],16); + assert_eq!(metadata["frequency_mhz"],5240);assert_eq!(receipt["raw_iq_or_derived_amplitudes_written_or_logged"],false); + let payload=bytes(53,-7,11);let mut wire=c5_datagram(&payload,false); + wire[4]=23;wire[8..12].copy_from_slice(&5240u32.to_le_bytes());wire[19]=0x10; + let mut i=c5_input(&payload,false);i.node_id=23;i.frequency_hz=5_240_000_000; + i.flags=Adr018Flags::from_byte(0x10); + assert_eq!(wire.len(),142);assert_eq!(&wire[126..],&[b'C',b'5',b'L',b'8',1,8,1,1,1,1,0,20,1,0,106,0]); + let format=validate_adr018_native_format(&wire,1,53,i.ppdu_type,i.flags).unwrap(); + let packet=canonicalize_esp32_with_format(i,format).unwrap(); + assert_eq!(packet.native_iq_wire.as_deref(),Some(payload.as_slice())); + assert_eq!((packet.source_id,packet.frequency_hz),(23,5_240_000_000)); + assert_eq!(packet.grid_id,C5_LLTF8_V1_GRID);assert!(packet.adr018_flags.ieee802154_sync_valid); + assert_eq!(packet.clock.kind,ClockKind::ReceiverOnly);assert!(!packet.temporal_sample_rate_known); + assert_eq!(packet.native_frame.provenance.class,ProvenanceClass::Synthetic); +} + +#[test] +fn c5_all_256_flag_bytes_are_bound_to_exact_sanitation_and_known_metadata() { + for sanitized in [false,true] { + let mut payload=bytes(53,7,-11);if sanitized {payload[..4].fill(0);} + for flag_byte in 0u8..=255 { + let mut wire=c5_datagram(&payload,sanitized);wire[19]=flag_byte; + let flags=Adr018Flags::from_byte(flag_byte); + let result=validate_adr018_native_format(&wire,1,53,PpduType::HtLegacy,flags); + let allowed=flag_byte & !0x30 == 0 && flags.first_word_sanitized==sanitized; + assert_eq!(result.is_ok(),allowed,"flags={flag_byte:02x} sanitized={sanitized}"); + if let Ok(format)=result { + let mut i=c5_input(&payload,sanitized);i.flags=flags; + let packet=canonicalize_esp32_with_format(i,format).unwrap(); + assert_eq!(packet.adr018_flags.to_byte(),flag_byte); + assert_eq!(packet.clock.kind,ClockKind::ReceiverOnly); + assert!(!packet.temporal_sample_rate_known); + } + } + } +} +#[test] +fn legacy64_and_he256_sync_flag_keep_existing_grids_iq_features_and_clock() { + for bins in [64,256] { + let payload=bytes(bins,-9,12); + let plain=canonicalize_esp32(input(&payload,bins)).unwrap(); + let mut synced_input=input(&payload,bins);synced_input.flags.ieee802154_sync_valid=true; + let synced=canonicalize_esp32(synced_input).unwrap(); + assert_eq!(plain.grid_id,synced.grid_id); + assert_eq!(plain.native_frame.native_iq,synced.native_frame.native_iq); + assert_eq!(plain.native_frame.valid_mask,synced.native_frame.valid_mask); + assert_eq!(plain.amplitudes,synced.amplitudes); + assert_eq!(plain.clock,synced.clock);assert_eq!(synced.clock.kind,ClockKind::ReceiverOnly); + assert!(synced.adr018_flags.ieee802154_sync_valid); + assert!(!synced.temporal_sample_rate_known && !synced.phase_consumed); + } +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store.rs index 7661bcfbb9..a8b28504da 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store.rs @@ -41,6 +41,7 @@ pub struct RecoveryStore { installation: String, key: Option>, operator_key: Option>, + variable_key: Option>, serial: Mutex<()>, } fn id(value: &str) -> bool { @@ -123,7 +124,14 @@ impl RecoveryStore { if self.directory!=self.owner_directory.join("room-learner-recovery"){return Err("recovery_profile_scope_invalid".into());} let directory = self.directory.join("operator-eight-step-v1"); private_directory(&directory)?; - Ok(Self { directory, owner_directory:self.owner_directory.clone(), owner:self.owner.clone(), installation:self.installation.clone(), key:self.operator_key.clone(), operator_key:None, serial:Mutex::new(()) }) + Ok(Self { directory, owner_directory:self.owner_directory.clone(), owner:self.owner.clone(), installation:self.installation.clone(), key:self.operator_key.clone(), operator_key:None, variable_key:None, serial:Mutex::new(()) }) + } + pub(crate) fn variable_sources_scope(&self) -> Result { + let mut scoped = self.operator_eight_scope()?; + scoped.directory = self.directory.join("operator-variable-sources-v2"); + scoped.key = self.variable_key.clone(); + private_directory(&scoped.directory)?; + Ok(scoped) } pub fn new( data_dir: &Path, @@ -197,6 +205,18 @@ impl RecoveryStore { let result = aead::UnboundKey::new(&aead::AES_256_GCM, &material).map(aead::LessSafeKey::new).map(std::sync::Arc::new).map_err(|_| "recovery_key_unavailable"); material.fill(0); result }).transpose()?; + let variable_key = seed.map(|seed| { + let mut info = Vec::new(); + for item in [b"ruview.capture-recovery.operator-variable-sources.aes256gcm.v2".as_slice(), owner.as_bytes(), installation.as_bytes()] { + info.extend_from_slice(&(item.len() as u32).to_be_bytes()); info.extend_from_slice(item); + } + let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, b"ruview.capture-recovery.hkdf.v1"); + let prk = salt.extract(seed); let infos = [info.as_slice()]; + let okm = prk.expand(&infos, &aead::AES_256_GCM).map_err(|_| "recovery_key_unavailable")?; + let mut material = [0u8; 32]; okm.fill(&mut material).map_err(|_| "recovery_key_unavailable")?; + let result = aead::UnboundKey::new(&aead::AES_256_GCM, &material).map(aead::LessSafeKey::new).map(std::sync::Arc::new).map_err(|_| "recovery_key_unavailable"); + material.fill(0); result + }).transpose()?; Ok(Self { directory, owner_directory:owned, @@ -204,6 +224,7 @@ impl RecoveryStore { installation: installation.into(), key, operator_key, + variable_key, serial: Mutex::new(()), }) } @@ -255,7 +276,7 @@ impl RecoveryStore { return Err("recovery_owner_mismatch".into()); } private_directory(&owned.join("room-learner-recovery"))?; - if self.directory!=owned.join("room-learner-recovery")&&self.directory!=owned.join("room-learner-recovery/operator-eight-step-v1"){return Err("recovery_profile_scope_invalid".into());} + if self.directory!=owned.join("room-learner-recovery")&&self.directory!=owned.join("room-learner-recovery/operator-eight-step-v1")&&self.directory!=owned.join("room-learner-recovery/operator-variable-sources-v2"){return Err("recovery_profile_scope_invalid".into());} private_directory(&self.directory) } /// Non-repairing owner validation for read-scoped status discovery. diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store_tests.rs index f96e72822a..8bc271381c 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/recovery_store_tests.rs @@ -379,3 +379,24 @@ fn operator_profile_scope_preserves_old_bytes_and_uses_a_separate_key_without_re fs::write(new.directory.join(FILE),valid_new).unwrap(); assert!(new.operator_eight_scope().is_err()); } + +#[test] +fn variable_profile_recovery_preserves_both_old_namespaces_and_rejects_cross_profile_ciphertext() { + let (_t,old)=fixture(Some(&[7;32])); + let operator=old.operator_eight_scope().unwrap(); + old.save(&descriptor(),b"synthetic legacy",NOW).unwrap(); + operator.save(&descriptor(),b"synthetic three-source operator",NOW).unwrap(); + let old_bytes=fs::read(old.directory.join(FILE)).unwrap(); + let operator_bytes=fs::read(operator.directory.join(FILE)).unwrap(); + let variable=old.variable_sources_scope().unwrap(); + assert!(variable.inspect().unwrap().is_none()); + variable.save(&descriptor(),b"synthetic variable-source operator",NOW).unwrap(); + assert_eq!(variable.load(NOW+1).unwrap().unwrap().plaintext,b"synthetic variable-source operator"); + for bytes in [&old_bytes,&operator_bytes] { + fs::write(variable.directory.join(FILE),bytes).unwrap(); + assert!(variable.load(NOW+1).is_err()); + } + assert_eq!(fs::read(old.directory.join(FILE)).unwrap(),old_bytes); + assert_eq!(fs::read(operator.directory.join(FILE)).unwrap(),operator_bytes); + assert!(variable.variable_sources_scope().is_err()); +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition.rs index e8344de80c..f8218bdafb 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition.rs @@ -46,10 +46,13 @@ impl ExperimentalPlanId { } } } -/// A frozen receiver-cadence study band, NOT a source measurement clock or -/// scientific adequacy claim. Actual packet intervals/rate must also fit it. +/// Frozen receiver-observation policies, never a source measurement clock or +/// scientific adequacy claim. Hz variants constrain each arrival interval; +/// Arrival18To22Burst200MsV1 bounds gaps and observed window/period rates while +/// retaining every original arrival, including delivery/scheduling bursts. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] pub enum ReceiverCadenceBand { + Arrival18To22Burst200MsV1, Hz30To36, Hz45To55, } @@ -61,6 +64,7 @@ impl ReceiverCadenceBand { } fn range(self) -> (u64, u64, u64) { match self { + Self::Arrival18To22Burst200MsV1 => (18_000, 22_000, 200), Self::Hz30To36 => (30_000, 36_000, 50), Self::Hz45To55 => (45_000, 55_000, 35), } @@ -160,7 +164,11 @@ impl AcquisitionPlan { return Err("acquisition_cadence_source_binding".into()); } let (target_ms, slots) = id.dimensions(); - let max_ms = if target_ms == 3900 { + let arrival_profile = cadences.iter().any(|(_,band)|*band==ReceiverCadenceBand::Arrival18To22Burst200MsV1); + if arrival_profile && (target_ms != 2000 || cadences.iter().any(|(_,band)|*band!=ReceiverCadenceBand::Arrival18To22Burst200MsV1)) { + return Err("acquisition_receiver_arrival_profile_requires_uniform_native2s_policy".into()); + } + let max_ms = if arrival_profile { 2200 } else if target_ms == 3900 { 4000 } else { target_ms + 50 @@ -178,13 +186,7 @@ impl AcquisitionPlan { || spec.link_index != 0 || !native::is_supported_frequency_hz(spec.center_frequency_hz) || spec.bandwidth_hz != 20_000_000 - || !(0..=3).any(|ppdu| { - spec.grid_id - == format!( - "ant1-bins{}-ppdu{ppdu}-usable-drop2-linear-v2", - if ppdu == 0 { 64 } else { 256 } - ) - }) + || !native::supported_feature_grid(&spec.grid_id,spec.center_frequency_hz) { return Err("acquisition_requires_existing_native56_source".into()); } @@ -214,7 +216,7 @@ impl AcquisitionPlan { receiver_cadence: *band, min_rows, max_rows, - min_packet_interval_ns: NS_PER_MILLI_HZ / hi, + min_packet_interval_ns: if arrival_profile { 1 } else { NS_PER_MILLI_HZ / hi }, max_gap_ns: gap_ms * NS_PER_MS, }); } @@ -309,8 +311,8 @@ impl AcquisitionPlan { target_span_ms: target_ms, min_observed_span_ms: target_ms, max_observed_span_ms: max_ms, - max_pairwise_receiver_skew_ms: 50, - max_first_packet_delay_ms: 100, + max_pairwise_receiver_skew_ms: if arrival_profile { 200 } else { 50 }, + max_first_packet_delay_ms: if arrival_profile { 200 } else { 100 }, slots_per_trial: slots, schedule, sources, @@ -431,8 +433,11 @@ impl WindowInputPolicy { ) -> Result<(&SourceSpec, &SourceWindowPolicy), String> { let (spec, policy) = self.validate_packet_source_identity(p)?; let (lo, hi, _) = policy.receiver_cadence.range(); - if p.receiver_sample_rate_hz < lo as f64 / 1000. - || p.receiver_sample_rate_hz > hi as f64 / 1000. + // Instantaneous arrival spacing is a diagnostic, not a source clock. + // The explicit burst-aware profile checks observed window/whole-period + // rates, every original arrival, gap bounds and row capacity instead. + if policy.receiver_cadence != ReceiverCadenceBand::Arrival18To22Burst200MsV1 && (p.receiver_sample_rate_hz < lo as f64 / 1000. + || p.receiver_sample_rate_hz > hi as f64 / 1000.) { return Err("acquisition_cadence_changed".into()); } @@ -677,12 +682,12 @@ impl NativeWindowAssembler { ) -> Result { let seed = AcquisitionPlan::build( contract.context().clone(), - ExperimentalPlanId::Native2000msSlots8, + if contract.is_variable_sources() { ExperimentalPlanId::Native2000msSlots4 } else { ExperimentalPlanId::Native2000msSlots8 }, &contract - .context() - .sources + .native_window_policy() + .source_policies() .iter() - .map(|s| (s.source_id, ReceiverCadenceBand::Hz30To36)) + .map(|s| (s.source_id, s.receiver_cadence)) .collect::>(), )?; let mut result = Self::new(seed, run_id)?; @@ -708,7 +713,7 @@ impl NativeWindowAssembler { .collect::>(); let seed = AcquisitionPlan::build( policy.context.clone(), - ExperimentalPlanId::Native2000msSlots8, + if policy.sources.iter().all(|s|s.receiver_cadence==ReceiverCadenceBand::Arrival18To22Burst200MsV1) { ExperimentalPlanId::Native2000msSlots4 } else { ExperimentalPlanId::Native2000msSlots8 }, &bands, )?; let mut result = Self::new(seed, run_id)?; @@ -1054,6 +1059,27 @@ impl NativeWindowAssembler { if self.failed { return Err("temporal_failed_fences".into()); } + Ok(self.replay_fence_metadata()) + } + /// Only the stopped, unfrozen FullRun Retry owner may call this. This is + /// denial/replay metadata, never an export of failed rows or window credit. + /// Ordinary checkpoint/export keeps rejecting a failed assembler above. + pub(super) fn stopped_retry_fence_checkpoint( + &self, + budget:&crate::room_learner::temporal_model_input::managed::execution::full_run::ReplayFenceBudget, + )->Result { + let WindowIdentityMode::Managed {contract,binding_sha256,..}=&self.identity else { + return Err("temporal_retry_managed_fences_required".into()); + }; + budget.matches_native_policy(&self.policy)?; + let snapshot=self.replay_fence_metadata(); + // Reuse the exact bounded source/frame/sequence validation of restore. + // The scratch assembler has no rows, runtime, filesystem or authority. + let mut verifier=Self::managed(contract.clone(),binding_sha256.clone(),self.run_id.clone())?; + verifier.restore_full_run_prefix_fences(snapshot.clone(),self.next,budget)?; + Ok(snapshot) + } + fn replay_fence_metadata(&self) -> AssemblerCheckpoint { let mut watermarks = self .watermarks .iter() @@ -1066,12 +1092,12 @@ impl NativeWindowAssembler { .map(|(id, f)| (*id, f.to_string())) .collect::>(); frames.sort(); - Ok(AssemblerCheckpoint { + AssemblerCheckpoint { next: self.next, last_end_ns: self.last_end_ns, watermarks, frames, - }) + } } pub(crate) fn restore_prefix_fences( &mut self, diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition_tests.rs index 87111e709c..d9dcaee4bb 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_acquisition_tests.rs @@ -26,6 +26,23 @@ fn context(count: u8) -> CaptureContext { .collect(), } } +#[test] +fn c5_claimed_feature_grid_plan_keeps_exact_frequency_and_rejects_unversioned_shapes() { + let mut ctx=context(3); + for source in &mut ctx.sources { + source.grid_id=super::super::native::C5_LLTF8_V1_GRID.into(); + source.center_frequency_hz=5_560_000_000; + } + let cadences=[(1,ReceiverCadenceBand::Hz30To36),(2,ReceiverCadenceBand::Hz30To36),(3,ReceiverCadenceBand::Hz30To36)]; + let p=AcquisitionPlan::build(ctx.clone(),ExperimentalPlanId::Native1000msSlots2,&cadences).unwrap(); + assert_eq!(p.context,ctx); + for mhz in [2437u64,5185,5955] { + let mut bad=ctx.clone();bad.sources[0].center_frequency_hz=mhz*1_000_000; + assert!(AcquisitionPlan::build(bad,ExperimentalPlanId::Native1000msSlots2,&cadences).is_err()); + } + let mut bad=ctx;bad.sources[0].grid_id="ant1-bins53-ppdu0-usable-drop2-linear-v2".into(); + assert!(AcquisitionPlan::build(bad,ExperimentalPlanId::Native1000msSlots2,&cadences).is_err()); +} fn plan( count: u8, id: ExperimentalPlanId, diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_capture_quality.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_capture_quality.rs index db05dcddcd..39e3c71c5a 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_capture_quality.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_capture_quality.rs @@ -3,7 +3,7 @@ //! Seals alone grant no fit authority; the private owner must separately consume //! the complete durable producer prefix into its opaque fit-only admission. use super::*; -use crate::room_learner::temporal_acquisition::WindowInputPolicy; +use crate::room_learner::temporal_acquisition::{ReceiverCadenceBand, WindowInputPolicy}; use serde_json::{json, Value}; pub(super) const BRIDGE_POLICY: &str = "native-receiver-whole-train-period-v1;all-selected-packets;existing-cadence-gap-arrival-skew;confirmed-durable-seals;no-fit-authority"; @@ -138,8 +138,9 @@ impl QualityPart { // native policy, including its integer interval representation. if s.packets < 2 || s.last_ns < end - || intervals < span * u128::from(lo) / 1_000_000_000_000u128 - || span < intervals * u128::from(1_000_000_000_000u64 / hi) + || (policy.receiver_cadence != ReceiverCadenceBand::Arrival18To22Burst200MsV1 + && (intervals < span * u128::from(lo) / 1_000_000_000_000u128 + || span < intervals * u128::from(1_000_000_000_000u64 / hi))) { return Err("temporal_whole_period_cadence".into()); } @@ -445,9 +446,100 @@ pub(super) fn validate_parts_with_frozen( if complete.is_some_and(|v| v != frontier) || complete.is_some() && parts.is_empty() { return Err("temporal_quality_period_incomplete".into()); } + if native.source_policies().iter().any(|p|p.receiver_cadence==ReceiverCadenceBand::Arrival18To22Burst200MsV1) { + let target = schedule.episodes().get(episode).ok_or("temporal_quality_episode")? + .target_active_recording_ms.checked_mul(1_000_000).ok_or("temporal_quality_time")?; + if complete.is_some() || frontier >= target { + for policy in native.source_policies().iter().filter(|p| + p.receiver_cadence == ReceiverCadenceBand::Arrival18To22Burst200MsV1) + { + // A reservation tail can contain a permissible scheduling burst. + // Only a complete episode has whole-period rate authority. Resume + // gaps contribute neither a packet interval nor receiver span. + let mut intervals = 0u128; + let mut span = 0u128; + for part in parts.iter().filter(|p|p.observed_end_ns > p.mapping.observed_start_ns) { + let source = part.sources.iter().find(|s|s.source_id==policy.source_id) + .ok_or("temporal_quality_required_sources")?; + intervals = intervals.checked_add(u128::from(source.packets-1)).ok_or("temporal_quality_count")?; + span = span.checked_add(u128::from(source.last_ns-source.first_ns)).ok_or("temporal_quality_time")?; + } + let (lo,hi)=policy.receiver_cadence.rate_bounds_millihz(); + if intervals==0 || span==0 + || intervals < span*u128::from(lo)/1_000_000_000_000u128 + || span < intervals*u128::from(1_000_000_000_000u64/hi) + { return Err("temporal_whole_period_cadence".into()); } + } + } + } Ok(()) } +#[cfg(test)] +mod arrival_quality_regressions { + use super::*; + use crate::room_learner::managed_schedule_contract::LeadInPolicy; + const SECOND:u64=1_000_000_000; + fn schedule(variable:bool)->ManagedScheduleContract { + let mut context=crate::room_learner::temporal_model_input::managed::tests::context(); + if variable { + let mut extra=context.sources[2].clone();extra.source_id=4; + extra.device_id="esp32-node-4".into();extra.link_id="native-4".into();context.sources.push(extra); + } + ManagedScheduleContract::build(context,if variable {LeadInPolicy::OperatorVariableSourcesV2}else{LeadInPolicy::OperatorEightStepV1}).unwrap() + } + fn part(schedule:&ManagedScheduleContract,ordinal:u16,start:u64,end:u64,receiver:u64,packets:u64)->QualityPart { + let bound=schedule.bind_episode_start("synthetic-rate-parts",0,0,ordinal,None).unwrap(); + QualityPart {mapping:ObservedSegmentMap{segment_ordinal:ordinal,session_id:bound.session_id().into(), + receiver_epoch:format!("synthetic-epoch-{ordinal}"),clock_anchor_ns:receiver,receiver_start_ns:receiver,observed_start_ns:start}, + observed_end_ns:end,sources:schedule.context().sources.iter().map(|s|SourceQuality { + source_id:s.source_id,first_ns:receiver,last_ns:receiver+end-start, + first_sequence:1+u64::from(ordinal)*100_000,last_sequence:u64::from(ordinal)*100_000+packets, + packets,maximum_gap_ns:200_000_000,minimum_interval_ns:10_000}).collect()} + } + #[test] + fn arrival_partial_tail_burst_is_valid_but_completed_frontier_and_restored_period_enforce_rate() { + let schedule=schedule(true); + let prefix=part(&schedule,0,0,2_400_000_000,SECOND,58); + assert!(validate_parts(&[prefix.clone()],&schedule,"synthetic-rate-parts",0,None,4*SECOND).is_ok()); + let complete=part(&schedule,0,0,600*SECOND,SECOND,12_001); + assert!(validate_parts(&[complete.clone()],&schedule,"synthetic-rate-parts",0,Some(600*SECOND),601*SECOND).is_ok()); + let mut too_dense=complete.clone();for source in &mut too_dense.sources {source.packets=14_401;source.last_sequence=14_401;} + assert_eq!(validate_parts(&[too_dense.clone()],&schedule,"synthetic-rate-parts",0,None,601*SECOND).unwrap_err(),"temporal_whole_period_cadence"); + let restored:Vec=serde_json::from_slice(&serde_json::to_vec(&vec![too_dense]).unwrap()).unwrap(); + assert_eq!(validate_parts(&restored,&schedule,"synthetic-rate-parts",0,Some(600*SECOND),601*SECOND).unwrap_err(),"temporal_whole_period_cadence"); + for case in 0..4 { + let mut invalid=prefix.clone();match case { + 0=>invalid.sources[0].maximum_gap_ns=200_000_001, + 1=>invalid.sources[0].last_sequence=0, + 2=>{invalid.sources.pop();}, + _=>invalid.sources[0].last_ns-=1, + } + assert!(validate_parts(&[invalid],&schedule,"synthetic-rate-parts",0,None,4*SECOND).is_err(),"prefix structural control {case}"); + } + } + #[test] + fn arrival_resumed_period_sums_only_each_positive_parts_intervals_and_span() { + let schedule=schedule(true); + let high=part(&schedule,0,0,100*SECOND,SECOND,2401); + let low=part(&schedule,1,100*SECOND,600*SECOND,1001*SECOND,9601); + assert!(validate_parts(&[high,low],&schedule,"synthetic-rate-parts",0,Some(600*SECOND),1501*SECOND).is_ok()); + let exact0=part(&schedule,0,0,300*SECOND,SECOND,5401); + let exact1=part(&schedule,1,300*SECOND,600*SECOND,1001*SECOND,5401); + assert!(validate_parts(&[exact0.clone(),exact1.clone()],&schedule,"synthetic-rate-parts",0,Some(600*SECOND),1301*SECOND).is_ok(),"paused gap must not lower the aggregate rate"); + let mut one_interval_short=exact0; + for s in &mut one_interval_short.sources {s.packets-=1;s.last_sequence-=1;} + assert_eq!(validate_parts(&[one_interval_short,exact1],&schedule,"synthetic-rate-parts",0,Some(600*SECOND),1301*SECOND).unwrap_err(),"temporal_whole_period_cadence","summing packet counts before subtracting one would incorrectly pass"); + } + #[test] + fn old_interval_strict_profile_still_rejects_bad_partial_part_rate() { + let schedule=schedule(false); + let mut prefix=part(&schedule,0,0,2_400_000_000,SECOND,58); + for s in &mut prefix.sources {s.maximum_gap_ns=50_000_000;s.minimum_interval_ns=30_000_000;} + assert_eq!(validate_parts(&[prefix],&schedule,"synthetic-rate-parts",0,None,4*SECOND).unwrap_err(),"temporal_whole_period_cadence"); + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum TemporalCaptureStage { Preparing, @@ -1220,13 +1312,15 @@ impl TemporalTrainCapture { || !self.is_full_run() || self.workflow.full_run.as_ref().is_some_and(|m| m.is_frozen() || m.is_complete()) { return Err("temporal_retry_requires_stopped_capture".into()); } + let budget=self.workflow.full_run.as_ref().ok_or("temporal_full_run_required")? + .policy.replay_fence_budget(&self.workflow.session.managed.as_ref().ok_or("managed_session_required")?.binding)?; let state = FailedRetryState { generation:self.public_generation_id.clone(), schedule:self.schedule.sha256().into(), created_at_ms:self.workflow.descriptor.created_at_ms, expires_at_ms:self.workflow.descriptor.expires_at_ms, durable_windows:self.workflow.durable_windows, seals:self.durable_seals, accepted_prefix_sha256:self.workflow.async_state.as_ref().and_then(|state|state.row_prefix_sha256.clone()), accepted_seal_digests:self.workflow.bridge.as_ref().map_or_else(Vec::new,|b|b.seals.iter().take(self.durable_seals).map(|seal|seal.sha256.clone()).collect()), - fences:self.workflow.session.assembler.fence_checkpoint()?, source_high:self.workflow.source_high.clone(), + fences:self.workflow.session.assembler.stopped_retry_fence_checkpoint(&budget)?, source_high:self.workflow.source_high.clone(), }; if self.failure.is_none() { self.invalidate("temporal_retry_stopped_capture"); } Ok(state) diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_checkpoint_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_checkpoint_tests.rs index 5ca5f4d414..f33b4161d5 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_checkpoint_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_checkpoint_tests.rs @@ -1,6 +1,33 @@ use super::super::tests::{commit_next, setup, start}; use super::*; #[test] +fn variable_first_real_checkpoint_keeps_valid_window_and_bursty_reservation_tail() { + use crate::room_learner::managed_schedule_contract::LeadInPolicy; + let dir=tempfile::tempdir().unwrap(); + let mut context=crate::room_learner::temporal_model_input::managed::tests::context(); + let mut extra=context.sources[2].clone();extra.source_id=4;extra.device_id="esp32-node-4".into();extra.link_id="native-4".into();context.sources.push(extra); + let store=RecoveryStore::new(&dir.path().join(&context.owner_scope).join("SensingServer"),&context.owner_scope,&context.installation_id,Some(&[7;32])).unwrap(); + let plan=ManagedScheduleContract::build(context,LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + let mut capture=TemporalTrainCapture::prepare(plan,"synthetic-variable-first-checkpoint".into(),FitConfig::for_source_count(4),1_000_000_000,&store).unwrap(); + let start=2_000_000_000; + capture.start_segment("synthetic-variable-checkpoint",start,&store).unwrap(); + let mut times=(0..=40).map(|i|i*50_000_000u64).collect::>();times.push(2_200_000_000); + for i in 0..16 {times.push(2_399_850_000+i*10_000);} + for (index,relative) in times.iter().copied().enumerate() { + for source in 1..=4 { + let now=start+relative; + capture.ingest(&super::super::tests::bridge_packet(source,index as u32+1,now),now,&store).unwrap(); + } + } + let now=start+2_400_000_000; + let loaded=store.load_temporal(now).unwrap().unwrap();let prefix=loaded.prefix.unwrap(); + assert_eq!(prefix.window_count(),1); + assert!(validated_prefix(prefix.bytes(),prefix.descriptor(),now).is_ok()); + let restored=TemporalTrainCapture::cold_restore(&store,capture.context(),now,"synthetic-variable-restored",now).unwrap(); + assert_eq!(restored.snapshot()["durable_windows"],1); + assert_eq!(capture.snapshot()["durable_windows"],1); +} +#[test] fn real_aead_initial_barrier_and_ambiguous_save_fail_closed_without_new_authority() { let (_dir, store, mut w) = setup(); assert!(w diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation.rs index 16c5c7661e..5b9cfd217d 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation.rs @@ -119,7 +119,7 @@ pub(super) struct TemporalEvaluationIdentityData { pub execution_policy_sha256: String, pub schedule_sha256: String, pub configured_fit_sha256: String, - pub source_ids: [u8; 3], + pub source_ids: Vec, } impl TemporalEvaluationIdentityData { fn validate_data(&self) -> Result<(), String> { @@ -143,6 +143,7 @@ impl TemporalEvaluationIdentityData { || self.artifact_kind != MODEL_KIND || self.prefix_schema != PREFIX_SCHEMA || self.metadata_kind != METADATA_KIND + || !(2..=8).contains(&self.source_ids.len()) || self.source_ids.windows(2).any(|w| w[0] >= w[1]) { return invalid(); @@ -216,7 +217,7 @@ pub(super) struct TemporalTrainProofBodyData { pub declared_episodes_per_condition: [u16; 4], pub accepted_train_commitment: CommitmentData, pub freeze_prepare_receiver_ns: String, - pub source_floors: [FrozenSourceFloorData; 3], + pub source_floors: Vec, pub claims: DiagnosticClaimsData, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -257,6 +258,7 @@ impl TemporalTrainProofData { .len() != if self.is_operator_eight_step() { 4 } else { 7 } || b.train_seal_sha256s.len() != if self.is_operator_eight_step() { 4 } else { 7 } + || b.source_floors.len() != b.identity.source_ids.len() || b.train_windows != 64 || b.windows_per_condition != [16; 4] || b.declared_episodes_per_condition != if self.is_operator_eight_step() { [1; 4] } else { [1, 2, 2, 2] } @@ -264,7 +266,7 @@ impl TemporalTrainProofData { { return invalid(); } - for (floor, id) in b.source_floors.iter().zip(b.identity.source_ids) { + for (floor, id) in b.source_floors.iter().zip(b.identity.source_ids.iter().copied()) { let ns = decimal(&floor.receiver_ns)?; if floor.source_id != id || floor.sequence > u32::MAX as u64 || ns == 0 || ns > cut { return invalid(); @@ -301,7 +303,7 @@ pub(super) struct TemporalHeldOutBodyData { pub complete_commitment: CommitmentData, pub complete_prepare_receiver_ns: String, pub complete_persisted_receiver_ns: String, - pub final_source_fences: [FinalSourceFenceData; 3], + pub final_source_fences: Vec, pub held_out_windows: u16, pub windows_per_condition: [u16; 4], pub declared_episodes_per_condition: [u16; 4], @@ -350,6 +352,7 @@ impl TemporalHeldOutEvidenceData { .len() != if self.is_operator_eight_step() { 4 } else { 8 } || b.held_out_seal_sha256s.len() != if self.is_operator_eight_step() { 4 } else { 8 } + || b.final_source_fences.len() != b.identity.source_ids.len() || b.held_out_windows != if self.is_operator_eight_step() { 16 } else { 64 } || b.windows_per_condition != if self.is_operator_eight_step() { [4; 4] } else { [16; 4] } || b.declared_episodes_per_condition != if self.is_operator_eight_step() { [1; 4] } else { [2; 4] } @@ -366,7 +369,7 @@ impl TemporalHeldOutEvidenceData { { return invalid(); } - for (floor, id) in b.final_source_fences.iter().zip(b.identity.source_ids) { + for (floor, id) in b.final_source_fences.iter().zip(b.identity.source_ids.iter().copied()) { let ns = decimal(&floor.receiver_ns)?; let frame = decimal_frame(&floor.native_frame_id)?; let expected = diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_data_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_data_tests.rs index 5a2cce8a0e..b3f350c5a9 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_data_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_data_tests.rs @@ -35,7 +35,7 @@ fn identity() -> TemporalEvaluationIdentityData { execution_policy_sha256: fixture_sha(7), schedule_sha256: fixture_sha(8), configured_fit_sha256: fixture_sha(9), - source_ids: [15, 16, 17], + source_ids: vec![15, 16, 17], } } fn token(id: &TemporalEvaluationIdentityData, revision: u16) -> CommitmentData { @@ -52,11 +52,11 @@ fn train() -> TemporalTrainProofData { let cut = "1800000900000000000".to_owned(); let body = TemporalTrainProofBodyData { accepted_train_commitment: token(&id, 78), - source_floors: std::array::from_fn(|i| FrozenSourceFloorData { + source_floors: (0..3).map(|i| FrozenSourceFloorData { source_id: id.source_ids[i], sequence: 10_000, receiver_ns: "1800000899999000000".into(), - }), + }).collect(), identity: id, training_data_sha256: fixture_sha(20), training_evidence_sha256: fixture_sha(21), @@ -92,7 +92,7 @@ fn held(t: &TemporalTrainProofData) -> TemporalHeldOutEvidenceData { complete_commitment: token(&t.body.identity, 160), complete_prepare_receiver_ns: "1800001300000000000".into(), complete_persisted_receiver_ns: "1800001300000000000".into(), - final_source_fences: std::array::from_fn(|i| { + final_source_fences: (0..3).map(|i| { let id = t.body.identity.source_ids[i]; let ns = 1_800_001_299_999_000_000u64; FinalSourceFenceData { @@ -102,7 +102,7 @@ fn held(t: &TemporalTrainProofData) -> TemporalHeldOutEvidenceData { native_frame_id: ((u128::from(ns) << 40) | (u128::from(id) << 32) | 20_000) .to_string(), } - }), + }).collect(), held_out_windows: 64, windows_per_condition: [16; 4], declared_episodes_per_condition: [2; 4], @@ -335,7 +335,7 @@ fn bounded_max_width_metadata_fixture_fits_without_relaxing_reader_limit() { id.installation_id = escaped.clone(); id.run = escaped.clone(); id.original_deadline.id = escaped.clone(); - id.source_ids = [253, 254, 255]; + id.source_ids = vec![253, 254, 255]; id.original_deadline.expires_at_unix_ms = u64::MAX / 1_000_000 + 1; id.original_deadline.created_at_unix_ms = id.original_deadline.expires_at_unix_ms - TTL_MS; t.body.freeze_prepare_receiver_ns = (u64::MAX - 1_000_000_000_000).to_string(); @@ -347,7 +347,7 @@ fn bounded_max_width_metadata_fixture_fits_without_relaxing_reader_limit() { .body .source_floors .iter_mut() - .zip(t.body.identity.source_ids) + .zip(t.body.identity.source_ids.iter().copied()) { floor.source_id = id; floor.sequence = u32::MAX as u64 - 100_000; diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_projection.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_projection.rs index 4c3ff453f2..be1c121a79 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_projection.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_evaluation_projection.rs @@ -366,9 +366,7 @@ impl PendingTemporalEvidenceSource { .sources .iter() .map(|s| s.source_id) - .collect::>() - .try_into() - .map_err(|_| "temporal_evaluation_three_sources_required")?, + .collect::>(), }; let seals = &w .bridge @@ -401,9 +399,7 @@ impl PendingTemporalEvidenceSource { sequence: *seq, receiver_ns: ns.to_string(), }) - .collect::>() - .try_into() - .map_err(|_| "temporal_evaluation_three_sources_required")?, + .collect::>(), claims: data::DiagnosticClaimsData::diagnostic_only(), })?; let held = if self.held_out { @@ -466,9 +462,7 @@ impl PendingTemporalEvidenceSource { | u128::from(*seq)) .to_string(), }) - .collect::>() - .try_into() - .map_err(|_| "temporal_evaluation_three_sources_required")?, + .collect::>(), held_out_windows: if operator { 16 } else { 64 }, windows_per_condition: if operator { [4; 4] } else { [16; 4] }, declared_episodes_per_condition: if operator { [1; 4] } else { [2; 4] }, diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_fit_admission.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_fit_admission.rs index a496bcb5fc..ff20be056e 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_fit_admission.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_fit_admission.rs @@ -185,7 +185,7 @@ fn identity( prefix_schema:if w.full_run.is_some(){full_run::PREFIX_SCHEMA}else{"ruview.room-learner.temporal-runtime-prefix.v2"}, metadata_kind:if w.full_run.is_some(){full_run::META_KIND}else{"temporal-prefix-commitment-v1"}, continuation_policy:w.full_run.as_ref().map(|m|m.policy.sha256().into()), - operator_profile:schedule.is_operator_eight_step().then(||"native-2s-three-source-56bin-operator-eight-step-v1".into()), + operator_profile:schedule.is_operator_eight_step().then(||schedule.profile_id().into()), }) } pub(super) fn current_identity( diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_full_run.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_full_run.rs index 134d2c5ee3..7279b66491 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_full_run.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_full_run.rs @@ -47,15 +47,17 @@ impl ContinuationPolicy { let schedule = binding.contract()?; let c = schedule.counts(); let context = schedule.context(); - if context.sources.len() != 3 + let variable = schedule.is_variable_sources(); + let source_count = context.sources.len(); + if (if variable { !(2..=8).contains(&source_count) } else { source_count != 3 }) || context.sources.iter().any(|s| s.feature_count != 56) || binding.native.target_span_ms() != 2000 - || binding.native.source_policies().len() != 3 + || binding.native.source_policies().len() != source_count || binding .native .source_policies() .iter() - .any(|s| s.receiver_cadence != ReceiverCadenceBand::Hz30To36 || s.max_rows != 77) + .any(|s| s.receiver_cadence != if variable { ReceiverCadenceBand::Arrival18To22Burst200MsV1 } else { ReceiverCadenceBand::Hz30To36 } || s.max_rows != if variable { 52 } else { 77 }) || ( c.train_episodes, c.held_out_episodes, @@ -63,7 +65,7 @@ impl ContinuationPolicy { c.held_out_windows, c.total_windows, ) != if schedule.is_operator_eight_step(){(4,4,64,16,80)}else{(7,8,64,64,128)} - || schedule.resources().max_numeric_values != if schedule.is_operator_eight_step(){1_034_880}else{1_655_808} + || schedule.resources().max_numeric_values != if variable { source_count * 52 * 56 * 80 } else if schedule.is_operator_eight_step(){1_034_880}else{1_655_808} || schedule.resources().max_numeric_values > 2_000_000 { return Err("temporal_full_run_engineering_profile_unsupported".into()); @@ -335,7 +337,7 @@ impl VerifiedFitRecordData { || b.owner_scope != c.owner_scope || b.installation_id != c.installation_id || b.context_digest != c.digest() - || b.operator_profile.as_deref() != binding.contract()?.is_operator_eight_step().then_some("native-2s-three-source-56bin-operator-eight-step-v1") + || b.operator_profile != { let schedule = binding.contract()?; schedule.is_operator_eight_step().then(||schedule.profile_id().to_owned()) } || b.run.is_empty() || b.run.len() > 256 || !b.run.is_ascii() @@ -1117,7 +1119,9 @@ impl ContinuationPolicy { let attempts=self.body.max_total_windows.checked_add(self.body.max_global_gaps).ok_or("temporal_full2_fence_capacity")?; let per_attempt=binding.native.source_policies().iter().try_fold(0usize,|n,s|n.checked_add(s.max_rows)).ok_or("temporal_full2_fence_capacity")?; let max_frames=attempts.checked_mul(per_attempt).ok_or("temporal_full2_fence_capacity")?; - if attempts!=256||per_attempt!=231||max_frames!=59_136{return Err("temporal_full2_fence_capacity".into());} + let variable = binding.contract()?.is_variable_sources(); + let expected_rows = if variable { binding.native.context().sources.len() * 52 } else { 231 }; + if attempts!=256||per_attempt!=expected_rows||max_frames!=256 * expected_rows{return Err("temporal_full2_fence_capacity".into());} Ok(ReplayFenceBudget{max_frames,native_policy_sha256:hash(&binding.native)?}) } } @@ -1130,3 +1134,25 @@ impl FullRunState { pub(super) fn public_verified_fit(&self)->Option<&VerifiedFitRecordData>{let verified=self.verified.as_ref()?;let data=self.frozen.as_ref()?;if self.owner.is_none()||data!=&verified.record{return None}Some(data)} pub(super) fn public_complete(&self,current:Option<&TemporalToken>)->Option<&held_out::FullCompleteRecordData>{let fact=self.completed.as_ref()?;let data=self.complete.as_ref()?;if current!=Some(&fact.token)||data.sha256!=fact.record_sha256{return None}Some(data)} } + +#[cfg(test)] +mod variable_source_tests { + use super::*; + #[test] + fn variable_profile_continuation_and_replay_budget_bind_all_sources() { + use crate::room_learner::managed_schedule_contract::{LeadInPolicy,ManagedScheduleContract}; + for count in 2..=8u8 { + let mut context = crate::room_learner::temporal_model_input::managed::tests::context(); + let template = context.sources[0].clone(); + context.sources = (1..=count).map(|source_id| crate::room_learner::observation::SourceSpec { + source_id,device_id:format!("esp32-node-{source_id}"),link_id:format!("native-{source_id}"),..template.clone() + }).collect(); + let schedule = ManagedScheduleContract::build(context,LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + let binding = ManagedBinding::build(&schedule,FitConfig::for_source_count(usize::from(count))).unwrap(); + let policy = ContinuationPolicy::build(&binding).unwrap(); + policy.validate(&binding).unwrap(); + assert_eq!(policy.replay_fence_budget(&binding).unwrap().max_frames(),256*52*usize::from(count)); + assert_eq!(policy.body.native_profile.context().sources.len(),usize::from(count)); + } + } +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_held_out_capture.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_held_out_capture.rs index ee3c126a99..9ed692ca75 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_held_out_capture.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_held_out_capture.rs @@ -285,7 +285,7 @@ impl FullCompleteRecordData { now: u64, ) -> Result<(), String> { let body = &self.body; - let operator=fit.body.operator_profile.as_deref()==Some("native-2s-three-source-56bin-operator-eight-step-v1"); + let operator=matches!(fit.body.operator_profile.as_deref(),Some(crate::room_learner::managed_schedule_contract::OPERATOR_EIGHT_PROFILE | crate::room_learner::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE)); if fit.body.operator_profile.is_some() && !operator{return Err("temporal_full_complete_profile_changed".into());} let domain=if operator{OPERATOR_COMPLETE_DOMAIN}else{FULL_COMPLETE_DOMAIN}; let hashes = [ diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_live_driver.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_live_driver.rs index 7408618cb8..effbd04d5f 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_live_driver.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_live_driver.rs @@ -505,7 +505,7 @@ impl ContinuousTemporalInput { driver.activate();Ok(driver) } pub(crate) fn advance_selected_floors(&mut self,floors:&[(u8,u64,u64)],receiver_floor:u64)->Result<(),String>{ - if floors.len()!=3||floors.iter().any(|(id,seq,_)|*seq>u32::MAX as u64||!self.policy.context().sources.iter().any(|s|s.source_id==*id)){return Err("selected_source_floor_identity".into());} + if floors.len()!=self.policy.context().sources.len()||floors.iter().map(|s|s.0).ne(self.policy.context().sources.iter().map(|s|s.source_id))||floors.iter().any(|(id,seq,_)|*seq>u32::MAX as u64||!self.policy.context().sources.iter().any(|s|s.source_id==*id)){return Err("selected_source_floor_identity".into());} for(id,seq,time)in floors{let frame=(u128::from(*time)<<40)|(u128::from(*id)<<32)|u128::from(*seq);if let Some(old)=self.fences.get(id){if *seq Result { } fn band(s: &str) -> Result { match s { + "Arrival18To22Burst200MsV1" => Ok(ReceiverCadenceBand::Arrival18To22Burst200MsV1), "Hz30To36" => Ok(ReceiverCadenceBand::Hz30To36), "Hz45To55" => Ok(ReceiverCadenceBand::Hz45To55), _ => Err("temporal_cadence_band".into()), diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed.rs index 26635b07b4..7f188d5885 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed.rs @@ -288,14 +288,14 @@ impl TemporalTrainingSession { // Only the unchanged legacy fields' native-validation carrier is built; // managed identity/hash/schedule NEVER comes from this seed. let bands = schedule - .context() - .sources + .native_window_policy() + .source_policies() .iter() - .map(|s| (s.source_id, ReceiverCadenceBand::Hz30To36)) + .map(|s| (s.source_id, s.receiver_cadence)) .collect::>(); let plan = AcquisitionPlan::build( schedule.context().clone(), - ExperimentalPlanId::Native2000msSlots8, + if schedule.is_variable_sources() { ExperimentalPlanId::Native2000msSlots4 } else { ExperimentalPlanId::Native2000msSlots8 }, &bands, )?; let assembler = NativeWindowAssembler::managed(schedule, policy, run_id.clone())?; diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed_tests.rs index d0576b8b16..ac0f28909d 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_model_input_managed_tests.rs @@ -539,3 +539,102 @@ fn operator_training_partition_rejects_relabelled_validation_before_fitting(){ assert!(!session.fitted); } } + +#[test] +fn variable_profile_builds_bound_models_for_every_supported_source_count() { + for count in 2..=8u8 { + let mut c=context(); + let template=c.sources[0].clone(); + c.sources=(1..=count).map(|source_id| SourceSpec { source_id, device_id:format!("esp32-node-{source_id}"), link_id:format!("native-{source_id}"), ..template.clone() }).collect(); + let schedule=ManagedScheduleContract::build(c,LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + let session=TemporalTrainingSession::managed(schedule.clone(),"synthetic-variable-run".into(),FitConfig::for_source_count(usize::from(count))).unwrap(); + let binding=&session.managed.as_ref().unwrap().binding; + assert_eq!(binding.encoder.source_count,usize::from(count)); + assert_eq!(binding.native.source_policies().len(),usize::from(count)); + assert!(binding.native.source_policies().iter().all(|s|s.receiver_cadence==ReceiverCadenceBand::Arrival18To22Burst200MsV1&&s.max_rows==52)); + assert_eq!(binding.contract().unwrap().sha256(),schedule.sha256()); + } +} + +#[test] +fn variable_profile_assembles_four_c5_sources_with_bursty_twenty_hz_receiver_arrivals() { + use crate::room_learner::native::{C5_LLTF8_V1_GRID,validate_adr018_native_format,canonicalize_esp32_with_format}; + let mut c=context();let template=c.sources[0].clone(); + c.sources=(20..=23).map(|source_id|SourceSpec{source_id,device_id:format!("esp32-node-{source_id}"),link_id:format!("native-{source_id}"),grid_id:C5_LLTF8_V1_GRID.into(),center_frequency_hz:5_180_000_000,..template.clone()}).collect(); + let plan=ManagedScheduleContract::build(c,LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + let mut session=TemporalTrainingSession::managed(plan.clone(),"synthetic-four-c5".into(),FitConfig::for_source_count(4)).unwrap(); + let bound=plan.bind_episode_start("synthetic-four-c5",0,0,0,None).unwrap(); + let target=ManagedWindowTarget::from_runtime_episode(&plan,&bound,"synthetic-four-c5",0,10_000_000_000).unwrap(); + session.begin_managed_window(&target).unwrap(); + let mut completed=false; + 'window: for row in 0..45u32 { for source in 20..=23u8 { + let sequence=row+1;let at=target.target_ns()+u64::from(row/2)*100_000_000+u64::from(row%2)*10_000+u64::from(source)*1000; + let iq=vec![5u8;106];let mut wire=vec![0u8;20]; + wire[..4].copy_from_slice(&0xC5110001u32.to_le_bytes());wire[4]=source;wire[5]=1; + wire[6..8].copy_from_slice(&53u16.to_le_bytes());wire[8..12].copy_from_slice(&5180u32.to_le_bytes());wire[12..16].copy_from_slice(&sequence.to_le_bytes()); + wire.extend(&iq);wire.extend([b'C',b'5',b'L',b'8',1,8,1,1,1,1,0,20,1,0,106,0]); + let flags=Adr018Flags::default(); + let format=validate_adr018_native_format(&wire,1,53,PpduType::HtLegacy,flags).unwrap(); + let packet=canonicalize_esp32_with_format(NativePacketInput{node_id:source,n_antennas:1,raw_bins:53,frequency_hz:5_180_000_000,ppdu_type:PpduType::HtLegacy,sequence,received_at_ns:at,receiver_sample_rate_hz:if row%2==1 {100_000.}else{10.001},iq_bytes:&iq,flags,provenance:CaptureProvenance::Synthetic},format).unwrap(); + if session.ingest(&packet).unwrap()==WindowAdmission::Ready { session.finish_window(at).unwrap();completed=true;break 'window; } + }} + assert!(completed,"all four original C5 sources must close one native two-second window"); + assert_eq!(session.rows.len(),1); + assert_eq!(session.rows[0].views.len(),4); +} + +#[test] +fn variable_profile_four_source_training_keeps_reserved_checks_and_cold_model_identity() { + let mut c=context();let mut fourth=c.sources[2].clone();fourth.source_id=4;fourth.device_id="esp32-node-4".into();fourth.link_id="native-4".into();c.sources.push(fourth); + let plan=ManagedScheduleContract::build(c,LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + let mut session=TemporalTrainingSession::managed(plan.clone(),"synthetic-variable-fit".into(),FitConfig{epochs:2,..FitConfig::for_source_count(4)}).unwrap(); + let mut start=10_000_000_000u64;let mut index=0u32; + for episode in plan.episodes() { + let bound=plan.bind_episode_start("synthetic-variable-fit",episode.index,0,0,None).unwrap(); + for slot in 0..episode.slots.len() { + let target=ManagedWindowTarget::from_runtime_episode(&plan,&bound,"synthetic-variable-fit",slot,start).unwrap(); + session.begin_managed_window(&target).unwrap();let mut completed=false; + 'window: for row in 0..45u32 { for source in 1..=4u8 { + let at=target.target_ns()+u64::from(row)*50_000_000+u64::from(source)*1000; + let mut p=packet(source,index*1000+row+1,at,episode.condition,row as usize); + // Synthetic receiver-only fixture: row intervals and cadence agree. + p.receiver_sample_rate_hz=20.; + if session.ingest(&p).unwrap()==WindowAdmission::Ready {session.finish_window(at).unwrap();completed=true;break 'window;} + }} + assert!(completed);index+=1; + } + start+=episode.target_active_recording_ms*1_000_000+10_000_000_000; + } + assert_eq!(session.rows.len(),80); + assert_eq!(session.rows.iter().filter(|r|r.role==DataRole::Validation).count(),16); + assert!(session.rows.iter().all(|r|r.views.len()==4)); + session.retain_managed_train_only().unwrap();assert_eq!(session.rows.len(),64); + let admission=session.synthetic_test_fit_admission().unwrap(); + let (model,_)=session.fit_managed_with_cancel(admission,&AtomicBool::new(false)).unwrap(); + let bytes=model.export().unwrap();let cold=TemporalModel::import(&bytes).unwrap(); + assert_eq!(cold.export().unwrap(),bytes);assert_eq!(cold.context().sources.len(),4); + assert!(cold.managed_is_operator_eight_step().unwrap()); +} + +#[test] +fn variable_profile_arrival_bursts_still_reject_long_gaps_and_packet_floods() { + for flood in [false,true] { + let plan=ManagedScheduleContract::build(context(),LeadInPolicy::OperatorVariableSourcesV2).unwrap(); + let mut session=TemporalTrainingSession::managed(plan.clone(),"synthetic-burst-negative".into(),FitConfig::default()).unwrap(); + let bound=plan.bind_episode_start("synthetic-burst-negative",0,0,0,None).unwrap(); + let target=ManagedWindowTarget::from_runtime_episode(&plan,&bound,"synthetic-burst-negative",0,10_000_000_000).unwrap(); + session.begin_managed_window(&target).unwrap(); + let mut failure=None; + 'input: for row in 0..60u32 { for source in 1..=3u8 { + let delta=if flood {u64::from(row)*1_000_000}else{u64::from(row)*250_000_000}; + let mut p=packet(source,row+1,target.target_ns()+delta+u64::from(source)*1000,RoomLabel::Empty,row as usize); + p.receiver_sample_rate_hz=if flood {1000.}else{4.}; + match session.ingest(&p) { + Ok(WindowAdmission::Ready)=>panic!("unacceptable arrivals may not create a model window"), + Ok(_)=>{},Err(e)=>{failure=Some(e);break 'input;} + } + }} + assert_eq!(failure.as_deref(),Some(if flood {"acquisition_row_capacity"}else{"acquisition_packet_gap_or_rate"})); + assert!(session.rows.is_empty()); + } +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_wire.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_wire.rs index 799411bfba..11d838dd16 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_wire.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner/temporal_wire.rs @@ -1,5 +1,6 @@ //! Strict whole-Temporal public DTOs. These are read models/command inputs, //! never Complete/evaluation/selection capabilities. V1 producers are unchanged. +pub const VARIABLE_SOURCE_PROFILE_ID: &str = super::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE; use super::{ lifecycle::MutationGuard, observation::{DataRole, RoomLabel}, @@ -382,6 +383,11 @@ pub struct TemporalDiscardRequestV2 { } impl TemporalProfileWire { + pub(crate) fn variable_sources() -> Self { + let mut profile = Self::operator_eight_step(); + profile.profile_id = super::managed_schedule_contract::OPERATOR_VARIABLE_PROFILE.into(); + profile + } pub(crate) fn operator_eight_step() -> Self { let labels=[RoomLabel::Empty,RoomLabel::OccupiedStatic,RoomLabel::OccupiedMoving,RoomLabel::AdjacentOnly]; Self {profile_id:super::managed_schedule_contract::OPERATOR_EIGHT_PROFILE.into(),window_unit:"native_receiver_2s_window".into(),native_window_ms:2000, diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api.rs index ff95542388..647d07408b 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api.rs @@ -13,7 +13,7 @@ use wifi_densepose_sensing_server::room_learner::{ #[path = "room_learner_ingress.rs"] mod ingress; use ingress::native_candidates; -pub(super) use ingress::{observe, observe_with_receiver_timing, ReceiverIngressTiming, LiveSource, NativeSourceKey}; +pub(super) use ingress::{observe, observe_with_receiver_timing, ReceiverIngressTiming, LiveSource, NativeSourceKey, NativePacketRejection}; fn failure(code: &str, error: impl ToString) -> Json { let message = error.to_string(); @@ -58,11 +58,7 @@ fn source_ready(state: &AppStateInner, spec: &SourceSpec, now: std::time::Instan native_candidates(state, spec.source_id, now) .iter() .any(|(key, meta)| { - native::grid_id( - key.n_antennas as usize, - key.raw_bins as usize, - wifi_densepose_hardware::PpduType::from_byte(key.ppdu_type), - ) + key.grid_id() .ok() .as_deref() == Some(spec.grid_id.as_str()) @@ -162,11 +158,7 @@ pub(super) async fn configure( sources.push(SourceSpec { source_id: id, device_id: format!("esp32-node-{id}"), - grid_id: match native::grid_id( - key.n_antennas as usize, - key.raw_bins as usize, - wifi_densepose_hardware::PpduType::from_byte(key.ppdu_type), - ) { + grid_id: match key.grid_id() { Ok(id) => id, Err(error) => return failure("learner_grid_unsupported", error), }, @@ -198,10 +190,19 @@ pub(super) async fn configure( } } pub(super) async fn status(State(state): State) -> Json { + status_with_native_diagnostics(State(state),false).await +} +pub(super) async fn status_with_native_diagnostics(State(state): State, include:bool) + -> Json { match runtime(&state).await { Ok(rt) => { let state = state.read().await; - Json(selection_routes::enriched_status(&state, &rt)) + if include && (state.privacy_mode || !state.room_learning.as_ref().is_some_and(|live|Arc::ptr_eq(live,&rt))) { + return failure("learner_state_changed","learner_state_changed"); + } + let mut value=selection_routes::enriched_status(&state, &rt); + if include {value["native_source_diagnostics"]=ingress::source_rejection_diagnostics(&state,std::time::Instant::now());} + Json(value) } Err(e) => e, } diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal.rs index 409b43d11a..b8c1fee219 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal.rs @@ -3,11 +3,21 @@ use super::*; use wifi_densepose_sensing_server::room_learner::temporal_wire::*; +pub(super) fn temporal_profile_source_count_valid(profile: Option<&str>, count: usize) -> bool { + if profile == Some(VARIABLE_SOURCE_PROFILE_ID) { (2..=8).contains(&count) } else { count == 3 } +} + #[derive(Default, serde::Deserialize)] #[serde(deny_unknown_fields)] pub(crate) struct SchemaQuery { schema: Option, } +#[derive(Default, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct NativeStatusQuery { + schema: Option, + include_native_diagnostics: Option, +} fn schema_matches(actual: &str, expected: &str) -> Result<(), Json> { if actual == expected { Ok(()) @@ -68,10 +78,14 @@ command!( pub(crate) async fn status_dispatch( State(state): State, - Query(query): Query, + Query(query): Query, ) -> Json { + let include=match query.include_native_diagnostics { + None|Some(0)=>false,Some(1)=>true, + _=>return failure("learner_status_query_invalid","include_native_diagnostics must be 0 or 1"), + }; let Some(schema) = query.schema else { - return status(State(state)).await; + return status_with_native_diagnostics(State(state),include).await; }; if let Err(error) = schema_matches(&schema, STATUS_SCHEMA) { return error; @@ -80,8 +94,8 @@ pub(crate) async fn status_dispatch( Ok(rt) => rt, Err(e) => return e, }; - if let Err(e)=rt.temporal_default_operator_profile_v2(){return failure("learner_profile_unavailable",e);} - temporal_status(&state, &rt).await + if let Err(e)=rt.temporal_default_operator_profile_v2(now_ns(&rt)){return failure("learner_profile_unavailable",e);} + temporal_status_with_reader_options(&state,&rt,|reader,now|reader.temporal_status_snapshot_v2(now),include).await } fn temporal_selection( state: &AppStateInner, @@ -125,6 +139,12 @@ pub(super) async fn temporal_status_with_reader( where F: FnOnce(Arc, u64) -> Result + Send + 'static, { + temporal_status_with_reader_options(state,rt,read_snapshot,false).await +} +async fn temporal_status_with_reader_options( + state:&SharedState, rt:&Arc, read_snapshot:F, include:bool, +) -> Json +where F:FnOnce(Arc,u64)->Result+Send+'static { // Concurrent polls wait as async futures, without owning an RF lock or // spawning another blocking worker. Explicit cancellation removes a waiter. let permit = match rt.acquire_temporal_status_reader().await { @@ -187,10 +207,11 @@ where Ok(result) => result, Err(_) => return failure("learner_status_unavailable", "learner_status_worker_unavailable"), }; - match result.and_then(|status| { + match result.and_then(|mut status| { if status["mutation_guard"] != serde_json::to_value(&expected).map_err(|_| "learner_status_guard_invalid")? { return Err("learner_state_changed".into()); } + if include {status["native_source_diagnostics"] = ingress::source_rejection_diagnostics(¤t, std::time::Instant::now());} Ok(status) }) { Ok(status) => Json(serde_json::json!({"success":true,"status":status})), @@ -263,9 +284,9 @@ pub(crate) async fn configure_dispatch( if !valid_binding_digest(&request.binding_digest) || request.revision == 0 || !valid_source_node_ids(&request.source_node_ids) - || request.source_node_ids.len() != 3 + || !temporal_profile_source_count_valid(request.profile_id.as_deref(),request.source_node_ids.len()) { - return failure("learner_context_invalid", "Temporal engineering profile requires a current room revision and exactly three sorted unique sources."); + return failure("learner_context_invalid", "Temporal profile requires a current room revision and its bounded sorted unique source set."); } let rt = match runtime(&state).await { Ok(rt) => rt, @@ -302,11 +323,7 @@ pub(crate) async fn configure_dispatch( "A selected native source/PHY stream is not ready.", ); }; - let grid_id = match native::grid_id( - key.n_antennas as usize, - key.raw_bins as usize, - wifi_densepose_hardware::PpduType::from_byte(key.ppdu_type), - ) { + let grid_id = match key.grid_id() { Ok(grid) => grid, Err(e) => return failure("learner_grid_unsupported", e), }; diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal_tests.rs index 2b777a0a0b..412916b8e8 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_temporal_tests.rs @@ -55,6 +55,61 @@ fn configure_v2(expected: MutationGuard) -> serde_json::Value { "new_training":true,"recovery_consent":true}) } #[tokio::test] +async fn c5_status_diagnostics_require_explicit_opt_in_without_changing_default_schema() { + let (_dir,state)=c5_fixture().await; + { + let mut current=state.write().await; + observe_wire_at(&mut current,&c5_wire(22,121,5180,false),std::time::Instant::now()); + } + let app=temporal_app(state.clone()); + for schema in [None,Some(STATUS_SCHEMA)] { + let path=schema.map_or_else(||"/status".to_string(),|s|format!("/status?schema={s}")); + let plain=decoded(app.clone(),&path,None).await; + let key=if schema.is_some(){&plain["status"]}else{&plain}; + assert!(key.get("native_source_diagnostics").is_none()); + let sep=if schema.is_some(){'&'}else{'?'}; + let off=decoded(app.clone(),&format!("{path}{sep}include_native_diagnostics=0"),None).await; + let off_key=if schema.is_some(){&off["status"]}else{&off}; + assert!(off_key.get("native_source_diagnostics").is_none()); + let opted=decoded(app.clone(),&format!("{path}{sep}include_native_diagnostics=1"),None).await; + let body=if schema.is_some(){&opted["status"]}else{&opted}; + if schema.is_some() { + println!("SYNTHETIC_C5_DEFAULT_STATUS={plain}"); + println!("SYNTHETIC_C5_DIAGNOSTICS_STATUS={opted}"); + } + assert_eq!(body["native_source_diagnostics"]["schema"],"ruview.native-packet-rejections.v1"); + assert_eq!(body["native_source_diagnostics"]["sources"][0]["node_id"],22); + let mut keys=body.as_object().unwrap().keys().filter(|k|k.as_str()!="native_source_diagnostics").cloned().collect::>();keys.sort(); + let mut original=key.as_object().unwrap().keys().cloned().collect::>();original.sort(); + assert_eq!(keys,original); + assert_eq!(body["mutation_guard"],key["mutation_guard"]); + } + assert_eq!(decoded(app.clone(),"/status?include_native_diagnostics=2",None).await["error_code"],"learner_status_query_invalid"); + assert_eq!(request_raw(app.clone(),"/status?include_native_diagnostics=true",None).await.0,StatusCode::BAD_REQUEST); + state.write().await.privacy_mode=true; + let private=decoded(app,&format!("/status?schema={STATUS_SCHEMA}&include_native_diagnostics=1"),None).await; + assert_eq!(private["error_code"],"learner_privacy_mode"); + assert!(private.to_string().find("last_rejected_packet").is_none()); +} +#[tokio::test] +async fn c5_actual_temporal_configure_dispatch_accepts_only_versioned_three_source_context() { + use wifi_densepose_sensing_server::room_learner::recovery_store::RecoveryStore; + let (dir,state)=c5_fixture().await;let owner="a".repeat(64);let path=dir.path().join(&owner).join("SensingServer"); + let store=RecoveryStore::new(&path,&owner,"synthetic-install",Some(&[7;32])).unwrap(); + let rt=Arc::new(RoomLearningRuntime::new_with_recovery(&path,&owner,"synthetic-install",store).unwrap()); + state.write().await.room_learning=Some(rt.clone()); + let app=temporal_app(state.clone());let mut body=configure_v2(rt.mutation_guard().unwrap()); + body["source_node_ids"]=serde_json::json!([20,21,22]); + let configured=decoded(app.clone(),"/configure",Some(body)).await; + assert_eq!(configured["success"],true,"{configured}"); + let context=rt.context().unwrap();assert_eq!(context.sources.iter().map(|s|s.source_id).collect::>(),[20,21,22]); + for source in context.sources {assert_eq!(source.grid_id,native::C5_LLTF8_V1_GRID);assert_eq!(source.center_frequency_hz,5_180_000_000);} + assert!(configured["status"].get("native_source_diagnostics").is_none(),"mutation/default ACK must preserve old status schema"); + assert_eq!(configured["status"]["capture"]["observed_ms"],0); + assert_eq!(configured["status"]["capture"]["retained_windows"],0); + assert!(state.read().await.field_model.is_none()); +} +#[tokio::test] async fn negotiated_idle_capability_preserves_default_status_and_selection() { let (_dir, state) = fixture(); let app = temporal_app(state); @@ -779,3 +834,13 @@ async fn cancelled_status_retains_one_reader_permit_until_actual_work_finishes() let response = temporal_status_with_reader(&state, &rt, |reader, now| reader.temporal_status_snapshot_v2(now)).await.0; assert_eq!(response["success"], true, "{response}"); } + +#[test] +fn variable_source_count_contract_keeps_every_supported_node_and_legacy_three_exact() { + use wifi_densepose_sensing_server::room_learner::temporal_wire::VARIABLE_SOURCE_PROFILE_ID; + for count in 0..=9 { + assert_eq!(super::super::temporal_routes::temporal_profile_source_count_valid(Some(VARIABLE_SOURCE_PROFILE_ID),count),(2..=8).contains(&count)); + assert_eq!(super::super::temporal_routes::temporal_profile_source_count_valid(None,count),count==3); + assert_eq!(super::super::temporal_routes::temporal_profile_source_count_valid(Some("native-2s-three-source-56bin-operator-eight-step-v1"),count),count==3); + } +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_tests.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_tests.rs index 75d63b0a7a..8585d1e721 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_tests.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner_api_tests.rs @@ -404,6 +404,146 @@ fn observe_wire_at(inner: &mut AppStateInner, packet: &[u8], at: std::time::Inst .observe_raw_grid(CsiGridKey::from_frame(&frame), at); observe(inner, &frame, packet, at); } + +// New producer-format claims are SYNTHETIC metadata, not physical validation. +fn c5_wire(node:u8, seq:u32, frequency_mhz:u32, with_claim:bool)->Vec { + let mut packet=wire(node,seq); + packet[6..8].copy_from_slice(&53u16.to_le_bytes()); + packet[8..12].copy_from_slice(&frequency_mhz.to_le_bytes()); + packet.resize(20+106,0); + for pair in packet[20..].chunks_exact_mut(2) {pair[0]=node;pair[1]=4;} + packet[20..24].fill(0); // Actual invalid-prefix sanitation, two int8 positions. + if with_claim {packet.extend([b'C',b'5',b'L',b'8',1,8,1,1,1,1,0,20,1,1,106,0]);} + packet +} +async fn c5_fixture()->(tempfile::TempDir,SharedState) { + let (dir,state)=fixture();let now=std::time::Instant::now(); + { + let mut inner=state.write().await; + inner.node_states.clear();inner.room_learning_sources.clear();inner.room_learning_rejections.clear(); + for row in 0..120 { + let at=now-std::time::Duration::from_millis((120-row)as u64*100); + for node in [20,21,22] {observe_wire_at(&mut inner,&c5_wire(node,row+1,5180,true),at);} + } + } + (dir,state) +} +fn c5_config()->serde_json::Value { + serde_json::json!({"binding_digest":"b".repeat(64),"revision":1, + "source_node_ids":[20,21,22],"new_training":true}) +} +fn c5_app(state:SharedState)->Router { + let status_route=get(status_dispatch).with_state(state.clone()); + app(state).route("/native-status",status_route) +} +#[tokio::test] +async fn c5_claimed_datagrams_bind_three_independent_sources_and_enter_actual_capture() { + let (_dir,state)=c5_fixture().await;let router=app(state.clone()); + let configured=json_request(router.clone(),"/configure",Method::POST,c5_config()).await; + assert_eq!(configured["success"],true,"{configured}"); + let sources=configured["status"]["sources"].as_array().unwrap(); + assert_eq!(sources.len(),3); + for (source,node) in sources.iter().zip([20,21,22]) { + assert_eq!(source["source_id"],node);assert_eq!(source["device_id"],format!("esp32-node-{node}")); + assert_eq!(source["grid_id"],native::C5_LLTF8_V1_GRID); + assert_eq!(source["center_frequency_hz"],5_180_000_000u64); + assert_eq!(source["feature_count"],56); + } + let begun=json_request(router.clone(),"/phase",Method::POST,serde_json::json!({ + "trial_id":"synthetic-c5","session_id":"synthetic-c5","role":"Train", + "label":"Empty","duration_ms":12000,"conditions_confirmed":true})).await; + assert_eq!(begun["success"],true,"{begun}"); + for row in 0..8 { + for node in [20,21,22] { + let packet=c5_wire(node,121+row,5180,true);let frame=parse_esp32_frame(&packet).unwrap(); + assert_eq!(frame.n_subcarriers,53);assert_eq!(frame.amplitudes.len(),53); + observe(&mut *state.write().await,&frame,&packet,std::time::Instant::now()); + } + } + let read=json_request_status(router).await; + assert_eq!(read["required_source_ids"],serde_json::json!([20,21,22])); + for source in read["capture"]["sources"].as_array().unwrap() { + assert_eq!(source["admitted_packets"],8);assert_eq!(source["live_buffer_frames"],8); + } + assert_eq!(read["physically_validated"],false); + assert!(state.read().await.field_model.is_none()); +} +#[tokio::test] +async fn c5_unclaimed_or_contradictory_packets_cannot_borrow_other_sources_readiness() { + for mutant in 0..7 { + let (_dir,state)=c5_fixture().await; + { + let mut inner=state.write().await; + inner.room_learning_sources.retain(|key,_|key.node_id!=22); + let mut packet=c5_wire(22,121,5180,mutant!=0); + match mutant { + 0=>{},1=>packet[126+5]=12,2=>packet[126+12]=0, + 3=>packet[126+10]=1,4=>packet[19]|=1,5=>packet[18]=1, + _=>packet.push(0), + } + observe_wire_at(&mut inner,&packet,std::time::Instant::now()); + assert!(native_candidates(&inner,22,std::time::Instant::now()).is_empty()); + assert_eq!(inner.room_learning_sources.len(),2); + } + let router=c5_app(state.clone()); + let response=json_request(router.clone(),"/configure",Method::POST,c5_config()).await; + assert_eq!(response["error_code"],"learner_source_unready","mutant{mutant}: {response}"); + let read=json_request(router,"/native-status?include_native_diagnostics=1",Method::GET,serde_json::Value::Null).await; + let reasons=&read["native_source_diagnostics"]["sources"]; + assert_eq!(reasons[0]["node_id"],22);assert_eq!(reasons[0]["admission_authority"],false); + assert_eq!(reasons[0]["last_rejected_packet"]["code"],"native_format_unverified"); + } +} +#[tokio::test] +async fn c5_frozen_source_binding_withdraws_on_replaced_frequency_or_grid_without_relabelling() { + for change_grid in [false,true] { + let (_dir,state)=c5_fixture().await;let router=app(state.clone()); + let configured=json_request(router.clone(),"/configure",Method::POST,c5_config()).await; + assert_eq!(configured["success"],true,"{configured}"); + let context=state.read().await.room_learning.as_ref().unwrap().context().unwrap(); + { + let mut inner=state.write().await;inner.room_learning_sources.retain(|key,_|key.node_id!=20); + let now=std::time::Instant::now(); + for row in 0..120 { + let packet=if change_grid {wire(20,row+121)}else{c5_wire(20,row+121,5200,true)}; + let at=now-std::time::Duration::from_millis((120-row)as u64*100); + observe_wire_at(&mut inner,&packet,at); + } + assert!(!source_ready(&inner,&context.sources[0],std::time::Instant::now())); + assert!(source_ready(&inner,&context.sources[1],std::time::Instant::now())); + assert!(source_ready(&inner,&context.sources[2],std::time::Instant::now())); + let mut foreign=context.sources[1].clone();foreign.grid_id="ant1-bins64-ppdu0-usable-drop2-linear-v2".into(); + assert!(!source_ready(&inner,&foreign,std::time::Instant::now())); + } + let rejected=json_request(router.clone(),"/phase",Method::POST,serde_json::json!({ + "trial_id":"must-not-start","session_id":"must-not-start","role":"Train", + "label":"Empty","duration_ms":12000,"conditions_confirmed":true})).await; + assert_eq!(rejected["error_code"],"learner_source_unready","{rejected}"); + let read=json_request_status(router).await; + assert_eq!(read["mutation_guard"],configured["status"]["mutation_guard"]); + assert_eq!(read["sources"],configured["status"]["sources"]); + assert!(read["capture"]["phase"].is_null()); + } +} +#[tokio::test] +async fn c5_rejection_diagnostics_are_bounded_expire_and_do_not_invalidate_a_good_cohort() { + let (_dir,state)=c5_fixture().await;let now=std::time::Instant::now(); + { + let mut inner=state.write().await; + for node in 0u8..=255 {observe_wire_at(&mut inner,&c5_wire(node,121,5180,false),now);} + assert_eq!(inner.room_learning_rejections.len(),256); + assert_eq!(inner.room_learning_sources.len(),3); + for node in [20,21,22] {assert_eq!(native_candidates(&inner,node,now).len(),1);} + let expired=ingress::source_rejection_diagnostics(&inner,now+std::time::Duration::from_secs(6)); + assert_eq!(expired["sources"],serde_json::json!([])); + } + let read=json_request(c5_app(state),"/native-status?include_native_diagnostics=1",Method::GET,serde_json::Value::Null).await; + let data=read["native_source_diagnostics"].to_string(); + for private in ["native_iq","amplitudes","timestamp_ns","owner_scope","payload"] {assert!(!data.contains(private));} + assert_eq!(read["native_source_diagnostics"]["sources"].as_array().unwrap().len(),32); + assert_eq!(read["native_source_diagnostics"]["total_sources"],256); + assert_eq!(read["native_source_diagnostics"]["truncated"],true); +} #[tokio::test] async fn unsupported_class_churn_cannot_exhaust_readiness_for_healthy_nodes() { let (_dir, state) = fixture(); @@ -559,3 +699,43 @@ async fn enable_current_recovery_requires_explicit_versioned_consent_and_does_no #[path = "room_learner_api_temporal_tests.rs"] mod temporal_contract_tests; + +#[tokio::test] +async fn c5_cross_node_sync_metadata_reaches_real_ingress_and_readiness_without_clock_upgrade() { + let (_dir,state)=fixture();let now=std::time::Instant::now(); + { + let mut inner=state.write().await; + inner.node_states.clear();inner.room_learning_sources.clear();inner.room_learning_rejections.clear(); + for row in 0..120 { + let at=now-std::time::Duration::from_millis((120-row)as u64*100); + for node in [20,21,22] { + let mut packet=c5_wire(node,row+1,5240,true);packet[19]|=0x10; + observe_wire_at(&mut inner,&packet,at); + } + } + for node in [20,21,22] {assert_eq!(native_candidates(&inner,node,now).len(),1);} + assert!(inner.room_learning_rejections.is_empty()); + } + let router=app(state.clone()); + let configured=json_request(router.clone(),"/configure",Method::POST,c5_config()).await; + assert_eq!(configured["success"],true,"{configured}"); + for spec in configured["status"]["sources"].as_array().unwrap() { + assert_eq!(spec["grid_id"],native::C5_LLTF8_V1_GRID); + assert_eq!(spec["center_frequency_hz"],5_240_000_000u64); + } + let begun=json_request(router.clone(),"/phase",Method::POST,serde_json::json!({ + "trial_id":"synthetic-c5-sync","session_id":"synthetic-c5-sync","role":"Train", + "label":"Empty","duration_ms":12000,"conditions_confirmed":true})).await; + assert_eq!(begun["success"],true,"{begun}"); + for row in 0..8 {for node in [20,21,22] { + let mut packet=c5_wire(node,121+row,5240,true); + if row%2==0 {packet[19]|=0x10;} // Advisory bit may toggle; source grid is unchanged. + let mut inner=state.write().await;observe_wire_at(&mut inner,&packet,std::time::Instant::now()); + }} + let read=json_request_status(router).await; + for source in read["capture"]["sources"].as_array().unwrap() { + assert_eq!(source["admitted_packets"],8);assert_eq!(source["live_buffer_frames"],8); + } + assert_eq!(read["physically_validated"],false); + assert!(state.read().await.field_model.is_none()); +} diff --git a/v2/crates/wifi-densepose-sensing-server/src/room_learner_ingress.rs b/v2/crates/wifi-densepose-sensing-server/src/room_learner_ingress.rs index 1796b722c5..987562d7bd 100644 --- a/v2/crates/wifi-densepose-sensing-server/src/room_learner_ingress.rs +++ b/v2/crates/wifi-densepose-sensing-server/src/room_learner_ingress.rs @@ -26,9 +26,10 @@ pub(crate) struct NativeSourceKey { pub(super) ppdu_type: u8, pub(super) frequency_mhz: u16, pub(super) bw40: bool, + pub(super) format: native::NativeFormatId, } impl NativeSourceKey { - fn from_frame(frame: &Esp32Frame) -> Self { + fn from_frame(frame: &Esp32Frame, format: native::NativeFormatId) -> Self { Self { node_id: frame.node_id, n_antennas: frame.n_antennas, @@ -36,8 +37,56 @@ impl NativeSourceKey { ppdu_type: frame.ppdu_type.to_byte(), frequency_mhz: frame.freq_mhz, bw40: frame.adr018_flags.bw40, + format, } } + pub(super) fn grid_id(&self) -> Result { + native::grid_id_for_format(self.n_antennas as usize, self.raw_bins as usize, + wifi_densepose_hardware::PpduType::from_byte(self.ppdu_type), self.format) + } +} + +/// Last rejected packet metadata only, never readiness or model authority. +/// u8 node IDs bound storage to 256 entries; no raw payload/absolute timestamps. +#[derive(Debug, Clone)] +pub(crate) struct NativePacketRejection { + code: &'static str, + detail: &'static str, + raw_bins: u16, + ppdu_type: u8, + frequency_mhz: u16, + observed_at: std::time::Instant, +} +const NATIVE_REJECTION_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(5); +const MAX_REPORTED_NATIVE_REJECTIONS: usize = 32; +fn reject_packet(state: &mut AppStateInner, frame: &Esp32Frame, now: std::time::Instant, + code: &'static str, detail: &'static str) { + state.room_learning_rejections.retain(|_, d| + now.saturating_duration_since(d.observed_at) <= NATIVE_REJECTION_MAX_AGE); + state.room_learning_rejections.insert(frame.node_id, NativePacketRejection { + code, detail, raw_bins: frame.n_subcarriers, ppdu_type: frame.ppdu_type.to_byte(), + frequency_mhz: frame.freq_mhz, observed_at: now, + }); +} +pub(super) fn source_rejection_diagnostics(state: &AppStateInner, now: std::time::Instant) + -> serde_json::Value { + let selected=state.room_learning.as_ref().and_then(|rt|rt.context()) + .map(|context|context.sources.into_iter().map(|source|source.source_id).collect::>()).unwrap_or_default(); + let mut ids: Vec<_> = state.room_learning_rejections.iter().filter_map(|(&id,d)| + (now.saturating_duration_since(d.observed_at)<=NATIVE_REJECTION_MAX_AGE).then_some(id)).collect(); + ids.sort_unstable_by_key(|id|(!selected.contains(id),*id)); + let total=ids.len(); + let values: Vec<_> = ids.into_iter().take(MAX_REPORTED_NATIVE_REJECTIONS).filter_map(|node| { + let d = &state.room_learning_rejections[&node]; + let age = now.saturating_duration_since(d.observed_at); + (age <= NATIVE_REJECTION_MAX_AGE).then(|| serde_json::json!({ + "node_id":node,"last_rejected_packet":{"code":d.code,"detail":d.detail, + "raw_bins":d.raw_bins,"ppdu_type":d.ppdu_type,"frequency_mhz":d.frequency_mhz, + "age_ms":age.as_millis() as u64},"admission_authority":false + })) + }).collect(); + serde_json::json!({"schema":"ruview.native-packet-rejections.v1","sources":values, + "total_sources":total,"truncated":total>MAX_REPORTED_NATIVE_REJECTIONS}) } #[derive(Debug, Clone)] pub(crate) struct LiveSource { @@ -111,12 +160,7 @@ pub(super) fn native_candidates( .filter(|(key, meta)| { key.node_id == node && meta.eligible(now) - && native::grid_id( - key.n_antennas as usize, - key.raw_bins as usize, - wifi_densepose_hardware::PpduType::from_byte(key.ppdu_type), - ) - .is_ok() + && key.grid_id().is_ok() }) .collect() } @@ -140,11 +184,18 @@ pub(crate) fn observe_with_receiver_timing( }; // Unsupported input must never consume the bounded readiness cache. Keep // the selected-source rejection diagnostic without admitting any evidence. - let Ok(id) = native::grid_id( - frame.n_antennas as usize, - frame.n_subcarriers as usize, - frame.ppdu_type, - ) else { + let format = match native::validate_adr018_native_format(packet, + frame.n_antennas as usize, frame.n_subcarriers as usize, + frame.ppdu_type, frame.adr018_flags) { + Ok(format) => format, + Err(detail) => { + reject_packet(state, frame, now, "native_format_unverified", detail); + return; + } + }; + let key = NativeSourceKey::from_frame(frame, format.id()); + let Ok(id) = key.grid_id() else { + reject_packet(state, frame, now, "native_grid_unsupported", "The declared native grid/PPDU is unsupported."); return; }; let frequency_hz = u64::from(frame.freq_mhz) * 1_000_000; @@ -156,6 +207,7 @@ pub(crate) fn observe_with_receiver_timing( None }; if let Some(reason) = rejection { + reject_packet(state, frame, now, "native_phy_unsupported", reason); runtime.record_native_rejection(frame.node_id, &id, reason); return; } @@ -163,7 +215,11 @@ pub(crate) fn observe_with_receiver_timing( let Some(iq) = packet.get(20..20 + bytes) else { return; }; - let key = NativeSourceKey::from_frame(frame); + if state.room_learning_rejections.get(&frame.node_id).is_some_and(|d| + d.raw_bins == frame.n_subcarriers && d.ppdu_type == frame.ppdu_type.to_byte() + && d.frequency_mhz == frame.freq_mhz) { + state.room_learning_rejections.remove(&frame.node_id); + } if state.room_learning_sources.len() >= 1024 && !state.room_learning_sources.contains_key(&key) { // Reclaim only expired unrelated classes. Selected contexts keep their @@ -180,11 +236,7 @@ pub(crate) fn observe_with_receiver_timing( source.source_id == key.node_id && source.center_frequency_hz == meta.frequency_hz && Some(source.bandwidth_hz) == meta.bandwidth_hz - && native::grid_id( - key.n_antennas as usize, - key.raw_bins as usize, - wifi_densepose_hardware::PpduType::from_byte(key.ppdu_type), - ) + && key.grid_id() .ok() .as_deref() == Some(source.grid_id.as_str()) @@ -213,7 +265,7 @@ pub(crate) fn observe_with_receiver_timing( let dequeue_interval_us = receiver_timing.and_then(|t| meta.diagnostic_dequeue_interval(t.dequeued_at)); let native_stamp_at = receiver_timing.map(|_| std::time::Instant::now()); let ns = runtime.receiver_now_ns(); - let projected = match native::canonicalize_esp32(NativePacketInput { + let projected = match native::canonicalize_esp32_with_format(NativePacketInput { node_id: frame.node_id, n_antennas: frame.n_antennas as usize, raw_bins: frame.n_subcarriers as usize, @@ -225,7 +277,7 @@ pub(crate) fn observe_with_receiver_timing( iq_bytes: iq, flags: frame.adr018_flags, provenance: CaptureProvenance::LiveReceiverObserved, - }) { + }, format) { Ok(p) => p, Err(reason) => { runtime.record_native_rejection(frame.node_id, &id, &reason); @@ -249,7 +301,7 @@ mod receiver_timing_tests { #[test] fn diagnostic_cache_is_separate_from_readiness_and_exact_phy_keys_do_not_mix() { let t = Instant::now(); - let ht_key = NativeSourceKey { node_id:15, n_antennas:1, raw_bins:64, ppdu_type:0, frequency_mhz:2437, bw40:false }; + let ht_key = NativeSourceKey { node_id:15, n_antennas:1, raw_bins:64, ppdu_type:0, frequency_mhz:2437, bw40:false, format:native::NativeFormatId::LegacyV2 }; let he_key = NativeSourceKey { raw_bins:256, ppdu_type:1, ..ht_key }; let mut cache = std::collections::HashMap::from([(ht_key, source()), (he_key, source())]); let ht = cache.get_mut(&ht_key).unwrap(); ht.record(t); diff --git a/v2/crates/wifi-densepose-sensing-server/tests/fixtures/c5-node23-wire-metadata-20261110.json b/v2/crates/wifi-densepose-sensing-server/tests/fixtures/c5-node23-wire-metadata-20261110.json new file mode 100644 index 0000000000..fc0648f969 --- /dev/null +++ b/v2/crates/wifi-densepose-sensing-server/tests/fixtures/c5-node23-wire-metadata-20261110.json @@ -0,0 +1,76 @@ +{ + "c5_strict_accepted": 0, + "canonicalized_with_measured_receiver_interval": 0, + "capture_model_phase_accuracy_or_hardware_qualification": false, + "elapsed_seconds": 15.019938292, + "evidence": "EXECUTED / ACTUAL NODE23 UDP WIRE / RECEIVER METADATA ONLY", + "header_sequence": { + "duplicate_arrivals": 0, + "first": 1685, + "last": 2007, + "non_unit_transitions": 33 + }, + "node23_observed": true, + "node23_receiver_cadence": { + "gap_max_ns": 149005958, + "gap_mean_ns": 51645478.37370242, + "gap_min_ns": 16541, + "interval_count": 289, + "received_packets": 290, + "receiver_rate_hz": 19.362779307882143, + "receiver_span_ns": 14925543250, + "source_clock_or_source_sample_rate_qualified": false + }, + "node_filter": 23, + "other_sources_discarded_before_parsing_or_export": true, + "raw_iq_or_derived_amplitudes_written_or_logged": false, + "schema": "ruview.c5.metadata-wire-probe.v1", + "source_commit": "8930b7bfff1bf3b41d267ee522b80ba2bd1c3875", + "strict_c5_frames_observed": false, + "strict_c5_receiver_cadence": { + "gap_max_ns": null, + "gap_mean_ns": null, + "gap_min_ns": null, + "interval_count": 0, + "received_packets": 0, + "receiver_rate_hz": null, + "receiver_span_ns": null, + "source_clock_or_source_sample_rate_qualified": false + }, + "timestamp_method": "user-space monotonic dequeue time after recv_from; not kernel or source time", + "validator_accepted": 0, + "validator_rejections": { + "C5L8/v1 contains unsupported ADR-018 flag variants": 290 + }, + "variant_overflow_packets": 0, + "variants": [ + { + "count": 290, + "metadata": { + "antennas": 1, + "c5_strict_accepted": false, + "c5_suffix_metadata": { + "bb_format": 1, + "component_bits": 8, + "component_order": 1, + "declared_iq_bytes": 106, + "estimator_valid": 1, + "first_word_invalid": 0, + "marker": "C5L8", + "sdk_readback": 1, + "secondary_channel": 0, + "sta_bandwidth_mhz": 20, + "tone_order": 1, + "version": 1 + }, + "declared_native_slots": 53, + "flags_byte": 16, + "format_validator_accepted": false, + "frequency_mhz": 5240, + "ppdu_byte": 0, + "validator_error": "C5L8/v1 contains unsupported ADR-018 flag variants", + "wire_bytes": 142 + } + } + ] +} diff --git a/v2/vendor/security/wasmtime-internal-cache-36.0.20/RUVIEW-PROVENANCE.md b/v2/vendor/security/wasmtime-internal-cache-36.0.20/RUVIEW-PROVENANCE.md index cb51c691fb..547b73b5d0 100644 --- a/v2/vendor/security/wasmtime-internal-cache-36.0.20/RUVIEW-PROVENANCE.md +++ b/v2/vendor/security/wasmtime-internal-cache-36.0.20/RUVIEW-PROVENANCE.md @@ -1,13 +1,14 @@ # Dependency compatibility patch Source: crates.io `wasmtime-internal-cache` 36.0.20. -Published archive SHA-256: `65f09c789d1bb2e7ab1618ac8336d783c1ff0babc38430c7f1940d01c546722b` (verified against crates.io version metadata). +Published archive SHA-256: `65f09c789d1bb2e7ab1618ac8336d783c1ff0babc38430c7f1940d01c546722b` (retained verified upstream archive identity from the reviewed dependency patch). -Executable source, tests, fixtures and licenses are byte-for-byte upstream. -Only the normalized Cargo.toml dependency requirement changes: -`zstd` from `0.13.0` to `0.14.3`, retaining the upstream feature selection. -Registry bookkeeping, the nested lockfile, the unconsumed original manifest -and upstream CI files are omitted. No advisory suppression is added. +Upstream executable source code and tests are unchanged. Trailing whitespace +in upstream documentation/comments is normalized for clean repository diffs. +The normalized Cargo.toml changes only the +zstd dependency requirement from 0.13.0 to 0.14.3, retaining existing features. +Registry bookkeeping, CI files, the unconsumed original manifest, and the nested lockfile are omitted. +The upstream license and tests are retained. This preserves the parent API +while using the fixed Zstandard implementation without vendoring ML frameworks. -This preserves the parent API while selecting the patched registry dependency. -Remove this override when a compatible parent release includes the fixed dependency. +Remove this patch when the parent releases a compatible dependency update.