//! Unified recording timeline and deterministic causal analysis.
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashSet};
use base64::Engine as _;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::{DebuggerArtifact, DebuggerManager, DebuggerRecording, now_ms};
use crate::history::invocation_scope;
use crate::model::{CausalEvent, InvocationQuery, InvocationRecord};
const TIMELINE_DEFAULT_LIMIT: usize = 100;
const TIMELINE_MAX_LIMIT: usize = 500;
const CONTEXT_MARGIN_MS: u64 = 5 * 60 * 1_000;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTimelineItem {
pub id: String,
pub at: u64,
pub kind: String,
pub label: String,
pub ref_id: Option<String>,
#[serde(default)]
pub details: Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTimeline {
pub recording_id: String,
pub session_id: String,
pub items: Vec<DebuggerTimelineItem>,
pub report: DebuggerArtifact,
pub generated_at: u64,
pub truncated: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWhyCause {
pub item: DebuggerTimelineItem,
pub score: f64,
pub in_stack: bool,
pub ms_before: u64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWhyContext {
pub mark: Option<DebuggerTimelineItem>,
pub prompt: Option<DebuggerTimelineItem>,
pub commit: Option<DebuggerTimelineItem>,
#[serde(default)]
pub edit: Option<DebuggerTimelineItem>,
pub diff: Option<DebuggerTimelineItem>,
pub execution: Option<DebuggerTimelineItem>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWhy {
pub recording_id: String,
pub session_id: String,
pub target: DebuggerTimelineItem,
pub causes: Vec<DebuggerWhyCause>,
pub context: DebuggerWhyContext,
pub answer: String,
pub limitations: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct DebuggerRecordingCorrelation {
pub session_id: String,
pub kind: String,
pub reference: String,
pub path: Option<String>,
pub at: Option<u64>,
pub actor: String,
pub causation_id: String,
}
impl DebuggerManager {
pub fn recording_correlate(
&self,
correlation: DebuggerRecordingCorrelation,
) -> Result<CausalEvent, String> {
let DebuggerRecordingCorrelation {
session_id,
kind,
reference,
path,
at,
actor,
causation_id,
} = correlation;
let recording = self
.recording_status(&session_id)?
.ok_or_else(|| format!("Debugger session \"{session_id}\" has no recording"))?;
let (event_kind, subject, details) = match kind.as_str() {
"edit" => {
let path = path
.filter(|path| !path.is_empty())
.ok_or_else(|| "Recording edit correlation requires path".to_string())?;
(
"debugger.recording.edit",
path.clone(),
json!({"path":path,"reference":reference}),
)
}
"commit" => {
if reference.is_empty() {
return Err("Recording commit correlation requires reference".to_string());
}
(
"debugger.recording.commit",
reference.clone(),
json!({"commit":reference}),
)
}
other => {
return Err(format!(
"Unknown recording correlation kind \"{other}\"; expected edit or commit"
));
}
};
self.store.append_causal_event(CausalEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
at: at.unwrap_or_else(now_ms),
kind: event_kind.to_string(),
subject,
actor,
correlation_id: session_id.clone(),
causation_id: Some(causation_id),
execution_id: recording.execution_id,
session_id: Some(session_id),
payload_id: None,
details,
})
}
pub fn recording_timeline(
&self,
session_id: &str,
cwd: Option<&str>,
limit: usize,
) -> Result<DebuggerTimeline, String> {
let recording = self
.recording_status(session_id)?
.ok_or_else(|| format!("Debugger session \"{session_id}\" has no recording"))?;
let requested_limit = if limit == 0 {
TIMELINE_DEFAULT_LIMIT
} else {
limit.min(TIMELINE_MAX_LIMIT)
};
let (mut items, source_truncated) = self.recording_timeline_items(&recording, cwd)?;
let total = items.len();
if total > requested_limit {
let mut protected = items
.iter()
.filter(|item| {
matches!(item.kind.as_str(), "mark" | "error" | "exception" | "diff")
})
.cloned()
.collect::<Vec<_>>();
let mut protected_kinds = protected
.iter()
.map(|item| item.kind.clone())
.collect::<HashSet<_>>();
for item in items.iter().rev() {
if protected_kinds.insert(item.kind.clone()) {
protected.push(item.clone());
}
}
items.drain(..total - requested_limit);
let retained = items
.iter()
.map(|item| item.id.clone())
.collect::<HashSet<_>>();
items.extend(
protected
.into_iter()
.filter(|item| !retained.contains(&item.id)),
);
items.sort_by(|left, right| {
left.at
.cmp(&right.at)
.then_with(|| timeline_order(&left.kind).cmp(&timeline_order(&right.kind)))
.then_with(|| left.id.cmp(&right.id))
});
}
let generated_at = now_ms();
let html = render_timeline_report(&recording, &items, generated_at, total);
let report = self.store.put_debugger_artifact(
session_id,
recording.execution_id.as_deref(),
"debugger_timeline_report",
"text/html",
html.as_bytes(),
)?;
Ok(DebuggerTimeline {
recording_id: recording.id,
session_id: session_id.to_string(),
items,
report,
generated_at,
truncated: source_truncated || total > requested_limit,
})
}
pub fn recording_why(
&self,
session_id: &str,
cwd: Option<&str>,
substring: Option<&str>,
window_ms: u64,
) -> Result<DebuggerWhy, String> {
let recording = self
.recording_status(session_id)?
.ok_or_else(|| format!("Debugger session \"{session_id}\" has no recording"))?;
let (items, _) = self.recording_timeline_items(&recording, cwd)?;
let needle = substring.map(str::to_lowercase);
let errors = items
.iter()
.filter(|item| item.kind == "error" || item.kind == "exception")
.filter(|item| {
needle.as_ref().is_none_or(|needle| {
item.label.to_lowercase().contains(needle)
|| item.details.to_string().to_lowercase().contains(needle)
})
})
.collect::<Vec<_>>();
let latest = errors.last().ok_or_else(|| match substring {
Some(value) => format!("No recorded error matches \"{value}\""),
None => "No errors or exceptions are present in the recording".to_string(),
})?;
let target = errors
.iter()
.find(|item| item.label == latest.label && item.kind == latest.kind)
.copied()
.unwrap_or(latest);
let target = (*target).clone();
let window_ms = if window_ms == 0 {
CONTEXT_MARGIN_MS
} else {
window_ms
};
let lower = target.at.saturating_sub(window_ms);
let stack = target
.details
.get("stack")
.and_then(Value::as_str)
.unwrap_or_default()
.to_lowercase();
let mut causes = items
.iter()
.filter(|item| item.at <= target.at && item.at >= lower)
.filter(|item| matches!(item.kind.as_str(), "edit" | "diff" | "execution" | "causal"))
.map(|item| rank_cause(item, &stack, target.at, window_ms))
.collect::<Vec<_>>();
causes.sort_by(|left, right| {
right
.score
.partial_cmp(&left.score)
.unwrap_or(Ordering::Equal)
.then_with(|| right.item.at.cmp(&left.item.at))
.then_with(|| left.item.id.cmp(&right.item.id))
});
causes.truncate(8);
let context = DebuggerWhyContext {
mark: latest_item(&items, "mark", target.at),
prompt: latest_item(&items, "prompt", target.at),
commit: latest_item(&items, "commit", target.at),
edit: latest_item(&items, "edit", target.at),
diff: latest_item(&items, "diff", target.at),
execution: latest_item(&items, "execution", target.at),
};
let answer = build_why_answer(&target, causes.first(), &context);
let mut limitations = Vec::new();
if !items.iter().any(|item| item.kind == "edit") {
limitations.push(
"No file path was present in sanitized invocation input, so file-level edit blame is unavailable."
.to_string(),
);
}
if context.commit.is_none() {
limitations.push(
"No commit identity was present in invocation workspace evidence before the error."
.to_string(),
);
}
if causes.is_empty() {
limitations.push(
"No edit, diff, execution, or causal event was recorded inside the lookback window."
.to_string(),
);
}
Ok(DebuggerWhy {
recording_id: recording.id,
session_id: session_id.to_string(),
target,
causes,
context,
answer,
limitations,
})
}
fn recording_timeline_items(
&self,
recording: &DebuggerRecording,
cwd: Option<&str>,
) -> Result<(Vec<DebuggerTimelineItem>, bool), String> {
let since = recording.started_at.saturating_sub(CONTEXT_MARGIN_MS);
let until = recording
.stopped_at
.unwrap_or_else(now_ms)
.saturating_add(CONTEXT_MARGIN_MS);
let captures = self.store.debugger_captures(&recording.id)?;
let marks = self.store.debugger_marks(&recording.id)?;
let afters = self.store.debugger_afters(&recording.id)?;
let events = self
.store
.debugger_events(&recording.session_id, 0, 1_000)?;
let scope = cwd.map(|cwd| invocation_scope(Some(cwd)));
let mut invocation_query = InvocationQuery {
limit: TIMELINE_MAX_LIMIT,
scope_kind: scope.as_ref().map(|scope| scope.kind),
scope_key: scope.as_ref().and_then(|scope| scope.key.clone()),
since_ms: Some(since),
until_ms: Some(until),
..InvocationQuery::default()
};
let mut invocations = Vec::new();
let mut invocation_source_truncated = false;
for _ in 0..4 {
let page = self.store.timeline_invocations(&invocation_query)?;
invocations.extend(page.invocations);
let Some(cursor) = page.next_cursor else {
invocation_source_truncated = false;
break;
};
invocation_query.cursor = Some(cursor);
invocation_source_truncated = true;
}
let execution_ids = invocations
.iter()
.filter_map(|invocation| invocation.execution_id.clone())
.collect::<HashSet<_>>();
let causal_rows = self.store.causal_events_between(since, until, 1_000)?;
let causal_source_truncated = causal_rows.len() >= 1_000;
let causal = causal_rows
.into_iter()
.filter(|event| {
event.session_id.as_deref() == Some(recording.session_id.as_str())
|| event.execution_id.as_ref().is_some_and(|id| {
execution_ids.contains(id) || recording.execution_id.as_ref() == Some(id)
})
})
.collect::<Vec<_>>();
let mut items = Vec::new();
let mut seen_console = HashSet::new();
let mut seen_exceptions = HashSet::new();
let mut seen_network = HashSet::new();
for capture in &captures {
items.push(DebuggerTimelineItem {
id: format!("capture:{}", capture.id),
at: capture.at,
kind: "capture".to_string(),
label: format!("{}: {}", capture.reason, capture.url),
ref_id: Some(capture.id.clone()),
details: json!({
"sequence":capture.sequence,
"reason":capture.reason,
"url":capture.url,
"scroll_y":capture.scroll_y,
"artifact":capture.screenshot.artifact,
"warnings":capture.state.warnings
}),
});
for entry in &capture.state.console {
if entry.kind != "error" && entry.kind != "assert" {
continue;
}
let key = format!("{}:{}", entry.kind, entry.id);
if seen_console.insert(key.clone()) {
items.push(DebuggerTimelineItem {
id: format!("console:{key}"),
at: epoch_ms(entry.at, capture.at),
kind: "error".to_string(),
label: entry.text.clone(),
ref_id: Some(capture.id.clone()),
details: json!({"console_id":entry.id,"stack":entry.stack.join(" ")}),
});
}
}
for entry in &capture.state.exceptions {
let key = format!("{}:{}", entry.kind, entry.id);
if seen_exceptions.insert(key.clone()) {
items.push(DebuggerTimelineItem {
id: format!("exception:{key}"),
at: epoch_ms(entry.at, capture.at),
kind: "exception".to_string(),
label: entry.text.clone(),
ref_id: Some(capture.id.clone()),
details: json!({
"exception_id":entry.id,
"kind":entry.kind,
"file":entry.file,
"line":entry.line,
"stack":format!("{}:{}", entry.file, entry.line),
"uncaught":entry.uncaught
}),
});
}
}
for request in &capture.state.network {
if request.error.is_none() && request.status.is_none_or(|status| status < 400) {
continue;
}
if seen_network.insert(request.id.clone()) {
items.push(DebuggerTimelineItem {
id: format!("network:{}", request.id),
at: capture.at,
kind: "network_failure".to_string(),
label: format!("{} {}", request.method, request.url),
ref_id: Some(request.id.clone()),
details: json!({"status":request.status,"error":request.error}),
});
}
}
}
for mark in marks {
items.push(DebuggerTimelineItem {
id: format!("mark:{}", mark.id),
at: mark.at,
kind: "mark".to_string(),
label: mark.name,
ref_id: Some(mark.capture_id),
details: Value::Null,
});
}
for after in afters {
items.push(DebuggerTimelineItem {
id: format!("after:{}", after.id),
at: after.at,
kind: "diff".to_string(),
label: format!("{:.3}% pixels changed", after.diff_percent),
ref_id: Some(after.id),
details: json!({
"before_capture_id":after.before_capture_id,
"after_capture_id":after.after_capture_id,
"diff_pixels":after.diff_pixels,
"region":after.region,
"report":after.report
}),
});
}
let debugger_events_source_truncated = events.len() >= 1_000;
for event in events
.into_iter()
.filter(|event| event.at >= since && event.at <= until)
{
items.push(DebuggerTimelineItem {
id: format!("debugger_event:{}", event.id),
at: event.at,
kind: "debugger_event".to_string(),
label: event.kind,
ref_id: event.execution_id,
details: event.details,
});
}
for event in causal {
let item_kind = causal_item_kind(&event.kind, &event.details);
let path = (item_kind == "edit")
.then(|| named_strings(&event.details, "path").into_iter().next())
.flatten();
let ref_id = if item_kind == "commit" {
named_strings(&event.details, "commit").into_iter().next()
} else {
event.execution_id.clone().or(event.payload_id.clone())
};
items.push(DebuggerTimelineItem {
id: format!("causal:{}", event.id),
at: event.at,
kind: item_kind.to_string(),
label: format!("{}: {}", event.kind, event.subject),
ref_id,
details: json!({
"actor":event.actor,
"correlation_id":event.correlation_id,
"causation_id":event.causation_id,
"path":path,
"data":event.details
}),
});
}
append_invocation_items(&mut items, &invocations);
items.sort_by(|left, right| {
left.at
.cmp(&right.at)
.then_with(|| timeline_order(&left.kind).cmp(&timeline_order(&right.kind)))
.then_with(|| left.id.cmp(&right.id))
});
Ok((
items,
invocation_source_truncated
|| causal_source_truncated
|| debugger_events_source_truncated
|| captures.len() >= 1_000,
))
}
}
fn append_invocation_items(
items: &mut Vec<DebuggerTimelineItem>,
invocations: &[InvocationRecord],
) {
let mut commits = BTreeSet::new();
let mut diffs = BTreeSet::new();
for invocation in invocations {
if let Some(purpose) = invocation.purpose.as_ref() {
items.push(DebuggerTimelineItem {
id: format!("prompt:{}", invocation.id),
at: invocation.started_at,
kind: "prompt".to_string(),
label: purpose.clone(),
ref_id: Some(invocation.id.clone()),
details: json!({"command_path":invocation.command_path,"actor":invocation.actor}),
});
}
if let Some(execution_id) = invocation.execution_id.as_ref() {
items.push(DebuggerTimelineItem {
id: format!("execution:{}:{}", execution_id, invocation.id),
at: invocation.started_at,
kind: "execution".to_string(),
label: invocation.command_path.clone(),
ref_id: Some(execution_id.clone()),
details: json!({
"invocation_id":invocation.id,
"status":invocation.status,
"exit_code":invocation.exit_code,
"error_code":invocation.error_code,
"error":invocation.error
}),
});
}
for commit in named_strings(&invocation.normalized_input, "commit") {
if !commit.is_empty() && commits.insert(commit.clone()) {
items.push(DebuggerTimelineItem {
id: format!("commit:{}", commit),
at: invocation.started_at,
kind: "commit".to_string(),
label: short_value(&commit),
ref_id: Some(commit),
details: json!({"invocation_id":invocation.id}),
});
}
}
for digest in named_strings(&invocation.normalized_input, "dirty_digest") {
if !digest.is_empty() && diffs.insert(digest.clone()) {
items.push(DebuggerTimelineItem {
id: format!("workspace_diff:{}", digest),
at: invocation.started_at,
kind: "diff".to_string(),
label: format!("workspace {}", short_value(&digest)),
ref_id: Some(digest),
details: json!({"invocation_id":invocation.id,"command_path":invocation.command_path}),
});
}
}
}
}
fn rank_cause(
item: &DebuggerTimelineItem,
stack: &str,
target_at: u64,
window_ms: u64,
) -> DebuggerWhyCause {
let ms_before = target_at.saturating_sub(item.at);
let recency = 1.0 - ms_before as f64 / window_ms.max(1) as f64;
let path = item
.details
.get("path")
.and_then(Value::as_str)
.unwrap_or(&item.label);
let basename = path
.rsplit(['/', '\\'])
.next()
.unwrap_or(path)
.to_lowercase();
let in_stack = !stack.is_empty() && !basename.is_empty() && stack.contains(&basename);
DebuggerWhyCause {
item: item.clone(),
score: recency + if in_stack { 1.0 } else { 0.0 },
in_stack,
ms_before,
}
}
fn latest_item(
items: &[DebuggerTimelineItem],
kind: &str,
at: u64,
) -> Option<DebuggerTimelineItem> {
items
.iter()
.rev()
.find(|item| item.kind == kind && item.at <= at)
.cloned()
}
fn build_why_answer(
target: &DebuggerTimelineItem,
cause: Option<&DebuggerWhyCause>,
context: &DebuggerWhyContext,
) -> String {
let head = format!(
"\"{}\" first appeared at {}",
truncate(&target.label, 80),
target.at
);
let Some(cause) = cause else {
return format!("{head}; no recorded cause was found in the lookback window");
};
let mut answer = format!(
"{head}, {} after {} {}",
format_duration(cause.ms_before),
cause.item.kind,
truncate(&cause.item.label, 80)
);
if cause.in_stack {
answer.push_str("; its file appears in the stack");
}
if let Some(mark) = context.mark.as_ref() {
answer.push_str(&format!(" (mark: {})", truncate(&mark.label, 40)));
}
if let Some(edit) = context.edit.as_ref() {
answer.push_str(&format!(" (edit: {})", truncate(&edit.label, 40)));
}
answer
}
fn render_timeline_report(
recording: &DebuggerRecording,
items: &[DebuggerTimelineItem],
generated_at: u64,
total: usize,
) -> String {
let cards = items
.iter()
.map(|item| {
let image = if item.kind == "capture" {
item.details
.pointer("/artifact/path")
.and_then(Value::as_str)
.and_then(|path| std::fs::read(path).ok())
.map(|bytes| {
let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
format!("<img alt=\"Recorded browser capture\" src=\"data:image/png;base64,{encoded}\">")
})
.unwrap_or_default()
} else {
String::new()
};
format!(
"<article class=\"{}\"><div class=\"kind\">{}</div><h2>{}</h2><time>{}</time>{}<pre>{}</pre></article>",
html_escape(&item.kind),
html_escape(&item.kind),
html_escape(&item.label),
item.at,
image,
html_escape(&serde_json::to_string_pretty(&item.details).unwrap_or_default())
)
})
.collect::<Vec<_>>()
.join("\n");
format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>apoc debugger timeline</title><style>body{{margin:0;background:#0b0d10;color:#e8edf2;font:14px ui-monospace,monospace}}header{{position:sticky;top:0;background:#11151bcc;padding:20px;backdrop-filter:blur(12px);z-index:1}}main{{display:flex;gap:16px;overflow:auto;padding:20px;align-items:flex-start}}article{{width:360px;min-width:360px;background:#151a21;border:1px solid #303946;border-radius:12px;padding:14px}}article.capture{{width:520px;min-width:520px}}img{{display:block;width:100%;height:auto;border-radius:8px;margin:12px 0}}h1,h2{{margin:0 0 8px}}h2{{font-size:15px;overflow-wrap:anywhere}}.kind{{color:#7dd3fc;text-transform:uppercase;font-size:11px;letter-spacing:.08em}}time{{color:#94a3b8}}pre{{white-space:pre-wrap;overflow-wrap:anywhere;color:#bac6d3}}</style></head><body><header><h1>apoc debugger timeline</h1><div>recording {} · showing {} of {} items · generated {}</div></header><main>{}</main></body></html>",
html_escape(&recording.id),
items.len(),
total,
generated_at,
cards
)
}
fn epoch_ms(value: f64, fallback: u64) -> u64 {
if !value.is_finite() || value <= 0.0 {
return fallback;
}
if value >= 1_000_000_000_000.0 {
value as u64
} else if value >= 1_000_000_000.0 {
(value * 1_000.0) as u64
} else {
fallback
}
}
fn named_strings(value: &Value, name: &str) -> Vec<String> {
let mut output = Vec::new();
collect_named_strings(value, name, &mut output);
output
}
fn collect_named_strings(value: &Value, name: &str, output: &mut Vec<String>) {
match value {
Value::Object(values) => {
for (key, value) in values {
if key == name
&& let Some(value) = value.as_str()
{
output.push(value.to_string());
}
collect_named_strings(value, name, output);
}
}
Value::Array(values) => {
for value in values {
collect_named_strings(value, name, output);
}
}
_ => {}
}
}
fn causal_item_kind<'a>(kind: &'a str, details: &Value) -> &'a str {
let kind_lower = kind.to_lowercase();
let has_path = named_strings(details, "path")
.into_iter()
.any(|path| !path.is_empty());
if kind_lower.contains("commit")
&& named_strings(details, "commit")
.into_iter()
.any(|commit| !commit.is_empty())
{
"commit"
} else if has_path
&& ["edit", "write", "patch", "mutation"]
.iter()
.any(|marker| kind_lower.contains(marker))
{
"edit"
} else {
"causal"
}
}
fn timeline_order(kind: &str) -> u8 {
match kind {
"mark" => 0,
"prompt" | "commit" | "edit" => 1,
"execution" | "causal" | "debugger_event" => 2,
"capture" => 3,
"error" | "exception" | "network_failure" => 4,
"diff" => 5,
_ => 6,
}
}
fn short_value(value: &str) -> String {
value.chars().take(12).collect()
}
fn format_duration(milliseconds: u64) -> String {
if milliseconds < 1_000 {
format!("{milliseconds}ms")
} else {
format!("{:.1}s", milliseconds as f64 / 1_000.0)
}
}
fn truncate(value: &str, max: usize) -> String {
if value.chars().count() <= max {
value.to_string()
} else {
let mut value = value
.chars()
.take(max.saturating_sub(1))
.collect::<String>();
value.push('…');
value
}
}
fn html_escape(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ranks_a_recent_stack_file_above_a_newer_unrelated_edit() {
let stack_edit = DebuggerTimelineItem {
id: "edit:cart".to_string(),
at: 1_000,
kind: "edit".to_string(),
label: "src/Cart.tsx".to_string(),
ref_id: None,
details: json!({"path":"src/Cart.tsx"}),
};
let unrelated = DebuggerTimelineItem {
id: "edit:css".to_string(),
at: 1_900,
kind: "edit".to_string(),
label: "src/site.css".to_string(),
ref_id: None,
details: json!({"path":"src/site.css"}),
};
let stack = rank_cause(&stack_edit, "at cart.tsx:12", 2_000, 5_000);
let unrelated = rank_cause(&unrelated, "at cart.tsx:12", 2_000, 5_000);
assert!(stack.in_stack);
assert!(stack.score > unrelated.score);
}
#[test]
fn normalizes_epoch_and_monotonic_debugger_times_truthfully() {
assert_eq!(epoch_ms(1_700_000_000_000.0, 7), 1_700_000_000_000);
assert_eq!(epoch_ms(1_700_000_000.0, 7), 1_700_000_000_000);
assert_eq!(epoch_ms(123.0, 7), 7);
}
}