tempo: rustfmt the new code, LF endings as the base has them

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-01 01:46:10 +01:00
commit a40be6201b
3 changed files with 1049 additions and 838 deletions

View file

@ -44,7 +44,11 @@ pub struct Gains {
/// Chosen by the committed simulation (`docs/research/2026-11-01-tempo-pid-sim.md`), /// Chosen by the committed simulation (`docs/research/2026-11-01-tempo-pid-sim.md`),
/// never by a run-time search. /// never by a run-time search.
pub const GAINS: Gains = Gains { kp: 0.02, ki: 0.01, kd: 0.0 }; pub const GAINS: Gains = Gains {
kp: 0.02,
ki: 0.01,
kd: 0.0,
};
/// The fallback controller's memory. The heartbeat owns persisting it; it is /// The fallback controller's memory. The heartbeat owns persisting it; it is
/// never published as truth. `rate_per_h` is the last output as a turn rate /// never published as truth. `rate_per_h` is the last output as a turn rate
@ -79,7 +83,9 @@ pub fn fallback_beat(
fn beat_of(rate_per_h: f64) -> u32 { fn beat_of(rate_per_h: f64) -> u32 {
if rate_per_h > 0.0 { if rate_per_h > 0.0 {
((3600.0 / rate_per_h).round().clamp(f64::from(FALLBACK_MIN_S), f64::from(FALLBACK_MAX_S))) as u32 ((3600.0 / rate_per_h)
.round()
.clamp(f64::from(FALLBACK_MIN_S), f64::from(FALLBACK_MAX_S))) as u32
} else { } else {
FALLBACK_MAX_S FALLBACK_MAX_S
} }
@ -103,9 +109,15 @@ fn control(
target_permille: u32, target_permille: u32,
voted: bool, voted: bool,
) -> u32 { ) -> u32 {
let dt_h = if state.last_now_ms > 0 { (now_ms - state.last_now_ms).max(0) as f64 / HOUR_MS } else { 0.0 }; let dt_h = if state.last_now_ms > 0 {
(now_ms - state.last_now_ms).max(0) as f64 / HOUR_MS
} else {
0.0
};
state.last_now_ms = now_ms; state.last_now_ms = now_ms;
let Some(r) = reading.filter(|r| now_ms < r.resets_at_ms && r.observed_at_ms >= r.resets_at_ms - WINDOW_MS) else { let Some(r) = reading
.filter(|r| now_ms < r.resets_at_ms && r.observed_at_ms >= r.resets_at_ms - WINDOW_MS)
else {
return held(state); return held(state);
}; };
if r.resets_at_ms != state.window_resets_at_ms { if r.resets_at_ms != state.window_resets_at_ms {
@ -115,7 +127,8 @@ fn control(
state.last_observed_at_ms = r.observed_at_ms; state.last_observed_at_ms = r.observed_at_ms;
} }
let elapsed = (now_ms - (r.resets_at_ms - WINDOW_MS)).clamp(0, WINDOW_MS) as f64; let elapsed = (now_ms - (r.resets_at_ms - WINDOW_MS)).clamp(0, WINDOW_MS) as f64;
let error = f64::from(target_permille) * elapsed / WINDOW_MS as f64 - f64::from(r.used_permille); let error =
f64::from(target_permille) * elapsed / WINDOW_MS as f64 - f64::from(r.used_permille);
let fresh = r.observed_at_ms > state.last_observed_at_ms; let fresh = r.observed_at_ms > state.last_observed_at_ms;
let slope = if fresh { let slope = if fresh {
(f64::from(r.used_permille) - f64::from(state.last_used_permille)) (f64::from(r.used_permille) - f64::from(state.last_used_permille))
@ -133,8 +146,12 @@ fn control(
} }
return held(state); return held(state);
} }
let rate = |integral: f64| BIAS_PER_H + gains.kp * error + gains.ki * integral - gains.kd * slope; let rate =
let (low, high) = (3600.0 / f64::from(FALLBACK_MAX_S), 3600.0 / f64::from(FALLBACK_MIN_S)); |integral: f64| BIAS_PER_H + gains.kp * error + gains.ki * integral - gains.kd * slope;
let (low, high) = (
3600.0 / f64::from(FALLBACK_MAX_S),
3600.0 / f64::from(FALLBACK_MIN_S),
);
let before = rate(state.integral); let before = rate(state.integral);
let winding = (before >= high && error > 0.0) || (before <= low && error < 0.0); let winding = (before >= high && error > 0.0) || (before <= low && error < 0.0);
if !winding { if !winding {

View file

@ -80,15 +80,52 @@ const BASE: Scenario = Scenario {
fn scenarios() -> Vec<Scenario> { fn scenarios() -> Vec<Scenario> {
vec![ vec![
BASE, BASE,
Scenario { name: "cheap-turns", mean_cost: 0.6, ..BASE }, Scenario {
Scenario { name: "dear-turns", mean_cost: 3.0, ..BASE }, name: "cheap-turns",
Scenario { name: "burst", burst: Some((48.0, 52.0, 200.0)), ..BASE }, mean_cost: 0.6,
Scenario { name: "cost-x3", cost_step: Some((84.0, 3.0)), ..BASE }, ..BASE
Scenario { name: "vote-300s-24h", vote: Some((48.0, 72.0, 300)), ..BASE }, },
Scenario { name: "rollover", windows: 2, ..BASE }, Scenario {
Scenario { name: "gap-6h", gap: Some((72.0, 78.0)), ..BASE }, name: "dear-turns",
Scenario { name: "start-ahead", start_used: 500.0, ..BASE }, mean_cost: 3.0,
Scenario { name: "unreachable", mean_cost: 0.05, unreachable: true, ..BASE }, ..BASE
},
Scenario {
name: "burst",
burst: Some((48.0, 52.0, 200.0)),
..BASE
},
Scenario {
name: "cost-x3",
cost_step: Some((84.0, 3.0)),
..BASE
},
Scenario {
name: "vote-300s-24h",
vote: Some((48.0, 72.0, 300)),
..BASE
},
Scenario {
name: "rollover",
windows: 2,
..BASE
},
Scenario {
name: "gap-6h",
gap: Some((72.0, 78.0)),
..BASE
},
Scenario {
name: "start-ahead",
start_used: 500.0,
..BASE
},
Scenario {
name: "unreachable",
mean_cost: 0.05,
unreachable: true,
..BASE
},
] ]
} }
@ -142,11 +179,16 @@ fn run(scenario: &Scenario, sensor: Sensor, gains: &Gains, seed: u64) -> Outcome
{ {
used += amount * STEP_MS as f64 / HOUR_MS / (to - from); used += amount * STEP_MS as f64 / HOUR_MS / (to - from);
} }
let gap = scenario.gap.is_some_and(|(from, to)| in_window >= from && in_window < to); let gap = scenario
.gap
.is_some_and(|(from, to)| in_window >= from && in_window < to);
if sensor == Sensor::Poll && !gap && (now - W0) % POLL_MS == 0 { if sensor == Sensor::Poll && !gap && (now - W0) % POLL_MS == 0 {
reading = sense(used, now, resets); reading = sense(used, now, resets);
} }
let vote = scenario.vote.filter(|&(from, to, _)| in_window >= from && in_window < to).map(|v| v.2); let vote = scenario
.vote
.filter(|&(from, to, _)| in_window >= from && in_window < to)
.map(|v| v.2);
let shown = if gap { None } else { Some(reading) }; let shown = if gap { None } else { Some(reading) };
let beat = match vote { let beat = match vote {
Some(beat) => { Some(beat) => {
@ -166,9 +208,16 @@ fn run(scenario: &Scenario, sensor: Sensor, gains: &Gains, seed: u64) -> Outcome
prev_beat = beat; prev_beat = beat;
out.last_beat = beat; out.last_beat = beat;
if now - last_turn >= i64::from(beat) * 1000 { if now - last_turn >= i64::from(beat) * 1000 {
let step = scenario.cost_step.map_or(1.0, |(at, factor)| if in_window >= at { factor } else { 1.0 }); let step = scenario.cost_step.map_or(
1.0,
|(at, factor)| if in_window >= at { factor } else { 1.0 },
);
turns += 1; turns += 1;
let self_run = if turns % SELF_EVERY == 0 { SELF_FACTOR } else { 1.0 }; let self_run = if turns % SELF_EVERY == 0 {
SELF_FACTOR
} else {
1.0
};
used += rng.lognormal(scenario.mean_cost * step) * self_run; used += rng.lognormal(scenario.mean_cost * step) * self_run;
last_turn = now; last_turn = now;
if sensor == Sensor::Stream && !gap { if sensor == Sensor::Stream && !gap {
@ -176,7 +225,8 @@ fn run(scenario: &Scenario, sensor: Sensor, gains: &Gains, seed: u64) -> Outcome
} }
} }
used = used.min(1000.0); used = used.min(1000.0);
let error = f64::from(TARGET) * (now - (resets - WINDOW_MS)) as f64 / WINDOW_MS as f64 - used; let error =
f64::from(TARGET) * (now - (resets - WINDOW_MS)) as f64 / WINDOW_MS as f64 - used;
if window + 1 == scenario.windows { if window + 1 == scenario.windows {
if in_window >= 144.0 { if in_window >= 144.0 {
worst_day = worst_day.max(error.abs()); worst_day = worst_day.max(error.abs());
@ -226,13 +276,22 @@ fn sim_scenarios_meet_target() {
if scenario.unreachable { if scenario.unreachable {
assert_eq!(o.last_beat, FALLBACK_MIN_S, "saturated {tag}"); assert_eq!(o.last_beat, FALLBACK_MIN_S, "saturated {tag}");
assert!(o.frac_at_min > 0.9, "saturated {tag}"); assert!(o.frac_at_min > 0.9, "saturated {tag}");
assert!(o.final_used.iter().all(|u| *u < f64::from(TARGET) - 100.0), "{tag}"); assert!(
o.final_used.iter().all(|u| *u < f64::from(TARGET) - 100.0),
"{tag}"
);
continue; continue;
} }
for used in &o.final_used { for used in &o.final_used {
assert!((used - f64::from(TARGET)).abs() <= FINAL_TOLERANCE, "final {tag}"); assert!(
(used - f64::from(TARGET)).abs() <= FINAL_TOLERANCE,
"final {tag}"
);
} }
assert!(o.worst_error_last_day <= LAST_DAY_ERROR_BOUND, "error {tag}"); assert!(
o.worst_error_last_day <= LAST_DAY_ERROR_BOUND,
"error {tag}"
);
assert!(o.band_crossings <= 2, "oscillation {tag}"); assert!(o.band_crossings <= 2, "oscillation {tag}");
} }
} }
@ -262,7 +321,10 @@ fn sweep() {
if s.unreachable { if s.unreachable {
sat_ok &= o.last_beat == FALLBACK_MIN_S && o.frac_at_min > 0.9; sat_ok &= o.last_beat == FALLBACK_MIN_S && o.frac_at_min > 0.9;
} else { } else {
f = o.final_used.iter().fold(f, |m, u| m.max((u - f64::from(TARGET)).abs())); f = o
.final_used
.iter()
.fold(f, |m, u| m.max((u - f64::from(TARGET)).abs()));
e = e.max(o.worst_error_last_day); e = e.max(o.worst_error_last_day);
cross = cross.max(o.band_crossings); cross = cross.max(o.band_crossings);
} }
@ -283,9 +345,14 @@ fn sweep() {
} }
} }
rows.sort_by(|a, b| a.0.total_cmp(&b.0)); rows.sort_by(|a, b| a.0.total_cmp(&b.0));
println!("kp ki kd | worst final err | worst err last day | worst jumps/h | worst crossings | saturates when unreachable"); println!(
"kp ki kd | worst final err | worst err last day | worst jumps/h | worst crossings | saturates when unreachable"
);
for r in &rows { for r in &rows {
println!("{} {} {} | {:.1} | {:.1} | {:.2} | {} | {}", r.1.kp, r.1.ki, r.1.kd, r.2, r.3, r.4, r.5, r.6); println!(
"{} {} {} | {:.1} | {:.1} | {:.2} | {} | {}",
r.1.kp, r.1.ki, r.1.kd, r.2, r.3, r.4, r.5, r.6
);
} }
for r in rows.iter().take(4) { for r in rows.iter().take(4) {
println!("\nBEST {:?}\n{}", r.1, r.7); println!("\nBEST {:?}\n{}", r.1, r.7);

View file

@ -183,19 +183,39 @@ fn a_longer_beat_does_not_change_who_wins_among_equal_urgency() {
const RESETS: i64 = 1_000_000_000_000; const RESETS: i64 = 1_000_000_000_000;
const MID: i64 = RESETS - WINDOW_MS / 2; const MID: i64 = RESETS - WINDOW_MS / 2;
const HOUR: i64 = 3_600_000; const HOUR: i64 = 3_600_000;
const T: Gains = Gains { kp: 0.02, ki: 0.002, kd: 0.02 }; const T: Gains = Gains {
kp: 0.02,
ki: 0.002,
kd: 0.02,
};
fn read(used_permille: u32, observed_at_ms: i64) -> Reading { fn read(used_permille: u32, observed_at_ms: i64) -> Reading {
Reading { used_permille, observed_at_ms, resets_at_ms: RESETS } Reading {
used_permille,
observed_at_ms,
resets_at_ms: RESETS,
}
} }
fn near(got: u32, want: u32) { fn near(got: u32, want: u32) {
assert!(got.abs_diff(want) <= 1, "{got} is not within one second of {want}"); assert!(
got.abs_diff(want) <= 1,
"{got} is not within one second of {want}"
);
} }
#[test] #[test]
fn behind_target_shortens_the_beat() { fn behind_target_shortens_the_beat() {
let at = |used| control(&T, &mut Fallback::default(), Some(&read(used, MID)), MID, 900, false); let at = |used| {
control(
&T,
&mut Fallback::default(),
Some(&read(used, MID)),
MID,
900,
false,
)
};
// Halfway through the window the trajectory is 450: error +50, 0, -50 is a // Halfway through the window the trajectory is 450: error +50, 0, -50 is a
// turn rate of 5, 4 and 3 an hour. // turn rate of 5, 4 and 3 an hour.
near(at(400), 720); near(at(400), 720);
@ -207,26 +227,48 @@ fn behind_target_shortens_the_beat() {
fn derivative_is_on_measurement() { fn derivative_is_on_measurement() {
let g = Gains { ki: 0.0, ..T }; let g = Gains { ki: 0.0, ..T };
let mut s = Fallback::default(); let mut s = Fallback::default();
near(control(&g, &mut s, Some(&read(410, MID)), MID, 900, false), 750); near(
control(&g, &mut s, Some(&read(410, MID)), MID, 900, false),
750,
);
// A new observation 10 permille higher a quarter hour on: the slope is 40 an hour. // A new observation 10 permille higher a quarter hour on: the slope is 40 an hour.
let next = read(420, MID + 15 * 60_000); let next = read(420, MID + 15 * 60_000);
near(control(&g, &mut s, Some(&next), MID + 15 * 60_000, 900, false), 941); near(
control(&g, &mut s, Some(&next), MID + 15 * 60_000, 900, false),
941,
);
// The same reading again carries no derivative term. // The same reading again carries no derivative term.
near(control(&g, &mut s, Some(&next), MID + 16 * 60_000, 900, false), 778); near(
control(&g, &mut s, Some(&next), MID + 16 * 60_000, 900, false),
778,
);
// A step in the target with used unchanged moves the beat by kp x error alone. // A step in the target with used unchanged moves the beat by kp x error alone.
near(control(&g, &mut s, Some(&next), MID + 18 * 60_000, 1000, false), 639); near(
control(&g, &mut s, Some(&next), MID + 18 * 60_000, 1000, false),
639,
);
} }
#[test] #[test]
fn saturated_output_does_not_wind_up() { fn saturated_output_does_not_wind_up() {
let g = Gains { kp: 0.1, ki: 0.01, kd: 0.0 }; let g = Gains {
kp: 0.1,
ki: 0.01,
kd: 0.0,
};
let day5 = RESETS - 2 * 24 * HOUR; let day5 = RESETS - 2 * 24 * HOUR;
let mut s = Fallback::default(); let mut s = Fallback::default();
let behind = read(0, day5); let behind = read(0, day5);
for i in 0..100 { for i in 0..100 {
assert_eq!(control(&g, &mut s, Some(&behind), day5 + i * 60_000, 900, false), FALLBACK_MIN_S); assert_eq!(
control(&g, &mut s, Some(&behind), day5 + i * 60_000, 900, false),
FALLBACK_MIN_S
);
} }
assert_eq!(s.integral, 0.0, "error is positive and the output is at its limit"); assert_eq!(
s.integral, 0.0,
"error is positive and the output is at its limit"
);
let near_on = read(600, day5 + 100 * 60_000); let near_on = read(600, day5 + 100 * 60_000);
for i in 100..110 { for i in 100..110 {
control(&g, &mut s, Some(&near_on), day5 + i * 60_000, 900, false); control(&g, &mut s, Some(&near_on), day5 + i * 60_000, 900, false);
@ -234,7 +276,10 @@ fn saturated_output_does_not_wind_up() {
assert!(s.integral > 0.0, "unsaturated again, it integrates"); assert!(s.integral > 0.0, "unsaturated again, it integrates");
// Saturated at the slow limit with the error pulling the other way integrates. // Saturated at the slow limit with the error pulling the other way integrates.
let mut s = Fallback { integral: -1000.0, ..Fallback::default() }; let mut s = Fallback {
integral: -1000.0,
..Fallback::default()
};
let reading = read(400, MID); let reading = read(400, MID);
control(&g, &mut s, Some(&reading), MID, 900, false); control(&g, &mut s, Some(&reading), MID, 900, false);
control(&g, &mut s, Some(&reading), MID + HOUR, 900, false); control(&g, &mut s, Some(&reading), MID + HOUR, 900, false);
@ -251,11 +296,23 @@ fn vote_freezes_and_release_is_bumpless() {
s.rate_per_h = 3600.0 / 300.0; s.rate_per_h = 3600.0 / 300.0;
let (mut short, mut long) = (s.clone(), s.clone()); let (mut short, mut long) = (s.clone(), s.clone());
let (t_short, t_long) = (MID + 6 * 60_000, MID + 6 * 60_000 + HOUR); let (t_short, t_long) = (MID + 6 * 60_000, MID + 6 * 60_000 + HOUR);
assert_eq!(control(&T, &mut short, Some(&reading), t_short, 900, true), 300); assert_eq!(
assert_eq!(control(&T, &mut long, Some(&reading), t_long, 900, true), 300); control(&T, &mut short, Some(&reading), t_short, 900, true),
300
);
assert_eq!(
control(&T, &mut long, Some(&reading), t_long, 900, true),
300
);
// However long the vote held, the first beat after it is the voted beat. // However long the vote held, the first beat after it is the voted beat.
near(control(&T, &mut short, Some(&reading), t_short + 60_000, 900, false), 300); near(
near(control(&T, &mut long, Some(&reading), t_long + 60_000, 900, false), 300); control(&T, &mut short, Some(&reading), t_short + 60_000, 900, false),
300,
);
near(
control(&T, &mut long, Some(&reading), t_long + 60_000, 900, false),
300,
);
} }
#[test] #[test]
@ -267,9 +324,16 @@ fn rollover_resets_memory() {
control(&T, &mut s, Some(&read(100, before)), now, 900, false); control(&T, &mut s, Some(&read(100, before)), now, 900, false);
} }
assert!(s.integral > 100.0); assert!(s.integral > 100.0);
let new = Reading { used_permille: 5, observed_at_ms: RESETS + HOUR, resets_at_ms: RESETS + WINDOW_MS }; let new = Reading {
used_permille: 5,
observed_at_ms: RESETS + HOUR,
resets_at_ms: RESETS + WINDOW_MS,
};
// Used fell from 100 to 5 across the reset: no derivative kick, no old integral. // Used fell from 100 to 5 across the reset: no derivative kick, no old integral.
near(control(&T, &mut s, Some(&new), RESETS + HOUR, 900, false), 898); near(
control(&T, &mut s, Some(&new), RESETS + HOUR, 900, false),
898,
);
assert!(s.integral < 2.0); assert!(s.integral < 2.0);
assert_eq!(s.window_resets_at_ms, RESETS + WINDOW_MS); assert_eq!(s.window_resets_at_ms, RESETS + WINDOW_MS);
} }
@ -277,33 +341,96 @@ fn rollover_resets_memory() {
#[test] #[test]
fn no_reading_holds() { fn no_reading_holds() {
let mut s = Fallback::default(); let mut s = Fallback::default();
assert_eq!(control(&T, &mut s, None, MID, 900, false), DEFAULT_BEAT_S, "never set"); assert_eq!(
control(&T, &mut s, None, MID, 900, false),
DEFAULT_BEAT_S,
"never set"
);
let live = read(400, MID); let live = read(400, MID);
control(&T, &mut s, Some(&live), MID, 900, false); control(&T, &mut s, Some(&live), MID, 900, false);
let held = control(&T, &mut s, Some(&live), MID + 60_000, 900, false); let held = control(&T, &mut s, Some(&live), MID + 60_000, 900, false);
assert_ne!(held, DEFAULT_BEAT_S); assert_ne!(held, DEFAULT_BEAT_S);
let integral = s.integral; let integral = s.integral;
assert_eq!(control(&T, &mut s, None, MID + 2 * 60_000, 900, false), held); assert_eq!(
let stale = Reading { observed_at_ms: RESETS - WINDOW_MS - 1, ..live }; control(&T, &mut s, None, MID + 2 * 60_000, 900, false),
assert_eq!(control(&T, &mut s, Some(&stale), MID + 3 * 60_000, 900, false), held); held
let expired = Reading { resets_at_ms: MID + 4 * HOUR, observed_at_ms: MID + 4 * HOUR - WINDOW_MS, ..live }; );
assert_eq!(control(&T, &mut s, Some(&expired), MID + 6 * HOUR, 900, false), held); let stale = Reading {
observed_at_ms: RESETS - WINDOW_MS - 1,
..live
};
assert_eq!(
control(&T, &mut s, Some(&stale), MID + 3 * 60_000, 900, false),
held
);
let expired = Reading {
resets_at_ms: MID + 4 * HOUR,
observed_at_ms: MID + 4 * HOUR - WINDOW_MS,
..live
};
assert_eq!(
control(&T, &mut s, Some(&expired), MID + 6 * HOUR, 900, false),
held
);
assert_eq!(s.integral, integral, "nothing integrated while held"); assert_eq!(s.integral, integral, "nothing integrated while held");
// The six hours without a reading are not integrated when it comes back. // The six hours without a reading are not integrated when it comes back.
control(&T, &mut s, Some(&read(400, MID + 6 * HOUR + 60_000)), MID + 6 * HOUR + 60_000, 900, false); control(
assert!(s.integral - integral < 2.0, "{} then {}", integral, s.integral); &T,
&mut s,
Some(&read(400, MID + 6 * HOUR + 60_000)),
MID + 6 * HOUR + 60_000,
900,
false,
);
assert!(
s.integral - integral < 2.0,
"{} then {}",
integral,
s.integral
);
} }
#[test] #[test]
fn beat_is_bounded() { fn beat_is_bounded() {
let wild = Gains { kp: 1.0, ki: 0.0, kd: 0.0 }; let wild = Gains {
kp: 1.0,
ki: 0.0,
kd: 0.0,
};
let late = RESETS - 12 * HOUR; let late = RESETS - 12 * HOUR;
assert_eq!(control(&wild, &mut Fallback::default(), Some(&read(0, late)), late, 900, false), FALLBACK_MIN_S); assert_eq!(
assert_eq!(control(&wild, &mut Fallback::default(), Some(&read(1000, MID)), MID, 900, false), FALLBACK_MAX_S); control(
&wild,
&mut Fallback::default(),
Some(&read(0, late)),
late,
900,
false
),
FALLBACK_MIN_S
);
assert_eq!(
control(
&wild,
&mut Fallback::default(),
Some(&read(1000, MID)),
MID,
900,
false
),
FALLBACK_MAX_S
);
for used in [0, 1, 450, 900, 1000, 5000] { for used in [0, 1, 450, 900, 1000, 5000] {
for target in [0, 900, 1000] { for target in [0, 900, 1000] {
for gains in [wild, T, GAINS] { for gains in [wild, T, GAINS] {
let beat = control(&gains, &mut Fallback::default(), Some(&read(used, MID)), MID, target, false); let beat = control(
&gains,
&mut Fallback::default(),
Some(&read(used, MID)),
MID,
target,
false,
);
assert!((FALLBACK_MIN_S..=FALLBACK_MAX_S).contains(&beat), "{beat}"); assert!((FALLBACK_MIN_S..=FALLBACK_MAX_S).contains(&beat), "{beat}");
} }
} }