use super::*;
use crate::router::test_log::{captured_logs, log_capture};
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
const UNDECLARED: ConnectionId = ConnectionId::new(30);
fn restart_settings_rig() -> Rig {
let mut rig = Rig::new();
let fields = rig.declaration.schema["properties"]
.as_object_mut()
.unwrap();
fields.remove("credential");
for (field, apply) in [("model", "module_restart"), ("transport", "daemon_restart")] {
fields.insert(
field.into(),
json!({"type":"string", "description":field, "default":"initial", "x-ck-apply":apply}),
);
}
write_settings(&rig, "{}");
rig
}
fn write_settings(rig: &Rig, contents: &str) {
std::fs::write(&rig.declaration.user_file, contents).unwrap();
}
fn serve_settings(owner: &RuntimeOwner, connection: ConnectionId) -> ConfigView {
let reply = owner
.module_get(connection, "a", ConfigGetRequest::new())
.unwrap();
owner
.module_view_delivered(connection, "a", &reply, tokio::time::Instant::now(), true)
.unwrap();
reply.active.unwrap()
}
#[test]
fn config_gate_unstamped_user_file_only_module_restart_wins_over_the_hint() {
use crate::config_gate::runtime::unstamped::UserFileWatch;
for (edit, served, fields, hint) in [
(r#"{"model":"changed"}"#, true, &["/model"][..], false),
(r#"{"limit":2,"model":"changed"}"#, true, &["/model"], false),
(r#"{"limit":2}"#, true, &[], true),
(
r#"{"model":"changed","transport":"changed"}"#,
true,
&[],
true,
),
(r#"{"model":"changed","limit":false}"#, true, &[], false),
(r#"{"model":"changed"}"#, false, &[], false),
] {
let rig = restart_settings_rig();
let owner = rig.owner("watch-restart-policy");
rig.declare(&owner, INCUMBENT.get());
if served {
serve_settings(&owner, INCUMBENT);
}
let mut watch = UserFileWatch::default();
write_settings(&rig, edit);
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
let request = watch.take_restart();
assert_eq!(
request
.as_ref()
.map(|request| request.fields.as_slice())
.unwrap_or_default(),
fields,
"{edit}"
);
assert_eq!(owner.take_unstamp_hint(INCUMBENT).unwrap(), hint, "{edit}");
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
assert!(watch.take_restart().is_none(), "{edit}");
assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap(), "{edit}");
}
}
#[test]
fn config_gate_unstamped_user_file_coalesces_queued_restart_then_watches_replacement() {
use crate::config_gate::runtime::unstamped::UserFileWatch;
let rig = restart_settings_rig();
let owner = rig.owner("watch-restart-coalescing");
rig.declare(&owner, INCUMBENT.get());
serve_settings(&owner, INCUMBENT);
let mut watch = UserFileWatch::default();
write_settings(&rig, r#"{"model":"first"}"#);
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
let queued = watch.take_restart().expect("first edit requests a restart");
write_settings(&rig, r#"{"model":"second","limit":3}"#);
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
assert!(watch.take_restart().is_none());
assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap());
drop(queued);
owner.disconnected(INCUMBENT);
rig.declare(&owner, CANDIDATE.get());
let replacement = serve_settings(&owner, CANDIDATE);
assert_eq!(
replacement.effective,
json!({"model":"second","limit":3,"transport":"initial"})
);
let mut watch = UserFileWatch::default();
owner.poll_user_file(CANDIDATE, "a", &mut watch).unwrap();
assert!(
watch.take_restart().is_none(),
"unchanged file must not restart the replacement"
);
assert!(!owner.take_unstamp_hint(CANDIDATE).unwrap());
write_settings(&rig, r#"{"model":"third","limit":3}"#);
owner.poll_user_file(CANDIDATE, "a", &mut watch).unwrap();
assert_eq!(watch.take_restart().unwrap().connection, CANDIDATE);
}
#[cfg(unix)]
mod supervision {
use super::*;
use crate::{
router::OutboundFrame,
supervise::{
ModuleOverlap, RestartPolicy, SupervisedModule, Supervisor, SupervisorHandle,
SwapOutcome,
},
ForwardingTable, FrameSink, Registry,
};
use subc_protocol::{Frame, FrameType};
use tokio::time::timeout;
struct RestartRig {
rig: Rig,
owner: Arc<RuntimeOwner>,
registry: Arc<Registry>,
forwarding: Arc<ForwardingTable>,
module: SupervisedModule,
handler: Arc<crate::ControlHandler>,
idle: mpsc::UnboundedReceiver<(ConnectionId, oneshot::Sender<()>)>,
}
impl RestartRig {
fn new(mode: &'static str) -> Self {
let rig = restart_settings_rig();
rig.write_native_program(mode);
let mut spec = supervised_spec(&rig, "a");
spec.protocol = subc_control::ModuleProtocol::Subc;
spec.overlap = ModuleOverlap::Safe;
spec.env = ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
.into_iter()
.map(|key| (key.into(), rig.path.display().to_string()))
.collect();
std::fs::write(rig.path.join("subc.jsonc"), serde_json::to_vec(&json!({
"version":1, "modules":{"a":{
"program":spec.program, "args":spec.args, "env":spec.env.iter().cloned().collect::<BTreeMap<_,_>>(),
"protocol":"subc", "overlap":"safe", "registration_channel":true
}}
})).unwrap()).unwrap();
let owner = Arc::new(rig.owner("supervised-settings-restart"));
let registry = Arc::new(Registry::default());
let forwarding = Arc::new(ForwardingTable::default());
let handle = SupervisorHandle::new();
handle.capture_registration_channels_for_test();
let supervisor =
Supervisor::new_for_test(registry.clone(), RestartPolicy::new(3, Duration::ZERO))
.with_handle(handle.clone())
.with_forwarding(forwarding.clone())
.with_config_runtime(owner.clone())
.with_drain_timeout(Duration::from_secs(10));
let handler = Arc::new(
crate::ControlHandler::with_forwarding(registry.clone(), forwarding.clone())
.with_supervisor(handle)
.with_config_runtime(owner.clone()),
);
let (sender, idle) = mpsc::unbounded_channel();
*owner.user_file_test_idle.lock().unwrap() = Some(sender);
let module = supervisor.spawn(spec).unwrap();
Self {
rig,
owner,
registry,
forwarding,
module,
handler,
idle,
}
}
fn register(
&self,
connection: ConnectionId,
candidate: bool,
) -> mpsc::Receiver<OutboundFrame> {
let mut manifest =
subc_protocol::manifest::ModuleManifest::builder("a", "1.0.0").build();
manifest.ready = Some(true);
manifest.capabilities =
Some(serde_json::from_value(json!({"provides":["accepting-drain/v1"]})).unwrap());
let version = subc_protocol::PROTOCOL_VERSION;
let mut ops = vec!["config.review".into()];
if candidate {
ops.push("health.check".into());
}
let (sender, receiver) = mpsc::channel(8);
let sink = FrameSink::new(sender);
let concurrency = subc_protocol::manifest::Concurrency::ModuleManaged;
if candidate {
self.registry
.register_candidate_with_control_ops(manifest, version, connection, ops)
.unwrap();
self.forwarding
.register_candidate_module_connection(
connection,
"a".into(),
version,
concurrency,
sink,
)
.unwrap();
} else {
self.registry
.register_with_control_ops(manifest, version, connection, ops)
.unwrap();
self.forwarding
.register_module_connection(connection, "a".into(), version, concurrency, sink)
.unwrap();
}
receiver
}
async fn wait_for_starts(&self, count: usize) {
wait_for_supervised_stage(&self.module, "fixture child started", || {
std::fs::read_to_string(self.rig.path.join("a.launches"))
.is_ok_and(|text| text.lines().count() == count)
})
.await;
}
async fn worker_idle(&mut self, connection: ConnectionId) -> oneshot::Sender<()> {
let (observed, resume) = timeout(Duration::from_secs(5), self.idle.recv())
.await
.unwrap()
.unwrap();
assert_eq!(observed, connection);
resume
}
fn poll_again(&self, resume: oneshot::Sender<()>) {
self.owner.notify_delivery_changed();
resume.send(()).unwrap();
}
fn close(&self, connection: ConnectionId) {
self.forwarding.cleanup_connection(connection).unwrap();
self.registry.deregister_connection(connection).unwrap();
self.owner.disconnected(connection);
}
}
async fn next(receiver: &mut mpsc::Receiver<OutboundFrame>) -> Frame {
timeout(Duration::from_secs(5), receiver.recv())
.await
.unwrap()
.unwrap()
.frame
}
fn body(frame: &Frame) -> serde_json::Value {
serde_json::from_slice(&frame.body).unwrap()
}
#[tokio::test]
async fn config_gate_unstamped_restart_drains_coalesces_and_preserves_crash_budget() {
let mut rig = RestartRig::new("mark-first-exit23");
rig.wait_for_starts(2).await;
wait_for_supervised_stage(&rig.module, "incumbent published after the crash", || {
rig.module
.status()
.is_ok_and(|status| status.process_alive && status.spawn_generation == 2)
})
.await;
let incumbent = rig.module.status().unwrap();
assert_eq!(incumbent.restart_count, 1, "the first child really crashed");
let mut incumbent_frames = rig.register(INCUMBENT, false);
rig.rig.declare(&rig.owner, INCUMBENT.get());
serve_settings(&rig.owner, INCUMBENT);
let _worker = WorkerGuard(rig.handler.spawn_config_delivery_worker().unwrap());
let resume = rig.worker_idle(INCUMBENT).await;
let (logs, _logs_guard) = log_capture(tracing::Level::INFO);
write_settings(&rig.rig, r#"{"model":"private-first"}"#);
rig.poll_again(resume);
let notice = body(&next(&mut incumbent_frames).await);
assert_eq!(
notice["op"], "module.draining",
"restart must replace the hint"
);
assert_eq!(notice["accepting"], true);
let resume = rig.worker_idle(INCUMBENT).await;
write_settings(&rig.rig, r#"{"model":"private-second","limit":3}"#);
rig.poll_again(resume);
let _paused_incumbent = rig.worker_idle(INCUMBENT).await;
assert!(
incumbent_frames.try_recv().is_err(),
"nothing is pushed while draining"
);
assert_eq!(rig.module.status().unwrap().pid, incumbent.pid);
let ack = Frame::build(
FrameType::Response,
subc_protocol::Flags(0),
0,
0,
1,
vec![],
)
.unwrap();
assert!(rig
.forwarding
.mark_accepting_drain_ready(INCUMBENT, ack)
.unwrap());
assert_eq!(
next(&mut incumbent_frames).await.header.ty,
FrameType::Response
);
assert_eq!(
next(&mut incumbent_frames).await.header.ty,
FrameType::Goodbye
);
rig.close(INCUMBENT);
let pid = rustix::process::Pid::from_raw(incumbent.pid.unwrap() as i32).unwrap();
rustix::process::kill_process(pid, rustix::process::Signal::TERM).unwrap();
rig.wait_for_starts(3).await;
wait_for_supervised_stage(&rig.module, "replacement published after the drain", || {
rig.module.status().is_ok_and(|status| {
status.process_alive && status.spawn_generation > incumbent.spawn_generation
})
})
.await;
let replacement = rig.module.status().unwrap();
assert_eq!(replacement.spawn_generation, incumbent.spawn_generation + 1);
assert_eq!(
replacement.restart_count, incumbent.restart_count,
"a settings restart neither spends nor clears crash budget"
);
rig.rig.declare(&rig.owner, CANDIDATE.get());
assert_eq!(
serve_settings(&rig.owner, CANDIDATE).effective,
json!({"model":"private-second","limit":3,"transport":"initial"})
);
let mut replacement_frames = rig.register(CANDIDATE, false);
rig.owner.notify_delivery_changed();
let resume = rig.worker_idle(CANDIDATE).await;
rig.poll_again(resume);
let _paused_replacement = rig.worker_idle(CANDIDATE).await;
timeout(Duration::from_secs(5), rig.module.config_exit_hold())
.await
.unwrap()
.unwrap();
assert!(
replacement_frames.try_recv().is_err(),
"the replacement must not receive a hint or a drain for the same file"
);
assert_eq!(rig.module.status().unwrap().pid, replacement.pid);
let text = captured_logs(&logs);
let restarts: Vec<_> = text
.lines()
.filter(|line| line.contains("settings change needs a module restart"))
.collect();
assert_eq!(restarts.len(), 1, "{text}");
for expected in ["INFO", "module_id=a", "fields=/model"] {
assert!(restarts[0].contains(expected), "{}", restarts[0]);
}
assert!(!restarts[0].contains("private-"));
rig.close(CANDIDATE);
rig.module.stop().await.unwrap();
}
#[tokio::test]
async fn config_gate_unstamped_restart_during_swap_is_discarded_after_cutover() {
let mut rig = RestartRig::new("pid-sleep");
rig.wait_for_starts(1).await;
let mut incumbent_frames = rig.register(INCUMBENT, false);
rig.rig.declare(&rig.owner, INCUMBENT.get());
serve_settings(&rig.owner, INCUMBENT);
let _worker = WorkerGuard(rig.handler.spawn_config_delivery_worker().unwrap());
let resume = rig.worker_idle(INCUMBENT).await;
let swap = tokio::spawn({
let module = rig.module.clone();
async move { module.swap(Some(Duration::from_secs(10))).await }
});
rig.wait_for_starts(2).await;
write_settings(&rig.rig, r#"{"model":"swapped"}"#);
rig.poll_again(resume);
let _paused_incumbent = tokio::select! {
paused = rig.worker_idle(INCUMBENT) => paused,
frame = next(&mut incumbent_frames) => panic!("unexpected frame during warm-up: {:?}", body(&frame)),
};
assert!(
!timeout(Duration::from_secs(5), rig.module.set_enabled(true))
.await
.unwrap()
.unwrap()
);
rig.owner
.declare(CANDIDATE, "a", rig.rig.declaration.clone(), false)
.unwrap();
assert_eq!(
serve_settings(&rig.owner, CANDIDATE).effective["model"],
"swapped"
);
let mut candidate_frames = rig.register(CANDIDATE, true);
let probe = next(&mut candidate_frames).await;
assert_eq!(body(&probe)["op"], "health.check");
rig.forwarding
.complete_module_control_rpc(
CANDIDATE,
probe.header.corr,
Some("health.check"),
crate::forwarding::ModuleControlRpcOutcome::Response(
subc_protocol::session::ModuleControlResponse::HealthCheck {
status: subc_protocol::session::HealthStatus::Ok,
detail: None,
metrics: None,
summary: None,
},
),
)
.unwrap();
assert_eq!(
timeout(Duration::from_secs(5), swap)
.await
.unwrap()
.unwrap()
.unwrap(),
SwapOutcome::Cutover
);
timeout(Duration::from_secs(5), rig.module.config_exit_hold())
.await
.unwrap()
.unwrap();
assert_eq!(
rig.registry.get_module("a").unwrap().unwrap().connection_id,
CANDIDATE
);
assert_eq!(rig.module.status().unwrap().spawn_generation, 2);
while let Ok(OutboundFrame { frame, .. }) = candidate_frames.try_recv() {
assert_eq!(
body(&frame)["op"],
"health.check",
"the incumbent's request must not drain the candidate"
);
}
rig.close(INCUMBENT);
rig.close(CANDIDATE);
rig.module.stop().await.unwrap();
}
}
fn write_limit(rig: &Rig, limit: u64) {
std::fs::write(
rig.path.join("cortexkit/a.jsonc"),
format!("{{\"limit\":{limit}}}"),
)
.unwrap();
}
struct LiveFiles {
rig: Rig,
owner: Arc<RuntimeOwner>,
registry: Arc<crate::Registry>,
forwarding: Arc<crate::ForwardingTable>,
_handler: Arc<crate::ControlHandler>,
_worker: WorkerGuard,
_clock: WorkerGuard,
idle: mpsc::UnboundedReceiver<(ConnectionId, oneshot::Sender<()>)>,
paused: HashMap<ConnectionId, oneshot::Sender<()>>,
receivers: Vec<(ConnectionId, mpsc::Receiver<crate::router::OutboundFrame>)>,
pushes: Vec<(ConnectionId, serde_json::Value)>,
}
impl LiveFiles {
async fn new() -> Self {
let clock = hold_test_clock();
let mut rig = Rig::new();
rig.declaration.schema["properties"]
.as_object_mut()
.unwrap()
.remove("credential");
write_limit(&rig, 1);
let owner = Arc::new(rig.owner("live-files"));
rig.declare(&owner, INCUMBENT.get());
let registry = Arc::new(crate::Registry::default());
let forwarding = Arc::new(crate::ForwardingTable::default());
let handler = Arc::new(
crate::ControlHandler::with_forwarding(registry.clone(), forwarding.clone())
.with_config_runtime(owner.clone()),
);
let (sender, idle) = mpsc::unbounded_channel();
*owner.user_file_test_idle.lock().unwrap() = Some(sender);
let worker = WorkerGuard(handler.spawn_config_delivery_worker().unwrap());
let mut live = Self {
rig,
owner,
registry,
forwarding,
_handler: handler,
_worker: worker,
_clock: clock,
idle,
paused: HashMap::new(),
receivers: vec![],
pushes: vec![],
};
live.register(INCUMBENT, "a");
live.get();
live.owner.notify_delivery_changed();
live.until_idle(INCUMBENT).await;
assert!(
live.pushes.is_empty(),
"an initial observation is not an edit"
);
live
}
fn register(&mut self, connection: ConnectionId, module: &str) {
self.registry
.register_with_control_ops(
subc_protocol::manifest::ModuleManifest::builder(module, "0.1.0").build(),
subc_protocol::PROTOCOL_VERSION,
connection,
vec!["config.review".into()],
)
.unwrap();
let (sender, receiver) = mpsc::channel(8);
self.forwarding
.register_module_connection(
connection,
module.into(),
subc_protocol::PROTOCOL_VERSION,
subc_protocol::manifest::Concurrency::ModuleManaged,
crate::FrameSink::new(sender),
)
.unwrap();
self.receivers.push((connection, receiver));
}
fn get(&self) -> subc_protocol::config::ConfigGetReply {
let reply = self
.owner
.module_get(INCUMBENT, "a", ConfigGetRequest::new())
.unwrap();
self.owner
.module_view_delivered(INCUMBENT, "a", &reply, tokio::time::Instant::now(), true)
.unwrap();
reply
}
async fn until_idle(&mut self, connection: ConnectionId) {
wait_for_blocking_delivery(|| {
for (connection, receiver) in &mut self.receivers {
while let Ok(mut outbound) = receiver.try_recv() {
assert_eq!(outbound.frame.header.ty, subc_protocol::FrameType::Push);
let body: serde_json::Value =
serde_json::from_slice(&outbound.frame.body).unwrap();
assert_eq!(body["op"], "config.changed");
self.pushes.push((*connection, body));
outbound.flushed.take().unwrap().send(()).unwrap();
}
}
while let Ok((connection, resume)) = self.idle.try_recv() {
assert!(self.paused.insert(connection, resume).is_none());
}
self.paused.contains_key(&connection)
})
.await;
}
async fn tick(&mut self) {
tokio::time::advance(Duration::from_secs(2)).await;
self.paused.remove(&INCUMBENT).unwrap().send(()).unwrap();
self.until_idle(INCUMBENT).await;
}
fn expect_edit(&mut self) {
assert_eq!(
self.pushes.len(),
1,
"one generation-0 edit hint: {:?}",
self.pushes
);
assert_eq!(self.pushes[0].0, INCUMBENT);
assert_eq!(self.pushes[0].1["generation"], 0);
self.pushes.clear();
}
async fn real_edit(&mut self) {
write_limit(&self.rig, 2);
self.tick().await;
self.expect_edit();
assert_eq!(self.get().active.unwrap().effective["limit"], 2);
}
}
#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_edit_pushes_and_get_returns_new_bytes() {
let mut live = LiveFiles::new().await;
live.real_edit().await;
let path = live.rig.path.join("cortexkit/a.jsonc");
let raw = b"{ /* literal user bytes */ \"limit\":3 }";
std::fs::write(&path, raw).unwrap();
live.tick().await;
live.expect_edit();
let reply = live.get();
let view = reply.active.unwrap();
assert_eq!(view.generation, 0);
assert_eq!(view.status, ConfigStatus::Unstamped);
assert_eq!(view.layers[0].bytes.as_deref(), Some(raw.as_slice()));
assert!(reply.pending.is_none());
std::fs::remove_file(&path).unwrap();
live.tick().await;
live.expect_edit();
assert_eq!(live.get().active.unwrap().layers[0].bytes, None);
std::fs::write(&path, raw).unwrap();
live.tick().await;
live.expect_edit();
assert_eq!(
live.get().active.unwrap().layers[0].bytes.as_deref(),
Some(raw.as_slice())
);
live.owner.disconnected(INCUMBENT);
let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
assert_eq!(
live.owner
.poll_user_file(INCUMBENT, "a", &mut watch)
.unwrap(),
crate::config_gate::runtime::unstamped::UserFilePoll::Stopped
);
assert!(!live
.owner
.lock()
.unwrap()
.delivery
.unstamped_views
.contains_key(&INCUMBENT));
}
#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_same_bytes_and_touch_send_no_push() {
let mut live = LiveFiles::new().await;
live.real_edit().await;
let path = live.rig.path.join("cortexkit/a.jsonc");
let file = std::fs::File::options().write(true).open(&path).unwrap();
let modified = file.metadata().unwrap().modified().unwrap() + Duration::from_secs(10);
file.set_times(std::fs::FileTimes::new().set_modified(modified))
.unwrap();
live.tick().await;
assert!(
live.pushes.is_empty(),
"a touch must not push: {:?}",
live.pushes
);
let replacement = live.rig.path.join("same-bytes.jsonc");
std::fs::write(&replacement, std::fs::read(&path).unwrap()).unwrap();
std::fs::rename(replacement, path).unwrap();
live.tick().await;
assert!(
live.pushes.is_empty(),
"an identical replacement must not push: {:?}",
live.pushes
);
}
#[test]
fn config_gate_unstamped_user_file_refusal_logs_once_and_reports_path() {
use crate::config_gate::runtime::unstamped::UserFileWatch;
let mut rig = Rig::new();
rig.declaration.schema["properties"]
.as_object_mut()
.unwrap()
.remove("credential");
write_limit(&rig, 1);
let owner = rig.owner("user-file-refusal");
rig.declare(&owner, INCUMBENT.get());
let good = owner
.module_get(INCUMBENT, "a", ConfigGetRequest::new())
.unwrap();
owner
.module_view_delivered(INCUMBENT, "a", &good, tokio::time::Instant::now(), true)
.unwrap();
let (logs, _guard) = log_capture(tracing::Level::INFO);
let mut watch = UserFileWatch::default();
let path = &rig.declaration.user_file;
let refused = br#"{"limit":2,"not/declared":true}"#;
std::fs::write(path, refused).unwrap();
for _ in 0..3 {
let _ = owner.poll_user_file(INCUMBENT, "a", &mut watch);
assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap());
}
let text = captured_logs(&logs);
let warnings: Vec<_> = text
.lines()
.filter(|line| line.contains("user settings file refused"))
.collect();
assert_eq!(warnings.len(), 1, "{text}");
for part in ["WARN", "module_id=a", path, "reason=a: /not~1declared"] {
assert!(warnings[0].contains(part), "{}", warnings[0]);
}
assert_eq!(
serde_json::to_value(owner.polled_status().unwrap()).unwrap()["file_errors"],
json!([{
"module_id":"a", "code":"value_invalid", "message":"a: /not~1declared", "path":path,
"pointer":"/not~1declared"
}])
);
assert_eq!(
owner.lock().unwrap().delivery.unstamped_views[&INCUMBENT].as_ref(),
good.active.as_ref().unwrap()
);
let replacement = rig.path.join("replacement.jsonc");
std::fs::write(&replacement, refused).unwrap();
std::fs::rename(replacement, path).unwrap();
let mut watch = UserFileWatch::default();
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
assert_eq!(
captured_logs(&logs)
.matches("user settings file refused")
.count(),
1
);
std::fs::write(path, br#"{"limit":3,"not/declared":true}"#).unwrap();
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
assert_eq!(
captured_logs(&logs)
.matches("user settings file refused")
.count(),
2
);
assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap());
write_limit(&rig, 3);
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
assert!(owner.take_unstamp_hint(INCUMBENT).unwrap());
owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
assert!(owner.polled_status().unwrap().file_errors.is_empty());
let text = captured_logs(&logs);
let recoveries: Vec<_> = text
.lines()
.filter(|line| line.contains("user settings file accepted after refusal"))
.collect();
assert_eq!(recoveries.len(), 1, "{text}");
for part in ["INFO", "module_id=a", path] {
assert!(recoveries[0].contains(part), "{}", recoveries[0]);
}
}
#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_stamp_stops_generation_zero_pushes() {
let mut live = LiveFiles::new().await;
live.real_edit().await;
let generation = live.rig.stamp(&live.owner);
live.owner
.complete_authority_exit_for_test(generation)
.unwrap();
write_limit(&live.rig, 3);
live.tick().await;
assert_eq!(
live.pushes.len(),
1,
"the approved pending generation must still be delivered"
);
assert!(
live.pushes
.iter()
.all(|(_, push)| push["generation"] == generation),
"{:?}",
live.pushes
);
let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
assert_eq!(
live.owner
.poll_user_file(INCUMBENT, "a", &mut watch)
.unwrap(),
crate::config_gate::runtime::unstamped::UserFilePoll::Stopped,
"stamped files must not be watched"
);
let prepared = live.owner.prepare(PlanKind::Unstamp).unwrap();
let plan = live.owner.finish_plan(prepared, daemon_review).unwrap();
live.owner
.desktop_view_delivered(ConnectionId::new(7), &plan)
.unwrap();
let challenge = live
.owner
.begin_approval(&plan.digest, &Rig::facts())
.unwrap();
let unstamped = live
.owner
.finish_approval(
challenge.attempt(),
&Rig::facts(),
ApprovalReply::Presence(crate::config_gate::PresenceDecision::InteractiveApproval),
2,
)
.unwrap();
live.owner
.complete_authority_exit_for_test(unstamped)
.unwrap();
live.pushes.clear();
live.tick().await;
assert!(live.pushes.iter().all(|(_, push)| push["generation"] == 0));
live.pushes.clear();
assert_eq!(live.get().active.unwrap().effective["limit"], 3);
write_limit(&live.rig, 4);
live.tick().await;
live.expect_edit();
assert_eq!(live.get().active.unwrap().effective["limit"], 4);
}
#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_undeclared_module_gets_no_push() {
let mut live = LiveFiles::new().await;
live.real_edit().await;
live.register(UNDECLARED, "c");
std::fs::write(live.rig.path.join("cortexkit/c.jsonc"), b"{}").unwrap();
live.owner.notify_delivery_changed();
live.until_idle(UNDECLARED).await;
assert!(
live.pushes.is_empty(),
"an opted-in but undeclared module must not get a push: {:?}",
live.pushes
);
let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
assert_eq!(
live.owner
.poll_user_file(UNDECLARED, "c", &mut watch)
.unwrap(),
crate::config_gate::runtime::unstamped::UserFilePoll::Stopped
);
}
#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_over_bound_is_never_unchanged() {
let live = LiveFiles::new().await;
std::fs::write(
live.rig.path.join("cortexkit/a.jsonc"),
vec![b' '; 1024 * 1024 + 1],
)
.unwrap();
let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
for _ in 0..2 {
assert_eq!(
live.owner
.poll_user_file(INCUMBENT, "a", &mut watch)
.unwrap(),
crate::config_gate::runtime::unstamped::UserFilePoll::Observed
);
}
}
#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_unchanged_tick_takes_no_owner_guard() {
use std::sync::atomic::Ordering::SeqCst;
let mut live = LiveFiles::new().await;
live.real_edit().await;
live.tick().await;
live.tick().await;
let guards = live.owner.owner_guards.load(SeqCst);
let builds = live.owner.projection_builds.load(SeqCst);
for _ in 0..3 {
live.tick().await;
}
assert!(live.pushes.is_empty(), "{:?}", live.pushes);
assert_eq!(
live.owner.owner_guards.load(SeqCst),
guards,
"an unchanged timer pass must not take an owner guard"
);
assert_eq!(live.owner.projection_builds.load(SeqCst), builds);
let modified = std::fs::metadata(live.rig.path.join("cortexkit/a.jsonc"))
.unwrap()
.modified()
.unwrap();
write_limit(&live.rig, 5);
{
let file = std::fs::OpenOptions::new()
.write(true)
.open(live.rig.path.join("cortexkit/a.jsonc"))
.unwrap();
file.set_modified(modified).unwrap();
assert_eq!(file.metadata().unwrap().modified().unwrap(), modified);
}
live.tick().await;
live.expect_edit();
assert!(live.owner.owner_guards.load(SeqCst) > guards);
}