use std::collections::BTreeMap;
use lgwks_deps::libm;
use lgwks_macros::Error;
use lgwks_std::json::Value;
const OMEGA: f64 = 6.0 / 0.45;
const STEP_SECONDS: f64 = 1.0 / 60.0;
const SETTLE_POSITION: f64 = 1e-5;
const SETTLE_VELOCITY: f64 = 1e-4;
const CLOSE_TOLERANCE: f64 = 1e-9;
#[derive(Clone, Debug, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum TraceCheckError {
#[error("missing terminal summary")]
MissingSummary,
#[error("missing frames or unexpected record")]
MissingFrames,
#[error("unknown script phase: {0}")]
UnknownStep(String),
#[error("requested motion mode was not honored")]
ModeMismatch,
#[error("identity, revision or target drift")]
IdentityDrift,
#[error("false native claim or incorrect input byte count")]
NativeOrBytes,
#[error("trajectory differs from analytic oracle at {step} frame {index}")]
Trajectory {
step: String,
index: usize,
},
#[error("idle/revocation boundary failed")]
IdleBoundary,
#[error("frame accounting drift")]
AccountingDrift,
#[error("frame count conversion overflow")]
FrameCountConversion(#[from] core::num::TryFromIntError),
#[error("incomplete journey")]
IncompleteJourney,
#[error("script phase order changed")]
PhaseOrder,
#[error("script phase count changed")]
PhaseCount,
}
fn field_str<'a>(record: &'a Value, name: &str) -> Result<&'a str, TraceCheckError> {
record
.get(name)
.and_then(Value::as_str)
.ok_or(TraceCheckError::MissingFrames)
}
fn field_f64(record: &Value, name: &str) -> Result<f64, TraceCheckError> {
record
.get(name)
.and_then(Value::as_f64)
.ok_or(TraceCheckError::MissingFrames)
}
fn field_u64(record: &Value, name: &str) -> Result<u64, TraceCheckError> {
record
.get(name)
.and_then(Value::as_u64)
.ok_or(TraceCheckError::MissingFrames)
}
fn field_bool(record: &Value, name: &str) -> Result<bool, TraceCheckError> {
record
.get(name)
.and_then(Value::as_bool)
.ok_or(TraceCheckError::MissingFrames)
}
fn require(holds: bool, error: TraceCheckError) -> Result<(), TraceCheckError> {
holds.then_some(()).ok_or(error)
}
fn is_close(actual: f64, expected: f64) -> bool {
if !actual.is_finite() || !expected.is_finite() {
return false;
}
let allowed = (CLOSE_TOLERANCE * actual.abs().max(expected.abs())).max(CLOSE_TOLERANCE);
(actual - expected).abs() <= allowed
}
fn phase_target(step: &str) -> Result<f64, TraceCheckError> {
match step {
"initial" => Ok(0.0),
"toward-evidence" => Ok(2.0),
"interrupt" => Ok(0.0),
"settle" => Ok(1.0),
_ => Err(TraceCheckError::UnknownStep(String::from(step))),
}
}
pub fn check_records(
records: &[Value],
source_bytes: u64,
expected_reduced: bool,
) -> Result<usize, TraceCheckError> {
let (summary, frames) = records
.split_last()
.ok_or(TraceCheckError::MissingSummary)?;
require(
summary.get("kind").and_then(Value::as_str) == Some("summary"),
TraceCheckError::MissingSummary,
)?;
require(
frames.len() >= 4
&& frames
.iter()
.all(|frame| frame.get("kind").and_then(Value::as_str) == Some("frame")),
TraceCheckError::MissingFrames,
)?;
let key = String::from(field_str(&frames[0], "object_key")?);
let mut position = 0.0_f64;
let mut velocity = 0.0_f64;
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
let mut order: Vec<&str> = Vec::new();
for (index, frame) in frames.iter().enumerate() {
let step = field_str(frame, "step")?;
counts
.entry(step)
.and_modify(|count| *count = count.saturating_add(1))
.or_insert(1);
if order.last() != Some(&step) {
order.push(step);
}
require(
field_bool(frame, "reduced")? == expected_reduced,
TraceCheckError::ModeMismatch,
)?;
let target = phase_target(step)?;
require(
keeps_identity(frame, target, &key)?,
TraceCheckError::IdentityDrift,
)?;
require(
!field_bool(frame, "native_presented")?
&& field_u64(frame, "source_bytes")? == source_bytes,
TraceCheckError::NativeOrBytes,
)?;
if field_bool(frame, "reduced")? {
position = target;
velocity = 0.0;
} else if step != "initial" {
let displacement = position - target;
let coefficient = velocity + OMEGA * displacement;
let decay = libm::exp(-OMEGA * STEP_SECONDS);
position = target + (displacement + coefficient * STEP_SECONDS) * decay;
velocity = (velocity - OMEGA * coefficient * STEP_SECONDS) * decay;
if (position - target).abs() < SETTLE_POSITION && velocity.abs() < SETTLE_VELOCITY {
position = target;
velocity = 0.0;
}
}
(is_close(field_f64(frame, "position")?, position)
&& is_close(field_f64(frame, "velocity")?, velocity))
.then_some(())
.ok_or_else(|| TraceCheckError::Trajectory {
step: String::from(step),
index,
})?;
}
require(summary_is_idle(summary)?, TraceCheckError::IdleBoundary)?;
let frame_count = u64::try_from(frames.len())?;
require(
field_u64(summary, "prepared")? == frame_count
&& field_u64(summary, "acknowledged")? == frame_count,
TraceCheckError::AccountingDrift,
)?;
let phases: Vec<&str> = order.clone();
require(
phases == ["initial", "toward-evidence", "interrupt", "settle"],
TraceCheckError::IncompleteJourney,
)?;
let last = frames.last().ok_or(TraceCheckError::IncompleteJourney)?;
require(
field_f64(last, "position")?.to_bits() == 1.0_f64.to_bits(),
TraceCheckError::IncompleteJourney,
)?;
let expected_count = if expected_reduced { 1 } else { 5 };
require(
order == ["initial", "toward-evidence", "interrupt", "settle"]
&& counts.get("initial") == Some(&1),
TraceCheckError::PhaseOrder,
)?;
require(
counts.get("toward-evidence") == Some(&expected_count)
&& counts.get("interrupt") == Some(&expected_count),
TraceCheckError::PhaseCount,
)?;
Ok(frames.len())
}
fn keeps_identity(frame: &Value, target: f64, key: &str) -> Result<bool, TraceCheckError> {
Ok(field_f64(frame, "target")?.to_bits() == target.to_bits()
&& field_str(frame, "object_key")? == key
&& field_u64(frame, "content_revision")? == 1)
}
fn summary_is_idle(summary: &Value) -> Result<bool, TraceCheckError> {
Ok(field_bool(summary, "idle_no_frame")?
&& field_bool(summary, "revocation_refused")?
&& !field_bool(summary, "native_presented")?)
}