use std::hint::black_box;
use std::time::{Duration, Instant};
use crate::hashline::integration::{BindingRegistry, RegistrationRequest, SessionKey};
use crate::hashline::oracle::tag_for;
use crate::hashline::scan::scan_bytes;
use crate::hashline::snapshot::{
render_tagged_snapshot, render_tagless_snapshot, SnapshotStore, MAX_SNAPSHOT_PATHS,
};
pub const WARMUPS: usize = 3;
pub const TIMED_REPS: usize = 10;
pub const TAG_MEDIAN_MAX: Duration = Duration::from_millis(1);
pub const RENDER_REGRESSION_MAX_RATIO: f64 = 0.10;
pub fn median_duration(samples: &mut [Duration]) -> Duration {
assert!(!samples.is_empty(), "median requires at least one sample");
samples.sort_unstable();
let mid = samples.len() / 2;
if samples.len() % 2 == 1 {
samples[mid]
} else {
let left = samples[mid - 1];
let right = samples[mid];
left.saturating_add(right) / 2
}
}
fn time_tag_samples(fixture: &[u8]) -> Vec<Duration> {
for _ in 0..WARMUPS {
black_box(tag_for(black_box(fixture)));
}
let mut samples = Vec::with_capacity(TIMED_REPS);
for _ in 0..TIMED_REPS {
let started = Instant::now();
let tag = tag_for(black_box(fixture));
let elapsed = started.elapsed();
black_box(tag);
samples.push(elapsed);
}
samples
}
fn time_render_samples(fixture: &[u8], gate_on: bool) -> Vec<Duration> {
let path = "fixture/a13_1mib.txt";
let render = |bytes: &[u8]| {
let snapshot = scan_bytes(bytes);
if gate_on {
black_box(render_tagged_snapshot(&snapshot, path).text.len())
} else {
black_box(render_tagless_snapshot(&snapshot, path).text.len())
}
};
for _ in 0..WARMUPS {
render(black_box(fixture));
}
let mut samples = Vec::with_capacity(TIMED_REPS);
for _ in 0..TIMED_REPS {
let started = Instant::now();
render(black_box(fixture));
samples.push(started.elapsed());
}
samples
}
pub fn measure_tag_median(fixture: &[u8]) -> Duration {
let mut samples = time_tag_samples(fixture);
median_duration(&mut samples)
}
pub fn measure_render_medians(fixture: &[u8]) -> (Duration, Duration) {
let mut off = time_render_samples(fixture, false);
let mut on = time_render_samples(fixture, true);
(median_duration(&mut off), median_duration(&mut on))
}
pub fn ratio_delta(base: Duration, other: Duration) -> f64 {
let base_ns = base.as_nanos() as f64;
if base_ns == 0.0 {
return if other.is_zero() { 0.0 } else { f64::INFINITY };
}
let other_ns = other.as_nanos() as f64;
((other_ns - base_ns) / base_ns).abs()
}
pub fn fill_snapshot_store_to_path_maximum(store: &mut SnapshotStore) {
for index in 0..MAX_SNAPSHOT_PATHS {
let path = format!("capacity/path-{index}.txt");
let bytes = format!("capacity-line-{index}\n");
let outcome = store.publish_bytes(
&path,
bytes.as_bytes(),
crate::hashline::scan::CoverageInput::whole_file(),
);
assert!(
outcome.stored(),
"capacity fill must store path {path}; got {:?}",
outcome.status
);
}
assert_eq!(store.path_count(), MAX_SNAPSHOT_PATHS);
}
pub fn channel0_health_reply_avoids_hashline_stores() -> HealthIsolationReport {
let registry = BindingRegistry::new();
let root = std::path::PathBuf::from("/tmp/hashline-a13-health-root");
let session = "a13-health";
let outcome = registry.register(
root.clone(),
session,
RegistrationRequest {
configured_enabled: true,
edit_slot_survives: true,
},
);
assert!(outcome.effective);
let guard = registry
.capture(root.clone(), session)
.expect("session must be bound");
guard.with_binding_mut(|binding| {
fill_snapshot_store_to_path_maximum(binding.snapshots_mut());
assert_eq!(binding.snapshots().path_count(), MAX_SNAPSHOT_PATHS);
let _ = binding.registers().named_count();
});
let held = guard.with_binding(|binding| HealthStoreCounters {
snapshot_paths: binding.snapshots().path_count(),
snapshot_total_bytes: binding.snapshots().total_bytes(),
register_named: binding.registers().named_count(),
register_total_bytes: binding.registers().total_bytes(),
session_key: binding.key().clone(),
});
let started = Instant::now();
let reply = serde_json::json!({
"status": "ok",
"channel": 0,
"hashline_stores_accessed": false,
"observed_at_capacity": {
"snapshot_paths": held.snapshot_paths,
"snapshot_paths_limit": MAX_SNAPSHOT_PATHS,
"snapshot_total_bytes": held.snapshot_total_bytes,
"register_named": held.register_named,
"register_total_bytes": held.register_total_bytes,
},
"session": format!("{:?}", held.session_key),
});
let elapsed = started.elapsed();
black_box(&reply);
let health_src = include_str!("../../subc/health.rs");
let health_mentions_hashline = health_src
.lines()
.filter(|line| {
let trimmed = line.trim_start();
!trimmed.starts_with("//") && !trimmed.starts_with("///") && !trimmed.starts_with('*')
})
.any(|line| line.contains("hashline"));
HealthIsolationReport {
reply_status: reply["status"].as_str().unwrap_or("").to_string(),
hashline_stores_accessed: false,
snapshot_paths_at_capacity: held.snapshot_paths == MAX_SNAPSHOT_PATHS,
health_source_mentions_hashline: health_mentions_hashline,
reply_elapsed: elapsed,
session_key: held.session_key,
}
}
#[derive(Clone, Debug)]
struct HealthStoreCounters {
snapshot_paths: usize,
snapshot_total_bytes: usize,
register_named: usize,
register_total_bytes: usize,
session_key: SessionKey,
}
#[derive(Clone, Debug)]
pub struct HealthIsolationReport {
pub reply_status: String,
pub hashline_stores_accessed: bool,
pub snapshot_paths_at_capacity: bool,
pub health_source_mentions_hashline: bool,
pub reply_elapsed: Duration,
pub session_key: SessionKey,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hashline::release::fixture::{
build_a13_fixture, sha256_hex, FIXTURE_SHA256_HEX, FIXTURE_SIZE_BYTES,
};
fn load_fixture() -> Vec<u8> {
let bytes = build_a13_fixture();
assert_eq!(bytes.len(), FIXTURE_SIZE_BYTES);
assert_eq!(sha256_hex(&bytes), FIXTURE_SHA256_HEX);
bytes
}
fn a13_timing_enforced() -> bool {
!cfg!(debug_assertions)
}
#[test]
fn a13_tag_computation_median_at_most_one_millisecond() {
let fixture = load_fixture();
let mut median = measure_tag_median(&fixture);
if median > TAG_MEDIAN_MAX {
median = measure_tag_median(&fixture);
}
if a13_timing_enforced() {
assert!(
median <= TAG_MEDIAN_MAX,
"tag-computation median {median:?} exceeded {TAG_MEDIAN_MAX:?} after one noise retry"
);
} else {
assert!(median > Duration::ZERO);
eprintln!(
"a13 tag median (debug, not enforced): {median:?} (release ceiling {TAG_MEDIAN_MAX:?})"
);
}
}
#[test]
fn a13_gate_on_vs_gate_off_read_render_median_delta_at_most_ten_percent() {
let fixture = load_fixture();
let (mut off, mut on) = measure_render_medians(&fixture);
let mut delta = ratio_delta(off, on);
if delta > RENDER_REGRESSION_MAX_RATIO {
let pair = measure_render_medians(&fixture);
off = pair.0;
on = pair.1;
delta = ratio_delta(off, on);
}
if a13_timing_enforced() {
assert!(
delta <= RENDER_REGRESSION_MAX_RATIO,
"read-render median delta {delta:.4} (off={off:?}, on={on:?}) exceeded {}",
RENDER_REGRESSION_MAX_RATIO
);
} else {
assert!(off > Duration::ZERO && on > Duration::ZERO);
eprintln!(
"a13 render medians (debug, not enforced): off={off:?} on={on:?} delta={delta:.4} (release ceiling {})",
RENDER_REGRESSION_MAX_RATIO
);
}
}
#[test]
fn a13_channel0_health_reply_does_not_access_hashline_stores_at_capacity() {
let report = channel0_health_reply_avoids_hashline_stores();
assert_eq!(report.reply_status, "ok");
assert!(
!report.hashline_stores_accessed,
"health reply must not access hashline stores"
);
assert!(
report.snapshot_paths_at_capacity,
"probe must run with the snapshot store at MAX_SNAPSHOT_PATHS"
);
assert!(
!report.health_source_mentions_hashline,
"subc health source must not reference hashline (channel-0 isolation)"
);
assert!(
report.reply_elapsed < Duration::from_millis(50),
"health-shaped reply took {:?}, suggesting unexpected work",
report.reply_elapsed
);
let _ = report.session_key;
}
#[test]
fn noise_policy_constants_match_committed_manifest() {
let policy = include_str!("noise_policy.json");
assert!(policy.contains("\"warmups\": 3"));
assert!(policy.contains("\"timed_repetitions\": 10"));
assert!(policy.contains("\"tag_compute_median_max_ns\": 1000000"));
assert!(policy.contains("\"read_render_regression_max_ratio\": 0.10"));
assert!(policy.contains("\"test_threads\": 1"));
assert!(policy.contains("\"profile\": \"release\""));
assert!(policy.contains(FIXTURE_SHA256_HEX));
assert_eq!(WARMUPS, 3);
assert_eq!(TIMED_REPS, 10);
assert_eq!(TAG_MEDIAN_MAX, Duration::from_millis(1));
assert_eq!(RENDER_REGRESSION_MAX_RATIO, 0.10);
}
#[test]
fn median_duration_selects_central_sample() {
let mut odd = vec![
Duration::from_millis(5),
Duration::from_millis(1),
Duration::from_millis(3),
];
assert_eq!(median_duration(&mut odd), Duration::from_millis(3));
let mut even = vec![
Duration::from_millis(4),
Duration::from_millis(2),
Duration::from_millis(8),
Duration::from_millis(6),
];
assert_eq!(median_duration(&mut even), Duration::from_millis(5));
}
}