diff --git a/crates/api/src/web/discord_retry.rs b/crates/api/src/web/discord_retry.rs index 720fcbab6..007ec3f72 100644 --- a/crates/api/src/web/discord_retry.rs +++ b/crates/api/src/web/discord_retry.rs @@ -101,21 +101,44 @@ mod tests { .enable_all() .build() .unwrap(); - runtime.block_on(async { - store_deadlines( - &db, - r#"{"g:7":1710000000000,"t:7":1710000001000,"token":1710000001000,"nope":5,"m:bad":9}"#.into(), - ) - .await - .unwrap(); - }); - let loaded = load_deadlines_sync(&Db::open(&path, 2).unwrap()).unwrap(); - assert_eq!(loaded.get("g:7"), Some(&1_710_000_000_000)); - assert_eq!(loaded.get("t:7"), Some(&1_710_000_001_000)); - assert!(!loaded.contains_key("token")); - assert!(!loaded.contains_key("nope")); - assert!(!loaded.contains_key("m:bad")); + for length in 0..=21 { + let id = "7".repeat(length); + let keys = [ + format!("g:{id}"), + format!("t:{id}"), + format!("m:{id}"), + format!("r:{id}:9"), + format!("r:9:{id}"), + ]; + for millis in [i64::MIN, 0, 1, 1_710_000_000_000, i64::MAX] { + let mut record = serde_json::json!({"global": millis, "token": 5, "m:bad": 9}); + let mut expected = BTreeMap::new(); + if millis > 0 { + expected.insert("global".to_owned(), millis); + } + for key in keys.iter() { + record[key] = millis.into(); + if (1..=20).contains(&length) && millis > 0 { + expected.insert(key.clone(), millis); + } + } + runtime + .block_on(store_deadlines(&db, record.to_string())) + .unwrap(); + assert_eq!( + load_deadlines_sync(&db).unwrap(), + expected, + "id length {length}, deadline {millis}" + ); + } + } drop(db); + let reopened = Db::open(&path, 2).unwrap(); + assert_eq!( + load_deadlines_sync(&reopened).unwrap(), + BTreeMap::from([("global".to_owned(), i64::MAX)]) + ); + drop(reopened); for suffix in ["", "-wal", "-shm"] { let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); } diff --git a/crates/api/src/web/oauth.rs b/crates/api/src/web/oauth.rs index 064582784..2358fadc2 100644 --- a/crates/api/src/web/oauth.rs +++ b/crates/api/src/web/oauth.rs @@ -1404,15 +1404,34 @@ mod tests { #[tokio::test(start_paused = true)] async fn discord_retry_after_honors_header_and_json_seconds() { - assert_eq!(discord_retry_after(Some("2"), b"{}").as_secs(), 2); - assert_eq!( - discord_retry_after(Some("2"), br#"{"retry_after":4.5}"#).as_millis(), - 4500 - ); - assert_eq!(discord_retry_after(None, b"{}").as_secs(), 1); - assert_eq!(discord_retry_after(Some("0"), b"{}").as_secs(), 1); - assert_eq!(discord_retry_after(Some("120"), b"{}").as_secs(), 120); - assert_eq!(discord_retry_after(Some("90000"), b"{}").as_secs(), 90000); + // Eighth-seconds are exactly representable on the wire. Compute the + // expected wait in integer milliseconds independently of the parser. + let waits = [ + None, + Some(0u32), + Some(4), + Some(8), + Some(16), + Some(36), + Some(960), + Some(720_000), + ]; + for header in waits { + for body in waits { + let header_value = header.map(|n| (f64::from(n) / 8.0).to_string()); + let body_value = + serde_json::json!({"retry_after": body.map(|n| f64::from(n) / 8.0)}); + let expected_ms = header.into_iter().chain(body).max().unwrap_or(0).max(8) * 125; + assert_eq!( + discord_retry_after( + header_value.as_deref(), + &serde_json::to_vec(&body_value).unwrap() + ), + Duration::from_millis(u64::from(expected_ms)) + ); + } + } + assert_eq!(discord_retry_after(None, b"{}"), Duration::from_secs(1)); for invalid in ["-1", "NaN", "inf", "-inf"] { assert_eq!( discord_retry_after(Some(invalid), b"{}"), diff --git a/crates/bot/src/commands/userinfo/tests.rs b/crates/bot/src/commands/userinfo/tests.rs index 363046f4b..f9d48b649 100644 --- a/crates/bot/src/commands/userinfo/tests.rs +++ b/crates/bot/src/commands/userinfo/tests.rs @@ -3202,7 +3202,14 @@ impl StatsDispatch { "data": {"id": "3", "name": name, "type": 1, "options": options, "resolved": resolved} })) .unwrap(); - crate::commands::handle_interaction(&self.app, &self.ctx, interaction).await; + // Several fixture helpers await this dispatch. Keep its future on the heap + // so their nested debug frames fit on the normal Rust test thread. + Box::pin(crate::commands::handle_interaction( + &self.app, + &self.ctx, + interaction, + )) + .await; } /// Reply bodies sent to Discord (non-empty content or embeds), in order, diff --git a/crates/bot/src/handlers.rs b/crates/bot/src/handlers.rs index febe3e227..e437b0280 100644 --- a/crates/bot/src/handlers.rs +++ b/crates/bot/src/handlers.rs @@ -5426,12 +5426,18 @@ BEGIN SELECT RAISE(ABORT, 'fixture pacing failure'); END;", #[test] fn deadline_millis_clamps_to_i64() { - assert_eq!(member_sync_deadline_ms(10, Duration::MAX), i64::MAX); - assert_eq!(member_sync_deadline_ms(10, Duration::from_millis(5)), 15); - assert_eq!( - member_sync_deadline_ms(i64::MAX, Duration::from_millis(1)), - i64::MAX - ); + let max = i64::MAX; + for now in [0, 10, max / 2, max - 1, max] { + let room = (max - now) as u64; + for millis in [0, 1, 5, room.saturating_sub(1), room, room + 1, u64::MAX] { + for nanos in [0, 999_999] { + let wait = Duration::from_millis(millis) + Duration::from_nanos(nanos); + let expected = (u128::from(now as u64) + u128::from(millis)).min(max as u128); + assert_eq!(member_sync_deadline_ms(now, wait) as u128, expected); + } + } + assert_eq!(member_sync_deadline_ms(now, Duration::MAX), max); + } } const TOKEN_A: &str = "synthetic_token_r4303412353"; diff --git a/crates/bot/src/main.rs b/crates/bot/src/main.rs index 5be0bfbb5..2d3b27e5a 100644 --- a/crates/bot/src/main.rs +++ b/crates/bot/src/main.rs @@ -850,35 +850,40 @@ mod tests { #[test] fn planned_stop_needs_every_ready_shard_connected() { - use serenity::gateway::ConnectionStage::{Connected, Connecting, Resuming}; - let runners = |stages: &[(u32, serenity::gateway::ConnectionStage)]| { - stages - .iter() - .copied() - .collect::>() - }; - assert!(super::gateway_covered(&runners(&[(0, Connected)]), &[0])); - assert!( - !super::gateway_covered(&runners(&[(0, Connected)]), &[]), - "never reached Ready" - ); - assert!( - !super::gateway_covered(&runners(&[]), &[0]), - "restarting shard has no runner" - ); - assert!(!super::gateway_covered(&runners(&[(0, Resuming)]), &[0])); - assert!(!super::gateway_covered( - &runners(&[(0, Connected), (1, Connecting)]), - &[0, 1] - )); - assert!( - !super::gateway_covered(&runners(&[(1, Connected)]), &[0]), - "another shard's runner cannot stand in for a Ready shard" - ); - assert!(super::gateway_covered( - &runners(&[(0, Connected), (1, Connecting)]), - &[0] - )); + use serenity::gateway::ConnectionStage::*; + let stages = [ + None, + Some(Connected), + Some(Connecting), + Some(Disconnected), + Some(Handshake), + Some(Identifying), + Some(Resuming), + ]; + for ready_mask in 0..8 { + let ready = (0..3) + .filter(|shard| ready_mask & (1 << shard) != 0) + .collect::>(); + for mut layout in 0..stages.len().pow(3) { + let mut runners = std::collections::HashMap::new(); + let mut connected_mask = 0; + for shard in 0..3 { + if let Some(stage) = stages[layout % stages.len()] { + runners.insert(shard, stage); + if stage == Connected { + connected_mask |= 1 << shard; + } + } + layout /= stages.len(); + } + let expected = ready_mask != 0 && ready_mask & !connected_mask == 0; + assert_eq!( + super::gateway_covered(&runners, &ready), + expected, + "ready {ready:?}, runners {runners:?}" + ); + } + } } use super::*; diff --git a/crates/runtime/src/cgroup.rs b/crates/runtime/src/cgroup.rs index bf1400a72..4baa81b74 100644 --- a/crates/runtime/src/cgroup.rs +++ b/crates/runtime/src/cgroup.rs @@ -2734,6 +2734,58 @@ mod tests { } } + #[test] + fn memory_reading_agrees_across_limit_and_stat_boundaries() { + for (v1, usage, limit_file) in [ + (true, "memory.usage_in_bytes", "memory.limit_in_bytes"), + (false, "memory.current", "memory.max"), + ] { + for (stat, expected_usage) in [ + (None, Some((10, MemorySource::CgroupUsage))), + (Some("inactive_file 4"), Some((6, MemorySource::CgroupStat))), + ( + Some("inactive_file 11"), + Some((0, MemorySource::CgroupStat)), + ), + (Some("file 100"), None), + ] { + let tree = temp_tree(); + write_files(&tree.path, &[(usage, "10")]); + if let Some(stat) = stat { + write_files(&tree.path, &[("memory.stat", stat)]); + } + for limit in [ + None, + Some(0), + Some(63), + Some(64), + Some(65), + Some((1u64 << 62) - 1), + Some(1 << 62), + Some(u64::MAX), + ] { + if let Some(limit) = limit { + write_files(&tree.path, &[(limit_file, &limit.to_string())]); + } + for host in [None, Some(64)] { + let cap = + limit.filter(|&n| !v1 || (n < 1 << 62 && host.is_none_or(|h| n < h))); + let expected = expected_usage.map(|(program_bytes, source)| MemoryUse { + program_bytes, + source, + limit: cap.map_or(MemoryLimit::Unlimited, MemoryLimit::Bytes), + }); + assert_eq!( + read_memory(&tree.path, || host), + expected, + "v1 {v1}, limit {limit:?}, host {host:?}, stat {stat:?}" + ); + } + } + } + } + } + // A v1 memory controller mounted at `cgroup_dir`, with an optional // host `MemTotal` line, as read through the production /proc layout. fn v1_proc_fixture(cgroup_dir: &Path, meminfo: Option<&str>) -> TempTree { diff --git a/crates/runtime/src/health.rs b/crates/runtime/src/health.rs index fc6db72f7..fa5886eaf 100644 --- a/crates/runtime/src/health.rs +++ b/crates/runtime/src/health.rs @@ -409,32 +409,38 @@ mod tests { #[tokio::test] async fn health_request_line_can_span_multiple_reads() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let mut client = TcpStream::connect(listener.local_addr().unwrap()) - .await - .unwrap(); - let (server, _) = listener.accept().await.unwrap(); - client.write_all(b"GET ").await.unwrap(); - server.readable().await.unwrap(); - server.writable().await.unwrap(); - - let response = super::answer_connection(server); - tokio::pin!(response); - // Poll the handler with only the first fragment available. - tokio::select! { - biased; - result = &mut response => panic!("answered before the request line was complete: {result:?}"), - () = std::future::ready(()) => {} - } + for (method, body) in [("GET", "ok"), ("HEAD", "")] { + let line = format!("{method} /health HTTP/1.1\r\n"); + for split in 1..line.len() { + let mut client = TcpStream::connect(listener.local_addr().unwrap()) + .await + .unwrap(); + let (server, _) = listener.accept().await.unwrap(); + client.write_all(&line.as_bytes()[..split]).await.unwrap(); + server.readable().await.unwrap(); + server.writable().await.unwrap(); + + let response = super::answer_connection(server); + tokio::pin!(response); + // Poll the handler with only the first fragment available. + tokio::select! { + biased; + result = &mut response => panic!("answered before the request line was complete: {result:?}"), + () = std::future::ready(()) => {} + } - client - .write_all(b"/health HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n") - .await - .unwrap(); - response.await.unwrap(); - let mut text = String::new(); - client.read_to_string(&mut text).await.unwrap(); - assert!(text.starts_with("HTTP/1.1 200 OK"), "unexpected: {text}"); - assert!(text.ends_with("\r\n\r\nok"), "unexpected: {text}"); + client.write_all(&line.as_bytes()[split..]).await.unwrap(); + response.await.unwrap(); + let mut text = String::new(); + client.read_to_string(&mut text).await.unwrap(); + assert!(text.starts_with("HTTP/1.1 200 OK"), "unexpected: {text}"); + assert_eq!( + text.split_once("\r\n\r\n").unwrap().1, + body, + "split {split}" + ); + } + } } // Paused time fires the sleep below only after every ready accept and diff --git a/docs/BUNNY-UPDATES.md b/docs/BUNNY-UPDATES.md index 4d2771e5d..46a705edd 100644 --- a/docs/BUNNY-UPDATES.md +++ b/docs/BUNNY-UPDATES.md @@ -276,7 +276,7 @@ the new base image's baked bot before the API. On a managed installation, a same-ABI base-image swap restores the pinned bot and leaves the core schema unchanged. -For the guild schema 23 → 24 and 24 → 25 upgrades, use a revision-49 or newer +For the guild schema 23 → 24, 24 → 25, and 25 → 26 upgrades, use a revision-49 or newer bot launcher. Apply one guild schema step at a time. If the running bot launcher is older, check the matching release in Administration and use **Advanced launcher controls** to update the bot diff --git a/docs/DATABASE-BASELINE.md b/docs/DATABASE-BASELINE.md index fb087b449..2713cfc16 100644 --- a/docs/DATABASE-BASELINE.md +++ b/docs/DATABASE-BASELINE.md @@ -120,8 +120,8 @@ across guilds ([MEMBERS.md](MEMBERS.md)). ## Separate guild-store family -The `GuildDataStore` library initializes/verifies `jmodguard-guild-1`, version 25, -using `migrations/guild/0016_baseline.sql` through `0024_deletion_requests.sql`. +The `GuildDataStore` library initializes/verifies `jmodguard-guild-1`, version 26, +using `migrations/guild/0016_baseline.sql` through `0025_subject_case_dates.sql`. The v0.2.0 baseline includes the version 16 payload format with optional immutable ban attempt tags, and the version 17 `guild_member_pending_rejoin_notes` table for durable member-rejoin log delivery. @@ -142,12 +142,13 @@ Version 25 adds [deletion requests](DELETION-REQUESTS.md) and the transaction-scoped grants that let an erasure redact one person's data from cases, case history, evidence and unresolved audits. Existing rows are not changed. For stores on schema 24, use the same paired upgrade. +Version 26 indexes live cases by subject, date and case ID for chronological member case lists. Earlier binaries must not open stores that use a newer guild schema. This separate database holds identity, placement bindings, receipts, membership/log-channel settings, selected cases, history, sources, evidence ownership, Bunny transfer progress, tenant settings, bounded latest-message snapshots and the bounded [member directory](MEMBERS.md). Initialize verifies and upgrades a matching earlier -store atomically at bot startup. Ordinary opens require version 25. See +store atomically at bot startup. Ordinary opens require version 26. See [tenant runtime](TENANT-RUNTIME.md). Core is at schema 35. Each opener refuses the other family. No records are moved by startup. Guild migration 0009 adds bounded latest-message snapshots with fixed 24-hour expiry diff --git a/docs/GUILD-STORES.md b/docs/GUILD-STORES.md index c11daac98..408ed31be 100644 --- a/docs/GUILD-STORES.md +++ b/docs/GUILD-STORES.md @@ -56,7 +56,7 @@ pairs fail instead of falling back to a local file. Synchronous open/initializat on a startup or blocking worker, like core database opening. The separate `jmodguard-guild-1` family starts at the v0.2.0 baseline (schema -version 17) and applies migrations 0017–0024 to reach version 25. The baseline +version 17) and applies migrations 0017–0025 to reach version 26. The baseline includes the earlier schema changes described below. Version1 introduced an immutable singleton identity (family, store ID, shared/dedicated owner), immutable initial guild/revision bindings and mutation receipts. Version2 adds captured membership and @@ -103,12 +103,13 @@ Version 25 adds `guild_deletion_requests` and `guild_erasure_grants` for [deletion requests](DELETION-REQUESTS.md), and lets a granted transaction redact one person's data from otherwise immutable cases, history, evidence and unresolved audits. Use the same paired upgrade for stores on schema 24. +Version 26 adds a chronological case index for each subject within a membership. Guild-store migrations run separately from core bootstrap. | Operation | Contract | |---|---| -| `initialize` | At bot startup, initialize an empty database atomically, upgrade a matching store at version 17 or later to schema 25, or verify a current identity. Refuse core, foreign, unmarked, newer or mismatched stores without adopting them. | -| `open` | Verify the current schema 25 identity and ownership. Ordinary runtime opens create no schema or binding. | +| `initialize` | At bot startup, initialize an empty database atomically, upgrade a matching store at version 17 or later to schema 26, or verify a current identity. Refuse core, foreign, unmarked, newer or mismatched stores without adopting them. | +| `open` | Verify the current schema 26 identity and ownership. Ordinary runtime opens create no schema or binding. | | `bind_initial_placement` | Verify identity and install the catalog's initial guild/revision in one primary transaction. Matching retries write nothing; a different revision or dedicated owner conflicts. | | `verify_placement` | Check identity, ownership and the exact stored guild/revision in one primary snapshot; missing bindings fail. This is not authorization for a later separate data operation. | diff --git a/docs/HISTORICAL-PROPERTIES.md b/docs/HISTORICAL-PROPERTIES.md new file mode 100644 index 000000000..a5bd34171 --- /dev/null +++ b/docs/HISTORICAL-PROPERTIES.md @@ -0,0 +1,41 @@ +# Historical regression properties + +The [coverage ledger](historical-fix-coverage.tsv) inventories 399 candidate commits from the 773 commits reachable at `87e1dfed74a0`. Candidates came from fix markers in commit titles, squash bodies and published fix notes. Each property row names the contract, its executable test and the historical commit. A multi-fix commit can have additional unexamined contracts. Historical names on open rows are starting points for reading the original patch. + +| Evidence | Commits | +| --- | ---: | +| Property added or extended in this PR | 36 | +| Existing bounded property inspected | 71 | +| Historical test observed passing, domain still to examine | 239 | +| Missing or unmatched historical test, patch still to trace | 41 | +| Documentation, dependency, merge or retired pipeline | 12 | + +The ban-delivery model compares each prefix of generated audit delivery and unban sequences with durable history, the active ban and its event mirror. The cgroup properties exercise real temporary v1 and v2 filesystem trees. The checkout tests hold a real connection permit while advancing Tokio time past the original write deadline. The combined-memory UI property redistributes a byte total between processes around multiple billing block boundaries. These properties cover their stated domains. They do not establish correctness for arbitrary event interleavings or provider implementations. + +## Reproducing the checks + +Use `cargo nextest run --locked --workspace` for the default Rust workspace tests. Run `node --test --test-name-pattern='Bot Resources rounds combined memory' scripts/frontend-state-test.mjs` for the memory display property. The browser chart tests also require the repository's Firefox fixture. + +Run the two solver models with `z3 tests/models/case-pagination.smt2` and `z3 tests/models/read-templates-and-deadlines.smt2`. Unsatisfiable negations establish the modeled invariants. The pagination model assumes a fixed snapshot, unique IDs ranked by SQLite binary order, and a positive page limit. Its counterexample is a redacted subject key of zero rejected by the old cursor validator. The read-template model assumes a deterministic parser predicate and exact full-string cache hits. The deadline model uses integer times on one monotonic clock. Resetting a budget of two ticks after spending one admits one more tick at the original expiry. + +## Reproducing the performance fixture + +Use the same optimized build and CPU affinity for both revisions. The benchmark runs a real scoped read on a local guild with 24,000 live cases, eight matches, newest first, page size 25 and totals disabled. It checks the exact ordered IDs, continuation and total on every read. Each invocation records 25 samples after one warm-up per query. For the baseline, copy the benchmark module into the same test directory at `87e1dfed74a0` and add `mod latency;` to `tests/cases.rs` under `src/db/guild_data/`. + +```sh +cargo --config 'profile.release.package.jmodguard.debug-assertions=true' test \ + --release --locked -p jmodguard --lib \ + db::guild_data::tests::cases::latency::current_thread -- --ignored --exact --nocapture +``` + +Run the sibling `multi_thread` test for the runtime control. Five trials alternated the revision order. With CPU affinity pinned to four logical CPUs the median of trial medians was 21.476 ms before and 0.168 ms after for the member lookup (127.8×). The unfiltered first page measured 0.538 ms before and 0.214 ms after (2.5×). These figures describe warm local-store latency. + +Trial medians for member lookups, in microseconds. + +| Paired trial | Current-thread base | Current-thread PR | Multithread base | Multithread PR | +| ---: | ---: | ---: | ---: | ---: | +| 1 | 21502.754 | 176.811 | 19397.941 | 182.292 | +| 2 | 20952.112 | 164.217 | 20631.423 | 168.886 | +| 3 | 21295.985 | 168.034 | 20150.333 | 163.335 | +| 4 | 21475.552 | 173.575 | 20618.367 | 161.361 | +| 5 | 21815.237 | 166.892 | 20691.137 | 168.596 | diff --git a/docs/historical-fix-coverage.tsv b/docs/historical-fix-coverage.tsv new file mode 100644 index 000000000..b7188e182 --- /dev/null +++ b/docs/historical-fix-coverage.tsv @@ -0,0 +1,400 @@ +commit title status contract property test or first historical test lead +87e1dfed74a0 samwise: bound snapshot capture checkout by its write deadline (#1201) added or extended bounded property Held checkout expires exactly at its original deadline on both store entry points. remote_capture_permit_wait_uses_the_captured_write_deadline; advised_claim_promote_permit_wait_uses_the_captured_write_deadline +9ba79c7f6fd0 Keep owner sessions when deletion request references contain 401 (#1190) previously mapped property Session survives ordinary errors whose request reference contains 401. a request reference in an ordinary API error preserves the session +bb64957dda6a perf(bot,api): fix memory leaks, reduce RAM bloat, and optimize hot paths (#1185) added or extended bounded property All 16,384 adjacent ASCII pairs agree with the Unicode normalizer in both collapse modes. ascii_normalize_matches_unicode_pipeline_for_every_adjacent_pair +357a2c7132be feat(webui): redesign the Your servers page (#1182) historical test name observed passing; inspect assertion and domain server_enrollments_include_discord_role_and_active_member_count +9fe2abcb658c fix(ci): separate workflow shell steps from literal arguments (#1181) inspect patch; no added named test found — +0659b2d4d4d2 feat(webui): owner database backup export and restore (#1164) historical test name observed passing; inspect assertion and domain backup_routes_enforce_owner_origin_and_preview_denial +6051b04cd98c build(deps): bump rcgen from 0.13.2 to 0.14.10 (#1176) existing regression modified in fix and observed passing; inspect domain tls_control_record_cannot_start_delete_confirmation +660dbdbbcc58 fix(webui): apply Sentinel redesign styling to remaining pages and replace native confirm dialogs (#1180) historical test name observed passing; inspect assertion and domain in-app Sentinel confirmation modal handles Cancel, Close, Accept, destructive tone and never calls native confirm +c56898c5c1d4 test(webui): rework brittle source-grepping and daisyUI-class tests (#1179) historical test name observed passing; inspect assertion and domain ban_marker_reservation_times_out_at_deadline_and_never_blocks_ban +82f92d6c2eff refactor(webui): rebuild modal-box dialog interiors on Mantine Modal (#1178) historical test name observed passing; inspect assertion and domain all six modal dialogs use Mantine Modal parts, sizes, and close/dirty-leave semantics +2c0d63d34547 refactor(webui): replace daisy card stacks with Sentinel Paper cards (#1177) historical test name observed passing; inspect assertion and domain workspace cards and emptyPanel render Sentinel Paper cards without daisy classes +ec0bc499cac1 feat(webui): larger server icons and expandable server rail (#1173) historical test name observed passing; inspect assertion and domain server rail enlarges icons, toggles via keyboard, persists across reload, and expands cleanly on desktop and mobile +4935390675bf refactor(webui): switch form controls to Mantine inputs (#1172) historical test name observed passing; inspect assertion and domain workspace form controls render Mantine TextInput, NativeSelect, Textarea, Switch, and Checkbox without daisy classes +eda2d5c5baca fix(webui): increase overall UI scale via root percentage and rem tokens (#1171) existing bounded property inspected Two themes crossed with three real Firefox viewport sizes preserve root scale, bounded page width and minimum target size. dashboard density fits 1280x800 and keeps 24px targets in both themes +5c6a07d48649 fix(webui): rework dark mode color palette and button affordance contrast (#1170) historical test name absent from passing outputs; trace rename or retirement ${theme} controls and structural borders have >= 3:1 boundaries on their surfaces +65a329198ccb refactor(webui): replace custom toast and InfoTip with Mantine Notifications and Tooltip (#1168) historical test name observed passing; inspect assertion and domain toast notifications use Mantine Notifications with tone colors, persistent live region, modal focus safety, and autoClose timings +fc99180c19b3 refactor(webui): switch daisy-era buttons to Mantine Button and ActionIcon (#1167) existing regression modified in fix and observed passing; inspect domain Templates keep only form-footer text buttons and Settings role rows remove with icons +8c46ff632a26 test: remove obsolete frontend and launcher regression checks (#1160) historical test name observed passing; inspect assertion and domain workspace assets use local sources and shared package tooling +3cf5bc3c5b6d fix(webui): keep workspace navigation visible on scroll (#1158) historical test name observed passing; inspect assertion and domain workspace navigation and desktop rail stay in view while a tall page scrolls +0053a1d6f1f2 fix(webui): restore workspace routes with browser history (#1159) historical test name observed passing; inspect assertion and domain sign-in restores a non-list workspace link using the authorized guild +51cafdadcdfc ci(publish): validate release-please source by diff against validated commit (#1156) historical test name absent from passing outputs; trace rename or retirement JMODGUARD_REQUIRE_DESCENDANT=1 accepts an ancestor base and falls back for non-ancestor or missing bases +84d7a581fb4b ci: quick wins (parallel signing, slow-test clocks, cache restore) (#1154) existing regression modified in fix and observed passing; inspect domain audit_waits_for_delayed_callbacks_before_matching_an_older_ban +8cd42d78b6ff perf(docker): cache dependency and unchanged-crate compiles in image builds (#1152) historical test name observed passing; inspect assertion and domain build_commit_records_valid_sha_and_rejects_unknown_or_invalid +30d94d03461d fix(db): consolidate core migrations for v0.2.4 (#1120) existing regression modified in fix and observed passing; inspect domain released_core_databases_upgrade_with_data_and_reopen +e859a0b6c73a feat(webui): zero-modal Configuration workbench with Global diff (PR 2/2) (#1119) historical test name observed passing; inspect assertion and domain Automod Rules workbench selects rules via keyboard, compares underlying values, handles onboarding expected state, and hides empty search +fdefd9d3e43c feat(webui): Sentinel Fleet Workbench shell and Bento Command Center (PR 1/2) (#1118) historical test name observed passing; inspect assertion and domain Command Center inline shield controls cycle Off, Dry, and Live with captured enrollment +c94df1c4b584 Fix WebUI chart compatibility and bot lookup test timing (#1117) existing regression modified in fix and observed passing; inspect domain lookup_never_applies_and_returns_only_the_same_actors_result +de08139d2957 fix(webui): center workspace pages at a shared maximum width (#1114) existing bounded property inspected For each tested viewport and theme, workspace bounds have the expected width and centered offset. dashboard density fits 1280x800 and keeps 24px targets in both themes +83866cd8b8d8 fix(webui): give system admins access to Bot servers (#1106) historical test name observed passing; inspect assertion and domain system_admin_can_add_a_bot_server_without_a_server_admin_grant +7deaa2274961 fix(deps): bump cross-spawn to 7.1.2 to patch GHSA-ghv9-86vm-4v8m (#1100) lockfile-only dependency repair Only the dependency lock changed. Repository supply-chain checks are the applicable gate. — +1bf23ceb0eb1 Replace the WebUI component stack with Mantine (#1096) historical test name observed passing; inspect assertion and domain Mantine metrics, Automod actions, and editor focus work in the built workspace +f5727ededc1a feat(commands): let server admins allow roles to use a command (#1095) existing bounded property inspected A grant does not change the target hierarchy for each tested command, equal and higher targets. granted_callers_still_meet_the_role_hierarchy +da6aee6fe60a fix(bot): apply the moderator role hierarchy to ban, kick and timeout commands (#1094) existing bounded property inspected Moderation commands agree on the expected refusal across target rank, guild ownership and actor-role combinations. moderation_commands_refuse_targets_not_below_the_caller +b8f42b752a44 fix(webui): keep Bunny cost history across resource ID changes (#1090) existing bounded property inspected Changing the billing resource or its identifier spelling preserves historical pricing and avoids double counting. cdn_zone_changes_keep_saved_pricing_and_count_respelled_ids_once +2e53d561acce fix(automod): poll the primary config version before media-preset dispatch (#1091) historical test name observed passing; inspect assertion and domain pending_media_preset_stops_after_separate_connection_disable +8931562e7235 fix(automod): refresh rule scope and version before stale actions (#1084) historical test name observed passing; inspect assertion and domain primary_dispatch_poll_refreshes_after_unchanged_replica_observation +4e5863c2678c fix(db): bound advised promotion checkout by its write deadline (#1085) added or extended bounded property Held checkout expires exactly at its original deadline on both store entry points. remote_capture_permit_wait_uses_the_captured_write_deadline; advised_claim_promote_permit_wait_uses_the_captured_write_deadline +789587b83732 feat(webui): backfill historical Bunny CPU without losing daily usage (#1082) historical test name observed passing; inspect assertion and domain magic_backfill_leaves_cpu_only_day_incomplete_until_daily_observed +040798924ade feat(webui): manage server admin access and enrollment limits (#1083) historical test name observed passing; inspect assertion and domain owner_admin_management_updates_admission_and_revokes_the_reviewed_assignment +8e37d0710d78 fix(webui): report partial Bunny costs and collector availability (#1081) existing bounded property inspected Across the collector failure fixtures the panel shows the matching explanation and suppresses the history table. Bot Resources marks unknown Bunny costs in history bars and explains collector failures +a35786f3a3ab fix(webui): distinguish Bot Resources history preparation failures (#1080) historical test name observed passing; inspect assertion and domain history_preparation_failure_has_a_distinct_owner_response +af9f18452d8f feat(webui): grant scoped server enrollment access (#1075) historical test name observed passing; inspect assertion and domain One full-queue regression. Its loop fills the queue before a single assertion scenario. server_admin_enrollment_is_reviewed_and_revocable_on_the_dashboard_routes +e23b31c7b1a6 feat(webui): let the owner enroll additional servers (#1074) historical test name observed passing; inspect assertion and domain Bot servers offers repeat enrollment and refresh discovers the joined server +9f0c16b21af0 feat(db): store deletion requests and redact one account's data in a server (#1067) previously mapped property Deletion distinguishes whole decimal IDs and mentions from longer IDs. Subject-sorted pages resume after erasure. mention_redaction_preserves_surrounding_text_and_other_decimal_ids; case_pages_partition_the_sorted_rows_after_redaction +9e8b24d28ce1 feat(webui): show CDN pull zone usage and cost on Bot Resources (#1064) existing bounded property inspected The CDN refresh fixtures distinguish unavailable data and retained successful readings across provider failures and pricing states. cdn_refresh_persists_scoped_data_and_keeps_last_good_values_on_failure +2ce8386b7e80 fix(ci): bump workspace versions in Cargo.lock on release PRs (#1059) existing bounded property inspected Every package selected by the release-please lockfile updater resolves to exactly one local lock entry at the release manifest version. scripts/publish-image-test.sh (release package names) +a1a11440039a fix(automod): validate image and text spam policy parameters (#1058) historical test name observed passing; inspect assertion and domain policy_preserves_positional_params_and_rejects_non_schema_fields +7e95a28b3821 feat(automod): finish onboarding bot trap role removal (#1016) historical test name observed passing; inspect assertion and domain onboarding_role_removal_manage_server_can_enable_and_change_roles +9a48b29de763 feat(webui): show Bunny provider costs and history on Bot Resources (#1018) existing bounded property inspected Each generated monthly window stays within its service retention and publication boundaries. backfill_windows_respect_retention_and_close_after_publication_lag +a6be994dbe0e fix(automod): revalidate rules and stop stale spam actions (#1051) historical test name observed passing; inspect assertion and domain custom_actions_recheck_matchers_and_scope_before_dispatch +83d0c743d6a9 fix(db): pin the write deadline on the claim_advised_bot_action busy fallback (#1048) added or extended bounded property The busy fallback consumes only the original budget after different amounts have already elapsed. advised_claim_busy_fallback_times_out_at_original_deadline +435f35ba50fc fix(automod): revalidate rule edits, known-spam forms and text deletes on proven-match rechecks (#1046) historical test name observed passing; inspect assertion and domain custom_ban_purge_rechecks_effective_matchers_with_unchanged_rule_rows +3fedd8e522b2 fix(db): pin a write deadline on the claim_advised_bot_action_conn promote path (#1044) added or extended bounded property Promotion succeeds at 4999 ms and fails from 5000 ms onward with pending action and no receipt. advised_claim_promotion_changes_outcome_at_the_original_write_deadline +100ddc9325f6 fix(core): preserve the write deadline when promoting guild snapshot captures (#1039) existing bounded property inspected Direct commit and contention retry both retain the pooled five-second capture deadline. remote_capture_keeps_the_pooled_write_deadline_through_commit_and_retry +2cdf9cc32243 fix(automod): use one freshness check for ban sweeps and image and text proven matches (#1040) historical test name observed passing; inspect assertion and domain badword_ban_purge_stops_after_pattern_removed_during_ban_lookup +f16e37b1a1f3 fix(tenant): make erase_job steps advance only after their fenced writes succeed (#1037) historical test name observed passing; inspect assertion and domain erasure_supersedes_directory_wipe_when_guild_rejoins_mid_job +334fc186fadc fix(automod): share rule freshness across deletes, sweeps and replies (#1035) historical test name observed passing; inspect assertion and domain channel_reply_uses_the_rule_admitted_for_delete +f654aed3bc65 perf(bot): gate advised action claims on primary due work (#1032) historical test name observed passing; inspect assertion and domain scheduler_checks_ban_expiry_after_an_advised_claim_timeout +ea36b34ad9d1 fix(db): re-check the write fence in erase_job Directory and Placement phases (#1033) historical test name observed passing; inspect assertion and domain late_erasure_fence_before_directory_preserves_directory_and_placement +b74df9baf223 fix(db): defer drive_erasure when a post-selection write fence is held (#1029) existing regression modified in fix and observed passing; inspect domain fence_after_erasure_selection_defers_completion_until_retry +a79ca06158b0 fix(db): poll_due_sql advises due for fenced overdue rows the claim excludes (#1019) existing regression modified in fix and observed passing; inspect domain fenced_overdue_actions_do_not_wake_the_poller +f940dfa4b668 fix(automod): skip in-flight deletes after their rule is disabled (#1013) historical test name observed passing; inspect assertion and domain pending_destructive_action_stops_on_delete_to_log_edit_before_dispatch +cc452b69ea74 perf(bot): avoid gateway-ban audit reads when attribution has no consumer or downstream effect (#1012) historical test name observed passing; inspect assertion and domain gateway_ban_persists_ownership_before_first_audit_request +b2d9656a7ce2 test(db): use a fixed UTC date in analytics fixtures (#1009) existing regression modified in fix and observed passing; inspect domain analytics_reads_and_writes_refuse_retired_enrollments +6645c16f9ad9 perf(bot): release compiled guild configuration after confirmed guild departure (#965) historical test name observed passing; inspect assertion and domain confirmed_departure_releases_compiled_config_and_fences_in_flight_loads +dec07a8f6f20 test(bot): verify fresh Discord reads for Settings authorization (#955) historical test name observed passing; inspect assertion and domain uncached_settings_actor_uses_fresh_member_get +a2dc39c41926 Apply confirmed spam-list edits without reloading configuration (#1005) historical test name observed passing; inspect assertion and domain known_bad_image_http_omits_stale_patch_after_writer_recovers_a_lost_reply +2d2e7a1b95f4 perf(api): bound Discord display cache residency (#993) historical test name observed passing; inspect assertion and domain updating_payload_weight_evicts_the_oldest_and_leaves_oversized_payloads_uncached +8ebb6e1e0ce7 fix(bot): enforce repeat-text budgets on replacement (#994) historical test name observed passing; inspect assertion and domain replacement_byte_budget_enforces_the_guild_limit +a5c6351de6ef perf(webui): load Platform Analytics member totals independently (#991) historical test name observed passing; inspect assertion and domain platform_history_skips_tenant_reads_while_member_totals_are_pending +381c40dda6ad perf(webui): share the runtime across workspace and Administration (#990) historical test name observed passing; inspect assertion and domain publishes_split_release_and_rolls_back_to_legacy_package +8085dcb3d91f perf(api): share guild snapshots across warm authorization (#988) historical test name observed passing; inspect assertion and domain warm_authorization_shares_guilds_without_leaking_preview_permissions +6eeb5d900cbc perf(bot): share overlapping guild config loads (#971) existing bounded property inspected Overlapping configuration callers see the same loaded data and compiled object. config_flight_shares_one_snapshot_and_compiled_config +45ca400fb2ba perf(bot): revalidate unchanged compiled configs on expiry (#970) existing bounded property inspected Repeated expiry with unchanged versions preserves compiled object identity within the measured read budget. expired_config_reuses_unchanged_compiled_rules +c93b7311c9db perf(bot): resolve edit channel names only when used (#983) historical test name observed passing; inspect assertion and domain message_edit_template_without_channel_skips_the_source_channel_lookup +4752974ac941 perf(updater): stream the verified layer and executable to disk while staging (#973) historical test name observed passing; inspect assertion and domain failed_stage_keeps_the_staged_executable_and_no_temporaries +a3beeb9c2810 perf(webui): debounce directory searches in the shared member picker (#963) historical test name observed passing; inspect assertion and domain the member picker waits for typing to settle and drops searches on close or a server change +a23211274eec perf(bot): read the current stay and pending rejoin note together (#960) historical test name observed passing; inspect assertion and domain receipt_read_error_keeps_current_stay_and_marks_member_gap +a8af775a070c perf(webui): cap retained display-cache weight in browser memory (#962) historical test name observed passing; inspect assertion and domain an oversized filtered result is shown complete but not served from memory after navigation +0f4aca66afaf perf(bot): refresh snapshot scope once during Ready (#954) historical test name observed passing; inspect assertion and domain ready_resolves_each_cached_snapshot_scope_once +bc3a4481205e perf(webui): load Settings role cards from one snapshot (#926) historical test name observed passing; inspect assertion and domain legacy role reads keep each card paired with its own revision +e3b0c8b7ca40 perf(bot): skip fact refresh for adder-only backfill (#925) existing bounded property inspected Across five guild histories the startup backfill preserves matching facts, fills missing facts and discards an adder belonging to an earlier membership. startup_backfill_refreshes_only_missing_or_earlier_membership_facts +3848004e2b9b perf(webui): batch automod exception member labels (#921) existing bounded property inspected Across two editors and four saved ID lists, batch lookups carry distinct IDs while rendered chips preserve saved order, duplicates and fallback labels. both rule editors batch saved user exception labels and keep missing member fallbacks +07963a299d28 fix(bot): stop stale automod spam sweeps after bans (#918) existing regression modified in fix and observed passing; inspect domain ban_purge_repeated_text_uses_saved_selection_and_keeps_matched_deletes +4426b50c830c fix(automod): prefer same-guild onboarding replay eviction (#917) existing bounded property inspected Under capacity pressure in a busy guild, the other guild's recent entry survives in both live and dry-run modes. replay_history_pressure_keeps_other_guilds_recent_matches +25d2f10824b7 fix(bot): group automod cleanup in bulk-only log layouts (#910) historical test name observed passing; inspect assertion and domain bulk_only_destination_groups_cleanup_and_excludes_filtered_sources +3b08226da5c6 fix(ci): retry verified staging manifest lookups during promotion (#915) inspect patch; no added named test found — +dd21d81a1155 fix(webui): preserve resource chart endpoint dates at large fonts (#913) added or extended bounded property Firefox checks both endpoint labels and marks, plot bounds and intersections under font and viewport changes. chart plots and labels fit with a 64px browser default font; chart plots and labels fit with a 16px browser default font; chart plots and labels fit with a 32px browser default font +67883b412519 feat(automod): optionally clean recent messages after onboarding kicks (#909) historical test name observed passing; inspect assertion and domain trap_cleans_only_tracked_messages_in_the_stay_after_a_confirmed_kick +0c2c2ebffa0d perf(webui): limit renders from draft keystrokes (#916) historical test name observed passing; inspect assertion and domain template keystrokes update the edited field and its preview without rendering unrelated fields or the sidebar +4bbe0dee83fa fix(webui): handle empty analytics and reset chart cursors (#914) added or extended bounded property Absent series show no chart. Six nonempty series lengths preserve a hit per observation and one enforcement bar per nonzero day. Singleton membership draws a point. analytics distinguishes missing daily data from observed zeros and single days +dc8e63f29920 fix(webui): correct case-removal permission help (#908) existing regression modified in fix and observed passing; inspect domain access-role saves send string role IDs, levels and the loaded revision +cc591b31ed64 fix(webui): show the configured bot nickname (#907) historical test name observed passing; inspect assertion and domain dashboard distinguishes an unset bot nickname from unavailable settings +bc2ee36d065b feat(logging): consolidate automod spam cleanup into one delete-log notice (#794) historical test name observed passing; inspect assertion and domain one_notice_for_rest_and_single_and_bulk_purge_echoes_across_three_channels +bb7bf426b5fa fix(webui): keep both chart date labels at 320px with a 32px default font (#818) added or extended bounded property Firefox checks both endpoint labels and marks, plot bounds and intersections under font and viewport changes. chart plots and labels fit with a 64px browser default font; chart plots and labels fit with a 16px browser default font; chart plots and labels fit with a 32px browser default font +d1797bfe2725 perf(db): skip primary scans for ineligible ban expiries (#815) historical test name observed passing; inspect assertion and domain idle_queue_poll_opens_no_transaction_and_next_poll_dispatches +afd14fb1ddc1 feat(webui): show memory in 64 MB billing blocks and an estimated hosting cost on Bot Resources (#813) added or extended bounded property Moving bytes between bot and API leaves the displayed minimum capacity and headroom invariant on both sides of each 64 MiB block boundary. Bot Resources rounds combined memory up from bytes, including zero and block boundaries +a8df67fc3e77 fix(webui): cap chart size so graphs stay readable on wide screens (#810) added or extended bounded property Firefox checks both endpoint labels and marks, plot bounds and intersections under font and viewport changes. chart plots and labels fit with a 64px browser default font; chart plots and labels fit with a 16px browser default font; chart plots and labels fit with a 32px browser default font +ecd99ec4d3ce fix(members): show not-imported servers correctly and let unverified coverage recover (#809) existing bounded property inspected Audit recovery eligibility changes at the retry deadline while the displayed gap remains uncertain. short_restart_waits_for_bounded_audit_permission_retry +4757afb6f84c feat(automod): add a built-in onboarding bot trap rule with an admin setup guide (#804) historical test name observed passing; inspect assertion and domain onboarding_trap_bot_and_dashboard_saves_compare_the_same_base +3983f3e29f38 feat(automod): add a no links or media channel rule with a channel reply action (#803) historical test name observed passing; inspect assertion and domain media_preset_saves_with_deleted_channels_and_validates_remaining_types +961cff2874e8 fix(webui): stop password managers offering logins on non-login fields (#806) historical test name observed passing; inspect assertion and domain Cases fields tell password managers to ignore them +dc7fe03d57af fix(webui): remove the leftover routine chat collection tile (#795) historical test name observed passing; inspect assertion and domain bot_startup_warns_once_when_legacy_retention_is_configured +4dddc62417ad fix(webui): fail closed on sidebar access for users with no server access (#793) historical test name observed passing; inspect assertion and domain owner_routes_reject_a_discord_administrator +c2d39b905770 feat(webui): give the privacy and terms pages a proper layout (#792) existing bounded property inspected On both legal pages the contents links agree with the actual section headings and the header and footer preserve navigation. legal_pages_render_the_shared_layout_and_resolvable_section_links +393c6041a78c fix(deps): update cookie and url for RUSTSEC-2026-0594 and RUSTSEC-2026-0592 (#796) lockfile-only dependency repair Only the dependency lock changed. Repository supply-chain checks are the applicable gate. — +2e3341b36038 fix(runtime): handle split health probe requests (#780) added or extended bounded property Every internal byte split of a GET or HEAD health request yields its proper status and body. health_request_line_can_span_multiple_reads +9cb64c18d933 fix(db): coordinate backoff during remote primary stalls (#763) existing bounded property inspected The classified transport failures are checked in both gate-reporting states. primary_gate_counts_gateway_errors_and_closed_http_connections +28ebae914f93 fix(api): suppress stale session cookie warning (#762) historical test name observed passing; inspect assertion and domain stale_session_lookup_does_not_warn +a3985bf9bc93 fix(automod): delete sustained velocity floods after escalation (#761) historical test name observed passing; inspect assertion and domain velocity_does_not_delete_after_a_terminal_log_or_warn +f69fea48d18e perf(db): attribute primary statements by path and skip idle primary work (#753) (#760) historical test name observed passing; inspect assertion and domain range_breakdown_ranks_a_late_busy_label_by_count +e07177b36bd2 feat(commands): show friendly argument usage (#759) historical test name observed passing; inspect assertion and domain malformed_moderation_commands_send_usage_in_the_invocation_channel +ccda885eb0d9 fix(ci): select checks for affected test consumers (#752) existing bounded property inspected Each enumerated shared source and consumer manifest selects its expected downstream test groups when supplied as the only changed path. scripts/select-checks-test.sh (expect_each) +a7760d9a5631 Fix automod velocity and add bot regression coverage (#745) existing bounded property inspected Both permutations of the same arrivals preserve window membership. velocity_counts_messages_by_arrival_time +bb9c3c4a3dd5 fix(status): report published builds and refresh WebUI observations (#749) historical test name observed passing; inspect assertion and domain legacy_writer_preserves_manual_readback_and_scheduled_webui_admission +dce7cf8628f3 ci: enable owner-only Pullfrog reviews (#758) historical test name absent from passing outputs; trace rename or retirement accepts opening a PR, marking it ready, and pushing to it, including drafts +15e80466f2b5 feat(commands): give !about a branded embed with the project link (#743) (#751) existing bounded property inspected The help hint adapts to the configured command prefix for all three prefix fixtures and the branded embed retains its expected project link. about_embed_links_the_repo_and_shows_no_deployment_identifiers +9a1a6c60ebc9 test: use fixed clocks in core, updater and runtime tests (#735) historical test name observed passing; inspect assertion and domain neither_layout_readable_is_unavailable +f74c945e1bf9 fix(publish): retry staging pushes by phase, not registry error text (#731) added or extended bounded property For zero through four failed pushes, the real publication helper builds once and retries only the push. The trace, final outcome, metadata and diagnostic match the three-attempt budget. scripts/publish-image-test.sh (push_failures) +98b455c9aac7 test: replace fixed sleeps with signals in API tests (#736) existing regression modified in fix and observed passing; inspect domain api_process_waits_for_first_boot_with_overlapping_read_bind_without_a_bot_token +d4a024804ad8 test: replace fixed sleeps with signals in bot tests (#737) existing regression modified in fix and observed passing; inspect domain audit_waits_for_delayed_callbacks_before_matching_an_older_ban +dfa6186b8d25 test(ci): share the frontend Node timeout minimum (#729) inspect patch; no added named test found — +1c1f0704847a test(webui): stop frontend test runaways from exhausting memory (#709) (#711) historical test name observed passing; inspect assertion and domain failed assertions on mounted nodes report a short preview +910262771160 test: replace fixed sleeps with signals in core, updater and runtime tests (#710) existing regression modified in fix and observed passing; inspect domain cancellation_keeps_started_transfer_alive_and_independent_cleanup_blocked +332bae1b6f38 feat(webui): search the Audit log and show readable event details (#649) (#708) existing bounded property inspected Every server event type has a readable summary and hides every enumerated internal key and scalar value from the non-owner view. Audit Log Details summarize every event type without internal fields +2cf31c4d8196 ci(deps): move bot and API images to Debian 13 Trixie (#712) historical test name observed passing; inspect assertion and domain api_judges_bot_built_in_restore_by_the_bot_container_abi +ffdbb9292e40 fix(webui): show why a Ban user member search failed (#664) (#707) added or extended bounded property Four server error responses each preserve the actual error in the picker alert. Successful empty searches, transport failure and cancellation retain their distinct outcomes. the ban dialog finds current members by name and says when the search failed +5645ee37f78c perf(webui): render cached display reads at once and revalidate them in the background (#653) (#704) historical test name observed passing; inspect assertion and domain list_deadline_wire_response_distinguishes_a_retryable_read +26072a95b663 perf(webui): reuse Discord guild snapshots for minutes with gateway invalidation (#653) (#706) historical test name observed passing; inspect assertion and domain guild_reads_reuse_the_snapshot_for_minutes_and_refresh_it_in_the_background +758a07cd99f7 fix(bot): keep built-in rule dry-run and exemptions when its config re-read fails (#659) (#702) inspect patch; no added named test found — +73150ea5aa4b fix(bot): suppress stale Discord message edit replays (#694) historical test name observed passing; inspect assertion and domain edit_window_capacity_preserves_pending_claims_and_reuses_idle_slots +43c0af8c4d9f feat(webui): add owner Bot Resources page for bot and API resources (#652) (#696) existing bounded property inspected On repeated failed history reads, a warm range retains the stale snapshot and a cold range reports unavailable until a successful refresh. failed_history_reads_are_reused_until_the_next_refresh +adc2c5b458f1 fix(webui): link policy pages from dashboard footers (#698) historical test name observed passing; inspect assertion and domain signed-out landing footer links to public policies on the page origin +33068837bda5 fix(db): wait for the guild-store writer lock and fix two flaky tests (#695) historical test name observed passing; inspect assertion and domain writable_store_queues_for_the_writer_lock_like_the_bot_core +5d0bde21949a fix: correct Members name sort and bind list cursors (#692) previously mapped property Member name index migration and precedence for all null, empty, and populated field combinations. member_name_sort_key_skips_empty_names_after_schema_22_upgrade +d3e36f578945 fix(bot): align image metadata enforcement with hash matches (#691) historical test name observed passing; inspect assertion and domain gateway_fast_image_deletes_without_banning_when_moderator_status_is_unknown +39dd08602b0b feat(webui): toggle commands on and off from the Commands list (#689) existing bounded property inspected Toggling enabled state for the tested built-in and custom command layers preserves the other saved fields and their scope. enabled_only_command_updates_preserve_saved_fields_and_scope +e5d31a14f03d fix(webui): flush and restore a pending Bans search on auth loss (#687) historical test name observed passing; inspect assertion and domain Bans restores pending search after reauthentication before debounce +d9423c82b0c7 ci: add lints for flaky test patterns (#683) existing regression modified in fix and observed passing; inspect domain ordinary_exit_after_idle_keeps_health_during_stalled_control +d92b997b582c fix(api): bind the Bans list cursor to its filters and sort (#686) existing bounded property inspected Ban paging enumerates six sort orders in both directions and rejects changes to every captured filter. ban_list_filters_and_orders_use_the_same_cursor_page +39318c9b4d7e test: fix flaky tests tracked in #661 (#682) existing regression modified in fix and observed passing; inspect domain Database Usage Details lists disjoint physical categories and unknown guard status +909be2fcb89e feat(webui): sort Cases newest first with server-side column sort and shared list controls (#657) existing bounded property inspected Case order and filters apply before cursor pagination across sort directions. case_list_orders_and_filters_are_applied_before_paging +5a1ce426024d feat(webui): add server-side sort, search and filters to the Bans list (#660) existing bounded property inspected Ban paging enumerates six sort orders in both directions and rejects changes to every captured filter. ban_list_filters_and_orders_use_the_same_cursor_page +bfcf571a6a9e chore(deps): update Node to 26 LTS and npm dependencies (#669) existing regression modified in fix and observed passing; inspect domain server switcher name truncation keeps open rows inside the list and reuses the compact select sizing +2056f3c232e4 feat(webui): add public Privacy Policy and Terms of Service pages with data deletion requests (#667) existing bounded property inspected Both legal pages reference a resolvable self-contained dashboard stylesheet, home and each other. legal_pages_use_dashboard_origin_for_style_home_and_cross_links +0bc07f2e89a1 fix(webui): don't lock out a fresh login on a Discord 429 during guild checks (#655) historical test name observed passing; inspect assertion and domain fresh_login_reuses_callback_guild_list_for_me +72adb0645050 fix(bot): fold attachment burst into Exact image spam rule (ban + delete last hour) (#662) historical test name observed passing; inspect assertion and domain gateway_two_channel_image_burst_bans_and_sweeps_previous_hour +102ebf8f165b fix(deps): bump eslint to 10.15.0 for minimatch CVE-2026-118764 (#654) tooling dependency update Updates only the ESLint development tool manifest and lockfile. — +8cafef629f3c feat(webui): readable Bans page, editable reason and queued real bans (#625) (#641) existing bounded property inspected For either request outcome, all submitted fields stay locked with their submitted values through the pending interval, and exactly one request is emitted. the ban dialog locks all submitted options until acknowledgment or failure +b9765b727c2d feat(webui): open cases as a readable case file and filter the Cases list (#640) historical test name observed passing; inspect assertion and domain case_reads_filter_the_list_and_name_known_members +c85c25ce3e59 feat(webui): rebuild the command editor as a form and let servers override built-in commands (#639) existing bounded property inspected For each built-in command fixture, saving untouched typed fields preserves its effective behavior and produces one guild-scoped write. every built-in command edits its behavior through typed fields and saves the same shape +c5ea70a6903a feat(webui): redesign the Automod rule editor to be compact and self-explanatory for every rule (#635) existing bounded property inspected Rule fixtures have the expected human summary and editor sections, with live edits reflected in the summary. rule editor summary describes every built-in rule and custom rule and updates live +5796701d176f fix(bot): keep deleted-message content when snapshot storage is unavailable (#634) historical test name observed passing; inspect assertion and domain unavailable_snapshot_store_logs_edit_and_deletes_from_memory_cache +fe119b4c2a34 feat(webui): shorten Community help text into one-line intros and collapsed notes (#631) historical test name observed passing; inspect assertion and domain Members partial-import explanation opens inside narrow screens +f07d74901133 feat(webui): shorten Workspace help text into one-line intros and collapsed notes (#630) historical test name observed passing; inspect assertion and domain Workspace pages keep explanatory text short and move details into collapsed notes +907cb4645c85 feat(webui): make the Event templates variables help readable (#629) existing bounded property inspected The help view supplies the expected groups, meanings and examples for the enumerated template variables. template variable help lists each variable with its meaning and an example, grouped +f4f320f58fdb fix(bot): tolerate short database stalls and deduplicate startup notices (#628) historical test name observed passing; inspect assertion and domain local_replacement_waits_for_a_crashed_holders_longer_lease +2f2d0790f31d feat(webui): redesign Owner Platform analytics as a fleet dashboard (#626) existing bounded property inspected Each dashboard range of 7, 30 and 90 days returns exactly as many daily rows. The default is 30 and the sampled unsupported range is refused. platform_analytics_accepts_only_dashboard_ranges +2e322b8689eb fix(logging): keep expected startup states below WARN (#615) existing bounded property inspected Memory diagnostics distinguish absent optional stats from failed or invalid reads across real file layouts. memory_source_log_levels +6cf67eb516e9 feat(webui): move owner usage and platform analytics into workspace (#614) historical test name observed passing; inspect assertion and domain Database Usage shows size, limit share, next threshold, health and freshness without expanding anything +e7fd43db7a24 feat(webui): show server icons in the sidebar server switcher (#611) historical test name observed passing; inspect assertion and domain open server switcher keeps long names inside the list with an ellipsis +96a5ad0e96ff fix(runtime): don't show the host memory ceiling as the container limit in !status (#607) added or extended bounded property Local v1/v2 files across absent, zero, numeric and sentinel limits, host ceilings and accounting sources. memory_reading_agrees_across_limit_and_stat_boundaries +f35989f45c6b fix(webui): define sr-only so the chart summary is visually hidden (#605) historical test name absent from passing outputs; trace rename or retirement chart summary sr-only class resolves to a visually-hidden rule in the shipped CSS +71b0bdebc528 feat(webui): tighten global density to a desktop admin-console scale (#599) historical test name observed passing; inspect assertion and domain dashboard hides Getting started only once every setup step has data +c238018d4a1f feat(bot): render !status as a pastel embed (#596) existing bounded property inspected The prefix and slash routes both preserve the chosen custom stats presentation, with no duplicate embed. custom_stats_response_gets_plain_text_stats_through_prefix_and_slash +59df8b32a234 "fix(runtime): treat only ""max"" as unlimited for cgroup v2 memory.max (#598)" added or extended bounded property Local v1/v2 files across absent, zero, numeric and sentinel limits, host ceilings and accounting sources. memory_reading_agrees_across_limit_and_stat_boundaries +4fc65d85a3b2 fix(runtime): fall back from missing memory.stat and log cgroup layout (#594) added or extended bounded property Local v1/v2 files across absent, zero, numeric and sentinel limits, host ceilings and accounting sources. memory_reading_agrees_across_limit_and_stat_boundaries +36d6f698a833 fix(webui): show current components as Up to date and disable their Update buttons (#593) historical test name absent from passing outputs; trace rename or retirement a directly deployed bot or API on the available source is up to date and cannot be updated again +8af6a6c04a71 feat(webui): owner server directory with departure action (#584) historical test name observed passing; inspect assertion and domain owner_leave_checks_the_origin_before_any_data_access +fae2a7470ba0 feat: add server and platform analytics dashboards with daily trend charts (#583) historical test name observed passing; inspect assertion and domain platform_member_totals_distinguish_empty_unavailable_and_incomplete_fleets +f86595af2eaf feat(webui): let guild admins grant Web UI access to moderators by Discord role (#581) historical test name observed passing; inspect assertion and domain role_mapped_moderator_reaches_only_that_guild_at_its_level +245b379e06b7 fix(webui): show Local case history as Not counted, not Unknown (#578) (#580) existing regression modified in fix and observed passing; inspect domain Members keeps completed phases done while local case history finishes and shows phase counts +c1ddf20c116c fix(updater): log one line per unsaved startup receipt attempt (#552) (#570) historical test name observed passing; inspect assertion and domain api_role_startup_receipts_log_one_info_line_per_unreachable_link_attempt +b5c1f06a23ed fix(webui): make the Members coverage notice readable and let short planned restarts clear it (#569) added or extended bounded property Every Ready shard must have a connected runner over three shards, every runner stage and absence. planned_stop_needs_every_ready_shard_connected +481a9e24842b fix(webui): keep the sidebar and its footer controls visible while the page scrolls (#575) historical test name absent from passing outputs; trace rename or retirement desktop sidebar keeps its footer controls in view while a tall page scrolls +07a460e696d5 fix(webui): leave Known spam clean after a Global add and keep add errors visible (#573) historical test name observed passing; inspect assertion and domain known spam Global add keeps Global selected without an unsaved draft and keeps the other unsaved entry +a43e36d438a8 fix(updater): wait quietly while the bot migrates the core schema (#551) (#568) historical test name observed passing; inspect assertion and domain api_migration_wait_keeps_its_start_across_a_failed_control_read +1253a3dc7896 Merge pull request #574 from jatmn/fix/549-docker-login-credentials-comment documentation-only change First-parent diff contains only comments describing image publishing. — +7ac6e1fecebe Merge branch 'main' into fix/549-docker-login-credentials-comment merge integration; compare component commits Two-parent integration of main into the same topic branch. — +53132ddabae3 Merge branch 'main' into fix/549-docker-login-credentials-comment merge integration; compare component commits Two-parent integration of main into the same topic branch. — +5f850681bc5c fix(webui): lay out the Members import status card (#555) (#567) historical test name observed passing; inspect assertion and domain Members omits Retry after initial complete when audit recovery is healthy +f30e9f8f8ce4 fix(core): drop release-only unused mut in commit_after_lease_probe (#541) (#560) inspect patch; no added named test found — +87fe6cb17915 fix(docker): set a non-root USER in Dockerfile.webui (#559) inspect patch; no added named test found — +7e8d31366d6e fix(bot): hold on a refused guild-store schema instead of looping through the launcher (#531) (#538) historical test name observed passing; inspect assertion and domain guild_store_ahead_of_the_build_is_held_once_not_exited_for_a_launcher_restart +c3684688015d fix(db): name the store and versions when a guild store schema is refused (#531) (#535) historical test name observed passing; inspect assertion and domain existing_registration_does_not_relabel_unreadable_identity_as_schema_mismatch +f6c3070ea48b fix(security): resolve CodeQL hard-coded nonce and sanitization alerts (#534) existing regression modified in fix and observed passing; inspect domain replayed_nonce_is_rejected +d875191cfbc8 fix(db): read member cleanup candidates in a snapshot (#532) (#536) historical test name observed passing; inspect assertion and domain remote_cleanup_lookup_takes_the_writer_lock_only_to_queue_a_check +5815e65cbb05 fix(bot): warn about missing message content intent only for blank user messages (#537) historical test name observed passing; inspect assertion and domain empty_content_warning_skips_legitimately_empty_messages +71cc14ef47d2 fix(known-spam): ignore invisible characters inside scheme URLs (#526) existing bounded property inspected The historical matcher includes generated normalization and token-boundary cases in its own fixtures. known_spam_urls_preserve_safe_boundaries_inside_scheme_urls +193b322ad57b fix(known-spam): match emphasis-wrapped URLs after an invisible prefix (#525) existing bounded property inspected The historical matcher includes generated normalization and token-boundary cases in its own fixtures. known_spam_urls_match_emphasis_wrapped_invisible_prefixes +0b90a6fa4e68 fix(known-spam): keep rejecting invisible-only usernames before @host (#523) existing bounded property inspected The historical matcher includes generated normalization and token-boundary cases in its own fixtures. known_spam_bare_urls_reject_invisible_only_usernames +04be7d6bf0cc fix(frontend): nest emphasis in the live preview like Discord (#524) added or extended bounded property Across two markup pairs, four text samples and two code delimiters, nesting and node order match independently written HTML. Markdown preview keeps nested emphasis and literal code in their original order +32688efee5fa fix(frontend): index live-preview code spans once (#522) added or extended bounded property A marker inside an inline code span remains literal through nested emphasis and both supported single- and double-backtick fixtures. This covers rendered semantics. Markdown preview keeps nested emphasis and literal code in their original order +4c406d8ed6b3 fix(known-spam): match bare URLs after invisible prefixes (#511) existing bounded property inspected The historical matcher includes generated normalization and token-boundary cases in its own fixtures. known_spam_bare_urls_keep_utf8_boundaries_with_invisible_prefixes +980bb722a9b3 🤖 Fixer (jatmn's agent) Bound unmatched live-preview link scans (#519) historical test name observed passing; inspect assertion and domain Markdown preview preserves main output for valid and malformed syntax +7b94ec70c826 🤖 Fixer (jatmn's agent) Reapply invite descriptions after mixed-version writes (#516) existing bounded property inspected Legacy rule reads return the expected description after repeated old writes across marker states and scopes. invite_description_old_writer_reads_are_marker_gated_without_restart +9d6d53e4770b 🤖 Fixer (jatmn's agent) Keep the Automod title for CRLF guild templates (#517) historical test name absent from passing outputs; trace rename or retirement attachment_burst_guild_heading_crlf +20b1f54ede95 🤖 Fixer (jatmn's agent) Inherit global invite guidance for first guild overrides (#512) existing bounded property inspected First guild overrides agree on canonical inherited guidance across direct, enrolled and control saves. invite_description_first_override_inherits_global_on_stale_save +980b7d3b9bef 🤖 Fixer (jatmn's agent) Make log channels readable with pastel embeds (#487) existing bounded property inspected Every registered event type has the correct default accent, with no omitted registration. every_event_has_the_expected_accent +2608b270edc5 🤖 Fixer (jatmn's agent) Catch Unicode padding in Markdown spam links (#507) existing bounded property inspected The historical matcher includes generated normalization and token-boundary cases in its own fixtures. known_spam_urls_match_unicode_destination_padding +30831fdeab9a 🤖 Fixer (jatmn's agent) Preserve invite descriptions when copying rules (#509) existing bounded property inspected Cross-scope copies keep the expected destination description over old, current, custom and absent inputs. invite_description_copy_guards_old_text_using_target_row; invite_description_copy_without_marker_matches_save_semantics +0a551209f55d 🤖 Fixer (jatmn's agent) Preserve upgraded invite descriptions on stale saves (#494) existing bounded property inspected Stale saves preserve the applicable canonical description across save entry points and guild/global records. invite_description_stale_save_survives_upgrade_and_reopen; invite_description_stale_save_retains_post_upgrade_custom_guidance +fecd7e5d5afb 🤖 Fixer (jatmn's agent) Catch leading whitespace in Markdown spam links (#503) existing bounded property inspected The historical matcher includes generated normalization and token-boundary cases in its own fixtures. known_spam_urls_match_markdown_destinations_with_leading_whitespace +834a603c8b34 fix(known-spam): check adjacent Markdown destinations separately (#497) historical test name observed passing; inspect assertion and domain known_spam_urls_match_next_to_punctuation +3af9ed417be4 🤖 Fixer (jatmn's agent) Add a dedicated known-spam list (#484) historical test name observed passing; inspect assertion and domain known_spam_http_validates_lists_and_removes_with_captured_scopes +c575bfbe8cb0 🤖 Fixer (jatmn's agent) Harden built-in automod windows and invite fields (#489) historical test name observed passing; inspect assertion and domain builtin_legacy_windows_clamp_to_retained_history +ba1245fe43f1 fix(db): batch remote badword setup lookups and inserts (#482) (#486) historical test name observed passing; inspect assertion and domain maximal_badword_batch_commits_within_remote_transaction_lifetime +57a0699e7eb3 fix(webui): replace built-in automod JSON params with fields (#483) existing bounded property inspected An empty string, negative, fractional and unsafe integer field each produce zero save requests, while zero saves as a number. built-in numeric detection fields reject empty, negative and fractional values +35dbeecfeacb Fix Badwords setup with literal lists and connected rule controls (#480) historical test name observed passing; inspect assertion and domain badword_setup_saves_atomically_and_tests_saved_and_draft_lists +f5400d24051c fix(webui): bound Cases reads and cancel cold store opens (#479) historical test name observed passing; inspect assertion and domain case_list_deadline_includes_waiting_for_a_local_connection +f1b77756313a Fix read-only Bot actions lookups (#471) historical test name observed passing; inspect assertion and domain read_only_api_lists_bot_actions +3ac1cde4b244 fix(bot): check timed-ban expiry retries after other guilds (#461) (#462) historical test name observed passing; inspect assertion and domain timed_ban_expiry_retries_cannot_fill_every_poll +a2db215c85f8 🤖 Fixer (jatmn's agent): purge the WebUI Pull Zone after a managed publish; retire legacy Bunny publisher (#465) existing bounded property inspected Partial credential configurations and unacceptable zone identifiers cannot enable a purge. webui_purge_fails_closed_on_partial_configuration +80037158e682 fix(bot): finish timed-ban expiry follow-ups (#460) historical test name observed passing; inspect assertion and domain timed_ban_expiry_retry_delay_keeps_failing_guilds_from_starving_later_guilds +6746152c0851 fix(updater): name the guild schema in the outage refusal reason (#458) existing bounded property inspected Either direction of a guild schema mismatch refuses startup and records the guild-specific reason. A simultaneous core mismatch takes precedence. cold_start_outage_requires_matching_guild_schema +fb0a3cc621c1 feat(updates): alert the owner channel on boot repair version mismatch (#456) historical test name observed passing; inspect assertion and domain alerts_each_mismatch_once_and_again_after_versions_match +31b07ac4e88a fix(updater): route paired upgrades and owner recovery through the bot launcher (#455) historical test name observed passing; inspect assertion and domain paired_upgrade_needs_a_baked_api_that_routes_owner_recovery +197f56f8438e fix(bot): harden timed-ban expiry dispatch (#451) (#453) historical test name observed passing; inspect assertion and domain timed_ban_expiry_defers_until_live_membership_is_confirmed +a2062f50127f fix(updater): finish built-in startup schema and receipt follow-ups (#444) historical test name observed passing; inspect assertion and domain outage_diagnostic_recovers_after_post_spawn_write_failure +c0cf9154955d feat(bot): add timed bans with automatic expiry (#450) existing bounded property inspected Prefix and slash forms agree on duration and reason over valid arguments and rejected duration classes. timed_ban_prefix_and_slash_parse_the_same_duration_and_reason +0b222af4e005 feat(bot): add softban command (#446) historical test name observed passing; inspect assertion and domain softban_deletes_recent_messages_then_unbans_and_reports_failures +ea2a3af4b9ad fix(db): keep remote stream cleanup on its owning runtime (#447) existing bounded property inspected Prepared and direct transaction errors discard the stream and permit the next connection. remote_runtime_stream_errors_discard_transactions_and_allow_reconnect +dda9b64997bf fix(publish): report cleanup and registry deletion failures (#441) inspect patch; no added named test found — +e7c65a7b3f7d fix(updater): expose and replay boot mismatch diagnostics (#439) historical test name observed passing; inspect assertion and domain boot_mismatch_receipts_replay_after_handoff_and_reach_the_bot_writer +fcfac490a1d7 fix(bot): settle automod deletes and retry bounded log admission (#438) historical test name observed passing; inspect assertion and domain stalled_automod_delete_times_out_and_clears_its_mark +9d882a192152 fix(publish): recover interrupted tag promotions (#437) inspect patch; no added named test found — +0b58a65b4332 fix(updater): resolve deferred launcher selection and restore findings (#436) historical test name observed passing; inspect assertion and domain expired_installed_launcher_handoff_restores_only_the_recorded_release +2931c7b82cc7 fix(updater): address deferred signature verification findings (#433) historical test name observed passing; inspect assertion and domain prior_revisions_can_install_signature_payload_fix +9f1bbcf42f26 fix(updater): recover early installed startup outages (#435) historical test name observed passing; inspect assertion and domain cold_start_schema_refusal_considers_built_in_on_outage +91557710bcfb fix(updater): reject response-body resets as registry outages (#434) existing bounded property inspected A response that terminates early stays a body failure under both truncated-stream endings. registry_truncated_body_is_not_unreachable +648674f8129e fix(updater): refuse required verifier-era launcher hops (#432) historical test name observed passing; inspect assertion and domain required_verifier_launcher_is_blocked_before_the_verifier_era +08d83402848e fix(updater): recover applications during runtime registry outages (#431) historical test name observed passing; inspect assertion and domain runtime_outage_recovers_without_a_child_and_preserves_a_live_child +acd015f214ef fix(updater): re-read outage schemas immediately before spawn (#428) historical test name observed passing; inspect assertion and domain outage_spawn_rereads_core_and_guild_schemas +a17457d8c9fc fix(updater): handle registry request timeouts and server errors (#426) existing bounded property inspected All HTTP statuses from 100 through 599 classify consistently in string and supported typed forms. registry_status_classification +281772897f03 feat(bot): correlate bulk, overflow, and replay automod deletes (#414) existing bounded property inspected Three routing booleans crossed with five delivery outcomes obey the expected reporting rules. pending_bulk_automod_keeps_a_destination_for_every_route_and_outcome +cf90f36f0ab6 feat(bot): label automod deletes instead of a later plain delete (#382) existing regression modified in fix and observed passing; inspect domain log_mappings_are_membership_scoped_persistent_and_bounded_by_event_types +554843859ad8 feat(bot): optional reason DM on kick and ban (#381) historical test name observed passing; inspect assertion and domain kick_ban_slash_specs_include_optional_dm_flag +217aa7acf0e3 Userinfo case lines via bounded member case index (#383) existing bounded property inspected The three userinfo response paths suppress mention parsing for each enumerated mention type while the ordinary say command retains its existing behavior. userinfo_prefix_and_slash_replies_do_not_activate_mentions +2b46d16970ef feat(bot): report a member's cached voice channel (#385) existing bounded property inspected Running the migration twice preserves the expected custom command and shipped global rows without recreating removed legacy overrides. builtin_command_access_migration_drops_legacy_rows_and_is_idempotent +9363bed64085 feat(bot): note prior cases when a member rejoins (#384) historical test name observed passing; inspect assertion and domain rejoin_note_canceled_in_flight_allows_redelivery +e0db97f608f9 Sign release images (#379) existing regression modified in fix and observed passing; inspect domain published_schema_and_launcher_observations_allow_only_matching_services +fb0eb258b5a6 Refuse in-app database schema migrations (#380) historical test name observed passing; inspect assertion and domain update_control_refuses_higher_result_schema +e52351108a5c Time out the same attachment posted across channels (#378) historical test name observed passing; inspect assertion and domain late_create_after_delete_is_not_admitted +2d0ca3cccb4f fix(bot): hash exact-image bodies when the declared size is short (#377) historical test name observed passing; inspect assertion and domain concurrent_exact_streams_cannot_hash_against_the_same_spare_bytes +16f764ca5534 Fix update-check follow-ups for #370 (#372) historical test name observed passing; inspect assertion and domain scheduled_install_respects_active_lease_without_skip_set +b5222aa47a92 status: show why release check is unknown; record hourly digests and keep scheduled installs (#368) existing bounded property inspected Across the three release channels and four supported cadences, scheduled installs admit stable and nightly on daily, weekly or monthly schedules. scheduled_auto_install_allows_only_promoted_cadences +4ae771d73c5a fix(ci): bump webpki crates for RUSTSEC-2026-0381 through 0383 (#363) lockfile-only dependency repair Only the dependency lock changed. Repository supply-chain checks are the applicable gate. — +aa40dd758d79 fix(bot): commit member-sync pacing off the log-delivery future (#362) historical test name observed passing; inspect assertion and domain member_sync_rate_limit_persist_exit_reclaims_epoch_armed_during_handoff +a62ce5b2e432 fix(bot): notify member sync on global rate-limit waits; paused-clock 429 tests (#360) historical test name observed passing; inspect assertion and domain global_429_notifies_member_sync_and_retries_when_current +78b66d597fb9 Exact-image notice follow-ups from #355 review (#356) (#357) historical test name observed passing; inspect assertion and domain config_token_change_clears_an_incomplete_notice_reservation +a4de2a1ca948 fix(image-spam): name unfinished exact-image checks and keep stored hashes (#355) historical test name observed passing; inspect assertion and domain failed_job_with_none_hashes_does_not_clear_stored_some +a2a235a9d87c fix: retain ban events and reconcile durable audits without duplicates (#352) historical test name observed passing; inspect assertion and domain same_millisecond_peers_remain_ambiguous_after_apply_and_restart +7c8bae925161 fix(bot): save member-sync deadlines from the rate-limit hook (#351) added or extended bounded property Member-sync waits truncate to whole milliseconds and saturate at the signed deadline limit across additions around every sampled remaining budget. deadline_millis_clamps_to_i64 +8cab70a5be76 fix(ci): bump rustls to 0.23.46 and expire the h2 audit exception (#350) inspect patch; no added named test found — +34fe68b5c5ad fix(db): finish coverage-gap admission safeguards (#346) historical test name observed passing; inspect assertion and domain coverage_gap_restore_fence_after_admission_rolls_back_the_mark +4a2b108dcff1 fix(bot): preserve ban attribution across delayed and cancelled callbacks (#344) historical test name observed passing; inspect assertion and domain exact_audit_replaces_inferred_attribution_but_not_confirmed_facts +7790adb7d85e fix(launcher): restore token-hold health after readiness failure (#343) historical test name observed passing; inspect assertion and domain readiness_recovery_holds_token_exit_between_status_checks +ade813446916 fix(launcher): restore health when the bot exits during a stalled call (#337) historical test name observed passing; inspect assertion and domain running_bot_exit_during_stalled_tick_restores_health +ce87bf52aa96 fix(db): keep coverage-gap marks inside the remote write lifetime (#340) historical test name observed passing; inspect assertion and domain coverage_gap_mark_rolls_back_when_the_epoch_changes_before_commit +01f65c877ff1 fix(launcher): keep the rejected-token candidate across a restart during the hold (#338) historical test name observed passing; inspect assertion and domain rejected_token_marker_survives_launcher_restart_during_hold +435f5177d2bd fix(db): keep lease renewal independent of stalled reads (#336) historical test name observed passing; inspect assertion and domain prepared_snapshot_query_stops_inside_the_read_budget +e88495287a77 fix(bot): fence ban audits and preserve split attribution (#332) historical test name observed passing; inspect assertion and domain callback_starting_after_fence_sample_keeps_its_audit_pending +9698f4bcfcf5 fix(bot): preserve guild recovery generations after eviction (#333) existing bounded property inspected At every eviction through capacity the retained recovery floors stay bounded and old epochs cannot become current. reclaimed_guild_floors_stay_bounded_and_reject_stale_epochs +d64dd1d347a6 fix(db): release core before guild commits (#328) historical test name observed passing; inspect assertion and domain guild_commit_does_not_wait_for_the_core_writer +88020fc4c6c4 fix(api): finish typed authentication errors (#330) historical test name observed passing; inspect assertion and domain require_auth_session_failures_are_generic_and_retryable +406a81ac60f4 fix(logging): redact reported message and credential diagnostics (#327) existing bounded property inspected The bot and API configuration diagnostics preserve the error location while omitting the private sentinel from each tested invalid input. config_parse_errors_omit_source_and_values +93f5c9aff2d7 fix(api): respect shared refresh cooldown after session hold expires (#326) existing regression modified in fix and observed passing; inspect domain refresh_server_waits_are_capped_without_overflow +2e7fbc18371f fix(automod): skip exact-image actions when the digest was removed after admission (#324) historical test name observed passing; inspect assertion and domain known_bad_removal_during_member_lookup_skips_delete_and_ban +a8cc702d5120 fix(runtime): handle missing cgroup memory inputs without unsafe estimates (#314) added or extended bounded property Local v1/v2 files across absent, zero, numeric and sentinel limits, host ceilings and accounting sources. memory_reading_agrees_across_limit_and_stat_boundaries +f6e63aa2ba98 fix(bot): cap each lease CAS attempt so a hung stream can retry (#240) (#323) historical test name observed passing; inspect assertion and domain black_holed_first_renewal_retries_and_extends_the_stored_lease +41f953c24a34 fix(updater): reclaim launcher fence as soon as the authority window expires (#322) historical test name observed passing; inspect assertion and domain launcher_recovers_at_expiry_after_renewal_errors_and_resumes_cas +b7b64b6fb4ab fix(launcher): rebind health before database work on the poll tick (#234) (#321) historical test name observed passing; inspect assertion and domain exited_bot_serves_health_while_tick_database_is_stalled +53a55d3746da fix(updater): recreate a missing launcher_lease row on fence renewal (#231) (#319) historical test name observed passing; inspect assertion and domain launcher_cas_recovers_missing_row_then_resumes_cas +ad0e8b24e675 fix(bot): re-sync slash commands only for the edited server (#226) (#320) existing regression modified in fix and observed passing; inspect domain slash_http_saves_registration_and_failure_retries +28e23b05f43b perf(webui): cut Discord-backed request fan-out (#225) (#317) existing bounded property inspected Each tested case summary page uses one snapshot and a constant number of database calls for 0, 1 and 50 IDs. summary_pages_are_bounded_scoped_and_use_constant_database_calls +426367afb3e6 fix(bot): hold token rejection in-process under pre-revision-7 launchers (#245) (#313) existing bounded property inspected Launcher revision, absence and malformed values select the expected exit behavior around revision seven. auth_exit_requires_revision_seven_or_no_launcher +d128de2b4d6a fix(launcher): refresh /ready reason when a hold retry fails before start (#247) (#312) historical test name observed passing; inspect assertion and domain failed_auth_retry_tick_refreshes_ready_reason_before_control_error +cfad44d1dd83 fix(bot): skip slash command re-sync on unchanged command saves (#226) (#309) historical test name observed passing; inspect assertion and domain identical_command_saves_preserve_versions_across_concurrency_and_restart +58d3857f1622 fix(bot): lease renewal CAS only ever extends expiry (#237) (#310) historical test name observed passing; inspect assertion and domain lease_extend_only_local +39052719206c fix(recovery): map session store/flush errors to 5xx (#242) (#308) historical test name observed passing; inspect assertion and domain recovery_session_store_errors_are_generic_and_retryable +ec2c0525f1bc fix(bot): count guild-store cases on the stats card (#307) existing bounded property inspected Stats distinguish zero, positive and missing case counts with and without release information. stats_distinguishes_zero_cases_from_unavailable +c27c5fc49442 fix(lease): stop waiting on backoff at shutdown (#238) (#306) historical test name observed passing; inspect assertion and domain shutdown_interrupts_renewal_before_and_during_backoff +8a34d7c19596 fix(recovery): typed auth error in owner() (#241) (#305) historical test name observed passing; inspect assertion and domain recovery_routes_require_an_authenticated_owner +2815acfee819 Fix late manual ban audit identity for gateway deliveries (#300) added or extended bounded property For known audit IDs each prefix of a ban, replay and unban trace retains the distinct rows, events and correct active mirror. known_audit_deliveries_preserve_history_and_the_active_ban_after_every_prefix +72b4ee72c8e9 fix(ci): timed runner parity with cargo for excludes, signals and ignores (#301) historical test name absent from passing outputs; trace rename or retirement selected_package +7f973741c75e fix(ci): timed runner deadline and EXIT trap fixes (#253) (#296) inspect patch; no added named test found — +6fe405726818 ci: per-test cargo timeouts and timed runner scripts (#297) historical test name absent from passing outputs; trace rename or retirement ci_flag_scoped_runs +8a1cd9f033b6 fix(bot): remember permanent 403/404 Discord REST targets (#288) historical test name observed passing; inspect assertion and domain raced_channel_say_skips_after_permanent_channel_failure +f9db5f2545e0 fix(db,bot): distinct sub-60s manual gateway bans (#289) added or extended bounded property For known audit IDs each prefix of a ban, replay and unban trace retains the distinct rows, events and correct active mirror. known_audit_deliveries_preserve_history_and_the_active_ban_after_every_prefix +d03a740139f1 test(api): fix startup readiness flake under parallel tests (#290) historical test name observed passing; inspect assertion and domain guard_clears_readiness_on_scope_exit +13809d01bca5 fix(db,bot): record distinct manual bans when a stale mirror remains active (#279) historical test name observed passing; inspect assertion and domain dashboard_unban_echo_records_one_member_unban_with_dashboard_actor +7168d22b8e21 fix(launcher/bot): clear standby on ready and release lease on lost-lease exit (#283) historical test name observed passing; inspect assertion and domain lost_lease_exit_releases_row_so_replacement_can_claim_immediately +169201f13595 fix(db): batch member coverage-gap reconciliation writes (#281) historical test name observed passing; inspect assertion and domain coverage_gap_mark_batches_writes_for_remote_transport +deff0292c715 fix(deps): bump quinn-proto to resolve RustSec advisories (#270) (#278) lockfile-only dependency repair Only the dependency lock changed. Repository supply-chain checks are the applicable gate. — +e5713e90ec85 chore(ci): remove dead ci-agent-setup after GHA migration (#276) inspect patch; no added named test found — +8b5a60e360cd ci: replace Buildkite with affected GitHub Actions checks (#272) existing regression modified in fix and observed passing; inspect domain published_schema_and_launcher_observations_allow_only_matching_services +9ca58570c074 chore: adopt Apache 2.0 with Commons Clause (#269) inspect patch; no added named test found — +0a00735b67db fix(db): count copied rule batch payload once (#268) existing regression modified in fix and observed passing; inspect domain full_custom_rule_copy_batches_inserts_and_preserves_replacement +3b928580ecbd fix(webui): preserve save identity across delayed acknowledgements (#261) existing bounded property inspected Every tested failure stage leaves both saved rows and their version intact. atomic_global_rule_save_preserves_both_rows_on_fence_membership_or_commit_failure +234592fb4b05 fix(webui): refresh custom rule heading after rename (#266) historical test name observed passing; inspect assertion and domain custom rule rename updates the card heading after save without reloading +57a39e901b83 fix(db): export schema verification memo type (#267) inspect patch; no added named test found — +0224ce63d152 fix(bot): stop a slow container-use reply from outliving !stats (#264) historical test name observed passing; inspect assertion and domain closed_container_use_response_is_returned +3619977e4040 fix(bot): capture ban echoes without losing failure releases (#260) historical test name observed passing; inspect assertion and domain failed_dispatch_after_ban_capture_preserves_the_manual_record +d7e34a12d112 fix(api): cap concurrent connections on the private read listener (#263) historical test name observed passing; inspect assertion and domain container_read_listener_drops_connections_over_the_concurrency_limit +fb1edaef7ac5 fix(updater): clear stale queued selections that omit upgrade (#262) historical test name observed passing; inspect assertion and domain stale_schema_selections_without_upgrade_are_refused_once_after_migration +e09199ae81f1 fix(api): reserve the web listener before the private read bind (#259) existing regression modified in fix and observed passing; inspect domain api_process_waits_for_first_boot_with_overlapping_read_bind_without_a_bot_token +55cc8a509d6f fix(api): wait for first-boot SQLite database (#255) historical test name observed passing; inspect assertion and domain invalid_local_database_paths_and_contents_do_not_retry +400f7a6e2590 fix(api): preserve action-key errors across the control link (#256) historical test name observed passing; inspect assertion and domain action_key_errors_survive_the_bot_control_link +0a70379e944d fix: recover bans using immutable attempt tags (#257) previously mapped property A copied audit reason retains the selected immutable tag and respects the reason length. maximum_reason_keeps_identity_and_copied_prefixes_do_not_stack +c35f8f5584ba ci: Buildkite speedups (pinned dylint tools/libs, remote-database first, clippy before tests) (#250) inspect patch; no added named test found — +71bc393ba14f feat(automod): manage known-bad image hashes in WebUI (#211) historical test name observed passing; inspect assertion and domain known_bad_image_routes_require_current_page_and_live_permission +e4813fcfc3dd fix(bot): bound Discord retries on permanent errors (#227) existing bounded property inspected An unknown nickname read outcome increases delay across retries through budget exhaustion. unknown_nickname_read_failures_back_off_and_exhaust_the_budget +bd5c958ae4b3 fix(api): cache guild-list auth checks and drop dead Discord logins (#217, #224) (#232) added or extended bounded property 429 and every status from 500 through 599 retain the signed-in user and the running member-poll timer. transient Discord errors leave Members polling and sign-in state unchanged +278118ae72d4 fix(bot): renew the active-bot lease and launcher fence with one CAS request (#213, #214) (#230) historical test name observed passing; inspect assertion and domain slow_renewal_error_retries_through_the_activation_loop +f8c3c136107c fix(bot): renew the active-bot lease before slow startup work (#212) historical test name observed passing; inspect assertion and domain slow_startup_epoch_raise_keeps_the_lease_held_and_renewing +9530e73eab79 fix(updater): let the baked bot migrate an older database on first boot (#209) historical test name absent from passing outputs; trace rename or retirement baked_bot_migrates_queued_protocol3_core16_without_starting_api_early +6f825e038e40 fix(db): verify the guild identity row on memo hits (#197) (#201) historical test name observed passing; inspect assertion and domain identity_memo_rereads_store_row_and_rejects_swapped_identity +61f72ef4a8e8 feat(status): expose API container use over private read link (#198) historical test name observed passing; inspect assertion and domain public_web_router_returns_404_for_container_read +794fc509c9d2 feat(automod): add custom rules, scoping, and new rule types (#196) historical test name observed passing; inspect assertion and domain custom_pattern_and_word_rules +9dd8d90f3076 fix(bot): record one ban row and a manual moderation event (#195) added or extended bounded property For known audit IDs each prefix of a ban, replay and unban trace retains the distinct rows, events and correct active mirror. known_audit_deliveries_preserve_history_and_the_active_ban_after_every_prefix +6d7bf53a42e3 fix(updater): serve API reads while a launcher clear is pending (#194) historical test name observed passing; inspect assertion and domain api_role_serves_reads_while_a_superseded_launcher_clear_waits_for_the_writer +497f9af7be38 fix(db): cache guild-store identity checks (#197) historical test name observed passing; inspect assertion and domain identity_check_runs_once_and_again_after_reconnect_or_schema_change +6016be87a00c refactor(webui): use existing frameworks across both pages (#175) historical test name observed passing; inspect assertion and domain partial settings actions preserve dirty sibling fields in the same card +7a2d748e35f1 feat(bot): keep database writes on the bot process (#185) historical test name observed passing; inspect assertion and domain older_schema_stays_live_then_becomes_ready_without_exiting +41cbe776e29e fix(bot): bound oversized hash sets in automod notices (#184) existing bounded property inspected The rendered diagnostic's UTF-16 length stays within each of 15 budgets crossed with five hash counts and four tail lengths. automod_content_bound_stays_within_budget_across_sizes +3abda446aeea feat(bot): show container CPU and memory on status (#183) added or extended bounded property Working-set readings agree with usage minus inactive-file bytes across both cgroup layouts and the supported stat and limit boundaries. memory_reading_agrees_across_limit_and_stat_boundaries +a0b4fb1f1f2a feat(bot): log role, voice, nickname, username, and thread events (#182) existing bounded property inspected Every configured activity log event and default template belongs to the expected event category. activity_templates_cover_activity_events_without_joining_store_events +2b18db2a94f5 ci(pullfrog): pin checkout to v6 and document fixed authorPermission (#181) historical test name absent from passing outputs; trace rename or retirement fixed admin authorPermission stays coupled to the owner checks +384cbda1416b fix(bot): report exact-image matches instead of a budget notice (#177) historical test name observed passing; inspect assertion and domain proven_hashes_keep_a_match_reason_and_evidence_when_download_is_marked_failed +61c32851ec2b ci: align Pullfrog permissions and GPT Sol with reference (#176) historical test name absent from passing outputs; trace rename or retirement invisible Unicode instructions cannot authorize issue or PR commands +5983eb0d4877 fix: batch snapshot capture and shorten writer locks (#174) historical test name observed passing; inspect assertion and domain pressure_split_rechecks_deletions_before_each_admission +0226a0cbae3e fix(db): reduce guild-store hot query load (#173) existing bounded property inspected Query-plan assertions cover event type and user filters both present and absent and require a constrained user lookup when the user filter is present. status_dashboard_and_pages_use_bounded_index_searches +faac12981983 fix: show unavailable when status release reads fail (#172) historical test name observed passing; inspect assertion and domain stats_release_read_failure_is_unavailable +c5e205b9b0da fix: unify compact durations across Discord notices (#171) added or extended bounded property Both formatters preserve seconds and every intermediate unit around unit transitions through u64::MAX. compact_duration_recovers_seconds_and_keeps_all_intermediate_units +54b86723ee68 fix(startup): separate readiness from liveness and stop API startup writes historical test name observed passing; inspect assertion and domain api_startup_opens_no_write_transaction +3b0a8bafba13 fix: honor configured logging level and omit message author IDs (#163) historical test name observed passing; inspect assertion and domain message_diagnostics_respect_configured_level +8374a2c7719b fix(bot): cut member_sync idle database load (#150) historical test name observed passing; inspect assertion and domain idle_scan_waits_for_the_saved_attempt_instead_of_a_two_second_tick +877c0bcc52b1 fix(api): release the database lock when a write times out (#149) historical test name observed passing; inspect assertion and domain api_deadline_mid_write_releases_the_lock_for_the_next_writer +248d663a3224 fix(moderation): ban even when the database marker save fails (#148) historical test name observed passing; inspect assertion and domain failed_marker_save_still_bans_and_repairs_the_directory +9c8043e3c6b3 fix(db,api): stop web reads from taking the write lock (#147) historical test name observed passing; inspect assertion and domain api_remote_deadline_stays_inside_the_browser_abort +4dc472f084aa fix(db,api): follow up startup and rate-limit fixes (#146) historical test name observed passing; inspect assertion and domain spent_guild_bucket_does_not_request_the_next_page +1b0d9dfc81a8 fix(api): stop guild checks from hammering Discord's rate limit (#145) added or extended bounded property Durable retry records retain allowed scope IDs of lengths 1 through 20 and positive signed deadlines. deadlines_round_trip_through_meta_and_ignore_junk +8615c8ecd73d fix(updater): clear stored launcher selection with no capability contract (#144) historical test name observed passing; inspect assertion and domain stored_launcher_without_contract_is_cleared_once +e3f69efbc77b fix(db): stop startup seed from holding a remote transaction open (#143) historical test name observed passing; inspect assertion and domain exhausted_budget_waits_for_reset +e3792f26df62 fix(updater): install required launchers before applications (#139) historical test name observed passing; inspect assertion and domain independent_spawn_failure_settles_once +c6fd7f6ab751 fix(updater): coordinate bot/API schema upgrades and recovery (#138) historical test name observed passing; inspect assertion and domain future_schema_recovery_requires_owner_origin_and_explicit_pair_confirmation +d44b3a28257b [Members 18/20] Expose authorized Members API and dashboard (#134) historical test name observed passing; inspect assertion and domain member_sync_controls_require_an_existing_job_and_missing_job_receipt_fails +947583e6a404 [Members 17/20] Activate the durable fair member import worker (#133) historical test name observed passing; inspect assertion and domain committed_unknown_departure_keeps_leave_duration_unavailable +f80b25a0e18c [Members 09/20] Test observation ordering and targeted member verification (#125) historical test name observed passing; inspect assertion and domain no_row_remove_fences_inflight_page_and_old_join_cannot_reappear +2e62f957660b [Members 02/20] Stage member directory types and status projection (#118) inspect patch; no added named test found — +4208c493c948 [Members 01/20] Durable request pacing and backup compatibility (#117) historical test name observed passing; inspect assertion and domain pacing_survives_reopen_and_provider_extension +bddb98f3132d fix(ci): scope PR checks and main image rebuilds to affected components (#114) inspect patch; no added named test found — +08b217ec2823 fix(deps): update h2 0.4 to patched release (#115) lockfile-only dependency repair Only the dependency lock changed. Repository supply-chain checks are the applicable gate. — +75a55dfa67e6 ci: run pinned Dylint general lints on Rust diffs (#112) inspect patch; no added named test found — +e8d8415ed7d8 feat: retain message snapshots and expose owner database usage (#103) historical test name observed passing; inspect assertion and domain database_usage_routes_reject_anonymous_requests_with_private_headers +4fb8bdcf725a test: exercise bot and API config sync across OS processes (#106) historical test name absent from passing outputs; trace rename or retirement smoke_bot_and_api_executables_share_sqlite +2ae6775ede90 fix: return Discord guild-list rate limits as temporary errors (#102) added or extended bounded property All 64 header/body presence and duration combinations honor the longer wait with a one-second floor. Invalid and out-of-range values retain their separate boundary checks. discord_retry_after_honors_header_and_json_seconds +8d4e1b840410 fix(webui): overhaul Administration updates layout and status (#105) historical test name absent from passing outputs; trace rename or retirement check applies its returned snapshot and reports failures without leaving enabled stale controls +59eab6d55ec8 docs: define test quality and regression evidence guidance (#104) documentation-only change Only Markdown changed in this commit. — +aa6098fda8ad fix: reset idle remote database streams before pool reuse (#99) historical test name observed passing; inspect assertion and domain idle_remote_cursor_baton_is_reset_before_async_pool_reuse +b44e4919009d fix(ci): skip conductor for manual SHA publication (#97) inspect patch; no added named test found — +d3a57b08929c fix(ci): report owner-triggered Pullfrog PR checks (#98) historical test name absent from passing outputs; trace rename or retirement supplies native PR check context and preserves issue-only commands +6503bec9f593 Add independent Bunny component updates (#95) historical test name observed passing; inspect assertion and domain update_routes_reject_anonymous_requests_without_disclosing_state +257ce7643245 Fix Automod dry-run controls for dedicated spam rules (#91) historical test name observed passing; inspect assertion and domain rule_command_keeps_the_rule_id_for_prefix_and_slash_order +dde4f3cbbe1b Improve WebUI control contrast in light and dark themes (#90) historical test name absent from passing outputs; trace rename or retirement ${theme} controls have a visible boundary on their surfaces +4a40b0c616c1 Fix moderation workspace layout and editor usability (#88) added or extended bounded property All four enabled/dry-run flag combinations keep the semantic rule badge, scope and override tags consistent and the rule heading unchanged. rule badges separate status from heading and preserve distinct semantic variants +3d11c6d47886 Fix missing member leave and ban log details (#87) existing bounded property inspected Both ban and unban report fixtures render the audit context and apply their configured actor filters. member_reports_render_audit_context_and_apply_actor_filters +fb9fb1bdb387 Fix duplicate edit logs and add per-event ID ignores (#84) historical test name observed passing; inspect assertion and domain per_event_log_ignores_are_saved_in_the_authorized_guild_bundle +b8a3f39fd476 Fix WebUI control alignment across pages and dialogs (#83) existing regression modified in fix and observed passing; inspect domain image rule UI can save test mode or delete-and-ban +52e7bdfd0724 Fix WebUI save-state reconciliation (#81) historical test name observed passing; inspect assertion and domain queued log-channel saves clear dirty state and survive in-app navigation +b0b3cb90672c Recover stuck queued actions so log channels can be updated (#79) historical test name observed passing; inspect assertion and domain claimed_work_and_stuck_log_channels_can_be_cancelled_for_recovery +8ed8bc0df8c4 fix(bot): skip redundant !say confirmation in the invoking channel (#77) historical test name observed passing; inspect assertion and domain say_without_mention_targets_invocation_channel +4ce9bac0e3da Speed up WebUI saves and repair log-channel actions (#78) historical test name observed passing; inspect assertion and domain discord_timestamp_precision_skew_keeps_current_membership_valid +a24662397f53 Remove leftover Python install and private-ops frontend lock (#69) historical test name absent from passing outputs; trace rename or retirement publish accepts Storage receipt without requires_api field +210c479873f1 fix: unblock Dependabot version-update cycles on this private repo (#70) inspect patch; no added named test found — +37dcea4ea472 ci: wrap Buildkite preflight in optional local git hooks (#68) inspect patch; no added named test found — +1b212931d67e feat(bot): associate Discord audit entries with bot-owned cases (#65) historical test name observed passing; inspect assertion and domain queued_unban_links_a_bot_audit_without_subject_search +3e2f1dc0ba2a feat(bot): capture proving Discord attachments into evidence (#64) historical test name observed passing; inspect assertion and domain re_fetch_digest_must_match_proving_hash +f2427a8aaf2d feat(conductor): add public install validation and operator docs (#63) historical test name absent from passing outputs; trace rename or retirement local_plan_accepts_loopback_sqlite +2a3162e19423 feat(conductor): install selected releases and roll them back (#62) historical test name absent from passing outputs; trace rename or retirement update_root_must_not_overlap_backup_root +a5228711adc5 feat(conductor): discover signed Stable and Nightly releases (#61) historical test name absent from passing outputs; trace rename or retirement release_feed_and_keys_are_validated +0abfaf659919 feat(conductor): move enrolled guilds between shared and dedicated stores (#60) historical test name observed passing; inspect assertion and domain move_fence_reports_its_own_pre_dispatch_outcome +c37b056e15b6 feat(conductor): add local encrypted backup and restore (#59) historical test name observed passing; inspect assertion and domain restore_fence_blocks_primary_writes +b0e6ffbd1bb9 feat(conductor): add owner administration and permission preview (#58) historical test name observed passing; inspect assertion and domain owner_preview_cannot_write_and_does_not_inherit_owner_authority +90957aad67b9 feat(bot): complete exact-image and repeated-text spam enforcement (#57) historical test name observed passing; inspect assertion and domain unchanged_files_do_not_refresh_and_changed_files_replace +c80e6525f42e feat(tenant): route live guild stores, cases and erasure (#56) existing bounded property inspected The timeout, kick and ban plan fixtures each preserve the actor and original membership across successful and uncertain outcomes. selected_plan_results_keep_actor_outcome_and_original_membership +f43ba88290c8 feat(bot): add bounded exact-image spam test mode (#55) existing bounded property inspected For every triple of four-bit image sets the detector agrees with the independent common-intersection oracle. matcher_agrees_with_small_exhaustive_common_intersection_oracle +37289855dc21 Move CI and image publishing entirely to Buildkite (#36) inspect patch; no added named test found — +ea1515fa20a5 feat(bot): observe guild memberships with bounded repair (#34) historical test name observed passing; inspect assertion and domain membership_repair_config_is_bot_only_and_bounded +1e6e394cf538 feat(db): add inactive durable action queue storage (#33) existing bounded property inspected Bounded history pruning removes eligible completed actions and retains the tested unresolved states and recent completions. pruning_is_bounded_preserves_unresolved_and_uses_completion_age +f132217faffd feat: report routine Discord activity without SQL history (#29) historical test name observed passing; inspect assertion and domain dashboard moderation counts stay with their requested server +308e8854d2b3 Fix Buildkite cargo fetch over SSH for private git crates. (#20) retired pipeline Buildkite SSH fetch configuration, removed after migration to GitHub Actions. — +7e45847f6b06 Add remote libSQL backend with first-class Bunny support (#5) added or extended bounded property Nested IDs written to and read from the event store preserve exact numeric identity on both sides of the JS safe-integer boundary. Top-level user IDs always serialize as strings. insert_event_query_events_roundtrips_data_snowflakes_as_strings +e3d76ff41ae2 Fix split runtime review findings existing regression modified in fix and observed passing; inspect domain smoke_dual_process_config_sync +f69a47b70273 Fix setup binary paths documentation-only change Only Markdown changed in this commit. — +c73e67902937 Fix WebUI configuration contracts historical test name observed passing; inspect assertion and domain rejects_wildcard_credentialed_cors_origin +67eab8c2152f Fix targeted plan safety and slash retries historical test name observed passing; inspect assertion and domain reply_only_plan_has_no_user_option +175c8502ad4f Fix custom plan targeting and WebUI persistence historical test name observed passing; inspect assertion and domain only_moderation_steps_require_a_target +e6234f9c141a Harden durable configuration and WebUI contracts previously mapped property Nested audit JSON preserves exact integer identity across the JS precision boundary. wire_event_integers_preserve_the_exact_value_at_every_bit_boundary diff --git a/migrations/guild/0025_subject_case_dates.sql b/migrations/guild/0025_subject_case_dates.sql new file mode 100644 index 000000000..7876a78db --- /dev/null +++ b/migrations/guild/0025_subject_case_dates.sql @@ -0,0 +1,3 @@ +-- Guild schema 26. Scope a chronological case page to one subject before seeking. +CREATE INDEX guild_cases_subject_date + ON guild_cases(guild_id,enrollment_id,list_subject,list_date,case_id) WHERE deleted=0; diff --git a/migrations/guild/current_version.txt b/migrations/guild/current_version.txt index 7273c0fa8..6f4247a62 100644 --- a/migrations/guild/current_version.txt +++ b/migrations/guild/current_version.txt @@ -1 +1 @@ -25 +26 diff --git a/scripts/frontend-state-test.mjs b/scripts/frontend-state-test.mjs index 70d1d76cf..1cb2621e3 100644 --- a/scripts/frontend-state-test.mjs +++ b/scripts/frontend-state-test.mjs @@ -765,10 +765,13 @@ test('the ban dialog finds current members by name and says when the search fail search = () => response({ members: [], next_cursor: null, total: null }); await type('nobody'); assert.equal(results(), 'No matching members.'); - search = () => ({ ok: false, status: 503, headers: { get: () => null }, text: async () => JSON.stringify({ error: 'Members request timed out. Please try again.' }) }); - await type('jatm'); - assert.equal(results(), "Couldn't search members: Members request timed out. Please try again. Paste their ID instead."); - assert.equal(dialog.querySelector('ul.picker-results [role="alert"]') !== null, true); + for (const status of [500, 502, 503, 504]) { + const message = `Members request failed (${status}). Please try again.`; + search = () => ({ ok: false, status, headers: { get: () => null }, text: async () => JSON.stringify({ error: message }) }); + await type(`member ${status}`); + assert.equal(results(), `Couldn't search members: ${message} Paste their ID instead.`); + assert.ok(dialog.querySelector('ul.picker-results [role="alert"]')); + } search = () => { throw new TypeError('Failed to fetch'); }; await type('offline'); assert.equal(results(), "Couldn't search members: Failed to fetch. Paste their ID instead."); @@ -1604,15 +1607,26 @@ test('analytics distinguishes missing daily data from observed zeros and single assert.deepEqual([...panel.querySelectorAll('.an-panel .an-empty')].map((n) => n.textContent), ['No automod enforcement in this range.', 'No mod actions in this range.', 'No attributed mod actions in this range.']); assert.match(panel.querySelector('#an-heatmap-readout').textContent, /No enforcement actions in this range\./); - const single = harness(async () => response(analyticsSummary(30, { series: analyticsDays(1, () => ({ warns: 2, joins: 1 })) }))); - single.app.state.config = ANALYTICS_CONFIG; - const one = single.app.tabAnalytics(); - await settle(); - const membership = one.querySelectorAll('svg[role="img"]')[1]; - assert.equal(membership.querySelector('polyline'), null, 'one day draws a point, not a line'); - assert.equal(membership.querySelectorAll('circle').length, 1); - assert.equal(one.querySelectorAll('svg[role="img"]')[0].querySelectorAll('.an-bar').length, 1); - assert.doesNotMatch(one.innerHTML, /NaN|Infinity|undefined/); + for (const days of [1, 2, 6, 7, 29, 30]) { + const h = harness(async () => response(analyticsSummary(30, { + series: analyticsDays(days, (i) => i % 2 === 0 ? { warns: 2, joins: 1 } : {}), + }))); + h.app.state.config = ANALYTICS_CONFIG; + const trend = h.app.tabAnalytics(); + await settle(); + const [enforcement, membership] = trend.querySelectorAll('svg[role="img"]'); + for (const chart of [enforcement, membership]) { + assert.equal(chart.querySelectorAll('.an-hit').length, days); + } + assert.equal(enforcement.querySelectorAll('.an-bar').length, Math.ceil(days / 2)); + if (days === 1) { + assert.equal(membership.querySelector('polyline'), null); + assert.equal(membership.querySelectorAll('circle').length, 1); + } else { + assert.ok(membership.querySelector('polyline')); + } + assert.doesNotMatch(trend.innerHTML, /NaN|Infinity|undefined/); + } }); test('analytics formats very large numbers compactly and keeps exact values in labels', () => { @@ -6406,7 +6420,7 @@ for (const { defaultFontSize, heatmapOnly, resourceOnly, widths } of [ { defaultFontSize: 24, heatmapOnly: true, widths: [360, 320, 390, 480, 1280] }, { defaultFontSize: 32, widths: [1280, 320] }, { defaultFontSize: 48, heatmapOnly: true, widths: [1280, 320] }, - { defaultFontSize: 64, resourceOnly: true, widths: [308, 320, 418, 419] }, + { defaultFontSize: 64, resourceOnly: true, widths: [308, 319, 320, 321, 417, 418, 419, 420] }, ]) test(`${heatmapOnly ? 'heatmap cells and labels' : 'chart plots and labels'} fit with a ${defaultFontSize}px browser default font`, { timeout: 120000 }, async t => { if (!firefoxBinary || !fs.existsSync(new URL('../dist/frontend/app.js', import.meta.url))) { assert.ok(!process.env.CI, 'CI requires Firefox and the built WebUI'); @@ -7329,6 +7343,20 @@ test('Markdown preview preserves main output for valid and malformed syntax', () } }); +test('Markdown preview keeps nested emphasis and literal code in their original order', () => { + const parser = previewParser(); + for (const [outer, inner, innerTag] of [['*', '**', 'strong'], ['_', '__', 'u']]) { + for (const word of ['one', 'two words', 'café', '東京']) { + for (const ticks of ['`', '``']) { + const code = ticks + outer + ticks; + const input = outer + 'a ' + inner + word + inner + ' ' + code + ' z' + outer; + const html = renderToStaticMarkup(React.createElement(React.Fragment, null, parser.plain(input))); + assert.equal(html, `
a <${innerTag}>${word} ${outer} z
`, input); + } + } + } +}); + test('Markdown preview preserves the complete long template on edit and save', async () => { let stored = '['.repeat(64000), saved; const config = () => ({enrollment_id: 'original', templates: [{event: 'automod', effective: stored}]}); @@ -7677,14 +7705,17 @@ test('unauthenticated log-channel mutation returns to login', async () => { test('rule badges separate status from heading and preserve distinct semantic variants', () => { const { app } = harness(); - for (const [enabled, dry_run, variant] of [[true, false, 'rule-badge-on'], [true, true, 'rule-badge-dry'], [false, false, 'rule-badge-off']]) { - const card = app.ruleCard({ name: 'Mention spam', rule_id: 'mention_spam', global: {}, guild_override: {}, effective: { enabled, dry_run } }); - assert.equal(textOf(findNode(card, n => n.localName === 'h3')), 'Mention spam'); - const badge = findNode(card, n => String(n.className).split(/\s+/).includes(variant)); - assert.ok(badge, variant); - assert.equal(badge.getAttribute('data-variant'), 'outline'); - assert.ok(findNode(card, n => String(n.className).split(/\s+/).includes('scope-tag'))); - assert.ok(findNode(card, n => String(n.className).split(/\s+/).includes('override-tag'))); + for (const enabled of [false, true]) { + for (const dry_run of [false, true]) { + const variant = enabled ? (dry_run ? 'rule-badge-dry' : 'rule-badge-on') : 'rule-badge-off'; + const card = app.ruleCard({ name: 'Mention spam', rule_id: 'mention_spam', global: {}, guild_override: {}, effective: { enabled, dry_run } }); + assert.equal(textOf(findNode(card, n => n.localName === 'h3')), 'Mention spam'); + const badge = findNode(card, n => String(n.className).split(/\s+/).includes(variant)); + assert.ok(badge, variant); + assert.equal(badge.getAttribute('data-variant'), 'outline'); + assert.ok(findNode(card, n => String(n.className).split(/\s+/).includes('scope-tag'))); + assert.ok(findNode(card, n => String(n.className).split(/\s+/).includes('override-tag'))); + } } }); @@ -9471,6 +9502,22 @@ test('No links or media reports removed channels and uses the saved disabled sta assert.equal(h.toast().textContent, 'Rule saved. Removed 1 unavailable channel. The rule is now off.'); }); +test('a request reference in an ordinary API error preserves the session', () => { + const h = harness(); + const me = { id: "42", owner: true }; + h.app.state.me = me; + const references = ['401', '(401)', 'req-401/ref', 'ref 401 retry']; + for (let at = 0; at <= 5; at++) { + references.push('abcde'.slice(0, at) + '401' + 'abcde'.slice(at)); + } + for (const status of [400, 403, 404, 409, 429, 500, 503]) { + for (const reference of references) { + assert.equal(h.app.handleAuthLoss({ status, message: `Request ${reference} is unavailable` }), false, `${status}: ${reference}`); + assert.equal(h.app.state.me, me); + } + } +}); + for (const failure of [ { status: 401, error: 'authorization expired' }, { status: 400, error: 'authorization expired', code: 'auth_lost' }, @@ -9505,11 +9552,11 @@ test('transient Discord errors leave Members polling and sign-in state unchanged h.app.state.config = { enrollment_id: 'member-enrollment' }; h.app.tabMembers(); await settle(); - for (const status of [429, 503]) { + for (const status of [429, ...Array.from({ length: 100 }, (_, offset) => 500 + offset)]) { assert.equal(h.app.handleAuthLoss(Object.assign(new Error('temporary failure'), { status })), false); + assert.ok([...h.timers.values()].some(timer => timer.delay === 10000), String(status)); + assert.ok(h.app.state.me, String(status)); } - assert.ok([...h.timers.values()].some(timer => timer.delay === 10000)); - assert.ok(h.app.state.me); }); // Known-bad images: the list search (shown once it has items), then the add form's hash and note. @@ -16929,13 +16976,26 @@ test('Bot Resources renders scoped CDN usage and includes its estimates in curre test('Bot Resources rounds combined memory up from bytes, including zero and block boundaries', async () => { const mib = 2 ** 20; - for (const [botBytes, apiBytes, blocks, capacity, headroom] of [ + const cases = [ [0, 0, 1, '64', '64'], [40 * mib, 24 * mib, 1, '64', '0'], [40 * mib, 24 * mib + 1, 2, '128', '63.99'], [50 * mib, 60 * mib, 2, '128', '18'], [1024 ** 4, 1, 16385, '1,048,640', '63.99'], - ]) { + ]; + // On each side of an exact block, the displayed capacity depends only on + // the combined byte count, regardless of which process owns the last byte. + for (const boundary of [1, 2, 7, 16]) { + for (const delta of [-1, 0, 1]) { + const total = boundary * 64 * mib + delta; + const blocks = boundary + Number(delta > 0); + const headroom = delta < 0 ? '<0.01' : delta > 0 ? '63.99' : '0'; + for (const bot of [0, Math.floor(total / 2), total]) { + cases.push([bot, total - bot, blocks, (blocks * 64).toLocaleString('en-US'), headroom]); + } + } + } + for (const [botBytes, apiBytes, blocks, capacity, headroom] of cases) { const snapshot = resourceSnapshot({ bot: { current: resourceCurrent({ memory: { program_bytes: botBytes } }) }, api: { current: resourceCurrent({ memory: { program_bytes: apiBytes } }) }, diff --git a/scripts/publish-image-test.sh b/scripts/publish-image-test.sh index 7b3687559..6a192490b 100755 --- a/scripts/publish-image-test.sh +++ b/scripts/publish-image-test.sh @@ -223,16 +223,23 @@ grep -Fq 'docker "$@" || publish_fail "docker failed: $*"' "$root/scripts/publis sleep() { printf 'sleep %s\n' "$1" >>"$push_trace"; } build_fails=0 - push_failures=1 - run_docker "${push[@]}" 2>"$TEST_SIGNING_DIR/push-output" - assert_eq "$(<"$push_trace")" $'build\npush\nsleep 5\npush' - assert_eq "$(<"$push_metadata")" complete - grep -Fxq "$push_error" "$TEST_SIGNING_DIR/push-output" || fail 'failed attempt must retain its registry diagnostic' - - push_failures=3 - : >"$push_trace" - if (run_docker "${push[@]}") >/dev/null 2>&1; then fail 'persistent registry errors must fail'; fi - assert_eq "$(<"$push_trace")" $'build\npush\nsleep 5\npush\nsleep 10\npush' + expected_traces=($'build\npush' $'build\npush\nsleep 5\npush' $'build\npush\nsleep 5\npush\nsleep 10\npush') + for push_failures in 0 1 2 3 4; do + : >"$push_trace" + status=0 + (run_docker "${push[@]}") 2>"$TEST_SIGNING_DIR/push-output" || status=$? + if (( push_failures < 3 )); then + assert_eq "$status" 0 + assert_eq "$(<"$push_metadata")" complete + else + [[ "$status" != 0 ]] || fail 'persistent registry errors must fail' + fi + expected_index=$((push_failures < 2 ? push_failures : 2)) + assert_eq "$(<"$push_trace")" "${expected_traces[expected_index]}" + if (( push_failures > 0 )); then + grep -Fxq "$push_error" "$TEST_SIGNING_DIR/push-output" || fail 'failed attempt must retain its registry diagnostic' + fi + done build_fails=1 push_failures=0 @@ -421,7 +428,7 @@ grep_array webui_cache_args -q ':buildcache' \ && fail 'webui must not use :buildcache' # Migration origins are distinct from exact application runtime ranges. -for field in update-control=3 upgrade-min-core=23 upgrade-min-guild=17 guild-schema=25; do +for field in update-control=3 upgrade-min-core=23 upgrade-min-guild=17 guild-schema=26; do contains_arg "io.jmodguard.${field}" "${schema_args[@]}" || fail "missing coordinated metadata ${field}" done diff --git a/src/ban_reason.rs b/src/ban_reason.rs index ab5a898a7..b2b541a9b 100644 --- a/src/ban_reason.rs +++ b/src/ban_reason.rs @@ -65,11 +65,10 @@ pub fn without_tag(mut reason: &str) -> &str { pub fn discord_reason(reason: &str, tag: Option<&BanAttemptTag>) -> String { let reason = without_tag(reason); - let tagged = match tag { - Some(tag) => format!("[jmg:{}] {reason}", tag.as_str()), - None => reason.to_owned(), - }; - tagged.chars().take(512).collect() + let mut tagged = tag.map_or_else(String::new, |tag| format!("[jmg:{}] ", tag.as_str())); + // The generated prefix is ASCII, so its byte length is also its character count. + tagged.extend(reason.chars().take(512 - tagged.len())); + tagged } #[cfg(test)] @@ -80,13 +79,23 @@ mod tests { fn maximum_reason_keeps_identity_and_copied_prefixes_do_not_stack() { let tag = BanAttemptTag::new(); let other = BanAttemptTag::new(); - let text = "💬".repeat(512); - let sent = discord_reason(&text, Some(&tag)); - assert_eq!(sent.chars().count(), 512); - assert_eq!(attempt_tag(&sent), Some(tag.as_str())); - assert_eq!(without_tag(&sent), "💬".repeat(485)); - let copied = format!("[jmg:{}] {sent}", other.as_str()); - assert_eq!(discord_reason(&copied, Some(&tag)), sent); + for width in [0, 1, 484, 485, 486, 511, 512, 513, 2048] { + for symbol in ["x", "é", "💬"] { + let text = symbol.repeat(width); + let sent = discord_reason(&text, Some(&tag)); + assert_eq!(attempt_tag(&sent), Some(tag.as_str())); + assert_eq!(without_tag(&sent), symbol.repeat(width.min(485))); + assert_eq!(discord_reason(&sent, None), without_tag(&sent)); + assert_eq!(discord_reason(&text, None), symbol.repeat(width.min(512))); + for depth in 0..=4 { + let copied = format!( + "{}{sent}", + format!("[jmg:{}] ", other.as_str()).repeat(depth) + ); + assert_eq!(discord_reason(&copied, Some(&tag)), sent); + } + } + } assert_eq!( without_tag("[jmg:not-an-attempt] reason"), "[jmg:not-an-attempt] reason" diff --git a/src/db.rs b/src/db.rs index 441be9ccd..0c5cf057c 100644 --- a/src/db.rs +++ b/src/db.rs @@ -983,6 +983,7 @@ impl ConnectionLease { connection } }; + connection.local_file = !pool.remote; if pool.remote { // Successful autocommit reads can leave an Hrana cursor baton on // this connection. Never carry that potentially expired server diff --git a/src/db/guild_data.rs b/src/db/guild_data.rs index 747b5cf77..72a46462b 100644 --- a/src/db/guild_data.rs +++ b/src/db/guild_data.rs @@ -26,6 +26,23 @@ const ONBOARDING_TRAP_SCHEMA: &str = include_str!("../../migrations/guild/0023_onboarding_trap.sql"); const DELETION_REQUESTS_SCHEMA: &str = include_str!("../../migrations/guild/0024_deletion_requests.sql"); +const SUBJECT_CASE_DATES_SCHEMA: &str = + include_str!("../../migrations/guild/0025_subject_case_dates.sql"); +// Start the snapshot at the consumer's call site so primary-statement metrics +// keep the operation's file and line when the membership check is shared. +macro_rules! read_active_scope { + ($store:expr, $scope:expr, $read:expr) => {{ + let scope = $scope; + $store.check_target(&scope.placement)?; + let expected = $store.expected.clone(); + $store.db.with_conn(move |conn| { + let _runtime = conn.enter_local_read_worker(); + let tx = conn.transaction_primary_snapshot()?; + GuildDataStore::read_active_scope(tx, &expected, &scope, $read) + }) + }}; +} + mod bunny_transfer; #[cfg(any(test, feature = "test-support"))] mod historical_schema; @@ -421,6 +438,7 @@ fn verify_identity_version( "trigger", "guild_deletion_request_insert guild_deletion_request_update guild_erasure_grant_insert", ), + (26, "index", "guild_cases_subject_date"), ]; let missing = |kind: &str, name: &str| { StoreCheckError::Schema(format!( @@ -612,6 +630,19 @@ fn initialize_store( if version < 25 { tx.execute_batch_bounded(DELETION_REQUESTS_SCHEMA, 1024 * 1024)?; } + if version < 26 { + // One scoped index entry per live case. Use the same per-entry + // allowance as the version 21 indexes, including B-tree overhead. + let live_cases: i64 = tx.query_row( + "SELECT COUNT(*) FROM guild_cases WHERE deleted=0", + (), + |row| Ok(row.get(0)?), + )?; + let index_bound = (live_cases as u64) + .saturating_mul(256) + .saturating_add(1024 * 1024); + tx.execute_batch_bounded(SUBJECT_CASE_DATES_SCHEMA, index_bound)?; + } tx.pragma_update(None, "user_version", VERSION)?; verify_identity(&tx, expected)?; return tx.commit(); @@ -630,6 +661,7 @@ fn initialize_store( tx.execute_batch_bounded(MEMBER_NAME_SCHEMA, 1024 * 1024)?; tx.execute_batch_bounded(ONBOARDING_TRAP_SCHEMA, 1024 * 1024)?; tx.execute_batch_bounded(DELETION_REQUESTS_SCHEMA, 1024 * 1024)?; + tx.execute_batch_bounded(SUBJECT_CASE_DATES_SCHEMA, 1024 * 1024)?; tx.ensure_mutation_receipt()?; tx.execute_rows( "INSERT INTO store_identity(singleton,schema_family,store_id,dedicated_guild_id) VALUES(1,?1,?2,?3)", @@ -652,6 +684,19 @@ fn initialize_store( } impl GuildDataStore { + /// Run a read against the same primary snapshot that verified the active membership. + fn read_active_scope( + tx: crate::db_compat::Transaction, + expected: &StoreRegistration, + scope: &GuildDataScope, + read: impl FnOnce(&crate::db_compat::Transaction, &GuildDataScope) -> Result, + ) -> Result { + tenant_logs::verify_scope(&tx, expected, scope, true)?; + let result = read(&tx, scope)?; + tx.finish_read()?; + Ok(result) + } + pub fn capacity_runtime_status(&self) -> crate::db::CapacityRuntimeStatus { self.db.capacity_runtime_status() } diff --git a/src/db/guild_data/case_evidence.rs b/src/db/guild_data/case_evidence.rs index f36044be5..4f05433e1 100644 --- a/src/db/guild_data/case_evidence.rs +++ b/src/db/guild_data/case_evidence.rs @@ -339,26 +339,19 @@ impl GuildDataStore { case: CaseId, id: CaseId, ) -> Result> { - self.check_target(&scope.placement)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - if !live(&tx, &scope, &case)? { - tx.finish_read()?; - return Ok(None); + read_active_scope!(self, scope, move |tx, scope| { + if !live(tx, scope, &case)? { + return Ok(None); + } + let result = match record(tx, scope, &id)? { + Some(r) if r.job.case_id == case && r.job.state == EvidenceState::Available => { + Some(r.into_available()?) } - let result = match record(&tx, &scope, &id)? { - Some(r) if r.job.case_id == case && r.job.state == EvidenceState::Available => { - Some(r.into_available()?) - } - _ => None, - }; - tx.finish_read()?; - Ok(result) - }) - .await + _ => None, + }; + Ok(result) + }) + .await } pub async fn case_evidence_index( @@ -369,36 +362,30 @@ impl GuildDataStore { ) -> Result> { self.check_target(&scope.placement)?; limits.validate()?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - if !live(&tx, &scope, &case)? { - tx.finish_read()?; - return Ok(Vec::new()); - } - let mut stmt = tx.prepare( - "SELECT case_id,evidence_id,storage_id,reserved_bytes,state,cancelled,channel_id,message_id,attachment_id,sha256 - FROM guild_case_evidence - WHERE guild_id=?1 AND enrollment_id=?2 AND case_id=?3 AND state=1 AND cancelled=0 - ORDER BY evidence_id LIMIT ?4", - )?; - let rows = stmt.query_map( - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - case.as_str(), - limits.max_page_size as i64 - ], - |row| decode_record(row, &scope)?.into_available(), - )?; - let items = rows.collect::>>()?; - drop(stmt); - tx.finish_read()?; - Ok(items) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + if !live(tx, scope, &case)? { + return Ok(Vec::new()); + } + let mut stmt = tx.prepare( + "SELECT case_id,evidence_id,storage_id,reserved_bytes,state,cancelled,channel_id,message_id,attachment_id,sha256 + FROM guild_case_evidence + WHERE guild_id=?1 AND enrollment_id=?2 AND case_id=?3 AND state=1 AND cancelled=0 + ORDER BY evidence_id LIMIT ?4", + )?; + let rows = stmt.query_map( + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), + case.as_str(), + limits.max_page_size as i64 + ], + |row| decode_record(row, scope)?.into_available(), + )?; + let items = rows.collect::>>()?; + + Ok(items) + }) + .await } /// Prepare closed-membership object cleanup in bounded batches. Closure itself diff --git a/src/db/guild_data/case_history.rs b/src/db/guild_data/case_history.rs index 1966eb9d0..8ac98c25f 100644 --- a/src/db/guild_data/case_history.rs +++ b/src/db/guild_data/case_history.rs @@ -299,53 +299,47 @@ impl GuildDataStore { limits.validate()?; limits.entry.page(count)?; anyhow::ensure!(after_sequence >= 0, CaseError::Invalid); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - if history_parent(&tx, &scope, &case)? == HistoryParent::Unavailable { - tx.finish_read()?; - return Ok(Vec::new()); - } - let mut stmt = tx.prepare( - "SELECT entry_id, sequence, + read_active_scope!(self, scope, move |tx, scope| { + if history_parent(tx, scope, &case)? == HistoryParent::Unavailable { + return Ok(Vec::new()); + } + let mut stmt = tx.prepare( + "SELECT entry_id, sequence, CASE WHEN length(CAST(payload AS BLOB))<=?6 THEN payload END FROM guild_case_history WHERE guild_id=?1 AND enrollment_id=?2 AND case_id=?3 AND sequence>?4 ORDER BY sequence LIMIT ?5", - )?; - let rows = stmt.query_map( - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - case.as_str(), - after_sequence, - i64::from(count), - i64::from(limits.entry.max_record_bytes) - ], - |row| { - Ok(( - row.get::(0)?, - row.get::(1)?, - row.get::>(2)?, - )) - }, - )?; - let mut page = Vec::new(); - for row in rows { - let (id, sequence, payload) = row?; - let reference = CaseHistoryRef { - id: CaseId::try_from(id)?, - sequence, - }; - page.push((reference, decode_history_payload(payload, limits)?)); - } - drop(stmt); - tx.finish_read()?; - Ok(page) - }) - .await + )?; + let rows = stmt.query_map( + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), + case.as_str(), + after_sequence, + i64::from(count), + i64::from(limits.entry.max_record_bytes) + ], + |row| { + Ok(( + row.get::(0)?, + row.get::(1)?, + row.get::>(2)?, + )) + }, + )?; + let mut page = Vec::new(); + for row in rows { + let (id, sequence, payload) = row?; + let reference = CaseHistoryRef { + id: CaseId::try_from(id)?, + sequence, + }; + page.push((reference, decode_history_payload(payload, limits)?)); + } + + Ok(page) + }) + .await } /// Sequence keyset page of IDs only. Missing/removed parent yields an empty page; diff --git a/src/db/guild_data/case_listing.rs b/src/db/guild_data/case_listing.rs index 45fb84d58..0a72f0de2 100644 --- a/src/db/guild_data/case_listing.rs +++ b/src/db/guild_data/case_listing.rs @@ -1,6 +1,5 @@ //! Indexed keyset queries for the live moderation case list. use super::cases::{CASE_SUMMARY_SQL, parse_case_summary}; -use super::tenant_logs::verify_scope; use super::*; use crate::db_compat::{Value, params_from_iter}; use serde::Deserialize; @@ -31,8 +30,8 @@ impl CaseSort { fn accepts(self, position: &CaseListPosition) -> bool { use CaseSortValue::{Number, Text}; match (self, &position.value) { - (Self::Date | Self::Subject, Number(value)) => *value > 0, - (Self::Actor, Number(value)) => *value >= 0, + (Self::Date, Number(value)) => *value > 0, + (Self::Subject | Self::Actor, Number(value)) => *value >= 0, (Self::Case, Text(value)) => value == position.case_id.as_str(), (Self::Action, Text(value)) => { serde_json::from_value::(serde_json::Value::String(value.clone())) @@ -118,6 +117,11 @@ impl CaseListQuery { limits: CaseLimits, ) -> Result<(String, Vec)> { let (column, index) = self.sort.column_and_index(); + let index = if self.sort == CaseSort::Date && self.filter.subject_id.is_some() { + "guild_cases_subject_date" + } else { + index + }; let (direction, cmp) = if self.descending { ("DESC", "<") } else { @@ -215,54 +219,47 @@ impl GuildDataStore { .then(|| query.count_statement(&scope)) .transpose()?; let (sql, params) = query.statement(&scope, count, limits)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let total = count_statement - .map(|(sql, params)| { - tx.query_row(&sql, params_from_iter(params), |row| Ok(row.get(0)?)) - }) - .transpose()?; - let mut stmt = tx.prepare(&sql)?; - let mut rows = stmt - .query_map(params_from_iter(params), |row| { - Ok(( - row.get::(0)?, - row.get::>(1)?, - row.get_value(2)?, - )) - })? - .collect::>>()?; - let has_next = rows.len() > count as usize; - if has_next { - rows.pop(); - } - let next = rows - .last() - .filter(|_| has_next) - .map(|(id, _, key)| { - Ok::<_, anyhow::Error>(CaseListPosition { - value: CaseSortValue::try_from(key.clone())?, - case_id: CaseId::try_from(id.clone())?, - }) - }) - .transpose()?; - let entries = rows - .into_iter() - .map(|(id, payload, _)| { - Ok((CaseId::try_from(id)?, parse_case_summary(payload)?)) + read_active_scope!(self, scope, move |tx, _| { + let total = count_statement + .map(|(sql, params)| { + tx.query_row(&sql, params_from_iter(params), |row| Ok(row.get(0)?)) + }) + .transpose()?; + let mut stmt = tx.prepare_read_template(&sql)?; + let mut rows = stmt + .query_map(params_from_iter(params), |row| { + Ok(( + row.get::(0)?, + row.get::>(1)?, + row.get_value(2)?, + )) + })? + .collect::>>()?; + let has_next = rows.len() > count as usize; + if has_next { + rows.pop(); + } + let next = rows + .last() + .filter(|_| has_next) + .map(|(id, _, key)| { + Ok::<_, anyhow::Error>(CaseListPosition { + value: CaseSortValue::try_from(key.clone())?, + case_id: CaseId::try_from(id.clone())?, }) - .collect::>()?; - drop(stmt); - tx.finish_read()?; - Ok(CaseListPage { - entries, - next, - total, }) + .transpose()?; + let entries = rows + .into_iter() + .map(|(id, payload, _)| Ok((CaseId::try_from(id)?, parse_case_summary(payload)?))) + .collect::>()?; + + Ok(CaseListPage { + entries, + next, + total, }) - .await + }) + .await } } diff --git a/src/db/guild_data/case_sources.rs b/src/db/guild_data/case_sources.rs index 7bad550bb..c6e164646 100644 --- a/src/db/guild_data/case_sources.rs +++ b/src/db/guild_data/case_sources.rs @@ -74,16 +74,7 @@ impl GuildDataStore { ) -> Result> { self.check_target(&scope.placement)?; let key = source.key()?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let result = source_match(&tx, &scope, &key)?; - tx.finish_read()?; - Ok(result) - }) - .await + read_active_scope!(self, scope, move |tx, scope| source_match(tx, scope, &key)).await } /// Bind a proven counterpart to an existing case using an already-bound anchor. diff --git a/src/db/guild_data/cases.rs b/src/db/guild_data/cases.rs index c1da326b2..a248252bf 100644 --- a/src/db/guild_data/cases.rs +++ b/src/db/guild_data/cases.rs @@ -218,6 +218,21 @@ pub struct CaseData { pub redacted: CaseRedaction, } +/// Serialize a case in its stored layout, keeping the private ban attempt tag. +pub(super) fn stored_case_payload(data: &CaseData) -> Result { + #[derive(Serialize)] + struct StoredCase<'a> { + #[serde(flatten)] + data: &'a CaseData, + #[serde(skip_serializing_if = "Option::is_none")] + ban_attempt_tag: Option<&'a crate::ban_reason::BanAttemptTag>, + } + Ok(serde_json::to_string(&StoredCase { + data, + ban_attempt_tag: data.ban_attempt_tag.as_ref(), + })?) +} + /// Private list fields only; reason, source identifiers and evidence remain detail-only. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CaseSummary { @@ -420,18 +435,7 @@ impl GuildDataStore { data.reason = data .reason .map(|reason| crate::ban_reason::without_tag(&reason).to_owned()); - // Preserve the legacy field order for exact-payload replay comparisons. - #[derive(Serialize)] - struct StoredCase<'a> { - #[serde(flatten)] - data: &'a CaseData, - #[serde(skip_serializing_if = "Option::is_none")] - ban_attempt_tag: Option<&'a crate::ban_reason::BanAttemptTag>, - } - let payload = serde_json::to_string(&StoredCase { - data: &data, - ban_attempt_tag: data.ban_attempt_tag.as_ref(), - })?; + let payload = stored_case_payload(&data)?; anyhow::ensure!( payload.len() <= limits.max_record_bytes as usize, CaseError::Limit @@ -561,19 +565,16 @@ impl GuildDataStore { ) -> Result> { self.check_target(&scope.placement)?; limits.validate()?; - let expected = self.expected.clone(); - self.db.with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; + read_active_scope!(self, scope, move |tx, scope| { let row = tx.query_row("SELECT CASE WHEN length(CAST(payload AS BLOB))<=?4 THEN payload ELSE NULL END FROM guild_cases WHERE guild_id=?1 AND enrollment_id=?2 AND case_id=?3 AND deleted=0", params![scope.guild_id(),scope.enrollment.id.as_str(),id.as_str(),limits.max_record_bytes as i64], |r| Ok(r.get::>(0)?)).optional()?; let result = match row { None => None, Some(None) => return Err(CaseError::Limit.into()), Some(Some(payload)) => { let data = serde_json::from_str(&payload)?; validate_data(&data, limits)?; Some(data) } }; - tx.finish_read()?; Ok(result) - }).await + }) + .await } /// Read a bounded ID page's summaries in one scoped snapshot, including empty pages. @@ -588,35 +589,30 @@ impl GuildDataStore { limits.validate()?; anyhow::ensure!(ids.len() <= limits.max_page_size as usize, CaseError::Limit); let ids = serde_json::to_string(&ids)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let mut stmt = tx.prepare(&format!( - "SELECT case_id, {CASE_SUMMARY_SQL} + read_active_scope!(self, scope, move |tx, scope| { + let mut stmt = tx.prepare(&format!( + "SELECT case_id, {CASE_SUMMARY_SQL} FROM guild_cases WHERE guild_id=?1 AND enrollment_id=?2 AND deleted=0 AND case_id IN (SELECT value FROM json_each(?4))", - ))?; - let rows = stmt.query_map( - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - i64::from(limits.max_record_bytes), - ids - ], - |r| Ok((r.get::(0)?, r.get::>(1)?)), - )?; - let mut summaries = std::collections::BTreeMap::new(); - for row in rows { - let (id, payload) = row?; - summaries.insert(id, parse_case_summary(payload)?); - } - drop(stmt); - tx.finish_read()?; - Ok(summaries) - }) - .await + ))?; + let rows = stmt.query_map( + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), + i64::from(limits.max_record_bytes), + ids + ], + |r| Ok((r.get::(0)?, r.get::>(1)?)), + )?; + let mut summaries = std::collections::BTreeMap::new(); + for row in rows { + let (id, payload) = row?; + summaries.insert(id, parse_case_summary(payload)?); + } + + Ok(summaries) + }) + .await } /// Keyset page in opaque ID order, not chronology. Never loads evidence payloads. @@ -697,10 +693,7 @@ impl GuildDataStore { ) -> Result> { self.check_target(&scope.placement)?; let [action, outcome, subject, actor] = filter.sql_values()?; - let expected = self.expected.clone(); - self.db.with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; + read_active_scope!(self, scope, move |tx, scope| { // Removed rows keep no payload, so callers filter live pages only. let mut stmt = tx.prepare("SELECT case_id FROM guild_cases WHERE guild_id=?1 AND enrollment_id=?2 AND deleted=?5 AND case_id>?3 AND (?6 IS NULL OR json_extract(payload,'$.action')=?6) @@ -711,29 +704,24 @@ impl GuildDataStore { let rows = stmt.query_map(params![scope.guild_id(),scope.enrollment.id.as_str(),after.as_ref().map_or("",CaseId::as_str),count,removed,action,outcome,subject,actor], |r| Ok(r.get::(0)?))?; let mut ids = Vec::new(); for row in rows { ids.push(CaseId::try_from(row?)?); } - drop(stmt); - tx.finish_read()?; + Ok(ids) - }).await + }) + .await } pub async fn case_count(&self, scope: GuildDataScope, limits: CaseLimits) -> Result { self.check_target(&scope.placement)?; limits.validate()?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let count: i64 = tx.query_row( - "SELECT COUNT(*) FROM guild_cases WHERE guild_id=?1 AND enrollment_id=?2 AND deleted=0", - params![scope.guild_id(), scope.enrollment.id.as_str()], - |r| Ok(r.get(0)?), - )?; - tx.finish_read()?; - Ok(count) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + let count: i64 = tx.query_row( + "SELECT COUNT(*) FROM guild_cases WHERE guild_id=?1 AND enrollment_id=?2 AND deleted=0", + params![scope.guild_id(), scope.enrollment.id.as_str()], + |r| Ok(r.get(0)?), + )?; + Ok(count) + }) + .await } /// Remove retained text/reason/actor/subject/outcome atomically. Keep only replay diff --git a/src/db/guild_data/deletion_requests.rs b/src/db/guild_data/deletion_requests.rs index ceddf4325..5a5e49a5f 100644 --- a/src/db/guild_data/deletion_requests.rs +++ b/src/db/guild_data/deletion_requests.rs @@ -342,43 +342,40 @@ fn require_queued( /// Replace `<@ID>`, `<@!ID>` and the bare decimal ID (not part of a longer number). pub fn redact_mentions(text: &str, subject: i64) -> Option { - let id = subject.to_string(); - if subject <= 0 || !text.contains(&id) { + if subject <= 0 { return None; } - let mut out = String::with_capacity(text.len()); - let bytes = text.as_bytes(); - let mut index = 0; - let mut changed = false; - while index < text.len() { - let rest = &text[index..]; - let mention = ["<@!", "<@"].into_iter().find_map(|prefix| { - let after = rest.strip_prefix(prefix)?; - let tail = after.strip_prefix(id.as_str())?; - tail.starts_with('>').then_some(prefix.len() + id.len() + 1) - }); - if let Some(length) = mention { - out.push_str("[removed]"); - index += length; - changed = true; + let id = subject.to_string(); + let mut out = String::new(); + let mut copied = 0; + for (start, _) in text.match_indices(&id) { + let end = start + id.len(); + let before = &text[copied..start]; + let after = &text[end..]; + if before.as_bytes().last().is_some_and(u8::is_ascii_digit) + || after.as_bytes().first().is_some_and(u8::is_ascii_digit) + { continue; } - if rest.starts_with(id.as_str()) - && (index == 0 || !bytes[index - 1].is_ascii_digit()) - && bytes - .get(index + id.len()) - .is_none_or(|next| !next.is_ascii_digit()) + let opener = before + .strip_suffix("<@!") + .or_else(|| before.strip_suffix("<@")); + if let Some(prefix) = opener + && after.starts_with('>') { - out.push_str("[removed]"); - index += id.len(); - changed = true; - continue; + out.push_str(prefix); + copied = end + 1; + } else { + out.push_str(before); + copied = end; } - let ch = rest.chars().next().unwrap_or_default(); - out.push(ch); - index += ch.len_utf8().max(1); + out.push_str("[removed]"); } - changed.then_some(out) + if copied == 0 { + return None; + } + out.push_str(&text[copied..]); + Some(out) } /// What redacting one case removes. @@ -488,21 +485,6 @@ pub fn redact_history_entry(data: &mut CaseHistoryData, subject: i64, about_subj changed } -/// Serialize a case in its stored layout, keeping the private ban attempt tag. -fn stored_case_payload(data: &CaseData) -> Result { - #[derive(Serialize)] - struct StoredCase<'a> { - #[serde(flatten)] - data: &'a CaseData, - #[serde(skip_serializing_if = "Option::is_none")] - ban_attempt_tag: Option<&'a crate::ban_reason::BanAttemptTag>, - } - Ok(serde_json::to_string(&StoredCase { - data, - ban_attempt_tag: data.ban_attempt_tag.as_ref(), - })?) -} - struct ScannedCase { about_subject: bool, history_entries: u64, @@ -860,17 +842,11 @@ impl GuildDataStore { id: DeletionRequestId, now_ms: i64, ) -> Result> { - self.check_target(&scope.placement)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let request = visible(load_request(&tx, &scope, &id)?, origin, now_ms); - tx.finish_read()?; - Ok(request) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + let request = visible(load_request(tx, scope, &id)?, origin, now_ms); + Ok(request) + }) + .await } /// Requests of one origin, excluding expired rows: every unfinished request @@ -882,34 +858,28 @@ impl GuildDataStore { origin: DeletionOrigin, now_ms: i64, ) -> Result> { - self.check_target(&scope.placement)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let mut stmt = tx.prepare(&format!( - "SELECT {REQUEST_COLUMNS} FROM guild_deletion_requests + read_active_scope!(self, scope, move |tx, scope| { + let mut stmt = tx.prepare(&format!( + "SELECT {REQUEST_COLUMNS} FROM guild_deletion_requests WHERE guild_id=?1 AND enrollment_id=?2 AND origin=?3 AND (expires_at_ms IS NULL OR expires_at_ms>?4) ORDER BY state='complete', created_at_ms DESC, request_id LIMIT ?5" - ))?; - let rows = stmt.query_map( - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - origin.as_sql(), - now_ms, - LIST_LIMIT - ], - read_request, - )?; - let requests = rows.collect::>>()?; - drop(stmt); - tx.finish_read()?; - Ok(requests) - }) - .await + ))?; + let rows = stmt.query_map( + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), + origin.as_sql(), + now_ms, + LIST_LIMIT + ], + read_request, + )?; + let requests = rows.collect::>>()?; + + Ok(requests) + }) + .await } /// Confirmed requests waiting for erasure, oldest first. @@ -917,31 +887,25 @@ impl GuildDataStore { &self, scope: GuildDataScope, ) -> Result> { - self.check_target(&scope.placement)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let mut stmt = tx.prepare( - "SELECT request_id,subject_id FROM guild_deletion_requests + read_active_scope!(self, scope, move |tx, scope| { + let mut stmt = tx.prepare( + "SELECT request_id,subject_id FROM guild_deletion_requests WHERE guild_id=?1 AND enrollment_id=?2 AND state='queued' ORDER BY confirmed_at_ms, request_id LIMIT ?3", - )?; - let rows = stmt.query_map( - params![scope.guild_id(), scope.enrollment.id.as_str(), LIST_LIMIT], - |r| Ok((r.get::(0)?, r.get::(1)?)), - )?; - let mut queued = Vec::new(); - for row in rows { - let (id, subject) = row?; - queued.push((CaseId::try_from(id)?, subject)); - } - drop(stmt); - tx.finish_read()?; - Ok(queued) - }) - .await + )?; + let rows = stmt.query_map( + params![scope.guild_id(), scope.enrollment.id.as_str(), LIST_LIMIT], + |r| Ok((r.get::(0)?, r.get::(1)?)), + )?; + let mut queued = Vec::new(); + for row in rows { + let (id, subject) = row?; + queued.push((CaseId::try_from(id)?, subject)); + } + + Ok(queued) + }) + .await } /// What an erasure for `subject` would change in this guild store. Reads only. @@ -1007,34 +971,29 @@ impl GuildDataStore { subject: i64, after: Option, ) -> Result<(Vec, Option)> { - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let page = candidate_cases(&tx, &scope, subject, after.as_ref(), CASE_BATCH)?; - let next = (page.len() == CASE_BATCH as usize) - .then(|| page.last().map(|(case, _)| case.clone())) - .flatten(); - let mut scanned = Vec::new(); - for (case, payload) in &page { - let Some(planned) = plan_case(&tx, &scope, case, payload, subject)? else { - continue; - }; - let messages = serde_json::to_string(&planned.removed_messages)?; - let attachments = - live_evidence_count(&tx, &scope, case, planned.about_subject, &messages)?; - scanned.push(ScannedCase { - about_subject: planned.about_subject, - history_entries: planned.history.len() as u64, - evidence_items: planned.removed_messages.len() as u64 - + attachments.max(0) as u64, - }); - } - tx.finish_read()?; - Ok((scanned, next)) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + let page = candidate_cases(tx, scope, subject, after.as_ref(), CASE_BATCH)?; + let next = (page.len() == CASE_BATCH as usize) + .then(|| page.last().map(|(case, _)| case.clone())) + .flatten(); + let mut scanned = Vec::new(); + for (case, payload) in &page { + let Some(planned) = plan_case(tx, scope, case, payload, subject)? else { + continue; + }; + let messages = serde_json::to_string(&planned.removed_messages)?; + let attachments = + live_evidence_count(tx, scope, case, planned.about_subject, &messages)?; + scanned.push(ScannedCase { + about_subject: planned.about_subject, + history_entries: planned.history.len() as u64, + evidence_items: planned.removed_messages.len() as u64 + + attachments.max(0) as u64, + }); + } + Ok((scanned, next)) + }) + .await } /// Count an attempt. Returns the subject and attempt number while the request is queued. diff --git a/src/db/guild_data/historical_schema.rs b/src/db/guild_data/historical_schema.rs index 4d59b5434..8074449dd 100644 --- a/src/db/guild_data/historical_schema.rs +++ b/src/db/guild_data/historical_schema.rs @@ -75,6 +75,7 @@ pub(super) fn apply(tx: &crate::db_compat::Transaction, from: i64, to: i64) -> R (23, MEMBER_NAME_SCHEMA), (24, ONBOARDING_TRAP_SCHEMA), (25, DELETION_REQUESTS_SCHEMA), + (26, SUBJECT_CASE_DATES_SCHEMA), ]; for &(version, sql) in steps { if (from + 1..=to).contains(&version) { diff --git a/src/db/guild_data/member_directory.rs b/src/db/guild_data/member_directory.rs index a04ac84e6..e3cc47188 100644 --- a/src/db/guild_data/member_directory.rs +++ b/src/db/guild_data/member_directory.rs @@ -2266,16 +2266,10 @@ UPDATE guild_member_audit_recovery SET restart_requested_at_ms=MAX(coalesce(rest expected_bot_id.is_none_or(|id| id > 0), MemberSyncError::Invalid ); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let out = status(&tx, &scope, expected_bot_id, now_ms, true)?; - tx.finish_read()?; - Ok(out) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + status(tx, scope, expected_bot_id, now_ms, true) + }) + .await } /// Idle-loop status. Scheduling uses phase, state, and the saved attempt @@ -2449,16 +2443,10 @@ UPDATE guild_member_audit_recovery SET restart_requested_at_ms=MAX(coalesce(rest ) -> Result> { checked_scope(self, &scope)?; anyhow::ensure!(user_id > 0, MemberSyncError::Invalid); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let stay = current_member_stay_id_tx(&tx, &scope, user_id)?; - tx.finish_read()?; - Ok(stay) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + current_member_stay_id_tx(tx, scope, user_id) + }) + .await } pub async fn has_pending_rejoin_note( @@ -2468,24 +2456,19 @@ UPDATE guild_member_audit_recovery SET restart_requested_at_ms=MAX(coalesce(rest ) -> Result { checked_scope(self, &scope)?; anyhow::ensure!(user_id > 0, MemberSyncError::Invalid); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let pending: bool = tx.query_row( - "SELECT EXISTS(SELECT 1 FROM guild_member_pending_rejoin_notes p JOIN guild_member_directory d ON d.guild_id=p.guild_id AND d.enrollment_id=p.enrollment_id AND d.user_id=p.user_id WHERE p.guild_id=?1 AND p.enrollment_id=?2 AND p.user_id=?3 AND d.is_current=1 AND d.current_stay_id=p.stay_id)", - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - user_id - ], - |r| Ok(r.get(0)?), - )?; - tx.finish_read()?; - Ok(pending) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + let pending: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM guild_member_pending_rejoin_notes p JOIN guild_member_directory d ON d.guild_id=p.guild_id AND d.enrollment_id=p.enrollment_id AND d.user_id=p.user_id WHERE p.guild_id=?1 AND p.enrollment_id=?2 AND p.user_id=?3 AND d.is_current=1 AND d.current_stay_id=p.stay_id)", + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), + user_id + ], + |r| Ok(r.get(0)?), + )?; + Ok(pending) + }) + .await } pub async fn clear_pending_rejoin_note( @@ -2521,23 +2504,18 @@ UPDATE guild_member_audit_recovery SET restart_requested_at_ms=MAX(coalesce(rest pub async fn member_case_index_complete(&self, scope: GuildDataScope) -> Result { checked_scope(self, &scope)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let progress: BackfillProgress = tx - .query_row( - "SELECT case_backfill_done FROM guild_member_seed WHERE guild_id=?1 AND enrollment_id=?2", - params![scope.guild_id(), scope.enrollment.id.as_str()], - |r| Ok(BackfillProgress::from(r.get::(0)?)), - ) - .optional()? - .unwrap_or(BackfillProgress::Pending); - tx.finish_read()?; - Ok(progress == BackfillProgress::Complete) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + let progress: BackfillProgress = tx + .query_row( + "SELECT case_backfill_done FROM guild_member_seed WHERE guild_id=?1 AND enrollment_id=?2", + params![scope.guild_id(), scope.enrollment.id.as_str()], + |r| Ok(BackfillProgress::from(r.get::(0)?)), + ) + .optional()? + .unwrap_or(BackfillProgress::Pending); + Ok(progress == BackfillProgress::Complete) + }) + .await } pub async fn depart_member( @@ -4044,70 +4022,65 @@ impl GuildDataStore { }; (key, Some(anchor.user_id)) }); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let total = count_sql - .map(|sql| { - tx.query_row( - &sql, - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - search.as_str(), - mention_id, - query.joined_from_ms, - query.joined_to_ms - ], - |row| Ok(row.get(0)?), - ) - }) - .transpose()?; - let mut stmt = tx.prepare(&sql)?; - let rows = stmt.query_map( - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - search, - mention_id, - query.joined_from_ms, - query.joined_to_ms, - after_key, - after_id, - i64::from(query.limit) + 1 - ], - |row| { - let key = match query.sort { - MemberSort::Name => MemberSortValue::Name(row.get(12)?), - _ => MemberSortValue::Number(row.get(12)?), - }; - Ok(( - profile(row)?, - MemberListAnchor { - key, - user_id: row.get(0)?, - }, - )) - }, - )?; - let mut rows = rows.collect::>>()?; - drop(stmt); - let next_anchor = if rows.len() > query.limit as usize { - rows.pop(); - rows.last().map(|(_, anchor)| anchor.clone()) - } else { - None - }; - tx.finish_read()?; - Ok(MemberPage { - members: rows.into_iter().map(|(member, _)| member).collect(), - next_anchor, - total, + read_active_scope!(self, scope, move |tx, scope| { + let total = count_sql + .map(|sql| { + tx.query_row( + &sql, + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), + search.as_str(), + mention_id, + query.joined_from_ms, + query.joined_to_ms + ], + |row| Ok(row.get(0)?), + ) }) + .transpose()?; + let mut stmt = tx.prepare(&sql)?; + let rows = stmt.query_map( + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), + search, + mention_id, + query.joined_from_ms, + query.joined_to_ms, + after_key, + after_id, + i64::from(query.limit) + 1 + ], + |row| { + let key = match query.sort { + MemberSort::Name => MemberSortValue::Name(row.get(12)?), + _ => MemberSortValue::Number(row.get(12)?), + }; + Ok(( + profile(row)?, + MemberListAnchor { + key, + user_id: row.get(0)?, + }, + )) + }, + )?; + let mut rows = rows.collect::>>()?; + + let next_anchor = if rows.len() > query.limit as usize { + rows.pop(); + rows.last().map(|(_, anchor)| anchor.clone()) + } else { + None + }; + Ok(MemberPage { + members: rows.into_iter().map(|(member, _)| member).collect(), + next_anchor, + total, }) - .await + }) + .await } pub async fn get_member( @@ -4162,35 +4135,29 @@ impl GuildDataStore { user_ids.len() <= DIRECTORY_PROFILE_LOOKUP_LIMIT && user_ids.iter().all(|id| *id > 0), MemberSyncError::Invalid ); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - if user_ids.is_empty() { - tx.finish_read()?; - return Ok(Vec::new()); - } - let ids = serde_json::to_string(&user_ids)?; - let sql = format!( - "SELECT {columns} FROM guild_member_directory + read_active_scope!(self, scope, move |tx, scope| { + if user_ids.is_empty() { + return Ok(Vec::new()); + } + let ids = serde_json::to_string(&user_ids)?; + let sql = format!( + "SELECT {columns} FROM guild_member_directory WHERE guild_id=?1 AND enrollment_id=?2 AND user_id IN (SELECT value FROM json_each(?3)) ORDER BY user_id" - ); - let mut stmt = tx.prepare(&sql)?; - let rows = stmt.query_map( - params![scope.guild_id(), scope.enrollment.id.as_str(), ids], - decode, - )?; - let mut found = Vec::new(); - for row in rows { - found.push(row?); - } - drop(stmt); - tx.finish_read()?; - Ok(found) - }) - .await + ); + let mut stmt = tx.prepare(&sql)?; + let rows = stmt.query_map( + params![scope.guild_id(), scope.enrollment.id.as_str(), ids], + decode, + )?; + let mut found = Vec::new(); + for row in rows { + found.push(row?); + } + + Ok(found) + }) + .await } /// Bounded directory counts for the analytics views: current members, @@ -4388,49 +4355,42 @@ impl GuildDataStore { ); let fetch = i64::from(limit) + 1; let max_record_bytes = i64::from(limits.max_record_bytes); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let backfill_done: bool = tx - .query_row( - "SELECT case_backfill_done FROM guild_member_seed WHERE guild_id=?1 AND enrollment_id=?2", - params![scope.guild_id(), scope.enrollment.id.as_str()], - |r| Ok(r.get(0)?), - ) - .optional()? - .unwrap_or(false); - if !backfill_done { - tx.finish_read()?; - return Err(MemberSyncError::Stale.into()); - } - let index_gap: bool = tx.query_row( - GuildDataStore::member_case_entries_index_gap_sql(), - params![ - scope.guild_id(), - scope.enrollment.id.as_str(), - user_id, - fetch - ], + read_active_scope!(self, scope, move |tx, scope| { + let backfill_done: bool = tx + .query_row( + "SELECT case_backfill_done FROM guild_member_seed WHERE guild_id=?1 AND enrollment_id=?2", + params![scope.guild_id(), scope.enrollment.id.as_str()], |r| Ok(r.get(0)?), - )?; - if index_gap { - tx.finish_read()?; - return Err(MemberSyncError::Stale.into()); - } - let page = Self::collect_member_case_page( - &tx, - &scope, + ) + .optional()? + .unwrap_or(false); + if !backfill_done { + return Err(MemberSyncError::Stale.into()); + } + let index_gap: bool = tx.query_row( + GuildDataStore::member_case_entries_index_gap_sql(), + params![ + scope.guild_id(), + scope.enrollment.id.as_str(), user_id, - fetch, - limit, - max_record_bytes, - )?; - tx.finish_read()?; - Ok(page) - }) - .await + fetch + ], + |r| Ok(r.get(0)?), + )?; + if index_gap { + return Err(MemberSyncError::Stale.into()); + } + let page = Self::collect_member_case_page( + tx, + scope, + user_id, + fetch, + limit, + max_record_bytes, + )?; + Ok(page) + }) + .await } /// Reads indexed cases for one member while backfill is still running. @@ -4447,23 +4407,12 @@ impl GuildDataStore { ); let fetch = i64::from(limit) + 1; let max_record_bytes = i64::from(CaseLimits::default().max_record_bytes); - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let page = Self::collect_member_case_page( - &tx, - &scope, - user_id, - fetch, - limit, - max_record_bytes, - )?; - tx.finish_read()?; - Ok(page) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + let page = + Self::collect_member_case_page(tx, scope, user_id, fetch, limit, max_record_bytes)?; + Ok(page) + }) + .await } fn collect_member_case_page( diff --git a/src/db/guild_data/snapshots.rs b/src/db/guild_data/snapshots.rs index 908d81a1b..cca484865 100644 --- a/src/db/guild_data/snapshots.rs +++ b/src/db/guild_data/snapshots.rs @@ -729,18 +729,12 @@ impl GuildDataStore { channel_id: i64, message_id: i64, ) -> Result> { - self.check_target(&scope.placement)?; - let expected = self.expected.clone(); - self.db - .with_conn(move |conn| { - let tx = conn.transaction_primary_snapshot()?; - verify_scope(&tx, &expected, &scope, true)?; - let row = load(&tx, &scope, channel_id, message_id)?; - let now = write_time_ms()?; - tx.finish_read()?; - Ok(row.filter(|row| row.expires_at_ms > now)) - }) - .await + read_active_scope!(self, scope, move |tx, scope| { + let row = load(tx, scope, channel_id, message_id)?; + let now = write_time_ms()?; + Ok(row.filter(|row| row.expires_at_ms > now)) + }) + .await } /// Reads and writes one accepted edit in one primary transaction. Equal-version diff --git a/src/db/guild_data/tests.rs b/src/db/guild_data/tests.rs index c5348f9cb..8dafef69a 100644 --- a/src/db/guild_data/tests.rs +++ b/src/db/guild_data/tests.rs @@ -16,6 +16,11 @@ impl Fixture { store_path: path("store"), } } + async fn shared_store(&self) -> (StoreRegistration, GuildDataStore) { + let reg = self.registration(StoreId::new(), StorePolicy::Shared).await; + let store = GuildDataStore::initialize(self.options(), reg.clone()).unwrap(); + (reg, store) + } fn options(&self) -> GuildStoreOptions { options(&self.store_path) } @@ -34,6 +39,27 @@ impl Drop for Fixture { clean(&self.store_path); } } +async fn bound_guild_fixture() -> (Fixture, GuildDataStore, GuildDataScope) { + let f = Fixture::new(); + let (reg, store) = f.shared_store().await; + let placement = f.placement(®, 10).await; + store + .bind_initial_placement(placement.clone()) + .await + .unwrap(); + let scope = GuildDataScope::new( + placement, + crate::db::GuildEnrollment { + guild_id: 10, + id: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(), + joined_at_ns: 100, + }, + ) + .unwrap(); + store.bind_initial_membership(scope.clone()).await.unwrap(); + (f, store, scope) +} + fn path(label: &str) -> PathBuf { std::env::temp_dir().join(format!( "jmodguard_guild_{label}_{:032x}.db", @@ -1654,12 +1680,8 @@ async fn released_guild_stores_upgrade_with_data_and_reopen() { ) .unwrap(); - for (released, draft_extension) in [ - (GUILD_BASELINE_VERSION, false), - (V0_2_1_GUILD_VERSION, false), - (23, false), - (23, true), - ] { + let supported = (GUILD_BASELINE_VERSION..VERSION).map(|version| (version, false)); + for (released, draft_extension) in supported.chain([(23, true)]) { let historical = path("released_guild_upgrade"); let opts = options(&historical); GuildDataStore::create_historical_store(opts.clone(), registration.clone(), released) diff --git a/src/db/guild_data/tests/bunny_transfer.rs b/src/db/guild_data/tests/bunny_transfer.rs index 353057990..f7d8687ce 100644 --- a/src/db/guild_data/tests/bunny_transfer.rs +++ b/src/db/guild_data/tests/bunny_transfer.rs @@ -5,8 +5,7 @@ use super::*; #[tokio::test] async fn bunny_attempts_are_single_use_scoped_and_guard_generic_settlement() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let case = CaseId::new(); diff --git a/src/db/guild_data/tests/case_evidence.rs b/src/db/guild_data/tests/case_evidence.rs index 6e0488fc0..d77dc2076 100644 --- a/src/db/guild_data/tests/case_evidence.rs +++ b/src/db/guild_data/tests/case_evidence.rs @@ -39,8 +39,7 @@ async fn parent(store: &GuildDataStore, a: &GuildDataScope, n: i64) -> CaseId { #[tokio::test] async fn reservation_ready_read_and_retries_preserve_one_owned_object() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let id = CaseId::new(); @@ -142,8 +141,7 @@ async fn reservation_ready_read_and_retries_preserve_one_owned_object() { #[tokio::test] async fn removed_inflight_upload_must_settle_before_delete_and_parent_purge() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let id = CaseId::new(); @@ -249,8 +247,7 @@ async fn removed_inflight_upload_must_settle_before_delete_and_parent_purge() { #[tokio::test] async fn closure_preparation_is_bounded_and_keeps_neighbor_evidence() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let case = parent(&store, &a, 1).await; @@ -367,8 +364,7 @@ async fn closure_preparation_is_bounded_and_keeps_neighbor_evidence() { #[tokio::test] async fn budgets_and_identity_reject_churn_and_cross_case_reuse() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let other = parent(&store, &a, 2).await; @@ -485,8 +481,7 @@ async fn budgets_and_identity_reject_churn_and_cross_case_reuse() { #[tokio::test] async fn removal_racing_settlement_always_hides_evidence_and_schedules_cleanup() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let id = CaseId::new(); @@ -524,8 +519,7 @@ async fn removal_racing_settlement_always_hides_evidence_and_schedules_cleanup() #[tokio::test] async fn sql_guards_and_failed_cancellation_preserve_parent_and_metadata() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let id = CaseId::new(); @@ -605,8 +599,7 @@ async fn sql_guards_and_failed_cancellation_preserve_parent_and_metadata() { #[tokio::test] async fn empty_and_completion_paths_require_exact_scope_and_valid_inputs() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let case = parent(&store, &a, 1).await; diff --git a/src/db/guild_data/tests/case_history.rs b/src/db/guild_data/tests/case_history.rs index 00c631ae5..e7f1e9f59 100644 --- a/src/db/guild_data/tests/case_history.rs +++ b/src/db/guild_data/tests/case_history.rs @@ -42,8 +42,7 @@ async fn ordered_history_preserves_original_and_isolates_parent_and_guild() { let probe = std::sync::Arc::new(crate::db_compat::StartupProbe::default()); let _guard = crate::db_compat::enter_startup_probe(Some(probe.clone())); let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let case = parent(&store, &a, 1).await; @@ -152,8 +151,7 @@ async fn ordered_history_preserves_original_and_isolates_parent_and_guild() { #[tokio::test] async fn concurrent_retry_and_conflict_preserve_sequence_without_noop_writes() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let id = CaseId::new(); @@ -209,8 +207,7 @@ async fn concurrent_retry_and_conflict_preserve_sequence_without_noop_writes() { #[tokio::test] async fn budgets_cover_count_aggregate_bytes_and_read_size_without_eviction() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let id = CaseId::new(); @@ -346,8 +343,7 @@ async fn budgets_cover_count_aggregate_bytes_and_read_size_without_eviction() { #[tokio::test] async fn deletion_racing_append_erases_history_and_prevents_replay() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; let other = parent(&store, &a, 2).await; @@ -426,8 +422,7 @@ async fn deletion_racing_append_erases_history_and_prevents_replay() { #[tokio::test] async fn failed_child_removal_rolls_back_parent_and_closed_cleanup_cascades() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let case = parent(&store, &a, 1).await; @@ -524,8 +519,7 @@ async fn failed_child_removal_rolls_back_parent_and_closed_cleanup_cascades() { #[tokio::test] async fn sql_guards_validation_and_missing_scopes_refuse_history_changes() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let case = parent(&store, &a, 1).await; for body in [ diff --git a/src/db/guild_data/tests/case_sources.rs b/src/db/guild_data/tests/case_sources.rs index 94449c548..5d7a52966 100644 --- a/src/db/guild_data/tests/case_sources.rs +++ b/src/db/guild_data/tests/case_sources.rs @@ -39,8 +39,7 @@ fn found(id: &CaseId, removed: bool) -> CaseSourceMatch { #[tokio::test] async fn sources_resolve_both_orders_without_replacing_original_facts() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; for (original, counterpart) in [(app(), audit(10)), (audit(20), app())] { let id = record(&store, &a, original.clone()).await; @@ -97,8 +96,7 @@ async fn sources_resolve_both_orders_without_replacing_original_facts() { #[tokio::test] async fn concurrent_links_conflicts_and_retries_do_not_rewrite_or_add_receipts() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let original = app(); let id = record(&store, &a, original.clone()).await; @@ -170,8 +168,7 @@ async fn concurrent_links_conflicts_and_retries_do_not_rewrite_or_add_receipts() #[tokio::test] async fn late_link_and_removal_race_preserve_replay_suppression_without_content() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; for entry in [1, 2] { let original = app(); @@ -247,8 +244,7 @@ async fn late_link_and_removal_race_preserve_replay_suppression_without_content( #[tokio::test] async fn competing_record_or_link_never_steals_source_or_merges_cases() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let original = app(); let id = record(&store, &a, original.clone()).await; @@ -287,8 +283,7 @@ async fn competing_record_or_link_never_steals_source_or_merges_cases() { #[tokio::test] async fn source_cleanup_is_atomic_owned_and_refuses_closed_or_wrong_scopes() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let original = app(); @@ -416,8 +411,7 @@ async fn source_cleanup_is_atomic_owned_and_refuses_closed_or_wrong_scopes() { #[tokio::test] async fn raw_sql_guards_protect_sources_and_rollback_parent_insert() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let id = record(&store, &a, audit(1)).await; let original = app(); diff --git a/src/db/guild_data/tests/cases.rs b/src/db/guild_data/tests/cases.rs index f66a3b63f..2397d08f8 100644 --- a/src/db/guild_data/tests/cases.rs +++ b/src/db/guild_data/tests/cases.rs @@ -25,8 +25,7 @@ pub(super) fn data(source: i64) -> CaseData { #[tokio::test] async fn onboarding_case_uses_the_legacy_payload_and_survives_legacy_backfill() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let scope = scope(&f, &store, ®, 10).await; let id = CaseId::try_from("a".repeat(32)).unwrap(); let data = CaseData { @@ -187,8 +186,7 @@ async fn onboarding_case_uses_the_legacy_payload_and_survives_legacy_backfill() #[tokio::test] async fn cases_are_scoped_persistent_and_paginated_without_payloads() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let limits = CaseLimits::default(); @@ -254,8 +252,7 @@ async fn cases_are_scoped_persistent_and_paginated_without_payloads() { #[tokio::test] async fn source_retries_conflicts_and_removed_replays_preserve_canonical_identity() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let limits = CaseLimits::default(); let id = CaseId::new(); @@ -326,8 +323,7 @@ async fn source_retries_conflicts_and_removed_replays_preserve_canonical_identit #[tokio::test] async fn concurrent_recording_has_one_row_and_noop_paths_are_write_free() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let limits = CaseLimits::default(); let x = CaseId::new(); @@ -374,8 +370,7 @@ async fn concurrent_recording_has_one_row_and_noop_paths_are_write_free() { #[tokio::test] async fn record_budgets_reject_oversize_reads_without_erasing_records() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let limits = CaseLimits::default(); let id = CaseId::new(); @@ -435,8 +430,7 @@ async fn record_budgets_reject_oversize_reads_without_erasing_records() { #[tokio::test] async fn closed_memberships_deny_every_case_operation_and_cleanup_is_bounded() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let limits = CaseLimits::default(); @@ -497,8 +491,7 @@ async fn closed_memberships_deny_every_case_operation_and_cleanup_is_bounded() { #[tokio::test] async fn sql_guards_prevent_overwrite_replacement_and_live_replay_key_deletion() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let limits = CaseLimits::default(); let id = CaseId::new(); @@ -544,8 +537,7 @@ async fn sql_guards_prevent_overwrite_replacement_and_live_replay_key_deletion() #[tokio::test] async fn wrong_captured_membership_and_changed_identity_deny_empty_case_paths() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let wrong = GuildDataScope::new( f.placement(®, 10).await, @@ -723,8 +715,7 @@ async fn tagged_attempt_survives_reopen_and_cannot_be_retagged_or_exposed() { #[tokio::test] async fn matching_case_ids_filter_live_facts_and_keep_the_id_cursor() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let limits = CaseLimits::default(); @@ -760,102 +751,72 @@ async fn matching_case_ids_filter_live_facts_and_keep_the_id_cursor() { .unwrap(); by_fact.push(id); } - let sorted = |picks: &[usize]| { - let mut ids: Vec = picks.iter().map(|i| by_fact[*i].clone()).collect(); - ids.sort_by(|x, y| x.as_str().cmp(y.as_str())); - ids - }; - let page = |filter: CaseFilter, after: Option, count: u32| { + let page = |filter: CaseFilter, after, count| { let store = &store; - let a = a.clone(); + let scope = a.clone(); async move { store - .matching_case_ids(a, after, count, filter, limits) + .matching_case_ids(scope, after, count, filter, limits) .await - .unwrap() } }; - let bans = CaseFilter { - action: Some(CaseAction::Ban), - ..CaseFilter::default() - }; - assert_eq!(page(bans.clone(), None, 10).await, sorted(&[0, 2, 3])); - assert_eq!( - page( - CaseFilter { - outcome: Some(CaseOutcome::Failed), - ..CaseFilter::default() - }, - None, - 10 - ) - .await, - sorted(&[2]) - ); + // Each subset of the four fields intersects the stored facts. A second guild has + // the same facts under other IDs, and the removed row must disappear from every page. + for removed in [false, true] { + if removed { + store + .remove_case(a.clone(), by_fact[0].clone()) + .await + .unwrap(); + } + for (action, outcome, subject, actor) in &facts { + for mask in 0..16 { + let filter = CaseFilter { + action: (mask & 1 != 0).then_some(action.clone()), + outcome: (mask & 2 != 0).then_some(outcome.clone()), + subject_id: (mask & 4 != 0).then_some(*subject), + actor_id: actor.filter(|_| mask & 8 != 0), + }; + let mut expected: Vec<_> = facts + .iter() + .enumerate() + .filter(|(i, (a, o, s, m))| { + (!removed || *i != 0) + && filter.action.as_ref().is_none_or(|x| x == a) + && filter.outcome.as_ref().is_none_or(|x| x == o) + && filter.subject_id.is_none_or(|x| x == *s) + && filter.actor_id.is_none_or(|x| Some(x) == *m) + }) + .map(|(i, _)| by_fact[i].clone()) + .collect(); + expected.sort_by(|a, b| a.as_str().cmp(b.as_str())); + let first = page(filter.clone(), None, 2).await.unwrap(); + let split = expected.len().min(2); + assert_eq!(first, expected[..split]); + if let Some(last) = first.last() { + assert_eq!( + page(filter, Some(last.clone()), 10).await.unwrap(), + expected[split..] + ); + } + } + } + } assert_eq!( - page( - CaseFilter { - subject_id: Some(7), - ..CaseFilter::default() - }, - None, - 10 - ) - .await, - sorted(&[0, 1]) + page(CaseFilter::default(), None, 10).await.unwrap(), + store.case_ids(a.clone(), None, 10, limits).await.unwrap() ); - // Snowflakes above 2^53 are stored as strings and still match exactly. - assert_eq!( + assert!( page( CaseFilter { - actor_id: Some(i64::MAX), - ..CaseFilter::default() + subject_id: Some(0), + ..Default::default() }, None, 10 ) - .await, - sorted(&[4]) - ); - let combined = CaseFilter { - action: Some(CaseAction::Ban), - outcome: Some(CaseOutcome::Succeeded), - actor_id: Some(42), - ..CaseFilter::default() - }; - assert_eq!(page(combined, None, 10).await, sorted(&[0])); - // The ID cursor pages through matches only. - let all_bans = sorted(&[0, 2, 3]); - let first = page(bans.clone(), None, 2).await; - assert_eq!(first, all_bans[..2]); - assert_eq!( - page(bans.clone(), Some(first[1].clone()), 2).await, - all_bans[2..] - ); - // An empty filter is the unfiltered page; removed records never match. - assert_eq!( - page(CaseFilter::default(), None, 10).await, - store.case_ids(a.clone(), None, 10, limits).await.unwrap() - ); - store - .remove_case(a.clone(), by_fact[0].clone()) .await - .unwrap(); - assert_eq!(page(bans, None, 10).await, sorted(&[2, 3])); - assert!( - store - .matching_case_ids( - a, - None, - 10, - CaseFilter { - subject_id: Some(0), - ..CaseFilter::default() - }, - limits - ) - .await - .is_err() + .is_err() ); } @@ -864,8 +825,7 @@ async fn summary_pages_are_bounded_scoped_and_use_constant_database_calls() { let probe = std::sync::Arc::new(crate::db_compat::StartupProbe::default()); let _guard = crate::db_compat::enter_startup_probe(Some(probe.clone())); let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let limits = CaseLimits::default(); @@ -1119,37 +1079,51 @@ async fn case_listing_migration_indexes_existing_guild_rows_for_every_seek() { assert!(GuildDataStore::open(f.options(), reg.clone()).is_err()); let store = GuildDataStore::initialize(f.options(), reg).unwrap(); let limits = CaseLimits::default(); - for (sort, index, seek) in [ + for (sort, subject_id, index, seek) in [ ( CaseSort::Date, + None, "guild_cases_list_date", "(list_date,case_id)", ), - (CaseSort::Case, "guild_cases_visible", "case_id"), + (CaseSort::Case, None, "guild_cases_visible", "case_id"), ( CaseSort::Action, + None, "guild_cases_list_action", "(list_action,case_id)", ), ( CaseSort::Subject, + None, "guild_cases_list_subject", "(list_subject,case_id)", ), ( CaseSort::Actor, + None, "guild_cases_list_actor", "(list_actor,case_id)", ), ( CaseSort::Outcome, + None, "guild_cases_list_outcome", "(list_outcome,case_id)", ), + ( + CaseSort::Date, + Some(i64::MAX), + "guild_cases_subject_date", + "(list_date,case_id)", + ), ] { for descending in [false, true] { let query = |after| CaseListQuery { - filter: CaseFilter::default(), + filter: CaseFilter { + subject_id, + ..Default::default() + }, search: None, from_ms: None, until_ms: None, @@ -1185,6 +1159,9 @@ async fn case_listing_migration_indexes_existing_guild_rows_for_every_seek() { range.contains(index) && range.contains("guild_id=? AND enrollment_id=?"), "{plan:?}" ); + if subject_id.is_some() { + assert!(range.contains("list_subject=?"), "{plan:?}"); + } if has_cursor { let comparison = if descending { '<' } else { '>' }; assert!(range.contains(&format!("{seek}{comparison}")), "{plan:?}"); @@ -1197,3 +1174,20 @@ async fn case_listing_migration_indexes_existing_guild_rows_for_every_seek() { } } } + +#[tokio::test] +async fn scoped_case_reads_map_rows_on_the_pooled_blocking_worker() -> Result<()> { + let f = Fixture::new(); + let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; + let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let scope = scope(&f, &store, ®, 10).await; + read_active_scope!(store, scope, |tx, _| { + let worker = std::thread::current().id(); + let mapped = tx.query_row("SELECT 1", (), |_| Ok(std::thread::current().id()))?; + assert_eq!(mapped, worker); + Ok(()) + }) + .await +} + +mod latency; diff --git a/src/db/guild_data/tests/cases/latency.rs b/src/db/guild_data/tests/cases/latency.rs new file mode 100644 index 000000000..9b24c089e --- /dev/null +++ b/src/db/guild_data/tests/cases/latency.rs @@ -0,0 +1,80 @@ +use super::*; + +#[tokio::test] +#[ignore = "local case history latency benchmark"] +async fn current_thread() { + measure_case_page_latency().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "local case history latency benchmark"] +async fn multi_thread() { + measure_case_page_latency().await; +} + +async fn measure_case_page_latency() { + let total: i64 = std::env::var("CASE_BENCH_ROWS") + .unwrap_or_else(|_| "24000".into()) + .parse() + .unwrap(); + assert!(total >= 8 * 41 && total % 8 == 0); + let f = Fixture::new(); + let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; + let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let scope = scope(&f, &store, ®, 10).await; + let raw = Connection::open(&f.store_path).unwrap(); + raw.execute_bounded( + "WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n = if subject.is_some() { + (0..8).rev().map(|i| 40 + i * (total / 8)).collect() + } else { + (total - 24..=total).rev().collect() + }; + let expected: Vec<_> = expected.iter().map(|id| format!("{id:032x}")).collect(); + let mut samples = Vec::new(); + for run in 0..26 { + let start = std::time::Instant::now(); + let page = store + .list_cases( + scope.clone(), + CaseListQuery { + filter: CaseFilter { + subject_id: subject, + ..Default::default() + }, + sort: CaseSort::Date, + descending: true, + after: None, + search: None, + from_ms: None, + until_ms: None, + include_total: false, + }, + 25, + CaseLimits::default(), + ) + .await + .unwrap(); + let us = start.elapsed().as_secs_f64() * 1e6; + let ids: Vec<_> = page.entries.iter().map(|(id, _)| id.as_str()).collect(); + assert_eq!(ids, expected); + assert_eq!(page.next.is_some(), subject.is_none()); + assert_eq!(page.total, None); + if run > 0 { + samples.push(us); + } + } + samples.sort_by(f64::total_cmp); + println!( + "rows={total} subject={subject:?} median_us={} p95_us={}", + samples[12], samples[23] + ); + } +} diff --git a/src/db/guild_data/tests/deletion_requests.rs b/src/db/guild_data/tests/deletion_requests.rs index 25cec89f6..cd0bc4676 100644 --- a/src/db/guild_data/tests/deletion_requests.rs +++ b/src/db/guild_data/tests/deletion_requests.rs @@ -18,8 +18,7 @@ fn now_ms() -> i64 { async fn ready() -> (Fixture, GuildDataStore, GuildDataScope) { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let scope = scope(&f, &store, ®, 10).await; (f, store, scope) } @@ -899,13 +898,31 @@ async fn interrupted_erasure_resumes_without_double_counting_or_early_completion } #[test] -fn mention_redaction_keeps_longer_ids_and_other_text() { - assert_eq!( - redact_mentions("<@42> 42 <@!42>.", 42).as_deref(), - Some("[removed] [removed] [removed].") - ); - assert_eq!(redact_mentions("142 421 <@420>", 42), None); - assert_eq!(redact_mentions("é42é", 42).as_deref(), Some("é[removed]é")); +fn mention_redaction_preserves_surrounding_text_and_other_decimal_ids() { + for subject in [1, 11, 42, 9007199254740993, i64::MAX] { + let id = subject.to_string(); + let parts = [ + (id.clone(), "[removed]".to_owned()), + (format!("<@{id}>"), "[removed]".into()), + (format!("<@!{id}>"), "[removed]".into()), + (format!("1{id}"), format!("1{id}")), + (format!("<@{id}0>"), format!("<@{id}0>")), + ("already [removed]".into(), "already [removed]".into()), + ]; + for (a, ar) in &parts { + for (b, br) in &parts { + for separator in [" ", "é", "。", "."] { + let original = format!("{a}{separator}{b}"); + let expected = format!("{ar}{separator}{br}"); + assert_eq!( + redact_mentions(&original, subject), + (original != expected).then_some(expected.clone()) + ); + assert_eq!(redact_mentions(&expected, subject), None); + } + } + } + } } #[tokio::test] @@ -1082,3 +1099,101 @@ async fn a_row_added_to_an_existing_request_keeps_its_start_time() { assert_eq!(replayed.state, DeletionState::Queued); assert_eq!(replayed.request_id, row.request_id); } + +#[tokio::test] +async fn case_pages_partition_the_sorted_rows_after_redaction() { + let (_f, store, scope) = ready().await; + let limits = CaseLimits::default(); + let mut facts = Vec::new(); + for n in 1..=12 { + let id = CaseId::try_from(format!("{n:032x}")).unwrap(); + let mut case = data(n); + case.subject_id = [11, 22, i64::MAX][n as usize % 3]; + case.occurred_at_ms = 1000 + n % 2; + store + .record_case(scope.clone(), id.clone(), case.clone(), limits) + .await + .unwrap(); + if case.subject_id == 11 { + case.subject_id = 0; + } + facts.push((id, case)); + } + let request = confirmed(&store, &scope, 11).await; + store + .begin_deletion_attempt(scope.clone(), request.clone(), NOW) + .await + .unwrap(); + assert!( + store + .redact_subject_cases(scope.clone(), request, 11, None, NOW) + .await + .unwrap() + .is_none() + ); + for sort in [CaseSort::Date, CaseSort::Subject] { + for subject_id in [None, Some(22), Some(i64::MAX), Some(99)] { + let mut expected: Vec<_> = facts + .iter() + .filter(|(_, case)| subject_id.is_none_or(|id| id == case.subject_id)) + .collect(); + expected.sort_by_key(|(id, case)| { + ( + if sort == CaseSort::Subject { + case.subject_id + } else { + case.occurred_at_ms + }, + id.as_str(), + ) + }); + for descending in [false, true] { + if descending { + expected.reverse(); + } + for size in [1, 2, 3, 4, 5, 12] { + let mut cursor = None; + let mut actual = Vec::new(); + loop { + let page = store + .list_cases( + scope.clone(), + CaseListQuery { + filter: CaseFilter { + subject_id, + ..Default::default() + }, + sort, + descending, + after: cursor, + search: None, + from_ms: None, + until_ms: None, + include_total: true, + }, + size, + limits, + ) + .await + .unwrap(); + assert!(page.next.is_none() || page.entries.len() == size as usize); + assert_eq!(page.total, Some(expected.len() as i64)); + actual.extend(page.entries.into_iter().map(|(id, _)| id)); + assert_eq!(page.next.is_some(), actual.len() < expected.len()); + if page.next.is_none() { + break; + } + cursor = page.next; + } + assert_eq!( + actual, + expected + .iter() + .map(|(id, _)| id.clone()) + .collect::>() + ); + } + } + } + } +} diff --git a/src/db/guild_data/tests/member_directory.rs b/src/db/guild_data/tests/member_directory.rs index c086c2652..a5c2956ad 100644 --- a/src/db/guild_data/tests/member_directory.rs +++ b/src/db/guild_data/tests/member_directory.rs @@ -1,30 +1,9 @@ +use super::bound_guild_fixture as ready; use super::*; use crate::db::write_budget::MemberSqlWrites; const SCHEMA_BATCH_LIMIT: u64 = 64 * 1024 * 1024; -async fn ready() -> (Fixture, GuildDataStore, GuildDataScope) { - let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); - let placement = f.placement(®, 10).await; - store - .bind_initial_placement(placement.clone()) - .await - .unwrap(); - let scope = GuildDataScope::new( - placement, - crate::db::GuildEnrollment { - guild_id: 10, - id: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(), - joined_at_ns: 100, - }, - ) - .unwrap(); - store.bind_initial_membership(scope.clone()).await.unwrap(); - (f, store, scope) -} - #[tokio::test] async fn shared_store_member_cleanup_and_erasure_preserve_the_other_guild() { let (f, store, scope) = ready().await; @@ -339,23 +318,34 @@ async fn member_name_sort_key_skips_empty_names_after_schema_22_upgrade() { let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; GuildDataStore::create_historical_store(f.options(), reg.clone(), 22).unwrap(); let raw = Connection::open(&f.store_path).unwrap(); - raw.execute_batch_bounded( - "INSERT INTO guild_member_directory ( - guild_id, enrollment_id, user_id, username, global_name, nickname, - is_current, observed_at_ms - ) VALUES - (10, 'members', 11, 'Zulu', 'Alpha', '', 1, 3000), - (10, 'members', 12, 'Bravo', '', NULL, 1, 3000), - (10, 'members', 13, '', '', '', 1, 3000)", - SCHEMA_BATCH_LIMIT, - ) - .unwrap(); + let mut expected = Vec::new(); + for nickname in [None, Some(""), Some("Zulu")] { + for global in [None, Some(""), Some("ÉLI")] { + for username in [None, Some(""), Some("Alpha")] { + let id = 11 + expected.len() as i64; + raw.execute_bounded( + "INSERT INTO guild_member_directory + (guild_id,enrollment_id,user_id,username,global_name,nickname,is_current,observed_at_ms) + VALUES (10,'members',?1,?2,?3,?4,1,3000)", + params![id, username, global, nickname], SCHEMA_BATCH_LIMIT, + ).unwrap(); + let key = [nickname, global, username] + .into_iter() + .flatten() + .find(|name| !name.is_empty()) + .map(str::to_ascii_lowercase) + .unwrap_or_else(|| id.to_string()); + expected.push((id, key)); + } + } + } + expected.sort_by(|(aid, a), (bid, b)| a.cmp(b).then(aid.cmp(bid))); drop(raw); let store = GuildDataStore::initialize(f.options(), reg).unwrap(); store .db - .with_conn(|conn| { + .with_conn(move |conn| { let mut stmt = conn.prepare( "SELECT user_id, name_sort_key FROM guild_member_directory INDEXED BY guild_member_sort_current_name @@ -365,14 +355,7 @@ async fn member_name_sort_key_skips_empty_names_after_schema_22_upgrade() { let rows = stmt .query_map((), |row| Ok((row.get::(0)?, row.get::(1)?)))? .collect::>>()?; - assert_eq!( - rows, - [ - (13, "13".into()), - (11, "alpha".into()), - (12, "bravo".into()) - ] - ); + assert_eq!(rows, expected); Ok(()) }) .await @@ -7501,8 +7484,7 @@ fn member_statement_bound(members: u64) -> u64 { async fn ready_guild(guild_id: i64) -> (Fixture, GuildDataStore, GuildDataScope) { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let placement = f.placement(®, guild_id).await; store .bind_initial_placement(placement.clone()) @@ -7580,8 +7562,7 @@ async fn ready_with_probe( ) -> (Fixture, GuildDataStore, GuildDataScope) { let _guard = crate::db_compat::enter_startup_probe(Some(probe.clone())); let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let placement = f.placement(®, 10).await; store .bind_initial_placement(placement.clone()) diff --git a/src/db/guild_data/tests/server_names.rs b/src/db/guild_data/tests/server_names.rs index 87c9ed507..cca5c355d 100644 --- a/src/db/guild_data/tests/server_names.rs +++ b/src/db/guild_data/tests/server_names.rs @@ -1,28 +1,7 @@ +use super::bound_guild_fixture as ready; use super::*; use crate::db::guild_data::server_names::{SERVER_NAME_CHANNEL_LIMIT, SERVER_NAME_ROLE_LIMIT}; -async fn ready() -> (Fixture, GuildDataStore, GuildDataScope) { - let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); - let placement = f.placement(®, 10).await; - store - .bind_initial_placement(placement.clone()) - .await - .unwrap(); - let scope = GuildDataScope::new( - placement, - crate::db::GuildEnrollment { - guild_id: 10, - id: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(), - joined_at_ns: 100, - }, - ) - .unwrap(); - store.bind_initial_membership(scope.clone()).await.unwrap(); - (f, store, scope) -} - fn role(id: &str, name: &str, position: i64) -> ServerRoleName { ServerRoleName { id: id.into(), diff --git a/src/db/guild_data/tests/snapshots.rs b/src/db/guild_data/tests/snapshots.rs index cd2ff96f6..f10b9382e 100644 --- a/src/db/guild_data/tests/snapshots.rs +++ b/src/db/guild_data/tests/snapshots.rs @@ -16,8 +16,7 @@ fn at(offset_ms: i64) -> i64 { async fn ready() -> (Fixture, StoreRegistration, GuildDataStore, GuildDataScope) { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let placement = f.placement(®, 10).await; store .bind_initial_placement(placement.clone()) @@ -1415,47 +1414,17 @@ async fn remote_capture_permit_wait_uses_the_captured_write_deadline() { Default::default(), ) .await; - let write_limit = Duration::from_millis(100); - let remote = GuildDataStore { - db: fixture.db_with_operation_timeout(write_limit), - expected: local.expected.clone(), - core: None, - }; - let clock = crate::db_compat::ManualClock::new(); - remote - .db - .runtime - .install_manual_clock(Some(std::sync::Arc::clone(&clock))); - let _held = std::sync::Arc::clone(&remote.db.permits) - .try_acquire_many_owned(2) - .unwrap(); - let capture = remote.observe_snapshot(scope, observation(41, Some("queued"), None, 1)); - tokio::pin!(capture); - - tokio::select! { - biased; - result = &mut capture => panic!("capture returned before checkout queued: {result:?}"), - () = std::future::ready(()) => {} - } - clock.advance(write_limit - Duration::from_millis(1)); - tokio::select! { - biased; - result = &mut capture => panic!("checkout returned before the write deadline: {result:?}"), - () = std::future::ready(()) => {} + for millis in [2, 100, 251] { + let write_limit = Duration::from_millis(millis); + let remote = GuildDataStore { + db: fixture.db_with_operation_timeout(write_limit), + expected: local.expected.clone(), + core: None, + }; + let capture = + remote.observe_snapshot(scope.clone(), observation(41, Some("queued"), None, 1)); + fixture + .assert_checkout_deadline(&remote.db, write_limit, capture) + .await; } - clock.advance(Duration::from_millis(1)); - let error = tokio::select! { - biased; - result = &mut capture => result.expect_err("capture succeeded at the deadline"), - () = std::future::ready(()) => panic!("capture still waiting at the captured write deadline"), - }; - - assert_eq!( - crate::db_compat::local_database_timeout_operation(&error), - Some(crate::db::WAIT_FOR_CONNECTION), - "{error:#}" - ); - assert_eq!(remote.db.connections.outage.failure_count(), 0); - assert!(fixture.take_statements().is_empty(), "capture started SQL"); - assert_eq!(remote.db.permits.available_permits(), 0); } diff --git a/src/db/guild_data/tests/tenant_logs.rs b/src/db/guild_data/tests/tenant_logs.rs index e3869837e..6c7a9c933 100644 --- a/src/db/guild_data/tests/tenant_logs.rs +++ b/src/db/guild_data/tests/tenant_logs.rs @@ -26,8 +26,7 @@ pub(super) async fn scope( #[tokio::test] async fn activity_log_events_are_not_guild_store_log_channels() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let scope = scope(&f, &store, ®, 10).await; let revision = store .log_channels(scope.clone()) @@ -49,8 +48,7 @@ async fn activity_log_events_are_not_guild_store_log_channels() { #[tokio::test] async fn log_mappings_are_membership_scoped_persistent_and_bounded_by_event_types() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; let snapshot = store.log_channels(a.clone()).await.unwrap(); @@ -101,8 +99,7 @@ async fn log_mappings_are_membership_scoped_persistent_and_bounded_by_event_type #[tokio::test] async fn invalid_missing_and_different_membership_never_read_or_mutate() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let p = f.placement(®, 10).await; let e = enrollment(10, 100); let s = GuildDataScope::new(p.clone(), e.clone()).unwrap(); @@ -172,8 +169,7 @@ async fn invalid_missing_and_different_membership_never_read_or_mutate() { #[tokio::test] async fn scoped_data_rechecks_store_and_placement_inside_transaction() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let rev = store .log_channels(a.clone()) @@ -209,8 +205,7 @@ async fn scoped_data_rechecks_store_and_placement_inside_transaction() { #[tokio::test] async fn concurrent_edits_use_revision_cas_and_noop_edits_write_nothing() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let rev = store .log_channels(a.clone()) @@ -267,8 +262,7 @@ async fn concurrent_edits_use_revision_cas_and_noop_edits_write_nothing() { #[tokio::test] async fn closing_a_membership_removes_mappings_and_cannot_be_reopened() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let b = scope(&f, &store, ®, 20).await; for s in [&a, &b] { @@ -328,8 +322,7 @@ async fn closing_a_membership_removes_mappings_and_cannot_be_reopened() { #[tokio::test] async fn sql_scope_guards_work_without_foreign_keys_and_events_match_shared_types() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let revision = store .log_channels(a.clone()) @@ -422,8 +415,7 @@ async fn version_one_upgrade_preserves_identity_bindings_and_refuses_wrong_ident #[tokio::test] async fn failed_close_rolls_back_mapping_removal_and_repeated_close_is_write_free() { let f = Fixture::new(); - let reg = f.registration(StoreId::new(), StorePolicy::Shared).await; - let store = GuildDataStore::initialize(f.options(), reg.clone()).unwrap(); + let (reg, store) = f.shared_store().await; let a = scope(&f, &store, ®, 10).await; let revision = store .log_channels(a.clone()) diff --git a/src/db/tests.rs b/src/db/tests.rs index 654dd9e59..94a7febe6 100644 --- a/src/db/tests.rs +++ b/src/db/tests.rs @@ -1930,31 +1930,42 @@ fn event_row_snowflakes_serialize_as_strings() { fn insert_event_query_events_roundtrips_data_snowflakes_as_strings() { let tmp = tmp_db_path("event_data_sf"); let db = Db::open(&tmp, 2).unwrap(); - let guild = 11i64; - let snow = 9007199254740993u64; - tokio_test_block_on(crate::db::insert_event( - &db, - guild, - "message_delete", - Some(snow as i64), - None, - &serde_json::json!({ - "channel_id": snow, - "message_id": 99, - "nested": { "id": snow + 1 }, - }), - )) - .unwrap(); - - let rows = tokio_test_block_on(crate::db::query_events(&db, guild, None, None, 10)).unwrap(); - assert_eq!(rows.len(), 1); - let data: serde_json::Value = serde_json::from_str(rows[0].data.as_deref().unwrap()).unwrap(); - assert_eq!(data["channel_id"], "9007199254740993"); - assert_eq!(data["message_id"], 99); - assert_eq!(data["nested"]["id"], "9007199254740994"); - // Top-level EventRow IDs are also strings on the wire. - let wire = serde_json::to_value(&rows[0]).unwrap(); - assert_eq!(wire["user_id"], "9007199254740993"); + let safe = (1i64 << 53) - 1; + for (index, id) in [1, safe - 1, safe, safe + 1, safe + 2, i64::MAX] + .into_iter() + .enumerate() + { + let guild = 11 + index as i64; + let nested = id as u64 + 1; + tokio_test_block_on(crate::db::insert_event( + &db, + guild, + "message_delete", + Some(id), + None, + &serde_json::json!({"channel_id": id, "message_id": 99, "nested": {"id": nested}}), + )) + .unwrap(); + let rows = + tokio_test_block_on(crate::db::query_events(&db, guild, None, None, 10)).unwrap(); + assert_eq!(rows.len(), 1); + let data: serde_json::Value = + serde_json::from_str(rows[0].data.as_deref().unwrap()).unwrap(); + for (actual, value) in [ + (&data["channel_id"], id as u64), + (&data["nested"]["id"], nested), + ] { + let expected = if value <= safe as u64 { + serde_json::json!(value) + } else { + serde_json::json!(value.to_string()) + }; + assert_eq!(actual, &expected); + } + assert_eq!(data["message_id"], 99); + let wire = serde_json::to_value(&rows[0]).unwrap(); + assert_eq!(wire["user_id"], id.to_string()); + } cleanup_db(&tmp); } diff --git a/src/db/tests/moderation_enrollments.rs b/src/db/tests/moderation_enrollments.rs index bcc382287..9f90a5000 100644 --- a/src/db/tests/moderation_enrollments.rs +++ b/src/db/tests/moderation_enrollments.rs @@ -2179,94 +2179,107 @@ async fn delayed_old_bot_echo_does_not_replace_an_attributed_manual_gateway_ban( } #[tokio::test] -async fn same_timestamp_redelivery_and_distinct_reban_diverge_by_audit_entry_id() { +async fn known_audit_deliveries_preserve_history_and_the_active_ban_after_every_prefix() { + const IDS: [Option; 3] = [Some(101), Some(9_007_199_254_740_993), None]; let f = Fixture::new(); - let scope = enroll_guild(&f.db, 10, 100).await.unwrap().unwrap(); - let at = "2024-03-01T00:00:30+00:00"; - let first = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - None, - None, - Some(at), - false, - None, - false, - Some(5_501), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id } = first else { - panic!("first delivery must insert, got {first:?}"); - }; - let redelivery = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - None, - None, - Some(at), - false, - None, - false, - Some(5_501), - ) - .await - .unwrap(); - assert_eq!(redelivery, GatewayBanWrite::Existing { row_id }); - assert_eq!( - member_ban_events( - &query_enrolled_events(&f.db, scope.clone(), Some("member_ban"), Some(55), 50) - .await - .unwrap() - ), - 1 - ); - - let first = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 56, - None, - None, - Some(at), - false, - None, - true, - Some(5_601), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id: old_id } = first else { - panic!("first ban must insert, got {first:?}"); - }; - let second = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 56, - None, - None, - Some(at), - false, - None, - true, - Some(5_602), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id: new_id } = second else { - panic!("distinct audit id at the same timestamp must insert, got {second:?}"); - }; - assert_ne!(old_id, new_id); - assert_eq!( - member_ban_events( - &query_enrolled_events(&f.db, scope, Some("member_ban"), Some(56), 50) - .await - .unwrap() - ), - 2 - ); + let mut guild = 10; + // Two distinct audit identities and an unban. Reusing an identity + // leaves the current mirror alone, even after the original row closed. + for times in [[30, 30, 30], [0, 30, 31], [0, 30, 45]] { + for prechecks in [[false; 3], [false, true, true], [true; 3]] { + for second in IDS { + for third in IDS { + guild += 1; + let enrollment = enroll_guild(&f.db, guild, 100).await.unwrap().unwrap(); + let mut seen = std::collections::BTreeMap::new(); + let mut active = None; + let trace = [Some(101), second, third]; + for ((audit, time), was_banned) in trace.into_iter().zip(times).zip(prechecks) { + if let Some(id) = audit { + let at = format!("2024-03-01T00:00:{time:02}+00:00"); + let result = record_gateway_ban_with_audit( + &f.db, + Some(enrollment.clone()), + 55, + was_banned.then_some("member"), + None, + Some(&at), + false, + None, + was_banned, + Some(id), + ) + .await + .unwrap(); + if let Some(&original) = seen.get(&id) { + assert_eq!( + result, + GatewayBanWrite::Existing { + row_id: active.unwrap_or(original) + }, + "{trace:?}" + ); + } else { + let GatewayBanWrite::Recorded { row_id } = result else { + panic!("new audit id {id} in {trace:?}: {result:?}"); + }; + assert!(!seen.values().any(|&previous| previous == row_id)); + seen.insert(id, row_id); + active = Some(row_id); + } + } else { + mark_enrolled_unbanned(&f.db, Some(enrollment.clone()), 55) + .await + .unwrap(); + active = None; + } + let rows = list_enrolled_bans(&f.db, enrollment.clone(), 10) + .await + .unwrap(); + assert_eq!(rows.len(), seen.len()); + assert_eq!( + rows.iter() + .filter(|r| r.active) + .map(|r| r.id) + .collect::>(), + active.into_iter().collect::>(), + "{trace:?}" + ); + let events = query_enrolled_events( + &f.db, + enrollment.clone(), + Some("member_ban"), + Some(55), + 50, + ) + .await + .unwrap(); + assert_eq!(events.len(), seen.len(), "{trace:?}"); + let payloads: Vec = events + .iter() + .map(|event| { + serde_json::from_str(event.data.as_deref().unwrap()).unwrap() + }) + .collect(); + for (id, row) in &seen { + let wire_id = if *id == 101 { + serde_json::json!(101) + } else { + serde_json::json!(id.to_string()) + }; + assert!( + payloads + .iter() + .any(|event| event["audit_entry_id"] == wire_id + && event["ban_id"] == *row), + "{trace:?}: expected audit {id} for ban {row}" + ); + } + } + } + } + } + } } #[tokio::test] @@ -2384,108 +2397,6 @@ async fn stale_queued_audit_id_does_not_attach_to_later_ban_within_sixty_seconds assert_eq!(second, GatewayBanWrite::Existing { row_id: first_id }); } -#[tokio::test] -async fn replay_with_known_audit_and_no_active_mirror_stays_idempotent() { - let f = Fixture::new(); - let scope = enroll_guild(&f.db, 10, 100).await.unwrap().unwrap(); - let first = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - None, - None, - Some("2024-03-01T00:00:00+00:00"), - false, - None, - false, - Some(50_001), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id } = first else { - panic!("first manual ban must insert, got {first:?}"); - }; - mark_enrolled_unbanned(&f.db, Some(scope.clone()), 55) - .await - .unwrap(); - let replay = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - None, - None, - Some("2024-03-01T00:00:45+00:00"), - false, - None, - false, - Some(50_001), - ) - .await - .unwrap(); - assert_eq!(replay, GatewayBanWrite::Existing { row_id }); - assert_eq!( - list_enrolled_bans(&f.db, scope, 10) - .await - .unwrap() - .iter() - .filter(|row| row.active) - .count(), - 0 - ); -} - -#[tokio::test] -async fn distinct_manual_gateway_bans_within_sixty_seconds_use_audit_entry_ids() { - let f = Fixture::new(); - let scope = enroll_guild(&f.db, 10, 100).await.unwrap().unwrap(); - let first = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - Some("member"), - None, - Some("2024-03-01T00:00:00+00:00"), - false, - None, - false, - Some(10_001), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id: old_id } = first else { - panic!("first manual ban must insert, got {first:?}"); - }; - let replacement = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - Some("member"), - None, - Some("2024-03-01T00:00:30+00:00"), - false, - None, - true, - Some(10_002), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id: new_id } = replacement else { - panic!("distinct audit ids within 60s must insert, got {replacement:?}"); - }; - assert_ne!(new_id, old_id); - assert_eq!( - member_ban_events( - &query_enrolled_events(&f.db, scope.clone(), Some("member_ban"), Some(55), 50) - .await - .unwrap() - ), - 2 - ); - let rows = list_enrolled_bans(&f.db, scope, 10).await.unwrap(); - assert_eq!(rows.iter().filter(|row| row.active).count(), 1); - assert_eq!(rows.iter().find(|row| row.active).unwrap().id, new_id); -} - #[tokio::test] async fn sub_sixty_second_manual_reban_without_unban_records_distinct_gateway_ban() { let f = Fixture::new(); @@ -2611,73 +2522,6 @@ async fn id_less_delivery_after_stored_audit_id_can_replace_stale_mirror_beyond_ assert_eq!(rows.iter().find(|row| row.active).unwrap().id, new_id); } -#[tokio::test] -async fn replay_of_superseded_audit_id_leaves_newer_active_mirror() { - let f = Fixture::new(); - let scope = enroll_guild(&f.db, 10, 100).await.unwrap().unwrap(); - let first = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - None, - None, - Some("2024-03-01T00:00:00+00:00"), - false, - None, - true, - Some(12_001), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id: first_id } = first else { - panic!("first ban must insert, got {first:?}"); - }; - let second = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - None, - None, - Some("2024-03-01T00:00:30+00:00"), - false, - None, - true, - Some(12_002), - ) - .await - .unwrap(); - let GatewayBanWrite::Recorded { row_id: active_id } = second else { - panic!("second ban must insert, got {second:?}"); - }; - assert_ne!(first_id, active_id); - let replay = record_gateway_ban_with_audit( - &f.db, - Some(scope.clone()), - 55, - None, - None, - Some("2024-03-01T00:00:31+00:00"), - false, - None, - true, - Some(12_001), - ) - .await - .unwrap(); - assert_eq!(replay, GatewayBanWrite::Existing { row_id: active_id }); - assert_eq!( - member_ban_events( - &query_enrolled_events(&f.db, scope.clone(), Some("member_ban"), Some(55), 50) - .await - .unwrap() - ), - 2 - ); - let rows = list_enrolled_bans(&f.db, scope, 10).await.unwrap(); - assert_eq!(rows.iter().filter(|row| row.active).count(), 1); - assert_eq!(rows.iter().find(|row| row.active).unwrap().id, active_id); -} - #[tokio::test] async fn stringified_snowflake_audit_entry_id_dedupes_redelivery() { let f = Fixture::new(); diff --git a/src/db/tests/remote_stream.rs b/src/db/tests/remote_stream.rs index 07dbe1e23..56997cd08 100644 --- a/src/db/tests/remote_stream.rs +++ b/src/db/tests/remote_stream.rs @@ -693,6 +693,41 @@ impl HranaFixture { .collect() } + pub(in crate::db) async fn assert_checkout_deadline( + &self, + db: &Db, + limit: Duration, + operation: impl std::future::Future>, + ) { + let clock = install_clock(db); + let _held = Arc::clone(&db.permits).try_acquire_many_owned(2).unwrap(); + tokio::pin!(operation); + // Poll at admission, just before expiry, and exactly at the original + // deadline. The pool's independent timeout stays paused throughout. + for elapsed in [Duration::ZERO, limit - Duration::from_millis(1)] { + clock.advance(elapsed); + tokio::select! { + biased; + result = &mut operation => panic!("checkout returned early: {result:?}"), + () = std::future::ready(()) => {} + } + } + clock.advance(Duration::from_millis(1)); + let error = tokio::select! { + biased; + result = &mut operation => result.expect_err("checkout succeeded at expiry"), + () = std::future::ready(()) => panic!("checkout still waiting at its deadline"), + }; + assert_eq!( + local_database_timeout_operation(&error), + Some(WAIT_FOR_CONNECTION), + "{error:#}" + ); + assert_eq!(db.connections.outage.failure_count(), 0); + assert!(self.take_statements().is_empty(), "checkout started SQL"); + assert_eq!(db.permits.available_permits(), 0); + } + pub(in crate::db) fn take_statements(&self) -> Vec { std::mem::take(&mut self.state.lock().unwrap().statements) } @@ -1614,46 +1649,13 @@ async fn assert_advised_fallback_checkout_timeout( #[tokio::test(start_paused = true)] async fn advised_claim_promote_permit_wait_uses_the_captured_write_deadline() { let fixture = HranaFixture::start().await; - let write_limit = Duration::from_millis(100); - let remote = fixture.db_with_operation_timeout(write_limit); - let clock = install_clock(&remote); - let _held = Arc::clone(&remote.permits) - .try_acquire_many_owned(2) - .unwrap(); - let claim = claim_advised_bot_action(&remote, 100); - tokio::pin!(claim); - - // Poll with both permits held so the claim captures its deadline and queues. - tokio::select! { - biased; - result = &mut claim => panic!("claim returned before checkout queued: {result:?}"), - () = std::future::ready(()) => {} - } - // Advance only the write clock. The separate pool timeout stays paused. - clock.advance(write_limit - Duration::from_millis(1)); - tokio::select! { - biased; - result = &mut claim => panic!("checkout returned before the write deadline: {result:?}"), - () = std::future::ready(()) => {} + for millis in [2, 100, 251] { + let write_limit = Duration::from_millis(millis); + let remote = fixture.db_with_operation_timeout(write_limit); + fixture + .assert_checkout_deadline(&remote, write_limit, claim_advised_bot_action(&remote, 100)) + .await; } - clock.advance(Duration::from_millis(1)); - let error = tokio::select! { - biased; - result = &mut claim => result.expect_err("promotion claimed work at the deadline"), - () = std::future::ready(()) => panic!("promotion still waiting at the captured write deadline"), - }; - - assert_eq!( - local_database_timeout_operation(&error), - Some(WAIT_FOR_CONNECTION), - "{error:#}" - ); - assert_eq!(remote.connections.outage.failure_count(), 0); - assert!( - fixture.take_statements().is_empty(), - "promotion started SQL" - ); - assert_eq!(remote.permits.available_permits(), 0); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -1829,11 +1831,20 @@ async fn advised_claim_busy_fallback_expiry_releases_primary_probe() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn advised_claim_busy_fallback_times_out_at_original_deadline() { + for spent in [ + Duration::from_millis(1), + Duration::from_secs(3), + Duration::from_secs(4), + ] { + check_busy_fallback_deadline(spent).await; + } +} + +async fn check_busy_fallback_deadline(spent: Duration) { let path = super::tmp_db_path("remote_action_claim_fallback_deadline"); let (local, fixture, remote, action) = advised_claim_fallback_fixture(&path).await; invalidate_advised_claim_snapshot(&fixture, &path, &action.id); let clock = install_clock(&remote); - let spent = Duration::from_secs(3); let write_limit = remote.connections.runtime.operation_limit().unwrap(); let due_clock = Arc::clone(&clock); *remote.after_advised_due_read.lock().unwrap() = Some(Box::new(move || { @@ -2158,8 +2169,10 @@ async fn advised_claim_promotes_after_the_interactive_deadline() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn advised_claim_aborts_promotion_after_the_write_deadline() { - advised_claim_after_due_read(Duration::from_millis(5500), false).await; +async fn advised_claim_promotion_changes_outcome_at_the_original_write_deadline() { + for millis in [4999, 5000, 5001, 5500] { + advised_claim_after_due_read(Duration::from_millis(millis), millis < 5000).await; + } } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/src/db_compat.rs b/src/db_compat.rs index 0febcd281..10c1f7644 100644 --- a/src/db_compat.rs +++ b/src/db_compat.rs @@ -1207,6 +1207,7 @@ pub struct Connection { config_version: Arc, capacity_limits: CapacityLimits, read_only: bool, + pub(crate) local_file: bool, /// Copied from the pool at checkout. `None` leaves commits unchanged. expected_lease_owner: Option, /// Guild-store writer generation snapshotted at checkout. `None` skips the epoch check. @@ -1703,6 +1704,7 @@ impl Connection { config_version: Arc::new(std::sync::atomic::AtomicU64::new(0)), capacity_limits: CapacityLimits::default(), read_only: false, + local_file: true, expected_lease_owner: None, expected_writer_generation: None, expected_launcher: None, @@ -1726,6 +1728,8 @@ impl Connection { config_version: Arc::new(std::sync::atomic::AtomicU64::new(0)), capacity_limits: CapacityLimits::default(), read_only: false, + // The public constructor accepts an opaque libSQL database. + local_file: false, expected_lease_owner: None, expected_writer_generation: None, expected_launcher: None, @@ -1735,6 +1739,15 @@ impl Connection { }) } + /// Enter only from a pooled blocking worker, for the duration of a local + /// store read. The synchronous SQL facade can then use that same worker. + pub(crate) fn enter_local_read_worker(&self) -> Option> { + (self.local_file + && tokio::runtime::Handle::current().runtime_flavor() + == tokio::runtime::RuntimeFlavor::CurrentThread) + .then(|| self.runtime.handle.enter()) + } + pub(crate) fn set_expected_lease_owner(&mut self, owner: Option) { self.expected_lease_owner = owner; } @@ -2035,6 +2048,7 @@ impl Connection { }, primary, inner: TransactionHandle::Active(inner), + local_file: self.local_file, database: Arc::clone(&self.database), connection_health: Arc::clone(&self.health), connection_config_version: Arc::clone(&self.config_version), @@ -2453,6 +2467,7 @@ enum PrimaryReceipt { } pub struct Transaction { + local_file: bool, inner: TransactionHandle, database: Arc, runtime: DbRuntime, @@ -3211,7 +3226,13 @@ impl Transaction { self.note_remote_stream_loss(error); } let inner = self.inner.take(); - self.runtime.drop_transaction(inner); + if self.local_file && result.is_ok() { + // Local libSQL has no asynchronous close callback. ROLLBACK above + // finished the transaction, so its handle can drop on this worker. + drop(inner); + } else { + self.runtime.drop_transaction(inner); + } match result { Ok(_) => Ok(()), // The rows were already collected. The provider closing the stream @@ -3232,6 +3253,41 @@ impl Transaction { } } + /// Reuse the parser verdict for parameterized, application-generated + /// templates. Bindings and database results never enter this cache. + pub(crate) fn prepare_read_template(&self, sql: &str) -> Result { + use std::collections::VecDeque; + const CAPACITY: usize = 16; + static TEMPLATES: parking_lot::RwLock>> = + parking_lot::RwLock::new(VecDeque::new()); + if sql.len() > 4096 { + return self.prepare(sql); + } + if !TEMPLATES.read().iter().any(|entry| entry.as_ref() == sql) { + require_read_sql(sql)?; + let mut templates = TEMPLATES.write(); + if !templates.iter().any(|entry| entry.as_ref() == sql) { + if templates.len() == CAPACITY { + templates.pop_front(); + } + templates.push_back(sql.into()); + } + } + self.prepare_validated_read(sql) + } + + fn prepare_validated_read(&self, sql: &str) -> Result { + let inner = + self.map_stream(self.drive("transaction prepare", self.inner().prepare(sql)))?; + Ok(Statement { + inner: RuntimeOwned::new(inner, &self.runtime), + runtime: self.runtime.clone(), + read_deadline: self.active_read_deadline(), + write_deadline: self.write_deadline, + stream: Arc::clone(&self.stream), + }) + } + fn inner(&self) -> &libsql::Transaction { self.inner.active() } @@ -3559,15 +3615,7 @@ impl SqlExecutor for Transaction { fn prepare(&self, sql: &str) -> Result { require_read_sql(sql)?; - let inner = - self.map_stream(self.drive("transaction prepare", self.inner().prepare(sql)))?; - Ok(Statement { - inner: RuntimeOwned::new(inner, &self.runtime), - runtime: self.runtime.clone(), - read_deadline: self.active_read_deadline(), - write_deadline: self.write_deadline, - stream: Arc::clone(&self.stream), - }) + self.prepare_validated_read(sql) } fn record_config_version(&self, version: u64) { @@ -3618,6 +3666,35 @@ mod tests { use super::*; + #[test] + fn cached_read_templates_use_current_snapshot_and_parameters() -> Result<()> { + let conn = Connection::open(":memory:")?; + conn.execute_batch_bounded( + "CREATE TABLE counter(value INTEGER); INSERT INTO counter VALUES(1)", + 2_000_000, + )?; + for stored in [1i64, 2, 3] { + conn.execute_bounded("UPDATE counter SET value=?1", params![stored], 2_000_000)?; + let tx = conn.transaction_primary_snapshot()?; + for padding in [0, 1, 4096, 0] { + let sql = format!("SELECT value + ?1 FROM counter{}", " ".repeat(padding)); + for bound in [-2i64, 0, 2] { + let values = tx + .prepare_read_template(&sql)? + .query_map(params![bound], |row| Ok(row.get::(0)?))? + .collect::>>()?; + assert_eq!(values, [stored + bound]); + } + } + assert!( + tx.prepare_read_template("UPDATE counter SET value=0") + .is_err() + ); + tx.finish_read()?; + } + Ok(()) + } + #[test] fn read_only_connection_opens_primary_snapshot_and_refuses_primary_write() { let mut connection = Connection::open(":memory:").unwrap(); diff --git a/src/ids.rs b/src/ids.rs index 68c9aeeb9..88aa8d7be 100644 --- a/src/ids.rs +++ b/src/ids.rs @@ -33,10 +33,6 @@ where fn visit_str(self, v: &str) -> Result { v.trim().parse().map_err(E::custom) } - - fn visit_string(self, v: String) -> Result { - self.visit_str(&v) - } } deserializer.deserialize_any(U64Visitor) } @@ -65,10 +61,6 @@ where fn visit_str(self, v: &str) -> Result { v.trim().parse().map_err(E::custom) } - - fn visit_string(self, v: String) -> Result { - self.visit_str(&v) - } } deserializer.deserialize_any(I64Visitor) } @@ -139,10 +131,6 @@ where fn visit_str(self, v: &str) -> Result, E> { v.trim().parse().map(Some).map_err(E::custom) } - - fn visit_string(self, v: String) -> Result, E> { - self.visit_str(&v) - } } deserializer.deserialize_any(OptVisitor) } @@ -190,10 +178,6 @@ where } t.parse().map(Some).map_err(E::custom) } - - fn visit_string(self, v: String) -> Result, E> { - self.visit_str(&v) - } } deserializer.deserialize_any(OptVisitor) } @@ -213,7 +197,7 @@ where fn visit_seq>(self, mut seq: A) -> Result, A::Error> { let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0)); - while let Some(v) = seq.next_element::()? { + while let Some(v) = seq.next_element::()? { out.push(v.0); } Ok(out) @@ -234,16 +218,6 @@ where seq.end() } -/// Newtype used only inside `de_u64_vec`. -#[derive(Debug)] -struct SnowflakeU64(u64); - -impl<'de> Deserialize<'de> for SnowflakeU64 { - fn deserialize>(deserializer: D) -> Result { - Ok(Self(de_u64(deserializer)?)) - } -} - /// Transparent u64 that serializes as a string and deserializes from string|int. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Snowflake(pub u64); @@ -281,31 +255,24 @@ pub const JS_MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1; /// `JSON.parse` without corrupting Discord snowflakes (`channel_id`, /// `message_id`, …). Values already strings / small numbers are unchanged. pub fn stringify_js_unsafe_integers(value: &serde_json::Value) -> serde_json::Value { - use serde_json::{Map, Value}; + let mut result = value.clone(); + stringify_in_place(&mut result); + result +} + +fn stringify_in_place(value: &mut serde_json::Value) { + use serde_json::Value; match value { - Value::Object(map) => { - let mut out = Map::with_capacity(map.len()); - for (k, v) in map { - out.insert(k.clone(), stringify_js_unsafe_integers(v)); - } - Value::Object(out) - } - Value::Array(arr) => Value::Array(arr.iter().map(stringify_js_unsafe_integers).collect()), - Value::Number(n) => { - if let Some(u) = n.as_u64() { - if u > JS_MAX_SAFE_INTEGER { - return Value::String(u.to_string()); - } - } else if let Some(i) = n.as_i64() { - let abs = i.unsigned_abs(); - if abs > JS_MAX_SAFE_INTEGER { - return Value::String(i.to_string()); - } - } - // Preserve exact representation for safe integers / floats. - Value::Number(n.clone()) - } - other => other.clone(), + Value::Object(map) => map.values_mut().for_each(stringify_in_place), + Value::Array(items) => items.iter_mut().for_each(stringify_in_place), + Value::Number(n) + if n.as_u64().is_some_and(|v| v > JS_MAX_SAFE_INTEGER) + || n.as_i64() + .is_some_and(|v| v.unsigned_abs() > JS_MAX_SAFE_INTEGER) => + { + *value = Value::String(n.to_string()); + } + _ => {} } } @@ -313,7 +280,10 @@ pub fn stringify_js_unsafe_integers(value: &serde_json::Value) -> serde_json::Va /// WebUI wire. Non-JSON blobs are returned unchanged. pub fn wire_safe_event_data_json(raw: &str) -> String { match serde_json::from_str::(raw) { - Ok(v) => stringify_js_unsafe_integers(&v).to_string(), + Ok(mut value) => { + stringify_in_place(&mut value); + value.to_string() + } Err(_) => raw.to_string(), } } @@ -403,6 +373,35 @@ mod tests { assert_eq!(n.user, Some(99)); } + #[test] + fn wire_event_integers_preserve_the_exact_value_at_every_bit_boundary() { + // Both sides of every power of two, including the JS precision boundary + // and the extremes of serde_json's integer domain. + for bit in 0..=64 { + for offset in -1..=1 { + for sign in [-1, 1] { + let n = sign * ((1_i128 << bit) + offset); + if !(i128::from(i64::MIN)..=i128::from(u64::MAX)).contains(&n) { + continue; + } + let raw = format!(r#"{{"rows":[{n},"{n}",null,true,1.5]}}"#); + let wire = wire_safe_event_data_json(&raw); + let parsed: serde_json::Value = serde_json::from_str(&wire).unwrap(); + let exact = if n.abs() < (1_i128 << 53) { + serde_json::from_str(&n.to_string()).unwrap() + } else { + json!(n.to_string()) + }; + assert_eq!( + parsed, + json!({"rows": [exact, n.to_string(), null, true, 1.5]}) + ); + assert_eq!(wire_safe_event_data_json(&wire), wire); + } + } + } + assert_eq!(wire_safe_event_data_json("legacy text"), "legacy text"); + } #[test] fn stringify_js_unsafe_integers_rewrites_snowflakes_only() { let v = json!({ diff --git a/src/normalize.rs b/src/normalize.rs index da611e85b..ab50bc047 100644 --- a/src/normalize.rs +++ b/src/normalize.rs @@ -389,26 +389,21 @@ mod tests { } #[test] - fn ascii_normalize_matches_unicode_pipeline_for_all_ascii_bytes() { - let all_ascii: String = (0u8..128).map(char::from).collect(); - for collapse in [false, true] { - let expected: String = { - let mut out = String::new(); - let mut prev: Option = None; - for c in all_ascii.nfd().flat_map(|c| c.to_lowercase()) { - if is_zero_width(c) || is_combining_mark(c) { - continue; - } - let c = leetspeak(c).unwrap_or(c); - if collapse && prev == Some(c) { - continue; - } - prev = Some(c); - out.push(c); + fn ascii_normalize_matches_unicode_pipeline_for_every_adjacent_pair() { + for a in 0..=127u8 { + for b in 0..=127u8 { + let pair = [a, b]; + let input = std::str::from_utf8(&pair).unwrap(); + // The stripped prefix selects the general Unicode implementation. + let unicode = format!("\u{200b}{input}"); + for collapse in [false, true] { + assert_eq!( + normalize_text(input, collapse), + normalize_text(&unicode, collapse), + "pair {pair:?}, collapse {collapse}" + ); } - out - }; - assert_eq!(normalize_text(&all_ascii, collapse), expected); + } } } diff --git a/src/templates.rs b/src/templates.rs index 04371e172..b2a2af263 100644 --- a/src/templates.rs +++ b/src/templates.rs @@ -994,6 +994,44 @@ mod presentation_tests { } } + #[test] + fn compact_duration_recovers_seconds_and_keeps_all_intermediate_units() { + let units = [ + ("y", 31_104_000u64), + ("mo", 2_592_000), + ("w", 604_800), + ("d", 86_400), + ("h", 3600), + ("m", 60), + ("s", 1), + ]; + for (_, scale) in units { + for multiple in [1, 2, 7, 12, 30, 59, 60, u64::MAX / scale] { + let base = multiple * scale; + for seconds in [base.saturating_sub(1), base, base.saturating_add(1)] { + let rendered = format_duration(seconds); + let mut total = 0u64; + let mut previous = None; + for token in rendered.split_whitespace() { + let end = token.find(|c: char| !c.is_ascii_digit()).unwrap(); + let value: u64 = token[..end].parse().unwrap(); + let index = units + .iter() + .position(|(unit, _)| unit == &&token[end..]) + .unwrap(); + if let Some(last) = previous { + assert_eq!(index, last + 1, "{rendered}"); + } + total += value * units[index].1; + previous = Some(index); + } + assert_eq!(total, seconds, "{rendered}"); + assert_eq!(format_compact_duration(seconds), rendered); + } + } + } + } + /// Discord snowflakes (application, client, server and user IDs) are 17+ digits. fn has_snowflake(text: &str) -> bool { text.split(|c: char| !c.is_ascii_digit()) diff --git a/tests/models/case-pagination.smt2 b/tests/models/case-pagination.smt2 new file mode 100644 index 000000000..2ddaf7bd7 --- /dev/null +++ b/tests/models/case-pagination.smt2 @@ -0,0 +1,70 @@ +(set-logic QF_LIA) +; A case ID is its rank under SQLite's binary ordering of fixed-width hex IDs. +; A row is identified by (sort key, case ID), within one fixed enrollment. +(define-fun lt ((a Int) (i Int) (b Int) (j Int)) Bool + (or (< a b) (and (= a b) (< i j)))) +(declare-const a Int) +(declare-const i Int) +(declare-const b Int) +(declare-const j Int) +(declare-const c Int) +(declare-const k Int) +; Any two distinct case IDs with arbitrary integer sort keys have one ordering. +(push) +(assert (distinct i j)) +(assert (= (lt a i b j) (lt b j a i))) +(check-sat) +(pop) +; Transitive strict ordering, hence a progressing cursor cannot revisit a row. +(push) +(assert (and (lt a i b j) (lt b j c k) (not (lt a i c k)))) +(check-sat) +(pop) +; Before the fix a valid redacted subject generated an invalid continuation. +(push) +(assert (= a 0)) +(assert (not (> a 0))) +(check-sat) +(get-value (a)) +(pop) +; Every valid subject key passes the corrected cursor value validation. +(push) +(declare-const redacted Bool) +(assert (or (> a 0) (and redacted (= a 0)))) +(assert (not (>= a 0))) +(check-sat) +(pop) + +; Reduce either direction of a finite, uniquely ordered snapshot to its rank 0..n-1. +; The page after k rows consumes min(size,n-k). The LIMIT size+1 lookahead +; requests another page exactly when a row remains after the returned slice. +(declare-const n Int) +(declare-const seen Int) +(declare-const size Int) +(declare-const r Int) +(define-fun take () Int (ite (< (- n seen) size) (- n seen) size)) +(define-fun stop () Int (+ seen take)) +(push) +(assert (and (<= 0 seen n) (> size 0))) +; Test termination progress, exact continuation, and disjoint coverage of every rank. +(assert (or (> stop n) (< stop seen) + (and (< seen n) (<= stop seen)) + (not (= (> (- n seen) size) (< stop n))) + (and (<= 0 r) (< r n) + (not (= 1 (+ (ite (< r seen) 1 0) + (ite (and (<= seen r) (< r stop)) 1 0) + (ite (<= stop r) 1 0))))))) +(check-sat) +(pop) + +; An ASCII prefix is zero characters without a tag or exactly 27 with one. +; Character-prefix truncation distributes over concatenation in this domain. +(declare-const prefix Int) +(declare-const human Int) +(push) +(assert (or (= prefix 0) (= prefix 27))) +(assert (>= human 0)) +(assert (not (= (ite (< (+ prefix human) 512) (+ prefix human) 512) + (+ prefix (ite (< human (- 512 prefix)) human (- 512 prefix)))))) +(check-sat) +(pop) diff --git a/tests/models/read-templates-and-deadlines.smt2 b/tests/models/read-templates-and-deadlines.smt2 new file mode 100644 index 000000000..45e0e5cf8 --- /dev/null +++ b/tests/models/read-templates-and-deadlines.smt2 @@ -0,0 +1,45 @@ +; A cache entry is the complete SQL byte string. read models the (deterministic) +; acceptance predicate of require_read_sql. This is a proof of reuse, independent +; of whether the SQL parser implements the intended SQLite grammar. +(set-logic ALL) +(declare-fun read (String) Bool) +(declare-const old (Array Int String)) +(declare-const n Int) +(declare-const incoming String) +(declare-const i Int) +(define-fun cap () Int 16) +(assert (and (<= 0 n) (<= n cap))) +(assert (forall ((j Int)) (=> (and (<= 0 j) (< j n)) (read (select old j))))) +; A hit has a concrete index in the queue and compares its entire string. +(push) +(assert (and (<= 0 i) (< i n) (= incoming (select old i)) (not (read incoming)))) +(check-sat) +(pop) +; A miss only inserts after successful validation, removing the oldest at capacity. +(push) +(assert (read incoming)) +(define-fun count2 () Int (ite (= n cap) cap (+ n 1))) +(define-fun slot ((k Int)) String + (ite (= k (- count2 1)) incoming (select old (ite (= n cap) (+ 1 k) k)))) +(assert (or (> count2 cap) (and (<= 0 i) (< i count2) (not (read (slot i)))))) +(check-sat) +(pop) +; Splitting a fixed database time budget across read, promotion and checkout +; cannot create additional time when all phases keep the original deadline. +(declare-const start Int) +(declare-const budget Int) +(declare-const spent Int) +(declare-const elapsed Int) +(assert (and (> budget 0) (>= spent 0) (>= elapsed 0))) +(push) +(assert (distinct (< (+ start spent elapsed) (+ start budget)) (< elapsed (- budget spent)))) +(check-sat) +(pop) +; Counterexample to resetting the budget at promotion, with no wall-clock jitter. +(push) +(assert (< spent budget)) +(assert (< elapsed budget)) +(assert (>= (+ spent elapsed) budget)) +(check-sat) +(get-value (budget spent elapsed)) +(pop)