From f85da76b6d1ff71c745fb45d88d12cf3600ac988 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:59:36 -0300 Subject: [PATCH 01/13] test(common): catch the missed mutants in env, secrets, security and shutdown --- crates/common/src/env.rs | 13 ++++++++++++ crates/common/src/secrets.rs | 17 ++++++++++++++- crates/common/src/security.rs | 40 +++++++++++++++++++++++++++-------- crates/common/src/shutdown.rs | 4 +++- 4 files changed, 63 insertions(+), 11 deletions(-) diff --git a/crates/common/src/env.rs b/crates/common/src/env.rs index c6bb680..0f57b78 100644 --- a/crates/common/src/env.rs +++ b/crates/common/src/env.rs @@ -96,6 +96,19 @@ mod tests { assert_eq!(parse_integer(Some("\u{feff}42 "), 5, None, None, "K"), 42); } + #[test] + fn infinity_is_an_invalid_number_not_a_fraction() { + if std::env::var_os("TIMBA_CHILD").is_some() { + assert_eq!(parse_integer(Some("Infinity"), 5, None, None, "K"), 5); + return; + } + let output = crate::log::tests::run_child("env::tests::infinity_is_an_invalid_number_not_a_fraction"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{output:?}"); + assert!(stderr.contains("Ignoring invalid numeric value 'Infinity' for K; using 5."), "{stderr}"); + assert!(!stderr.contains("must be an integer"), "{stderr}"); + } + #[test] fn trims_like_javascript() { // Bun: "\ufeff\u0085\u00a0\u3000x\u2028\n".trim() === "x", while U+200B stays. diff --git a/crates/common/src/secrets.rs b/crates/common/src/secrets.rs index 4108b13..0fe0851 100644 --- a/crates/common/src/secrets.rs +++ b/crates/common/src/secrets.rs @@ -16,7 +16,8 @@ pub fn read_protected_secret(file_path: &str, label: &str) -> Result 4096 { @@ -64,6 +65,20 @@ mod tests { std::fs::write(&file, "x".repeat(size)).unwrap(); assert_eq!(read_protected_secret(path, "T").unwrap_err(), "T has an invalid size"); } + std::fs::write(&file, "x".repeat(4096)).unwrap(); + assert_eq!(read_protected_secret(path, "T").unwrap(), "x".repeat(4096)); + } + + #[test] + fn rejects_a_directory() { + let dir = tempfile::tempdir().unwrap(); + let secret = dir.path().join("token"); + std::fs::create_dir(&secret).unwrap(); + std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!( + read_protected_secret(secret.to_str().unwrap(), "T").unwrap_err(), + "T must be a regular file, not a symlink" + ); } #[test] diff --git a/crates/common/src/security.rs b/crates/common/src/security.rs index 6555307..ede2d9f 100644 --- a/crates/common/src/security.rs +++ b/crates/common/src/security.rs @@ -68,21 +68,20 @@ impl RouteRateLimiter { }; let now = (self.now)(); let mut windows = self.windows.lock().unwrap(); - match windows.get_mut(path) { - Some((started, count)) if now - *started < WINDOW_MS => { + if let Some((started, count)) = windows.get_mut(path) { + let elapsed = now - *started; + if elapsed < WINDOW_MS { *count += 1; if *count <= limit { return RateLimitResult { allowed: true, retry_after_seconds: None }; } - let remaining = WINDOW_MS - (now - *started); - let retry = ((remaining as f64) / 1000.0).ceil().max(1.0) as u64; - RateLimitResult { allowed: false, retry_after_seconds: Some(retry) } - } - _ => { - windows.insert(path, (now, 1)); - RateLimitResult { allowed: true, retry_after_seconds: None } + // `elapsed < WINDOW_MS`, so at least 1 ms of the window is left. + let retry = (WINDOW_MS - elapsed).unsigned_abs().div_ceil(1000); + return RateLimitResult { allowed: false, retry_after_seconds: Some(retry) }; } } + windows.insert(path, (now, 1)); + RateLimitResult { allowed: true, retry_after_seconds: None } } } @@ -130,6 +129,29 @@ mod tests { assert!(!has_valid_bearer_token(Some("abc"), "abc")); assert!(!has_valid_bearer_token(None, "abc")); assert!(!has_valid_bearer_token(Some("Bearer "), "")); + // Two bytes that differ the same way cancel out under `^` but not under `|`. + assert!(!has_valid_bearer_token(Some("Bearer ab"), "ba")); + } + + #[test] + fn request_bodies_stop_at_16_kib_like_api_security_ts() { + assert_eq!(MAX_REQUEST_BODY_BYTES, 16_384); + } + + #[test] + fn a_window_counts_from_its_first_request() { + let clock = Arc::new(AtomicI64::new(600)); + let c = clock.clone(); + let limiter = RouteRateLimiter::new(Box::new(move || c.load(Ordering::SeqCst))); + for _ in 0..10 { + assert!(limiter.check("/stats").allowed); + } + clock.store(1_000, Ordering::SeqCst); + assert_eq!(limiter.check("/stats"), RateLimitResult { allowed: false, retry_after_seconds: Some(1) }); + clock.store(1_599, Ordering::SeqCst); + assert!(!limiter.check("/stats").allowed); + clock.store(1_600, Ordering::SeqCst); + assert!(limiter.check("/stats").allowed); } #[test] diff --git a/crates/common/src/shutdown.rs b/crates/common/src/shutdown.rs index 12a6e5f..c610d38 100644 --- a/crates/common/src/shutdown.rs +++ b/crates/common/src/shutdown.rs @@ -37,7 +37,8 @@ impl Shutdown { /// Sleeps for `ms` or until shutdown, whichever comes first. pub async fn sleep(&self, ms: u64) { - if ms == 0 || self.is_triggered() { + // A triggered shutdown also returns at once: `wait` sees the current value first. + if ms == 0 { return; } tokio::select! { @@ -67,6 +68,7 @@ mod tests { }); shutdown.sleep(60_000).await; assert_eq!(started.elapsed(), Duration::from_millis(60)); + assert!(shutdown.is_triggered()); shutdown.wait().await; shutdown.sleep(60_000).await; assert_eq!(started.elapsed(), Duration::from_millis(60)); From 869ddfca153ef55ed9c6f039a43f48cb4f584a95 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:38:49 -0300 Subject: [PATCH 02/13] test(evm-oracle): catch the missed mutants in the service, server, RPC and timers --- crates/evm-oracle/src/app.rs | 30 ++++++++++++++-- crates/evm-oracle/src/config.rs | 7 ++++ crates/evm-oracle/src/erc8010.rs | 11 +++--- crates/evm-oracle/src/rpc.rs | 11 ++++++ crates/evm-oracle/tests/server.rs | 19 ++++++++++ crates/evm-oracle/tests/service.rs | 56 ++++++++++++++++++++++++++++++ crates/oracle/src/cli/mod.rs | 3 +- crates/oracle/src/core/mod.rs | 36 +++++++++++++++++++ 8 files changed, 165 insertions(+), 8 deletions(-) diff --git a/crates/evm-oracle/src/app.rs b/crates/evm-oracle/src/app.rs index 5b00ada..b7b853a 100644 --- a/crates/evm-oracle/src/app.rs +++ b/crates/evm-oracle/src/app.rs @@ -38,9 +38,8 @@ pub async fn run_cycles( last_warning = now_ms(); warn(CYCLE_FAILED_MESSAGE); } - if !shutdown.is_triggered() { - shutdown.sleep(poll_ms).await; - } + // `sleep` returns at once after a trigger. + shutdown.sleep(poll_ms).await; } } @@ -96,6 +95,31 @@ mod tests { } } + #[tokio::test] + async fn a_failure_exactly_one_minute_after_a_warning_is_not_warned_again() { + let shutdown = Shutdown::new(); + let ticks = Cell::new(0); + let warnings = RefCell::new(0); + let clock = Cell::new(1_000_000); + run_cycles( + || { + ticks.set(ticks.get() + 1); + if ticks.get() == 2 { + clock.set(1_000_000 + WARNING_INTERVAL_MS); + shutdown.trigger(); + } + async { anyhow::bail!("rpc unavailable") } + }, + 1, + &shutdown, + || clock.get(), + |_| *warnings.borrow_mut() += 1, + ) + .await; + assert_eq!(ticks.get(), 2); + assert_eq!(*warnings.borrow(), 1); + } + #[tokio::test] async fn warns_once_per_minute_about_failed_cycles_and_stops_on_shutdown() { let shutdown = Shutdown::new(); diff --git a/crates/evm-oracle/src/config.rs b/crates/evm-oracle/src/config.rs index 799c9a9..f775c5c 100644 --- a/crates/evm-oracle/src/config.rs +++ b/crates/evm-oracle/src/config.rs @@ -244,6 +244,13 @@ mod tests { assert!(error.contains("Duplicate token policy"), "{error}"); } + #[test] + fn accepts_the_largest_safe_start_block() { + let mut value = example(); + value["startBlock"] = Value::from("9007199254740991"); + assert_eq!(parse_config(&value).unwrap().start_block, 9_007_199_254_740_991); + } + #[test] fn rejects_unknown_keys_and_invalid_values() { let mut value = example(); diff --git a/crates/evm-oracle/src/erc8010.rs b/crates/evm-oracle/src/erc8010.rs index 7102f89..0afc905 100644 --- a/crates/evm-oracle/src/erc8010.rs +++ b/crates/evm-oracle/src/erc8010.rs @@ -81,13 +81,16 @@ pub fn is_wrapped(signature: &[u8]) -> bool { /// ox `SignatureErc8010.unwrap`, or `None` when the wrapper is malformed. pub fn unwrap(wrapped: &[u8]) -> Option { - if !is_wrapped(wrapped) || wrapped.len() < 64 { + if !is_wrapped(wrapped) { return None; } - let length_word = U256::from_be_slice(&wrapped[wrapped.len() - 64..wrapped.len() - 32]); + // The magic is the last 32 bytes, and the suffix length the 32 bytes before it. + let length_end = wrapped.len() - 32; + let length_start = length_end.checked_sub(32)?; + let length_word = U256::from_be_slice(&wrapped[length_start..length_end]); let suffix_length = usize::try_from(length_word).ok()?; - let signature_end = (wrapped.len() - 64).checked_sub(suffix_length)?; - let suffix = &wrapped[signature_end..wrapped.len() - 64]; + let signature_end = length_start.checked_sub(suffix_length)?; + let suffix = &wrapped[signature_end..length_start]; let (auth, to, data) = Suffix::abi_decode_params(suffix).ok()?; Some(Wrapped { authorization: SignedAuthorization { diff --git a/crates/evm-oracle/src/rpc.rs b/crates/evm-oracle/src/rpc.rs index 39010f2..9c4683b 100644 --- a/crates/evm-oracle/src/rpc.rs +++ b/crates/evm-oracle/src/rpc.rs @@ -577,6 +577,17 @@ mod tests { RpcError::Node { code, message: message.into(), data } } + #[test] + fn a_null_base_fee_means_a_chain_without_one() { + let block = parse_block(&json!({ + "hash": format!("0x{}", "ab".repeat(32)), + "timestamp": "0x1", + "baseFeePerGas": null, + })) + .unwrap(); + assert_eq!(block.base_fee_per_gas, None); + } + #[test] fn classifies_reverts_like_viem() { assert!(node(3, "execution reverted", Some(json!("0x1234"))).is_contract_revert()); diff --git a/crates/evm-oracle/tests/server.rs b/crates/evm-oracle/tests/server.rs index 8d79472..8302cda 100644 --- a/crates/evm-oracle/tests/server.rs +++ b/crates/evm-oracle/tests/server.rs @@ -88,6 +88,15 @@ async fn all_routes_require_bearer_auth_and_body_limits_cannot_be_bypassed() { .unwrap(); assert_eq!(send(&router, streamed).await.status(), StatusCode::PAYLOAD_TOO_LARGE); + // A streamed body of exactly 16 KiB is read, then rejected as invalid JSON. + let chunks = + futures::stream::iter((0..16).map(|_| Ok::<_, std::io::Error>(axum::body::Bytes::from(vec![b'x'; 1_024])))); + let exact = Request::post("/evm/private-join") + .header("authorization", "Bearer test-token") + .body(Body::from_stream(chunks)) + .unwrap(); + assert_eq!(send(&router, exact).await.status(), StatusCode::BAD_REQUEST); + let invalid = Request::post("/evm/authorize") .header("authorization", "Bearer test-token") .body(Body::from("not json")) @@ -169,6 +178,12 @@ async fn health_allows_three_long_poll_intervals() { assert_eq!(body(response).await["status"], "healthy"); fake.service.last_cycle_at.store(fake.service.now_ms() - 60_001, std::sync::atomic::Ordering::SeqCst); assert_eq!(send(&app, get("/evm/health")).await.status(), StatusCode::SERVICE_UNAVAILABLE); + // Exactly three intervals old is already stale. + fake.set_now_ms(1_700_000_000_000); + fake.service.last_cycle_at.store(1_700_000_000_000 - 60_000, std::sync::atomic::Ordering::SeqCst); + assert_eq!(send(&app, get("/evm/health")).await.status(), StatusCode::SERVICE_UNAVAILABLE); + fake.service.last_cycle_at.store(1_700_000_000_000 - 59_999, std::sync::atomic::Ordering::SeqCst); + assert_eq!(send(&app, get("/evm/health")).await.status(), StatusCode::OK); } #[tokio::test] @@ -239,6 +254,10 @@ async fn pages_public_games_with_their_on_chain_state() { let second_ids: Vec<&Value> = second["games"].as_array().unwrap().iter().map(|game| &game["id"]).collect(); assert_eq!(second_ids, [&json!(ids[0].to_string())]); assert_eq!(second["nextOffset"], Value::Null); + // Exactly one full page left has no next page. + let last_page = body(send(&router, get("/evm/games?offset=1")).await).await; + assert_eq!(last_page["games"].as_array().unwrap().len(), 20); + assert_eq!(last_page["nextOffset"], Value::Null); } #[tokio::test] diff --git a/crates/evm-oracle/tests/service.rs b/crates/evm-oracle/tests/service.rs index a849259..9c4bf70 100644 --- a/crates/evm-oracle/tests/service.rs +++ b/crates/evm-oracle/tests/service.rs @@ -174,6 +174,28 @@ mod authorize { } } + #[tokio::test] + async fn accepts_terms_exactly_on_the_window_limits_and_overflow_bound() { + let fake = setup(); + let now = fake.chain.state().now; + fake.chain.state().limits = [5, 600, 300, 3600, 10]; + for overrides in [ + json!({ "deadline": (now + 300).to_string() }), + json!({ "maxPlayers": 10 }), + json!({ "amount": (U256::MAX / U256::from(2)).to_string() }), + ] { + let input = creation_intent(&fake, overrides.clone()); + let result = fake.service.authorize(&input).await; + assert!(result.is_ok(), "{overrides}: {:?}", result.err()); + } + let input = + creation_intent(&fake, json!({ "amount": (U256::MAX / U256::from(2) + U256::from(1)).to_string() })); + assert_eq!(error_of(fake.service.authorize(&input)).await, "Invalid game terms"); + fake.chain.state().limits = [5, 600, 300, 3599, 10]; + let input = creation_intent(&fake, json!({})); + assert_eq!(error_of(fake.service.authorize(&input)).await, "Game exceeds current oracle limits"); + } + #[tokio::test] async fn rejects_timeouts_and_player_counts_beyond_the_oracle_limits() { let fake = setup(); @@ -300,6 +322,15 @@ mod private_join { assert_eq!(result.to_json(), json!({ "deadline": result.deadline, "signature": result.signature.to_string() })); } + #[tokio::test] + async fn accepts_an_invitation_that_ends_exactly_with_the_window() { + let fake = setup(); + fake.chain.state().games.insert(game_id(), private_game(1, true)); + let now = fake.chain.state().now; + let input = invitation(&fake, Some(now + 300)); + assert!(fake.service.private_join(&input).await.is_ok()); + } + #[tokio::test] async fn rejects_invitations_outside_the_five_minute_window() { let fake = setup(); @@ -382,6 +413,7 @@ mod tick_settlement { assert_eq!((simulated[0].gameId, simulated[0].secret), (GAME_A, SECRET_A)); let simulation = &fake.chain.contract_calls(completeGameCall::SELECTOR)[0][0]; assert_eq!(simulation["from"], operator().to_checksum(None)); + assert_eq!(simulation["to"], PROXY.to_checksum(None)); let estimate = &fake.chain.calls("eth_estimateGas")[0][0]; let data = complete_game_transaction(&fake.service.deployment, GAME_A, SECRET_A).unwrap().data; assert_eq!(estimate["from"], operator().to_checksum(None)); @@ -824,6 +856,28 @@ mod index { assert_eq!(fake.service.store().cursor().unwrap(), None); } + #[tokio::test] + async fn indexes_block_1_once_the_head_reaches_the_confirmation_depth() { + let fake = setup(); + fake.chain.state().head = 2; + + fake.service.index().await.unwrap(); + + assert_eq!(log_ranges(&fake), [("0x0".to_string(), "0x1".to_string())]); + } + + #[tokio::test] + async fn scans_a_single_new_confirmed_block() { + let fake = setup(); + fake.chain.state().head = 10; + fake.service.index().await.unwrap(); + fake.chain.state().head = 11; + + fake.service.index().await.unwrap(); + + assert_eq!(log_ranges(&fake)[1], ("0xa".to_string(), "0xa".to_string())); + } + #[tokio::test] async fn stores_decoded_deployment_events_and_advances_the_cursor() { let fake = setup(); @@ -898,6 +952,8 @@ mod index { fake.service.index().await.unwrap(); assert_eq!(fake.chain.calls("eth_getLogs").len(), 1); + // A cursor exactly at the confirmed head is not a reorganization. + assert_eq!(fake.service.store().cursor().unwrap().map(|cursor| cursor.block), Some(9)); } #[tokio::test] diff --git a/crates/oracle/src/cli/mod.rs b/crates/oracle/src/cli/mod.rs index f39d98e..f2e8bf8 100644 --- a/crates/oracle/src/cli/mod.rs +++ b/crates/oracle/src/cli/mod.rs @@ -238,7 +238,8 @@ where if stats.is_empty() { return Ok(summary); } - let only_errors = stats.errors > 0 && stats.completed == 0 && stats.not_ready == 0; + // The stats are not empty, so with nothing completed or waiting, every game failed. + let only_errors = stats.completed == 0 && stats.not_ready == 0; if !only_errors && stats.not_ready == 0 { return Ok(summary); } diff --git a/crates/oracle/src/core/mod.rs b/crates/oracle/src/core/mod.rs index 999370e..48f271b 100644 --- a/crates/oracle/src/core/mod.rs +++ b/crates/oracle/src/core/mod.rs @@ -22,3 +22,39 @@ fn cancel_timer(timer: Option>) { } } } + +#[cfg(test)] +mod tests { + use super::cancel_timer; + use std::time::Duration; + use tokio::sync::oneshot; + + #[tokio::test] + async fn cancelling_a_timer_aborts_it() { + let (alive, gone) = oneshot::channel::<()>(); + let timer = tokio::spawn(async move { + let _alive = alive; + std::future::pending::<()>().await; + }); + cancel_timer(Some(timer)); + // The abort drops the task and its sender. + let result = tokio::time::timeout(Duration::from_secs(5), gone).await; + assert!(matches!(result, Ok(Err(_))), "{result:?}"); + cancel_timer(None); + } + + #[tokio::test] + async fn a_timer_that_clears_itself_keeps_running() { + let (handle_tx, handle_rx) = oneshot::channel(); + let (done_tx, done_rx) = oneshot::channel(); + let timer = tokio::spawn(async move { + let Ok(own) = handle_rx.await else { return }; + cancel_timer(Some(own)); + tokio::task::yield_now().await; + let _ = done_tx.send(()); + }); + assert!(handle_tx.send(timer).is_ok()); + let result = tokio::time::timeout(Duration::from_secs(5), done_rx).await; + assert!(matches!(result, Ok(Ok(()))), "{result:?}"); + } +} From d9b71e39ec44f07b710a116507f784c6d1f1fb92 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:46:01 -0300 Subject: [PATCH 03/13] test(oracle): catch the missed mutants in the database and events, and stop hanging tests --- .cargo/mutants.toml | 6 ++++++ crates/evm-oracle/tests/main.rs | 7 ++++++- crates/oracle/src/cli/audit_random.rs | 14 ++++++++++++-- crates/oracle/src/db.rs | 16 +++++++++++++++- crates/oracle/src/indexed_events.rs | 8 ++++++++ 5 files changed, 47 insertions(+), 4 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index d2020cf..d28b234 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -1,3 +1,9 @@ # cargo-mutants settings, used by scripts/mutants.sh. # Build and test with the lock file, as CI does. additional_cargo_args = ["--locked"] + +exclude_re = [ + # After the reset statement, a game that it changed is pending with zero attempts, + # so the state check in the fallback also returns Ok. The row count only skips a read. + "replace > with < in OracleDatabase::reset_completion_attempts$", +] diff --git a/crates/evm-oracle/tests/main.rs b/crates/evm-oracle/tests/main.rs index c8f028f..317f212 100644 --- a/crates/evm-oracle/tests/main.rs +++ b/crates/evm-oracle/tests/main.rs @@ -172,7 +172,12 @@ async fn refuses_to_start_when_the_operator_does_not_own_the_proxy() { chain.state().owner = creator(); let url = rpc_endpoint(chain).await; let deployment = deployment(vec![url], &operator_key()); - let error = app::run(Some(deployment.config_file.clone()), Shutdown::new()).await.unwrap_err(); + // If the check passes by mistake, the oracle runs until shutdown, so the test must not wait for it. + let error = + tokio::time::timeout(Duration::from_secs(10), app::run(Some(deployment.config_file.clone()), Shutdown::new())) + .await + .expect("the oracle refuses to start") + .unwrap_err(); assert_eq!(error.to_string(), "EVM operator does not own configured proxy"); } diff --git a/crates/oracle/src/cli/audit_random.rs b/crates/oracle/src/cli/audit_random.rs index b80a489..34947f9 100644 --- a/crates/oracle/src/cli/audit_random.rs +++ b/crates/oracle/src/cli/audit_random.rs @@ -745,7 +745,12 @@ mod tests { } }; let options = CliOptions { once: false, listen: true, write_db: true, ..options(Some(&game)) }; - let (output, ()) = tokio::join!(audit_output(&h, options, ""), events); + // A broken audit must fail here, not wait forever for its listeners. + let (output, ()) = tokio::time::timeout(Duration::from_secs(30), async { + tokio::join!(audit_output(&h, options, ""), events) + }) + .await + .expect("the audit ends after the completion event"); let output = output.unwrap(); let last = output.rsplit("\x1Bc").next().unwrap(); assert!( @@ -796,7 +801,12 @@ mod tests { } }; let options = CliOptions { once: false, listen: true, ..options(Some(&game)) }; - let (output, ()) = tokio::join!(audit_output(&h, options, ""), events); + // A broken audit must fail here, not wait forever for its listeners. + let (output, ()) = tokio::time::timeout(Duration::from_secs(30), async { + tokio::join!(audit_output(&h, options, ""), events) + }) + .await + .expect("the audit ends after the completion event"); let output = output.unwrap(); let last = output.rsplit("\x1Bc").next().unwrap(); assert!(last.contains("Last joiner: alice (ticketIndex=0"), "{last}"); diff --git a/crates/oracle/src/db.rs b/crates/oracle/src/db.rs index 0c69e88..8b2cf65 100644 --- a/crates/oracle/src/db.rs +++ b/crates/oracle/src/db.rs @@ -13,7 +13,8 @@ use crate::token::policy::{normalize_mint, normalize_token_decimals, StoredToken const DEFAULT_STATUS: &str = "pending"; const PENDING_SCAN_LIMIT: i64 = 50; -pub const COMPLETION_RECOVERY_COOLDOWN_MS: i64 = 5 * 60 * 1000; +/// Five minutes. +pub const COMPLETION_RECOVERY_COOLDOWN_MS: i64 = 300_000; mod sql { pub const INSERT_SECRET_KEY: &str = @@ -1262,6 +1263,7 @@ mod tests { assert_eq!((stats.total_secrets, stats.used_secrets, stats.completed_games), (1, 1, 1)); assert!(db.reactivate_secret_key("g1").unwrap()); assert!(db.get_secret_key("g1").is_some()); + assert!(!db.reactivate_secret_key("missing").unwrap()); } #[test] @@ -1605,6 +1607,18 @@ mod tests { assert_eq!(db.get_completion_attempt_state("unknown"), None); } + #[test] + fn a_desynced_game_can_still_be_toggled_and_reset() { + let db = db(); + db.track_game("g", None, false).unwrap(); + db.increment_completion_attempts("g").unwrap(); + db.mark_game_desynced("g").unwrap(); + assert_eq!(db.get_game_status("g").as_deref(), Some("desynced")); + assert_eq!(db.set_auto_complete_disabled("g", true).unwrap(), Ok(true)); + assert_eq!(db.reset_completion_attempts("g", false).unwrap(), Ok(())); + assert_eq!(db.get_completion_attempt_state("g").unwrap().completion_attempts, 0); + } + #[test] fn resets_finalized_games_only_when_allowed() { let db = db(); diff --git a/crates/oracle/src/indexed_events.rs b/crates/oracle/src/indexed_events.rs index 23424f4..9449e92 100644 --- a/crates/oracle/src/indexed_events.rs +++ b/crates/oracle/src/indexed_events.rs @@ -328,6 +328,14 @@ mod tests { ); assert!(events.membership.is_empty(), "fee withdrawals and unknown events are ignored"); assert!(!events.is_empty()); + // One kind of event is enough. + for single in [ + IndexedEvents { initialized: events.initialized.clone(), ..Default::default() }, + IndexedEvents { completed: events.completed.clone(), ..Default::default() }, + IndexedEvents { closed: events.closed.clone(), ..Default::default() }, + ] { + assert!(!single.is_empty()); + } let mut merged = IndexedEvents::default(); assert!(merged.is_empty()); From faf1a2e05de7e0aec28d34b9e46e4988aea9d2c0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:08:39 -0300 Subject: [PATCH 04/13] test(oracle): catch cancelled games, listener removal, close and the last safe slot --- crates/oracle/src/cli/audit_random.rs | 5 ++++- crates/oracle/src/db.rs | 11 +++++++++++ crates/oracle/src/program_client.rs | 15 +++++++++++---- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/oracle/src/cli/audit_random.rs b/crates/oracle/src/cli/audit_random.rs index 34947f9..ccca3a6 100644 --- a/crates/oracle/src/cli/audit_random.rs +++ b/crates/oracle/src/cli/audit_random.rs @@ -670,7 +670,10 @@ mod tests { let options = CliOptions { once: false, with_block_time: true, refresh_from_db_each_tick: true, ..options(Some(&game)) }; let started = tokio::time::Instant::now(); - let output = audit_output(&h, options, "").await.unwrap(); + let output = tokio::time::timeout(Duration::from_secs(30), audit_output(&h, options, "")) + .await + .expect("the audit stops once the game is gone") + .unwrap(); // The first poll's result never sets the delay; the second doubles it and clamps to 2s. assert_eq!(started.elapsed(), Duration::from_millis(100 + 2_000)); let screens: Vec<&str> = output.split("\x1Bc").filter(|s| !s.is_empty()).collect(); diff --git a/crates/oracle/src/db.rs b/crates/oracle/src/db.rs index 8b2cf65..239eca8 100644 --- a/crates/oracle/src/db.rs +++ b/crates/oracle/src/db.rs @@ -1619,6 +1619,17 @@ mod tests { assert_eq!(db.get_completion_attempt_state("g").unwrap().completion_attempts, 0); } + #[test] + fn a_cancelled_game_is_finalized() { + let db = db(); + db.track_game("g", None, false).unwrap(); + db.mark_game_closed("g").unwrap(); + assert_eq!(db.set_auto_complete_disabled("g", true).unwrap(), Err(ToggleFailure::Finalized)); + assert_eq!(db.reset_completion_attempts("g", false).unwrap(), Err(ResetFailure::Finalized)); + assert_eq!(db.reset_completion_attempts("g", true).unwrap(), Ok(())); + assert_eq!(db.get_game_status("g").as_deref(), Some("pending")); + } + #[test] fn resets_finalized_games_only_when_allowed() { let db = db(); diff --git a/crates/oracle/src/program_client.rs b/crates/oracle/src/program_client.rs index 51e3d73..744ccb9 100644 --- a/crates/oracle/src/program_client.rs +++ b/crates/oracle/src/program_client.rs @@ -388,7 +388,8 @@ mod tests { .encode([39u8, 144, 49, 106, 108, 210, 183, 38, 1]) ); ws.send(notification(12, Value::Null, broken)).await.unwrap(); - ws.send(notification(13, Value::Null, joined_logs(5))).await.unwrap(); + // The last slot a JavaScript number holds exactly is still delivered. + ws.send(notification((1 << 53) - 1, Value::Null, joined_logs(5))).await.unwrap(); return; } else { ws.send(notification(20 + connection, Value::Null, joined_logs(4))).await.unwrap(); @@ -429,7 +430,7 @@ mod tests { // Failed, out-of-range and malformed notifications are skipped without // dropping the subscription. let ProgramDispatch::PlayerMembership(second) = next(&mut rx).await else { panic!("membership expected") }; - assert_eq!((second.slot, second.ticket_index), (13, 5)); + assert_eq!((second.slot, second.ticket_index), ((1 << 53) - 1, 5)); assert_eq!(connections.load(Ordering::SeqCst), 1); // The server then hangs up; the subscription is restored after the reconnect delay. let ProgramDispatch::PlayerMembership(third) = next(&mut rx).await else { panic!("membership expected") }; @@ -438,6 +439,10 @@ mod tests { client.remove_event_listener(ignored).await; assert_eq!(client.listener_count(), 1); + assert!( + client.state.lock().await.task.as_ref().is_some_and(|task| !task.is_finished()), + "the subscription stays while someone listens" + ); client.remove_event_listener(id).await; assert_eq!(client.listener_count(), 0); assert!(client.state.lock().await.task.is_none()); @@ -502,6 +507,8 @@ mod tests { assert_eq!(client.listener_count(), 1, "only the failed registration is undone"); assert!(client.state.lock().await.reconnect.as_ref().is_some_and(|timer| !timer.is_finished())); client.close().await; + assert_eq!(client.listener_count(), 0, "closing drops every listener"); + assert!(client.state.lock().await.reconnect.is_none(), "closing cancels the reconnect"); } #[tokio::test] @@ -581,8 +588,8 @@ mod tests { client.schedule_reconnect(&mut state); state.reconnect.take().unwrap() }; - // The client is stopped while the attempt is in flight. - client.state.lock().await.generation += 1; + // The subscription is stopped while the attempt is in flight, and someone still listens. + client.stop_subscription().await; timer.await.unwrap(); assert!(client.state.lock().await.reconnect.is_none()); } From fe268573c11d3ca12ac6b00e540b6373ef629881 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:11:18 -0300 Subject: [PATCH 05/13] test(oracle): catch audit events for other games, used secrets, and worker shutdown logs --- crates/oracle/src/cli/audit_random.rs | 44 ++++++++++++++++++-- crates/oracle/src/server.rs | 59 ++++++++++++++++++++++++++- 2 files changed, 98 insertions(+), 5 deletions(-) diff --git a/crates/oracle/src/cli/audit_random.rs b/crates/oracle/src/cli/audit_random.rs index ccca3a6..9a42147 100644 --- a/crates/oracle/src/cli/audit_random.rs +++ b/crates/oracle/src/cli/audit_random.rs @@ -790,17 +790,29 @@ mod tests { } program.dispatch(membership(MembershipKind::Joined, &game, "alice", 0)).await; assert!(db.get_game_players(&game).is_empty(), "read-only without --write-db"); + let closed = |game_key: &str, slot| { + ProgramDispatch::GameClosed(GameClosedEvent { + game_key: game_key.into(), + timestamp: 2, + operator: false, + signature: "c".into(), + slot, + }) + }; + program.dispatch(closed(&game, 130)).await; + // Events for another game change nothing. let completed = GameCompletedEvent { - game_key: game.clone(), - winner: "alice".into(), + game_key: "other-game".into(), + winner: "bob".into(), tickets_count: 1, winner_amount: 1, fee_amount: 0, timestamp: 3, signature: "d".into(), - slot: 140, + slot: 150, }; program.dispatch(ProgramDispatch::GameCompleted(completed)).await; + program.dispatch(closed("other-game", 160)).await; } }; let options = CliOptions { once: false, listen: true, ..options(Some(&game)) }; @@ -813,6 +825,7 @@ mod tests { let output = output.unwrap(); let last = output.rsplit("\x1Bc").next().unwrap(); assert!(last.contains("Last joiner: alice (ticketIndex=0"), "{last}"); + assert!(last.contains("Status: closed | CompletedAt: ") && last.contains(" | CompletedSlot: 130\n"), "{last}"); } #[test] @@ -824,6 +837,7 @@ mod tests { let options = parse_args(&args(&["--no-listen", "--write-db", "--with-block-time", "--db-refresh"])).unwrap(); assert!(!options.listen && options.write_db && options.with_block_time && options.refresh_from_db_each_tick); assert!(!parse_args(&args(&["--db-refresh", "--no-db-refresh"])).unwrap().refresh_from_db_each_tick); + assert_eq!(parse_args(&args(&["--interval", "100"])).unwrap().interval_ms, 100, "the minimum is allowed"); assert_eq!( parse_args(&args(&["--interval", "5"])).unwrap_err().to_string(), "--interval must be a number >= 100 (ms)" @@ -835,6 +849,30 @@ mod tests { assert_eq!(parse_args(&args(&["", "GAME", ""])).unwrap().game_address.as_deref(), Some("GAME")); } + #[test] + fn only_positive_unix_seconds_are_shown_as_dates() { + assert_eq!(format_unix_seconds(Some(1)), "1970-01-01T00:00:01.000Z"); + for unknown in [None, Some(0), Some(-1)] { + assert_eq!(format_unix_seconds(unknown), "n/a", "{unknown:?}"); + } + } + + #[tokio::test] + async fn a_game_with_a_used_secret_is_shown_as_completed() { + let h = harness(); + let game = h.service.generate_game_secrets(None).unwrap().game_address; + h.service.db().finalize_completed_game(&game).unwrap(); + let value = account_value(&game_account(0, 10, 2, 1_700_000_000, 600)); + h.transport.on(move |_, method, _| match method { + "getSlot" => Some(Ok(json!(100))), + "getAccountInfo" => Some(Ok(value.clone())), + _ => None, + }); + let output = audit_output(&h, options(Some(&game)), "").await.unwrap(); + assert!(output.contains(&format!("\x1BcGame: {game}\nStatus: completed\n")), "{output}"); + assert!(output.contains("Completed. Exiting..."), "{output}"); + } + #[test] fn winner_display_covers_missing_players() { let players = vec!["alice".to_string(), "bob".to_string()]; diff --git a/crates/oracle/src/server.rs b/crates/oracle/src/server.rs index c119f8e..8f2049c 100644 --- a/crates/oracle/src/server.rs +++ b/crates/oracle/src/server.rs @@ -388,12 +388,16 @@ mod tests { }), worker("scan loop", |_| async { Err(anyhow::anyhow!("database is locked").context("cycle")) }.boxed()), ]; - let exit = run_background(ok_init(), workers, Shutdown::new()).await; + // A crash that is never reported must fail here, not wait forever for the sibling. + async fn within(exit: impl std::future::Future) -> BackgroundExit { + tokio::time::timeout(Duration::from_secs(10), exit).await.expect("the crash is reported") + } + let exit = within(run_background(ok_init(), workers, Shutdown::new())).await; assert!(matches!(&exit, BackgroundExit::Crashed(m) if m == "scan loop: cycle: database is locked"), "{exit:?}"); assert_eq!(sibling_stopped.load(Ordering::SeqCst), 1); let panicking = vec![worker("indexer", |_| async { panic!("index out of bounds") }.boxed())]; - let exit = run_background(ok_init(), panicking, Shutdown::new()).await; + let exit = within(run_background(ok_init(), panicking, Shutdown::new())).await; assert!( matches!(&exit, BackgroundExit::Crashed(m) if m.starts_with("indexer: task") && m.contains("panicked")), "{exit:?}" @@ -447,6 +451,57 @@ mod tests { scan_worker(failing, signal).await.unwrap(); } + #[tokio::test(start_paused = true)] + async fn a_scan_that_ends_with_the_shutdown_is_not_logged_as_a_restart() { + // Runs again in a child process to read what the worker logs. + if std::env::var_os("TIMBA_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "server::tests::a_scan_that_ends_with_the_shutdown_is_not_logged_as_a_restart", + "--nocapture", + ]) + .env("TIMBA_CHILD", "1") + .env("LOG_LEVEL", "info") + .env_remove("LOG_SILENT") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{output:?}"); + assert_eq!( + stderr.matches("Background scan loop exited unexpectedly; restarting...").count(), + 1, + "{stderr}" + ); + assert_eq!(stderr.matches("Background scan loop failed: database is locked").count(), 1, "{stderr}"); + assert!(!stderr.contains("aborted by shutdown"), "{stderr}"); + return; + } + // Each worker ends early once without a shutdown, then ends with the shutdown. + for fail in [false, true] { + let signal = Shutdown::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let (stop, count) = (signal.clone(), calls.clone()); + let scan = move |_| { + let first = count.fetch_add(1, Ordering::SeqCst) == 0; + let stop = stop.clone(); + async move { + if !first { + stop.trigger(); + } + match (fail, first) { + (true, true) => anyhow::bail!("database is locked"), + (true, false) => anyhow::bail!("aborted by shutdown"), + (false, _) => Ok(ScanLoopSummary::default()), + } + } + .boxed() + }; + scan_worker(scan, signal).await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + } + fn jobs(path: &std::path::Path) -> Vec<(String, i64)> { let conn = rusqlite::Connection::open(path).unwrap(); let mut stmt = conn.prepare("SELECT signature,attempts FROM verification_jobs ORDER BY signature").unwrap(); From 0501d48b6c2931ba0617dba0d89b85e1427a3922 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:23:54 -0300 Subject: [PATCH 06/13] test(oracle): catch completion options, scan resolution, observers, registry stats and audit backoff --- crates/oracle/src/cli/audit_random.rs | 55 ++++++++++++++++++++++++--- crates/oracle/src/core/completion.rs | 48 +++++++++++++++++++++++ crates/oracle/src/core/events.rs | 20 +++++++++- crates/oracle/src/core/registry.rs | 16 ++++++++ 4 files changed, 133 insertions(+), 6 deletions(-) diff --git a/crates/oracle/src/cli/audit_random.rs b/crates/oracle/src/cli/audit_random.rs index 9a42147..c8eb6f9 100644 --- a/crates/oracle/src/cli/audit_random.rs +++ b/crates/oracle/src/cli/audit_random.rs @@ -548,7 +548,10 @@ mod tests { async fn audit_output(h: &Harness, options: CliOptions, typed: &str) -> anyhow::Result { let mut input = std::io::Cursor::new(typed.as_bytes().to_vec()); let mut out = Vec::new(); - audit(&h.service, options, &mut input, &mut out).await?; + // An audit that never ends must fail here, not hang the test. + tokio::time::timeout(Duration::from_secs(30), audit(&h.service, options, &mut input, &mut out)) + .await + .expect("the audit ends")?; Ok(String::from_utf8(out).unwrap()) } @@ -670,10 +673,7 @@ mod tests { let options = CliOptions { once: false, with_block_time: true, refresh_from_db_each_tick: true, ..options(Some(&game)) }; let started = tokio::time::Instant::now(); - let output = tokio::time::timeout(Duration::from_secs(30), audit_output(&h, options, "")) - .await - .expect("the audit stops once the game is gone") - .unwrap(); + let output = audit_output(&h, options, "").await.unwrap(); // The first poll's result never sets the delay; the second doubles it and clamps to 2s. assert_eq!(started.elapsed(), Duration::from_millis(100 + 2_000)); let screens: Vec<&str> = output.split("\x1Bc").filter(|s| !s.is_empty()).collect(); @@ -683,6 +683,29 @@ mod tests { assert!(screens[0].contains("n/a (slot unavailable)"), "{}", screens[0]); assert!(screens[2].contains("- RPC slot/time: ") && screens[2].contains("Status: completed (account missing)")); assert!(screens[2].contains("Tickets: 0 | Players(DB): 1"), "{}", screens[2]); + assert!(!screens[2].contains("Fetch game account"), "a missing account is no error: {}", screens[2]); + } + + #[tokio::test(start_paused = true)] + async fn the_backoff_doubles_while_rate_limited() { + let h = harness(); + let game = h.service.generate_game_secrets(None).unwrap().game_address; + // Polls at 0, 100 and 2 100 ms are rate limited; the next one finds the game gone. + let start = tokio::time::Instant::now(); + h.transport.on(move |_, method, _| { + let limited = start.elapsed() < Duration::from_millis(3_000); + match (method, limited) { + ("getSlot", true) => Some(Err(RpcError::http(429, "Too Many Requests", None))), + ("getSlot", false) => Some(Ok(json!(101))), + ("getAccountInfo", true) => Some(Err(RpcError::transport("RPC request failed: connection reset"))), + ("getAccountInfo", false) => Some(Ok(json!({ "value": null }))), + _ => None, + } + }); + let options = CliOptions { once: false, ..options(Some(&game)) }; + let output = audit_output(&h, options, "").await.unwrap(); + assert!(output.contains("Status: completed (account missing)"), "{output}"); + assert_eq!(start.elapsed(), Duration::from_millis(100 + 2_000 + 4_000)); } fn membership(kind: MembershipKind, game: &str, player: &str, ticket_index: u32) -> ProgramDispatch { @@ -849,6 +872,28 @@ mod tests { assert_eq!(parse_args(&args(&["", "GAME", ""])).unwrap().game_address.as_deref(), Some("GAME")); } + #[test] + fn render_lists_each_lookahead_winner_and_counts_the_wins() { + let state = AuditState::default(); + let players = vec!["alice".to_string(), "bob".to_string()]; + let screen = render(&RenderInput { + game_address: "g", + state: &state, + current_slot: Some(100), + block_time: None, + game: None, + players: &players, + winner_now: None, + errors: &[], + lookahead_slots: 3, + winner_for: &|slot, n| (slot % n) as u32, + }); + assert!(screen.contains(" 101 -> index= 2 pos= 3 winner=\n"), "{screen}"); + assert!(screen.contains(" 102 -> index= 0 pos= 1 winner=alice\n"), "{screen}"); + assert!(screen.contains(" 103 -> index= 1 pos= 2 winner=bob\n"), "{screen}"); + assert_eq!(screen.matches("( 1/3)").count(), 3, "{screen}"); + } + #[test] fn only_positive_unix_seconds_are_shown_as_dates() { assert_eq!(format_unix_seconds(Some(1)), "1970-01-01T00:00:01.000Z"); diff --git a/crates/oracle/src/core/completion.rs b/crates/oracle/src/core/completion.rs index 5e32c52..3a9cd81 100644 --- a/crates/oracle/src/core/completion.rs +++ b/crates/oracle/src/core/completion.rs @@ -1471,6 +1471,54 @@ mod tests { ); } + #[tokio::test] + async fn attempts_complete_with_the_context_and_readiness_they_are_given() { + let h = harness(None); + let random_hash = [0x34; 32]; + let pda = find_game_pda(&random_hash, &PROGRAM_ID); + let address = pda.to_base58(); + // Only tracked: the secret comes with the attempt, not from the database. + h.db.track_game(&address, None, false).unwrap(); + h.db.replace_game_players(&address, &players(1)).unwrap(); + // The chain no longer shows the game, so only the given snapshot makes it ready. + serve_game(&h, None); + serve_submission(&h); + let options = AttemptOptions { + context: Some(context(pda, random_hash, None)), + readiness: Some(Readiness { + ready: true, + game_account: Some(game_account(1, 1, 1, 0, 60)), + evaluated_at: Some(1), + }), + ..AttemptOptions::new(&address) + }; + let result = h.manager.attempt_game_completion(options).await.unwrap().unwrap(); + assert!(result.success, "{result:?}"); + assert_eq!(h.transport.calls_for("sendTransaction").len(), 1); + h.manager.reset_registry_prefetch_schedule(&address); + } + + #[tokio::test] + async fn scan_resolution_reads_the_chain_and_shares_the_block_time() { + use crate::core::scan::ScanCompletion; + let h = harness(None); + let (address, _, _) = store_game(&h, [0x35; 32]); + // A cached ready snapshot is ignored: the scan always reads the chain. + let cached = Readiness { ready: true, game_account: Some(game_account(1, 1, 1, 0, 60)), evaluated_at: Some(1) }; + h.cache.lock().unwrap().insert(address.clone(), cached); + let game = game_account(0, 5, 2, 1_000, 60); + serve_game(&h, Some(game.clone())); + let cache = BlockTimeCache::default(); + let resolution = ScanCompletion::resolve(&h.manager, &address, &cache).await.unwrap(); + let ReadinessResolution::Resolved { ready, readiness, .. } = resolution else { + panic!("the stored game resolves: {resolution:?}") + }; + assert!(!ready, "zero tickets are never ready"); + assert_eq!(readiness.game_account, Some(game)); + let block_time = h.manager.get_blockchain_time().await; + assert_eq!(cache.get(), Some(block_time), "the scan cycle shares the block time"); + } + #[tokio::test] async fn prevents_concurrent_completions_for_the_same_game() { let h = harness(None); diff --git a/crates/oracle/src/core/events.rs b/crates/oracle/src/core/events.rs index 282ba2c..afb61e4 100644 --- a/crates/oracle/src/core/events.rs +++ b/crates/oracle/src/core/events.rs @@ -1056,6 +1056,18 @@ mod tests { assert!(!h.processor.has_pending_registry_sync(&game())); } + #[tokio::test] + async fn names_registry_syncs_after_refunds() { + let h = harness(0); + h.db.save_secret_key(&game(), "secret", "hash").unwrap(); + h.db.track_game(&game(), None, true).unwrap(); + // The refund leaves no known player while the event counts one ticket. + h.processor.handle_player_event(unjoin(&game(), 0, None)).await; + settle().await; + let syncs = h.hooks.syncs.lock().unwrap().clone(); + assert_eq!(syncs.first().map(|sync| sync.trigger.as_str()), Some("player unjoined"), "{syncs:?}"); + } + #[tokio::test] async fn game_initialized_tracks_type() { let h = harness(0); @@ -1237,7 +1249,12 @@ mod tests { h.processor.add_program_event_observer(Arc::new(move || { counter.fetch_add(1, Ordering::SeqCst); })); - let broken = h.processor.add_program_event_observer(Arc::new(|| panic!("observer bug"))); + let broken_calls = Arc::new(AtomicUsize::new(0)); + let broken_counter = broken_calls.clone(); + let broken = h.processor.add_program_event_observer(Arc::new(move || { + broken_counter.fetch_add(1, Ordering::SeqCst); + panic!("observer bug") + })); h.processor.start_listening().await.unwrap(); h.processor.start_listening().await.unwrap(); @@ -1260,6 +1277,7 @@ mod tests { assert!(h.db.get_game_players(&game).is_empty(), "closing clears the stale players"); assert_eq!(h.hooks.finalized.lock().unwrap().clone(), vec![game.clone()]); assert_eq!(seen.load(Ordering::SeqCst), 5); + assert_eq!(broken_calls.load(Ordering::SeqCst), 4, "a removed observer is not called"); h.processor.stop_listening().await; h.processor.stop_listening().await; diff --git a/crates/oracle/src/core/registry.rs b/crates/oracle/src/core/registry.rs index 6caad8a..c6539d2 100644 --- a/crates/oracle/src/core/registry.rs +++ b/crates/oracle/src/core/registry.rs @@ -501,6 +501,22 @@ mod tests { assert!(mismatch.needs_reconciliation); } + #[test] + fn dense_stats_have_indexes_only_when_not_empty() { + assert_eq!(RegistryStats::dense(0), RegistryStats { count: 0, max_index: None, min_index: None }); + assert_eq!(RegistryStats::dense(3), RegistryStats { count: 3, max_index: Some(2), min_index: Some(0) }); + } + + #[test] + fn the_cached_analysis_is_reused_only_for_the_same_counts() { + let dir = tempfile::tempdir().unwrap(); + let db = Arc::new(OracleDatabase::open(dir.path().join("o.sqlite").to_str().unwrap()).unwrap()); + let manager = RegistrySyncManager::new(db, None, false, None); + assert!(!manager.cached_or_analyze("g", 3, 3).needs_reconciliation); + assert!(manager.cached_or_analyze("g", 2, 3).needs_reconciliation, "a new player count is analyzed again"); + assert!(manager.cached_or_analyze("g", 2, 2).expected_matches, "a new expected count is analyzed again"); + } + #[test] fn replays_swap_remove_unjoins() { let events = vec![ From 53e96f8f1a0ef19f821dfa951f359a0762c2301b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:28:14 -0300 Subject: [PATCH 07/13] test(oracle): bound the scan loop tests and check the loop totals and default continue rule --- crates/oracle/src/core/scan.rs | 37 +++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/oracle/src/core/scan.rs b/crates/oracle/src/core/scan.rs index 0f66055..86c794f 100644 --- a/crates/oracle/src/core/scan.rs +++ b/crates/oracle/src/core/scan.rs @@ -482,7 +482,8 @@ mod tests { if cycle == 3 { trigger.trigger(); } - true + // A loop that ignores the abort ends here instead of hanging the test. + cycle < 100 })), signal: Some(signal), ..Default::default() @@ -498,7 +499,8 @@ mod tests { let (_dir, _db, _completion, _metrics, runner) = setup(vec![], CompletionResult::default()); let options = || ScanLoopOptions { wait_between_cycles_ms: Some(60_000), - should_continue: Some(Arc::new(|_, _| true)), + // A loop that never waits ends here instead of hanging the test. + should_continue: Some(Arc::new(|_, cycle| cycle < 100)), ..Default::default() }; // Cancel the loop while it waits between cycles. @@ -770,9 +772,10 @@ mod tests { let summary = runner .run_scan_loop(ScanLoopOptions { cleanup_after_cycle_hours: Some(1), - should_continue: Some(Arc::new(move |_, _| { + should_continue: Some(Arc::new(move |_, cycle| { *flag.lock().unwrap() = true; - true + // A loop that ignores the abort ends here instead of hanging the test. + cycle < 100 })), signal: Some(signal), ..Default::default() @@ -792,7 +795,8 @@ mod tests { looping .run_scan_loop(ScanLoopOptions { wait_between_cycles_ms: Some(60_000), - should_continue: Some(Arc::new(|_, _| true)), + // A loop that never waits ends here instead of hanging the test. + should_continue: Some(Arc::new(|_, cycle| cycle < 100)), ..Default::default() }) .await @@ -805,6 +809,29 @@ mod tests { assert_eq!(summary.cycles, 1); } + #[tokio::test(start_paused = true)] + async fn without_a_continue_hook_the_loop_runs_until_a_cycle_finds_nothing() { + let success = CompletionResult { success: true, ..Default::default() }; + for (resolution, result, expected) in [ + (Ok(resolved(true)), success, (1, 0, 0)), + (Err(anyhow::anyhow!("RPC request failed: boom")), CompletionResult::default(), (0, 1, 0)), + (Ok(resolved(false)), CompletionResult::not_ready(), (0, 0, 1)), + ] { + let (_dir, db, completion, _metrics, runner) = setup(vec![resolution], result); + track(&db, "g1", true); + // The game leaves the pending list after its first scan, so the second cycle finds nothing. + let finished = db.clone(); + *completion.on_resolve.lock().unwrap() = + Some(Box::new(move || finished.mark_game_completed("g1").unwrap())); + let summary = runner + .run_scan_loop(ScanLoopOptions { wait_between_cycles_ms: Some(1_000), ..Default::default() }) + .await + .unwrap(); + assert_eq!(summary.cycles, 2, "{expected:?}"); + assert_eq!((summary.total_completed, summary.total_errors, summary.total_not_ready), expected); + } + } + #[tokio::test] async fn waiting_for_pending_work_only_skips_the_cycle_delay() { let success = CompletionResult { success: true, ..Default::default() }; From 630818577e986d75ed58d408aadef7a449ab8226 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:12:43 -0300 Subject: [PATCH 08/13] test(oracle): catch the service retry, signer, indexer and RPC pool mutants --- crates/oracle/src/core/service.rs | 241 +++++++++++++++++++++++--- crates/oracle/src/core/signer.rs | 21 ++- crates/oracle/src/core/types.rs | 12 ++ crates/oracle/src/http/docs.rs | 5 +- crates/oracle/src/indexer/api.rs | 9 +- crates/oracle/src/indexer/database.rs | 7 + crates/oracle/src/indexer/pricing.rs | 3 + crates/oracle/src/indexer/schema.rs | 4 + crates/oracle/src/indexer/tests.rs | 25 +++ crates/oracle/src/solana/pool.rs | 43 ++++- crates/oracle/src/solana/rpc.rs | 3 + 11 files changed, 335 insertions(+), 38 deletions(-) diff --git a/crates/oracle/src/core/service.rs b/crates/oracle/src/core/service.rs index 9451df7..c32fb94 100644 --- a/crates/oracle/src/core/service.rs +++ b/crates/oracle/src/core/service.rs @@ -141,6 +141,11 @@ fn cancel_timer(timer: Option<(u64, JoinHandle<()>)>) { super::cancel_timer(timer.map(|(_, handle)| handle)); } +/// A cooldown that ends at `next_eligible_at` still holds at `now`. +fn cooling_down(next_eligible_at: i64, now: i64) -> bool { + now < next_eligible_at +} + fn is_fallback_scan_trigger(trigger: &str) -> bool { trigger == "fallback scan" || trigger.starts_with("fallback scan retry") } @@ -888,7 +893,7 @@ impl OracleService { let mut retries = self.retries.lock().unwrap(); if let Some(existing) = retries.get_mut(game_address) { if existing.phase == RetryPhase::Cooldown { - if let Some(next) = existing.next_eligible_at.filter(|next| now < *next) { + if let Some(next) = existing.next_eligible_at.filter(|next| cooling_down(*next, now)) { return Admission::Cooldown(Some(next)); } let timer = existing.timer.take(); @@ -924,7 +929,7 @@ impl OracleService { let state = self.db.get_completion_attempt_state(game_address); if let Some(next) = state.as_ref().and_then(|s| s.completion_retry_after) { - if now < next { + if cooling_down(next, now) { let attempts = state.as_ref().map(|s| s.completion_attempts).unwrap_or(0).max(0) as usize; self.install_completion_cooldown(game_address, game_key, trigger, attempts, next); return Admission::Cooldown(Some(next)); @@ -975,19 +980,10 @@ impl OracleService { self.cancel_completion_retry(&game_address); return None; } - let attempt_options = if retry_attempt == 0 { - AttemptOptions { game_key, ..options } - } else { - AttemptOptions { - game_key, - on_result: options.on_result, - success_log: options.success_log, - failure_log: options.failure_log, - ..AttemptOptions::new(&game_address) - } - }; + // `game_key` is `options.game_key`, and a retry's options come from `fire_retry` with only the + // key and the logs set, so the options go through unchanged. let fallback = is_fallback_scan_trigger(&trigger); - match self.attempt_game_completion(attempt_options).await { + match self.attempt_game_completion(options).await { Ok(None) => { if !fallback { let next = self.next_readiness_attempt(&game_address, mode, retry_attempt); @@ -1229,7 +1225,7 @@ impl OracleService { let persisted = self.db.get_completion_attempt_state(game_address).and_then(|s| s.completion_retry_after); let next_eligible_at = existing_cooldown.unwrap_or(0).max(persisted.unwrap_or(0)).max(now + COMPLETION_RECOVERY_COOLDOWN_MS); - if existing_cooldown.is_some_and(|at| at > now) { + if existing_cooldown.is_some_and(|at| cooling_down(at, now)) { return; } if let Some(existing) = self.retries.lock().unwrap().get_mut(game_address) { @@ -1319,7 +1315,8 @@ impl OracleService { // The hook only lives as long as this attempt, which borrows the service. let service = self.clone(); let on_result: super::types::ResultHook = Arc::new(move |result: &CompletionResult| { - if !result.success || result.winner_address.is_none() { + // Every successful result names its winner; `notify_bot_of_completion` reports one that does not. + if !result.success { return; } let (service, result, address) = (service.clone(), result.clone(), game_address.clone()); @@ -1474,6 +1471,11 @@ mod tests { }; use crate::solana::rpc::RpcError; + /// Closes the service; a close that waits forever fails the test instead. + async fn close(h: &Harness) { + tokio::time::timeout(Duration::from_secs(10), h.service.close()).await.expect("close ends"); + } + fn tracked_game(h: &Harness) -> String { h.service.generate_game_secrets(None).unwrap().game_address } @@ -1501,6 +1503,34 @@ mod tests { } let err = h.service.sign_game_transaction("not base64!").await.unwrap_err(); assert!(matches!(err, GameTransactionError::Validation(_))); + // The limit is 4000 characters: a transaction at the limit reaches the policy checks. + let err = h.service.sign_game_transaction(&transaction_of_bytes(3_000)).await.unwrap_err(); + assert_eq!(err.to_string(), "Transaction must contain initialization and an optional creator join"); + let err = h.service.sign_game_transaction(&transaction_of_bytes(3_003)).await.unwrap_err(); + assert_eq!(err.to_string(), "Invalid transaction payload"); + } + + /// A decodable legacy transaction of exactly `total` bytes, as base64, with no game instruction. + fn transaction_of_bytes(total: usize) -> String { + use timba_protocol::transaction::{CompiledInstruction, LegacyMessage, MessageHeader, Transaction}; + let message = |data_len: usize| LegacyMessage { + header: MessageHeader { + num_required_signatures: 1, + num_readonly_signed_accounts: 0, + num_readonly_unsigned_accounts: 1, + }, + account_keys: (0..89u8).map(|i| Address([i; 32])).collect(), + recent_blockhash: Address([0; 32]), + instructions: vec![CompiledInstruction { + program_id_index: 88, + account_indices: vec![], + data: vec![0; data_len], + }], + }; + let base = Transaction::from_message(&message(0)).encode().len(); + let transaction = Transaction::from_message(&message(total - base)); + assert_eq!(transaction.encode().len(), total); + transaction.to_base64() } #[tokio::test] @@ -1514,6 +1544,10 @@ mod tests { assert_eq!(h.service.db.get_completion_attempt_state(&game).unwrap().completion_attempts, 0); h.service.db.track_game("orphan", None, false).unwrap(); assert_eq!(h.service.requeue_game("orphan"), Err(RequeueFailure::MissingSecret)); + // A desynced game is still pending on chain, so it can be queued again. + let desynced = tracked_game(&h); + h.service.db.mark_game_desynced(&desynced).unwrap(); + assert_eq!(h.service.requeue_game(&desynced), Ok(())); } #[tokio::test] @@ -1528,6 +1562,8 @@ mod tests { let mint_a = Address::parse(MINT_A).unwrap(); let err = h.service.check_creation_policy(&mint_a, 1).await.unwrap_err(); assert_eq!(err.code, RejectionCode::AmountBelowMinimum); + assert_eq!(err.minimum_amount_raw.as_deref(), Some(policies[0].minimum_amount_raw.as_str())); + assert_eq!(err.revision, Some(1)); assert_eq!(err.accepted_minimum_amount_raw.as_deref(), Some(policies[0].accepted_minimum_amount_raw.as_str())); let accepted: u64 = policies[0].accepted_minimum_amount_raw.parse().unwrap(); h.service.check_creation_policy(&mint_a, accepted).await.unwrap(); @@ -1535,6 +1571,7 @@ mod tests { let mint_b = Address::parse(MINT_B).unwrap(); let err = h.service.check_creation_policy(&mint_b, 1_000_000).await.unwrap_err(); assert_eq!(err.code, RejectionCode::PolicyUnavailable); + assert_eq!(err.revision, Some(1), "a policy without a price keeps its revision"); let unknown = Address([9; 32]); let err = h.service.check_creation_policy(&unknown, 1).await.unwrap_err(); assert_eq!(err.code, RejectionCode::UnsupportedMint); @@ -1619,13 +1656,25 @@ mod tests { ); // Permanent failures stop the fallback scan as well. assert!(h.service.automatic_completion_stop_reason(&game, "fallback scan").is_some()); + // Without a permanent failure only the fallback scan may try again. + let transient = tracked_game(&h); + for _ in 0..MAX_COMPLETION_ATTEMPTS { + h.service.db.increment_completion_attempts(&transient).unwrap(); + } + // Rows from before the failure kind column have no kind. + exec_sql( + h._dir.path(), + &format!("UPDATE game_tracking SET completion_failure_kind = NULL WHERE game_address = '{transient}'"), + ); + assert_eq!(h.service.automatic_completion_stop_reason(&transient, "fallback scan"), None); + assert!(h.service.automatic_completion_stop_reason(&transient, "player joined").is_some()); h.service.set_auto_complete_disabled(&game, true).unwrap().unwrap(); assert_eq!(h.service.automatic_completion_stop_reason(&game, "x").as_deref(), Some("auto-complete disabled")); - h.service.close().await; + close(&h).await; assert_eq!(h.service.automatic_completion_stop_reason(&game, "x").as_deref(), Some("service shutting down")); assert_eq!(h.service.complete_game_now(&game).await, None); // Closing again is harmless. - h.service.close().await; + close(&h).await; } #[test] @@ -1694,6 +1743,8 @@ mod tests { // -- ported oracle-service.ts cases ----------------------------------------- use crate::core::scan::ScanLoopOptions; + use crate::indexed_events::GameClosedEvent; + use crate::program_client::ProgramDispatch; use base64::Engine; use futures::{SinkExt, StreamExt}; use serde_json::{json, Value}; @@ -1970,7 +2021,7 @@ mod tests { let (game, _) = ready_game(&h); assert!(h.service.complete_game_now(&game).await.unwrap().success); - h.service.close().await; + close(&h).await; assert_eq!(bodies.try_recv().unwrap()["gameAddress"], game.as_str()); } @@ -1989,7 +2040,8 @@ mod tests { }; // A non-200 response is logged, not raised. h.service.notify_bot_of_completion("g", &result).await.unwrap(); - assert_eq!(bodies.recv().await.unwrap()["gameAddress"], "g"); + let body = tokio::time::timeout(Duration::from_secs(5), bodies.recv()).await.expect("bot notified").unwrap(); + assert_eq!(body["gameAddress"], "g"); let incomplete = CompletionResult { tx_hash: None, ..result.clone() }; assert_eq!( @@ -2025,7 +2077,7 @@ mod tests { let (other, _) = ready_game(&h); assert_eq!(h.service.queue_game_completion(&other), None); eventually(|| h.service.db.get_game_status(&other).as_deref() == Some("completed")).await; - h.service.close().await; + close(&h).await; } #[tokio::test(start_paused = true)] @@ -2098,7 +2150,7 @@ mod tests { tokio::time::sleep(Duration::from_secs(10)).await; assert_eq!(h.service.db.get_game_status(&game).as_deref(), Some("completed")); assert_eq!(h.service.expiry.scheduled(&game), None); - h.service.close().await; + close(&h).await; } #[tokio::test] @@ -2114,7 +2166,7 @@ mod tests { h.service.complete_game_now(&game).await.unwrap(); assert!(h.service.expiry.scheduled(&game).is_some()); - h.service.close().await; + close(&h).await; assert_eq!(h.service.expiry.scheduled(&game), None); } @@ -2468,7 +2520,7 @@ mod tests { // Exhausted readiness retries drop the entry. h.service.schedule_readiness_retry(&game, None, "t", READINESS_RETRY_DELAYS_MS.len() + 1); assert!(h.service.retries.lock().unwrap().is_empty()); - h.service.close().await; + close(&h).await; h.service.retries.lock().unwrap().insert(game.clone(), active_entry(RetryMode::Transient, 1, None)); h.service.schedule_completion_retry(&game, None, "t", 2); assert!(h.service.retries.lock().unwrap().is_empty(), "closing services cancel retries"); @@ -2626,7 +2678,7 @@ mod tests { assert!(h.service.retries.lock().unwrap().is_empty()); // Closing services ignore event-driven attempts. - h.service.close().await; + close(&h).await; h.service.clone().try_auto_complete(None, game.clone(), "player joined".into()).await; assert!(h.service.retries.lock().unwrap().is_empty()); } @@ -2780,7 +2832,7 @@ mod tests { h.service.stop_event_listening().await; assert!(!h.service.get_stats().event_listening); h.service.stop_event_listening().await; - h.service.close().await; + close(&h).await; assert!(!h.service.db().is_open()); } @@ -2943,6 +2995,141 @@ mod tests { h.service.retries.lock().unwrap().insert("g".into(), active_entry(RetryMode::Transient, 2, None)); assert_eq!(h.service.next_transient_attempt("g", RetryMode::Transient, 9), 3); assert_eq!(h.service.next_readiness_attempt("g", RetryMode::Transient, 9), 1); + // A cooldown entry, or an active entry that has not counted yet, does not decide. + for (game, mode) in [("t", RetryMode::Transient), ("r", RetryMode::Readiness)] { + let cooldown = CompletionRetry { phase: RetryPhase::Cooldown, ..active_entry(mode, 3, None) }; + h.service.retries.lock().unwrap().insert(game.into(), cooldown); + } + h.service.retries.lock().unwrap().insert("z".into(), active_entry(RetryMode::Transient, 0, None)); + assert_eq!(h.service.next_transient_attempt("t", RetryMode::Transient, 5), 6); + assert_eq!(h.service.next_readiness_attempt("r", RetryMode::Readiness, 5), 6); + assert_eq!(h.service.next_transient_attempt("z", RetryMode::Transient, 5), 6); + assert_eq!(h.service.next_readiness_attempt("z", RetryMode::Readiness, 5), 6); + } + + #[test] + fn cooldowns_hold_until_their_deadline() { + assert!(cooling_down(11, 10)); + assert!(!cooling_down(10, 10)); + assert!(!cooling_down(9, 10)); + } + + /// A parked timer task that closes `rx` when it is aborted. + fn parked_timer() -> (JoinHandle<()>, tokio::sync::oneshot::Receiver<()>) { + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + let task = tokio::spawn(async move { + let _tx = tx; + futures::future::pending::<()>().await + }); + (task, rx) + } + + async fn aborted(rx: tokio::sync::oneshot::Receiver<()>) -> bool { + tokio::time::timeout(Duration::from_secs(5), rx).await.is_ok_and(|r| r.is_err()) + } + + #[tokio::test] + async fn cancelled_and_cleared_retries_abort_their_timers() { + let h = harness(); + let (task, rx) = parked_timer(); + h.service.retries.lock().unwrap().insert("a".into(), active_entry(RetryMode::Transient, 1, Some((1, task)))); + h.service.cancel_completion_retry("a"); + assert!(aborted(rx).await, "cancelling aborts the timer"); + + let (first, first_rx) = parked_timer(); + let (second, second_rx) = parked_timer(); + h.service.retries.lock().unwrap().insert("b".into(), active_entry(RetryMode::Transient, 1, Some((2, first)))); + h.service.retries.lock().unwrap().insert("c".into(), active_entry(RetryMode::Readiness, 1, Some((3, second)))); + h.service.clear_completion_retries(); + assert!(h.service.retries.lock().unwrap().is_empty()); + assert!(aborted(first_rx).await && aborted(second_rx).await, "clearing aborts every timer"); + } + + #[tokio::test] + async fn installing_a_cooldown_replaces_what_is_there() { + let h = harness(); + let now = timba_common::time::now_ms(); + // A later deadline replaces an earlier one. + h.service.install_completion_cooldown("g", None, "t", 4, now + 60_000); + h.service.install_completion_cooldown("g", None, "t", 4, now + 120_000); + assert_eq!(retry_entry(&h, "g", |e| e.next_eligible_at), Some(now + 120_000)); + + // An active retry with a pending timer gives way to the cooldown. + let (task, rx) = parked_timer(); + h.service.retries.lock().unwrap().insert("a".into(), active_entry(RetryMode::Transient, 2, Some((5, task)))); + h.service.install_completion_cooldown("a", None, "t", 4, now + 60_000); + assert_eq!(retry_entry(&h, "a", |e| e.phase), RetryPhase::Cooldown); + assert!(aborted(rx).await); + + // A cooldown timer whose token was replaced leaves the cooldown entry alone. + h.service.install_completion_cooldown("k", None, "t", 4, timba_common::time::now_ms() + 20); + let (other, _other_rx) = parked_timer(); + let replaced = h.service.retries.lock().unwrap().get_mut("k").unwrap().timer.replace((999, other)); + // Dropping the old handle detaches the old timer; it keeps running. + drop(replaced); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!( + retry_entry(&h, "k", |e| (e.phase, e.timer.as_ref().map(|(t, _)| *t))), + (RetryPhase::Cooldown, Some(999)) + ); + h.service.clear_completion_retries(); + } + + #[tokio::test] + async fn the_readiness_cache_is_the_services_own() { + let h = harness(); + let readiness = Readiness { ready: true, game_account: None, evaluated_at: Some(1) }; + h.service.readiness_cache().lock().unwrap().insert("g".into(), readiness.clone()); + assert_eq!(h.service.readiness_cache.lock().unwrap().get("g"), Some(&readiness)); + } + + #[tokio::test] + async fn removed_program_event_observers_are_not_called() { + let (url, _) = ws_server().await; + let mut config = OracleConfig::for_tests(); + config.solana_ws_endpoint = Some(url); + let h = harness_with(config, Keypair::generate(), &["https://a"]); + let game = tracked_game(&h); + let (kept, removed) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let counter = kept.clone(); + let first = h.service.add_program_event_observer(Arc::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + })); + let counter = removed.clone(); + let second = h.service.add_program_event_observer(Arc::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + })); + assert_ne!(first, second); + h.service.remove_program_event_observer(second); + h.service.start_event_listening().await.unwrap(); + let closed = + GameClosedEvent { game_key: game.clone(), timestamp: 1, operator: false, signature: "c".into(), slot: 2 }; + h.service.program.dispatch(ProgramDispatch::GameClosed(closed)).await; + eventually(|| kept.load(Ordering::SeqCst) == 1).await; + assert_eq!(removed.load(Ordering::SeqCst), 0); + close(&h).await; + } + + #[test] + fn database_errors_are_logged() { + // Runs again in a child process to read the log. + if std::env::var_os("TIMBA_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "core::service::tests::database_errors_are_logged", "--nocapture"]) + .env("TIMBA_CHILD", "1") + .env("LOG_LEVEL", "info") + .env_remove("LOG_SILENT") + .output() + .unwrap(); + let logs = + format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(output.status.success(), "{output:?}"); + assert!(logs.contains("Failed to save: disk full"), "{logs}"); + assert!(!logs.contains("Saved fine"), "{logs}"); + return; + } + log_db_error(Err::<(), _>(anyhow::anyhow!("disk full")), "Failed to save"); + log_db_error(Ok(()), "Saved fine"); } #[tokio::test] @@ -2954,7 +3141,7 @@ mod tests { let result = h.service.complete_game_now(&game).await.unwrap(); assert!(result.success, "{result:?}"); // `close()` waits for the failed notification instead of hanging on it. - h.service.close().await; + close(&h).await; assert_eq!(*h.service.active_runs.borrow(), 0); } diff --git a/crates/oracle/src/core/signer.rs b/crates/oracle/src/core/signer.rs index 733a83d..3cf04cb 100644 --- a/crates/oracle/src/core/signer.rs +++ b/crates/oracle/src/core/signer.rs @@ -153,7 +153,8 @@ pub async fn sign_game_transaction_with_policy( if initialize.accounts.len() != create_game_account_count(version) || initialize.data.is_empty() { return Err(policy("Invalid initialize-game account list")); } - if initialize.data.len() < 8 || initialize.data[..8] != discriminators::create_game(version) { + // `CreateGameArgs::decode` takes either version's discriminator, so check this version's here. + if !initialize.data.starts_with(&discriminators::create_game(version)) { return Err(policy("Invalid game instruction data")); } let initialize_data = @@ -312,7 +313,7 @@ fn validate_creator_join(join: &Instruction, v: &JoinExpectations) -> Result<(), if join.accounts.len() != join_game_account_count(v.version) || join.data.is_empty() { return Err(policy("Invalid creator join instruction")); } - if join.data.len() < 8 || join.data[..8] != discriminators::JOIN_GAME { + if !join.data.starts_with(&discriminators::JOIN_GAME) { return Err(policy("Invalid creator join instruction")); } let legacy = v.version == ContractVersion::V0_2_0; @@ -531,9 +532,16 @@ mod tests { let mut foreign = init.clone(); foreign.data[..8].copy_from_slice(&discriminators::JOIN_GAME); add("foreign discriminator", s.tx(&[foreign], true), Some("Invalid game instruction data"), false); + let mut other_version = init.clone(); + let other = if legacy { ContractVersion::V0_3_0 } else { ContractVersion::V0_2_0 }; + other_version.data[..8].copy_from_slice(&discriminators::create_game(other)); + add("other version discriminator", s.tx(&[other_version], true), Some("Invalid game instruction data"), false); let mut short_data = init.clone(); short_data.data.truncate(20); add("short data", s.tx(&[short_data], true), Some("Invalid game instruction data"), false); + let mut no_discriminator = init.clone(); + no_discriminator.data.truncate(5); + add("no discriminator", s.tx(&[no_discriminator], true), Some("Invalid game instruction data"), false); let mut writable_operator = init.clone(); writable_operator.accounts[3].writable = true; add("writable operator", s.tx(&[writable_operator], true), Some("Invalid oracle operator account"), false); @@ -543,7 +551,6 @@ mod tests { Some("Invalid game vault account"), false, ); - let other = if legacy { ContractVersion::V0_3_0 } else { ContractVersion::V0_2_0 }; let other = Scenario::new(other, Options::default()); add( "version mismatch", @@ -555,6 +562,14 @@ mod tests { let mut short_join = join.clone(); short_join.accounts.pop(); add("bad join count", s.tx(&[init.clone(), short_join], true), Some("Invalid creator join instruction"), true); + let mut short_join_data = join.clone(); + short_join_data.data.truncate(5); + add( + "join without a discriminator", + s.tx(&[init.clone(), short_join_data], true), + Some("Invalid creator join instruction"), + true, + ); let mut foreign_join = join.clone(); foreign_join.data = init.data[..8].to_vec(); add( diff --git a/crates/oracle/src/core/types.rs b/crates/oracle/src/core/types.rs index ab920bd..1b21942 100644 --- a/crates/oracle/src/core/types.rs +++ b/crates/oracle/src/core/types.rs @@ -123,4 +123,16 @@ mod tests { "1 completed, 2 errors, 3 not ready" ); } + + #[test] + fn stats_are_empty_only_without_counts() { + assert!(CompletionStats::default().is_empty()); + for stats in [ + CompletionStats { completed: 1, ..Default::default() }, + CompletionStats { errors: 1, ..Default::default() }, + CompletionStats { not_ready: 1, ..Default::default() }, + ] { + assert!(!stats.is_empty(), "{stats:?}"); + } + } } diff --git a/crates/oracle/src/http/docs.rs b/crates/oracle/src/http/docs.rs index 089b91f..a8781bd 100644 --- a/crates/oracle/src/http/docs.rs +++ b/crates/oracle/src/http/docs.rs @@ -32,9 +32,8 @@ pub fn generate_documentation_html(routes: &[RouteDocumentation]) -> String { .iter() .map(|route| { let method = route.method.as_str(); - let method_class: String = - method.to_lowercase().chars().filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == '-').collect(); - let method_class = if method_class.is_empty() { "custom".to_string() } else { method_class }; + // `HttpMethod` names are plain ASCII words, so the lower-case name is a safe class. + let method_class = method.to_lowercase(); let request_example = route .request_example .map(|example| format!("
Body: {}", escape_html(example))) diff --git a/crates/oracle/src/indexer/api.rs b/crates/oracle/src/indexer/api.rs index 8b0b8ff..0344e44 100644 --- a/crates/oracle/src/indexer/api.rs +++ b/crates/oracle/src/indexer/api.rs @@ -142,10 +142,8 @@ fn serialize_lifecycle(game: &Row) -> Row { ); out.insert("createdAt".into(), created_at.clone()); out.insert("timeout".into(), timeout.clone()); - out.insert( - "expiresAt".into(), - if created_at.is_null() || timeout.is_null() { Value::Null } else { add(&created_at, &timeout) }, - ); + // A missing time makes the sum NaN, which `add` writes as null. + out.insert("expiresAt".into(), add(&created_at, &timeout)); out.insert("winner".into(), field(game, "winner")); out.insert("winnerAmount".into(), field(game, "winner_amount")); out.insert("feeAmount".into(), field(game, "fee_amount")); @@ -473,6 +471,9 @@ mod tests { assert_eq!(add(&json!(1_000), &json!(3_600)), json!(4_600)); // Past the 64-bit range the sum is a float, like in JavaScript. assert_eq!(add(&json!(i64::MAX), &json!(1)), json!(9_223_372_036_854_775_808u64 as f64)); + assert_eq!(add(&json!(i64::MAX), &json!(i64::MAX)), json!(i64::MAX as f64 * 2.0)); + // Inside the 64-bit range integer sums stay exact, also past 2^53. + assert_eq!(add(&json!(1_i64 << 53), &json!(1)), json!((1_i64 << 53) + 1)); // Any non-integer operand makes it a float addition. assert_eq!(add(&json!(1.5), &json!(2)), json!(3.5)); assert_eq!(add(&json!(2), &json!(0.25)), json!(2.25)); diff --git a/crates/oracle/src/indexer/database.rs b/crates/oracle/src/indexer/database.rs index 7652eb3..b170cc3 100644 --- a/crates/oracle/src/indexer/database.rs +++ b/crates/oracle/src/indexer/database.rs @@ -1190,6 +1190,13 @@ mod tests { IndexerDatabase::open(":memory:").unwrap() } + #[test] + fn falls_back_for_missing_and_null_values() { + assert_eq!(or(None, Value::from(0)), Value::from(0)); + assert_eq!(or(Some(Value::Null), Value::from(0)), Value::from(0)); + assert_eq!(or(Some(Value::from(5)), Value::from(0)), Value::from(5)); + } + #[test] fn a_zero_leaderboard_ttl_caches_nothing() { let options = IndexerDatabaseOptions { leaderboard_cache_ttl_ms: Some(0), ..Default::default() }; diff --git a/crates/oracle/src/indexer/pricing.rs b/crates/oracle/src/indexer/pricing.rs index c07aad3..a41bb1b 100644 --- a/crates/oracle/src/indexer/pricing.rs +++ b/crates/oracle/src/indexer/pricing.rs @@ -285,6 +285,9 @@ mod tests { async fn the_shared_instance_serves_only_cached_prices_without_a_key() { assert!(Arc::ptr_eq(&TokenUsdPrices::global(), &TokenUsdPrices::global())); assert!(get_token_usd_prices(&[mint(99)], None).await.is_empty()); + let cached = CachedPrice { price: Some(2.5), expires_at: i64::MAX }; + TokenUsdPrices::global().cache.lock().unwrap().insert(mint(98), cached); + assert_eq!(get_token_usd_prices(&[mint(98)], None).await.get(&mint(98)), Some(&2.5)); assert!(TokenUsdPrices::default().get(&[mint(99)], Some("")).await.is_empty()); } diff --git a/crates/oracle/src/indexer/schema.rs b/crates/oracle/src/indexer/schema.rs index 05869c8..e410492 100644 --- a/crates/oracle/src/indexer/schema.rs +++ b/crates/oracle/src/indexer/schema.rs @@ -68,6 +68,10 @@ mod tests { assert_eq!(js_number(&json!(true)), json!(1)); assert_eq!(js_number(&json!(false)), json!(0)); assert_eq!(js_number(&json!(u64::MAX)), json!(u64::MAX)); + // A whole real becomes an integer, as SQLite REAL values are read. + assert!(js_number(&json!(2.0)).is_i64()); + // Integers print exactly, also past 2^53. + assert_eq!(js_string(&json!(9_007_199_254_740_993_i64)), json!("9007199254740993")); assert_eq!(js_number(&json!("abc")), json!("NaN")); assert_eq!(js_number(&json!("Infinity")), json!("NaN")); assert_eq!(js_number(&json!([1])), json!("NaN")); diff --git a/crates/oracle/src/indexer/tests.rs b/crates/oracle/src/indexer/tests.rs index 7e358ac..4b8c6a0 100644 --- a/crates/oracle/src/indexer/tests.rs +++ b/crates/oracle/src/indexer/tests.rs @@ -530,6 +530,30 @@ fn completed_events_queue_verification_jobs() { assert_eq!(f.db.next_verification_job().unwrap(), job(&f.completed_signature, 0)); } +#[test] +fn stored_completions_and_empty_batches_change_nothing() { + let f = fixture(IndexerDatabaseOptions { cache_rebuild_interval_ms: Some(0), ..Default::default() }); + assert_eq!(f.db.apply(&f.events, &cursor(&f.completed_signature, 12)).unwrap(), 2); + let completed = IndexedEvents { completed: f.events.completed.clone(), ..Default::default() }; + assert_eq!(f.db.apply(&completed, &cursor(&f.completed_signature, 13)).unwrap(), 0, "already stored"); + let generation = f.db.cache_generation(); + assert_eq!(f.db.apply(&IndexedEvents::default(), &cursor(&f.completed_signature, 14)).unwrap(), 0); + assert_eq!(f.db.cache_generation(), generation, "an empty batch does not rebuild the caches"); +} + +#[test] +fn stores_index_times_in_seconds() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("indexer.sqlite"); + let now: ManualClock = Arc::new(AtomicI64::new(5_500_999)); + let options = IndexerDatabaseOptions { wall_clock: Some(clock_of(&now)), ..Default::default() }; + let f = fixture_at(path.to_str().unwrap(), options); + f.db.apply(&f.events, &cursor(&f.completed_signature, 12)).unwrap(); + let conn = rusqlite::Connection::open(&path).unwrap(); + let indexed_at: i64 = conn.query_row("SELECT indexed_at FROM games", [], |row| row.get(0)).unwrap(); + assert_eq!(indexed_at, 5_500); +} + #[test] fn caches_verified_game_payloads_by_key() { let db = IndexerDatabase::open(":memory:").unwrap(); @@ -576,6 +600,7 @@ fn reports_backfill_state() { #[test] fn closed_databases_fail_cleanly() { let db = IndexerDatabase::open(":memory:").unwrap(); + assert!(db.is_open()); db.close(); assert!(!db.is_open()); assert!(db.get_tokens().is_err()); diff --git a/crates/oracle/src/solana/pool.rs b/crates/oracle/src/solana/pool.rs index 1b7dc97..b18004d 100644 --- a/crates/oracle/src/solana/pool.rs +++ b/crates/oracle/src/solana/pool.rs @@ -136,7 +136,8 @@ impl RpcPool { } pub fn active_endpoint(&self) -> &str { - &self.endpoints[self.active.load(Ordering::SeqCst).min(self.endpoints.len() - 1)] + // Only `promote` writes the index, and only with the index of one of the endpoints. + &self.endpoints[self.active.load(Ordering::SeqCst)] } pub fn endpoints(&self) -> &[String] { @@ -479,6 +480,7 @@ mod tests { vec!["https://x", "8899", r#"{"a":1}"#] ); assert!(parse_rpc_endpoint_list(None).unwrap_err().contains("required")); + assert!(parse_rpc_endpoint_list(Some(" ")).unwrap_err().contains("required")); assert!(parse_rpc_endpoint_list(Some("[nope]")).unwrap_err().contains("JSON array")); // Only a value wrapped in brackets on both ends is JSON; a lone bracket is a list entry. assert_eq!(parse_rpc_endpoint_list(Some("https://x/]")).unwrap(), vec!["https://x/]"]); @@ -632,6 +634,45 @@ mod tests { assert!((1_000..1_500).contains(&waited[1]), "{waited:?}"); } + #[test] + fn retry_delays_add_jitter() { + // Up to one base delay of jitter: 100 draws all under 1 ms are practically impossible. + assert!((0..100).any(|_| compute_retry_delay_ms(0, None) > RPC_RETRY_BASE_DELAY_MS)); + } + + #[test] + fn failures_without_fallback_are_logged_except_missing_blocks() { + // Runs again in a child process to read the log. + if std::env::var_os("TIMBA_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "solana::pool::tests::failures_without_fallback_are_logged_except_missing_blocks", + "--nocapture", + ]) + .env("TIMBA_CHILD", "1") + .env("LOG_LEVEL", "info") + .env_remove("LOG_SILENT") + .output() + .unwrap(); + let logs = + format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(output.status.success(), "{output:?}"); + assert!(logs.contains("RPC call getSlot failed on endpoint 1 (a) without fallback"), "{logs}"); + assert!(!logs.contains("getBlockTime"), "{logs}"); + return; + } + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + runtime.block_on(async { + let transport = FakeTransport::new(); + transport.push("getSlot", Err(RpcError::json_rpc(-32602, "Invalid params"))); + transport.push("getBlockTime", Err(RpcError::json_rpc(BLOCK_NOT_AVAILABLE, "Block not available"))); + let pool = RpcPool::with_transport(&["https://a".into()], transport).unwrap(); + assert!(pool.get_slot().await.is_err()); + assert!(pool.get_block_time(9).await.is_err()); + }); + } + #[test] fn retry_delay_never_exceeds_the_cap() { for attempt in 0..20 { diff --git a/crates/oracle/src/solana/rpc.rs b/crates/oracle/src/solana/rpc.rs index 968a547..d0d6f79 100644 --- a/crates/oracle/src/solana/rpc.rs +++ b/crates/oracle/src/solana/rpc.rs @@ -365,6 +365,9 @@ mod tests { #[test] fn retryable_classification() { assert!(RpcError::http(429, "Too Many Requests", None).is_rate_limit()); + // Some providers report a rate limit only in the message. + assert!(RpcError::json_rpc(-32005, "upstream answered 429").is_rate_limit()); + assert!(!RpcError::json_rpc(-32005, "request 4290 failed").is_rate_limit()); assert!(RpcError::http(503, "Service Unavailable", None).is_retryable()); assert!(!RpcError::http(400, "Bad Request", None).is_retryable()); assert!(RpcError::transport("error sending request").is_retryable()); From 18b02114cfce664467012a350c379eceb258372a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:17:27 -0300 Subject: [PATCH 09/13] test(oracle): catch the token, RPC status and ERC-8010 mutants --- crates/evm-oracle/src/rpc.rs | 3 ++- crates/oracle/src/solana/rpc.rs | 32 ++++++++++++++++++++++----- crates/oracle/src/token/onboarding.rs | 5 +++++ crates/oracle/src/token/policy.rs | 3 +++ 4 files changed, 37 insertions(+), 6 deletions(-) diff --git a/crates/evm-oracle/src/rpc.rs b/crates/evm-oracle/src/rpc.rs index 9c4683b..abd52e7 100644 --- a/crates/evm-oracle/src/rpc.rs +++ b/crates/evm-oracle/src/rpc.rs @@ -747,7 +747,8 @@ mod tests { assert_eq!((wrapped.signature, wrapped.init), (inner.clone(), Some(init))); assert_eq!(wrapped.authorization.authority(), Some(account().address())); let plain = unwrap(&hex(&fixture["plain"])).unwrap(); - assert_eq!((plain.signature, plain.init), (inner, None)); + assert_eq!((plain.signature, plain.init), (inner.clone(), None)); + assert!(unwrap(&inner).is_none(), "a signature without the magic suffix is not wrapped"); } #[tokio::test] diff --git a/crates/oracle/src/solana/rpc.rs b/crates/oracle/src/solana/rpc.rs index d0d6f79..1278cda 100644 --- a/crates/oracle/src/solana/rpc.rs +++ b/crates/oracle/src/solana/rpc.rs @@ -145,6 +145,15 @@ pub fn submission_url(endpoint: &str, rebate: Option<&str>) -> String { url.to_string() } +/// The URL for one request: only `sendTransaction` carries the rebate address. +fn request_url(endpoint: &str, method: &str, rebate: Option<&str>) -> String { + if method == "sendTransaction" { + submission_url(endpoint, rebate) + } else { + endpoint.to_string() + } +} + pub struct HttpTransport { client: reqwest::Client, rebate_address: Option, @@ -169,11 +178,7 @@ impl HttpTransport { impl RpcTransport for HttpTransport { fn send<'a>(&'a self, endpoint: &'a str, method: &'a str, params: Value) -> BoxFuture<'a, Result> { Box::pin(async move { - let url = if method == "sendTransaction" { - submission_url(endpoint, self.rebate_address.as_deref()) - } else { - endpoint.to_string() - }; + let url = request_url(endpoint, method, self.rebate_address.as_deref()); let id = self.next_id.fetch_add(1, Ordering::Relaxed); let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }); let response = self.client.post(&url).json(&body).send().await.map_err(transport_error)?; @@ -375,6 +380,23 @@ mod tests { assert!(RpcError::json_rpc(-32603, "upstream timed out").is_retryable()); } + #[test] + fn rebates_apply_only_to_submissions() { + let helius = "https://mainnet.helius-rpc.com/?api-key=x"; + assert_eq!(request_url(helius, "sendTransaction", Some("R")), submission_url(helius, Some("R"))); + assert_eq!(request_url(helius, "getSlot", Some("R")), helius); + } + + #[test] + fn only_confirmed_and_finalized_statuses_count() { + let status = + |level: Option<&str>| SignatureStatus { slot: 1, err: None, confirmation_status: level.map(String::from) }; + assert!(status(Some("confirmed")).is_confirmed()); + assert!(status(Some("finalized")).is_confirmed()); + assert!(!status(Some("processed")).is_confirmed()); + assert!(!status(None).is_confirmed()); + } + #[test] fn rebate_only_for_helius() { assert_eq!( diff --git a/crates/oracle/src/token/onboarding.rs b/crates/oracle/src/token/onboarding.rs index 46b7f75..cd00c6f 100644 --- a/crates/oracle/src/token/onboarding.rs +++ b/crates/oracle/src/token/onboarding.rs @@ -103,6 +103,11 @@ mod tests { assert_eq!(decode_mint_decimals(&mint, &mint_account(6, 1)).unwrap(), 6); assert!(decode_mint_decimals(&mint, &mint_account(6, 0)).is_err()); assert!(decode_mint_decimals(&mint, &mint_account(16, 1)).is_err()); + let foreign = AccountInfo { owner: Address::new([8; 32]), ..mint_account(6, 1) }; + assert!(decode_mint_decimals(&mint, &foreign).is_err(), "another program owns it"); + let mut extended = mint_account(6, 1); + extended.data.resize(165, 0); + assert!(decode_mint_decimals(&mint, &extended).is_err(), "not the legacy mint size"); let owner = Address::new([9; 32]); let mut data = vec![0u8; LEGACY_TOKEN_ACCOUNT_SIZE]; diff --git a/crates/oracle/src/token/policy.rs b/crates/oracle/src/token/policy.rs index 97beabf..5746a90 100644 --- a/crates/oracle/src/token/policy.rs +++ b/crates/oracle/src/token/policy.rs @@ -225,6 +225,9 @@ mod tests { let err = compute_minimum_amount_raw(1e200, 6).unwrap_err(); assert_eq!(err, "token USD price exponent is invalid"); assert_eq!(compute_minimum_amount_raw(1e-200, 6).unwrap_err(), "token USD price exponent is invalid"); + // Exponents up to 100 are allowed. + assert_eq!(compute_minimum_amount_raw(1e100, 0).unwrap(), 1); + assert_eq!(compute_minimum_amount_raw(1e101, 0).unwrap_err(), "token USD price exponent is invalid"); assert_eq!(compute_minimum_amount_raw(1e-30, 15).unwrap_err(), "dynamic minimum amount exceeds u64"); assert_eq!(accepted_minimum_amount_raw(0).unwrap_err(), "recommended minimum must be positive"); } From b17d269767e524edf541878bf52799fa87775bbf Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:10:52 -0300 Subject: [PATCH 10/13] test(oracle): catch the scan duration, requeue, close and scan loop mutants Scan cycles use the tokio clock, so a paused test checks their duration. delay() no longer needs a guard for 0 ms. Tests now requeue a completed game, check that an empty scan logs nothing, and bound every close() and CLI run, so a mutant that hangs fails fast. --- crates/oracle/src/core/completion.rs | 17 ++++ crates/oracle/src/core/scan.rs | 116 +++++++++++++++++++++++---- crates/oracle/src/core/service.rs | 5 ++ crates/oracle/src/http/tests.rs | 2 +- crates/oracle/tests/binary.rs | 9 ++- 5 files changed, 129 insertions(+), 20 deletions(-) diff --git a/crates/oracle/src/core/completion.rs b/crates/oracle/src/core/completion.rs index 3a9cd81..5b451a4 100644 --- a/crates/oracle/src/core/completion.rs +++ b/crates/oracle/src/core/completion.rs @@ -1146,6 +1146,23 @@ mod tests { assert!(h.cache.lock().unwrap().is_empty(), "fatal failures clear cached readiness"); } + #[tokio::test] + async fn provided_readiness_with_its_account_needs_no_chain_read() { + let h = harness(None); + let (address, pda, random_hash) = store_game(&h, [0x29; 32]); + h.db.replace_game_players(&address, &players(1)).unwrap(); + // The chain no longer shows the game, and the context carries no snapshot, + // so only the readiness given to `complete_game` makes it ready. + serve_game(&h, None); + serve_submission(&h); + let readiness = + Readiness { ready: true, game_account: Some(game_account(1, 1, 1, 0, 60)), evaluated_at: Some(1) }; + let result = h.manager.complete_game(&address, Some(readiness), Some(context(pda, random_hash, None))).await; + assert!(result.success, "{result:?}"); + assert_eq!(h.transport.calls_for("sendTransaction").len(), 1); + h.manager.reset_registry_prefetch_schedule(&address); + } + #[tokio::test] async fn registry_desync_marks_the_game() { let h = harness(None); diff --git a/crates/oracle/src/core/scan.rs b/crates/oracle/src/core/scan.rs index 86c794f..4be2af2 100644 --- a/crates/oracle/src/core/scan.rs +++ b/crates/oracle/src/core/scan.rs @@ -2,7 +2,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use std::time::Instant; +use tokio::time::Instant; use futures::future::{BoxFuture, FutureExt}; use timba_common::shutdown::Shutdown; @@ -86,8 +86,8 @@ fn aborted(signal: Option<&Shutdown>) -> bool { async fn delay(ms: u64, signal: Option<&Shutdown>) { match signal { Some(signal) => signal.sleep(ms).await, - None if ms > 0 => tokio::time::sleep(std::time::Duration::from_millis(ms)).await, - None => {} + // A sleep of 0 ms ends at once. + None => tokio::time::sleep(std::time::Duration::from_millis(ms)).await, } } @@ -339,6 +339,15 @@ mod tests { type Hook = Box; + impl ScanLoopRunner { + /// The loop under a virtual time limit, so a loop that never ends fails the test. + async fn bounded_scan_loop(&self, options: ScanLoopOptions) -> anyhow::Result { + tokio::time::timeout(Duration::from_secs(7_200), self.run_scan_loop(options)) + .await + .expect("the scan loop ends") + } + } + #[derive(Default)] struct FakeCompletion { resolutions: Mutex>>, @@ -464,10 +473,10 @@ mod tests { assert_eq!(stats.errors, 1); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn loop_stops_when_idle_and_rejects_reentry() { let (_dir, _db, _completion, _metrics, runner) = setup(vec![], CompletionResult::default()); - let summary = runner.run_scan_loop(ScanLoopOptions::default()).await.unwrap(); + let summary = runner.bounded_scan_loop(ScanLoopOptions::default()).await.unwrap(); assert_eq!(summary.cycles, 1); assert_eq!(summary.last_stats, Some(CompletionStats::default())); @@ -488,7 +497,7 @@ mod tests { signal: Some(signal), ..Default::default() }; - let summary = runner.run_scan_loop(options).await.unwrap(); + let summary = runner.bounded_scan_loop(options).await.unwrap(); assert_eq!(summary.cycles, 3); assert_eq!(*calls.lock().unwrap(), 3); assert!(!runner.is_running()); @@ -732,16 +741,16 @@ mod tests { assert_eq!(metrics.completion_records().len(), 1); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_second_loop_is_rejected_while_one_runs() { let (_dir, _db, _completion, _metrics, runner) = setup(vec![], CompletionResult::default()); runner.running.store(true, Ordering::SeqCst); - let err = runner.run_scan_loop(ScanLoopOptions::default()).await.unwrap_err(); + let err = runner.bounded_scan_loop(ScanLoopOptions::default()).await.unwrap_err(); assert_eq!(err.to_string(), "Scan loop is already running"); assert!(runner.is_running(), "the running loop is left alone"); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn cleanup_failures_do_not_stop_the_loop() { let (_dir, _db, _completion, _metrics, mut runner) = setup(vec![], CompletionResult::default()); let hours = Arc::new(Mutex::new(Vec::new())); @@ -751,14 +760,14 @@ mod tests { anyhow::bail!("cleanup failed") }); let summary = runner - .run_scan_loop(ScanLoopOptions { cleanup_after_cycle_hours: Some(12), ..Default::default() }) + .bounded_scan_loop(ScanLoopOptions { cleanup_after_cycle_hours: Some(12), ..Default::default() }) .await .unwrap(); assert_eq!(summary.cycles, 1); assert_eq!(hours.lock().unwrap().clone(), vec![12]); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn an_abort_during_cleanup_ends_the_loop() { let (_dir, _db, _completion, _metrics, mut runner) = setup(vec![], CompletionResult::default()); let signal = Shutdown::new(); @@ -770,7 +779,7 @@ mod tests { let continued = Arc::new(Mutex::new(false)); let flag = continued.clone(); let summary = runner - .run_scan_loop(ScanLoopOptions { + .bounded_scan_loop(ScanLoopOptions { cleanup_after_cycle_hours: Some(1), should_continue: Some(Arc::new(move |_, cycle| { *flag.lock().unwrap() = true; @@ -824,7 +833,7 @@ mod tests { *completion.on_resolve.lock().unwrap() = Some(Box::new(move || finished.mark_game_completed("g1").unwrap())); let summary = runner - .run_scan_loop(ScanLoopOptions { wait_between_cycles_ms: Some(1_000), ..Default::default() }) + .bounded_scan_loop(ScanLoopOptions { wait_between_cycles_ms: Some(1_000), ..Default::default() }) .await .unwrap(); assert_eq!(summary.cycles, 2, "{expected:?}"); @@ -832,14 +841,89 @@ mod tests { } } - #[tokio::test] + #[test] + fn scan_results_are_logged_only_when_something_happened() { + // Runs again in a child process to read the log. + if std::env::var_os("TIMBA_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "core::scan::tests::scan_results_are_logged_only_when_something_happened", + "--nocapture", + ]) + .env("TIMBA_CHILD", "1") + .env("LOG_LEVEL", "info") + .env_remove("LOG_SILENT") + .output() + .unwrap(); + let logs = + format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(output.status.success(), "{output:?}"); + assert_eq!(logs.matches("Scan:").count(), 1, "{logs}"); + assert!(logs.contains("Scan: 2 completed"), "{logs}"); + // A scan with no pending games logs nothing. + assert!(!logs.contains("Scanning"), "{logs}"); + return; + } + let success = CompletionResult { success: true, ..Default::default() }; + let (_dir, _db, _completion, _metrics, runner) = setup(vec![], success); + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + assert_eq!(runtime.block_on(runner.scan_and_complete_active_games(None)), CompletionStats::default()); + log_scan_results(&CompletionStats::default()); + log_scan_results(&CompletionStats { completed: 2, ..Default::default() }); + } + + #[tokio::test(start_paused = true)] + async fn scan_cycles_record_their_duration_in_milliseconds() { + let success = CompletionResult { success: true, ..Default::default() }; + let (_dir, db, _completion, metrics, mut runner) = + setup(vec![Err(anyhow::anyhow!("RPC request failed: boom"))], success); + runner.options.inter_game_delay_ms = 1_500; + track(&db, "g1", true); + let stats = runner.scan_and_complete_active_games(None).await; + assert_eq!(stats.errors, 1); + // The failed game waits the delay, and the paused clock moves exactly that far. + assert_eq!(metrics.scan_cycles()[0].duration_ms, 1_500.0); + } + + /// Virtual time of a two-cycle loop that waits only for pending work. + async fn pending_only_loop_time(games: &[&str], resolutions: Vec>) -> u64 { + let success = CompletionResult { success: true, ..Default::default() }; + let (_dir, db, _completion, _metrics, runner) = setup(resolutions, success); + for game in games { + track(&db, game, true); + } + let started = tokio::time::Instant::now(); + let summary = runner + .bounded_scan_loop(ScanLoopOptions { + wait_between_cycles_ms: Some(1_000), + wait_for_pending_only: true, + should_continue: Some(Arc::new(|_, cycle| cycle < 2)), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(summary.cycles, 2); + started.elapsed().as_millis() as u64 + } + + #[tokio::test(start_paused = true)] + async fn waiting_for_pending_work_only_still_waits_after_errors_alone() { + let failure = || Err(anyhow::anyhow!("RPC request failed: boom")); + assert_eq!(pending_only_loop_time(&["g1"], vec![failure(), failure()]).await, 1_000, "only errors"); + let mixed = vec![Ok(resolved(true)), failure(), Ok(resolved(true)), failure()]; + assert_eq!(pending_only_loop_time(&["g1", "g2"], mixed).await, 0, "errors next to a completion"); + assert_eq!(pending_only_loop_time(&[], vec![]).await, 0, "nothing found"); + } + + #[tokio::test(start_paused = true)] async fn waiting_for_pending_work_only_skips_the_cycle_delay() { let success = CompletionResult { success: true, ..Default::default() }; // Without a continue hook the loop ends after the cycle that found work. let (_dir, db, completion, _metrics, runner) = setup(vec![Ok(resolved(true))], success.clone()); track(&db, "g1", true); let summary = runner - .run_scan_loop(ScanLoopOptions { + .bounded_scan_loop(ScanLoopOptions { wait_between_cycles_ms: Some(3_600_000), wait_for_pending_only: true, ..Default::default() @@ -853,7 +937,7 @@ mod tests { let (_dir, db, _completion, _metrics, runner) = setup((0..2).map(|_| Ok(resolved(true))).collect(), success); track(&db, "g1", true); let summary = runner - .run_scan_loop(ScanLoopOptions { + .bounded_scan_loop(ScanLoopOptions { wait_between_cycles_ms: Some(3_600_000), wait_for_pending_only: true, should_continue: Some(Arc::new(|_, cycle| cycle < 2)), diff --git a/crates/oracle/src/core/service.rs b/crates/oracle/src/core/service.rs index c32fb94..1bb6e6e 100644 --- a/crates/oracle/src/core/service.rs +++ b/crates/oracle/src/core/service.rs @@ -1548,6 +1548,11 @@ mod tests { let desynced = tracked_game(&h); h.service.db.mark_game_desynced(&desynced).unwrap(); assert_eq!(h.service.requeue_game(&desynced), Ok(())); + // A completed game can be queued again, and it goes back to pending. + let completed = tracked_game(&h); + h.service.db.mark_game_completed(&completed).unwrap(); + assert_eq!(h.service.requeue_game(&completed), Ok(())); + assert_eq!(h.service.db.get_game_status(&completed).as_deref(), Some("pending")); } #[tokio::test] diff --git a/crates/oracle/src/http/tests.rs b/crates/oracle/src/http/tests.rs index 415a825..8c79db7 100644 --- a/crates/oracle/src/http/tests.rs +++ b/crates/oracle/src/http/tests.rs @@ -582,6 +582,6 @@ mod service_api { let complete = format!(r#"{{"gameAddress":"{game}"}}"#); let (status, body, _) = call(&app, "POST", "/games/complete-now", Some(&complete), true).await; assert_eq!((status, body["status"].clone()), (StatusCode::OK, json!("in-flight"))); - service.close().await; + tokio::time::timeout(std::time::Duration::from_secs(10), service.close()).await.expect("close ends"); } } diff --git a/crates/oracle/tests/binary.rs b/crates/oracle/tests/binary.rs index 2f59b64..65ca09b 100644 --- a/crates/oracle/tests/binary.rs +++ b/crates/oracle/tests/binary.rs @@ -134,10 +134,13 @@ impl Oracle { command } - /// Runs a one-shot command to completion off the async runtime. + /// Runs a one-shot command to completion, and kills it if it hangs. async fn run(&self, args: &[&str]) -> (i32, String, String) { - let mut command = self.command(args); - let output = tokio::task::spawn_blocking(move || command.output().unwrap()).await.unwrap(); + let mut command = tokio::process::Command::from(self.command(args)); + let output = tokio::time::timeout(Duration::from_secs(60), command.kill_on_drop(true).output()) + .await + .expect("the command ends") + .unwrap(); let text = |bytes: Vec| String::from_utf8(bytes).unwrap(); (output.status.code().unwrap(), text(output.stdout), text(output.stderr)) } From 31eaa442ba11ef3f2e1f5227bfae82856185600d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:02:22 -0300 Subject: [PATCH 11/13] test(oracle): bound the drain and scan stop tests, requeue a cancelled game A drain that never ends and a loop that goes on after a no now fail fast instead of hanging, and a cancelled game is requeued like a completed one. --- crates/oracle/src/cli/mod.rs | 18 +++++++++++++----- crates/oracle/src/core/service.rs | 10 +++++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/oracle/src/cli/mod.rs b/crates/oracle/src/cli/mod.rs index f2e8bf8..a2f43aa 100644 --- a/crates/oracle/src/cli/mod.rs +++ b/crates/oracle/src/cli/mod.rs @@ -451,11 +451,15 @@ mod tests { assert!(text.ends_with("Completed: 3, Not Ready: 0, Errors: 1\n"), "{text}"); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn manual_shutdown_cleans_up_once_nothing_is_pending() { let h = harness(); let mut out = Vec::new(); - drain(&h.service, 0, &mut out).await.unwrap(); + // Each extra cycle waits 1 s, so a drain that never stops reaches the bound. + tokio::time::timeout(std::time::Duration::from_secs(60), drain(&h.service, 1_000, &mut out)) + .await + .expect("the drain ends") + .unwrap(); let text = String::from_utf8(out).unwrap(); assert!(text.starts_with("🛑 Timba Oracle Manual Shutdown\n"), "{text}"); assert!( @@ -488,16 +492,20 @@ mod tests { let h = harness(); let mut failures = 0; // Break the output after every possible number of writes, up to a complete run. - for allowed in 0.. { + // A complete run has far fewer than 100 writes. + for allowed in 0..100 { match drain(&h.service, 0, &mut BrokenPipe { allowed }).await { - Ok(()) => break, + Ok(()) => { + assert!(failures > 10, "every write is checked: {failures}"); + return; + } Err(err) => { assert_eq!(err.downcast_ref::().unwrap().kind(), std::io::ErrorKind::BrokenPipe); failures += 1; } } } - assert!(failures > 10, "every write is checked: {failures}"); + panic!("the drain did not end after {failures} broken outputs"); } async fn health_server(status: StatusCode) -> u16 { diff --git a/crates/oracle/src/core/service.rs b/crates/oracle/src/core/service.rs index 1bb6e6e..dbaa096 100644 --- a/crates/oracle/src/core/service.rs +++ b/crates/oracle/src/core/service.rs @@ -1553,6 +1553,10 @@ mod tests { h.service.db.mark_game_completed(&completed).unwrap(); assert_eq!(h.service.requeue_game(&completed), Ok(())); assert_eq!(h.service.db.get_game_status(&completed).as_deref(), Some("pending")); + let cancelled = tracked_game(&h); + h.service.db.mark_game_closed(&cancelled).unwrap(); + assert_eq!(h.service.requeue_game(&cancelled), Ok(())); + assert_eq!(h.service.db.get_game_status(&cancelled).as_deref(), Some("pending")); } #[tokio::test] @@ -2611,7 +2615,11 @@ mod tests { wait_between_cycles_ms: Some(0), wait_for_pending_only: false, cleanup_after_cycle_hours: Some(24), - should_continue: Some(Arc::new(|_, _| false)), + // The loop stops at the first no, so it never asks again. + should_continue: Some(Arc::new(|_, cycle| { + assert_eq!(cycle, 1, "the loop went on after a no"); + false + })), signal: None, }) .await From 88c40aebe9ca3a9c36e2a1b44b5eab3164ee1bcb Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:18:10 -0300 Subject: [PATCH 12/13] test(oracle): check that a pending-only loop with a continue hook does not wait --- crates/oracle/src/core/scan.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/oracle/src/core/scan.rs b/crates/oracle/src/core/scan.rs index 4be2af2..5fde693 100644 --- a/crates/oracle/src/core/scan.rs +++ b/crates/oracle/src/core/scan.rs @@ -936,6 +936,7 @@ mod tests { // With one, the hook decides and the loop goes straight into the next cycle. let (_dir, db, _completion, _metrics, runner) = setup((0..2).map(|_| Ok(resolved(true))).collect(), success); track(&db, "g1", true); + let started = tokio::time::Instant::now(); let summary = runner .bounded_scan_loop(ScanLoopOptions { wait_between_cycles_ms: Some(3_600_000), @@ -946,5 +947,6 @@ mod tests { .await .unwrap(); assert_eq!(summary.cycles, 2); + assert_eq!(started.elapsed(), std::time::Duration::ZERO, "no wait between the cycles"); } } From 3fcb488114c54cdc2eb520119dae1f0dddda79de Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:50:44 -0300 Subject: [PATCH 13/13] test(oracle): let a token refresh run before checking that a fresh value starts none --- crates/oracle/src/web_api/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/oracle/src/web_api/tests.rs b/crates/oracle/src/web_api/tests.rs index 4773ebc..e951fc1 100644 --- a/crates/oracle/src/web_api/tests.rs +++ b/crates/oracle/src/web_api/tests.rs @@ -300,6 +300,8 @@ async fn token_config_serves_fresh_then_stale_while_revalidating_then_refreshes( let after_first = reads(); assert!(after_first > 0); harness.get("/web/config").await; + // Give a background refresh time to run, so a fresh value that started one fails here. + tokio::time::sleep(std::time::Duration::from_millis(20)).await; assert_eq!(reads(), after_first); harness.advance(6_000);