use super::*;
use crate::operator_apps::{dev_builds, TestOperatorAppPolicy};
use crate::peer_identity_lane::{CheckPoint, PeerIdentityLane};
use crate::router::test_log::{captured_logs, log_capture};
use std::future::{poll_fn, Future};
use std::pin::{pin, Pin};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Condvar;
use std::task::Poll;
use std::time::{Duration, Instant};
use subc_os::local_peer::{
check_dev_app_bundle,
fixture::{SignedAppFixture, SignedPeerFixture},
};
use tokio::sync::Semaphore;
const CONNECTION: ConnectionId = ConnectionId::new(73);
const IDENTIFIER: &str = "io.cortexkit.fixture.route-stamp";
struct Fixture {
handler: ControlHandler,
lane: Arc<PeerIdentityLane>,
checks: Arc<AtomicUsize>,
caps: CapabilityDeclarations,
_socket: std::os::unix::net::UnixStream,
_process: SignedPeerFixture,
_root: cortexkit_test_support::ScratchDir,
}
impl Fixture {
fn new() -> Self {
Self::with_check_probe(false, |_| {})
}
fn with_check_probe(dev: bool, probe: impl Fn(CheckPoint) + Send + Sync + 'static) -> Self {
let root = cortexkit_test_support::ScratchDir::new("route-stamp-lane");
let identifier = if dev {
dev_builds::IDENTIFIER
} else {
IDENTIFIER
};
let bundle =
SignedAppFixture::new(&root.join("app"), identifier, Some("1.2.10"), true, None);
let mut process = bundle.launch();
let (socket, peer) = process.connect();
let checks = Arc::new(AtomicUsize::new(0));
let lane = Arc::new(
PeerIdentityLane::start()
.with_probe({
let checks = checks.clone();
move || {
checks.fetch_add(1, Ordering::Relaxed);
}
})
.with_check_probe(probe),
);
let mut handler = ControlHandler::default();
handler.operator_app_policy = TestOperatorAppPolicy {
macos_enabled: true,
windows_enabled: false,
linux_enabled: false,
app: "test-app",
requirement: "identifier \"io.cortexkit.fixture.route-stamp\"",
floor: semver::Version::new(1, 2, 10),
windows_publisher: None,
windows_path: None,
linux_path: None,
windows_breakaway: true,
linux_force_direct: false,
}
.into();
if dev {
let code = check_dev_app_bundle(bundle.bundle(), identifier).unwrap();
let store = dev_builds::TrustedBuilds::memory_for_tests();
store
.add(subc_control::TrustedAppBuild::new(
identifier.into(),
dev_builds::format_hash(code.cdhash),
"1.2.10".into(),
code.build_time,
0,
))
.unwrap();
handler.operator_app_policy.trusted_builds = Arc::new(store);
}
handler.operator_app_policy.test_lane = Some(lane.clone());
handler.record_captured_peer(CONNECTION, peer);
let caps =
serde_json::from_value(serde_json::json!({"provides": [OPERATOR_APP_CAPABILITY]}))
.unwrap();
Self {
handler,
lane,
checks,
caps,
_socket: socket,
_process: process,
_root: root,
}
}
async fn bind(&self) -> Option<OperatorAppStamp> {
self.candidate()
.await
.and_then(RouteOperatorApp::into_current_stamp)
}
async fn candidate(&self) -> Option<RouteOperatorApp> {
self.handler
.route_operator_app(CONNECTION, Some(&self.caps), "restarted-module", "test")
.await
}
}
struct Hold {
entered: Semaphore,
released: Mutex<bool>,
wake: Condvar,
}
struct Occupancy(Arc<Hold>);
type Filler<'a> = Pin<Box<dyn Future<Output = Option<()>> + 'a>>;
impl Occupancy {
fn new() -> Self {
Self(Arc::new(Hold {
entered: Semaphore::new(0),
released: Mutex::new(false),
wake: Condvar::new(),
}))
}
fn check_probe(&self, point: CheckPoint) -> impl Fn(CheckPoint) + Send + Sync + 'static {
let hold = self.0.clone();
move |reached| {
if reached == point {
hold.block();
}
}
}
async fn fill<'a>(&self, lane: &'a PeerIdentityLane, count: usize) -> Vec<Filler<'a>> {
let mut jobs = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
for _ in 0..count {
let hold = self.0.clone();
let mut job: Filler<'_> = Box::pin(lane.run_until(deadline, move || hold.block()));
assert!(poll_once(job.as_mut()).await.is_pending());
jobs.push(job);
}
jobs
}
async fn workers_entered(&self) {
self.entered(2).await;
}
async fn entered(&self, n: u32) {
tokio::time::timeout(Duration::from_secs(5), self.0.entered.acquire_many(n))
.await
.expect("worker reached the hold")
.unwrap()
.forget();
}
fn release(&self) {
*self.0.released.lock().unwrap() = true;
self.0.wake.notify_all();
}
}
impl Hold {
fn block(&self) {
let released = self.released.lock().unwrap();
self.entered.add_permits(1);
drop(
self.wake
.wait_while(released, |released| !*released)
.unwrap(),
);
}
}
impl Drop for Occupancy {
fn drop(&mut self) {
self.release();
}
}
async fn poll_once<F: Future + ?Sized>(mut future: Pin<&mut F>) -> Poll<F::Output> {
poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx))).await
}
#[tokio::test]
async fn concurrent_reopened_binds_share_only_the_in_flight_check() {
let fixture = Fixture::new();
let original = fixture.bind().await.expect("recognize stamped peer");
let occupied = Occupancy::new();
let _workers = occupied.fill(&fixture.lane, 2).await;
occupied.workers_entered().await;
let before = fixture.checks.load(Ordering::Relaxed);
let mut pending = Vec::new();
for _ in 0..6 {
let mut bind = Box::pin(fixture.bind());
assert!(
poll_once(bind.as_mut()).await.is_pending(),
"a reopened bind was refused while the workers were busy"
);
pending.push(bind);
}
occupied.release();
for bind in pending {
assert!(original.same_generation(&bind.await.expect("reopened route is stamped")));
}
assert_eq!(fixture.checks.load(Ordering::Relaxed), before + 1);
assert!(original.same_generation(&fixture.bind().await.unwrap()));
assert_eq!(
fixture.checks.load(Ordering::Relaxed),
before + 2,
"a later bind must revalidate again"
);
}
#[tokio::test]
async fn reopened_bind_waits_for_a_full_identity_queue() {
bind_waits_for_full_queue(true).await;
}
#[tokio::test]
async fn first_bind_waits_for_a_full_identity_queue() {
bind_waits_for_full_queue(false).await;
}
async fn bind_waits_for_full_queue(recognize_first: bool) {
let fixture = Fixture::new();
if recognize_first {
fixture.bind().await.expect("recognize stamped peer");
}
let occupied = Occupancy::new();
let _workers = occupied.fill(&fixture.lane, 2).await;
occupied.workers_entered().await;
let _queued = occupied.fill(&fixture.lane, 2).await;
let mut bind = pin!(fixture.bind());
tokio::select! {
() = fixture.lane.waiting_for_capacity.notified() => {},
_ = &mut bind => panic!("bind did not wait for lane capacity"),
}
occupied.release();
assert!(bind.await.is_some(), "bind stamps after a queue slot opens");
}
#[tokio::test]
async fn first_bind_retries_refused_immediate_recognition() {
let fixture = Fixture::new();
let occupied = Occupancy::new();
let _workers = occupied.fill(&fixture.lane, 2).await;
occupied.workers_entered().await;
let _queued = occupied.fill(&fixture.lane, 2).await;
let mut describe = pin!(fixture
.handler
.recognize_operator_peer(CONNECTION, Admission::Immediate));
assert!(poll_once(describe.as_mut()).await.is_pending());
let original_deadline = fixture.handler.captured_peers.lock().unwrap()[&CONNECTION]
.recognized
.lock()
.unwrap()
.as_ref()
.unwrap()
.deadline;
let mut bind = pin!(fixture.bind());
assert!(poll_once(bind.as_mut()).await.is_pending());
let described = describe.await;
assert!(described.fresh.is_none());
assert!(poll_once(bind.as_mut()).await.is_pending());
let capture = fixture.handler.captured_peers.lock().unwrap()[&CONNECTION].clone();
{
let recognition = capture.recognized.lock().unwrap();
let retry = recognition.as_ref().unwrap();
assert_eq!(
retry.deadline, original_deadline,
"retry shares the first attempt's budget"
);
assert!(matches!(
*retry.verdict.borrow(),
RecognitionVerdict::Pending
));
}
occupied.release();
assert!(bind.await.is_some());
}
#[tokio::test]
async fn reopened_binds_fail_closed_and_warn_once_when_admission_expires() {
let fixture = Fixture::new();
fixture.bind().await.expect("recognize stamped peer");
let occupied = Occupancy::new();
let _workers = occupied.fill(&fixture.lane, 2).await;
occupied.workers_entered().await;
let _queued = occupied.fill(&fixture.lane, 2).await;
let before = fixture.checks.load(Ordering::Relaxed);
let (output, _logs) = log_capture(tracing::Level::WARN);
let (first, second) = tokio::join!(fixture.bind(), fixture.bind());
assert!(first.is_none() && second.is_none());
assert_eq!(
fixture.checks.load(Ordering::Relaxed),
before,
"native work did not run"
);
let logs = captured_logs(&output);
let mut warnings = logs
.lines()
.filter(|line| line.contains("operator app stamp could not be revalidated"));
let warning = warnings.next().expect("timed-out stamp check warns");
assert!(warning.contains("connection_id=73"), "{warning}");
assert!(
warning.contains("module_id=\"restarted-module\""),
"{warning}"
);
assert!(warning.contains("reason=\"deadline\""), "{warning}");
assert!(
warnings.next().is_none(),
"concurrent binds should not repeat the warning: {logs}"
);
}
#[tokio::test]
async fn revocation_fences_a_bind_joining_an_already_checked_flight() {
let hold = Occupancy::new();
let fixture =
Fixture::with_check_probe(true, hold.check_probe(CheckPoint::RevalidationChecked));
let original = fixture.bind().await.expect("approved dev build is stamped");
let hash = original
.dev_hash()
.expect("fixture stamped through dev trust");
let mut first = Box::pin(fixture.bind());
assert!(poll_once(first.as_mut()).await.is_pending());
hold.entered(1).await;
assert!(fixture
.handler
.operator_app_policy
.trusted_builds
.remove(&hash)
.unwrap());
let mut joining = Box::pin(fixture.bind());
let joined = poll_once(joining.as_mut()).await;
hold.release();
let stamp = match joined {
Poll::Ready(stamp) => stamp,
Poll::Pending => joining.await,
};
assert!(
stamp.is_none(),
"a bind joining after revocation reused the old trust check"
);
assert!(
first.await.is_none(),
"revocation also invalidates the first bind"
);
}
#[tokio::test]
async fn revocation_after_verification_fences_the_stamp_at_attachment() {
let fixture = Fixture::with_check_probe(true, |_| {});
let candidate = fixture
.candidate()
.await
.expect("approved dev build is verified");
let hash = candidate
.stamp
.dev_hash()
.expect("fixture stamped through dev trust");
assert!(fixture
.handler
.operator_app_policy
.trusted_builds
.remove(&hash)
.unwrap());
assert!(candidate.into_current_stamp().is_none());
}
#[tokio::test]
async fn first_recognition_cannot_resubmit_while_its_native_check_hangs() {
let hold = Occupancy::new();
let fixture =
Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionStarted));
let mut first = Box::pin(fixture.bind());
assert!(poll_once(first.as_mut()).await.is_pending());
hold.entered(1).await;
assert!(first.await.is_none());
let (output, _logs) = log_capture(tracing::Level::WARN);
assert!(fixture.bind().await.is_none());
assert!(fixture.bind().await.is_none());
assert_eq!(
fixture.checks.load(Ordering::Relaxed),
1,
"a hung recognition resubmitted native work"
);
let logs = captured_logs(&output);
assert_eq!(
logs.matches("reason=\"check_running\"").count(),
1,
"{logs}"
);
assert!(
logs.contains("connection_id=73") && logs.contains("restarted-module"),
"{logs}"
);
assert_eq!(
fixture.lane.run(|| 42).await,
Some(42),
"the other worker remains available"
);
hold.release();
}
#[tokio::test]
async fn a_bind_joining_after_native_recognition_returned_revalidates() {
let hold = Occupancy::new();
let fixture =
Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionReturned));
let mut first = Box::pin(fixture.bind());
assert!(poll_once(first.as_mut()).await.is_pending());
hold.entered(1).await;
let mut later = Box::pin(fixture.bind());
assert!(poll_once(later.as_mut()).await.is_pending());
hold.release();
let original = first.await.expect("recognition stamps the original bind");
assert!(original.same_generation(&later.await.expect("later bind revalidated")));
assert_eq!(
fixture.checks.load(Ordering::Relaxed),
2,
"late bind reused evidence from a check that finished before it arrived"
);
}
#[tokio::test]
async fn cancelling_the_bind_that_started_a_flight_does_not_cancel_the_check() {
let hold = Occupancy::new();
let fixture =
Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RevalidationStarted));
fixture.bind().await.expect("recognize stamped peer");
let mut first = Box::pin(fixture.bind());
assert!(poll_once(first.as_mut()).await.is_pending());
hold.entered(1).await;
drop(first);
let mut follower = Box::pin(fixture.bind());
assert!(poll_once(follower.as_mut()).await.is_pending());
hold.release();
assert!(follower.await.is_some());
assert_eq!(
fixture.checks.load(Ordering::Relaxed),
2,
"recognition plus one flight"
);
}
#[tokio::test]
async fn reopened_bind_warns_when_its_previous_native_check_is_still_running() {
let hold = Occupancy::new();
let fixture =
Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RevalidationStarted));
fixture.bind().await.expect("recognize stamped peer");
let mut first = Box::pin(fixture.bind());
assert!(poll_once(first.as_mut()).await.is_pending());
hold.entered(1).await;
assert!(first.await.is_none());
let (output, _logs) = log_capture(tracing::Level::WARN);
assert!(fixture.bind().await.is_none());
assert!(fixture.bind().await.is_none());
assert_eq!(fixture.checks.load(Ordering::Relaxed), 2);
let logs = captured_logs(&output);
assert_eq!(
logs.matches("reason=\"check_running\"").count(),
1,
"{logs}"
);
assert!(
logs.contains("connection_id=73") && logs.contains("restarted-module"),
"{logs}"
);
}
fn set_recognition(
fixture: &Fixture,
deadline: Instant,
initial: RecognitionVerdict,
progress: Arc<RecognitionProgress>,
) -> watch::Sender<RecognitionVerdict> {
let (publish, verdict) = watch::channel(initial);
let capture = fixture.handler.captured_peers.lock().unwrap()[&CONNECTION].clone();
*capture.recognized.lock().unwrap() = Some(Recognition {
deadline,
verdict,
progress,
});
publish
}
#[tokio::test]
async fn expired_recognition_result_cannot_stamp_a_waiting_bind() {
let fixture = Fixture::new();
let stamp = OperatorAppStamp::fixture("test-app", 42);
fixture
.handler
.operator_apps
.lock()
.unwrap()
.insert(CONNECTION, stamp.clone());
let deadline = Instant::now() + EVIDENCE_BUDGET;
let progress = Arc::<RecognitionProgress>::default();
let publish = set_recognition(
&fixture,
deadline,
RecognitionVerdict::Pending,
progress.clone(),
);
let mut bind = pin!(fixture.bind());
assert!(poll_once(bind.as_mut()).await.is_pending());
progress.complete_for_test(deadline);
tokio::time::sleep_until(deadline.into()).await;
publish.send_replace(RecognitionVerdict::Complete {
stamp: Some(stamp),
dev_build: None,
});
assert!(
bind.await.is_none(),
"a ready recognition verdict must not beat its elapsed deadline"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn expired_complete_recognition_cannot_be_fresh_on_retry() {
let hold = Occupancy::new();
let fixture =
Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionRetrying));
let deadline = Instant::now() + EVIDENCE_BUDGET;
let publish = set_recognition(
&fixture,
deadline,
RecognitionVerdict::Pending,
Arc::default(),
);
let handler = fixture.handler.clone();
let mut waiting = Box::pin(async move {
handler
.recognize_operator_peer(CONNECTION, Admission::Wait)
.await
.fresh
});
assert!(poll_once(waiting.as_mut()).await.is_pending());
publish.send_replace(RecognitionVerdict::AdmissionRefused);
let retrying = tokio::spawn(waiting);
hold.entered(1).await;
let progress = Arc::<RecognitionProgress>::default();
progress.complete_for_test(deadline);
let _completed = set_recognition(
&fixture,
deadline,
RecognitionVerdict::Complete {
stamp: Some(OperatorAppStamp::fixture("test-app", 42)),
dev_build: None,
},
progress,
);
tokio::time::sleep_until(deadline.into()).await;
hold.release();
assert!(
retrying.await.unwrap().is_none(),
"a completed retry must not supply fresh evidence after its deadline"
);
}