diff --git a/.env.example b/.env.example index 059176b194d..bfa8d36cacc 100644 --- a/.env.example +++ b/.env.example @@ -27,6 +27,16 @@ PGUSER=buzz PGPASSWORD=buzz_dev PGDATABASE=buzz +# Fleet usage telemetry is replica-only and independent of serving-read +# routing. This freshness budget defaults to 30000ms; 0 disables the database +# telemetry families. When the reader is absent, stale, or unavailable, the +# relay skips the collection and reports its availability as 0 instead of +# falling back to the writer. +# BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS=30000 +# Per-community metric series are disabled by default to bound relay memory and +# monitoring cardinality. `all` is the temporary rollback mode. +# BUZZ_USAGE_METRICS_PER_COMMUNITY=off + # ----------------------------------------------------------------------------- # Redis 7 # ----------------------------------------------------------------------------- @@ -37,6 +47,30 @@ REDIS_URL=redis://localhost:6379 # Max connections in each of the relay's Postgres pools — writer and, when # READ_DATABASE_URL is set, reader (default 50). # BUZZ_DB_POOL_SIZE=50 +# Read-only partition catalog audit interval, clamped to 60s..24h (default 900s). +# BUZZ_PARTITION_AUDIT_INTERVAL_SECS=900 +# Emergency kill switch for all automatic partition DDL, including catch-all +# advancement; audits remain enabled. +# BUZZ_PARTITION_MANAGER_CREATE_ENABLED=true +# Opt in to replacing an empty partition catch-all with six months of dedicated +# monthlies, at startup and on every audit interval (default false). Has no +# effect while the kill switch above is off. +# BUZZ_PARTITION_MANAGER_ADVANCE_ENABLED=false + +# Writer-session Postgres timeouts for buzz-db-backed pools and the relay audit +# pool, all in milliseconds; 0 disables. The separately deployed push gateway +# owns its own database and session policy and does not consume these knobs. +# lock_timeout: fail a statement that waits this long on any lock instead of +# parking behind a wedged holder (default 5000). +# BUZZ_DB_LOCK_TIMEOUT_MS=5000 +# idle_in_transaction_session_timeout: reap sessions idle inside an open +# transaction — bounds how long a wedged client can hold locks (default 60000). +# BUZZ_DB_IDLE_TXN_TIMEOUT_MS=60000 +# statement_timeout: cap any single statement's runtime. Off by default — +# startup migrations/backfills legitimately run long statements. Warning: a +# pathologically low value (e.g. 1) also times out connection setup and can +# prevent any DB connection from establishing. +# BUZZ_DB_STATEMENT_TIMEOUT_MS=0 # ----------------------------------------------------------------------------- # Typesense (search) @@ -60,10 +94,11 @@ RELAY_URL=ws://localhost:3000 # BUZZ_WEB_DIR=./web/dist # NIP-PL mobile push is an explicit deployment opt-in. A gateway URL alone -# never enables it. When enabled and the URL is absent, the canonical -# https://push.buzz.xyz/v1/deliveries/apns endpoint is used. +# never enables it. When enabled, the exact HTTP(S) delivery URL is required. +# Rollback requires replacing every enabled writer/worker process. Inspect and +# explicitly decide retained queue disposition before re-enabling (see docs/push-gateway-deployment.md). BUZZ_PUSH_ENABLED=false -# BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns +BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # ----------------------------------------------------------------------------- # Admin Dashboard (private moderation surface) @@ -91,9 +126,16 @@ BUZZ_PUSH_ENABLED=false # the console without manual URL entry. # RELAY_OPERATOR_PUBKEYS=<64-char hex pubkey>[,<64-char hex pubkey>...] # -# Option B — BUZZ_ADMIN_AUTH=disabled (network-layer auth only): -# Set only when the admin API is already protected at the network layer -# (VPN, private ingress). The relay logs a WARN on every startup. +# Option B — BUZZ_ADMIN_AUTH=disabled (read-only, no authentication): +# Anyone who can reach the relay can read, in every community: reports (with +# reporter notes and reported message content, deleted included), feedback and +# attachments, bans and timeouts with reasons, the community directory, member +# search and profiles (not staff status), and any stored message by ID. +# Writes and staffing are refused. +# Only people allowed to see all of that should be able to reach it. The admin +# API is on the relay's main listener and its hostname check uses the caller's +# Host header, so the whole relay port must be private, not just the admin +# hostname. The relay logs a WARN on every startup. # `just admin` defaults to this mode for local review. # # Directory holding the built dashboard assets (`pnpm -C admin-web build`). @@ -106,6 +148,15 @@ BUZZ_PUSH_ENABLED=false # and provisioning requests fail closed until it is set. # RELAY_OPERATOR_API_ORIGIN=http://127.0.0.1:3000 +# Deployment-global operator-listener routes. Each configured Nostr identity +# may register target pubkeys and receives mention notifications at its URL. +# URLs may use HTTP or HTTPS. Use HTTP only for operator-controlled internal +# connections: NIP-98 signs requests but does not encrypt them, and +# notifications carry full message content. +# Format: pubkey:deliveryUrl;pubkey:deliveryUrl +# BUZZ_OPERATOR_LISTENER_TIMEOUT_MS=5000 +# BUZZ_OPERATOR_LISTENERS=<64-char hex pubkey>:https://listener.example/mentions + # Optional relay-owned KLIPY key. When set, NIP-11 advertises GIF search and # authenticated desktop clients use this relay as the metadata/search proxy. # Keep the real value in your deployment's secret manager; never commit it. @@ -259,6 +310,10 @@ RUST_LOG=buzz_relay=debug,buzz_datastore=info,buzz_db=debug,buzz_auth=debug,buzz # app launch while keeping the current identity and relay data. # VITE_BUZZ_FORCE_FRESH_ONBOARDING=true +# Protected internal builds only: selects the module graph that contains the +# default-off Bestie experiment. Official OSS builds must leave this unset. +# VITE_BUZZ_BESTIE=1 + # ── Subscription & filtering ───────────────────────────────────────────────── # Subscribe mode: "mentions" (default), "all", or "config" (rule-based). # BUZZ_ACP_SUBSCRIBE=mentions @@ -282,6 +337,14 @@ RUST_LOG=buzz_relay=debug,buzz_datastore=info,buzz_db=debug,buzz_auth=debug,buzz # Set to true to process the agent's own messages (default: ignore self). # BUZZ_ACP_NO_IGNORE_SELF=false +# ── Session scoping ────────────────────────────────────────────────────────── +# How ACP provider sessions are scoped in channels: "channel" (default) or +# "thread". "channel" keeps one provider session per channel (legacy). "thread" +# gives each canonical channel thread its own isolated provider session; direct +# messages stay conversation-scoped either way. Ships as "channel" so thread +# scoping can be canaried and rolled back without code changes. +# BUZZ_ACP_SESSION_POLICY=channel + # ── Context ────────────────────────────────────────────────────────────────── # Max context messages fetched for thread replies and DMs (0–100). 0 = disabled. # BUZZ_ACP_CONTEXT_MESSAGE_LIMIT=12 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e9504afc707..e3ed4a32449 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1,2 @@ * @block/buzz-oss-team +/VISION_MOBILE.md @brow diff --git a/.intersect/sadscan.yaml b/.intersect/sadscan.yaml index 806fcb66899..956feac99b8 100644 --- a/.intersect/sadscan.yaml +++ b/.intersect/sadscan.yaml @@ -4,12 +4,16 @@ exclude_rules_for_files: - Cargo.lock # Self-signed test fixture generated solely to exercise reqwest identity parsing. kingfisher.privkey.2: + # Published upstream synthetic CA key, compiled only under cfg(test). + # The gateway pins Apple's root and cannot trust this fixture CA. + - "*appattest-test-ca-key.pem" - "*apns-test-identity.pem" - "*apns-test-key-only.pem" - "*apns-test-encrypted-identity.pem" - "*apns-test-mismatched-identity.pem" - "*apns-test-auth-key.p8" np.pem.1: + - "*appattest-test-ca-key.pem" - "*apns-test-identity.pem" - "*apns-test-key-only.pem" - "*apns-test-encrypted-identity.pem" diff --git a/.release/desktop-candidate.json b/.release/desktop-candidate.json index 4751a7d3517..4df6aa008bf 100644 --- a/.release/desktop-candidate.json +++ b/.release/desktop-candidate.json @@ -1,10 +1,10 @@ { "schema": 2, - "version": "0.5.20", - "base_sha": "8471049c430073474939336dfc6aa98272bc8762", - "previous_tag": "desktop-v0.5.19", - "previous_base_sha": "ee6ca5fa28bce04dfecb6717de65b08a57f2ac47", - "previous_merge_sha": "7a1b7d8e09f96c10b6617a66bb8589e9984ffb3c", - "tag": "desktop-v0.5.20", - "commit_count": 4 + "version": "0.5.28", + "base_sha": "5142cf6b2a0f44686eeda1ed07905ee3560fd78e", + "previous_tag": "desktop-v0.5.27", + "previous_base_sha": "af5bb0af488784c3707e99c87e0675a729711a6e", + "previous_merge_sha": "001290a34d4b854f0b5d354ae848163b43e6ff85", + "tag": "desktop-v0.5.28", + "commit_count": 41 } diff --git a/AGENTS.md b/AGENTS.md index 3f03af7e102..8c48e4816f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,6 +43,48 @@ and runtime evidence answer different questions. --- +## Before opening a PR + +Open work in progress as a draft PR. Mark it ready for review only when this +checklist holds for the current change. Scale it to what changed: +documentation-only changes need content, link, and diff checks plus human +confirmation, not app runs. + +1. **Agent review ran** under [Reviewing](#reviewing), and its recommended + blockers were fixed or explicitly declined by the human author. Optional + suggestions do not gate readiness. +2. **An agent exercised the changed behavior.** Client changes: the affected flow + in the app, using the native app or a device when the behavior needs it + (browser or headless Playwright counts only for what it can exercise). Relay + changes: a local relay, exercising the changed events or endpoints. CLI or + tooling changes: the affected command or workflow. The human may skip this + step, for example for a small change or while iterating. +3. **A human then tested it themselves**: in the app, against the local relay + (through the app or `curl`), or by running the changed command. Agent testing + does not substitute. Agents give the human exact steps and what working looks + like, then wait for explicit confirmation. Never mark this step done yourself. +4. **Add `buzz-review-completed` to the PR description** once steps 1–3 hold. It + attests the checklist, and automated reviewers may skip review because of it. + If later edits change behavior, remove it and return the PR to draft until the + affected steps are redone. + +## Reviewing + +- Before reviewing, read [VISION.md](VISION.md), the `VISION_*.md` docs for the affected surface, and the PR's stated goal and linked + issue. Review the change against what it is trying to do. +- Check the change against the [Review-Proven Rules](#review-proven-rules): the defects reviewers here find most often. +- Judge minimalism, elegance, and correctness, aiming for 9/10 on each. A score + below 9 names the concrete defect and the fix. +- Recommend blocking only for concrete correctness, security, or agreed-contract + defects with a realistic failure scenario: state the defect, how it fails, and + the fix. Label everything else (nits, wording, speculative hardening, + out-of-scope improvements) as optional. +- Put all findings in the first review. Later reviews check prior blockers and + defects the fixes introduced; reopen other areas only on new evidence of a + material defect. +- Agents post reviews as comments, never Request Changes. Humans decide which + findings must be fixed. + ## Ecosystem Buzz spans five repos. This one (`block/buzz`) is the OSS source for the relay, desktop, mobile, and CLI. The others handle internal builds and deployment: @@ -130,6 +172,10 @@ See CONTRIBUTING.md for full setup details and dependency requirements. Run `just ci` before every PR — it runs repository-wide formatting, lint, and static checks; Rust, Tauri, desktop, and mobile tests; and desktop and web builds. Clippy passing does not mean fmt passes; run both. +For changes limited to Flutter/Dart code in the mobile app, run +`just mobile-install mobile-check mobile-test` instead of `just ci`. +Native code and build-configuration changes also require the corresponding +platform checks. Run `just test` for integration tests if you touched `buzz-relay`, `buzz-db`, or `buzz-auth` — these require a running Postgres and Redis. @@ -169,6 +215,91 @@ Additional rules: --- +## Review-Proven Rules + +These rules distill the recurring findings from the last 25 PRs' review +threads — 53% of substantive review findings were repeats of the clusters +below, and reviewed PRs averaged ~5 review rounds. A second, independent +mining pass over 71 agent-review rooms (303 findings, Aug 18–29) confirmed +the same clusters and measured how often authors actually fix each class +once flagged: test-seam binding and unbounded-resource findings were fixed +**100%** of the time, swallowed-error findings **90%**, stale-state races +**70%** — these are not style opinions, they are defects authors agree +with on sight. Authors apply them **before writing code**, and reviewers check +against them; each cites the PRs where reviewers litigated it. + +1. **Every caught failure must leave a durable retry record or propagate.** + Never catch-log-and-return-success (opt-out revocation permanently + abandoned, PR #6269), never convert a terminal failure into an + authoritative success/empty result (cold-history `error` → `success` + with `[]`, PR #7013), and never delete the durable journal an operation + depends on before its retry has actually succeeded (PR #6269). If a + partial failure can orphan committed state (installations, endpoints), + schedule its cleanup/renewal durably (PRs #6269, #6996, #7013). + +2. **Fence async results by generation; clear derived metadata on every + removal path.** A completing in-flight probe or fetch must verify it is + still the newest before writing its result (stale login-shell probe + recached a false-negative PATH, PR #6904). Provenance/ownership metadata + attached to synthetic state must be updated or cleared on *all* paths + that remove or refresh that state — typed deletion, toolbar removal, + profile/name refresh; enumerate the paths and test each (PR #6956 burned + 4 rounds on this one class). Backfill and live subscriptions must + overlap — a gap between a finite history REQ and the live subscription + silently drops events (PR #3995); a retired chunk must not keep a stale + scope fence (PR #6996). (PRs #3995, #6904, #6956, #6996) + +3. **Regression tests must bind the production seam and be falsifiable.** + See "Review-Proven Test Standards" in [TESTING.md](TESTING.md) for the + full rule — in short: a guard whose removal doesn't fail any test + protects nothing; bind regression tests to the production code path, + not test-only helpers. (PRs #6807, #6980, #6996, #7013) + +4. **Bound every resource, loop, and process tree.** Cap captured + output (unbounded discovery temp files exhausted disk and overran the + deadline, PR #6904). Containment failures are errors, not warnings — a + tolerated Job Object creation failure or a `setsid` escape leaks whole + process trees (PR #6904). Retry/re-subscribe loops need backoff and a + terminal state: a persistent failure must not self-amplify into an + unbounded refresh loop (PR #6996), and check zero-delay edge cases + (`remainingMs()==0` selected the wrong fallback window, PR #6996). + (PRs #6904, #6996) + +5. **One user action = one atomic persist.** Implementing a single user + commit as N independent durable writes leaves torn state on partial + failure (theme "Set" as three independent notifier persists, PR #6944; + relay-commit vs. local-save recovery gap, PR #6269). Persist one + snapshot, or order the writes so every prefix is consistent and the + remainder is durably retried per rule 1. (PRs #6269, #6944) + +6. **A guard that hides the only recovery affordance is a functional + failure.** Before adding a visibility predicate or state fence, ask: + if the state it assumes goes wrong, does the user still have a way + back? A fence that permanently suppresses "jump to latest" after a + bounded correction fails strands the user silently — two reviewers + flagged this independently (PR #6807). + +7. **Audit assistive semantics on every new visual component.** The + agent-review lanes flagged accessibility defects on 44 findings across + the Aug 18–29 window — the second-largest cluster — and authors fixed + the concrete ones (duplicate VoiceOver stops on native controls, + actionable labels owned by two widgets at once, PR #6680; missing or + decorative-leaking semantics on new UI, PRs #6611, #6702, #6885, #6905, + #6908). New UI ships with: one owner per actionable label, no duplicate + screen-reader stops, and explicit semantics for every interactive + element. (PRs #6611, #6680, #6702, #6885, #6905, #6908, #6980) + +8. **Every input modality is a first-class seam.** Keyboard, pointer, and + hotkey paths must not silently diverge: `Shift+Space` treated as plain + `Space` because the guard omitted `shiftKey` (PR #6862), keyboard + ownership not released on blur, modifier keys dropped on the non-mouse + path (PRs #5958, #6793, #6860, #6908, #7006). When adding an input + handler, enumerate the modalities that can reach it and test the + non-primary ones — that's where the defects were. (PRs #5958, #5972, + #6793, #6860, #6862, #6908, #7006) + +--- + ## Key Patterns **Nostr-first HTTP surface**: Buzz's primary API is NIP-29 over WebSocket. The relay also exposes a narrow HTTP surface: NIP-11/NIP-05 metadata, `POST /events`, `POST /query`, `POST /count`, workflow webhooks at `/hooks/{id}`, Blossom media, git smart HTTP, git policy hooks, and health probes. These HTTP paths all preserve the same host-derived community boundary. @@ -200,7 +331,9 @@ Filters and queries must scope to `h` tags when operating within a channel. This applies to events *inside* a channel. Addressable events that describe a channel carry its id in their `d` tag instead: kind:39000 (metadata), kind:39001, kind:39002 (membership). `get_channels` resolves a user's channels -from the `d` tag of their kind:39002 events, not from `h`. +from the `d` tag of their kind:39002 events, not from `h`. The relay leaves +system channels out of these reads unless the filter asks for them (see +`docs/nips/NIP-CL.md`). **Agent-facing operations go in `buzz-cli`**: New agent-facing features belong in `buzz-cli` — add a subcommand there first, then wire the REST/WebSocket call in `client.rs`. `buzz-dev-mcp` (shell + file tools for `buzz-agent`) is separate. @@ -487,7 +620,7 @@ description. See [PR #803](https://github.com/block/buzz/pull/803). 4. **Worktrees: `cd` in the same command** — shell CWD doesn't persist between tool calls. Use `cd /path && cargo build` as one command. 5. **Desktop crate excluded from root workspace** — `cargo test` at repo root does NOT run desktop tests. Use `cargo test --manifest-path desktop/src-tauri/Cargo.toml` explicitly. 6. **React render perf: `React.memo` is all-or-nothing** — it only skips a re-render when *every* prop is reference-stable; one unstable prop (inline arrow/JSX, or a hook returning a fresh `{}`/`[]`/`Map` each render) defeats it. Two repeat offenders: (a) React Query results (`useMutation`/`useQuery`) are a **new object each render** — depend on the stable method (`mutation.mutateAsync`), not the object; (b) derived `Map`/array state that recomputes on a version bump — wrap in a content-equality ref cache (`shared/hooks/useStableReference.ts`). When chasing interaction lag, **measure with DevTools closed and no perf probes** (an open Web Inspector + per-keystroke `console.log` inflate the numbers), and isolate by removing one suspect at a time rather than guessing. -7. **`pgschema` omits seed DML and some storage parameters** — Fresh desired-state bootstraps use `./bin/pgschema apply`, which does not execute `INSERT` statements or preserve every table storage parameter from `schema/schema.sql`. Put each unsupported invariant in `scripts/reconcile-schema-after-pgschema.sql` as an idempotent convergence statement plus a live catalog or data assertion. Every `pgschema apply` caller must run that script. A string assertion against `schema.sql` alone does not prove the pgschema-created database has the intended state. +7. **`pgschema` omits seed DML and some storage parameters** — `schema/schema.sql` is an ordered `\i` manifest: `schema/tables/public/.sql` holds only that table's `CREATE TABLE` and `CREATE INDEX` statements (one table per file, the shape SchemaBot reads), and types, functions, partitions, triggers, and seed rows live in the sibling `schema/` directories. Fresh desired-state bootstraps use `./bin/pgschema apply`, which does not execute `INSERT` statements or preserve every table storage parameter from `schema/schema.sql`. Put each unsupported invariant in `scripts/reconcile-schema-after-pgschema.sql` as an idempotent convergence statement plus a live catalog or data assertion. Every `pgschema apply` caller must run that script. A string assertion against `schema.sql` alone does not prove the pgschema-created database has the intended state. --- @@ -607,11 +740,13 @@ The mobile app lives in `mobile/` — a Flutter app using Riverpod + Hooks. over raw `Theme.of(context)` calls. - **Keep widgets small and composable.** One public widget per file; push private sub-widgets (`_Foo`) into sibling `part` files under a - `/` folder rather than growing the page file. Hard ceiling: - **1000 lines/file**, enforced across Desktop, Web, and Mobile by the + `/` folder rather than growing the page file. Mobile's hard ceiling is + **1200 lines/file**, enforced with the other surface-specific limits by the repository-level `just file-size-check` gate (`just check`, CI, and every - pre-push). If the guard trips, **split the file — never bump the limit or add - an override to slip under it.** + pre-push). If an individual file trips the guard, **split the file — never + bump a surface limit or add an override merely to admit that file.** + Deliberate repository-wide policy revisions must update the enforced rules, + tests, and guidance together. - Feature modules must not import from other feature modules — only from `shared/`. - Use `Grid` tokens for spacing, `Radii` for border radius. @@ -622,7 +757,7 @@ The mobile app lives in `mobile/` — a Flutter app using Riverpod + Hooks. cd mobile dart format --output=none --set-exit-if-changed . flutter analyze -flutter test +flutter test --dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example ``` Or from repo root: `just mobile-fmt` (auto-fix), `just mobile-check` (lint + fmt check), `just mobile-test` (tests). @@ -664,3 +799,16 @@ usage. - [ARCHITECTURE.md](ARCHITECTURE.md) — system design and component relationships - [RELEASING.md](RELEASING.md) — release process: `release-desktop`, `release-relay`, `scripts/mobile-release.sh`, candidate tags, internal builds - [README.md](README.md) — project overview and quick start + +### Mention editor contract + +Autocomplete inserts a literal full label and a separator, including multi-word +names. Only autocomplete settlement may move the caret past that separator; +internal label spaces and deliberate ArrowLeft/click movement must be respected. +See `docs/mention-editor.md` and `desktop/tests/e2e/mention-spacing.spec.ts`. + +Selected mention labels bind exact keys, including same-name teammates and +persistent automatic addresses. Use the returned label from registration for +insert/restore/remove. Ambiguous manually typed names must fail visibly without +clearing the draft in chat, edit, and standalone forum consumers; never fan out +silently to all identities sharing a name. See `docs/mention-editor.md`. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 892082d96c6..5bb9896d713 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -14,6 +14,57 @@ EVENT, REQ, REST, media, git, search, workflow, or pub/sub handling. Unknown hosts fail closed, and NIP-98/API-token stamps must agree with the host-derived community rather than overriding it. +Deployment-root community management uses operator-signed NIP-98 HTTP requests. +`POST /operator/communities/delete` accepts only an exact normalized, archived +community whose asserted pubkey is its sole current owner. The caller supplies the +request UUID as the stable correlation/idempotency identity; the durable row +records operator-attested owner intent, mediating operator, and acknowledgement +version. Admission returns `202` at the `submitted` stage and performs no +inventory, approval, +quiescing, object-store access, or deletion execution synchronously. While that +non-aborted request exists, unarchive and ownership transfer conflict and owner +management lists suppress the archived row. Replaying the same UUID converges +to its current stage; a different UUID conflicts with the existing one-active- +request invariant until that request is aborted. + +Owner consent on this path is asserted, not proven. The mediating operator +authenticates the owner and collects the deletion acknowledgement out of band, +upstream of the relay; the request itself carries only the operator's NIP-98 +signature. The relay verifies operator authority and that the asserted pubkey +is the community's sole current owner, then records the owner pubkey, mediating +operator pubkey, and acknowledgement version as durable provenance for that +upstream ceremony. No owner-signed attestation is required or checked, and +owners have no self-service cancellation. Recovery is a privileged abort, +which stays open across the reversible `submitted`, `inventoried`, `approved`, +and `fenced` stages — releasing the request fence while leaving the community +archived — and closes from `drained` onward, when tenant-state destruction may +have begun. + +Manual operator handoff converges on an admitted owner request only when +`buzz-admin deletions submit --requested-by` repeats the owner pubkey recorded +on the row. Owner provenance pins `requested_by` to `owner_pubkey`, so passing +the operator's own pubkey does not converge — it conflicts with the existing +one-active-request invariant instead. + +The privileged one-shot `buzz-admin deletions drain` process gives already- +approved work priority. When none is ready, it may claim only an +operator-attested owner-origin `submitted` request under the same durable +generation lease used for execution, inventory it with lease-loss cancellation, +and atomically freeze the inventory plus a digest-bound `owner_automatic` +approval. The mediating operator remains the approval actor; the owner +acknowledgement is pre-inventory +intent, not a claim that the owner reviewed the digest. The retained lease then +enters the unchanged approved-request executor. Operator-origin requests never +auto-progress and still require explicit inventory and approval. Owner +admission still has no owner-facing cancellation or grace period; the +privileged abort described above remains the recovery path. + +Ownership is mutable only while a community is active. Archiving freezes the +current owner. Normal transfer and deployment-root legacy convergence take the +same community-row lock as owner-deletion admission, then reject archived, +quiescing, deleted, or deletion-pending rotation without changing membership. +Initial owner bootstrap for a newly created community remains supported. + Buzz is a Rust monorepo, licensed Apache 2.0 under Block, Inc. --- @@ -94,7 +145,7 @@ buzz-admin (operator CLI: relay membership + key generation) buzz-test-client (integration test harness + manual CLI) ``` -**Key architectural principle:** The relay is the single source of truth. `buzz-relay` orchestrates all subsystems by calling them directly — it imports `buzz-db`, `buzz-auth`, `buzz-pubsub`, `buzz-search`, `buzz-audit`, and `buzz-workflow`. However, those subsystems are isolated from each other: `buzz-workflow` never calls `buzz-pubsub`, `buzz-search` never calls `buzz-db`, etc. Cross-subsystem coordination happens only through the relay. In multi-community mode, the relay also owns propagation of `TenantContext`; service crates should receive community-scoped inputs rather than independently deriving tenancy from client-controlled event tags. +**Key architectural principle:** The relay is the single source of truth. `buzz-relay` orchestrates all subsystems by calling them directly — it imports `buzz-db`, `buzz-auth`, `buzz-pubsub`, `buzz-search`, `buzz-audit`, and `buzz-workflow`. However, those subsystems are isolated from each other: `buzz-workflow` never calls `buzz-pubsub`, `buzz-search` never calls `buzz-db`, etc. The one sanctioned exception is `buzz-audit`, which calls `buzz_db::deletion::guard_community_write` to admit each audit append into its community before taking the chain lock. Cross-subsystem coordination happens only through the relay. In multi-community mode, the relay also owns propagation of `TenantContext`; service crates should receive community-scoped inputs rather than independently deriving tenancy from client-controlled event tags. --- @@ -138,6 +189,7 @@ The `kind` integer is the only dispatch switch. The relay routes, stores, and fa | 45003 | KIND_FORUM_COMMENT | Forum thread reply | | 46001–46012 | KIND_WORKFLOW_* | Workflow execution events | | 20001 | KIND_PRESENCE_UPDATE | Ephemeral presence heartbeat | +| 20003 | KIND_AGENT_PRESENCE | Ephemeral presence heartbeat an owner sends for its agents | `buzz-core` defines each event kind as a `pub const u32` and exports the full registry as `ALL_KINDS: &[u32]` (127 kinds at the time of writing); `crates/buzz-core/src/kind.rs` is the source of truth for the current list. Kinds are `u32` (NIP-01 specifies unsigned integer; `u32` covers the full range). Buzz uses both standard Nostr kinds (e.g., kind 7 for reactions) and custom ranges (40000+). @@ -229,15 +281,14 @@ When the relay receives `["EVENT", ]`, the handler in `handlers/event.rs` 4. EPHEMERAL ROUTE — kind 20000–29999 → ephemeral sub-pipeline (see below) 5. VERIFY — spawn_blocking(verify_event) — Schnorr sig + ID hash 6. MEMBERSHIP — channel_id in event tags? → check_channel_membership -7. DB INSERT — db.insert_event (ON CONFLICT DO NOTHING — idempotent) +7. DB INSERT — db.insert_event (idempotent; search_tsv generated synchronously) 8. REDIS PUBLISH — pubsub.publish_event (if channel-scoped) 9. FAN-OUT — sub_registry.fan_out → conn_manager.send_to -10. SEARCH INDEX — search_index_tx.send (bounded worker queue, non-blocking) -11. AUDIT LOG — audit.log (spawned async, non-blocking) -12. WORKFLOW TRIGGER — wf.on_event (spawned async, excludes kinds 46001–46012) +10. AUDIT LOG — audit.log (spawned async, non-blocking) +11. WORKFLOW TRIGGER — wf.on_event (spawned async, excludes kinds 46001–46012) ``` -Steps 10–12 are fire-and-forget. Search indexing is sent to a bounded worker queue (`search_index_tx`, capacity 1000); audit and workflow triggers are spawned as independent async tasks. A failure in any of these does not fail the event submission. The client receives `["OK", , true, ""]` at the end of the pipeline, not immediately after DB insert. +Steps 10–11 are fire-and-forget: audit and workflow triggers are spawned as independent async tasks. A failure in either does not fail the event submission. Search has no asynchronous indexing step: Postgres maintains the generated `events.search_tsv` column as part of step 7, and `buzz-search` only queries it. The client receives `["OK", , true, ""]` at the end of the pipeline, not immediately after DB insert. Step 9 (fan-out) explicitly **excludes** global subscriptions (no `channel_id` constraint) from channel-scoped events — global subscriptions do NOT receive events from private channels, regardless of filter match. This is a deliberate security boundary: only subscriptions scoped to an accessible `channel_id` receive those events. @@ -255,6 +306,8 @@ Ephemeral events bypass DB storage, audit, and search. Two sub-paths: ``` Presence events skip membership checks and use local-only fan-out. Multi-node presence fan-out would require Redis pub/sub (documented as future work). +**Agent presence (kind 20003):** an owner's one heartbeat for all its agents, so an app that runs agents without a socket per agent can still show them online. Content is the status (`online`, `away` or `offline`) and each `p` tag names an agent, at most 256. WebSocket only. The relay keeps the agents the signer owns (`users.agent_owner_pubkey`, through the owner cache), skips the rest, and sets or clears their presence exactly as their own kind 20001 would, so the presence snapshot reports them unchanged. It is not fanned out, since live presence is matched by author; viewers see it on their next snapshot read. + **Other ephemeral events (e.g., typing indicators):** ``` 1. VERIFY — spawn_blocking(verify_event) @@ -264,6 +317,8 @@ Presence events skip membership checks and use local-only fan-out. Multi-node pr 5. LOCAL FAN-OUT — sub_registry.fan_out → conn_manager.send_to ``` +Typing indicators (kind 20002) are also accepted through HTTP `POST /events`, for clients that sign events but hold no WebSocket, such as app-hosted agents. The HTTP route requires an `h` tag, checks bans/timeouts and the community write fence, then runs steps 1–5 above. + Ephemeral events are never stored in Postgres and never appear in REQ historical queries. ### Handler Semaphore @@ -325,6 +380,15 @@ This prevents a race where a non-member receives live fan-out events from a priv After registering, the REQ handler queries Postgres for stored events matching the filters (up to 500 per filter, hard cap). These are sent as `["EVENT", sub_id, event]` frames before `["EOSE", sub_id]`. New events arriving after EOSE are delivered via the fan-out path. +**Client consumption invariant.** A client rebuilding channel state must +open its live subscription before (or overlapping) the finite history +REQ — a gap between the last backfill page and live delivery silently +drops events and rebuilds stale state (PR #3995). When the relay sends a +terminal CLOSED, the subscription is removed server-side; any client-side +ownership tied to it (chunk/scope fences) must be released in the same +step, or live delivery stops permanently while the client believes it is +subscribed (PR #6996). + --- ## 6. Crate Reference @@ -352,7 +416,7 @@ pub const ALL_KINDS: &[u32] // 80 entries (KIND_AUTH excluded — never stored) |----------|---------| | `filters_match(filters, event)` | OR across filters, AND within each filter. Includes NIP-01 prefix matching on event IDs. | | `verify_event(event)` | Schnorr signature + SHA-256 ID check. CPU-bound — callers use `spawn_blocking`. | -| `is_private_ip(ip)` | SSRF protection: IPv4 unspecified/loopback/private/link-local/CGNAT/benchmarking/broadcast + IPv6 loopback/ULA/link-local/multicast/documentation + IPv4-mapped IPv6. | +| `is_not_global_unicast(ip)` | SSRF protection: enumerated-deny policy — blocks a specific set of non-public address classes and accepts everything else (including addresses not covered by an explicit deny rule, e.g. `fe00::1`). Blocked IPv4 classes: loopback, private (RFC 1918), link-local, CGNAT (RFC 6598), benchmarking (RFC 2544), IETF Protocol Assignments (192.0.0.0/24, exceptions: 192.0.0.9 PCP anycast, 192.0.0.10 TURN anycast), documentation (RFC 5737: 192.0.2/24, 198.51.100/24, 203.0.113/24), deprecated 6to4 relay anycast (192.88.99.0/24, RFC 7526), multicast (RFC 5771, 224/4), reserved/class-E (240/4). Blocked IPv6 classes: loopback, unspecified, ULA (fc00::/7), link-local (fe80::/10), deprecated site-local (fec0::/10, RFC 3879), multicast (ff00::/8), IETF Protocol Assignments envelope (2001::/23, global exceptions: 2001:1::1–::3 anycast, 2001:3::/32 AMT, 2001:4:112::/48 AS112-v6, 2001:20::/28 ORCHIDv2, 2001:30::/28 DETs), documentation (2001:db8::/32, 3fff::/20), 6to4 (2002::/16), Discard-Only (100::/64), Dummy prefix (100:0:0:1::/64), SRv6 SIDs (5f00::/16), NAT64 local-use (64:ff9b:1::/48). IPv4 embedded in mapped, compatible, NAT64 well-known (64:ff9b::/96), and SIIT IPv4-translated (::ffff:0:0:0/96) forms checked recursively. Compat alias: `is_private_ip`. | **Does NOT:** store events, make network calls, spawn tasks, or depend on any async runtime. @@ -403,14 +467,14 @@ All database access. Uses `sqlx::query()` (runtime, not compile-time macros) — | `channel.rs` | Channel CRUD, membership management, role enforcement (transactional) | | `feed.rs` | `query_mentions` (INNER JOIN event_mentions), `query_needs_action`, `query_activity` | | `workflow.rs` | Full workflow/run/approval CRUD; SHA-256 hashed approval tokens | -| `partition.rs` | Monthly range partitioning for `events` and `delivery_log` tables | +| `partition.rs` | Monthly range partitioning for `events` and `delivery_log` tables: read-only catalog audit plus advisory-locked, time-bounded maintenance that creates uncovered months and advances an empty catch-all (`partition/maintenance.rs`) | | `dm.rs` | DM channel management | | `reaction.rs` | Reaction storage and retrieval | | `thread.rs` | Thread/reply tracking | | `user.rs` | User profile storage | | `error.rs` | Database error types | -**Channel types:** `Stream`, `Forum`, `Dm`, `Workflow` +**Channel types:** `Stream`, `Forum`, `Dm`, `Workflow`, `System` **Member roles:** `Owner`, `Admin`, `Member`, `Guest`, `Bot` **Workflow statuses:** `Active`, `Disabled`, `Archived` **Run statuses:** `Pending`, `Running`, `WaitingApproval`, `Completed`, `Failed`, `Cancelled` @@ -425,6 +489,42 @@ All database access. Uses `sqlx::query()` (runtime, not compile-time macros) — - Approval tokens: `create_approval` receives the raw token and hashes it internally with SHA-256. - DDL injection protection in partition manager: allowlist of table names + strict suffix/date validators. +### Supported Writer Contract (transition state) + +The repository is moving toward a **supported-writer contract** where relay-owned +write APIs provide the only supported mutation path for tenant data. The current +shape is an explicit transition, not a flag day: + +- **Trajectory:** converge from trigger/function/FK-enforced fencing toward + application-owned transaction protocols, while keeping existing DB backstops + in place until coverage and fleet gates are proven. +- **Community fence (transition foundation):** runtime admission APIs now offer + one shared community deletion lock per transaction, while deletion lifecycle + transitions take the matching exclusive lock. A supported serving transaction + never spans communities. Serving leases use the same application admission. + Startup and deletion catalog validation tolerate the universal fence objects + being absent; inventories still record live fences for older executors. +- **Replica floor (transition foundation):** runtime now provides a shared + replica-floor lock helper for compliant channel-event writers, and the writer + probe handshake takes the exclusive counterpart before sampling `S`, scanning + activity, and committing the heartbeat token last. `probe_once` remains the + sole token/fence-wall publication path; there is no separately persisted active + floor cutoff. Commit-time trigger+GUC enforcement remains authoritative for all + paths. +- **Dual enforcement (current):** application-owned lock+precheck paths run in + front of the existing trigger/function enforcement; commit-time trigger checks + remain authoritative during this phase. Removing those backstops is a separate + gated migration, after every pod tolerates their absence and no rollback below + that version is expected. +- **Role separation:** relay/runtime code owns admission and lock protocols; + operator maintenance/backfill workflows must either use those protocols or run + under explicit reviewed procedures that keep routing fences closed. +- **Unsupported shape:** direct owner SQL that bypasses supported transaction and + lock protocols is not a supported write path. +- **Fleet gates and reconciliation:** startup/fence probes verify guard catalog + + behavior, pgschema bootstraps run reconciliation, and lock/pool metrics remain + the operational evidence path for rollout safety. + **Does NOT:** cache queries, implement connection pooling logic (delegated to sqlx), or make network calls outside Postgres. --- @@ -498,7 +598,7 @@ Tamper-evident append-only log with SHA-256 hash chaining. **Hash covers:** seq (big-endian bytes), timestamp (RFC3339), event_id, event_kind (big-endian), actor_pubkey, action string, channel_id (16 bytes or 16 zero bytes if None), canonical metadata JSON (BTreeMap for deterministic key ordering), prev_hash. -**Single-writer guarantee:** `pg_advisory_lock` before each transaction. Lock released in all branches including panic (`catch_unwind`). +**Single-writer guarantee:** each append runs in one transaction that first passes community write admission (the shared community deletion lock plus the active/undeleted check, via `buzz-db`'s `DeletionStore::guard_transaction`), then takes a per-community `pg_advisory_xact_lock`. Both locks release on commit or rollback, including a dropped future. **10 audit actions:** `EventCreated`, `EventDeleted`, `ChannelCreated`, `ChannelUpdated`, `ChannelDeleted`, `MemberAdded`, `MemberRemoved`, `AuthSuccess`, `AuthFailure`, `RateLimitExceeded`. @@ -553,6 +653,15 @@ Note: Both `TriggerDef` and `ActionDef` use serde internally-tagged enums. Trigg **Cron scheduler:** loop ticks every 60 seconds, evaluates cron expressions with window-based matching, and creates workflow runs for matched triggers. Fully implemented. +**Deletion and recreation:** An authorized kind:5 `a`-tag deletion commits its +public event, executable workflow removal, and visible kind:30620 removal in one +transaction. Rejected deletions are not accepted history; identical concurrent +requests have one dispatch/audit owner. Deletions older than a live definition +leave that newer version intact. Deletion is not a permanent coordinate ban: +clients may publish a distinct signed definition afterward, including a backdated +version, to recreate the workflow and enable triggers again. This intentionally +retains arrival-order recreation without a deletion watermark. + **Does NOT:** recursively resolve templates (single-pass only). Does NOT queue workflow runs when at capacity — returns `CapacityExceeded` immediately. --- @@ -591,11 +700,22 @@ pub struct AppState { pub handler_semaphore: Arc, // 1024 concurrent handlers pub relay_keypair: nostr::Keys, // relay identity pub local_event_ids: moka::sync::Cache, // local-echo dedup - pub search_index_tx: mpsc::Sender, // bounded search worker queue // + config, redis_pool, membership_cache, media_storage, shutdown state } ``` +Postgres pools use the closed physical role vocabulary `writer`, `reader`, +`audit`, and `search`. The periodic sampler retains cheap SQLx pool handles and +exports `buzz_db_pool_connections{pool_role,state}` for the bounded states +`idle` and `active`, `buzz_db_pool_max_connections{pool_role}` for capacity, +and `buzz_db_pool_configured{pool_role}`. All four roles are always present (16 +raw gauge series total); absent optional pools report zero. Current pool size is +exactly the sum of its idle and active connection gauges. The legacy +`buzz_db_pool_*` writer gauges and `buzz_db_read_pool_*` reader gauges remain +for dashboard compatibility. Pool sizing and aggregate deployment connection +budgets remain configuration/deployment concerns rather than a relay pool +manager. + **`ConnectionState`** (per-connection): ```rust @@ -616,7 +736,7 @@ pub enum AuthState { Pending { challenge: String }, Authenticated(AuthContext), | GET | `/.well-known/nostr.json` | NIP-05 identity | | GET | `/health` | Health check | | GET | `/_liveness` | Liveness probe | -| GET | `/_readiness` | Readiness probe | +| GET | `/_readiness` | Readiness probe — local process lifecycle only | | POST | `/events` | Submit a signed Nostr event over HTTP (same ingest path as WebSocket `EVENT`) | | POST | `/query` | Query Nostr events over HTTP with NIP-01 filters | | POST | `/count` | Count Nostr events over HTTP with NIP-45 filters | @@ -685,10 +805,23 @@ Subcommands: | `remove-member` | Remove a pubkey from the relay membership list (`--pubkey`, optional `--role` guard); publishes kind:13534 roster | | `list-members` | List all relay members | | `generate-key` | Generate a new Nostr keypair (for bootstrapping) | +| `deletions` | Submit, inspect, approve, abort, unblock, run, or drain durable whole-community deletion requests | +| `storage-snapshot` | Run one isolated S3 accounting scan and publish its complete Postgres snapshot | | `reconcile-channels` | Emit kind:39000/39002 discovery events for channels missing them (idempotent) | The `buzz-admin` binary is shipped in the relay Docker image (`/usr/local/bin/buzz-admin`) and is the recommended way to manage relay membership in production. Use `./run.sh add-member`, `./run.sh remove-member`, and `./run.sh list-members` in Docker Compose deployments. +Kubernetes deployments may schedule the typed one-shot +`buzz-admin deletions drain` command directly. The pod owns its bounded +Postgres/Redis clients and S3 client; it does not call relay HTTP. Durable +requests, leases, retry timing, and checkpoints in Postgres are the handoff and +execution authority, so Kubernetes uses `Forbid` concurrency and zero Job +retries rather than introducing a second retry system. +The same drain first claims runnable approved work and, only when none exists, +may prepare one owner-origin submission. Inventory, automatic approval, and +execution share one generation lease and the existing retry/block/checkpoint +records; there is no preparation worker, command, queue, or retry authority. + --- ### buzz-test-client — Integration Test Harness @@ -737,12 +870,22 @@ Every security-sensitive operation uses an explicit, verified pattern. No implic ### SSRF Protection -`is_private_ip()` in `buzz-core` covers: -- IPv4: unspecified (0.0.0.0/8), loopback (127.0.0.0/8), private (10/8, 172.16/12, 192.168/16), link-local (169.254/16), CGNAT (100.64/10), benchmarking (198.18/15), broadcast (255.255.255.255) -- IPv6: loopback (::1), ULA (fc00::/7), link-local (fe80::/10), multicast (ff00::/8), documentation (2001:db8::/32) -- IPv4-mapped IPv6 (::ffff:0:0/96) — recursively checks the embedded IPv4 address +`is_not_global_unicast(ip)` (compat alias `is_private_ip`) in `buzz-core` is an enumerated-deny policy: it blocks a specific set of non-public address classes and accepts everything else, including addresses not covered by an explicit deny rule (e.g. `fe00::1`). Blocked IPv4 classes: loopback (127.0.0.0/8), private RFC 1918 (10/8, 172.16/12, 192.168/16), link-local (169.254/16), unspecified (0/8), broadcast, CGNAT/RFC 6598 (100.64/10), benchmarking/RFC 2544 (198.18/15), IETF Protocol Assignments (192.0.0.0/24, globally reachable exceptions: 192.0.0.9 PCP anycast RFC 7723 and 192.0.0.10 TURN anycast RFC 8155), documentation/RFC 5737 (192.0.2/24, 198.51.100/24, 203.0.113/24), deprecated 6to4 relay anycast (192.88.99.0/24, RFC 7526, global=None/blank → conservative deny), multicast/RFC 5771 (224/4), and reserved class-E (240/4). Blocked IPv6 classes: loopback (::1), unspecified (::), ULA (fc00::/7), link-local (fe80::/10), deprecated site-local (fec0::/10, RFC 3879), multicast (ff00::/8), IETF Protocol Assignments envelope (2001::/23, global exceptions: 2001:1::1–::3 PCP/TURN/DNS-SD anycast, 2001:3::/32 AMT RFC 7450, 2001:4:112::/48 AS112-v6 RFC 7535, 2001:20::/28 ORCHIDv2 RFC 7343, 2001:30::/28 DETs RFC 9374), documentation (2001:db8::/32 RFC 3849, 3fff::/20 RFC 9637), 6to4 (2002::/16, RFC 3056), Discard-Only (100::/64, RFC 6666), Dummy IPv6 Prefix (100:0:0:1::/64, RFC 9780), SRv6 SIDs (5f00::/16, RFC 9252), and NAT64 local-use (64:ff9b:1::/48, RFC 8215). IPv4 embedded in IPv4-mapped, IPv4-compatible, and NAT64 well-known (64:ff9b::/96, RFC 6052) forms is checked recursively against the IPv4 table; SIIT IPv4-translated (::ffff:0:0:0/96) follows the same path. + +Applied in: `buzz-auth` (JWKS boundary), `buzz-workflow` (CallWebhook action), +desktop `link_preview` (SSRF check). -Applied in: `buzz-workflow` (CallWebhook action), `buzz-core` (shared utility). +JWKS uses `public_https` by default and applies this public-address check to +every resolved answer before pinning the first permitted address. Explicit +`mesh` mode accepts HTTP only for a DNS hostname (not an IP literal) without +userinfo, query, fragment, or backslash. It checks every DNS answer against the +positive address allow-list in the +[NIP-FI JWKS snapshot contract](docs/nips/NIP-FI.md#jwks-snapshot), rejects +empty or mixed answers, and pins the first checked address. Mesh selection is +an operator assertion, not a transport property the Rust relay verifies. +Operators must enforce mutual TLS peer authentication and integrity +protection, authorize the JWKS endpoint, and restrict egress. Unauthenticated +HTTP permits key substitution and issuer impersonation. ### Audit Integrity @@ -776,7 +919,7 @@ Docker Compose provides the full local development stack. All services include h | Postgres | `postgres:17-alpine` | 5432 | Primary event store — events, channels, tokens, workflows, audit; full-text search (`search_tsv` GIN) | | Redis | `redis:7-alpine` | 6379 | Pub/sub fan-out, presence (SET EX), typing (sorted sets) | | Adminer | `adminer` | 8082 | DB web UI (dev only) | -| MinIO | `minio/minio` | 9000 (API), 9001 (console) | S3-compatible object storage (media) | +| Silo (MinIO fork) | `pgsty/silo` | 9000 (API), 9001 (console) | S3-compatible object storage (media) | | Prometheus | `prom/prometheus` | 9090 | Metrics collection | ### Postgres Schema (key tables) diff --git a/CHANGELOG.md b/CHANGELOG.md index eec43c38716..c8c8de39b99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,569 @@ # Changelog +## v0.5.28 + +### Desktop and shared changes + +- test(desktop): move CSP guards from Rust to the desktop JS suite ([#8172](https://github.com/block/buzz/pull/8172)) ([`5142cf6b2a0f44686eeda1ed07905ee3560fd78e`](https://github.com/block/buzz/commit/5142cf6b2a0f44686eeda1ed07905ee3560fd78e)) +- fix(desktop): repair the Windows notification shim's false denial on read ([#5600](https://github.com/block/buzz/pull/5600)) ([`99924a5a69200d34f5cc67e9b76748d7ece72705`](https://github.com/block/buzz/commit/99924a5a69200d34f5cc67e9b76748d7ece72705)) +- feat: raise hosted community limit to fifty ([#8186](https://github.com/block/buzz/pull/8186)) ([`8f66f7051c68560feb27dbc74b069c851bc018bd`](https://github.com/block/buzz/commit/8f66f7051c68560feb27dbc74b069c851bc018bd)) +- feat(desktop): browse and moderate every community in the Admin Console ([#8027](https://github.com/block/buzz/pull/8027)) ([`836e7d0d06789765b4d98a93c2b509a2a0fbd1bf`](https://github.com/block/buzz/commit/836e7d0d06789765b4d98a93c2b509a2a0fbd1bf)) +- Use Silo for bundled object storage ([#8023](https://github.com/block/buzz/pull/8023)) ([`d742fc5f304a430e94e89b0d4a427d17adc1a47f`](https://github.com/block/buzz/commit/d742fc5f304a430e94e89b0d4a427d17adc1a47f)) +- fix(desktop): address workflow deletions at the workflow's actual owner ([#2669](https://github.com/block/buzz/pull/2669)) ([`5ff83d82f852edb50a96cab4cb67a13baa8bf830`](https://github.com/block/buzz/commit/5ff83d82f852edb50a96cab4cb67a13baa8bf830)) +- fix(desktop): show OpenAI-compatible endpoint settings in the baked-env UI ([#8117](https://github.com/block/buzz/pull/8117)) ([`403c19f6734259cc22ef8ac0c90162ffceeec796`](https://github.com/block/buzz/commit/403c19f6734259cc22ef8ac0c90162ffceeec796)) +- feat(buzz-agent): send User-Agent on LLM requests ([#8116](https://github.com/block/buzz/pull/8116)) ([`1e2281fd45f0a18da95924fa445cd34080d349ea`](https://github.com/block/buzz/commit/1e2281fd45f0a18da95924fa445cd34080d349ea)) + +### Other repository changes + +- fix(mobile): normalize relay URL before disabling push ([#8201](https://github.com/block/buzz/pull/8201)) ([`394d4a434b70f6c14587174bc9942b3ba1d0eb59`](https://github.com/block/buzz/commit/394d4a434b70f6c14587174bc9942b3ba1d0eb59)) +- feat(buzz-db): run push enqueue and channel TTL refresh in app code ([#8135](https://github.com/block/buzz/pull/8135)) ([`16eb0b6685a9ea5cd06275aed172903dac69f225`](https://github.com/block/buzz/commit/16eb0b6685a9ea5cd06275aed172903dac69f225)) +- fix(mobile): keep thread content visible while positioning replies ([#8134](https://github.com/block/buzz/pull/8134)) ([`b6d97a69f0aeed53d58689c57a9939f8fab52093`](https://github.com/block/buzz/commit/b6d97a69f0aeed53d58689c57a9939f8fab52093)) +- fix(mobile): simplify notification settings ([#8199](https://github.com/block/buzz/pull/8199)) ([`e9269cbdf66b0e2fdb588aa20aad65bcba3ca622`](https://github.com/block/buzz/commit/e9269cbdf66b0e2fdb588aa20aad65bcba3ca622)) +- fix(push): stop backfilling messages on lease activation ([#8178](https://github.com/block/buzz/pull/8178)) ([`4db7bb0e7f904b2f0ea232aacae6cd7f6b8a3b39`](https://github.com/block/buzz/commit/4db7bb0e7f904b2f0ea232aacae6cd7f6b8a3b39)) +- docs(nip-ap): add teams and kind:44300 instructions versions ([#8191](https://github.com/block/buzz/pull/8191)) ([`acf1ede20288f5c31e1aae351c1559764b614c1f`](https://github.com/block/buzz/commit/acf1ede20288f5c31e1aae351c1559764b614c1f)) +- feat(db): advance an empty partition catch-all under bounded locks ([#7993](https://github.com/block/buzz/pull/7993)) ([`a8fe2b612c1c83de8f0983fa7a5cc1cb81ac7be8`](https://github.com/block/buzz/commit/a8fe2b612c1c83de8f0983fa7a5cc1cb81ac7be8)) +- fix(chart): own the Datadog version label on every workload Pod ([#7876](https://github.com/block/buzz/pull/7876)) ([`5a93e862ee28b8804f681ae15997a00bdc45d1bf`](https://github.com/block/buzz/commit/5a93e862ee28b8804f681ae15997a00bdc45d1bf)) +- fix(mobile): polish channel management and iOS Settings ([#8171](https://github.com/block/buzz/pull/8171)) ([`7e8aac44034a19a8ea845dbc5484e53eed7d02ef`](https://github.com/block/buzz/commit/7e8aac44034a19a8ea845dbc5484e53eed7d02ef)) +- fix(mobile): preserve Markdown attachment destinations ([#8168](https://github.com/block/buzz/pull/8168)) ([`1ac0a1271bfabe5a5af5578e2860c15fc8b0991e`](https://github.com/block/buzz/commit/1ac0a1271bfabe5a5af5578e2860c15fc8b0991e)) +- docs(nips): add NIP-FA federated identity adapter spec ([#8148](https://github.com/block/buzz/pull/8148)) ([`a918e605cae84789d7ec47df152219b4c341a1c7`](https://github.com/block/buzz/commit/a918e605cae84789d7ec47df152219b4c341a1c7)) +- feat(relay): record when a read-state account starts ([#8157](https://github.com/block/buzz/pull/8157)) ([`7afdc2aac930cd02001825d0b528f6f48595cd4a`](https://github.com/block/buzz/commit/7afdc2aac930cd02001825d0b528f6f48595cd4a)) +- ci: shorten the PR critical path (desktop lanes, smoke shards, parallel relay artifacts) ([#8156](https://github.com/block/buzz/pull/8156)) ([`d34c9c2c9b2e8e81675e8635c6b101481d561a97`](https://github.com/block/buzz/commit/d34c9c2c9b2e8e81675e8635c6b101481d561a97)) +- Preview Tabler icons in the mobile app ([#8109](https://github.com/block/buzz/pull/8109)) ([`bbcbd7ce139ccd24b39eb13df85bd294346a609c`](https://github.com/block/buzz/commit/bbcbd7ce139ccd24b39eb13df85bd294346a609c)) +- fix(deletion): give the scheduled drain the cold-start DB connector ([#8146](https://github.com/block/buzz/pull/8146)) ([`c6340a45a072c1793280cdcaec793d4a5dd82d97`](https://github.com/block/buzz/commit/c6340a45a072c1793280cdcaec793d4a5dd82d97)) +- refactor(schema): fan desired-state schema out to one file per table ([#8131](https://github.com/block/buzz/pull/8131)) ([`745501962e68041b3aee5c83fd3ea3bf5a496dbc`](https://github.com/block/buzz/commit/745501962e68041b3aee5c83fd3ea3bf5a496dbc)) +- refactor(db): type-level admitted event-write transactions (AdmittedTx) ([#8130](https://github.com/block/buzz/pull/8130)) ([`f8bf2c529cdf2c193ad0be6cf333def124d182f2`](https://github.com/block/buzz/commit/f8bf2c529cdf2c193ad0be6cf333def124d182f2)) +- fix(mobile): tolerate unrelated NIP-11 relay metadata ([#8160](https://github.com/block/buzz/pull/8160)) ([`70d2ca7760f5f6d5217e73d4921555bb3ce0c0e8`](https://github.com/block/buzz/commit/70d2ca7760f5f6d5217e73d4921555bb3ce0c0e8)) +- feat(admin): add community archive commands ([#7107](https://github.com/block/buzz/pull/7107)) ([`1972b7d256a5d0bb90eea6ef78e93d6b55bb1a12`](https://github.com/block/buzz/commit/1972b7d256a5d0bb90eea6ef78e93d6b55bb1a12)) +- feat(relay): add community reads to the admin API ([#8011](https://github.com/block/buzz/pull/8011)) ([`032198ce43680947c288bfd219d6a9b81d882348`](https://github.com/block/buzz/commit/032198ce43680947c288bfd219d6a9b81d882348)) +- fix(ios): use the shared glass capsule for thread titles ([#8150](https://github.com/block/buzz/pull/8150)) ([`f260ad7f957ab0d4e491cc75bffefce321ee9430`](https://github.com/block/buzz/commit/f260ad7f957ab0d4e491cc75bffefce321ee9430)) +- perf(relay): bound fleet usage metrics collection ([#7176](https://github.com/block/buzz/pull/7176)) ([`6d07a291376477942b70ba44489a47c9f6bfe006`](https://github.com/block/buzz/commit/6d07a291376477942b70ba44489a47c9f6bfe006)) +- fix(ios): let channel titles use available navigation space ([#8137](https://github.com/block/buzz/pull/8137)) ([`c96d707f6efd359e6cfdc34bd93c8b5fb36f1d5d`](https://github.com/block/buzz/commit/c96d707f6efd359e6cfdc34bd93c8b5fb36f1d5d)) +- buzz-db: purge retention-free deletions in the app and index mentions in the event transaction ([#8128](https://github.com/block/buzz/pull/8128)) ([`da651ad6726154ff1fe314fc64462031970f1106`](https://github.com/block/buzz/commit/da651ad6726154ff1fe314fc64462031970f1106)) +- feat(relay): time post-metrics-bind startup steps ([#8132](https://github.com/block/buzz/pull/8132)) ([`e097c42996c9a634209fd46df86998ee4a71ea48`](https://github.com/block/buzz/commit/e097c42996c9a634209fd46df86998ee4a71ea48)) +- release: push gateway chart 0.3.5 ([#8141](https://github.com/block/buzz/pull/8141)) ([`bd1ff00e487d473bb60691f023a360d4d89e3079`](https://github.com/block/buzz/commit/bd1ff00e487d473bb60691f023a360d4d89e3079)) +- feat(push): support Deployment metadata annotations ([#8136](https://github.com/block/buzz/pull/8136)) ([`9f5a25a41ed292576e27be59f902270e63636eaf`](https://github.com/block/buzz/commit/9f5a25a41ed292576e27be59f902270e63636eaf)) +- fix(buzz-pair): install rustls ring CryptoProvider before WSS ([#7998](https://github.com/block/buzz/pull/7998)) ([`b9e851d7be0af4f7f13294a8cb41de257f0dcf12`](https://github.com/block/buzz/commit/b9e851d7be0af4f7f13294a8cb41de257f0dcf12)) +- fix(buzz-acp): bound sibling-gate lookup failures instead of caching them ([#7216](https://github.com/block/buzz/pull/7216)) ([`003770cb7961adb8dd4905823dfe76dfcf5e07c7`](https://github.com/block/buzz/commit/003770cb7961adb8dd4905823dfe76dfcf5e07c7)) +- feat(relay): private read-state accessory API ([#7906](https://github.com/block/buzz/pull/7906)) ([`1a2ddf9eaa87031a0d49ca1d882a46b5b89beb8d`](https://github.com/block/buzz/commit/1a2ddf9eaa87031a0d49ca1d882a46b5b89beb8d)) +- fix(acp): keep agent-to-agent thread replies in the thread ([#8124](https://github.com/block/buzz/pull/8124)) ([`46dcc01873aae7ef926c2c9be7c5d360f296ac94`](https://github.com/block/buzz/commit/46dcc01873aae7ef926c2c9be7c5d360f296ac94)) +- release: push gateway chart 0.3.4 ([#8126](https://github.com/block/buzz/pull/8126)) ([`c6dd587e2ae3ee7c0abb15a93437edf1ecb52860`](https://github.com/block/buzz/commit/c6dd587e2ae3ee7c0abb15a93437edf1ecb52860)) +- feat(push): support platform-managed gateway runtime pods ([#8113](https://github.com/block/buzz/pull/8113)) ([`73a2a05c973bb97593f2d456c23a2ccdfe1a7bec`](https://github.com/block/buzz/commit/73a2a05c973bb97593f2d456c23a2ccdfe1a7bec)) + +[Compare desktop-v0.5.27...desktop-v0.5.28](https://github.com/block/buzz/compare/desktop-v0.5.27...desktop-v0.5.28) + +## v0.5.27 + +### Desktop and shared changes + +- feat(desktop): offer Claude effort levels in agent edit and create ([#8059](https://github.com/block/buzz/pull/8059)) ([`9c6fa14aa03358b4188f2ce0a92a9e435a3cb41b`](https://github.com/block/buzz/commit/9c6fa14aa03358b4188f2ce0a92a9e435a3cb41b)) +- fix(desktop): use object-scale-down for inline markdown images ([#4686](https://github.com/block/buzz/pull/4686)) ([`fcf5f044b3af56f3855a417e61e4389fa925c1bd`](https://github.com/block/buzz/commit/fcf5f044b3af56f3855a417e61e4389fa925c1bd)) +- fix(desktop): detect Kimi Code in its default install path ([#3700](https://github.com/block/buzz/pull/3700)) ([`964b556a429c77c43df8429e97e3648f42d47d52`](https://github.com/block/buzz/commit/964b556a429c77c43df8429e97e3648f42d47d52)) +- feat(pairing): enter desktop codes on mobile ([#8085](https://github.com/block/buzz/pull/8085)) ([`5173fad6602ae82c06f338d19ef0f18eff57159b`](https://github.com/block/buzz/commit/5173fad6602ae82c06f338d19ef0f18eff57159b)) +- fix(desktop): show readable Claude Code model names and descriptions ([#8053](https://github.com/block/buzz/pull/8053)) ([`5a4b2d3dcc422954b4bd5829310a40f12b3cb03d`](https://github.com/block/buzz/commit/5a4b2d3dcc422954b4bd5829310a40f12b3cb03d)) +- feat(agents): request summarized Claude thinking and label empty rows ([#8051](https://github.com/block/buzz/pull/8051)) ([`cc528dbe0538cff0357b7644a9466ad689a1874f`](https://github.com/block/buzz/commit/cc528dbe0538cff0357b7644a9466ad689a1874f)) +- fix(mcp): support Goose discovery handshake ([#8037](https://github.com/block/buzz/pull/8037)) ([`4f51b9e1010e086a16c099cd8d8218ca974a5e18`](https://github.com/block/buzz/commit/4f51b9e1010e086a16c099cd8d8218ca974a5e18)) +- test(agent): synchronize handoff steering with tool approval ([#8042](https://github.com/block/buzz/pull/8042)) ([`2c270cf9d7849b6fc596a17608d78d91e2c10507`](https://github.com/block/buzz/commit/2c270cf9d7849b6fc596a17608d78d91e2c10507)) +- fix(acp): wake agents for mentions added by edits ([#6131](https://github.com/block/buzz/pull/6131)) ([`47654215ebe44829941e6d7edc635ef401e8d8e8`](https://github.com/block/buzz/commit/47654215ebe44829941e6d7edc635ef401e8d8e8)) +- fix(relay): close community ban gaps across audio, agents and HTTP ([#8005](https://github.com/block/buzz/pull/8005)) ([`a38707d35c5d7028a83dcb4b85482a26f8b67605`](https://github.com/block/buzz/commit/a38707d35c5d7028a83dcb4b85482a26f8b67605)) +- feat(acp): add BUZZ_GIT_IDENTITY switch for agent commit identity ([#8024](https://github.com/block/buzz/pull/8024)) ([`d1b7da45a232316118d33793c15cbc45e4a86976`](https://github.com/block/buzz/commit/d1b7da45a232316118d33793c15cbc45e4a86976)) +- test(desktop): pin mention undo and status expiry smoke behavior ([#7592](https://github.com/block/buzz/pull/7592)) ([`04b040ef6ce1a748fb2418340735cfc04e0fd8f4`](https://github.com/block/buzz/commit/04b040ef6ce1a748fb2418340735cfc04e0fd8f4)) +- feat(desktop): remove communities locally and stop their agent pairs ([#7997](https://github.com/block/buzz/pull/7997)) ([`83aab8cb5c4fb1f7b73d8782ae44edc8f6df4dce`](https://github.com/block/buzz/commit/83aab8cb5c4fb1f7b73d8782ae44edc8f6df4dce)) +- Allow following channel messages before their first reply ([#7692](https://github.com/block/buzz/pull/7692)) ([`036215636f530a93ef5e0cddf985e579ed52e393`](https://github.com/block/buzz/commit/036215636f530a93ef5e0cddf985e579ed52e393)) +- Fix rounded macOS icon on older Macs ([#8018](https://github.com/block/buzz/pull/8018)) ([`0ee2ad7fbf49dff593c34ab50dd32f891845611b`](https://github.com/block/buzz/commit/0ee2ad7fbf49dff593c34ab50dd32f891845611b)) +- fix(desktop): read channel metadata and member lists from writer after writes ([#7999](https://github.com/block/buzz/pull/7999)) ([`bd0896f5c0dfcc6d0c27b23ba644dff63e50617a`](https://github.com/block/buzz/commit/bd0896f5c0dfcc6d0c27b23ba644dff63e50617a)) +- feat(desktop): add Admin Console Actions tab for direct staff actions ([#7904](https://github.com/block/buzz/pull/7904)) ([`f001ebbb6ea5ad2cf262fcd0f05e1cd2ae83bb7f`](https://github.com/block/buzz/commit/f001ebbb6ea5ad2cf262fcd0f05e1cd2ae83bb7f)) +- fix(agents): stop built-in prompts from teaching sleep polling ([#7992](https://github.com/block/buzz/pull/7992)) ([`965e1997b5de462a3b87a3c455d0db00261a06b3`](https://github.com/block/buzz/commit/965e1997b5de462a3b87a3c455d0db00261a06b3)) +- feat(relay): add direct staff ban/timeout/delete with staff guard ([#7883](https://github.com/block/buzz/pull/7883)) ([`020193f8e36bede04a57e0c06ba60e26ed67612b`](https://github.com/block/buzz/commit/020193f8e36bede04a57e0c06ba60e26ed67612b)) +- feat(acp): wrap workers at the subprocess launch boundary ([#7985](https://github.com/block/buzz/pull/7985)) ([`95b018c8713be9beebbd2517ace48529e3c0e6ed`](https://github.com/block/buzz/commit/95b018c8713be9beebbd2517ace48529e3c0e6ed)) +- Add Kimi Code's default install path to managed-agent binary discovery ([#5997](https://github.com/block/buzz/pull/5997)) ([`2664d14316790a57ea44b3f97c57440b70e43436`](https://github.com/block/buzz/commit/2664d14316790a57ea44b3f97c57440b70e43436)) +- test(desktop): fix flaky forum empty-draft replacement e2e ([#7981](https://github.com/block/buzz/pull/7981)) ([`12dbb114aad72b89d17d6d1c668d8d4c3fdad2ae`](https://github.com/block/buzz/commit/12dbb114aad72b89d17d6d1c668d8d4c3fdad2ae)) + +### Other repository changes + +- docs(changelog): remove hand-written Unreleased section ([#8123](https://github.com/block/buzz/pull/8123)) ([`af5bb0af488784c3707e99c87e0675a729711a6e`](https://github.com/block/buzz/commit/af5bb0af488784c3707e99c87e0675a729711a6e)) +- BUZZ-175: Route serving event writes through the tenant lock ([#7828](https://github.com/block/buzz/pull/7828)) ([`d0fd96fca6704548cebe2f69d8dff0e3c80e77e2`](https://github.com/block/buzz/commit/d0fd96fca6704548cebe2f69d8dff0e3c80e77e2)) +- feat(mobile): follow the portable mention rules, including DMs ([#8102](https://github.com/block/buzz/pull/8102)) ([`932228936464a0bdd44eae0f5e95ca5bbcd819b9`](https://github.com/block/buzz/commit/932228936464a0bdd44eae0f5e95ca5bbcd819b9)) +- feat(mobile): read web app catch-up marks for unread state ([#8103](https://github.com/block/buzz/pull/8103)) ([`166d383ca7aa9ffd5796ad7e4d3be1884d81da73`](https://github.com/block/buzz/commit/166d383ca7aa9ffd5796ad7e4d3be1884d81da73)) +- docs(identity): tighten enterprise adapter contract ([#8069](https://github.com/block/buzz/pull/8069)) ([`1e67395fd19a8b4de0cecca97cd1b36842fe8b77`](https://github.com/block/buzz/commit/1e67395fd19a8b4de0cecca97cd1b36842fe8b77)) +- chore(push): release gateway chart 0.3.3 ([#8107](https://github.com/block/buzz/pull/8107)) ([`c9143ed8f709a06db9f4e6994f3ffa39aa5f3950`](https://github.com/block/buzz/commit/c9143ed8f709a06db9f4e6994f3ffa39aa5f3950)) +- fix(acp): steer mid-turn DM follow-ups natively again ([#8058](https://github.com/block/buzz/pull/8058)) ([`0a070dfd3f3c233ea71bf390813abee4032068cb`](https://github.com/block/buzz/commit/0a070dfd3f3c233ea71bf390813abee4032068cb)) +- feat(push): support migration pod annotations ([#8105](https://github.com/block/buzz/pull/8105)) ([`fd885b553004520ce5ed5dffdb085957d01a80cd`](https://github.com/block/buzz/commit/fd885b553004520ce5ed5dffdb085957d01a80cd)) +- fix(db): enumerate only active communities for maintenance ([#8061](https://github.com/block/buzz/pull/8061)) ([`7f6ffd5ee5ae1b66d660245acf465b88e17639bc`](https://github.com/block/buzz/commit/7f6ffd5ee5ae1b66d660245acf465b88e17639bc)) +- Polish iOS header glass and scroll-edge blur ([#8097](https://github.com/block/buzz/pull/8097)) ([`8746bfebfffd31e418b439d262cbb70de54aafa4`](https://github.com/block/buzz/commit/8746bfebfffd31e418b439d262cbb70de54aafa4)) +- fix(mobile): fill and stabilize content-aware loading placeholders ([#8083](https://github.com/block/buzz/pull/8083)) ([`46e60206a47ed1f696d625df57a1e5dd2d019a42`](https://github.com/block/buzz/commit/46e60206a47ed1f696d625df57a1e5dd2d019a42)) +- fix(mobile): polish photo carousels and video viewer controls ([#8079](https://github.com/block/buzz/pull/8079)) ([`f0eb5575ffc9d5f57af4ed3f574529d997c83a0d`](https://github.com/block/buzz/commit/f0eb5575ffc9d5f57af4ed3f574529d997c83a0d)) +- fix(mobile): align Android conversation headers and reactions ([#8082](https://github.com/block/buzz/pull/8082)) ([`5f2d801b8f1d7be0c06839bded3f0391cbb46f92`](https://github.com/block/buzz/commit/5f2d801b8f1d7be0c06839bded3f0391cbb46f92)) +- fix(mobile): unify sheet sections and bottom spacing ([#8081](https://github.com/block/buzz/pull/8081)) ([`75a4efd0cabed81c1583cb3868b232b4bde50c81`](https://github.com/block/buzz/commit/75a4efd0cabed81c1583cb3868b232b4bde50c81)) +- feat(mobile): add iOS Liquid Glass tabs and quick actions ([#8080](https://github.com/block/buzz/pull/8080)) ([`03f24a69bf34adf25bc7f85aa00ab74c9e80c759`](https://github.com/block/buzz/commit/03f24a69bf34adf25bc7f85aa00ab74c9e80c759)) +- feat(mobile): add animated community switcher ([#8076](https://github.com/block/buzz/pull/8076)) ([`d2da104d947e07dd0c203dabd92f245eeca6b672`](https://github.com/block/buzz/commit/d2da104d947e07dd0c203dabd92f245eeca6b672)) +- fix(mobile): manage channel members from profile sheets ([#8078](https://github.com/block/buzz/pull/8078)) ([`05d1714912589737636735baac8e5edce2c26ee1`](https://github.com/block/buzz/commit/05d1714912589737636735baac8e5edce2c26ee1)) +- fix(mobile): refine iOS navigation and conversation details ([#8075](https://github.com/block/buzz/pull/8075)) ([`a14107ab2edee286d3a458a1a4c1ec26e7be8a17`](https://github.com/block/buzz/commit/a14107ab2edee286d3a458a1a4c1ec26e7be8a17)) +- docs: restore enterprise identity adapter contract with relay assertion ([#8064](https://github.com/block/buzz/pull/8064)) ([`e982f70fba29cdaa9a8378f118a0e498537bd8db`](https://github.com/block/buzz/commit/e982f70fba29cdaa9a8378f118a0e498537bd8db)) +- Use native iOS navigation bars with large titles and avatars ([#8052](https://github.com/block/buzz/pull/8052)) ([`6cf45820025721367c9f174aae164c8cf9a52a19`](https://github.com/block/buzz/commit/6cf45820025721367c9f174aae164c8cf9a52a19)) +- feat(mobile): organize community and profile settings ([#8056](https://github.com/block/buzz/pull/8056)) ([`33f54de2dd27a8f6bce0d359183f5ebe5f2fa9ba`](https://github.com/block/buzz/commit/33f54de2dd27a8f6bce0d359183f5ebe5f2fa9ba)) +- refactor(relay): bind HTTP tenants through one shadow-aware helper ([#8062](https://github.com/block/buzz/pull/8062)) ([`8af2d91f37270365d5cd9170ac48349baa08475e`](https://github.com/block/buzz/commit/8af2d91f37270365d5cd9170ac48349baa08475e)) +- feat(relay): add NIP-FI shadow mode for HTTP, WebSocket and admin ([#8034](https://github.com/block/buzz/pull/8034)) ([`df3f28a2c44f0bd258cff046717cde3fa026662e`](https://github.com/block/buzz/commit/df3f28a2c44f0bd258cff046717cde3fa026662e)) +- BUZZ-175: Add application-owned writer lock foundations ([#7706](https://github.com/block/buzz/pull/7706)) ([`fe9e2409a02fbac415d5c66181135be3eec28a86`](https://github.com/block/buzz/commit/fe9e2409a02fbac415d5c66181135be3eec28a86)) +- feat(mobile): native iOS message menus and reaction sheets ([#8055](https://github.com/block/buzz/pull/8055)) ([`ea143ea64beb79abacf423920cd70bbf23698b64`](https://github.com/block/buzz/commit/ea143ea64beb79abacf423920cd70bbf23698b64)) +- fix(acp): steer running turns with edited mentions ([#6132](https://github.com/block/buzz/pull/6132)) ([`133fb9869228dab4c00cb2b9e259bf834a55dbf7`](https://github.com/block/buzz/commit/133fb9869228dab4c00cb2b9e259bf834a55dbf7)) +- test(relay): configure a community in the Git ban-lookup fixture ([#8039](https://github.com/block/buzz/pull/8039)) ([`448407a972ca9da0c1e13d49ee2c2170821be8a2`](https://github.com/block/buzz/commit/448407a972ca9da0c1e13d49ee2c2170821be8a2)) +- fix(acp): wake quiet hosts for respawns and queued retries ([#7459](https://github.com/block/buzz/pull/7459)) ([`e4681e44a72fa3c4c873d0315024187351f4068d`](https://github.com/block/buzz/commit/e4681e44a72fa3c4c873d0315024187351f4068d)) +- fix(relay): restore buzz-relay build after #8005 and #8028 ([#8036](https://github.com/block/buzz/pull/8036)) ([`639593bba97b4ed1386d5128bceecfab2072df31`](https://github.com/block/buzz/commit/639593bba97b4ed1386d5128bceecfab2072df31)) +- fix(mobile): preserve exact mention recipients in saved drafts ([#7387](https://github.com/block/buzz/pull/7387)) ([`2782b9cd5ea11d31954fae0e080d1446533f4e8f`](https://github.com/block/buzz/commit/2782b9cd5ea11d31954fae0e080d1446533f4e8f)) +- feat(nip-fi): bind assertions to the request Host's community ([#8028](https://github.com/block/buzz/pull/8028)) ([`2ebfde9147140a4036b11bfc2c6b0da68688a05c`](https://github.com/block/buzz/commit/2ebfde9147140a4036b11bfc2c6b0da68688a05c)) +- refactor(buzz-relay): share NIP-FI assertion evaluation across adapters ([#7990](https://github.com/block/buzz/pull/7990)) ([`9b083957f6802fd8e0efc7414269714619139cf2`](https://github.com/block/buzz/commit/9b083957f6802fd8e0efc7414269714619139cf2)) +- Include thread roots in agent activity events ([#8029](https://github.com/block/buzz/pull/8029)) ([`2e8b8d9a92b080024356004955625615c33ee543`](https://github.com/block/buzz/commit/2e8b8d9a92b080024356004955625615c33ee543)) +- fix(relay): gate owner-only kinds in shared fan-out access filter ([#8006](https://github.com/block/buzz/pull/8006)) ([`24c1e702a68c7b1623f4a33dd2745a39b0597098`](https://github.com/block/buzz/commit/24c1e702a68c7b1623f4a33dd2745a39b0597098)) +- fix(relay): deny channel writes when the channel lookup fails ([#8007](https://github.com/block/buzz/pull/8007)) ([`15772c54f36d1ed68c9c77ffb63235acb5ee8a64`](https://github.com/block/buzz/commit/15772c54f36d1ed68c9c77ffb63235acb5ee8a64)) +- feat(nip-fi): admin disconnect/deny API with in-memory deny-until-TTL map (S4) ([#7977](https://github.com/block/buzz/pull/7977)) ([`16839a07738cf6189ee2f21c02d923b0f9dbe80d`](https://github.com/block/buzz/commit/16839a07738cf6189ee2f21c02d923b0f9dbe80d)) +- fix(mobile): hide notification settings without relay push capability ([#8025](https://github.com/block/buzz/pull/8025)) ([`fad4ff637a56a80e4871b5591a7aca58964ca903`](https://github.com/block/buzz/commit/fad4ff637a56a80e4871b5591a7aca58964ca903)) +- test(mobile): cover presence ordering against delayed live events ([#7526](https://github.com/block/buzz/pull/7526)) ([`2cca0ec15789370d494f06192f71400afdb60c98`](https://github.com/block/buzz/commit/2cca0ec15789370d494f06192f71400afdb60c98)) +- fix(acp): add edit field to native-steer fallback test event ([#8022](https://github.com/block/buzz/pull/8022)) ([`d56ed75424d803cf29b2f1f4f430ee81dc145f92`](https://github.com/block/buzz/commit/d56ed75424d803cf29b2f1f4f430ee81dc145f92)) +- fix(acp): interrupted frame writes close the sole writer; fixed native-steer refusal reasons ([#7568](https://github.com/block/buzz/pull/7568)) ([`514a9a86d3664fdd5d40457b7db09dccc5b27b3c`](https://github.com/block/buzz/commit/514a9a86d3664fdd5d40457b7db09dccc5b27b3c)) +- feat(mobile): refresh onboarding and smooth QR scanner motion ([#8019](https://github.com/block/buzz/pull/8019)) ([`6b5bb6f5a3fbad1ca42d8f9b14a1418d333b6461`](https://github.com/block/buzz/commit/6b5bb6f5a3fbad1ca42d8f9b14a1418d333b6461)) +- fix(acp): preserve routing for edited messages ([#4741](https://github.com/block/buzz/pull/4741)) ([`5fdb2e53659ee29002545f1022c138fe0b8282f9`](https://github.com/block/buzz/commit/5fdb2e53659ee29002545f1022c138fe0b8282f9)) +- fix(mobile): distinguish unknown presence on identity surfaces ([#7383](https://github.com/block/buzz/pull/7383)) ([`cf5e83829a9e9ace6332bf1d0793aa31030b7eeb`](https://github.com/block/buzz/commit/cf5e83829a9e9ace6332bf1d0793aa31030b7eeb)) +- fix(mobile): hydrate and refresh relay presence snapshots ([#7382](https://github.com/block/buzz/pull/7382)) ([`965fe1dffa12e2fa5419bf61cbcfed1b3691b0d1`](https://github.com/block/buzz/commit/965fe1dffa12e2fa5419bf61cbcfed1b3691b0d1)) +- fix(deletion): require sole owner at admission ([#7966](https://github.com/block/buzz/pull/7966)) ([`53a12100b34577286c89102f1875ca2b6eea61e5`](https://github.com/block/buzz/commit/53a12100b34577286c89102f1875ca2b6eea61e5)) +- fix(ci): gate security review on repo write access ([#7986](https://github.com/block/buzz/pull/7986)) ([`0ee609379004a894e99b449885c37a044f41919e`](https://github.com/block/buzz/commit/0ee609379004a894e99b449885c37a044f41919e)) +- feat(buzz-relay): idempotent owner community deletion with quota reservation ([#7969](https://github.com/block/buzz/pull/7969)) ([`d7a35afa9859a0c666de93ab1cd4f8a433a1cfe8`](https://github.com/block/buzz/commit/d7a35afa9859a0c666de93ab1cd4f8a433a1cfe8)) +- feat(mobile): show contextual names in lists, Search and Pulse ([#7896](https://github.com/block/buzz/pull/7896)) ([`7a1910e700c08358292ec82fdc93464be8f00274`](https://github.com/block/buzz/commit/7a1910e700c08358292ec82fdc93464be8f00274)) + +[Compare desktop-v0.5.26...desktop-v0.5.27](https://github.com/block/buzz/compare/desktop-v0.5.26...desktop-v0.5.27) + +## v0.5.26 + +### Desktop and shared changes + +- fix(desktop): correct Grok Build setup guide URL ([#4846](https://github.com/block/buzz/pull/4846)) ([`7ebf1beb44139264e9c5c7fee6970429ff66f934`](https://github.com/block/buzz/commit/7ebf1beb44139264e9c5c7fee6970429ff66f934)) +- feat(relay): implement NIP-AR channel artifacts ([#7919](https://github.com/block/buzz/pull/7919)) ([`12670bd0f037c66a682272bb81c46c3f254fad74`](https://github.com/block/buzz/commit/12670bd0f037c66a682272bb81c46c3f254fad74)) +- fix(desktop): resolve unlisted project channel requests ([#7619](https://github.com/block/buzz/pull/7619)) ([`c96553eb13a073ca9f4ee1547b50ba3d28dfd4db`](https://github.com/block/buzz/commit/c96553eb13a073ca9f4ee1547b50ba3d28dfd4db)) +- Schedule the deletion drain safely ([#7827](https://github.com/block/buzz/pull/7827)) ([`6918dd3a83fd7aacf6d8e4634d3864eb10ead61d`](https://github.com/block/buzz/commit/6918dd3a83fd7aacf6d8e4634d3864eb10ead61d)) +- test(desktop): wait for channel head refresh before paging thread summary test ([#7955](https://github.com/block/buzz/pull/7955)) ([`f1e50be4103addabd497563495e0ffe5bda07ef7`](https://github.com/block/buzz/commit/f1e50be4103addabd497563495e0ffe5bda07ef7)) +- 🤖 perf: bound long-thread aux reads and make query deadlines terminal ([#7854](https://github.com/block/buzz/pull/7854)) ([`9b1c4f98e2981d6d89fbfa3154b8ef0b3b6ad334`](https://github.com/block/buzz/commit/9b1c4f98e2981d6d89fbfa3154b8ef0b3b6ad334)) +- Add native HPKE encryption for nsec backups ([#7849](https://github.com/block/buzz/pull/7849)) ([`cc36d25bec2d34340ab7aace50110f51162edd7a`](https://github.com/block/buzz/commit/cc36d25bec2d34340ab7aace50110f51162edd7a)) +- test(desktop): scope video menu e2e probes to emitted messages ([#7953](https://github.com/block/buzz/pull/7953)) ([`548718e042decbc059fd7ebfb9b9ad2459ac258d`](https://github.com/block/buzz/commit/548718e042decbc059fd7ebfb9b9ad2459ac258d)) +- fix(sidebar): converge stale-at-open state across devices (sections/sort/stars/mutes) ([#7805](https://github.com/block/buzz/pull/7805)) ([`52c4c08c9ef349f2bb994ca40e98faa0f44209ea`](https://github.com/block/buzz/commit/52c4c08c9ef349f2bb994ca40e98faa0f44209ea)) +- feat(nip-fi): harden Blossom kind-24242 verifier to NIP-FI spec ([#7288](https://github.com/block/buzz/pull/7288)) ([`f7ff4294fa95191d1fc7b29a765e6f0b48db6bd8`](https://github.com/block/buzz/commit/f7ff4294fa95191d1fc7b29a765e6f0b48db6bd8)) +- fix(ci): select runtime suites from PR changes only ([#7843](https://github.com/block/buzz/pull/7843)) ([`02c6309f534050e54c8d36f5ce90e48e4dd152b1`](https://github.com/block/buzz/commit/02c6309f534050e54c8d36f5ce90e48e4dd152b1)) +- test(desktop): synchronize upload edit smoke test ([#7903](https://github.com/block/buzz/pull/7903)) ([`a1fb6645d994e72b5f39fae8bd482d400e4005b6`](https://github.com/block/buzz/commit/a1fb6645d994e72b5f39fae8bd482d400e4005b6)) +- feat(desktop): relay admin console for the /api/admin/v1 operator surface ([#4768](https://github.com/block/buzz/pull/4768)) ([`8f8c4dfadecb2298a9140af5d323487aaad844ab`](https://github.com/block/buzz/commit/8f8c4dfadecb2298a9140af5d323487aaad844ab)) + +### Other repository changes + +- fix(db): audit partition catalog before creation ([#6515](https://github.com/block/buzz/pull/6515)) ([`14a752fb2445790bf4620348e485e8576371f906`](https://github.com/block/buzz/commit/14a752fb2445790bf4620348e485e8576371f906)) +- feat(mobile): show contextual names in channel conversations ([#7895](https://github.com/block/buzz/pull/7895)) ([`4ef23609b7025bc356a9ea078834d57b69ec33cf`](https://github.com/block/buzz/commit/4ef23609b7025bc356a9ea078834d57b69ec33cf)) +- feat(buzz-relay): NIP-FI stateless enforcement (S3) — upgrade gate, NIP-42 pairing, session lifetime, JWKS warm ([#7224](https://github.com/block/buzz/pull/7224)) ([`8519db1532efd6cda8f72bb6454c00fc3f87cfba`](https://github.com/block/buzz/commit/8519db1532efd6cda8f72bb6454c00fc3f87cfba)) +- feat(web): add Browse releases link next to invite download ([#2255](https://github.com/block/buzz/pull/2255)) ([`b9d22a273f2225917f13b13a9fde305629126502`](https://github.com/block/buzz/commit/b9d22a273f2225917f13b13a9fde305629126502)) +- docs(nips): fix stray angle brackets in created_at clauses ([#4486](https://github.com/block/buzz/pull/4486)) ([`12423f2868b810240a6b949d21c8a09e9e8a1994`](https://github.com/block/buzz/commit/12423f2868b810240a6b949d21c8a09e9e8a1994)) +- docs: specify desktop-driven mobile push suppression ([#7809](https://github.com/block/buzz/pull/7809)) ([`45c288c1793bbbbbbb1be88f8a53c6aecfff8d2f`](https://github.com/block/buzz/commit/45c288c1793bbbbbbb1be88f8a53c6aecfff8d2f)) +- feat(mobile): add the contextual identity-name resolver ([#7894](https://github.com/block/buzz/pull/7894)) ([`efe04288ea907adfe91a38ae916c0d364c315cca`](https://github.com/block/buzz/commit/efe04288ea907adfe91a38ae916c0d364c315cca)) +- Automate owner deletion preparation ([#7830](https://github.com/block/buzz/pull/7830)) ([`bba75a71eb5a719b597479ec848053cde364befd`](https://github.com/block/buzz/commit/bba75a71eb5a719b597479ec848053cde364befd)) +- fix(mobile): stale community selection during mobile invite setup ([#7951](https://github.com/block/buzz/pull/7951)) ([`662014d544f835a075f0020e7d161fe7985d7959`](https://github.com/block/buzz/commit/662014d544f835a075f0020e7d161fe7985d7959)) +- Add owner deletion admission control plane ([#7818](https://github.com/block/buzz/pull/7818)) ([`15d44dcceee0679979991b3100f21f01fc799693`](https://github.com/block/buzz/commit/15d44dcceee0679979991b3100f21f01fc799693)) +- Make relay readiness process-local ([#7341](https://github.com/block/buzz/pull/7341)) ([`b37e477211313a94344a31aea4b180ed4effe0b8`](https://github.com/block/buzz/commit/b37e477211313a94344a31aea4b180ed4effe0b8)) +- 🤖 docs(nip-fi): remove implementation references from the spec ([#7912](https://github.com/block/buzz/pull/7912)) ([`447951a19c00edfa6432636f50782445929ab678`](https://github.com/block/buzz/commit/447951a19c00edfa6432636f50782445929ab678)) +- fix(relay): fail startup on invalid operator listener config ([#7933](https://github.com/block/buzz/pull/7933)) ([`ebe99a46e8802b9ff20fdf6a1028ce93bdefaa43`](https://github.com/block/buzz/commit/ebe99a46e8802b9ff20fdf6a1028ce93bdefaa43)) +- fix(db): limit event transactions to listener mention kinds ([#7932](https://github.com/block/buzz/pull/7932)) ([`1846094b3111a059f856bb4f3466c102fad17ef7`](https://github.com/block/buzz/commit/1846094b3111a059f856bb4f3466c102fad17ef7)) +- feat(relay): deliver pubkey mentions to relay companions ([#7793](https://github.com/block/buzz/pull/7793)) ([`c4c86006f2d67b2ea9055780129ee7ce95c54e0a`](https://github.com/block/buzz/commit/c4c86006f2d67b2ea9055780129ee7ce95c54e0a)) +- docs(protocol): propose simplified channel artifacts ([#7791](https://github.com/block/buzz/pull/7791)) ([`b0d6fb8ad27f6f255a5044e49ed0a59e11542914`](https://github.com/block/buzz/commit/b0d6fb8ad27f6f255a5044e49ed0a59e11542914)) +- feat(push): support configurable HTTP(S) delivery URLs ([#7877](https://github.com/block/buzz/pull/7877)) ([`781d39510cf23cfe224e8f521ae06a23377e06de`](https://github.com/block/buzz/commit/781d39510cf23cfe224e8f521ae06a23377e06de)) +- feat(relay): enforce NIP-FI assertion+NIP-98 pairing on HTTP ingress ([#7264](https://github.com/block/buzz/pull/7264)) ([`6410e685a80d42db0645fadc9bbe710559ef911e`](https://github.com/block/buzz/commit/6410e685a80d42db0645fadc9bbe710559ef911e)) +- fix(ci): run the admin disabled-mode DB test in the PostgreSQL lane ([#7900](https://github.com/block/buzz/pull/7900)) ([`b65cff31a4c5f4a0af63952b60a21fd73195321a`](https://github.com/block/buzz/commit/b65cff31a4c5f4a0af63952b60a21fd73195321a)) +- 🤖 docs: add pre-PR checklist and review guidance to AGENTS.md ([#7897](https://github.com/block/buzz/pull/7897)) ([`9c7687cc914cd8eddee7ba25cb980ad1a6bc0fdc`](https://github.com/block/buzz/commit/9c7687cc914cd8eddee7ba25cb980ad1a6bc0fdc)) +- docs: specify durable data backfills ([#7326](https://github.com/block/buzz/pull/7326)) ([`9263cda8455b8fd27f4491e5e4fc0ebc2ce2e8bc`](https://github.com/block/buzz/commit/9263cda8455b8fd27f4491e5e4fc0ebc2ce2e8bc)) +- docs(vision): add /buzz/v1 read endpoints to the protocol contract ([#7879](https://github.com/block/buzz/pull/7879)) ([`930b8bb800d8149ce29a881ba4c5d9f424580434`](https://github.com/block/buzz/commit/930b8bb800d8149ce29a881ba4c5d9f424580434)) +- 🤖 fix(justfile): point just staging at the current staging relay ([#7881](https://github.com/block/buzz/pull/7881)) ([`20131488528e35e6c50f4ccdb0490a9135c28edf`](https://github.com/block/buzz/commit/20131488528e35e6c50f4ccdb0490a9135c28edf)) +- fix(relay-admin): make thread deletions atomic and fence expired action leases under row lock ([#7853](https://github.com/block/buzz/pull/7853)) ([`676e8c43825fa478850a3a320b1367d3288cce1a`](https://github.com/block/buzz/commit/676e8c43825fa478850a3a320b1367d3288cce1a)) +- fix(mobile): keep retired sections manager out of successor cache ([#7873](https://github.com/block/buzz/pull/7873)) ([`28a8b90805278a91d723731bf7b824cea473bcfa`](https://github.com/block/buzz/commit/28a8b90805278a91d723731bf7b824cea473bcfa)) +- Select one feature flag provider at compile time ([#7677](https://github.com/block/buzz/pull/7677)) ([`8f6b66f9ff6b2e42cd713506805763269375b473`](https://github.com/block/buzz/commit/8f6b66f9ff6b2e42cd713506805763269375b473)) + +[Compare desktop-v0.5.25...desktop-v0.5.26](https://github.com/block/buzz/compare/desktop-v0.5.25...desktop-v0.5.26) + +## v0.5.25 + +### Desktop and shared changes + +- Discover alternate Buzz ACP commands ([#6948](https://github.com/block/buzz/pull/6948)) ([`dd1c2afc2a16238656c5ed19fbfc558605248163`](https://github.com/block/buzz/commit/dd1c2afc2a16238656c5ed19fbfc558605248163)) +- chore(mesh): upgrade MeshLLM to 0.76.2 ([#7559](https://github.com/block/buzz/pull/7559)) ([`4544ba1713d8d7f5959d7d63886ff3927357e1ac`](https://github.com/block/buzz/commit/4544ba1713d8d7f5959d7d63886ff3927357e1ac)) +- feat(agents): humanize uncurated Databricks model ids with a label grammar ([#7844](https://github.com/block/buzz/pull/7844)) ([`d01e5f82058463709a22e93bb4cd795da5f53e10`](https://github.com/block/buzz/commit/d01e5f82058463709a22e93bb4cd795da5f53e10)) +- fix: route databricks claude fqns to anthropic messages ([#7829](https://github.com/block/buzz/pull/7829)) ([`48884848f566d02c42ce07636636c4ad5f164c27`](https://github.com/block/buzz/commit/48884848f566d02c42ce07636636c4ad5f164c27)) +- feat(relay): add opt-in newest-first thread windows ([#7823](https://github.com/block/buzz/pull/7823)) ([`5a349db91c23fa70c8c8aa43a3a5ba0005d8dd41`](https://github.com/block/buzz/commit/5a349db91c23fa70c8c8aa43a3a5ba0005d8dd41)) +- refactor: move agent Git bootstrap into ACP harness ([#7819](https://github.com/block/buzz/pull/7819)) ([`5621006bcf84b82e5da489824a5b4d76568d8602`](https://github.com/block/buzz/commit/5621006bcf84b82e5da489824a5b4d76568d8602)) +- fix(agent): preserve Databricks Opus UC reasoning and tool continuation ([#7840](https://github.com/block/buzz/pull/7840)) ([`0cc63fe3e607cf47ff32bc61e7eaca2f21e6cc23`](https://github.com/block/buzz/commit/0cc63fe3e607cf47ff32bc61e7eaca2f21e6cc23)) +- feat(canvas): add version history with atomic restore ([#6780](https://github.com/block/buzz/pull/6780)) ([`b6a26556ec904cdebe0fbc7e6c25b4ea2cf294d1`](https://github.com/block/buzz/commit/b6a26556ec904cdebe0fbc7e6c25b4ea2cf294d1)) + +### Other repository changes + +- fix(ci): consume the published MinIO image ([#7870](https://github.com/block/buzz/pull/7870)) ([`797012ff01a6d499959b45ed2e56f7927c6a4d6b`](https://github.com/block/buzz/commit/797012ff01a6d499959b45ed2e56f7927c6a4d6b)) +- fix(mobile): converge sidebar managers on relay head with resume re-read ([#7806](https://github.com/block/buzz/pull/7806)) ([`309e34d80f8c1f8524df089674f951f524c50119`](https://github.com/block/buzz/commit/309e34d80f8c1f8524df089674f951f524c50119)) +- fix(ci): bootstrap the reusable MinIO image in GHCR ([#7869](https://github.com/block/buzz/pull/7869)) ([`99c2acf90cfbb1cb2d3a8bd900c0ec1642e20540`](https://github.com/block/buzz/commit/99c2acf90cfbb1cb2d3a8bd900c0ec1642e20540)) +- fix(hooks): surface nextest failures and stale pnpm deps in pre-push ([#7850](https://github.com/block/buzz/pull/7850)) ([`611faf7511c2f7ba564437daea18987db83fd82b`](https://github.com/block/buzz/commit/611faf7511c2f7ba564437daea18987db83fd82b)) +- feat(acp): run one prepared task from a file or stdin ([#7851](https://github.com/block/buzz/pull/7851)) ([`ea1e97e65f816a1f4d92f2da6e3498eb90f5d361`](https://github.com/block/buzz/commit/ea1e97e65f816a1f4d92f2da6e3498eb90f5d361)) +- Fix mobile heart and warning emoji with native font fallback ([#7842](https://github.com/block/buzz/pull/7842)) ([`9462d8884a78147cf277988acb254af81f3df7f9`](https://github.com/block/buzz/commit/9462d8884a78147cf277988acb254af81f3df7f9)) +- Use worker snapshots for relay storage metrics ([#7845](https://github.com/block/buzz/pull/7845)) ([`4142d2b84e1c3230fbe6c4b2d1e994721c409092`](https://github.com/block/buzz/commit/4142d2b84e1c3230fbe6c4b2d1e994721c409092)) +- fix(hooks): strip repo-local git env from pre-push test lanes ([#7841](https://github.com/block/buzz/pull/7841)) ([`3b2e50b15c6afba3ff3b8fbe1bdf0a7a69d29f7b`](https://github.com/block/buzz/commit/3b2e50b15c6afba3ff3b8fbe1bdf0a7a69d29f7b)) +- fix(mobile-infra): render push grant lifetimes as decimal in chart 0.3.2 ([#7820](https://github.com/block/buzz/pull/7820)) ([`0ef7a2222ef4e9b221f310ac60ca6a535d9c840d`](https://github.com/block/buzz/commit/0ef7a2222ef4e9b221f310ac60ca6a535d9c840d)) + +[Compare desktop-v0.5.24...desktop-v0.5.25](https://github.com/block/buzz/compare/desktop-v0.5.24...desktop-v0.5.25) + +## v0.5.24 + +### Desktop and shared changes + +- test(desktop): stabilize unread and audio release smoke fixtures ([#7821](https://github.com/block/buzz/pull/7821)) ([`fe56d311a7156802408afb04023c3f75d4015007`](https://github.com/block/buzz/commit/fe56d311a7156802408afb04023c3f75d4015007)) +- fix(desktop): remember Inbox unread-only choice ([#7672](https://github.com/block/buzz/pull/7672)) ([`312cf674fad5563c24a66ec5350d306d192ed64a`](https://github.com/block/buzz/commit/312cf674fad5563c24a66ec5350d306d192ed64a)) +- fix(desktop): refresh channels after access-revoked closure ([#7784](https://github.com/block/buzz/pull/7784)) ([`a024b83d5448598928d512364fea099ca96b373c`](https://github.com/block/buzz/commit/a024b83d5448598928d512364fea099ca96b373c)) +- fix(desktop): bound startup request bursts and recover quota refusals ([#7790](https://github.com/block/buzz/pull/7790)) ([`c213d90d5c450e2e579505da4a4145f528ecbcf2`](https://github.com/block/buzz/commit/c213d90d5c450e2e579505da4a4145f528ecbcf2)) +- fix(desktop): register macOS badges for new and existing installs ([#7783](https://github.com/block/buzz/pull/7783)) ([`a3117a4762e3349054474e221c2e9cc5fea60dd9`](https://github.com/block/buzz/commit/a3117a4762e3349054474e221c2e9cc5fea60dd9)) +- fix(workflows): make deletion persistent and retryable ([#7735](https://github.com/block/buzz/pull/7735)) ([`5079c770fe30bb3d8204822ce6c2431eacac6d4b`](https://github.com/block/buzz/commit/5079c770fe30bb3d8204822ce6c2431eacac6d4b)) +- fix(relay): exclude ephemeral activity from message quota ([#7736](https://github.com/block/buzz/pull/7736)) ([`5511b56fcf0047f9d0d4887dc75125b6933a6bbd`](https://github.com/block/buzz/commit/5511b56fcf0047f9d0d4887dc75125b6933a6bbd)) +- Replace personal and internal data in desktop test fixtures ([#7748](https://github.com/block/buzz/pull/7748)) ([`f18ea456984a1a94d444615fa3b38ec326a79793`](https://github.com/block/buzz/commit/f18ea456984a1a94d444615fa3b38ec326a79793)) +- fix(desktop): keep managed agent avatars usable across communities ([#7732](https://github.com/block/buzz/pull/7732)) ([`8953cbfff58ed768d996677fed3af0e3bac64a20`](https://github.com/block/buzz/commit/8953cbfff58ed768d996677fed3af0e3bac64a20)) +- Isolate S3 storage metrics from the relay ([#7543](https://github.com/block/buzz/pull/7543)) ([`6b1e45d2f6084a3754a09bb1b800f370ce5399dd`](https://github.com/block/buzz/commit/6b1e45d2f6084a3754a09bb1b800f370ce5399dd)) +- refactor(desktop): share relay request construction ([#7667](https://github.com/block/buzz/pull/7667)) ([`6d1f488d2273dd314184fc2ec805f8982327dc51`](https://github.com/block/buzz/commit/6d1f488d2273dd314184fc2ec805f8982327dc51)) +- Fix desktop onboarding regressions ([#7659](https://github.com/block/buzz/pull/7659)) ([`a9dd4d3bd771b47f0efb4e7f6f7329a5921372b5`](https://github.com/block/buzz/commit/a9dd4d3bd771b47f0efb4e7f6f7329a5921372b5)) +- Refresh desktop onboarding flow ([#7528](https://github.com/block/buzz/pull/7528)) ([`81fba7bda4da0f2c5891eec31852c4f98a6949bf`](https://github.com/block/buzz/commit/81fba7bda4da0f2c5891eec31852c4f98a6949bf)) +- Fix Apple Silicon iOS simulator builds ([#7646](https://github.com/block/buzz/pull/7646)) ([`7c789dee09d198469bded1cb5be902eaf5562ad9`](https://github.com/block/buzz/commit/7c789dee09d198469bded1cb5be902eaf5562ad9)) +- feat(buzz-agent): add opt-in workspace-scoped Databricks reuse ([#7606](https://github.com/block/buzz/pull/7606)) ([`4cd82f513214aad11c2b742ce7cc7c681e8e32a0`](https://github.com/block/buzz/commit/4cd82f513214aad11c2b742ce7cc7c681e8e32a0)) +- fix(acp): improve hints in pi agent setup guide ([#7594](https://github.com/block/buzz/pull/7594)) ([`6c35e82bd50f4ad6587554eeb429e7378d474ba7`](https://github.com/block/buzz/commit/6c35e82bd50f4ad6587554eeb429e7378d474ba7)) +- Configure ACP session scope per agent ([#7578](https://github.com/block/buzz/pull/7578)) ([`78618804ec86a014524ad7d1fb55928e8f5c3edf`](https://github.com/block/buzz/commit/78618804ec86a014524ad7d1fb55928e8f5c3edf)) +- fix(avatars): scale agent squircles from normalized paths ([#7307](https://github.com/block/buzz/pull/7307)) ([`ec11f8e2f30d921a6148d79c688414833af8b1c5`](https://github.com/block/buzz/commit/ec11f8e2f30d921a6148d79c688414833af8b1c5)) +- fix(desktop): isolate quota backoff and reuse channel discovery rosters ([#6998](https://github.com/block/buzz/pull/6998)) ([`f3408fc62045654183c704ceba2076b529a8140c`](https://github.com/block/buzz/commit/f3408fc62045654183c704ceba2076b529a8140c)) +- test(desktop): isolate login-shell probe measurements ([#7570](https://github.com/block/buzz/pull/7570)) ([`9847b0967d72adbd50b4acae31d318575a962c07`](https://github.com/block/buzz/commit/9847b0967d72adbd50b4acae31d318575a962c07)) +- fix(acp): integrate the Buzz Pi adapter fork ([#7552](https://github.com/block/buzz/pull/7552)) ([`813bbd14121edacc6cb4733301a3af12131aa10e`](https://github.com/block/buzz/commit/813bbd14121edacc6cb4733301a3af12131aa10e)) +- fix(markdown): align mention chip wrapping ([#7501](https://github.com/block/buzz/pull/7501)) ([`092c6a7277698bd373ccbc1d008fc1507094ae74`](https://github.com/block/buzz/commit/092c6a7277698bd373ccbc1d008fc1507094ae74)) +- fix(desktop): let inbox title and message author names truncate under narrow panes ([#7550](https://github.com/block/buzz/pull/7550)) ([`cec5c8fd9280d30f56effac701e1e19d5cfe6fea`](https://github.com/block/buzz/commit/cec5c8fd9280d30f56effac701e1e19d5cfe6fea)) +- fix(desktop): require a Codex adapter with Astra support ([#7427](https://github.com/block/buzz/pull/7427)) ([`12023a3cba60e9a6336bf790bf3565b271af929f`](https://github.com/block/buzz/commit/12023a3cba60e9a6336bf790bf3565b271af929f)) +- fix(desktop): order unnamed roster members by full canonical npub ([#7503](https://github.com/block/buzz/pull/7503)) ([`ad9591c43bdb7e221ee93964b09d5dadf820497f`](https://github.com/block/buzz/commit/ad9591c43bdb7e221ee93964b09d5dadf820497f)) +- fix(desktop): npub identity controls across profile, agents, and workflows ([#7489](https://github.com/block/buzz/pull/7489)) ([`2226b6f95b0218d5ba896a8afa6ea217706cc8a3`](https://github.com/block/buzz/commit/2226b6f95b0218d5ba896a8afa6ea217706cc8a3)) +- fix(desktop): npub identity displays for mention, member, and workflow surfaces ([#7495](https://github.com/block/buzz/pull/7495)) ([`ad2a84131ee99d087b8dba95cff0f319785209df`](https://github.com/block/buzz/commit/ad2a84131ee99d087b8dba95cff0f319785209df)) +- fix(desktop): shared npub identity foundation (canonicalNpub, PubKey gate, strict parser) ([#7488](https://github.com/block/buzz/pull/7488)) ([`bfc384855889432df4a333a0edf3080f332ee169`](https://github.com/block/buzz/commit/bfc384855889432df4a333a0edf3080f332ee169)) +- fix(link-preview): keep composer fetches user-paced ([#7211](https://github.com/block/buzz/pull/7211)) ([`218633b8fd6ee41aee8eb18ba9806e8d90694751`](https://github.com/block/buzz/commit/218633b8fd6ee41aee8eb18ba9806e8d90694751)) +- feat(mesh): upgrade to mesh-llm 0.76.0-rc8 and recommend Qwen3.8 27B ([#6189](https://github.com/block/buzz/pull/6189)) ([`44316ff72f5f7de014c66b01cbf534298a70c249`](https://github.com/block/buzz/commit/44316ff72f5f7de014c66b01cbf534298a70c249)) +- fix(agent): route GPT-5+ model-service FQNs to Responses ([#7358](https://github.com/block/buzz/pull/7358)) ([`cd54e26823117259e0bde16bd71a9531e729046b`](https://github.com/block/buzz/commit/cd54e26823117259e0bde16bd71a9531e729046b)) + +### Other repository changes + +- feat(mobile-infra): support development App Attest ([#7744](https://github.com/block/buzz/pull/7744)) ([`7e96f9122961d58159e6c6e6838b2026caaec3cd`](https://github.com/block/buzz/commit/7e96f9122961d58159e6c6e6838b2026caaec3cd)) +- docs(nip-fi): clarify federated identity amendments ([#7803](https://github.com/block/buzz/pull/7803)) ([`26ede6dfa2496993aa62ce5781d2112df4c2d009`](https://github.com/block/buzz/commit/26ede6dfa2496993aa62ce5781d2112df4c2d009)) +- fix(audit): frame hash inputs with TLV ([#7492](https://github.com/block/buzz/pull/7492)) ([`7881447c193edf2ed3a860d959d11dc94f0946fb`](https://github.com/block/buzz/commit/7881447c193edf2ed3a860d959d11dc94f0946fb)) +- fix(admin): allow cold storage worker DB startup ([#7770](https://github.com/block/buzz/pull/7770)) ([`a929532a04cd010705c359ae29c91887c333ee92`](https://github.com/block/buzz/commit/a929532a04cd010705c359ae29c91887c333ee92)) +- feat(relay): add admin HTTP routes for member restriction management ([#7302](https://github.com/block/buzz/pull/7302)) ([`77729abfb692b25a0f4ec4a69add86af2e32c0dd`](https://github.com/block/buzz/commit/77729abfb692b25a0f4ec4a69add86af2e32c0dd)) +- fix(relay): fire kick live side effects at convergence; persist target; fence re-add race with held lock ([#7298](https://github.com/block/buzz/pull/7298)) ([`ce41be9c4b1ca50dea0b04379333eb082826ba0f`](https://github.com/block/buzz/commit/ce41be9c4b1ca50dea0b04379333eb082826ba0f)) +- feat(relay): add atomic complete read-state snapshots ([#7572](https://github.com/block/buzz/pull/7572)) ([`6a86531ac9d27b5123cca14636ced581578975df`](https://github.com/block/buzz/commit/6a86531ac9d27b5123cca14636ced581578975df)) +- fix(mobile): avoid opening empty threads on message tap ([#7756](https://github.com/block/buzz/pull/7756)) ([`a61239f0d8036aff58176f5c0ce7f080c66e21b7`](https://github.com/block/buzz/commit/a61239f0d8036aff58176f5c0ce7f080c66e21b7)) +- fix(mobile): preserve thread replies through refresh failures ([#7757](https://github.com/block/buzz/pull/7757)) ([`ef2aa1ae38fadcc0bc22b8bf6ed96b35933146be`](https://github.com/block/buzz/commit/ef2aa1ae38fadcc0bc22b8bf6ed96b35933146be)) +- fix(mobile): keep iOS message menu actions responsive after rebuilds ([#7758](https://github.com/block/buzz/pull/7758)) ([`4ee9f8b35a612b5c83459af2fcee9f77000a29f6`](https://github.com/block/buzz/commit/4ee9f8b35a612b5c83459af2fcee9f77000a29f6)) +- release: push gateway chart 0.3.1 ([#7749](https://github.com/block/buzz/pull/7749)) ([`4e65148e76bd4f8dff757da4014a37fbc95fcc12`](https://github.com/block/buzz/commit/4e65148e76bd4f8dff757da4014a37fbc95fcc12)) +- fix(push): label plaintext push gateway service as HTTP ([#7717](https://github.com/block/buzz/pull/7717)) ([`fe808eae0e1194be48923567c4e0f179aead5acf`](https://github.com/block/buzz/commit/fe808eae0e1194be48923567c4e0f179aead5acf)) +- Add mobile VISION ([#7710](https://github.com/block/buzz/pull/7710)) ([`4e1770aa3ee7552e2bb50e897e113c22e30488de`](https://github.com/block/buzz/commit/4e1770aa3ee7552e2bb50e897e113c22e30488de)) +- fix(mobile): keep relay sessions stable during push lease updates ([#7745](https://github.com/block/buzz/pull/7745)) ([`4af2324d85e927518c59adc8ad15043233d8cd53`](https://github.com/block/buzz/commit/4af2324d85e927518c59adc8ad15043233d8cd53)) +- fix(mobile): fail open when age checks are unavailable ([#7714](https://github.com/block/buzz/pull/7714)) ([`779af8886caae1317b4de962082429867ab61503`](https://github.com/block/buzz/commit/779af8886caae1317b4de962082429867ab61503)) +- fix(ci): don't run desktop tests for purely mobile client changes ([#7709](https://github.com/block/buzz/pull/7709)) ([`01b6174a1cbad249e93f31df97d4b2ed1d0e8638`](https://github.com/block/buzz/commit/01b6174a1cbad249e93f31df97d4b2ed1d0e8638)) +- fix(mobile): temporarily disable age gating ([#7708](https://github.com/block/buzz/pull/7708)) ([`d1cae93c1a584d14abc1563132892f9f953e8c1c`](https://github.com/block/buzz/commit/d1cae93c1a584d14abc1563132892f9f953e8c1c)) +- feat(db): expose connection setup metrics ([#7286](https://github.com/block/buzz/pull/7286)) ([`4c2086c0844c30a0956aa1e3b1c2901f0357fb56`](https://github.com/block/buzz/commit/4c2086c0844c30a0956aa1e3b1c2901f0357fb56)) +- fix(web): route mobile invite downloads to app stores ([#7702](https://github.com/block/buzz/pull/7702)) ([`4ab4f786085a23fe6126529861840eff6048ceee`](https://github.com/block/buzz/commit/4ab4f786085a23fe6126529861840eff6048ceee)) +- feat(mobile): show build number with version in settings ([#7697](https://github.com/block/buzz/pull/7697)) ([`b36600fc440615e2565f94bffc800e0495180f6b`](https://github.com/block/buzz/commit/b36600fc440615e2565f94bffc800e0495180f6b)) +- release(mobile-infra): buzz-push-gateway 0.3.0 ([#7685](https://github.com/block/buzz/pull/7685)) ([`6dfd145cde4bf0d45091de1cc5e6c7e3462d5703`](https://github.com/block/buzz/commit/6dfd145cde4bf0d45091de1cc5e6c7e3462d5703)) +- Add authenticated WebSocket recovery telemetry ([#7546](https://github.com/block/buzz/pull/7546)) ([`891208914ed51c55b11ef6102f10ed08b5d9bb30`](https://github.com/block/buzz/commit/891208914ed51c55b11ef6102f10ed08b5d9bb30)) +- Instrument database pool roles ([#7356](https://github.com/block/buzz/pull/7356)) ([`213092074c269bee90c87163672f9c2b8d714cfe`](https://github.com/block/buzz/commit/213092074c269bee90c87163672f9c2b8d714cfe)) +- fix(db): allow naturally expired push lease replacement ([#7653](https://github.com/block/buzz/pull/7653)) ([`c507a4d488ca27796e78d876b9c24ee38442cc1b`](https://github.com/block/buzz/commit/c507a4d488ca27796e78d876b9c24ee38442cc1b)) +- perf(mobile): verify notification cache events in background ([#7650](https://github.com/block/buzz/pull/7650)) ([`b8aa0233f9e36afa1ea83b02ecc5b1ebd20cbee4`](https://github.com/block/buzz/commit/b8aa0233f9e36afa1ea83b02ecc5b1ebd20cbee4)) +- feat(push): make gateway origin configurable ([#7261](https://github.com/block/buzz/pull/7261)) ([`76f7e5ef0cc4a7d71d9562ecfb3e4a6887a51461`](https://github.com/block/buzz/commit/76f7e5ef0cc4a7d71d9562ecfb3e4a6887a51461)) +- perf(mobile): move profile sig checks off main thread ([#7648](https://github.com/block/buzz/pull/7648)) ([`41c5ace93740261ee5a5d962c2a17e8d846c2c1b`](https://github.com/block/buzz/commit/41c5ace93740261ee5a5d962c2a17e8d846c2c1b)) +- perf(mobile): avoid redundant message list sorting ([#7647](https://github.com/block/buzz/pull/7647)) ([`5b9dbcb4c26f9ae507e99e1957a8c6201a5242c9`](https://github.com/block/buzz/commit/5b9dbcb4c26f9ae507e99e1957a8c6201a5242c9)) +- perf(mobile): avoid reparsing unchanged Markdown ([#7649](https://github.com/block/buzz/pull/7649)) ([`98a6db5d67cb4797f5f878bc09674d4f69611cf5`](https://github.com/block/buzz/commit/98a6db5d67cb4797f5f878bc09674d4f69611cf5)) +- Deduplicate thread context by ACP session delivery ([#7620](https://github.com/block/buzz/pull/7620)) ([`4d08194ea96e6942cbaad03f8a0abd347dff79c1`](https://github.com/block/buzz/commit/4d08194ea96e6942cbaad03f8a0abd347dff79c1)) +- feat(mobile): hard-block under-18 users on the store age signal ([#4665](https://github.com/block/buzz/pull/4665)) ([`f78a32cf03aa90b0da36b44d075daecd8f85d7d8`](https://github.com/block/buzz/commit/f78a32cf03aa90b0da36b44d075daecd8f85d7d8)) +- Document incoming Buzz turn structure ([#7624](https://github.com/block/buzz/pull/7624)) ([`deda09c18c78d48847b032557c331f28faf64ee8`](https://github.com/block/buzz/commit/deda09c18c78d48847b032557c331f28faf64ee8)) +- fix(ci): pull pinned MinIO images from Quay ([#7599](https://github.com/block/buzz/pull/7599)) ([`f3940ff21e8b6050ff617c645578aefa45db7e9f`](https://github.com/block/buzz/commit/f3940ff21e8b6050ff617c645578aefa45db7e9f)) +- refactor(buzz-acp): point agents at buzz --help instead of a command table ([#7586](https://github.com/block/buzz/pull/7586)) ([`e17cdd9d5c7e2b836b4670ae88bb87a79f94337a`](https://github.com/block/buzz/commit/e17cdd9d5c7e2b836b4670ae88bb87a79f94337a)) +- feat(buzz-cli): render an agent-friendly command tree in --help ([#7584](https://github.com/block/buzz/pull/7584)) ([`44c1cc7df8e0067c9d578a93ad8e4393304422b3`](https://github.com/block/buzz/commit/44c1cc7df8e0067c9d578a93ad8e4393304422b3)) +- fix(mobile): bind same-name mentions to exact selected identities ([#7385](https://github.com/block/buzz/pull/7385)) ([`d074576871a66c72e4a9eb5ad59ec0b22a7f0081`](https://github.com/block/buzz/commit/d074576871a66c72e4a9eb5ad59ec0b22a7f0081)) +- feat(git): add default-branch management to relay and CLI ([#7562](https://github.com/block/buzz/pull/7562)) ([`6146c4fd16f734b525f9ac31e1a3433ccc1ec96f`](https://github.com/block/buzz/commit/6146c4fd16f734b525f9ac31e1a3433ccc1ec96f)) +- fix(relay): reject presence updates when Redis storage fails ([#7532](https://github.com/block/buzz/pull/7532)) ([`00209076c7a10d9e4a475466c313e8ebecf041f5`](https://github.com/block/buzz/commit/00209076c7a10d9e4a475466c313e8ebecf041f5)) +- fix(buzz-acp): report missing models without retrying ([#7538](https://github.com/block/buzz/pull/7538)) ([`051c3a270be9c73da9ab06700bcab7d5552fceaa`](https://github.com/block/buzz/commit/051c3a270be9c73da9ab06700bcab7d5552fceaa)) +- fix(mobile): standardize public-key identity display on npub ([#7493](https://github.com/block/buzz/pull/7493)) ([`82656ffea080cc28cec9163ebbf7d1c6be327e43`](https://github.com/block/buzz/commit/82656ffea080cc28cec9163ebbf7d1c6be327e43)) +- fix(mobile): render push notification sender identity as npub ([#7494](https://github.com/block/buzz/pull/7494)) ([`93761e411ced557d859c00df1933ab053d8d854b`](https://github.com/block/buzz/commit/93761e411ced557d859c00df1933ab053d8d854b)) +- fix(acp): pace targeted overflow recovery on consumer capacity ([#7325](https://github.com/block/buzz/pull/7325)) ([`c045321a7fb3ca8939f28519ce7a555a6f597728`](https://github.com/block/buzz/commit/c045321a7fb3ca8939f28519ce7a555a6f597728)) +- fix(buzz-acp): wake held ACP threads and fence forked sessions ([#7340](https://github.com/block/buzz/pull/7340)) ([`86c189e8571d4254726f4d0519a500df9b9d947e`](https://github.com/block/buzz/commit/86c189e8571d4254726f4d0519a500df9b9d947e)) +- fix(mobile): style inline code with the app mono face ([#6631](https://github.com/block/buzz/pull/6631)) ([`fa1b27bcc8e0f076076b766273b305407b593f60`](https://github.com/block/buzz/commit/fa1b27bcc8e0f076076b766273b305407b593f60)) + +[Compare desktop-v0.5.23...desktop-v0.5.24](https://github.com/block/buzz/compare/desktop-v0.5.23...desktop-v0.5.24) + +## v0.5.23 + +### Desktop and shared changes + +- fix(desktop): keep packaged frontendDist relative so Windows embeds assets ([#7177](https://github.com/block/buzz/pull/7177)) ([`dad5a33865fc81a2e55b3b60746632f615ec1e3a`](https://github.com/block/buzz/commit/dad5a33865fc81a2e55b3b60746632f615ec1e3a)) +- fix(sidebar): simplify unread indicators and emphasize priority activity ([#7134](https://github.com/block/buzz/pull/7134)) ([`f038cbbb0d4092a72ffd93f17916f84d2b39bb43`](https://github.com/block/buzz/commit/f038cbbb0d4092a72ffd93f17916f84d2b39bb43)) +- feat(buzz-acp): update base prompt; add buzz context and skills to Pi agents ([#7335](https://github.com/block/buzz/pull/7335)) ([`4beffef6979347f7ebdc760705865bdd04d23508`](https://github.com/block/buzz/commit/4beffef6979347f7ebdc760705865bdd04d23508)) +- fix(desktop): restore mention chip identity icons ([#7338](https://github.com/block/buzz/pull/7338)) ([`4afef8649ab11d60b423893e9e4f8cd36868d35a`](https://github.com/block/buzz/commit/4afef8649ab11d60b423893e9e4f8cd36868d35a)) +- Persist video playback speed preference ([#7336](https://github.com/block/buzz/pull/7336)) ([`5d107836c6bd6a57e2da28560ec0acc0d016b8d9`](https://github.com/block/buzz/commit/5d107836c6bd6a57e2da28560ec0acc0d016b8d9)) +- feat(desktop): invite owned agents from standalone forums ([#7125](https://github.com/block/buzz/pull/7125)) ([`e7e29937a145aca7a3c7f5436b07e32c6c20087f`](https://github.com/block/buzz/commit/e7e29937a145aca7a3c7f5436b07e32c6c20087f)) +- fix(desktop): authorize remote mentions at publication ([#7124](https://github.com/block/buzz/pull/7124)) ([`d595806fc3b9c9758992e39b9b51cbb5f55791b0`](https://github.com/block/buzz/commit/d595806fc3b9c9758992e39b9b51cbb5f55791b0)) +- fix(acp): rename system tag to agent-instructions ([#7332](https://github.com/block/buzz/pull/7332)) ([`ce9decb235f628c484631ac923db96466460fc3f`](https://github.com/block/buzz/commit/ce9decb235f628c484631ac923db96466460fc3f)) +- fix(desktop): bind duplicate mention selections to exact recipients ([#7133](https://github.com/block/buzz/pull/7133)) ([`ee883d73fb84752d26f52c6606ad3cadc9f12cc7`](https://github.com/block/buzz/commit/ee883d73fb84752d26f52c6606ad3cadc9f12cc7)) +- feat(desktop): preserve mentions across copy and paste ([#7228](https://github.com/block/buzz/pull/7228)) ([`b1f6b7ef770dddbb7f33c9f5861c379a47bca1d6`](https://github.com/block/buzz/commit/b1f6b7ef770dddbb7f33c9f5861c379a47bca1d6)) +- test(desktop): await Bestie drag and profile hover endpoints ([#7294](https://github.com/block/buzz/pull/7294)) ([`4b0744d7f3161d9f045dd67a73e014e4440c2b47`](https://github.com/block/buzz/commit/4b0744d7f3161d9f045dd67a73e014e4440c2b47)) +- Collapse contiguous join messages ([#7262](https://github.com/block/buzz/pull/7262)) ([`2ac0aa1dd18c0b9d4fa722658c4692b0c79a496f`](https://github.com/block/buzz/commit/2ac0aa1dd18c0b9d4fa722658c4692b0c79a496f)) + +### Other repository changes + +- Add generic information-flow control core ([#7293](https://github.com/block/buzz/pull/7293)) ([`4d447b9c20a23fb33c94778e6cf309424abea6c8`](https://github.com/block/buzz/commit/4d447b9c20a23fb33c94778e6cf309424abea6c8)) +- Verify ACP relay events before prompt routing ([#7010](https://github.com/block/buzz/pull/7010)) ([`e09f715c9d0ee2cb7bf8a39061e601f3a502f588`](https://github.com/block/buzz/commit/e09f715c9d0ee2cb7bf8a39061e601f3a502f588)) +- fix(buzz-acp): bound busy-owner hold to prevent cross-channel starvation ([#7337](https://github.com/block/buzz/pull/7337)) ([`b17c0776b7438d59904e8c38926148bf692fa5f5`](https://github.com/block/buzz/commit/b17c0776b7438d59904e8c38926148bf692fa5f5)) +- refactor(relay): extract NIP-29 membership authorization ([#7285](https://github.com/block/buzz/pull/7285)) ([`cd02b693aae86444b0b5636474a3d202c6fc8f26`](https://github.com/block/buzz/commit/cd02b693aae86444b0b5636474a3d202c6fc8f26)) + +[Compare desktop-v0.5.22...desktop-v0.5.23](https://github.com/block/buzz/compare/desktop-v0.5.22...desktop-v0.5.23) + +## v0.5.22 + +### Desktop and shared changes + +- chore(release): release Buzz Desktop version 0.5.21 ([#7301](https://github.com/block/buzz/pull/7301)) ([`75f101d8b4f5b4b26f9891b73b87c67fedac25a0`](https://github.com/block/buzz/commit/75f101d8b4f5b4b26f9891b73b87c67fedac25a0)) +- fix(desktop): wrap message tables within the available pane ([#7279](https://github.com/block/buzz/pull/7279)) ([`6cf514ed90981d1db4acdb97a272543ecca83993`](https://github.com/block/buzz/commit/6cf514ed90981d1db4acdb97a272543ecca83993)) +- 🤖 fix(desktop): harden smoke E2E tests against Bestie overlay and toast timing ([#7270](https://github.com/block/buzz/pull/7270)) ([`7a9a5233d9d755e715be0c585cf7850e935d28cf`](https://github.com/block/buzz/commit/7a9a5233d9d755e715be0c585cf7850e935d28cf)) +- Show status and huddle indicators beside names ([#7112](https://github.com/block/buzz/pull/7112)) ([`c6ca9d94d94230a315257a87beb8dc116fec56cc`](https://github.com/block/buzz/commit/c6ca9d94d94230a315257a87beb8dc116fec56cc)) +- perf(desktop): publish mention sends before waking agents ([#7154](https://github.com/block/buzz/pull/7154)) ([`40220d5618fc7dbe06421f358053ca77ed0f67d7`](https://github.com/block/buzz/commit/40220d5618fc7dbe06421f358053ca77ed0f67d7)) +- fix(desktop): unify owned-agent cloud provenance markers ([#7129](https://github.com/block/buzz/pull/7129)) ([`5073e075d7e7d95558c57f24d86d5db6196491c4`](https://github.com/block/buzz/commit/5073e075d7e7d95558c57f24d86d5db6196491c4)) +- fix(desktop): derive agent availability from relay presence ([#7127](https://github.com/block/buzz/pull/7127)) ([`d5a73b9f35feaa81ef9afb13d1ec8943e8ec6ca9`](https://github.com/block/buzz/commit/d5a73b9f35feaa81ef9afb13d1ec8943e8ec6ca9)) +- fix(desktop): preserve spacing after multi-word mentions ([#7128](https://github.com/block/buzz/pull/7128)) ([`44d19f59a593dfb541bf40dcadbed313ca4a8f97`](https://github.com/block/buzz/commit/44d19f59a593dfb541bf40dcadbed313ca4a8f97)) +- feat(cli): add buzz gifs command group and NIP-30 emoji tags on messages ([#7259](https://github.com/block/buzz/pull/7259)) ([`47d068e2109d077414cbf2f4f1c927f6d051037a`](https://github.com/block/buzz/commit/47d068e2109d077414cbf2f4f1c927f6d051037a)) +- feat(desktop): add persistent Bestie experience ([#7223](https://github.com/block/buzz/pull/7223)) ([`ac5a18697c8294e9237f505a2e01ec6fc374849a`](https://github.com/block/buzz/commit/ac5a18697c8294e9237f505a2e01ec6fc374849a)) +- fix(desktop): harden profile batch and thread-reply fetches against relay slowness ([#7188](https://github.com/block/buzz/pull/7188)) ([`6f6093243eaea5160db79b7e054f06dfffd207aa`](https://github.com/block/buzz/commit/6f6093243eaea5160db79b7e054f06dfffd207aa)) +- fix(composer): align wrapped inline chip fragments ([#7242](https://github.com/block/buzz/pull/7242)) ([`b6dc533b7c2aadb70a8f011a88a5bd2f06d800f2`](https://github.com/block/buzz/commit/b6dc533b7c2aadb70a8f011a88a5bd2f06d800f2)) +- fix(desktop): keep explicit agent profiles bound to their exact key ([#7131](https://github.com/block/buzz/pull/7131)) ([`83e596298449ab1cb57481221d0e41ce69e52814`](https://github.com/block/buzz/commit/83e596298449ab1cb57481221d0e41ce69e52814)) +- fix(desktop): discover authenticated owned relay agents ([#7122](https://github.com/block/buzz/pull/7122)) ([`434dafe958d82ca07d2b42b0f7d023ab923c2ff9`](https://github.com/block/buzz/commit/434dafe958d82ca07d2b42b0f7d023ab923c2ff9)) +- feat(agents): harness-agnostic effort write path and spawn bridge ([#4625](https://github.com/block/buzz/pull/4625)) ([`0dbd036f5bff33e7ade75e7639f3218d424a6e73`](https://github.com/block/buzz/commit/0dbd036f5bff33e7ade75e7639f3218d424a6e73)) +- fix(desktop): retain automatic mentions only in threads ([#7144](https://github.com/block/buzz/pull/7144)) ([`1c8321cd08feb597f8bcff5195c21148fb3e98ed`](https://github.com/block/buzz/commit/1c8321cd08feb597f8bcff5195c21148fb3e98ed)) +- feat: add databricks fable 5.1 model capabilities ([#7213](https://github.com/block/buzz/pull/7213)) ([`560fea7b4fc5e96a4de45d988e039ffb3fd66662`](https://github.com/block/buzz/commit/560fea7b4fc5e96a4de45d988e039ffb3fd66662)) +- feat(desktop): add Pi agent preset ([#7208](https://github.com/block/buzz/pull/7208)) ([`42aeb1571cc1f1ed4d73f05b420474be970021ab`](https://github.com/block/buzz/commit/42aeb1571cc1f1ed4d73f05b420474be970021ab)) +- feat(buzz-agent): add DatabricksAuthCoordinator single-flight OAuth ([#5545](https://github.com/block/buzz/pull/5545)) ([`5aed49b505a7e27f3b0e34dafa53d6c4e8cdcd64`](https://github.com/block/buzz/commit/5aed49b505a7e27f3b0e34dafa53d6c4e8cdcd64)) +- fix(desktop): preserve keyring identity during recovery ([#7203](https://github.com/block/buzz/pull/7203)) ([`e5a7e26a1008227ff6a0b9430a6df2470475bec1`](https://github.com/block/buzz/commit/e5a7e26a1008227ff6a0b9430a6df2470475bec1)) +- ci: relax file-size ceilings by surface ([#6485](https://github.com/block/buzz/pull/6485)) ([`4794a5cecf058ebbe2b367f40b1ce6ff80791e91`](https://github.com/block/buzz/commit/4794a5cecf058ebbe2b367f40b1ce6ff80791e91)) +- fix(dev-mcp): extend shell timeout cap to 20 minutes and align outer budgets ([#7185](https://github.com/block/buzz/pull/7185)) ([`cae158ce7fd72dee1f34d264f6790711d82d46bf`](https://github.com/block/buzz/commit/cae158ce7fd72dee1f34d264f6790711d82d46bf)) +- feat(buzz-auth): add production NIP-FI federated assertion runtime ([#7109](https://github.com/block/buzz/pull/7109)) ([`70895b355fcea9f99894b426c020052b715bd368`](https://github.com/block/buzz/commit/70895b355fcea9f99894b426c020052b715bd368)) +- Hide download action on voice notes ([#7182](https://github.com/block/buzz/pull/7182)) ([`ac4aa94b05417c2830e5489ddda0c87f6a9d1dbf`](https://github.com/block/buzz/commit/ac4aa94b05417c2830e5489ddda0c87f6a9d1dbf)) +- Add voice notes to desktop messages ([#6978](https://github.com/block/buzz/pull/6978)) ([`114dbf745f1fe0bdbecb70e07a07f03c23687bdc`](https://github.com/block/buzz/commit/114dbf745f1fe0bdbecb70e07a07f03c23687bdc)) +- feat(desktop): add thread-scoped ACP session experiment ([#6909](https://github.com/block/buzz/pull/6909)) ([`59328d5ae38a51a618dd2fddd7faf1343d42096f`](https://github.com/block/buzz/commit/59328d5ae38a51a618dd2fddd7faf1343d42096f)) +- fix(desktop): scope composer autocomplete to focus ([#6860](https://github.com/block/buzz/pull/6860)) ([`571c1902d0ca55cfd4ccf6b91eeb731909cc10be`](https://github.com/block/buzz/commit/571c1902d0ca55cfd4ccf6b91eeb731909cc10be)) +- feat(desktop): add isolated named demo builds ([#6407](https://github.com/block/buzz/pull/6407)) ([`4a9de1a3a121285ef475d630b2b5764044c02cde`](https://github.com/block/buzz/commit/4a9de1a3a121285ef475d630b2b5764044c02cde)) +- fix(model-capabilities): humanize databricks goose model names ([#7135](https://github.com/block/buzz/pull/7135)) ([`0affe527e880ddd300ae7d4dac3f0600c79b4f5e`](https://github.com/block/buzz/commit/0affe527e880ddd300ae7d4dac3f0600c79b4f5e)) +- fix(desktop): back split thread headers ([#7137](https://github.com/block/buzz/pull/7137)) ([`b47b5a50127c080a74ed4de19a43534cd9a7b563`](https://github.com/block/buzz/commit/b47b5a50127c080a74ed4de19a43534cd9a7b563)) +- add public descriptions to agent personas ([#7126](https://github.com/block/buzz/pull/7126)) ([`cb3144999bebc4939cb15b2200b373281d493b52`](https://github.com/block/buzz/commit/cb3144999bebc4939cb15b2200b373281d493b52)) +- feat(desktop): add protected-build Bestie experiment ([#6902](https://github.com/block/buzz/pull/6902)) ([`5673c3307e248530beeea060da437350d3939a4b`](https://github.com/block/buzz/commit/5673c3307e248530beeea060da437350d3939a4b)) +- fix(relay): reject a frame on its own acknowledgement channel ([#6961](https://github.com/block/buzz/pull/6961)) ([`2f3dd850db3afe27e56f18cbcd3548eabdd9b9c2`](https://github.com/block/buzz/commit/2f3dd850db3afe27e56f18cbcd3548eabdd9b9c2)) +- feat: render agent avatars as squircles ([#7106](https://github.com/block/buzz/pull/7106)) ([`bc006f67087b049e2f9c4d8a2f26faceff628225`](https://github.com/block/buzz/commit/bc006f67087b049e2f9c4d8a2f26faceff628225)) +- Enforce NIP-OA authorization time bounds ([#7004](https://github.com/block/buzz/pull/7004)) ([`e47690c21b519128b40c917456b3e3f33f018fe4`](https://github.com/block/buzz/commit/e47690c21b519128b40c917456b3e3f33f018fe4)) +- feat(desktop): use segmented controls for channel creation ([#6845](https://github.com/block/buzz/pull/6845)) ([`c3132c3ee982d194cd0198ad07b57ec8bd726e4e`](https://github.com/block/buzz/commit/c3132c3ee982d194cd0198ad07b57ec8bd726e4e)) +- feat(buzz-agent): surface stop reason and silent-turn WARN in telemetry ([#7038](https://github.com/block/buzz/pull/7038)) ([`eed74bde2f4797714335ac10c56c0b0244c1def4`](https://github.com/block/buzz/commit/eed74bde2f4797714335ac10c56c0b0244c1def4)) +- fix(desktop): surface channel history load failures ([#7013](https://github.com/block/buzz/pull/7013)) ([`00e61eafa917d296104006576b7a2ddbfd58bb5a`](https://github.com/block/buzz/commit/00e61eafa917d296104006576b7a2ddbfd58bb5a)) +- fix(composer): polish automatic mentions ([#6956](https://github.com/block/buzz/pull/6956)) ([`8dbc65d9e2c80d9d8516e17b751c46e0568100e6`](https://github.com/block/buzz/commit/8dbc65d9e2c80d9d8516e17b751c46e0568100e6)) +- fix(desktop): resolve bundled sidecar on cheap path and bound login-shell spawns ([#6904](https://github.com/block/buzz/pull/6904)) ([`2c99ee7af5a20d239e95ec5368407887449795c9`](https://github.com/block/buzz/commit/2c99ee7af5a20d239e95ec5368407887449795c9)) +- refactor(db): extract domain stores from database runtime ([#6987](https://github.com/block/buzz/pull/6987)) ([`a3730784fc851bb1125b40cca9b0a30788a293c1`](https://github.com/block/buzz/commit/a3730784fc851bb1125b40cca9b0a30788a293c1)) +- feat(desktop): add team sharing to community catalog ([#3995](https://github.com/block/buzz/pull/3995)) ([`2f66ee24a0bf5efa958378069a6b155e99a1d068`](https://github.com/block/buzz/commit/2f66ee24a0bf5efa958378069a6b155e99a1d068)) +- fix(desktop): complete project empty and context states ([#6980](https://github.com/block/buzz/pull/6980)) ([`a89f5df4c52c3aa5875d9fccb0eaf2222aee4084`](https://github.com/block/buzz/commit/a89f5df4c52c3aa5875d9fccb0eaf2222aee4084)) +- fix(desktop): resolve exact typed mentions on space ([#6862](https://github.com/block/buzz/pull/6862)) ([`b49675894b39f87215e4dfc8c1ad4a3c28c6097e`](https://github.com/block/buzz/commit/b49675894b39f87215e4dfc8c1ad4a3c28c6097e)) +- perf(desktop): restore project context during startup ([#6939](https://github.com/block/buzz/pull/6939)) ([`973386351646d01efca2735ad4921c0d219cff85`](https://github.com/block/buzz/commit/973386351646d01efca2735ad4921c0d219cff85)) +- fix(desktop): lift right auxiliary pane above shared header backdrop ([#6966](https://github.com/block/buzz/pull/6966)) ([`350caf1de3136f6ec473a69d394544e99dfd4d85`](https://github.com/block/buzz/commit/350caf1de3136f6ec473a69d394544e99dfd4d85)) +- feat(desktop): implement 30178 team catalog backend ([#5112](https://github.com/block/buzz/pull/5112)) ([`a7c7414a7fadfe1585b8a90af0f29d6593bb6126`](https://github.com/block/buzz/commit/a7c7414a7fadfe1585b8a90af0f29d6593bb6126)) +- feat(model-capabilities): humanize Databricks UC model families ([#6955](https://github.com/block/buzz/pull/6955)) ([`ae0ecd9a676c692876116fee7265cba5f18cbd90`](https://github.com/block/buzz/commit/ae0ecd9a676c692876116fee7265cba5f18cbd90)) +- feat(agent): discover Databricks Unity Catalog models ([#6918](https://github.com/block/buzz/pull/6918)) ([`be8d7756d5f17285f1e8a4b77d67f7d7cfb6f9e7`](https://github.com/block/buzz/commit/be8d7756d5f17285f1e8a4b77d67f7d7cfb6f9e7)) +- preserve channel description paragraph breaks ([#6946](https://github.com/block/buzz/pull/6946)) ([`69096c9a8db726eebd83422cdc5e6c72ed9d4f90`](https://github.com/block/buzz/commit/69096c9a8db726eebd83422cdc5e6c72ed9d4f90)) +- fix(projects): allow owners to delete agent projects ([#6533](https://github.com/block/buzz/pull/6533)) ([`9176e34405ae59fdefc50dc585454b7e9cb3833a`](https://github.com/block/buzz/commit/9176e34405ae59fdefc50dc585454b7e9cb3833a)) +- Fade expanded video controls on hover ([#6926](https://github.com/block/buzz/pull/6926)) ([`27c1a7c91b658535c8a655dbe8f2421af9099b80`](https://github.com/block/buzz/commit/27c1a7c91b658535c8a655dbe8f2421af9099b80)) +- fix(client): resurface hidden DMs from live activity ([#6885](https://github.com/block/buzz/pull/6885)) ([`4d77175c78f4df48e13398b25b271e3ac1b31dd3`](https://github.com/block/buzz/commit/4d77175c78f4df48e13398b25b271e3ac1b31dd3)) +- fix(desktop): keep the draft space when typing right after a mention pick ([#6875](https://github.com/block/buzz/pull/6875)) ([`c856be0fb954c9e5267d622841098c24e3381e8f`](https://github.com/block/buzz/commit/c856be0fb954c9e5267d622841098c24e3381e8f)) +- broker: define the agent-to-broker action contract ([#6742](https://github.com/block/buzz/pull/6742)) ([`b622003f74aa5bf9b659786452813299a25e4897`](https://github.com/block/buzz/commit/b622003f74aa5bf9b659786452813299a25e4897)) +- fix(desktop): keep project sheets independent from threads ([#6901](https://github.com/block/buzz/pull/6901)) ([`cada3028ceda7ebdae61329f15b5364ca0d23dd4`](https://github.com/block/buzz/commit/cada3028ceda7ebdae61329f15b5364ca0d23dd4)) +- fix(desktop): accent-colored mention badges that count thread mentions ([#6900](https://github.com/block/buzz/pull/6900)) ([`ceb8ba605f43728bdab64aa461211baeeb54364a`](https://github.com/block/buzz/commit/ceb8ba605f43728bdab64aa461211baeeb54364a)) +- fix(desktop): show edited head content in thread panel ([#6887](https://github.com/block/buzz/pull/6887)) ([`eb8e97cfe74afbe560d92f3a8f470967a992767f`](https://github.com/block/buzz/commit/eb8e97cfe74afbe560d92f3a8f470967a992767f)) +- fix(desktop-tooltip): increase surface contrast ([#6897](https://github.com/block/buzz/pull/6897)) ([`03bfc837cbe463de9ef59a86742825a4863fb603`](https://github.com/block/buzz/commit/03bfc837cbe463de9ef59a86742825a4863fb603)) +- Apply access policy when reusing channel agents ([#6838](https://github.com/block/buzz/pull/6838)) ([`01c87a350b0fda89c8d333a5dd6c0e9d89d0c03f`](https://github.com/block/buzz/commit/01c87a350b0fda89c8d333a5dd6c0e9d89d0c03f)) +- feat(sidebar): prioritize unread DMs in overflow navigation ([#6842](https://github.com/block/buzz/pull/6842)) ([`4f554b6385065b698db819498a6f359b17a45459`](https://github.com/block/buzz/commit/4f554b6385065b698db819498a6f359b17a45459)) +- feat(projects): add agent and CLI project-home support ([#6590](https://github.com/block/buzz/pull/6590)) ([`de188ebf06f701ca0f47c51f859da21e19a35f04`](https://github.com/block/buzz/commit/de188ebf06f701ca0f47c51f859da21e19a35f04)) +- feat(desktop): restore message quick reactions ([#6892](https://github.com/block/buzz/pull/6892)) ([`22cdda441d19da1b15dd7db4d932d2f067cd87b3`](https://github.com/block/buzz/commit/22cdda441d19da1b15dd7db4d932d2f067cd87b3)) +- Use paired tags for standing & per-turn context ([#6701](https://github.com/block/buzz/pull/6701)) ([`f177f4909d55ad48a36e86a682cd5be4f006f0fe`](https://github.com/block/buzz/commit/f177f4909d55ad48a36e86a682cd5be4f006f0fe)) +- fix(cli): preserve signatures in event reads ([#6884](https://github.com/block/buzz/pull/6884)) ([`583af02299e20cbd8603044c7844bc128e4e06cd`](https://github.com/block/buzz/commit/583af02299e20cbd8603044c7844bc128e4e06cd)) +- fix(desktop): stop pulsing addressed agents on send ([#6873](https://github.com/block/buzz/pull/6873)) ([`db514b153a8cb17631d6e80b91c95fdc45deb147`](https://github.com/block/buzz/commit/db514b153a8cb17631d6e80b91c95fdc45deb147)) +- fix(desktop): prioritize sidebar channel status ([#6861](https://github.com/block/buzz/pull/6861)) ([`4f529a45f219f55bc6038f304cd69e3f51ec0533`](https://github.com/block/buzz/commit/4f529a45f219f55bc6038f304cd69e3f51ec0533)) +- feat(desktop): hyperlink selected composer text on link paste ([#6684](https://github.com/block/buzz/pull/6684)) ([`e8172b5baccd0f4a711f5e19a3bc4313708f1c78`](https://github.com/block/buzz/commit/e8172b5baccd0f4a711f5e19a3bc4313708f1c78)) + +### Other repository changes + +- fix(scripts): copy global-agent-config.json in buzz-adopt-prod-agents ([#7303](https://github.com/block/buzz/pull/7303)) ([`8e7b275cb07fc1abea55b34e8db90136d039bd08`](https://github.com/block/buzz/commit/8e7b275cb07fc1abea55b34e8db90136d039bd08)) +- feat(relay): add early startup lifecycle logs ([#7258](https://github.com/block/buzz/pull/7258)) ([`88687876f7808a2fd742b7eb2e4b9f87d999ad8d`](https://github.com/block/buzz/commit/88687876f7808a2fd742b7eb2e4b9f87d999ad8d)) +- docs(nip-fi): add Blossom kind-24242 media possession-proof exception ([#7278](https://github.com/block/buzz/pull/7278)) ([`752cbfc0375efc8bac3d5cc2a5716250bc0be234`](https://github.com/block/buzz/commit/752cbfc0375efc8bac3d5cc2a5716250bc0be234)) +- Add mobile voice notes ([#7121](https://github.com/block/buzz/pull/7121)) ([`6f5ec4a731901bf3ff2a370c7ccbfbc3fba93368`](https://github.com/block/buzz/commit/6f5ec4a731901bf3ff2a370c7ccbfbc3fba93368)) +- docs(nip-fi): document Git smart-HTTP credential exemption ([#7268](https://github.com/block/buzz/pull/7268)) ([`c328202cb08cac5b8c1610d2d373e69889772b4e`](https://github.com/block/buzz/commit/c328202cb08cac5b8c1610d2d373e69889772b4e)) +- docs(nip-fi): adopt deny-until-TTL and extend enforcement to HTTP ingress ([#7254](https://github.com/block/buzz/pull/7254)) ([`187df22252fa24cce2f3295fb9df9f4dc211b30a`](https://github.com/block/buzz/commit/187df22252fa24cce2f3295fb9df9f4dc211b30a)) +- Add operation-aware database pool acquisition metrics ([#7195](https://github.com/block/buzz/pull/7195)) ([`91ab9d31b8f7249ff1db141ae9d8bb3f2a20bcdd`](https://github.com/block/buzz/commit/91ab9d31b8f7249ff1db141ae9d8bb3f2a20bcdd)) +- chore(db): drop Phase-A NIP-FI relay-side authority ledger ([#7221](https://github.com/block/buzz/pull/7221)) ([`04babf02655440b4dfd37f2e2df605ead0a030d8`](https://github.com/block/buzz/commit/04babf02655440b4dfd37f2e2df605ead0a030d8)) +- fix(acp): replace real user name in base prompt mention example ([#7250](https://github.com/block/buzz/pull/7250)) ([`2af9773d6271ce62cbe5dfbd28fbe5dd79372465`](https://github.com/block/buzz/commit/2af9773d6271ce62cbe5dfbd28fbe5dd79372465)) +- ci: split CI into reusable workflows ([#7168](https://github.com/block/buzz/pull/7168)) ([`0e878664b08cdf7fb2d89d940bc2aa92cdc485f7`](https://github.com/block/buzz/commit/0e878664b08cdf7fb2d89d940bc2aa92cdc485f7)) +- docs(nip-fi): rewrite NIP-FI as stateless OSS Buzz spec v2 ([#7214](https://github.com/block/buzz/pull/7214)) ([`d4420eb47f9d48bd81358f928dfe6dee6804ac13`](https://github.com/block/buzz/commit/d4420eb47f9d48bd81358f928dfe6dee6804ac13)) +- feat(relay): add detailed readiness metrics ([#7149](https://github.com/block/buzz/pull/7149)) ([`beb76406c12ab8a7af9b2fcf7547c353e3369c34`](https://github.com/block/buzz/commit/beb76406c12ab8a7af9b2fcf7547c353e3369c34)) +- feat(mobile): prepare `buzz-push-gateway` for deployment ([#7158](https://github.com/block/buzz/pull/7158)) ([`42b42447b0dc47c3e1a4d95caab893567dcd1677`](https://github.com/block/buzz/commit/42b42447b0dc47c3e1a4d95caab893567dcd1677)) +- fix(mobile): isolate extension linker flags; complete iOS build in CI ([#7187](https://github.com/block/buzz/pull/7187)) ([`b270437a62bc1049b27745799dc44268d0c23489`](https://github.com/block/buzz/commit/b270437a62bc1049b27745799dc44268d0c23489)) +- chore(ci): lower Codex security review effort ([#7179](https://github.com/block/buzz/pull/7179)) ([`4365883151698cd30e31cf4091629543b61c2478`](https://github.com/block/buzz/commit/4365883151698cd30e31cf4091629543b61c2478)) +- fix(dev): keep the canonical profile when launching from desktop/ ([#7143](https://github.com/block/buzz/pull/7143)) ([`e17a0d44c379b2ae40b91b8ba43f9a9c5bede90f`](https://github.com/block/buzz/commit/e17a0d44c379b2ae40b91b8ba43f9a9c5bede90f)) +- ci: run PostgreSQL tests in isolated lane ([#6730](https://github.com/block/buzz/pull/6730)) ([`bd73490418266f267d9bb3bdf13e64582adc8e80`](https://github.com/block/buzz/commit/bd73490418266f267d9bb3bdf13e64582adc8e80)) +- feat(db): add NIP-FI identity and final-admission schema foundation ([#6994](https://github.com/block/buzz/pull/6994)) ([`9ab163190b4d4994a742a66d5fa4cae23c35fa4e`](https://github.com/block/buzz/commit/9ab163190b4d4994a742a66d5fa4cae23c35fa4e)) +- feat(buzz-acp): give each channel thread its own agent session ([#6732](https://github.com/block/buzz/pull/6732)) ([`674c173eb7b2805864fd8375297c849c3a758f69`](https://github.com/block/buzz/commit/674c173eb7b2805864fd8375297c849c3a758f69)) +- docs: add review-proven failure-path & async-state rules to AGENTS.md ([#7061](https://github.com/block/buzz/pull/7061)) ([`4952f5810290d00a1dd9413235b39e9a7154acf6`](https://github.com/block/buzz/commit/4952f5810290d00a1dd9413235b39e9a7154acf6)) +- fix(acp): wake agents from workflow messages ([#6953](https://github.com/block/buzz/pull/6953)) ([`93237b4a745b14cb8bfe292053bf34adef652d29`](https://github.com/block/buzz/commit/93237b4a745b14cb8bfe292053bf34adef652d29)) +- fix(ci): salvage Codex review output on PTY-shutdown hang ([#7042](https://github.com/block/buzz/pull/7042)) ([`17ecf0b8c9c0f4bb9d098f25c2a2ece6a3500a4c`](https://github.com/block/buzz/commit/17ecf0b8c9c0f4bb9d098f25c2a2ece6a3500a4c)) +- fix: retrieving cold memories; add regression task ([#6950](https://github.com/block/buzz/pull/6950)) ([`f463e726dd173146c3c2bcbf7fdba03c9790dd3a`](https://github.com/block/buzz/commit/f463e726dd173146c3c2bcbf7fdba03c9790dd3a)) +- feat(db): configurable writer session timeouts (lock, idle-txn, statement) ([#6229](https://github.com/block/buzz/pull/6229)) ([`3ed623bb217bf9697b0ce4562529254977e0ea04`](https://github.com/block/buzz/commit/3ed623bb217bf9697b0ce4562529254977e0ea04)) +- perf(mobile): reduce cold startup and channel rendering delays ([#6996](https://github.com/block/buzz/pull/6996)) ([`b593c7d7feb6bf4207dbf3439906c25a714b703f`](https://github.com/block/buzz/commit/b593c7d7feb6bf4207dbf3439906c25a714b703f)) +- feat(mobile): push notifications MVP ([#6269](https://github.com/block/buzz/pull/6269)) ([`c432a111ca9ddd31a85e1312d5995f8b92191b82`](https://github.com/block/buzz/commit/c432a111ca9ddd31a85e1312d5995f8b92191b82)) +- Refresh mobile utility surfaces and theme picker ([#6944](https://github.com/block/buzz/pull/6944)) ([`ed11c8d8bf0a17402be5cf243724f89471530d2f`](https://github.com/block/buzz/commit/ed11c8d8bf0a17402be5cf243724f89471530d2f)) +- Fix mobile jump-to-latest flicker ([#6807](https://github.com/block/buzz/pull/6807)) ([`58cc4b7e9be71223f7898ea5f930a4248830ccfb`](https://github.com/block/buzz/commit/58cc4b7e9be71223f7898ea5f930a4248830ccfb)) +- refactor(relay): NIP-98 admin auth with Operator/Moderator roles and NIP-11 discovery ([#3777](https://github.com/block/buzz/pull/3777)) ([`86b9142a09f2af3ba2fff7effa6a6cd53b40f51c`](https://github.com/block/buzz/commit/86b9142a09f2af3ba2fff7effa6a6cd53b40f51c)) +- refactor(db): split channel membership store ([#6782](https://github.com/block/buzz/pull/6782)) ([`e76c81968b65b0755b83efdd59dc3375c59ddf40`](https://github.com/block/buzz/commit/e76c81968b65b0755b83efdd59dc3375c59ddf40)) +- feat(auth): add NIP-FI canonical assertion verifier and contracts ([#6776](https://github.com/block/buzz/pull/6776)) ([`953a1798b23b04289b3a225f463e60a172c1aac3`](https://github.com/block/buzz/commit/953a1798b23b04289b3a225f463e60a172c1aac3)) +- fix(ci): bump Codex CLI to 0.150.1 to unhang security review jobs ([#6962](https://github.com/block/buzz/pull/6962)) ([`80177e4c8e97e7bf1f1a3760c4e3503aace22860`](https://github.com/block/buzz/commit/80177e4c8e97e7bf1f1a3760c4e3503aace22860)) +- test(db): use canonical channel roster fixtures ([#6819](https://github.com/block/buzz/pull/6819)) ([`57216c942f171db305135bcb6a4ede2d87e0be8a`](https://github.com/block/buzz/commit/57216c942f171db305135bcb6a4ede2d87e0be8a)) +- fix(cli): enrich template cardinality error with per-candidate presence and profile hints ([#4825](https://github.com/block/buzz/pull/4825)) ([`0808ab485c39c3c12ef02af2188c65a5145eb99d`](https://github.com/block/buzz/commit/0808ab485c39c3c12ef02af2188c65a5145eb99d)) +- Fix Codex security review authorization ([#6913](https://github.com/block/buzz/pull/6913)) ([`745ff6066c92372ea1ee6a5fe05862cdd9b81303`](https://github.com/block/buzz/commit/745ff6066c92372ea1ee6a5fe05862cdd9b81303)) +- fix(db): disable heartbeat vacuum truncation ([#6898](https://github.com/block/buzz/pull/6898)) ([`0ccf934b88f610f5f235862ecd51e2dcbae2cb74`](https://github.com/block/buzz/commit/0ccf934b88f610f5f235862ecd51e2dcbae2cb74)) +- chore(deps): update rui314/setup-mold digest to 7e4f20a ([#6663](https://github.com/block/buzz/pull/6663)) ([`c363ce13c07cb454d6fa92b96d65cb52322c13e9`](https://github.com/block/buzz/commit/c363ce13c07cb454d6fa92b96d65cb52322c13e9)) +- chore(deps): update dependency vitest to v4.1.11 ([#6667](https://github.com/block/buzz/pull/6667)) ([`525007af4b2f644ce07fab92ef4863c46cbae8a3`](https://github.com/block/buzz/commit/525007af4b2f644ce07fab92ef4863c46cbae8a3)) +- chore(deps): update dependency @tanstack/react-virtual to v3.14.10 ([#6666](https://github.com/block/buzz/pull/6666)) ([`30596d3addf69a6954d034ce28f886539604f2c8`](https://github.com/block/buzz/commit/30596d3addf69a6954d034ce28f886539604f2c8)) +- chore(deps): update ubuntu:24.04 docker digest to 33ceb71 ([#6664](https://github.com/block/buzz/pull/6664)) ([`82e748085e3f06b8e297387b33f7615a6db23501`](https://github.com/block/buzz/commit/82e748085e3f06b8e297387b33f7615a6db23501)) +- fix(db): exclude kind:30179 ciphertext from brownfield FTS ([#6822](https://github.com/block/buzz/pull/6822)) ([`b3baa56ba83d01a0b7292d81aae9370f5616c62b`](https://github.com/block/buzz/commit/b3baa56ba83d01a0b7292d81aae9370f5616c62b)) +- Add gated security reviews ([#6816](https://github.com/block/buzz/pull/6816)) ([`cdab765748ddfeba10830a9a5331b6157bd321df`](https://github.com/block/buzz/commit/cdab765748ddfeba10830a9a5331b6157bd321df)) +- Add Buzz benchmark evaluation layers ([#6823](https://github.com/block/buzz/pull/6823)) ([`79df468255b50f6aa7bd9cb19a622a4a37b88dac`](https://github.com/block/buzz/commit/79df468255b50f6aa7bd9cb19a622a4a37b88dac)) +- Deduplicate ACP thread prompt context ([#6706](https://github.com/block/buzz/pull/6706)) ([`8f3566ad9ebbd225e53ce66a7072ceee074eb25a`](https://github.com/block/buzz/commit/8f3566ad9ebbd225e53ce66a7072ceee074eb25a)) +- refactor(db): finish replaceable event store extraction ([#6777](https://github.com/block/buzz/pull/6777)) ([`ef0d2025683869418e8eee22ac5b5ac16c5198b7`](https://github.com/block/buzz/commit/ef0d2025683869418e8eee22ac5b5ac16c5198b7)) +- Fix Admin feedback filter overflow ([#6825](https://github.com/block/buzz/pull/6825)) ([`dcee330b5ca984de8657a6d8cf36e34e1d825d4a`](https://github.com/block/buzz/commit/dcee330b5ca984de8657a6d8cf36e34e1d825d4a)) + +[Compare desktop-v0.5.20...desktop-v0.5.22](https://github.com/block/buzz/compare/desktop-v0.5.20...desktop-v0.5.22) + +## v0.5.21 + +### Desktop and shared changes + +- fix(desktop): wrap message tables within the available pane ([#7279](https://github.com/block/buzz/pull/7279)) ([`6cf514ed90981d1db4acdb97a272543ecca83993`](https://github.com/block/buzz/commit/6cf514ed90981d1db4acdb97a272543ecca83993)) +- 🤖 fix(desktop): harden smoke E2E tests against Bestie overlay and toast timing ([#7270](https://github.com/block/buzz/pull/7270)) ([`7a9a5233d9d755e715be0c585cf7850e935d28cf`](https://github.com/block/buzz/commit/7a9a5233d9d755e715be0c585cf7850e935d28cf)) +- Show status and huddle indicators beside names ([#7112](https://github.com/block/buzz/pull/7112)) ([`c6ca9d94d94230a315257a87beb8dc116fec56cc`](https://github.com/block/buzz/commit/c6ca9d94d94230a315257a87beb8dc116fec56cc)) +- perf(desktop): publish mention sends before waking agents ([#7154](https://github.com/block/buzz/pull/7154)) ([`40220d5618fc7dbe06421f358053ca77ed0f67d7`](https://github.com/block/buzz/commit/40220d5618fc7dbe06421f358053ca77ed0f67d7)) +- fix(desktop): unify owned-agent cloud provenance markers ([#7129](https://github.com/block/buzz/pull/7129)) ([`5073e075d7e7d95558c57f24d86d5db6196491c4`](https://github.com/block/buzz/commit/5073e075d7e7d95558c57f24d86d5db6196491c4)) +- fix(desktop): derive agent availability from relay presence ([#7127](https://github.com/block/buzz/pull/7127)) ([`d5a73b9f35feaa81ef9afb13d1ec8943e8ec6ca9`](https://github.com/block/buzz/commit/d5a73b9f35feaa81ef9afb13d1ec8943e8ec6ca9)) +- fix(desktop): preserve spacing after multi-word mentions ([#7128](https://github.com/block/buzz/pull/7128)) ([`44d19f59a593dfb541bf40dcadbed313ca4a8f97`](https://github.com/block/buzz/commit/44d19f59a593dfb541bf40dcadbed313ca4a8f97)) +- feat(cli): add buzz gifs command group and NIP-30 emoji tags on messages ([#7259](https://github.com/block/buzz/pull/7259)) ([`47d068e2109d077414cbf2f4f1c927f6d051037a`](https://github.com/block/buzz/commit/47d068e2109d077414cbf2f4f1c927f6d051037a)) +- feat(desktop): add persistent Bestie experience ([#7223](https://github.com/block/buzz/pull/7223)) ([`ac5a18697c8294e9237f505a2e01ec6fc374849a`](https://github.com/block/buzz/commit/ac5a18697c8294e9237f505a2e01ec6fc374849a)) +- fix(desktop): harden profile batch and thread-reply fetches against relay slowness ([#7188](https://github.com/block/buzz/pull/7188)) ([`6f6093243eaea5160db79b7e054f06dfffd207aa`](https://github.com/block/buzz/commit/6f6093243eaea5160db79b7e054f06dfffd207aa)) +- fix(composer): align wrapped inline chip fragments ([#7242](https://github.com/block/buzz/pull/7242)) ([`b6dc533b7c2aadb70a8f011a88a5bd2f06d800f2`](https://github.com/block/buzz/commit/b6dc533b7c2aadb70a8f011a88a5bd2f06d800f2)) +- fix(desktop): keep explicit agent profiles bound to their exact key ([#7131](https://github.com/block/buzz/pull/7131)) ([`83e596298449ab1cb57481221d0e41ce69e52814`](https://github.com/block/buzz/commit/83e596298449ab1cb57481221d0e41ce69e52814)) +- fix(desktop): discover authenticated owned relay agents ([#7122](https://github.com/block/buzz/pull/7122)) ([`434dafe958d82ca07d2b42b0f7d023ab923c2ff9`](https://github.com/block/buzz/commit/434dafe958d82ca07d2b42b0f7d023ab923c2ff9)) +- feat(agents): harness-agnostic effort write path and spawn bridge ([#4625](https://github.com/block/buzz/pull/4625)) ([`0dbd036f5bff33e7ade75e7639f3218d424a6e73`](https://github.com/block/buzz/commit/0dbd036f5bff33e7ade75e7639f3218d424a6e73)) +- fix(desktop): retain automatic mentions only in threads ([#7144](https://github.com/block/buzz/pull/7144)) ([`1c8321cd08feb597f8bcff5195c21148fb3e98ed`](https://github.com/block/buzz/commit/1c8321cd08feb597f8bcff5195c21148fb3e98ed)) +- feat: add databricks fable 5.1 model capabilities ([#7213](https://github.com/block/buzz/pull/7213)) ([`560fea7b4fc5e96a4de45d988e039ffb3fd66662`](https://github.com/block/buzz/commit/560fea7b4fc5e96a4de45d988e039ffb3fd66662)) +- feat(desktop): add Pi agent preset ([#7208](https://github.com/block/buzz/pull/7208)) ([`42aeb1571cc1f1ed4d73f05b420474be970021ab`](https://github.com/block/buzz/commit/42aeb1571cc1f1ed4d73f05b420474be970021ab)) +- feat(buzz-agent): add DatabricksAuthCoordinator single-flight OAuth ([#5545](https://github.com/block/buzz/pull/5545)) ([`5aed49b505a7e27f3b0e34dafa53d6c4e8cdcd64`](https://github.com/block/buzz/commit/5aed49b505a7e27f3b0e34dafa53d6c4e8cdcd64)) +- fix(desktop): preserve keyring identity during recovery ([#7203](https://github.com/block/buzz/pull/7203)) ([`e5a7e26a1008227ff6a0b9430a6df2470475bec1`](https://github.com/block/buzz/commit/e5a7e26a1008227ff6a0b9430a6df2470475bec1)) +- ci: relax file-size ceilings by surface ([#6485](https://github.com/block/buzz/pull/6485)) ([`4794a5cecf058ebbe2b367f40b1ce6ff80791e91`](https://github.com/block/buzz/commit/4794a5cecf058ebbe2b367f40b1ce6ff80791e91)) +- fix(dev-mcp): extend shell timeout cap to 20 minutes and align outer budgets ([#7185](https://github.com/block/buzz/pull/7185)) ([`cae158ce7fd72dee1f34d264f6790711d82d46bf`](https://github.com/block/buzz/commit/cae158ce7fd72dee1f34d264f6790711d82d46bf)) +- feat(buzz-auth): add production NIP-FI federated assertion runtime ([#7109](https://github.com/block/buzz/pull/7109)) ([`70895b355fcea9f99894b426c020052b715bd368`](https://github.com/block/buzz/commit/70895b355fcea9f99894b426c020052b715bd368)) +- Hide download action on voice notes ([#7182](https://github.com/block/buzz/pull/7182)) ([`ac4aa94b05417c2830e5489ddda0c87f6a9d1dbf`](https://github.com/block/buzz/commit/ac4aa94b05417c2830e5489ddda0c87f6a9d1dbf)) +- Add voice notes to desktop messages ([#6978](https://github.com/block/buzz/pull/6978)) ([`114dbf745f1fe0bdbecb70e07a07f03c23687bdc`](https://github.com/block/buzz/commit/114dbf745f1fe0bdbecb70e07a07f03c23687bdc)) +- feat(desktop): add thread-scoped ACP session experiment ([#6909](https://github.com/block/buzz/pull/6909)) ([`59328d5ae38a51a618dd2fddd7faf1343d42096f`](https://github.com/block/buzz/commit/59328d5ae38a51a618dd2fddd7faf1343d42096f)) +- fix(desktop): scope composer autocomplete to focus ([#6860](https://github.com/block/buzz/pull/6860)) ([`571c1902d0ca55cfd4ccf6b91eeb731909cc10be`](https://github.com/block/buzz/commit/571c1902d0ca55cfd4ccf6b91eeb731909cc10be)) +- feat(desktop): add isolated named demo builds ([#6407](https://github.com/block/buzz/pull/6407)) ([`4a9de1a3a121285ef475d630b2b5764044c02cde`](https://github.com/block/buzz/commit/4a9de1a3a121285ef475d630b2b5764044c02cde)) +- fix(model-capabilities): humanize databricks goose model names ([#7135](https://github.com/block/buzz/pull/7135)) ([`0affe527e880ddd300ae7d4dac3f0600c79b4f5e`](https://github.com/block/buzz/commit/0affe527e880ddd300ae7d4dac3f0600c79b4f5e)) +- fix(desktop): back split thread headers ([#7137](https://github.com/block/buzz/pull/7137)) ([`b47b5a50127c080a74ed4de19a43534cd9a7b563`](https://github.com/block/buzz/commit/b47b5a50127c080a74ed4de19a43534cd9a7b563)) +- add public descriptions to agent personas ([#7126](https://github.com/block/buzz/pull/7126)) ([`cb3144999bebc4939cb15b2200b373281d493b52`](https://github.com/block/buzz/commit/cb3144999bebc4939cb15b2200b373281d493b52)) +- feat(desktop): add protected-build Bestie experiment ([#6902](https://github.com/block/buzz/pull/6902)) ([`5673c3307e248530beeea060da437350d3939a4b`](https://github.com/block/buzz/commit/5673c3307e248530beeea060da437350d3939a4b)) +- fix(relay): reject a frame on its own acknowledgement channel ([#6961](https://github.com/block/buzz/pull/6961)) ([`2f3dd850db3afe27e56f18cbcd3548eabdd9b9c2`](https://github.com/block/buzz/commit/2f3dd850db3afe27e56f18cbcd3548eabdd9b9c2)) +- feat: render agent avatars as squircles ([#7106](https://github.com/block/buzz/pull/7106)) ([`bc006f67087b049e2f9c4d8a2f26faceff628225`](https://github.com/block/buzz/commit/bc006f67087b049e2f9c4d8a2f26faceff628225)) +- Enforce NIP-OA authorization time bounds ([#7004](https://github.com/block/buzz/pull/7004)) ([`e47690c21b519128b40c917456b3e3f33f018fe4`](https://github.com/block/buzz/commit/e47690c21b519128b40c917456b3e3f33f018fe4)) +- feat(desktop): use segmented controls for channel creation ([#6845](https://github.com/block/buzz/pull/6845)) ([`c3132c3ee982d194cd0198ad07b57ec8bd726e4e`](https://github.com/block/buzz/commit/c3132c3ee982d194cd0198ad07b57ec8bd726e4e)) +- feat(buzz-agent): surface stop reason and silent-turn WARN in telemetry ([#7038](https://github.com/block/buzz/pull/7038)) ([`eed74bde2f4797714335ac10c56c0b0244c1def4`](https://github.com/block/buzz/commit/eed74bde2f4797714335ac10c56c0b0244c1def4)) +- fix(desktop): surface channel history load failures ([#7013](https://github.com/block/buzz/pull/7013)) ([`00e61eafa917d296104006576b7a2ddbfd58bb5a`](https://github.com/block/buzz/commit/00e61eafa917d296104006576b7a2ddbfd58bb5a)) +- fix(composer): polish automatic mentions ([#6956](https://github.com/block/buzz/pull/6956)) ([`8dbc65d9e2c80d9d8516e17b751c46e0568100e6`](https://github.com/block/buzz/commit/8dbc65d9e2c80d9d8516e17b751c46e0568100e6)) +- fix(desktop): resolve bundled sidecar on cheap path and bound login-shell spawns ([#6904](https://github.com/block/buzz/pull/6904)) ([`2c99ee7af5a20d239e95ec5368407887449795c9`](https://github.com/block/buzz/commit/2c99ee7af5a20d239e95ec5368407887449795c9)) +- refactor(db): extract domain stores from database runtime ([#6987](https://github.com/block/buzz/pull/6987)) ([`a3730784fc851bb1125b40cca9b0a30788a293c1`](https://github.com/block/buzz/commit/a3730784fc851bb1125b40cca9b0a30788a293c1)) +- feat(desktop): add team sharing to community catalog ([#3995](https://github.com/block/buzz/pull/3995)) ([`2f66ee24a0bf5efa958378069a6b155e99a1d068`](https://github.com/block/buzz/commit/2f66ee24a0bf5efa958378069a6b155e99a1d068)) +- fix(desktop): complete project empty and context states ([#6980](https://github.com/block/buzz/pull/6980)) ([`a89f5df4c52c3aa5875d9fccb0eaf2222aee4084`](https://github.com/block/buzz/commit/a89f5df4c52c3aa5875d9fccb0eaf2222aee4084)) +- fix(desktop): resolve exact typed mentions on space ([#6862](https://github.com/block/buzz/pull/6862)) ([`b49675894b39f87215e4dfc8c1ad4a3c28c6097e`](https://github.com/block/buzz/commit/b49675894b39f87215e4dfc8c1ad4a3c28c6097e)) +- perf(desktop): restore project context during startup ([#6939](https://github.com/block/buzz/pull/6939)) ([`973386351646d01efca2735ad4921c0d219cff85`](https://github.com/block/buzz/commit/973386351646d01efca2735ad4921c0d219cff85)) +- fix(desktop): lift right auxiliary pane above shared header backdrop ([#6966](https://github.com/block/buzz/pull/6966)) ([`350caf1de3136f6ec473a69d394544e99dfd4d85`](https://github.com/block/buzz/commit/350caf1de3136f6ec473a69d394544e99dfd4d85)) +- feat(desktop): implement 30178 team catalog backend ([#5112](https://github.com/block/buzz/pull/5112)) ([`a7c7414a7fadfe1585b8a90af0f29d6593bb6126`](https://github.com/block/buzz/commit/a7c7414a7fadfe1585b8a90af0f29d6593bb6126)) +- feat(model-capabilities): humanize Databricks UC model families ([#6955](https://github.com/block/buzz/pull/6955)) ([`ae0ecd9a676c692876116fee7265cba5f18cbd90`](https://github.com/block/buzz/commit/ae0ecd9a676c692876116fee7265cba5f18cbd90)) +- feat(agent): discover Databricks Unity Catalog models ([#6918](https://github.com/block/buzz/pull/6918)) ([`be8d7756d5f17285f1e8a4b77d67f7d7cfb6f9e7`](https://github.com/block/buzz/commit/be8d7756d5f17285f1e8a4b77d67f7d7cfb6f9e7)) +- preserve channel description paragraph breaks ([#6946](https://github.com/block/buzz/pull/6946)) ([`69096c9a8db726eebd83422cdc5e6c72ed9d4f90`](https://github.com/block/buzz/commit/69096c9a8db726eebd83422cdc5e6c72ed9d4f90)) +- fix(projects): allow owners to delete agent projects ([#6533](https://github.com/block/buzz/pull/6533)) ([`9176e34405ae59fdefc50dc585454b7e9cb3833a`](https://github.com/block/buzz/commit/9176e34405ae59fdefc50dc585454b7e9cb3833a)) +- Fade expanded video controls on hover ([#6926](https://github.com/block/buzz/pull/6926)) ([`27c1a7c91b658535c8a655dbe8f2421af9099b80`](https://github.com/block/buzz/commit/27c1a7c91b658535c8a655dbe8f2421af9099b80)) +- fix(client): resurface hidden DMs from live activity ([#6885](https://github.com/block/buzz/pull/6885)) ([`4d77175c78f4df48e13398b25b271e3ac1b31dd3`](https://github.com/block/buzz/commit/4d77175c78f4df48e13398b25b271e3ac1b31dd3)) +- fix(desktop): keep the draft space when typing right after a mention pick ([#6875](https://github.com/block/buzz/pull/6875)) ([`c856be0fb954c9e5267d622841098c24e3381e8f`](https://github.com/block/buzz/commit/c856be0fb954c9e5267d622841098c24e3381e8f)) +- broker: define the agent-to-broker action contract ([#6742](https://github.com/block/buzz/pull/6742)) ([`b622003f74aa5bf9b659786452813299a25e4897`](https://github.com/block/buzz/commit/b622003f74aa5bf9b659786452813299a25e4897)) +- fix(desktop): keep project sheets independent from threads ([#6901](https://github.com/block/buzz/pull/6901)) ([`cada3028ceda7ebdae61329f15b5364ca0d23dd4`](https://github.com/block/buzz/commit/cada3028ceda7ebdae61329f15b5364ca0d23dd4)) +- fix(desktop): accent-colored mention badges that count thread mentions ([#6900](https://github.com/block/buzz/pull/6900)) ([`ceb8ba605f43728bdab64aa461211baeeb54364a`](https://github.com/block/buzz/commit/ceb8ba605f43728bdab64aa461211baeeb54364a)) +- fix(desktop): show edited head content in thread panel ([#6887](https://github.com/block/buzz/pull/6887)) ([`eb8e97cfe74afbe560d92f3a8f470967a992767f`](https://github.com/block/buzz/commit/eb8e97cfe74afbe560d92f3a8f470967a992767f)) +- fix(desktop-tooltip): increase surface contrast ([#6897](https://github.com/block/buzz/pull/6897)) ([`03bfc837cbe463de9ef59a86742825a4863fb603`](https://github.com/block/buzz/commit/03bfc837cbe463de9ef59a86742825a4863fb603)) +- Apply access policy when reusing channel agents ([#6838](https://github.com/block/buzz/pull/6838)) ([`01c87a350b0fda89c8d333a5dd6c0e9d89d0c03f`](https://github.com/block/buzz/commit/01c87a350b0fda89c8d333a5dd6c0e9d89d0c03f)) +- feat(sidebar): prioritize unread DMs in overflow navigation ([#6842](https://github.com/block/buzz/pull/6842)) ([`4f554b6385065b698db819498a6f359b17a45459`](https://github.com/block/buzz/commit/4f554b6385065b698db819498a6f359b17a45459)) +- feat(projects): add agent and CLI project-home support ([#6590](https://github.com/block/buzz/pull/6590)) ([`de188ebf06f701ca0f47c51f859da21e19a35f04`](https://github.com/block/buzz/commit/de188ebf06f701ca0f47c51f859da21e19a35f04)) +- feat(desktop): restore message quick reactions ([#6892](https://github.com/block/buzz/pull/6892)) ([`22cdda441d19da1b15dd7db4d932d2f067cd87b3`](https://github.com/block/buzz/commit/22cdda441d19da1b15dd7db4d932d2f067cd87b3)) +- Use paired tags for standing & per-turn context ([#6701](https://github.com/block/buzz/pull/6701)) ([`f177f4909d55ad48a36e86a682cd5be4f006f0fe`](https://github.com/block/buzz/commit/f177f4909d55ad48a36e86a682cd5be4f006f0fe)) +- fix(cli): preserve signatures in event reads ([#6884](https://github.com/block/buzz/pull/6884)) ([`583af02299e20cbd8603044c7844bc128e4e06cd`](https://github.com/block/buzz/commit/583af02299e20cbd8603044c7844bc128e4e06cd)) +- fix(desktop): stop pulsing addressed agents on send ([#6873](https://github.com/block/buzz/pull/6873)) ([`db514b153a8cb17631d6e80b91c95fdc45deb147`](https://github.com/block/buzz/commit/db514b153a8cb17631d6e80b91c95fdc45deb147)) +- fix(desktop): prioritize sidebar channel status ([#6861](https://github.com/block/buzz/pull/6861)) ([`4f529a45f219f55bc6038f304cd69e3f51ec0533`](https://github.com/block/buzz/commit/4f529a45f219f55bc6038f304cd69e3f51ec0533)) +- feat(desktop): hyperlink selected composer text on link paste ([#6684](https://github.com/block/buzz/pull/6684)) ([`e8172b5baccd0f4a711f5e19a3bc4313708f1c78`](https://github.com/block/buzz/commit/e8172b5baccd0f4a711f5e19a3bc4313708f1c78)) + +### Other repository changes + +- feat(relay): add early startup lifecycle logs ([#7258](https://github.com/block/buzz/pull/7258)) ([`88687876f7808a2fd742b7eb2e4b9f87d999ad8d`](https://github.com/block/buzz/commit/88687876f7808a2fd742b7eb2e4b9f87d999ad8d)) +- docs(nip-fi): add Blossom kind-24242 media possession-proof exception ([#7278](https://github.com/block/buzz/pull/7278)) ([`752cbfc0375efc8bac3d5cc2a5716250bc0be234`](https://github.com/block/buzz/commit/752cbfc0375efc8bac3d5cc2a5716250bc0be234)) +- Add mobile voice notes ([#7121](https://github.com/block/buzz/pull/7121)) ([`6f5ec4a731901bf3ff2a370c7ccbfbc3fba93368`](https://github.com/block/buzz/commit/6f5ec4a731901bf3ff2a370c7ccbfbc3fba93368)) +- docs(nip-fi): document Git smart-HTTP credential exemption ([#7268](https://github.com/block/buzz/pull/7268)) ([`c328202cb08cac5b8c1610d2d373e69889772b4e`](https://github.com/block/buzz/commit/c328202cb08cac5b8c1610d2d373e69889772b4e)) +- docs(nip-fi): adopt deny-until-TTL and extend enforcement to HTTP ingress ([#7254](https://github.com/block/buzz/pull/7254)) ([`187df22252fa24cce2f3295fb9df9f4dc211b30a`](https://github.com/block/buzz/commit/187df22252fa24cce2f3295fb9df9f4dc211b30a)) +- Add operation-aware database pool acquisition metrics ([#7195](https://github.com/block/buzz/pull/7195)) ([`91ab9d31b8f7249ff1db141ae9d8bb3f2a20bcdd`](https://github.com/block/buzz/commit/91ab9d31b8f7249ff1db141ae9d8bb3f2a20bcdd)) +- chore(db): drop Phase-A NIP-FI relay-side authority ledger ([#7221](https://github.com/block/buzz/pull/7221)) ([`04babf02655440b4dfd37f2e2df605ead0a030d8`](https://github.com/block/buzz/commit/04babf02655440b4dfd37f2e2df605ead0a030d8)) +- fix(acp): replace real user name in base prompt mention example ([#7250](https://github.com/block/buzz/pull/7250)) ([`2af9773d6271ce62cbe5dfbd28fbe5dd79372465`](https://github.com/block/buzz/commit/2af9773d6271ce62cbe5dfbd28fbe5dd79372465)) +- ci: split CI into reusable workflows ([#7168](https://github.com/block/buzz/pull/7168)) ([`0e878664b08cdf7fb2d89d940bc2aa92cdc485f7`](https://github.com/block/buzz/commit/0e878664b08cdf7fb2d89d940bc2aa92cdc485f7)) +- docs(nip-fi): rewrite NIP-FI as stateless OSS Buzz spec v2 ([#7214](https://github.com/block/buzz/pull/7214)) ([`d4420eb47f9d48bd81358f928dfe6dee6804ac13`](https://github.com/block/buzz/commit/d4420eb47f9d48bd81358f928dfe6dee6804ac13)) +- feat(relay): add detailed readiness metrics ([#7149](https://github.com/block/buzz/pull/7149)) ([`beb76406c12ab8a7af9b2fcf7547c353e3369c34`](https://github.com/block/buzz/commit/beb76406c12ab8a7af9b2fcf7547c353e3369c34)) +- feat(mobile): prepare `buzz-push-gateway` for deployment ([#7158](https://github.com/block/buzz/pull/7158)) ([`42b42447b0dc47c3e1a4d95caab893567dcd1677`](https://github.com/block/buzz/commit/42b42447b0dc47c3e1a4d95caab893567dcd1677)) +- fix(mobile): isolate extension linker flags; complete iOS build in CI ([#7187](https://github.com/block/buzz/pull/7187)) ([`b270437a62bc1049b27745799dc44268d0c23489`](https://github.com/block/buzz/commit/b270437a62bc1049b27745799dc44268d0c23489)) +- chore(ci): lower Codex security review effort ([#7179](https://github.com/block/buzz/pull/7179)) ([`4365883151698cd30e31cf4091629543b61c2478`](https://github.com/block/buzz/commit/4365883151698cd30e31cf4091629543b61c2478)) +- fix(dev): keep the canonical profile when launching from desktop/ ([#7143](https://github.com/block/buzz/pull/7143)) ([`e17a0d44c379b2ae40b91b8ba43f9a9c5bede90f`](https://github.com/block/buzz/commit/e17a0d44c379b2ae40b91b8ba43f9a9c5bede90f)) +- ci: run PostgreSQL tests in isolated lane ([#6730](https://github.com/block/buzz/pull/6730)) ([`bd73490418266f267d9bb3bdf13e64582adc8e80`](https://github.com/block/buzz/commit/bd73490418266f267d9bb3bdf13e64582adc8e80)) +- feat(db): add NIP-FI identity and final-admission schema foundation ([#6994](https://github.com/block/buzz/pull/6994)) ([`9ab163190b4d4994a742a66d5fa4cae23c35fa4e`](https://github.com/block/buzz/commit/9ab163190b4d4994a742a66d5fa4cae23c35fa4e)) +- feat(buzz-acp): give each channel thread its own agent session ([#6732](https://github.com/block/buzz/pull/6732)) ([`674c173eb7b2805864fd8375297c849c3a758f69`](https://github.com/block/buzz/commit/674c173eb7b2805864fd8375297c849c3a758f69)) +- docs: add review-proven failure-path & async-state rules to AGENTS.md ([#7061](https://github.com/block/buzz/pull/7061)) ([`4952f5810290d00a1dd9413235b39e9a7154acf6`](https://github.com/block/buzz/commit/4952f5810290d00a1dd9413235b39e9a7154acf6)) +- fix(acp): wake agents from workflow messages ([#6953](https://github.com/block/buzz/pull/6953)) ([`93237b4a745b14cb8bfe292053bf34adef652d29`](https://github.com/block/buzz/commit/93237b4a745b14cb8bfe292053bf34adef652d29)) +- fix(ci): salvage Codex review output on PTY-shutdown hang ([#7042](https://github.com/block/buzz/pull/7042)) ([`17ecf0b8c9c0f4bb9d098f25c2a2ece6a3500a4c`](https://github.com/block/buzz/commit/17ecf0b8c9c0f4bb9d098f25c2a2ece6a3500a4c)) +- fix: retrieving cold memories; add regression task ([#6950](https://github.com/block/buzz/pull/6950)) ([`f463e726dd173146c3c2bcbf7fdba03c9790dd3a`](https://github.com/block/buzz/commit/f463e726dd173146c3c2bcbf7fdba03c9790dd3a)) +- feat(db): configurable writer session timeouts (lock, idle-txn, statement) ([#6229](https://github.com/block/buzz/pull/6229)) ([`3ed623bb217bf9697b0ce4562529254977e0ea04`](https://github.com/block/buzz/commit/3ed623bb217bf9697b0ce4562529254977e0ea04)) +- perf(mobile): reduce cold startup and channel rendering delays ([#6996](https://github.com/block/buzz/pull/6996)) ([`b593c7d7feb6bf4207dbf3439906c25a714b703f`](https://github.com/block/buzz/commit/b593c7d7feb6bf4207dbf3439906c25a714b703f)) +- feat(mobile): push notifications MVP ([#6269](https://github.com/block/buzz/pull/6269)) ([`c432a111ca9ddd31a85e1312d5995f8b92191b82`](https://github.com/block/buzz/commit/c432a111ca9ddd31a85e1312d5995f8b92191b82)) +- Refresh mobile utility surfaces and theme picker ([#6944](https://github.com/block/buzz/pull/6944)) ([`ed11c8d8bf0a17402be5cf243724f89471530d2f`](https://github.com/block/buzz/commit/ed11c8d8bf0a17402be5cf243724f89471530d2f)) +- Fix mobile jump-to-latest flicker ([#6807](https://github.com/block/buzz/pull/6807)) ([`58cc4b7e9be71223f7898ea5f930a4248830ccfb`](https://github.com/block/buzz/commit/58cc4b7e9be71223f7898ea5f930a4248830ccfb)) +- refactor(relay): NIP-98 admin auth with Operator/Moderator roles and NIP-11 discovery ([#3777](https://github.com/block/buzz/pull/3777)) ([`86b9142a09f2af3ba2fff7effa6a6cd53b40f51c`](https://github.com/block/buzz/commit/86b9142a09f2af3ba2fff7effa6a6cd53b40f51c)) +- refactor(db): split channel membership store ([#6782](https://github.com/block/buzz/pull/6782)) ([`e76c81968b65b0755b83efdd59dc3375c59ddf40`](https://github.com/block/buzz/commit/e76c81968b65b0755b83efdd59dc3375c59ddf40)) +- feat(auth): add NIP-FI canonical assertion verifier and contracts ([#6776](https://github.com/block/buzz/pull/6776)) ([`953a1798b23b04289b3a225f463e60a172c1aac3`](https://github.com/block/buzz/commit/953a1798b23b04289b3a225f463e60a172c1aac3)) +- fix(ci): bump Codex CLI to 0.150.1 to unhang security review jobs ([#6962](https://github.com/block/buzz/pull/6962)) ([`80177e4c8e97e7bf1f1a3760c4e3503aace22860`](https://github.com/block/buzz/commit/80177e4c8e97e7bf1f1a3760c4e3503aace22860)) +- test(db): use canonical channel roster fixtures ([#6819](https://github.com/block/buzz/pull/6819)) ([`57216c942f171db305135bcb6a4ede2d87e0be8a`](https://github.com/block/buzz/commit/57216c942f171db305135bcb6a4ede2d87e0be8a)) +- fix(cli): enrich template cardinality error with per-candidate presence and profile hints ([#4825](https://github.com/block/buzz/pull/4825)) ([`0808ab485c39c3c12ef02af2188c65a5145eb99d`](https://github.com/block/buzz/commit/0808ab485c39c3c12ef02af2188c65a5145eb99d)) +- Fix Codex security review authorization ([#6913](https://github.com/block/buzz/pull/6913)) ([`745ff6066c92372ea1ee6a5fe05862cdd9b81303`](https://github.com/block/buzz/commit/745ff6066c92372ea1ee6a5fe05862cdd9b81303)) +- fix(db): disable heartbeat vacuum truncation ([#6898](https://github.com/block/buzz/pull/6898)) ([`0ccf934b88f610f5f235862ecd51e2dcbae2cb74`](https://github.com/block/buzz/commit/0ccf934b88f610f5f235862ecd51e2dcbae2cb74)) +- chore(deps): update rui314/setup-mold digest to 7e4f20a ([#6663](https://github.com/block/buzz/pull/6663)) ([`c363ce13c07cb454d6fa92b96d65cb52322c13e9`](https://github.com/block/buzz/commit/c363ce13c07cb454d6fa92b96d65cb52322c13e9)) +- chore(deps): update dependency vitest to v4.1.11 ([#6667](https://github.com/block/buzz/pull/6667)) ([`525007af4b2f644ce07fab92ef4863c46cbae8a3`](https://github.com/block/buzz/commit/525007af4b2f644ce07fab92ef4863c46cbae8a3)) +- chore(deps): update dependency @tanstack/react-virtual to v3.14.10 ([#6666](https://github.com/block/buzz/pull/6666)) ([`30596d3addf69a6954d034ce28f886539604f2c8`](https://github.com/block/buzz/commit/30596d3addf69a6954d034ce28f886539604f2c8)) +- chore(deps): update ubuntu:24.04 docker digest to 33ceb71 ([#6664](https://github.com/block/buzz/pull/6664)) ([`82e748085e3f06b8e297387b33f7615a6db23501`](https://github.com/block/buzz/commit/82e748085e3f06b8e297387b33f7615a6db23501)) +- fix(db): exclude kind:30179 ciphertext from brownfield FTS ([#6822](https://github.com/block/buzz/pull/6822)) ([`b3baa56ba83d01a0b7292d81aae9370f5616c62b`](https://github.com/block/buzz/commit/b3baa56ba83d01a0b7292d81aae9370f5616c62b)) +- Add gated security reviews ([#6816](https://github.com/block/buzz/pull/6816)) ([`cdab765748ddfeba10830a9a5331b6157bd321df`](https://github.com/block/buzz/commit/cdab765748ddfeba10830a9a5331b6157bd321df)) +- Add Buzz benchmark evaluation layers ([#6823](https://github.com/block/buzz/pull/6823)) ([`79df468255b50f6aa7bd9cb19a622a4a37b88dac`](https://github.com/block/buzz/commit/79df468255b50f6aa7bd9cb19a622a4a37b88dac)) +- Deduplicate ACP thread prompt context ([#6706](https://github.com/block/buzz/pull/6706)) ([`8f3566ad9ebbd225e53ce66a7072ceee074eb25a`](https://github.com/block/buzz/commit/8f3566ad9ebbd225e53ce66a7072ceee074eb25a)) +- refactor(db): finish replaceable event store extraction ([#6777](https://github.com/block/buzz/pull/6777)) ([`ef0d2025683869418e8eee22ac5b5ac16c5198b7`](https://github.com/block/buzz/commit/ef0d2025683869418e8eee22ac5b5ac16c5198b7)) +- Fix Admin feedback filter overflow ([#6825](https://github.com/block/buzz/pull/6825)) ([`dcee330b5ca984de8657a6d8cf36e34e1d825d4a`](https://github.com/block/buzz/commit/dcee330b5ca984de8657a6d8cf36e34e1d825d4a)) + +[Compare desktop-v0.5.20...desktop-v0.5.21](https://github.com/block/buzz/compare/desktop-v0.5.20...desktop-v0.5.21) + ## v0.5.20 ### Desktop and shared changes diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 00000000000..c9f74be0dff --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,53 @@ +# Buzz domain language + +Shared terminology for Buzz product behavior. This glossary currently covers mobile [push suppression](#push-suppression); it is not a complete model of Buzz. + +## Notifications + +### Mobile push notification + +A notification directed to a user's mobile installation through the platform's push service. + +### Push suppression + +Withholding an otherwise eligible [mobile push notification](#mobile-push-notification) based on [desktop activity](#desktop-activity) and a working connection to the relevant community. It does not depend on whether desktop alerts can be shown. + +_Avoid_: Read receipt, mark as read, mute + +### Desktop activity + +User interaction with the computer running Buzz, including interaction with another application. It is the interaction itself, not a state that lasts afterward, and does not imply that a particular Buzz message was displayed or read. + +_Avoid_: Message visibility, read activity + +### In-app activity + +User interaction inside Buzz. Recent in-app activity remains evidence of [desktop activity](#desktop-activity) after Buzz loses focus; current window focus is a separate condition. + +### Desktop inactivity + +The state reached when the duration specified in the spec has elapsed since the last observed [desktop activity](#desktop-activity). + +### Additional notification delay + +A waiting period after [desktop inactivity](#desktop-inactivity) begins before [mobile push notifications](#mobile-push-notification) resume. This is distinct from the inactivity threshold itself. + +### Suppressed message + +A message whose otherwise eligible [mobile push notification](#mobile-push-notification) was withheld. The term refers to its notification, not withholding the message itself, and says nothing about whether the message has been read. + +### Suppression activity signal + +Information communicated for deciding whether [desktop activity](#desktop-activity) warrants [push suppression](#push-suppression). It is distinct from [visible presence](#visible-presence) and is not a read receipt. + +### Visible presence + +The availability status shown to other members, such as online, away, or offline. A chosen visible presence status does not necessarily reflect actual [desktop activity](#desktop-activity). + +### Suppression renewal + +A [suppression activity signal](#suppression-activity-signal) that extends how long [push suppression](#push-suppression) applies based on activity on one desktop. + +### Inactivity cutoff + +The time of the last observed [desktop activity](#desktop-activity) plus the duration specified in the spec, when [desktop inactivity](#desktop-inactivity) begins. New desktop activity moves this cutoff forward. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0247b570a23..c761fab9c14 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,6 +84,7 @@ We review as capacity allows — focused PRs that follow this guide move fastest | Node.js | 24+ | Required for desktop app commands and `just ci` | | pnpm | 10+ | Required for desktop app commands and `just ci` | | Flutter | 3.41+ | Required for mobile app — install via [flutter.dev](https://docs.flutter.dev/get-started/install) | +| Xcode | 27.0 recommended; 26 supported | Required for iOS builds; see [iOS toolchain setup](mobile/README.md#ios-toolchain) | | Docker | 24+ | For Postgres, Redis, MinIO | | `just` | latest | Task runner — `cargo install just` | | `lefthook` | 2.1.3 (Hermit-pinned) | Auto-installed by `just hooks` — no manual install needed | @@ -215,6 +216,64 @@ connections, NIP-42 auth, event ingestion, search indexing, and workflow execution. `just test` starts Docker services automatically if they're not already running. +### PostgreSQL-backed tests + +PostgreSQL-backed tests run in a dedicated nextest lane. Mark them ignored with +a PostgreSQL reason and place them in a module whose name ends in +`postgres_tests`. Standalone integration-test targets use a `postgres_` +filename prefix instead. Tests that also require infrastructure beyond +PostgreSQL and Redis live under an `external_infra*_tests` module and are +excluded without changing their descriptive function names. + +See the [buzz-db testing guide](crates/buzz-db/TESTING.md) for the crate-level +checklist. + +`scripts/test-postgres-test-discovery.sh` enforces the convention across every +Rust source file. It fails CI when an ignored PostgreSQL test would be omitted, +or when a Redis-only or hybrid test is accidentally included, so module or file +renames cannot silently change lane membership. The archive and runner derive +their Cargo package set from the same markers, so a database test in a new crate +does not require a separate package-list update. + +The `postgres-ci` nextest profile creates one database per test process, so +destructive and concurrent tests must use the database URL supplied through +`BUZZ_TEST_DATABASE_URL`, `TEST_DATABASE_URL`, or `DATABASE_URL`; do not +hard-code the shared development database. Ordinary tests receive the committed +desired-state schema from `schema/schema.sql`. Tests under +`migration::postgres_tests` receive an empty database and own the embedded +migration lifecycle. A test outside that module whose behavior intentionally +depends on migration-created triggers or seed rows uses a +`migration_schema_` function-name prefix and also receives an empty database +with `BUZZ_TEST_SCHEMA_MODE=migration`. Test helpers that normally call the +migrator honor `BUZZ_TEST_SCHEMA_MODE=desired` so the desired-state contract is +not re-migrated. + +Tests that inspect cluster-wide PostgreSQL state or open least-privilege +sessions use a `cluster_global_` function-name segment; migration-backed cases +use `migration_schema_cluster_global_`. Nextest serializes this small group +while the database-isolated remainder stays parallel. + +The setup process requires a PostgreSQL role that can create and drop databases +and owns the databases it creates; the harness itself does not require +superuser access. The complete inventory includes privilege-boundary tests that +create temporary roles and inspect all sessions, so grant that role +`CREATEROLE` and membership in `pg_read_all_stats` (or use an ephemeral +superuser, as CI does). +Set `BUZZ_POSTGRES_ADMIN_URL` to that role's maintenance database, and set +`PGHOST`, `PGPORT`, `PGUSER`, and `PGPASSWORD` for the desired-state +schema bootstrap. PostgreSQL client tools are resolved from `PATH` unless +`PG_BIN_DIR` is set. Tests that use Redis read `REDIS_URL`. + +With native PostgreSQL and Redis running, the complete lane is below. The +runner bounds compilation to the packages discovered from the current source +tree and removes the run-scoped desired-state source database on exit. +Per-test and source-database cleanup retries transient PostgreSQL disconnect +races and emits a warning if all five attempts fail. + +```bash +./scripts/postgres-test-run.sh +``` + ### End-to-End Tests End-to-end tests live in `crates/buzz-test-client/tests/`: diff --git a/Cargo.lock b/Cargo.lock index 07b79aba44b..e67088890df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,6 +18,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.2", +] + [[package]] name = "aes" version = "0.8.4" @@ -25,19 +35,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if 1.0.4", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", ] +[[package]] +name = "aes" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.0", +] + [[package]] name = "aes-gcm" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" dependencies = [ - "aead", - "aes", - "cipher", + "aead 0.5.2", + "aes 0.8.4", + "cipher 0.4.4", "ctr", "ghash", "subtle", @@ -138,18 +159,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] -name = "appattest" -version = "0.1.1" +name = "apple-native-keyring-store" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0a66767aaf7d483c556386fb68ca2fba9347684d8bb17a4bd8b755851870f7" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" dependencies = [ - "arrayvec", - "aws-lc-rs", - "base64 0.22.1", - "byteorder", - "minicbor", - "rustls-pki-types", - "rustls-webpki", + "keyring-core", + "log", + "security-framework", ] [[package]] @@ -161,15 +178,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arc-swap" version = "1.9.2" @@ -187,14 +195,14 @@ checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d" [[package]] name = "argon2" -version = "0.5.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" dependencies = [ "base64ct", "blake2", - "cpufeatures 0.2.17", - "password-hash", + "cpufeatures 0.3.0", + "password-hash 0.6.1", ] [[package]] @@ -209,6 +217,45 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror 2.0.18", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -245,6 +292,20 @@ dependencies = [ "tokio", ] +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + [[package]] name = "async-io" version = "2.6.0" @@ -258,7 +319,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.4", + "rustix", "slab", "windows-sys 0.61.2", ] @@ -289,7 +350,7 @@ dependencies = [ "cfg-if 1.0.4", "event-listener", "futures-lite", - "rustix 1.1.4", + "rustix", ] [[package]] @@ -315,7 +376,7 @@ dependencies = [ "cfg-if 1.0.4", "futures-core", "futures-io", - "rustix 1.1.4", + "rustix", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -517,7 +578,7 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-tungstenite 0.29.0", - "tower", + "tower 0.5.3", "tower-layer", "tower-service", "tracing", @@ -564,6 +625,12 @@ dependencies = [ "tokio", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base16ct" version = "1.0.0" @@ -582,6 +649,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -647,6 +720,15 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + [[package]] name = "bitcoin-consensus-encoding" version = "1.1.0" @@ -708,11 +790,11 @@ dependencies = [ [[package]] name = "blake2" -version = "0.10.6" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" dependencies = [ - "digest 0.10.7", + "digest 0.11.3", ] [[package]] @@ -756,6 +838,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -809,6 +900,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bstr" version = "1.12.1" @@ -831,6 +931,7 @@ name = "buzz-acp" version = "0.1.0" dependencies = [ "anyhow", + "axum", "base64 0.22.1", "buzz-core", "buzz-persona", @@ -841,6 +942,8 @@ dependencies = [ "evalexpr", "fs4", "futures-util", + "git-credential-nostr", + "git-sign-nostr", "hex", "httparse", "nix 0.31.3", @@ -850,15 +953,17 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.18", "tokio", "tokio-tungstenite 0.29.0", "tokio-util", - "toml 1.1.2+spec-1.1.0", + "toml", "tracing", "tracing-subscriber", "url", "uuid", + "zeroize", ] [[package]] @@ -880,6 +985,7 @@ dependencies = [ "hex", "nostr 0.44.7", "rustls", + "serde", "serde_json", "sqlx", "tokio", @@ -897,17 +1003,20 @@ dependencies = [ "axum", "base64 0.22.1", "dirs", + "fs2", "getrandom 0.4.3", "hex", "nix 0.31.3", + "rcgen", "reqwest 0.13.4", - "rmcp", + "rmcp 1.8.0", "serde", "serde_json", "serde_yaml", "sha2 0.11.0", "tempfile", "tokio", + "tokio-rustls", "tracing", "tracing-subscriber", "url", @@ -915,14 +1024,26 @@ dependencies = [ "webbrowser", ] +[[package]] +name = "buzz-audio-client" +version = "0.1.0" +dependencies = [ + "futures-util", + "neteq", + "opus", + "serde_json", + "tokio", + "tokio-tungstenite 0.29.0", +] + [[package]] name = "buzz-audit" version = "0.1.0" dependencies = [ "buzz-core", "buzz-datastore-tracing", + "buzz-db", "chrono", - "futures-util", "hex", "metrics", "serde", @@ -942,10 +1063,13 @@ dependencies = [ "base64 0.22.1", "buzz-core", "chrono", + "dashmap", + "futures-util", "hex", "jsonwebtoken", "nostr 0.44.7", "rand 0.10.1", + "reqwest 0.13.4", "serde", "serde_json", "sha2 0.11.0", @@ -986,7 +1110,7 @@ dependencies = [ "serde_json", "sha2 0.11.0", "tokio", - "tower", + "tower 0.5.3", ] [[package]] @@ -1060,8 +1184,8 @@ version = "0.1.0" dependencies = [ "metrics", "metrics-util", - "opentelemetry 0.32.0", - "opentelemetry_sdk 0.32.1", + "opentelemetry", + "opentelemetry_sdk", "proc-macro2", "quote", "syn 2.0.117", @@ -1080,6 +1204,7 @@ dependencies = [ "buzz-datastore-tracing", "chrono", "ed25519-dalek", + "futures-util", "hex", "metrics", "metrics-util", @@ -1091,6 +1216,7 @@ dependencies = [ "sqlx", "thiserror 2.0.18", "tokio", + "tokio-util", "tracing", "uuid", ] @@ -1125,16 +1251,14 @@ dependencies = [ "base64 0.22.1", "buzz-cli", "buzz-core", - "git-credential-nostr", - "git-sign-nostr", "ignore", "image", "nix 0.31.3", "nostr 0.44.7", "reqwest 0.13.4", - "rmcp", + "rmcp 3.4.1", "rustls", - "schemars", + "schemars 1.2.1", "serde", "serde_json", "similar", @@ -1144,7 +1268,19 @@ dependencies = [ "tracing", "tracing-subscriber", "windows-sys 0.61.2", - "zeroize", +] + +[[package]] +name = "buzz-feature-flags" +version = "0.1.0" +dependencies = [ + "buzz-core", + "http", + "launchdarkly-server-sdk", + "serde_json", + "tempfile", + "thiserror 2.0.18", + "tokio", ] [[package]] @@ -1179,14 +1315,34 @@ dependencies = [ "uuid", ] +[[package]] +name = "buzz-mesh-smoke" +version = "0.1.0" +dependencies = [ + "anyhow", + "buzz-test-client", + "ed25519-dalek", + "hex", + "mesh-llm-host-runtime", + "mesh-llm-sdk", + "nostr 0.44.7", + "reqwest 0.13.4", + "serde_json", + "sha2 0.11.0", + "tokio", + "uuid", +] + [[package]] name = "buzz-pair-relay" version = "0.1.0" dependencies = [ + "buzz-core", "futures-util", "http-body-util", "hyper", "hyper-util", + "nostr 0.44.7", "parking_lot", "secp256k1 0.31.1", "serde_json", @@ -1194,6 +1350,7 @@ dependencies = [ "tokio", "tokio-tungstenite 0.29.0", "tokio-util", + "zeroize", ] [[package]] @@ -1205,6 +1362,7 @@ dependencies = [ "futures-util", "hex", "nostr 0.44.7", + "rustls", "serde_json", "thiserror 2.0.18", "tokio", @@ -1249,12 +1407,12 @@ name = "buzz-push-gateway" version = "0.1.0" dependencies = [ "aes-gcm", - "appattest", "async-trait", + "aws-lc-rs", "axum", "base64 0.22.1", - "byteorder", "chrono", + "ciborium", "getrandom 0.4.3", "hex", "jsonwebtoken", @@ -1262,21 +1420,26 @@ dependencies = [ "metrics-exporter-prometheus", "minicbor", "nostr 0.44.7", + "openssl", + "p256", "proptest", "rand 0.10.1", "reqwest 0.13.4", + "rustls-pki-types", + "rustls-webpki", "serde", "serde_json", "sha2 0.11.0", "sqlx", "thiserror 2.0.18", "tokio", - "tower", + "tower 0.5.3", "tower-http", "tracing", "tracing-subscriber", "url", "uuid", + "x509-parser", ] [[package]] @@ -1301,38 +1464,39 @@ dependencies = [ "buzz-relay-mesh", "buzz-sdk", "buzz-search", - "buzz-test-client", "buzz-workflow", "bytes", "chrono", "dashmap", "deadpool-redis", - "ed25519-dalek", "flate2", "futures", "futures-util", "hex", "hmac 0.13.0", + "http-body", + "http-body-util", "infer", - "mesh-llm-host-runtime", - "mesh-llm-sdk", + "jsonwebtoken", "metrics", "metrics-exporter-prometheus", "metrics-util", "moka", "nostr 0.44.7", - "opentelemetry 0.32.0", - "opentelemetry-otlp 0.32.0", - "opentelemetry_sdk 0.32.1", + "opentelemetry", + "opentelemetry-otlp", + "opentelemetry_sdk", "postcard", "pulldown-cmark", "rand 0.10.1", "redis", "reqwest 0.13.4", + "ring", "rust-s3", "rustls", "serde", "serde_json", + "serde_urlencoded", "serde_yaml", "sha2 0.11.0", "sqlx", @@ -1342,7 +1506,7 @@ dependencies = [ "tokio", "tokio-tungstenite 0.29.0", "tokio-util", - "tower", + "tower 0.5.3", "tower-http", "tracing", "tracing-opentelemetry", @@ -1392,6 +1556,7 @@ version = "0.1.0" dependencies = [ "buzz-core", "buzz-datastore-tracing", + "buzz-db", "metrics", "sqlx", "thiserror 2.0.18", @@ -1553,7 +1718,16 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" dependencies = [ - "cipher", + "cipher 0.4.4", +] + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", ] [[package]] @@ -1599,9 +1773,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" @@ -1610,17 +1784,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" dependencies = [ "cfg-if 1.0.4", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", ] [[package]] name = "chacha20" -version = "0.10.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if 1.0.4", + "cipher 0.5.2", "cpufeatures 0.3.0", "rand_core 0.10.1", ] @@ -1631,13 +1806,25 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" dependencies = [ - "aead", + "aead 0.5.2", "chacha20 0.9.1", - "cipher", - "poly1305", + "cipher 0.4.4", + "poly1305 0.8.0", "zeroize", ] +[[package]] +name = "chacha20poly1305" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb" +dependencies = [ + "aead 0.6.1", + "chacha20 0.10.2", + "cipher 0.5.2", + "poly1305 0.9.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -1652,6 +1839,39 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "cidr" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579504560394e388085d0c080ea587dfa5c15f7e251b4d5247d1e1a61d1d6928" + [[package]] name = "cipher" version = "0.4.4" @@ -1659,10 +1879,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common 0.1.7", - "inout", + "inout 0.1.4", "zeroize", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.0", + "crypto-common 0.2.2", + "inout 0.2.2", +] + [[package]] name = "clap" version = "4.6.6" @@ -1828,6 +2059,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -1943,6 +2180,12 @@ dependencies = [ "futures-io", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -2046,22 +2289,6 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" -[[package]] -name = "crossterm" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" -dependencies = [ - "bitflags 2.13.0", - "crossterm_winapi", - "mio", - "parking_lot", - "rustix 0.38.44", - "signal-hook", - "signal-hook-mio", - "winapi", -] - [[package]] name = "crossterm" version = "0.29.0" @@ -2074,7 +2301,7 @@ dependencies = [ "document-features", "mio", "parking_lot", - "rustix 1.1.4", + "rustix", "signal-hook", "signal-hook-mio", "winapi", @@ -2096,7 +2323,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] -name = "crypto-common" +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" @@ -2112,7 +2351,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -2121,7 +2362,7 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16182b4f39a82ec8a6851155cc4c0cda3065bb1db33651726a29e1951de0f009" dependencies = [ - "aead", + "aead 0.5.2", "crypto_secretbox", "curve25519-dalek 4.1.3", "salsa20", @@ -2135,10 +2376,10 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1" dependencies = [ - "aead", - "cipher", + "aead 0.5.2", + "cipher 0.4.4", "generic-array", - "poly1305", + "poly1305 0.8.0", "salsa20", "subtle", "zeroize", @@ -2170,7 +2411,7 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "cipher", + "cipher 0.4.4", ] [[package]] @@ -2199,9 +2440,9 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "5.0.0-rc.0" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f359e08ca85e7bd759e1fd933ff2bccd81864c60a8fba0e259c7f822b0924bf" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" dependencies = [ "cfg-if 1.0.4", "cpufeatures 0.3.0", @@ -2246,6 +2487,16 @@ dependencies = [ "darling_macro 0.23.0", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", +] + [[package]] name = "darling_core" version = "0.20.11" @@ -2273,6 +2524,19 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.3", +] + [[package]] name = "darling_macro" version = "0.20.11" @@ -2295,6 +2559,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.3", +] + [[package]] name = "dary_heap" version = "0.3.9" @@ -2344,36 +2619,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "dbus" -version = "0.9.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b942602992bb7acfd1f51c49811c58a610ef9181b6e66f3e519d79b540a3bf73" -dependencies = [ - "libc", - "libdbus-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "dbus-secret-service" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" -dependencies = [ - "aes", - "block-padding", - "cbc", - "dbus", - "fastrand", - "hkdf 0.12.4", - "num", - "once_cell", - "openssl", - "sha2 0.10.9", - "zeroize", -] - [[package]] name = "deadpool" version = "0.13.0" @@ -2404,6 +2649,37 @@ dependencies = [ "tokio", ] +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror 2.0.18", +] + [[package]] name = "deltae" version = "0.3.2" @@ -2412,34 +2688,48 @@ checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4" [[package]] name = "der" -version = "0.8.0" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71fd89660b2dc699704064e59e9dba0147b903e85319429e131620d022be411b" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", - "pem-rfc7468", + "const-oid 0.9.6", + "pem-rfc7468 0.7.0", "zeroize", ] [[package]] -name = "deranged" -version = "0.5.8" +name = "der" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" dependencies = [ - "powerfmt", - "serde_core", + "const-oid 0.10.2", + "pem-rfc7468 1.0.0", + "zeroize", ] [[package]] -name = "derive_arbitrary" -version = "1.4.2" +name = "der-parser" +version = "10.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", + "serde_core", ] [[package]] @@ -2518,6 +2808,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -2529,7 +2820,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.0", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", ] @@ -2625,24 +2916,38 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der 0.7.10", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature 2.2.0", + "spki 0.7.3", +] + [[package]] name = "ed25519" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" dependencies = [ - "pkcs8", + "pkcs8 0.11.0", "serdect", "signature 3.0.0", ] [[package]] name = "ed25519-dalek" -version = "3.0.0-rc.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b011170fe4f04665565b4110afef66774fe9ffff278f3eb5b81cc73d26e27d60" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ - "curve25519-dalek 5.0.0-rc.0", + "curve25519-dalek 5.0.0", "ed25519", "rand_core 0.10.1", "serde", @@ -2661,6 +2966,26 @@ dependencies = [ "serde", ] +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct 0.2.0", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "pem-rfc7468 0.7.0", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "embedded-io" version = "0.4.0" @@ -2794,6 +3119,23 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "eventsource-client" +version = "0.17.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96df8cfa11d3c8e4e1a48b81c9c600ecbe8c11d1326f41e1524cc4d42f7bf6d9" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures", + "http", + "launchdarkly-sdk-transport", + "log", + "pin-project", + "rand 0.10.1", + "tokio", +] + [[package]] name = "evmap" version = "11.0.0" @@ -2811,6 +3153,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fancy-regex" version = "0.11.0" @@ -2863,6 +3217,16 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -2928,17 +3292,7 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", "miniz_oxide", -] - -[[package]] -name = "flume" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" -dependencies = [ - "futures-core", - "futures-sink", - "spin 0.9.9", + "zlib-rs", ] [[package]] @@ -2994,13 +3348,23 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "fs4" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" dependencies = [ - "rustix 1.1.4", + "rustix", "windows-sys 0.61.2", ] @@ -3297,6 +3661,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "h2" version = "0.4.16" @@ -3309,13 +3684,24 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap", + "indexmap 2.14.0", "slab", "tokio", "tokio-util", "tracing", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if 1.0.4", + "crunchy", + "zerocopy", +] + [[package]] name = "hash32" version = "0.3.1" @@ -3331,6 +3717,12 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7040a10f52cba493ddb09926e15d10a9d8a28043708a405931fe4c6f19fac064" +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.14.5" @@ -3355,6 +3747,8 @@ dependencies = [ "allocator-api2", "equivalent", "foldhash 0.2.0", + "serde", + "serde_core", ] [[package]] @@ -3377,6 +3771,30 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "headers" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" +dependencies = [ + "base64 0.22.1", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1 0.10.6", +] + +[[package]] +name = "headers-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" +dependencies = [ + "http", +] + [[package]] name = "heapify" version = "0.2.0" @@ -3531,15 +3949,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "hkdf" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" -dependencies = [ - "hmac 0.12.1", -] - [[package]] name = "hkdf" version = "0.13.0" @@ -3664,6 +4073,25 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-http-proxy" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd1d471ea2f65ba45eddb1d6ab7d58ac2671d2d4ac14da5c6516ae1d97e1327a" +dependencies = [ + "bytes", + "futures-util", + "headers", + "http", + "hyper", + "hyper-rustls", + "hyper-util", + "pin-project-lite", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "hyper-rustls" version = "0.27.9" @@ -3695,22 +4123,6 @@ dependencies = [ "tower-service", ] -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - [[package]] name = "hyper-util" version = "0.1.20" @@ -3885,6 +4297,13 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ifc-core" +version = "0.1.0" +dependencies = [ + "proptest", +] + [[package]] name = "igd-next" version = "0.17.0" @@ -3955,6 +4374,17 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.14.0" @@ -3963,6 +4393,8 @@ checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -3989,10 +4421,20 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ - "block-padding", + "block-padding 0.3.3", "generic-array", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "block-padding 0.4.2", + "hybrid-array", +] + [[package]] name = "instability" version = "0.3.12" @@ -4042,9 +4484,9 @@ dependencies = [ [[package]] name = "iroh" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fca9b4b462c343ff88fc0af4096c186f939b602a0bc08723536ef2c31c93971" +checksum = "460de6bc52163b41b1646931f2897e5ab986f0966ade444467fec25024751a72" dependencies = [ "backon", "blake3", @@ -4093,11 +4535,11 @@ dependencies = [ [[package]] name = "iroh-base" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830a582cd54410dc1aa71d4786a82c3297d7b0165accd8b6dbbb3b240b48140d" +checksum = "6be73e16ee21c923aca9b3121aaa0db936f7c7ecc156ff47b8dac944c68d59a8" dependencies = [ - "curve25519-dalek 5.0.0-rc.0", + "curve25519-dalek 5.0.0", "data-encoding", "data-encoding-macro", "derive_more", @@ -4112,9 +4554,9 @@ dependencies = [ [[package]] name = "iroh-dns" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "516e4eedc38e33ab69a6bd325520332dc3d67b25454e2d590ebb84a25240dd9a" +checksum = "46f6a9b39d18e6345f5c151afd299f2488e2cb5c520fe41b107b6bd3dc4c3349" dependencies = [ "arc-swap", "cfg_aliases", @@ -4163,9 +4605,9 @@ dependencies = [ [[package]] name = "iroh-relay" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8149bb6a57126225a07d6928846d82dcedfd24ea0f863ef7b2eb475e1d726354" +checksum = "24bd586cf927f7b700f56ec3639b53cb5fa901ce284784051ff71092bfbf8193" dependencies = [ "blake3", "bytes", @@ -4181,7 +4623,7 @@ dependencies = [ "iroh-base", "iroh-dns", "iroh-metrics", - "lru", + "lru 0.18.0", "n0-error", "n0-future", "noq", @@ -4202,7 +4644,6 @@ dependencies = [ "tokio-websockets", "tracing", "url", - "vergen-gitcl", "webpki-roots 1.0.7", "ws_stream_wasm", ] @@ -4237,6 +4678,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jni" version = "0.21.1" @@ -4333,16 +4828,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "json5" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "733a844dbd6fef128e98cb4487b887cb55454d92cd9994b1bafe004fabbe670c" -dependencies = [ - "serde", - "ucd-trie", -] - [[package]] name = "jsonpath-rust" version = "0.7.5" @@ -4399,19 +4884,23 @@ dependencies = [ [[package]] name = "keyring" -version = "3.6.3" +version = "4.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb1e621458ca9c51aa110bd0339d4751a056b9576bf1253aee1aa560dda0fc9d" dependencies = [ - "byteorder", - "dbus-secret-service", "log", - "openssl", - "secret-service", - "security-framework 2.11.1", - "security-framework 3.7.0", - "windows-sys 0.60.2", - "zeroize", ] [[package]] @@ -4473,7 +4962,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-util", - "tower", + "tower 0.5.3", "tower-http", "tracing", ] @@ -4501,6 +4990,77 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f" +[[package]] +name = "launchdarkly-sdk-transport" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "032d66802c461d7254ed1de887be6ca98ebbe126867d9a60c754baae81c4d10d" +dependencies = [ + "bytes", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-http-proxy", + "hyper-rustls", + "hyper-timeout", + "hyper-util", + "log", + "no-proxy", + "tower 0.4.13", +] + +[[package]] +name = "launchdarkly-server-sdk" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22259877ec581fa56a9f0b982e583e16fa01b71ba6d3f786ef5ccfc6ca6f92ff" +dependencies = [ + "aws-lc-rs", + "bitflags 2.13.0", + "bytes", + "chrono", + "crossbeam-channel", + "data-encoding", + "eventsource-client", + "flate2", + "futures", + "http", + "launchdarkly-sdk-transport", + "launchdarkly-server-sdk-evaluation", + "log", + "lru 0.16.4", + "moka", + "parking_lot", + "rand 0.9.4", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "uuid", +] + +[[package]] +name = "launchdarkly-server-sdk-evaluation" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76560a130b2a7e7fdb9c56043168844cde483e08e7f0e4a5e178e3888edc4336" +dependencies = [ + "base16ct 0.2.0", + "chrono", + "itertools 0.14.0", + "lazy_static", + "log", + "maplit", + "regex", + "semver", + "serde", + "serde_json", + "serde_with", + "sha1 0.10.6", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -4520,25 +5080,15 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.186" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" - -[[package]] -name = "libdbus-sys" -version = "0.2.7" +version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" -dependencies = [ - "cc", - "pkg-config", -] +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] name = "libloading" -version = "0.8.9" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" dependencies = [ "cfg-if 1.0.4", "windows-link 0.2.1", @@ -4561,10 +5111,11 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.30.1" +version = "0.38.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" dependencies = [ + "cc", "pkg-config", "vcpkg", ] @@ -4590,12 +5141,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "348d0075b1fc163b26d72a7f75fc5141daf2fd1bdf128d873cbaf6785d495bdf" -[[package]] -name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -4675,6 +5220,12 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" + [[package]] name = "lru" version = "0.18.0" @@ -4731,6 +5282,12 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" +[[package]] +name = "maplit" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" + [[package]] name = "matchers" version = "0.2.0" @@ -4785,12 +5342,12 @@ checksum = "ae960838283323069879657ca3de837e9f7bbb4c7bf6ea7f1b290d5e9476d2e0" [[package]] name = "mdns-sd" -version = "0.19.2" +version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18148fee27e99e76dbf6e137f27727113d31f766e578d1b93a93c3615fca7081" +checksum = "a63c9b854b5ad0812ac5969f8db92a59f28b45d0a5ae599b9a45b84c5c8a08e8" dependencies = [ "fastrand", - "flume 0.11.1", + "flume", "if-addrs", "log", "mio", @@ -4804,6 +5361,15 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + [[package]] name = "memmem" version = "0.1.1" @@ -4821,8 +5387,8 @@ dependencies = [ [[package]] name = "mesh-llm-api-client" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "hex", "mesh-llm-client", @@ -4831,8 +5397,8 @@ dependencies = [ [[package]] name = "mesh-llm-api-server" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "mesh-llm-api-client", @@ -4842,21 +5408,18 @@ dependencies = [ [[package]] name = "mesh-llm-build-info" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" [[package]] name = "mesh-llm-client" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "async-trait", - "base64 0.22.1", + "base64 0.23.1", "bytes", - "crypto_box", - "ed25519-dalek", - "hex", "httparse", "iroh", "mesh-llm-identity", @@ -4866,11 +5429,9 @@ dependencies = [ "model-artifact", "nostr-sdk", "prost 0.14.3", - "rand 0.10.1", "rustls", "serde", "serde_json", - "sha2 0.10.9", "thiserror 2.0.18", "tokio", "tracing", @@ -4879,24 +5440,25 @@ dependencies = [ [[package]] name = "mesh-llm-config" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "dirs", + "mesh-llm-native-runtime", "mesh-llm-types", "semver", "serde", "skippy-protocol", - "toml 0.9.12+spec-1.1.0", + "toml", "toml_edit", "url", ] [[package]] name = "mesh-llm-embedded-runtime" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "mesh-llm-host-runtime", @@ -4905,20 +5467,25 @@ dependencies = [ [[package]] name = "mesh-llm-events" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", + "chrono", "clap", - "crossterm 0.28.1", + "crossterm", + "libc", "ratatui", + "serde", "serde_json", + "tracing", + "uuid", ] [[package]] name = "mesh-llm-gpu-bench" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "serde", "serde_json", @@ -4927,8 +5494,8 @@ dependencies = [ [[package]] name = "mesh-llm-guardrails" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "serde", "serde_json", @@ -4936,8 +5503,8 @@ dependencies = [ [[package]] name = "mesh-llm-hardware-profile" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "mesh-llm-native-runtime", ] @@ -4973,19 +5540,19 @@ dependencies = [ [[package]] name = "mesh-llm-host-runtime" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "argon2", "async-trait", "axum", - "base64 0.22.1", + "base64 0.23.1", "bytes", - "chacha20poly1305", + "chacha20poly1305 0.11.0", "chrono", "clap", - "crossterm 0.28.1", + "crossterm", "crypto_box", "dirs", "ed25519-dalek", @@ -4996,7 +5563,6 @@ dependencies = [ "http-body-util", "httparse", "iroh", - "json5", "keyring", "libc", "mdns-sd", @@ -5008,6 +5574,7 @@ dependencies = [ "mesh-llm-guardrails", "mesh-llm-hf-hub", "mesh-llm-identity", + "mesh-llm-log-store", "mesh-llm-native-runtime", "mesh-llm-node", "mesh-llm-plugin", @@ -5027,24 +5594,26 @@ dependencies = [ "model-resolver", "nostr-sdk", "openai-frontend", - "opentelemetry 0.31.0", - "opentelemetry-otlp 0.31.1", - "opentelemetry_sdk 0.31.0", + "opentelemetry", + "opentelemetry-otlp", + "opentelemetry_sdk", "prost 0.14.3", "rand 0.10.1", "regex-lite", - "reqwest 0.12.28", - "rmcp", + "reqwest 0.13.4", + "rmcp 3.4.1", "rpassword", "rustls", - "schemars", + "same-file", + "schemars 1.2.1", "semver", "serde", "serde_json", - "serde_yaml", - "sha2 0.10.9", + "sha2 0.11.0", "skippy-coordinator", "skippy-ffi", + "skippy-model", + "skippy-package-format", "skippy-protocol", "skippy-runtime", "skippy-server", @@ -5056,23 +5625,26 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-stream", - "toml 0.9.12+spec-1.1.0", + "toml", "tracing", "tracing-subscriber", "url", "urlencoding", + "uuid", + "windows-sys 0.61.2", "zeroize", "zip", ] [[package]] name = "mesh-llm-identity" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ + "apple-native-keyring-store", "argon2", - "base64 0.22.1", - "chacha20poly1305", + "base64 0.23.1", + "chacha20poly1305 0.11.0", "chrono", "crypto_box", "dirs", @@ -5082,26 +5654,45 @@ dependencies = [ "rand 0.10.1", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "thiserror 2.0.18", "zeroize", ] +[[package]] +name = "mesh-llm-log-store" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" +dependencies = [ + "chrono", + "data-encoding", + "hex", + "mesh-llm-events", + "rusqlite", + "serde", + "serde_json", + "sha2 0.11.0", + "thiserror 2.0.18", + "uuid", + "windows-sys 0.61.2", +] + [[package]] name = "mesh-llm-native-runtime" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", + "hex", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", ] [[package]] name = "mesh-llm-node" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "mesh-llm-types", @@ -5114,16 +5705,16 @@ dependencies = [ [[package]] name = "mesh-llm-plugin" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "async-trait", "prost 0.14.3", "prost-build 0.14.3", "protoc-bin-vendored", - "rmcp", - "schemars", + "rmcp 3.4.1", + "schemars 1.2.1", "serde", "serde_json", "tokio", @@ -5131,18 +5722,19 @@ dependencies = [ [[package]] name = "mesh-llm-plugin-manager" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "dirs", "flate2", "futures-util", + "hex", "mesh-llm-skills", - "reqwest 0.12.28", + "reqwest 0.13.4", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "tar", "tempfile", "zip", @@ -5150,38 +5742,41 @@ dependencies = [ [[package]] name = "mesh-llm-protocol" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "hex", "iroh", "prost 0.14.3", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", ] [[package]] name = "mesh-llm-release-footer" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "hex", - "sha2 0.10.9", + "sha2 0.11.0", ] [[package]] name = "mesh-llm-routing" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ + "blake3", "iroh", + "serde", + "serde_json", ] [[package]] name = "mesh-llm-runtime-install" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "dirs", @@ -5191,10 +5786,10 @@ dependencies = [ "mesh-llm-build-info", "mesh-llm-hardware-profile", "mesh-llm-native-runtime", - "reqwest 0.12.28", + "reqwest 0.13.4", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "skippy-ffi", "tar", "tempfile", @@ -5203,23 +5798,23 @@ dependencies = [ [[package]] name = "mesh-llm-sdk" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "mesh-llm-api-client", "mesh-llm-api-server", "mesh-llm-embedded-runtime", "mesh-llm-runtime-install", - "reqwest 0.12.28", + "reqwest 0.13.4", "serde", "serde_json", ] [[package]] name = "mesh-llm-skills" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "dirs", @@ -5229,8 +5824,8 @@ dependencies = [ [[package]] name = "mesh-llm-system" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "chrono", @@ -5244,11 +5839,11 @@ dependencies = [ "mesh-llm-native-runtime", "mesh-llm-release-footer", "mesh-llm-runtime-install", - "reqwest 0.12.28", + "reqwest 0.13.4", "semver", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "skippy-runtime", "tracing", "zip", @@ -5256,28 +5851,28 @@ dependencies = [ [[package]] name = "mesh-llm-types" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "hex", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", ] [[package]] name = "mesh-llm-ui" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" [[package]] name = "mesh-mixture-of-agents" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "async-trait", "mesh-llm-guardrails", - "reqwest 0.12.28", + "reqwest 0.13.4", "serde", "serde_json", "tokio", @@ -5286,18 +5881,19 @@ dependencies = [ [[package]] name = "mesh-native-serving-plugin-api" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" [[package]] name = "mesh-native-serving-plugin-host" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "libloading", "mesh-native-serving-plugin-api", "skippy-server", + "skippy-tokenizer", ] [[package]] @@ -5322,7 +5918,7 @@ dependencies = [ "hyper", "hyper-rustls", "hyper-util", - "indexmap", + "indexmap 2.14.0", "ipnet", "metrics", "metrics-util", @@ -5343,7 +5939,7 @@ dependencies = [ "crossbeam-epoch", "crossbeam-utils", "hashbrown 0.16.1", - "indexmap", + "indexmap 2.14.0", "metrics", "ordered-float 5.3.0", "quanta", @@ -5397,6 +5993,21 @@ name = "minicbor" version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0452a60c1863c1f50b5f77cd295e8d2786849f35883f0b9e18e7e6e1b5691b0" +dependencies = [ + "half", + "minicbor-derive", +] + +[[package]] +name = "minicbor-derive" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd2209fff77f705b00c737016a48e73733d7fbccb8b007194db148f03561fb70" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "minidom" @@ -5437,8 +6048,8 @@ dependencies = [ [[package]] name = "model-artifact" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "async-trait", @@ -5448,26 +6059,30 @@ dependencies = [ [[package]] name = "model-hf" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "async-trait", "chrono", "dirs", + "hex", + "libc", "mesh-llm-hf-hub", "model-artifact", "model-ref", + "rustls", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "tokio", + "tracing", ] [[package]] name = "model-package" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "bytes", @@ -5476,26 +6091,26 @@ dependencies = [ "mesh-llm-hf-hub", "model-hf", "model-ref", - "reqwest 0.12.28", + "reqwest 0.13.4", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "tempfile", "tokio", ] [[package]] name = "model-ref" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "serde", ] [[package]] name = "model-resolver" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "model-artifact", @@ -5632,23 +6247,6 @@ dependencies = [ "n0-future", ] -[[package]] -name = "native-tls" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework 3.7.0", - "security-framework-sys", - "tempfile", -] - [[package]] name = "ndarray" version = "0.17.2" @@ -5703,6 +6301,19 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "neteq" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57fbe9601485d95750187c92344fa056e75055027b00e375c53d9f4b8b883112" +dependencies = [ + "log", + "ringbuf", + "serde", + "thiserror 1.0.69", + "web-time", +] + [[package]] name = "netlink-packet-core" version = "0.8.1" @@ -5834,6 +6445,15 @@ dependencies = [ "libc", ] +[[package]] +name = "no-proxy" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd3f71e44f009513a82ac2612c0c2da7e2924fad776931164317baa9695e150" +dependencies = [ + "cidr", +] + [[package]] name = "nom" version = "7.1.3" @@ -5846,9 +6466,9 @@ dependencies = [ [[package]] name = "noq" -version = "1.0.1" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bf95190af1bd4a00a10e8255ca0c8ddd9e9a9f5e79151d7a7eb6d56aff5dc89" +checksum = "09e4bb6601fa543c110d8957813267d5a8d775a0f8fbaccf1f615d06ba9b10da" dependencies = [ "bytes", "cfg_aliases", @@ -5868,9 +6488,9 @@ dependencies = [ [[package]] name = "noq-proto" -version = "1.0.1" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa6c890013591e709a3e45dd53501351b7e27e7ff3c7e9fc3dce43e300e7e9d3" +checksum = "baa7b5ccd819a9c68a0d955e67a881032d09b1a17219b1f90b0997a0888e1a15" dependencies = [ "aes-gcm", "aws-lc-rs", @@ -5896,9 +6516,9 @@ dependencies = [ [[package]] name = "noq-udp" -version = "1.0.1" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3137a52df66c20090a889828d1c655f21f52294cba64e5c4fbb04fc83eee7c8e" +checksum = "02bba20e097a5a16cd0ad14ec882fae1e80a092a124e9422fc4dddd92e96a647" dependencies = [ "cfg_aliases", "libc", @@ -5917,9 +6537,9 @@ dependencies = [ "bech32 0.11.1", "bip39", "bitcoin_hashes 0.14.1", - "cbc", + "cbc 0.1.2", "chacha20 0.9.1", - "chacha20poly1305", + "chacha20poly1305 0.10.1", "getrandom 0.2.17", "hex", "instant", @@ -5941,9 +6561,9 @@ dependencies = [ "bech32 0.12.0", "bip39", "bitcoin_hashes 1.2.0", - "cbc", + "cbc 0.1.2", "chacha20 0.9.1", - "chacha20poly1305", + "chacha20poly1305 0.10.1", "faster-hex", "opaquerr", "rand 0.10.1", @@ -5986,7 +6606,7 @@ dependencies = [ "async-wsocket", "faster-hex", "futures", - "lru", + "lru 0.18.0", "negentropy", "nostr 0.45.1", "nostr-database", @@ -6298,6 +6918,15 @@ dependencies = [ "web-time", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -6334,19 +6963,20 @@ checksum = "4f933a4265d5cdad61d19bbdfc972ea5726d56cd8d3d57b8f2d3c365dd42bee9" [[package]] name = "openai-frontend" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "async-trait", "axum", "futures-core", "futures-util", + "mesh-llm-events", "mesh-llm-guardrails", "serde", "serde_json", "tokio", - "tokio-stream", "tracing", + "uuid", ] [[package]] @@ -6382,9 +7012,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] name = "openssl-src" -version = "300.6.0+3.6.2" +version = "300.6.1+3.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8e8cbfd3a4a8c8f089147fd7aaa33cf8c7450c4d09f8f80698a0cf093abeff4" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" dependencies = [ "cc", ] @@ -6402,20 +7032,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "opentelemetry" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b84bcd6ae87133e903af7ef497404dda70c60d0ea14895fc8a5e6722754fc2a0" -dependencies = [ - "futures-core", - "futures-sink", - "js-sys", - "pin-project-lite", - "thiserror 2.0.18", - "tracing", -] - [[package]] name = "opentelemetry" version = "0.32.0" @@ -6431,32 +7047,16 @@ dependencies = [ ] [[package]] -name = "opentelemetry-http" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a6d09a73194e6b66df7c8f1b680f156d916a1a942abf2de06823dd02b7855d" -dependencies = [ - "async-trait", - "bytes", - "http", - "opentelemetry 0.31.0", - "reqwest 0.12.28", -] - -[[package]] -name = "opentelemetry-otlp" -version = "0.31.1" +name = "opentelemetry-http" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f69cd6acbb9af919df949cd1ec9e5e7fdc2ef15d234b6b795aaa525cc02f71f" +checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331" dependencies = [ + "async-trait", + "bytes", "http", - "opentelemetry 0.31.0", - "opentelemetry-http", - "opentelemetry-proto 0.31.0", - "opentelemetry_sdk 0.31.0", - "prost 0.14.3", - "reqwest 0.12.28", - "thiserror 2.0.18", + "opentelemetry", + "reqwest 0.13.4", ] [[package]] @@ -6466,10 +7066,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35" dependencies = [ "http", - "opentelemetry 0.32.0", - "opentelemetry-proto 0.32.0", - "opentelemetry_sdk 0.32.1", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-proto", + "opentelemetry_sdk", "prost 0.14.3", + "reqwest 0.13.4", "thiserror 2.0.18", "tokio", "tonic", @@ -6478,49 +7080,20 @@ dependencies = [ [[package]] name = "opentelemetry-proto" -version = "0.31.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7175df06de5eaee9909d4805a3d07e28bb752c34cab57fa9cff549da596b30f" +checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638" dependencies = [ "base64 0.22.1", "const-hex", - "opentelemetry 0.31.0", - "opentelemetry_sdk 0.31.0", + "opentelemetry", + "opentelemetry_sdk", "prost 0.14.3", "serde", - "serde_json", - "tonic", - "tonic-prost", -] - -[[package]] -name = "opentelemetry-proto" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638" -dependencies = [ - "opentelemetry 0.32.0", - "opentelemetry_sdk 0.32.1", - "prost 0.14.3", "tonic", "tonic-prost", ] -[[package]] -name = "opentelemetry_sdk" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14ae4f5991976fd48df6d843de219ca6d31b01daaab2dad5af2badeded372bd" -dependencies = [ - "futures-channel", - "futures-executor", - "futures-util", - "opentelemetry 0.31.0", - "percent-encoding", - "rand 0.9.4", - "thiserror 2.0.18", -] - [[package]] name = "opentelemetry_sdk" version = "0.32.1" @@ -6530,7 +7103,7 @@ dependencies = [ "futures-channel", "futures-executor", "futures-util", - "opentelemetry 0.32.0", + "opentelemetry", "percent-encoding", "portable-atomic", "rand 0.9.4", @@ -6545,6 +7118,24 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "opus" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33718946cc77d4032911d4efe03a66dbcbfbd2bb16c3da06aaeadcc637c32216" +dependencies = [ + "opusic-sys", +] + +[[package]] +name = "opusic-sys" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9d1ecdf206421bc74343ab3bb2f30ad2abbfee41fa341f7181fecbaf957769a" +dependencies = [ + "cmake", +] + [[package]] name = "ordered-float" version = "2.10.1" @@ -6619,6 +7210,18 @@ dependencies = [ "memchr", ] +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + [[package]] name = "palette" version = "0.7.6" @@ -6693,6 +7296,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "password-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b" +dependencies = [ + "getrandom 0.4.3", + "phc", +] + [[package]] name = "paste" version = "1.0.15" @@ -6731,6 +7344,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "pem-rfc7468" version = "1.0.0" @@ -6795,7 +7417,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" dependencies = [ "fixedbitset 0.5.7", - "indexmap", + "indexmap 2.14.0", ] [[package]] @@ -6806,7 +7428,7 @@ checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset 0.5.7", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.14.0", ] [[package]] @@ -6819,6 +7441,17 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "phc" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892" +dependencies = [ + "base64ct", + "ctutils", + "getrandom 0.4.3", +] + [[package]] name = "phf" version = "0.11.3" @@ -6908,14 +7541,24 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", +] + [[package]] name = "pkcs8" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" dependencies = [ - "der", - "spki", + "der 0.8.2", + "spki 0.8.0", ] [[package]] @@ -6931,7 +7574,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "092791278e026273c1b65bbdcfbba3a300f2994c896bd01ab01da613c29c46f1" dependencies = [ "base64 0.22.1", - "indexmap", + "indexmap 2.14.0", "quick-xml 0.39.4", "serde", "time", @@ -6960,7 +7603,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.4", + "rustix", "windows-sys 0.61.2", ] @@ -6972,7 +7615,17 @@ checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" dependencies = [ "cpufeatures 0.2.17", "opaque-debug", - "universal-hash", + "universal-hash 0.5.1", +] + +[[package]] +name = "poly1305" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" +dependencies = [ + "cpufeatures 0.3.0", + "universal-hash 0.6.1", ] [[package]] @@ -6984,7 +7637,7 @@ dependencies = [ "cfg-if 1.0.4", "cpufeatures 0.2.17", "opaque-debug", - "universal-hash", + "universal-hash 0.5.1", ] [[package]] @@ -7103,6 +7756,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -7128,7 +7790,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e842efad9119158434d193c6682e2ebee4b44d6ad801d7b349623b3f57cdf55" dependencies = [ "futures", - "indexmap", + "indexmap 2.14.0", + "nix 0.31.3", + "tokio", + "tracing", + "windows 0.62.2", +] + +[[package]] +name = "process-wrap" +version = "10.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f21b97672d2dc848e7b25701ab4535618b92f4861c13cc3f7f7bed52ad3c8da" +dependencies = [ + "futures", + "indexmap 2.14.0", "nix 0.31.3", "tokio", "tracing", @@ -7556,7 +8232,7 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ - "chacha20 0.10.0", + "chacha20 0.10.2", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -7669,7 +8345,7 @@ dependencies = [ "hashbrown 0.17.1", "itertools 0.14.0", "kasuari", - "lru", + "lru 0.18.0", "palette", "serde", "strum", @@ -7686,7 +8362,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" dependencies = [ "cfg-if 1.0.4", - "crossterm 0.29.0", + "crossterm", "instability", "ratatui-core", ] @@ -7788,6 +8464,19 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "redb" version = "3.1.3" @@ -7911,22 +8600,16 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", - "encoding_rs", - "futures-channel", "futures-core", "futures-util", - "h2", "http", "http-body", "http-body-util", "hyper", "hyper-rustls", - "hyper-tls", "hyper-util", "js-sys", "log", - "mime", - "native-tls", "percent-encoding", "pin-project-lite", "quinn", @@ -7937,10 +8620,9 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", "tokio-rustls", "tokio-util", - "tower", + "tower 0.5.3", "tower-http", "tower-service", "url", @@ -7960,6 +8642,7 @@ dependencies = [ "base64 0.22.1", "bytes", "encoding_rs", + "futures-channel", "futures-core", "futures-util", "h2", @@ -7986,7 +8669,7 @@ dependencies = [ "tokio", "tokio-rustls", "tokio-util", - "tower", + "tower 0.5.3", "tower-http", "tower-service", "url", @@ -8016,6 +8699,16 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -8030,6 +8723,15 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "ringbuf" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79abed428d1fd2a128201cec72c5f6938e2da607c6f3745f769fabea399d950a" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "rmcp" version = "1.8.0" @@ -8037,20 +8739,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d1f571c72940a19d9532fe52dbea8bc9912bf1d766c2970bb824056b86f3f59" dependencies = [ "async-trait", - "base64 0.22.1", + "chrono", + "futures", + "pin-project-lite", + "process-wrap 9.1.0", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "tokio-util", + "tracing", +] + +[[package]] +name = "rmcp" +version = "3.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b6317cd8c13e3ec9033cf2aa5aa92cd743f0f4f8a93cddc42ea0ae6ce3b8898" +dependencies = [ + "async-trait", + "base64 0.23.1", "bytes", "chrono", "futures", "http", "http-body", "http-body-util", + "indexmap 2.14.0", "pastey", "pin-project-lite", - "process-wrap", + "process-wrap 10.0.1", "rand 0.10.1", "reqwest 0.13.4", "rmcp-macros", - "schemars", + "schemars 1.2.1", "serde", "serde_json", "sse-stream", @@ -8065,25 +8788,49 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "1.8.0" +version = "3.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aad0035b69380782d78ea95b508327e6deaa2235909053e596eea8f27b5e1d5" +checksum = "d2ee366004e5f87c103be91c6c09337811517ae8d2f919ece9da7c21444b85c5" dependencies = [ - "darling 0.23.0", + "darling 0.24.1", "proc-macro2", "quote", "serde_json", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] name = "rpassword" -version = "5.0.1" +version = "7.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffc936cf8a7ea60c58f030fd36a612a48f440610214dc54bc36431f9ea0c3efb" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" dependencies = [ "libc", - "winapi", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "rusqlite" +version = "0.40.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +dependencies = [ + "bitflags 2.13.0", + "fallible-iterator", + "fallible-streaming-iterator", + "libsqlite3-sys", + "smallvec", ] [[package]] @@ -8147,16 +8894,12 @@ dependencies = [ ] [[package]] -name = "rustix" -version = "0.38.44" +name = "rusticata-macros" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" dependencies = [ - "bitflags 2.13.0", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", + "nom", ] [[package]] @@ -8168,7 +8911,7 @@ dependencies = [ "bitflags 2.13.0", "errno", "libc", - "linux-raw-sys 0.12.1", + "linux-raw-sys", "windows-sys 0.61.2", ] @@ -8197,7 +8940,7 @@ dependencies = [ "openssl-probe", "rustls-pki-types", "schannel", - "security-framework 3.7.0", + "security-framework", ] [[package]] @@ -8225,7 +8968,7 @@ dependencies = [ "rustls-native-certs", "rustls-platform-verifier-android", "rustls-webpki", - "security-framework 3.7.0", + "security-framework", "security-framework-sys", "webpki-root-certs", "windows-sys 0.61.2", @@ -8298,13 +9041,26 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3944826ff8fa8093089aba3acb4ef44b9446a99a16f3bf4e74af3f77d340ab7d" +[[package]] +name = "safetensors" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846" +dependencies = [ + "hashbrown 0.16.1", + "libc", + "serde", + "serde_json", + "tempfile", +] + [[package]] name = "salsa20" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" dependencies = [ - "cipher", + "cipher 0.4.4", ] [[package]] @@ -8325,6 +9081,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "schemars" version = "1.2.1" @@ -8369,12 +9137,26 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" dependencies = [ - "password-hash", + "password-hash 0.5.0", "pbkdf2", "salsa20", "sha2 0.10.9", ] +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct 0.2.0", + "der 0.7.10", + "generic-array", + "pkcs8 0.10.2", + "subtle", + "zeroize", +] + [[package]] name = "secp256k1" version = "0.29.1" @@ -8437,36 +9219,23 @@ dependencies = [ [[package]] name = "secret-service" -version = "4.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" dependencies = [ - "aes", - "cbc", + "aes 0.9.3", + "cbc 0.2.1", "futures-util", - "generic-array", - "hkdf 0.12.4", + "getrandom 0.4.3", + "hkdf", + "hybrid-array", "num", "once_cell", - "rand 0.8.6", "serde", - "sha2 0.10.9", + "sha2 0.11.0", "zbus", ] -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags 2.13.0", - "core-foundation 0.9.4", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - [[package]] name = "security-framework" version = "3.7.0" @@ -8641,13 +9410,46 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_with" +version = "3.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee78f1fbe43ac4a0e47aadb3dbd357b69eb0d3793e948624cd03dd2750ab1c0a" +dependencies = [ + "base64 0.22.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.0", + "jiff", + "schemars 0.9.0", + "schemars 1.2.1", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8705578779c2b6bd90d84d66eb2e206b708b1a4d7b9f17641b293545bf1c7e46" +dependencies = [ + "darling 0.23.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "serde_yaml" version = "0.9.34+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ - "indexmap", + "indexmap 2.14.0", "itoa", "ryu", "serde", @@ -8660,7 +9462,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" dependencies = [ - "base16ct", + "base16ct 1.0.0", "serde", ] @@ -8799,6 +9601,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ + "digest 0.10.7", "rand_core 0.6.4", ] @@ -8807,6 +9610,9 @@ name = "signature" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "rand_core 0.10.1", +] [[package]] name = "simd-adler32" @@ -8874,8 +9680,8 @@ checksum = "0c6f73aeb92d671e0cc4dca167e59b2deb6387c375391bc99ee743f326994a2b" [[package]] name = "skippy-cache" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", "blake3", @@ -8884,29 +9690,53 @@ dependencies = [ [[package]] name = "skippy-coordinator" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "thiserror 2.0.18", ] [[package]] name = "skippy-ffi" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "libloading", ] [[package]] name = "skippy-metrics" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" + +[[package]] +name = "skippy-model" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" +dependencies = [ + "anyhow", + "clap", + "memmap2", + "safetensors", + "serde", + "serde_json", + "skippy-package-format", +] + +[[package]] +name = "skippy-package-format" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" +dependencies = [ + "serde", + "serde_json", + "sha2 0.11.0", +] [[package]] name = "skippy-protocol" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "prost 0.14.3", "prost-build 0.14.3", @@ -8917,62 +9747,78 @@ dependencies = [ [[package]] name = "skippy-runtime" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "anyhow", + "hex", "libc", + "model-ref", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "skippy-ffi", + "skippy-model", "tokio", ] +[[package]] +name = "skippy-scheduler" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" +dependencies = [ + "skippy-runtime", + "thiserror 2.0.18", +] + [[package]] name = "skippy-server" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "ahash", "anyhow", "async-trait", "axum", - "base64 0.22.1", + "base64 0.23.1", "blake3", "clap", "futures-util", "libc", + "mesh-llm-events", "mesh-native-serving-plugin-api", "model-artifact", "openai-frontend", - "opentelemetry-proto 0.31.0", + "opentelemetry-proto", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "skippy-cache", "skippy-metrics", "skippy-protocol", "skippy-runtime", + "skippy-scheduler", "skippy-tokenizer", + "skippy-topology", "socket2", "tokio", - "tokio-stream", "tonic", + "tracing", + "uuid", ] [[package]] name = "skippy-tokenizer" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "serde", ] [[package]] name = "skippy-topology" -version = "0.75.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.75.1#3295c902d4c4f859aaadf9240042ffdaf06dd07e" +version = "0.76.2" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.76.2#a0c1e66b0ac037dd56544b9e2d94969ea43d694f" dependencies = [ "serde", "serde_json", @@ -8995,13 +9841,13 @@ dependencies = [ [[package]] name = "socket-pktinfo" -version = "0.3.2" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927136cc2ae6a1b0e66ac6b1210902b75c3f726db004a73bc18686dcd0dcd22f" +checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac" dependencies = [ "libc", "socket2", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -9046,6 +9892,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + [[package]] name = "spki" version = "0.8.0" @@ -9053,7 +9909,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" dependencies = [ "base64ct", - "der", + "der 0.8.2", ] [[package]] @@ -9083,7 +9939,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71" dependencies = [ - "sqlx-core", + "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "sqlx-macros", "sqlx-mysql", "sqlx-postgres", @@ -9110,7 +9966,7 @@ dependencies = [ "futures-util", "hashbrown 0.16.1", "hashlink", - "indexmap", + "indexmap 2.14.0", "log", "memchr", "percent-encoding", @@ -9128,6 +9984,39 @@ dependencies = [ "webpki-roots 1.0.7", ] +[[package]] +name = "sqlx-core" +version = "0.9.0" +source = "git+https://github.com/launchbadge/sqlx?rev=94aafe3a68884d923b0798a767c8d7f6cfda89d2#94aafe3a68884d923b0798a767c8d7f6cfda89d2" +dependencies = [ + "base64 0.22.1", + "bytes", + "cfg-if 1.0.4", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.16.1", + "hashlink", + "indexmap 2.14.0", + "log", + "memchr", + "percent-encoding", + "serde", + "serde_json", + "sha2 0.11.0", + "smallvec", + "thiserror 2.0.18", + "tracing", + "url", + "uuid", +] + [[package]] name = "sqlx-macros" version = "0.9.0" @@ -9136,7 +10025,7 @@ checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf" dependencies = [ "proc-macro2", "quote", - "sqlx-core", + "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "sqlx-macros-core", "syn 2.0.117", ] @@ -9157,7 +10046,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", - "sqlx-core", + "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "sqlx-mysql", "sqlx-postgres", "sqlx-sqlite", @@ -9189,7 +10078,7 @@ dependencies = [ "serde", "sha1 0.11.0", "sha2 0.11.0", - "sqlx-core", + "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "thiserror 2.0.18", "tracing", "uuid", @@ -9213,7 +10102,7 @@ dependencies = [ "futures-core", "futures-util", "hex", - "hkdf 0.13.0", + "hkdf", "hmac 0.13.0", "itoa", "log", @@ -9224,7 +10113,7 @@ dependencies = [ "serde_json", "sha2 0.11.0", "smallvec", - "sqlx-core", + "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "stringprep", "thiserror 2.0.18", "tracing", @@ -9235,12 +10124,11 @@ dependencies = [ [[package]] name = "sqlx-sqlite" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c" +source = "git+https://github.com/launchbadge/sqlx?rev=94aafe3a68884d923b0798a767c8d7f6cfda89d2#94aafe3a68884d923b0798a767c8d7f6cfda89d2" dependencies = [ "atoi", "chrono", - "flume 0.12.0", + "flume", "form_urlencoded", "futures-channel", "futures-core", @@ -9251,7 +10139,7 @@ dependencies = [ "log", "percent-encoding", "serde", - "sqlx-core", + "sqlx-core 0.9.0 (git+https://github.com/launchbadge/sqlx?rev=94aafe3a68884d923b0798a767c8d7f6cfda89d2)", "thiserror 2.0.18", "tracing", "url", @@ -9260,9 +10148,9 @@ dependencies = [ [[package]] name = "sse-stream" -version = "0.2.3" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3962b63f038885f15bce2c6e02c0e7925c072f1ac86bb60fd44c5c6b762fb72" +checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4" dependencies = [ "bytes", "futures-util", @@ -9638,7 +10526,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.4", + "rustix", "windows-sys 0.61.2", ] @@ -9650,7 +10538,7 @@ checksum = "9048a889effe34a5cddee0af7f53285198b16dca3be510858d38dfdb3e62a04e" dependencies = [ "bitflags 2.13.0", "parking_lot", - "rustix 1.1.4", + "rustix", "signal-hook", "windows-sys 0.61.2", ] @@ -9905,16 +10793,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - [[package]] name = "tokio-retry" version = "0.3.1" @@ -9985,6 +10863,7 @@ dependencies = [ "futures-util", "log", "rustls", + "rustls-native-certs", "rustls-pki-types", "tokio", "tokio-rustls", @@ -10054,45 +10933,21 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "toml" -version = "0.9.12+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" -dependencies = [ - "indexmap", - "serde_core", - "serde_spanned", - "toml_datetime 0.7.5+spec-1.1.0", - "toml_parser", - "toml_writer", - "winnow 0.7.15", -] - [[package]] name = "toml" version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee" dependencies = [ - "indexmap", + "indexmap 2.14.0", "serde_core", "serde_spanned", - "toml_datetime 1.1.1+spec-1.1.0", + "toml_datetime", "toml_parser", "toml_writer", "winnow 1.0.3", ] -[[package]] -name = "toml_datetime" -version = "0.7.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" -dependencies = [ - "serde_core", -] - [[package]] name = "toml_datetime" version = "1.1.1+spec-1.1.0" @@ -10108,8 +10963,8 @@ version = "0.25.12+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" dependencies = [ - "indexmap", - "toml_datetime 1.1.1+spec-1.1.0", + "indexmap 2.14.0", + "toml_datetime", "toml_parser", "toml_writer", "winnow 1.0.3", @@ -10154,7 +11009,7 @@ dependencies = [ "tokio", "tokio-rustls", "tokio-stream", - "tower", + "tower 0.5.3", "tower-layer", "tower-service", "tracing", @@ -10182,6 +11037,17 @@ dependencies = [ "tonic", ] +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "tower" version = "0.5.3" @@ -10190,7 +11056,7 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap", + "indexmap 2.14.0", "pin-project-lite", "slab", "sync_wrapper", @@ -10224,7 +11090,7 @@ dependencies = [ "pin-project-lite", "tokio", "tokio-util", - "tower", + "tower 0.5.3", "tower-layer", "tower-service", "tracing", @@ -10307,7 +11173,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adbc64cba7137545b8044cb1fe9814f7aacf3c6b5f9b45be8bb5db538befdb26" dependencies = [ "js-sys", - "opentelemetry 0.32.0", + "opentelemetry", "smallvec", "tracing", "tracing-core", @@ -10396,6 +11262,12 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c" +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.0" @@ -10534,6 +11406,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "universal-time" version = "0.3.1" @@ -10636,43 +11518,6 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" -[[package]] -name = "vergen" -version = "9.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b849a1f6d8639e8de261e81ee0fc881e3e3620db1af9f2e0da015d4382ceaf75" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "vergen-lib", -] - -[[package]] -name = "vergen-gitcl" -version = "9.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ff3b5300a085d6bcd8fc96a507f706a28ae3814693236c9b409db71a1d15b9" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "time", - "vergen", - "vergen-lib", -] - -[[package]] -name = "vergen-lib" -version = "9.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b34a29ba7e9c59e62f229ae1932fb1b8fb8a6fdcc99215a641913f5f5a59a569" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", -] - [[package]] name = "version_check" version = "0.9.5" @@ -11146,6 +11991,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.2.0" @@ -11231,15 +12089,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - [[package]] name = "windows-sys" version = "0.60.2" @@ -11527,23 +12376,31 @@ dependencies = [ ] [[package]] -name = "xattr" -version = "1.6.1" +name = "x509-parser" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" dependencies = [ - "libc", - "rustix 1.1.4", + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.18", + "time", ] [[package]] -name = "xdg-home" -version = "1.3.0" +name = "xattr" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "windows-sys 0.59.0", + "rustix", ] [[package]] @@ -11708,6 +12565,16 @@ version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec 0.9.1", + "time", +] + [[package]] name = "yoke" version = "0.8.2" @@ -11733,60 +12600,85 @@ dependencies = [ [[package]] name = "zbus" -version = "4.4.0" +version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" dependencies = [ "async-broadcast", + "async-executor", + "async-io", + "async-lock", "async-process", "async-recursion", + "async-task", "async-trait", + "blocking", "enumflags2", "event-listener", "futures-core", - "futures-sink", - "futures-util", + "futures-lite", "hex", - "nix 0.29.0", + "libc", "ordered-stream", - "rand 0.8.6", + "rustix", "serde", "serde_repr", - "sha1 0.10.6", - "static_assertions", "tracing", "uds_windows", - "windows-sys 0.52.0", - "xdg-home", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.3", "zbus_macros", "zbus_names", "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" -version = "4.4.0" +version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", + "zbus_names", + "zvariant", "zvariant_utils", ] [[package]] name = "zbus_names" -version = "3.0.0" +version = "4.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" dependencies = [ "serde", - "static_assertions", + "winnow 1.0.3", "zvariant", ] +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" version = "0.8.48" @@ -11883,21 +12775,24 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "8.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", - "indexmap", + "indexmap 2.14.0", "memchr", - "thiserror 2.0.18", + "typed-path", "zopfli", ] +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + [[package]] name = "zmij" version = "1.0.21" @@ -11933,37 +12828,41 @@ dependencies = [ [[package]] name = "zvariant" -version = "4.2.0" +version = "5.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" dependencies = [ "endi", "enumflags2", "serde", - "static_assertions", + "winnow 1.0.3", + "zcheapstr", "zvariant_derive", + "zvariant_utils", ] [[package]] name = "zvariant_derive" -version = "4.2.0" +version = "5.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", "zvariant_utils", ] [[package]] name = "zvariant_utils" -version = "2.1.0" +version = "4.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "serde", + "syn 3.0.3", + "winnow 1.0.3", ] diff --git a/Cargo.toml b/Cargo.toml index c1f2039e293..4540e2b8223 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ members = [ "crates/buzz-relay", "crates/buzz-core", + "crates/ifc-core", "crates/buzz-conformance", "crates/buzz-push-gateway", "crates/buzz-db", @@ -16,6 +17,7 @@ members = [ "crates/buzz-ws-client", "crates/buzz-admin", "crates/buzz-deletion", + "crates/buzz-feature-flags", "crates/buzz-workflow", "crates/buzz-media", "crates/buzz-azure-storage", @@ -27,8 +29,10 @@ members = [ "crates/git-sign-nostr", "crates/buzz-pair-relay", "crates/buzz-relay-mesh", + "crates/buzz-mesh-smoke", "crates/buzz-dev-mcp", "crates/buzz-voice", + "crates/buzz-audio-client", "crates/buzz-backend-kubernetes", "crates/buzz-datastore-tracing", "examples/countdown-bot", @@ -105,7 +109,7 @@ chrono = { version = "0.4", features = ["serde"] } jsonwebtoken = { version = "10.4.0", default-features = false, features = ["aws_lc_rs"] } # HTTP client (webhook delivery) -reqwest = { version = "0.13", features = ["json", "rustls"], default-features = false } +reqwest = { version = "0.13", features = ["json", "rustls", "stream"], default-features = false } # Cryptography sha2 = "0.11" @@ -141,6 +145,7 @@ buzz-core = { path = "crates/buzz-core" } buzz-conformance = { path = "crates/buzz-conformance" } buzz-db = { path = "crates/buzz-db" } buzz-deletion = { path = "crates/buzz-deletion" } +buzz-feature-flags = { path = "crates/buzz-feature-flags" } buzz-auth = { path = "crates/buzz-auth" } buzz-pubsub = { path = "crates/buzz-pubsub" } buzz-search = { path = "crates/buzz-search" } @@ -188,3 +193,8 @@ strip = true # allowlist for the auth token). Revert to crates.io once #449 lands upstream. [patch.crates-io] aws-creds = { git = "https://github.com/tlongwell-block/rust-s3", rev = "c9fce3620dd434c1f810101d672cf384268dbb0f" } +# MeshLLM 0.76 uses rusqlite 0.40 / libsqlite3-sys 0.38. SQLx 0.9.0's +# optional SQLite driver still caps libsqlite3-sys below 0.38, which Cargo +# resolves even though Buzz only enables PostgreSQL. Pin the merged upstream +# compatibility fix until it is released: https://github.com/transact-rs/sqlx/pull/4402 +sqlx-sqlite = { git = "https://github.com/launchbadge/sqlx", rev = "94aafe3a68884d923b0798a767c8d7f6cfda89d2" } diff --git a/Dockerfile b/Dockerfile index 19a29223621..c1108d013b1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -54,6 +54,7 @@ FROM chef AS builder RUN apt-get update \ && apt-get install -y --no-install-recommends \ build-essential \ + cmake \ pkg-config \ libssl-dev \ ca-certificates \ diff --git a/Dockerfile.push-gateway b/Dockerfile.push-gateway index 202262d222f..2b899c89e5b 100644 --- a/Dockerfile.push-gateway +++ b/Dockerfile.push-gateway @@ -11,13 +11,14 @@ COPY . . RUN cargo chef prepare --recipe-path recipe.json FROM chef AS builder +ARG BUZZ_PUSH_CARGO_FEATURES="" RUN apt-get update \ - && apt-get install -y --no-install-recommends build-essential pkg-config libssl-dev ca-certificates \ + && apt-get install -y --no-install-recommends build-essential cmake pkg-config libssl-dev ca-certificates \ && rm -rf /var/lib/apt/lists/* COPY --from=planner /build/recipe.json recipe.json -RUN cargo chef cook --release --recipe-path recipe.json +RUN cargo chef cook --release --recipe-path recipe.json --features "$BUZZ_PUSH_CARGO_FEATURES" COPY . . -RUN cargo build --release --locked -p buzz-push-gateway --bin buzz-push-gateway \ +RUN cargo build --release --locked -p buzz-push-gateway --bin buzz-push-gateway --features "$BUZZ_PUSH_CARGO_FEATURES" \ && strip target/release/buzz-push-gateway FROM debian:${DEBIAN_VERSION}-slim AS runtime diff --git a/Dockerfile.sprig b/Dockerfile.sprig index 160e0b56625..ee8ac1a64f1 100644 --- a/Dockerfile.sprig +++ b/Dockerfile.sprig @@ -23,11 +23,7 @@ FROM alpine:3.22@sha256:14358309a308569c32bdc37e2e0e9694be33a9d99e68afb0f5ff33cc RUN apk add --no-cache bash ca-certificates curl git \ && adduser -D -h /home/agent agent \ - && install -d -o agent -g agent /workspace /home/agent \ - && git config --system gpg.format x509 \ - && git config --system gpg.x509.program /usr/local/bin/git-sign-nostr \ - && git config --system commit.gpgSign true \ - && git config --system tag.gpgSign true + && install -d -o agent -g agent /workspace /home/agent COPY --from=builder --chmod=0755 /build/target/sprig/sprig /usr/local/bin/sprig COPY --chmod=0755 scripts/sprig-entrypoint.sh /usr/local/bin/sprig-entrypoint diff --git a/Justfile b/Justfile index 40f44382939..67d950cc272 100644 --- a/Justfile +++ b/Justfile @@ -99,6 +99,7 @@ check: fmt-check clippy desktop-check desktop-tauri-fmt-check desktop-tauri-clip security-review-check: node --check .github/scripts/codex-security-review.js node --test .github/scripts/codex-security-review.test.js + actionlint .github/workflows/codex-security-review.yml # Verify Tauri placeholder sidecars use the platform filenames its build validates. sidecar-stub-contract-check: @@ -181,8 +182,12 @@ _ensure-sidecar-stubs: else SIDECARS+=(buzz-backend-kubernetes) fi + # Create missing stubs only: tauri-build reruns build.rs (and recompiles + # buzz-desktop) whenever an externalBin's mtime changes, so touching + # existing files would invalidate every cached desktop test build. for bin in "${SIDECARS[@]}"; do - touch "desktop/src-tauri/binaries/${bin}-${TARGET}${EXE}" + stub="desktop/src-tauri/binaries/${bin}-${TARGET}${EXE}" + [[ -e "$stub" ]] || : > "$stub" done # Ensure Docker dev services (Postgres, Redis, etc.) are running and healthy @@ -217,8 +222,13 @@ _ensure-migrations: _ensure-services ./scripts/seed-local-community.sh # Run clippy on the desktop Tauri Rust crate +# Features are additive, so a single invocation lints only one cfg graph. +# Both graphs ship (release-windows builds without mesh-llm), so lint both: +# the default graph covers the `#[cfg(not(feature = "mesh-llm"))]` arms and +# the feature-enabled graph covers the mesh code. desktop-tauri-clippy: _ensure-sidecar-stubs cargo clippy --manifest-path {{desktop_tauri_manifest}} --workspace --all-targets -- -D warnings + cargo clippy --manifest-path {{desktop_tauri_manifest}} --workspace --all-targets --features mesh-llm -- -D warnings # Check the desktop Tauri Rust crate compiles desktop-tauri-check: _ensure-sidecar-stubs @@ -228,41 +238,82 @@ desktop-tauri-check: _ensure-sidecar-stubs desktop-tauri-test: _ensure-sidecar-stubs cd desktop/src-tauri && cargo test --workspace +# Run the desktop Tauri lib tests with the mesh-llm feature graph +desktop-tauri-test-mesh: _ensure-sidecar-stubs + cargo test --manifest-path {{desktop_tauri_manifest}} --features mesh-llm --lib + # Run the native terminal latency gate explicitly on a known-idle host. # This is intentionally excluded from shared CI: scheduler contention makes a # wall-clock assertion flaky, and the release profile is the shipped shape. desktop-terminal-performance-test: cargo test --manifest-path desktop/src-tauri/crates/buzz-terminal/Cargo.toml --release --test latency g3_renderer_acquire_stays_within_frame_budget -- --ignored --exact --nocapture -# Verify compiled-flag behavior under both compile states (clean + capability set). -# Runs the auto-connect and owner-only access focused tests twice with -# independently supplied expected values; build.rs rerun-if-env-changed -# triggers recompilation. +# Verify compiled-flag behavior in each compile state. +# The clean (OSS) state's full suite already runs in desktop-tauri-test, so +# only its flag assertions run here. The internal state sets both release +# capabilities together, as internal release packaging does, and reruns the +# buzz_lib suite. An auto-connect-only state asserts the two capabilities stay +# independent (a swapped build.rs variable fails it). The demo state sets only +# the demo slug, asserts neither capability leaks on, and reruns the suite. +# Every invocation uses --lib so each state compiles a single test harness; +# build.rs rerun-if-env-changed triggers the recompile between states. The +# workspace member crates and integration tests do not read these build +# variables, so they are not rerun. desktop-tauri-test-compiled-flags: _ensure-sidecar-stubs #!/usr/bin/env bash set -euo pipefail cd desktop/src-tauri + unset BUZZ_BUILD_AUTO_CONNECT_DEFAULT_RELAY BUZZ_BUILD_AGENT_ACCESS_OWNER_ONLY BUZZ_BUILD_DEMO_SLUG + unset BUZZ_TEST_EXPECTED_AUTO_CONNECT_DEFAULT_RELAY BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY BUZZ_TEST_EXPECTED_DEMO_SLUG + # Run ignored assertions by name; libtest passes a filter that matches + # nothing, so require exactly one passing test per filter. + run_ignored() { + local out + out="$(cargo test --lib -- --ignored --nocapture "$@" 2>&1 | tee >(cat >&2))" + if ! grep -qE "^test result: ok\. $# passed;" <<<"$out"; then + echo "expected exactly $# ignored compiled-flag assertions to pass: $*" >&2 + exit 1 + fi + } + flag_tests=(compiled_flag_matches_expected compiled_policy_matches_expected) echo "=== Clean build (no flag) → expect false ===" - env -u BUZZ_BUILD_AUTO_CONNECT_DEFAULT_RELAY \ - BUZZ_TEST_EXPECTED_AUTO_CONNECT_DEFAULT_RELAY=false \ - cargo test compiled_flag_matches_expected -- --ignored --nocapture - env -u BUZZ_BUILD_AGENT_ACCESS_OWNER_ONLY \ - BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=false \ - cargo test --lib - env -u BUZZ_BUILD_AGENT_ACCESS_OWNER_ONLY \ - BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=false \ - cargo test compiled_policy_matches_expected -- --ignored --nocapture + ( + export BUZZ_TEST_EXPECTED_AUTO_CONNECT_DEFAULT_RELAY=false + export BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=false + run_ignored "${flag_tests[@]}" + ) echo "=== Internal build (flags set) → expect true ===" - BUZZ_BUILD_AUTO_CONNECT_DEFAULT_RELAY=1 \ - BUZZ_TEST_EXPECTED_AUTO_CONNECT_DEFAULT_RELAY=true \ - cargo test compiled_flag_matches_expected -- --ignored --nocapture - BUZZ_BUILD_AGENT_ACCESS_OWNER_ONLY=1 \ - BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=true \ + ( + export BUZZ_BUILD_AUTO_CONNECT_DEFAULT_RELAY=1 + export BUZZ_BUILD_AGENT_ACCESS_OWNER_ONLY=1 + export BUZZ_TEST_EXPECTED_AUTO_CONNECT_DEFAULT_RELAY=true + export BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=true + run_ignored "${flag_tests[@]}" + cargo test --lib + ) + echo "=== Auto-connect only → capabilities stay independent ===" + ( + export BUZZ_BUILD_AUTO_CONNECT_DEFAULT_RELAY=1 + export BUZZ_TEST_EXPECTED_AUTO_CONNECT_DEFAULT_RELAY=true + export BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=false + run_ignored "${flag_tests[@]}" + ) + echo "=== Maximum accepted demo name reaches Rust build validation ===" + DEMO_CONFIG="$(node ../scripts/demo-build-config.mjs "$(printf 'x%.0s' {1..31})" /dev/null 1234567812345678)" + DEMO_SLUG="$(node -e 'console.log(JSON.parse(process.argv[1]).slug)' "$DEMO_CONFIG")" + ( + export BUZZ_BUILD_DEMO_SLUG="$DEMO_SLUG" + export BUZZ_TEST_EXPECTED_DEMO_SLUG="$DEMO_SLUG" + export BUZZ_TEST_EXPECTED_AUTO_CONNECT_DEFAULT_RELAY=false + export BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=false + run_ignored compiled_demo_slug_matches_expected "${flag_tests[@]}" cargo test --lib - BUZZ_BUILD_AGENT_ACCESS_OWNER_ONLY=1 \ - BUZZ_TEST_EXPECTED_AGENT_ACCESS_OWNER_ONLY=true \ - cargo test compiled_policy_matches_expected -- --ignored --nocapture - echo "Both compiled states verified." + ) + if node ../scripts/demo-build-config.mjs "$(printf 'x%.0s' {1..32})" /dev/null 1234567812345678; then + echo "A 32-character demo name unexpectedly passed JavaScript validation" >&2 + exit 1 + fi + echo "All compiled states and the accepted/rejected demo-name boundary verified." # Build the full desktop Tauri app locally (unsigned, for testing) # Sidecar binary list must stay in sync with _ensure-sidecar-stubs above. @@ -285,6 +336,38 @@ desktop-release-build target="aarch64-apple-darwin": pnpm install cd {{desktop_dir}} && pnpm tauri build --features mesh-llm --target {{target}} +# Build an unsigned named macOS demo DMG with isolated app and runtime identities. +desktop-demo-build demo_name target="aarch64-apple-darwin": + #!/usr/bin/env bash + set -euo pipefail + TARGET={{target}} + [[ "$(uname -s)" == "Darwin" && "$TARGET" == *-apple-darwin ]] || { echo "Demo DMGs require a macOS Apple target" >&2; exit 2; } + CONFIG_PATH="$(mktemp "${TMPDIR:-/tmp}/buzz-demo-config.XXXXXX")" + trap 'rm -f "$CONFIG_PATH"' EXIT + DEMO_BUILD_ID="$(node -e 'console.log(require("node:crypto").randomBytes(8).toString("hex"))')" + DEMO_CONFIG="$(node desktop/scripts/demo-build-config.mjs {{quote(demo_name)}} "$CONFIG_PATH" "$DEMO_BUILD_ID")" + read_config() { node -e 'console.log(JSON.parse(process.argv[1])[process.argv[2]])' "$DEMO_CONFIG" "$1"; } + PRODUCT_NAME="$(read_config productName)" + DMG_VOLUME_NAME="$(read_config dmgVolumeName)" + DMG_FILE_STEM="$(read_config dmgFileStem)" + DEMO_SLUG="$(read_config slug)" + cargo build --release --target "$TARGET" \ + -p buzz-acp -p buzz-agent -p buzz-backend-kubernetes -p buzz-dev-mcp \ + -p git-credential-nostr -p buzz-cli + ./scripts/bundle-sidecars.sh "$TARGET" + pnpm install + cd {{desktop_dir}} + BUZZ_BUILD_DEMO_SLUG="$DEMO_SLUG" pnpm tauri build --features mesh-llm --target "$TARGET" --bundles app --config "$CONFIG_PATH" + cd .. + VERSION="$(node -p "require('./desktop/package.json').version")" + DMG_ARCH="${TARGET%%-*}"; [[ "$DMG_ARCH" == "x86_64" ]] && DMG_ARCH=x64 + APP_PATH="desktop/src-tauri/target/$TARGET/release/bundle/macos/$PRODUCT_NAME.app" + PLIST="$APP_PATH/Contents/Info.plist" + /usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName $PRODUCT_NAME" "$PLIST" + /usr/libexec/PlistBuddy -c "Set :CFBundleName $PRODUCT_NAME" "$PLIST" + codesign --force --deep --sign - "$APP_PATH" + VOL_NAME="$DMG_VOLUME_NAME" ./desktop/scripts/package-macos-dmg.sh "$APP_PATH" "desktop/src-tauri/target/$TARGET/release/bundle/dmg/${DMG_FILE_STEM}_${VERSION}_${DMG_ARCH}.dmg" + # Run desktop checks suitable for CI / pre-push desktop-ci: desktop-check desktop-test desktop-tauri-fmt-check desktop-build desktop-tauri-check desktop-tauri-test @@ -323,8 +406,18 @@ test-unit: #!/usr/bin/env bash set -euo pipefail ./scripts/test-ensure-local-relay-key.sh + # Shared Huddle transport, codec, and loopback authentication regressions. + cargo test -p buzz-audio-client if command -v cargo-nextest &>/dev/null; then cargo nextest run -p buzz-core -p buzz-auth --lib + # Mesh JWKS proxy-bypass regression: infra-free loopback I/O with + # child-process environment isolation. Its integration-test binary + # is not selected by --lib above. Keep the Cargo fallback in step. + cargo nextest run -p buzz-auth --test mesh_jwks_proxy + cargo nextest run -p buzz-audit --lib + # Cross-pod disconnect payload tests (NIP-FI and community archive + # fence); all infra-free. + cargo nextest run -p buzz-pubsub --lib -E 'test(/^conn_control::tests::/)' # buzz-auth NIP-FI verifier doctests. The sealed-authority # `compile_fail` doctests prove the default-feature public API alone # cannot forge the issuer→JWKS authority; nextest does not run @@ -334,6 +427,18 @@ test-unit: cargo test -p buzz-auth --doc cargo nextest run -p buzz-voice --lib cargo nextest run -p buzz-cli + # buzz-sdk builder/validation unit tests: pure event-builder and input + # validation (e.g. the canvas writer-discipline/skew guard and the + # canvas_write_survived predicate), no infra. `--lib` runs all unit + # tests without the rustdoc dependency-resolution flake the full-package + # invocation hits. Enumerated explicitly because nothing in CI runs + # `cargo test --workspace` — membership buys clippy/check, not tests. + cargo nextest run -p buzz-sdk --lib + # buzz-acp owns the relay-to-agent trust boundary. Run its tests here so + # forged relay events cannot regain a path into agent routing unnoticed. + cargo nextest run -p buzz-acp + # Exercise the real MCP server for modern and legacy clients. + cargo nextest run -p buzz-dev-mcp # buzz-db migrator/lint tests: pure SQL-parsing unit tests (no infra). # They guard the embedded-migrator invariant (the complete checked-in # additive migration set; legacy cutover/backfill remains an operator @@ -342,6 +447,25 @@ test-unit: # #[ignore]d, so --lib runs only the infra-free set. Without this gate a # stray file in migrations/ or a broken lint ships green. cargo nextest run -p buzz-db --lib + # buzz-db source-policy tests: infra-free scans of the crate sources + # that enforce the event-write admission chokepoint, metric/provenance + # contracts, and their fixtures. They live in an integration-test + # binary, so `--lib` above does not run them. + cargo nextest run -p buzz-db --test observability_source + # buzz-db `AdmittedTx` doctests. The `compile_fail` cases prove code + # outside the crate can neither construct an admitted transaction nor + # pass a raw `sqlx::Transaction` to an event-write helper; nextest + # does not run doctests, hence this separate step. + cargo test -p buzz-db --doc + # Storage accounting crosses three crates whose focused regression + # suites are otherwise absent from the infra-free unit lane. + cargo nextest run -p buzz-media --lib \ + -E 'test(=bucket_index::tests::bucket_snapshot_json_round_trip_preserves_community_keys)' + # buzz-admin: storage-snapshot worker, the community archive command + # parser, validation, and propagation-evidence tests, and the partition + # audit outcome contract. + cargo nextest run -p buzz-admin \ + -E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes)' # Multi-tenant conformance gate (buzz-conformance): the independent # replay checker + golden fixtures. No infra — pure in-process trace # replay — so it belongs in the unit job. Run all targets (lib + the @@ -350,20 +474,32 @@ test-unit: # Gateway unit and black-box HTTP tests are infra-free. Postgres-backed # contract/race tests run in the dedicated CI job below. cargo nextest run -p buzz-push-gateway + cargo nextest run -p buzz-push-gateway --features personal-dev-app-attest # Kubernetes backend provider: the decision layers (state machine, GC # planner, env precedence, naming, wire) are pure functions with a fake # substrate, so they belong in the unit job. Enumerated explicitly # because nothing in CI runs `cargo test --workspace` — workspace # membership alone buys clippy/check, not a single executed test. cargo nextest run -p buzz-backend-kubernetes - # buzz-agent model-capabilities corpus: the Rust half of the - # cross-language drift guard. `model_capabilities.rs` embeds - # scripts/model-capabilities.json + scripts/normative-corpus.json via - # include_str! and replays the full locked corpus as pure in-process tests (no - # infra). Enumerated explicitly because nothing in CI runs - # `cargo test --workspace`; without this step a manifest edit that - # diverges Rust from the corpus ships green. - cargo nextest run -p buzz-agent --lib + # Feature-flag crate coverage: run once with LaunchDarkly enabled. + # This includes all default tests plus the cfg(feature="launchdarkly") + # tests, avoiding duplicate default-only execution in the unit lane. + cargo nextest run -p buzz-feature-flags --features launchdarkly + # buzz-agent: two infra-free concerns run together by executing the + # whole crate (lib + integration tests), because nothing in CI runs + # `cargo test --workspace`, so without this stanza neither the crate's + # library tests nor its integration tests execute remotely. + # * model-capabilities corpus (lib): the Rust half of the + # cross-language drift guard. `model_capabilities.rs` embeds + # scripts/model-capabilities.json + scripts/normative-corpus.json via + # include_str! and replays the full locked corpus as pure in-process + # tests; without it a manifest edit that diverges Rust from the + # corpus ships green. + # * OAuth auth coordinator (lib concurrency matrix + databricks + # integration tests): lock single-flight, cooldown, cross-process + # crash recovery — infra-free via a stub OIDC provider and an + # injected browser opener, no network or Postgres. + cargo nextest run -p buzz-agent # Admin API auth-boundary tests (api::admin in buzz-relay): the NIP-98 # duplicate-tag rejections, the Host/Origin replay-ordering causal pair, # the admin.localhost origin/advertisement/canonical-URL pins, and the @@ -375,20 +511,116 @@ test-unit: # and a red one could ship green (exactly how a broken admin test slipped # past every gate once). Scoped to api::admin, not the whole buzz-relay # --lib, because api::media has non-ignored tests that require Postgres. - # Two api::admin tests are excluded: both exercise a read-route DB - # fallthrough and pass without a database only by waiting out the sqlx - # acquire timeout (~30s each), so they do not belong in the infra-free - # unit job. nip98_mode_unrostered_signer_does_not_consume_a_replay_slot - # asserts a unique replay-guard invariant, so it is wired into the - # Postgres-backed Backend Integration job (see ci.yml "Admin API - # unrostered-signer replay invariant"). disabled_mode_allows_ - # unauthenticated_requests_on_the_admin_host has no unique invariant: - # disabled-mode unauthenticated success is covered by - # disabled_mode_regression_pin_unauthenticated_request_is_served on the - # DB-free /probe route, and its Host/Origin gating is covered here by - # disabled_mode_still_requires_the_correct_host / _a_matching_origin. - cargo nextest run -p buzz-relay --lib \ - -E 'test(/^api::admin::/) - test(=api::admin::tests::disabled_mode_allows_unauthenticated_requests_on_the_admin_host) - test(=api::admin::tests::nip98_mode_unrostered_signer_does_not_consume_a_replay_slot)' + # DB-backed api::admin tests are #[ignore]d and run in the PostgreSQL + # lane; the non-ignored ones reject before touching the database. Any + # new non-ignored test here must stay DB-free: without a database, a + # DB fallthrough only "passes" by waiting out the ~30s sqlx acquire + # timeout. + # The second clause adds the relay's pure authorization-decision tests: + # the NIP-29 channel membership grid (handlers::channel_authz), the + # moderation capability grid (handlers::moderation_authz), and the pure + # helpers in handlers::side_effects. They ran in NO lane before — + # `test(/^api::admin::/)` never matched them, and the PostgreSQL lane + # pairs `--run-ignored ignored-only` with a `postgres_tests::` + # default-filter — so a red one shipped green, exactly the gap the + # api::admin clause above was added to close. + # Deliberately scoped to these three modules instead of all of + # `handlers::`: the wider set is mostly Postgres-backed, and five of its + # non-postgres_tests cases only "pass" without a database by waiting out + # the ~30s sqlx acquire timeout, so they do not belong in the infra-free + # unit job either. The REQ subscription-lifecycle tests are picked by + # exact name for the same reason: the rest of handlers::req needs a DB. + # The third clause adds the NIP-FI HTTP ingress and its router/config + # neighbours: nip_fi_http, nip_fi_config, router, api::parse_query_tests, + # the profile search request bounds (api::profiles), and the Git + # transport off_mode_precedence_tests. All are infra-free + # and finish in well under a second with no DATABASE_URL, so none wait + # out the sqlx acquire timeout. `--bin buzz-relay` adds main.rs's + # `tests::` module (JWKS refresh cadence) and `composition_tests::` + # (JWKS source + refresh-loop composition), which `--lib` cannot reach + # because they live in the binary target; the nested + # `tests::postgres_tests::` stays in the PostgreSQL lane. + # The fourth clause adds the startup step timers (startup_steps) and the + # env- and log-capture tests in telemetry and config. All three modules + # are infra-free; config parses env into a struct and never connects. + # `^config::` is anchored so it does not also select nip_fi_config. + cargo nextest run -p buzz-relay --lib --bin buzz-relay \ + -E 'test(/^api::admin::/) + test(/^push_runtime::/) + test(/^operator_listener::tests::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^handlers::system_channels::tests::/) + test(/^nip11::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_core::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::profiles::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(/^audio::join::tests::/) + test(/^audio::handler::tests::/) + test(/^nip_fi_gate::tests::/) + test(/^nip_fi_session::tests::/) + test(/^nip_fi_shadow::tests::/) + test(/^nip_fi_shadow_session::tests::/) + test(/^startup_steps::tests::/) + test(/^telemetry::tests::/) + test(/^config::tests::/) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + test(=state::tests::periodic_revalidation_disconnects_inside_the_fenced_callback) + test(=state::tests::bare_community_disconnect_fails_closed_when_the_fence_is_unavailable) + test(=connection::tests::send_loop_sends_policy_close_when_community_is_archived) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=handlers::req::tests::timed_out_historical_read_deregisters_before_closed) + test(=handlers::req::tests::superseded_timeout_leaves_replacement_intact) + test(=handlers::req::tests::search_claim_retires_live_and_yields_to_replacement) + test(=handlers::req::tests::concurrent_claims_and_stale_teardowns_keep_the_last_owner) + test(=handlers::req::tests::timeout_closed_is_emitted_before_a_replacement_can_claim) + test(=handlers::req::tests::revoke_then_replacement_keeps_replacement_whole) + test(=handlers::req::tests::claims_after_connection_cleanup_are_refused) + test(=handlers::req::tests::dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::count_fallback_covers_filters_that_can_match_private_deletions) + test(=handlers::req::tests::group_state_t_and_creator_tags_reach_sql_only_for_group_state_kinds) + test(=api::bridge::postgres_tests::bridge_search_mode_extension_accepts_prefix_snake_or_camel_case) + test(=api::bridge::postgres_tests::bridge_search_sort_extension_selects_newest_only_when_named) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))' + # Note on audio::join::tests scope: the full suite is infra-free (no DB, + # no Redis). The infra-free audio/FI regression witnesses — bootstrap + # ordering barrier, CommitConfirmed arm, pending-close invisibility, + # abnormal-stream-close fanout, and never-ready-sink writer witnesses — + # are all selected by audio::join::tests and audio::handler::tests. + # DB-backed audio join tests use #[ignore] and run in the postgres lane. + # NIP-FI (S3/S4) relay witnesses: the wholly-new nip_fi_upgrade and + # api::nip_fi modules, + # the auth metrics contract module, the DB-free partition alert series + # tests (their Postgres case is #[ignore]d and runs in the PostgreSQL + # lane), plus the exact NIP-FI tests added, + # or whose assertions changed, in mixed modules (audio::room, + # connection, handlers::*, state). nip_fi_config and router are + # selected whole by the command above. Mixed modules are listed by exact + # name so main's unselected tests (several wait out the ~30s sqlx + # acquire timeout) stay out. NIP-FI tests that need Postgres live in + # postgres_tests and + # run in the PostgreSQL lane. Keep scripts/run-tests.sh in step. + cargo nextest run -p buzz-relay --lib -E ' + test(/^nip_fi_upgrade::/) + + test(/^metrics::contract_tests::/) + + test(/^metrics::partition_alert_tests::/) + + test(=audio::room::tests::roster_revisions_are_ordered_and_snapshot_is_authoritative) + + test(=connection::tests::auth_lifecycle_reconciles_every_terminal_and_never_leaks_gauge) + + test(=audio::room::tests::b1_pending_peer_removed_before_commit_emits_no_delta) + + test(=audio::room::tests::b2_commit_peer_emits_exactly_one_joined_delta_and_marks_visible) + + test(=audio::room::tests::b3_commit_peer_revision_is_monotone_between_concurrent_events) + + test(=audio::room::tests::f7a_pending_peer_excluded_from_snapshot_until_committed) + + test(=connection::tests::b2_cancelled_connection_event_frame_not_dispatched) + + test(=connection::tests::b3_expiry_denial_precedes_close_through_send_loop) + + test(=connection::tests::b3_root_pairing_denial_precedes_close_through_send_loop) + + test(=connection::tests::cancellation_during_select_with_fi_denial_routes_through_bounded_path) + + test(=connection::tests::cancelled_never_ready_sink_with_queued_fi_denial_exits_within_timeout) + + test(=connection::tests::deadline_exp_is_earliest_selects_exp) + + test(=connection::tests::deadline_max_connection_lifetime_is_earliest_selects_partition) + + test(=connection::tests::deadline_no_lifetime_returns_upstream_only) + + test(=connection::tests::expiry_notice_queued_on_ctrl_before_cancel) + + test(=connection::tests::f3_root_outer_wrapper_delivers_denial_on_bootstrap_cancellation) + + test(=connection::tests::f3_root_pre_built_expired_gate_terminates_connection) + + test(=handlers::auth::tests::b2_pre_cancelled_connection_never_becomes_authenticated) + + test(=handlers::auth::tests::fi_ban_check_error_emits_terminal_authorization_unavailable) + + test(=handlers::auth::tests::fi_root_authorization_denied_rows_emit_identical_frames) + + test(=handlers::auth::tests::fi_invalid_nip42_proof_emits_terminal_evidence_rejected) + + test(=handlers::auth::tests::handle_auth_pairing_mismatch_runs_full_root_denial_path) + + test(=handlers::auth::tests::shadow_root_auth_records_pairing_denial) + + test(=handlers::auth::tests::shadow_root_invalid_nip42_retires_without_record) + + test(=handlers::auth::tests::nip42_denial_class_separates_internal_failure_from_bad_evidence) + + test(=handlers::event::tests::fanout_access::owner_only_kinds_keep_only_the_owner) + + test(=handlers::event::tests::pubsub_fanout::pubsub_owner_only_kinds_reach_only_the_owner) + + test(=handlers::event::tests::pubsub_fanout::dispatch_owner_only_kinds_reach_only_the_owner) + + test(=handlers::req::tests::p1a_huddle_liveness_req_barrier_expiry_blocks_query_and_emission) + + test(=state::tests::f3_cancellation_during_check_terminates_socket_without_waiting_for_check) + + test(=state::tests::on_not_run_runs_once_on_each_deny_arm_and_never_on_admit) + + test(=state::tests::conn_manager_disconnect_nip_fi_ignores_unproven_connection) + + test(=state::tests::conn_manager_disconnect_nip_fi_is_issuer_scoped) + + test(=state::tests::conn_manager_disconnect_nip_fi_sets_authorization_denied_reason) + + test(=state::tests::nip_fi_disconnect_audio_is_issuer_scoped) + + test(=state::tests::nip_fi_disconnect_closes_proven_audio_socket_and_sends_policy_close_reason) + + test(=state::tests::nip_fi_disconnect_closes_target_audio_only_and_preserves_collocated_peer) + + test(=state::tests::nip_fi_disconnect_does_not_close_different_pubkey_audio_socket) + + test(=state::tests::nip_fi_disconnect_does_not_close_unproven_audio_socket) + + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + + test(=state::tests::manager_disconnect_sets_reason_enqueues_frame_then_cancels) + + test(/^api::nip_fi::/)' + # boot_lifecycle spawns the real relay binary and asserts its startup + # lifecycle, including that buzz_startup_phase_* reaches /metrics. Its + # non-ignored tests need no Postgres or Redis; the Postgres cases are + # #[ignore]d and stay in the PostgreSQL lane. Keep + # scripts/run-tests.sh in step. + cargo nextest run -p buzz-relay --test boot_lifecycle + # ACP author-gate and queue tests protect the trust boundary between + # relay events and agent prompts. They are infra-free; ignored lifecycle + # tests remain excluded and run in their dedicated integration lanes. + cargo nextest run -p buzz-acp --lib else ./scripts/run-tests.sh unit fi @@ -434,23 +666,23 @@ mesh-dev-fresh: mesh-e2e-hardware: #!/usr/bin/env bash set -euo pipefail - cargo run -p buzz-relay --example mesh_serve_client_smoke + cargo run -p buzz-mesh-smoke --example mesh_serve_client_smoke # Three isolated node processes: trusted member joins and infers; stranger is rejected. # Uses temp homes and explicit mesh owner keystores. Never reads the Buzz Keychain. mesh-e2e-admission: #!/usr/bin/env bash set -euo pipefail - cargo run -p buzz-relay --example mesh_admission_smoke + cargo run -p buzz-mesh-smoke --example mesh_admission_smoke # Full hardware confidence suite: routing, owner admission, and real agent inference. mesh-e2e-confidence: #!/usr/bin/env bash set -euo pipefail cargo build --release -p buzz-agent -p buzz-dev-mcp - cargo run -p buzz-relay --example mesh_serve_client_smoke - cargo run -p buzz-relay --example mesh_admission_smoke - cargo run -p buzz-relay --example mesh_agent_e2e + cargo run -p buzz-mesh-smoke --example mesh_serve_client_smoke + cargo run -p buzz-mesh-smoke --example mesh_admission_smoke + cargo run -p buzz-mesh-smoke --example mesh_agent_e2e # Take desktop screenshots using the mock bridge desktop-screenshot *ARGS: @@ -477,6 +709,10 @@ relay: bootstrap _ensure-migrations set +o allexport cargo run -p buzz-relay +# Post one root + N replies (and a few reactions) to the local dev relay, for eyeballing long threads +seed-long-thread replies="187": + ./scripts/seed-long-thread.sh {{replies}} + # Start the relay with the built web UI served from it relay-web: bootstrap _ensure-migrations #!/usr/bin/env bash @@ -501,13 +737,24 @@ admin: bootstrap _ensure-migrations pnpm -C admin-web build export BUZZ_ADMIN_HOST="${BUZZ_ADMIN_HOST:-admin.localhost:3000}" export BUZZ_ADMIN_WEB_DIR="${BUZZ_ADMIN_WEB_DIR:-{{justfile_directory()}}/admin-web/dist}" - # Default to disabled auth locally: localhost is the network boundary and a - # NIP-07 signer extension can't be assumed in dev. Override per run with - # BUZZ_ADMIN_AUTH=nip98 (plus RELAY_OPERATOR_PUBKEYS or RELAY_OWNER_PUBKEY) - # to exercise the authenticated path. + # Default to disabled auth locally: a NIP-07 signer extension can't be + # assumed in dev. Disabled mode serves every moderation read (reports, + # feedback, restrictions, community directory, member profiles, any stored + # message by ID) to anyone who can reach the relay port and refuses writes + # and staffing, so it binds the relay to 127.0.0.1 (port from .env) + # unless the mode is exactly nip98: a padded or misspelled value stays + # local. Override per run with BUZZ_ADMIN_AUTH=nip98 (plus + # RELAY_OPERATOR_PUBKEYS or RELAY_OWNER_PUBKEY) to exercise the + # authenticated path; that keeps BUZZ_BIND_ADDR as configured. export BUZZ_ADMIN_AUTH="${BUZZ_ADMIN_AUTH:-disabled}" + if [[ "$BUZZ_ADMIN_AUTH" != nip98 ]]; then + bind_addr="${BUZZ_BIND_ADDR:-0.0.0.0:3000}" + relay_port="${bind_addr##*:}"; [[ -n "$relay_port" ]] || relay_port=3000 + export BUZZ_BIND_ADDR="127.0.0.1:${relay_port}" + fi echo "Admin dashboard: http://${BUZZ_ADMIN_HOST}/reports" echo "Auth mode: ${BUZZ_ADMIN_AUTH} (set BUZZ_ADMIN_AUTH=nip98 to require a signed operator)" + echo "Relay bind: ${BUZZ_BIND_ADDR:-0.0.0.0:3000}" cargo run -p buzz-relay # Seed deterministic reports and product feedback for local admin dashboard review @@ -620,7 +867,11 @@ desktop-standalone *ARGS: _ensure-sidecar-stubs fi trap '../scripts/cleanup-instance-agents.sh "$INSTANCE_ID" || true' EXIT echo "Starting standalone desktop on Vite port ${BUZZ_VITE_PORT}; no relay services were started" - pnpm exec tauri dev --config "$BUZZ_TAURI_CONFIG" {{ARGS}} + FEATURES=() + if [[ -n "{{mesh}}" ]]; then + FEATURES=(--features mesh-llm) + fi + pnpm exec tauri dev ${FEATURES[@]+"${FEATURES[@]}"} --config "$BUZZ_TAURI_CONFIG" {{ARGS}} # Run the desktop app against the internal staging relay (installs deps + builds agent tools automatically) staging *ARGS: bootstrap _ensure-sidecar-stubs @@ -648,7 +899,7 @@ staging *ARGS: bootstrap _ensure-sidecar-stubs chmod +x "desktop/src-tauri/binaries/${bin}-${TARGET}" done cd {{desktop_dir}} - export BUZZ_RELAY_URL="wss://sprout-oss.stage.blox.sqprod.co" + export BUZZ_RELAY_URL="wss://buzz.test.blockstaging.build" source ../scripts/instance-env.sh # Ctrl+C kills the Tauri app before its in-process sweep finishes, leaking # agent workers. Reap this instance's agents on exit as a backstop. @@ -758,7 +1009,9 @@ mobile-check: # Run mobile tests mobile-test: - unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter test + /bin/bash ./scripts/test-mobile-gateway-recipes.sh + unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter test --dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example + unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter test test/shared/push/push_unconfigured_build_test.dart # Regenerate the emoji dataset asset from desktop's emoji-mart install. # Output is committed — rerun after bumping @emoji-mart/data. @@ -767,21 +1020,42 @@ mobile-emoji-data: # Compile an unsigned Android debug APK (worktree-aware debug identity) mobile-build-android: + #!/usr/bin/env bash + set -euo pipefail ./scripts/mobile-worktree-overrides.sh - unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter build apk --debug --no-pub + set -- build apk --debug --no-pub + if [[ -n "${BUZZ_PUSH_GATEWAY_URL:-}" ]]; then + set -- "$@" --dart-define="BUZZ_PUSH_GATEWAY_URL=${BUZZ_PUSH_GATEWAY_URL}" + fi + unset GIT_DIR GIT_WORK_TREE + cd {{mobile_dir}} + flutter "$@" # Run the mobile app on iOS simulator (worktree-aware debug identity) mobile-dev: #!/usr/bin/env bash set -euo pipefail - if ! pgrep -x Simulator &>/dev/null; then - open -a Simulator - sleep 3 + developer_dir="$(xcode-select -p)" + simulator_app="$developer_dir/../Applications/DeviceHub.app" + if [[ ! -d "$simulator_app" ]]; then + simulator_app="$developer_dir/Applications/Simulator.app" fi + # Use the selected Xcode even when another version's app is already running. + open -a "$simulator_app" + sleep 3 ./scripts/mobile-worktree-overrides.sh + gateway_url="${BUZZ_PUSH_GATEWAY_URL:-}" + overrides_file="{{mobile_dir}}/ios/Flutter/AppOverrides.xcconfig" + if [[ -z "$gateway_url" && -f "$overrides_file" ]]; then + gateway_url="$(sed -nE 's/^[[:space:]]*BUZZ_PUSH_GATEWAY_URL[[:space:]]*=[[:space:]]*(.*[^[:space:]])[[:space:]]*$/\1/p' "$overrides_file" | tail -n 1 | sed 's/\$()//g')" + fi + set -- run + if [[ -n "$gateway_url" ]]; then + set -- "$@" --dart-define="BUZZ_PUSH_GATEWAY_URL=${gateway_url}" + fi cd {{mobile_dir}} unset GIT_DIR GIT_WORK_TREE - flutter run + flutter "$@" # Uninstall stale worktree-suffixed Buzz debug installs (production apps kept) mobile-clean: diff --git a/NOSTR.md b/NOSTR.md index cce70f2f77f..62e438d30db 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -50,23 +50,24 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \ | **Reactions (kind:7)** | ✅ | Standard NIP-25; channel derived from target event's `#e` tag (client `#h` ignored) | | **Deletions (kind:5)** | ✅ | Standard NIP-09; self-authored only. `#h` optional, `#e` required | | **User profiles (kind:0)** | ✅ | NIP-01 metadata; synced to users table (display_name, avatar, about, NIP-05). NIP-05 handles must canonicalize to this relay's domain — off-domain or invalid handles are silently cleared. If a NIP-05 handle collides with another user's (UNIQUE constraint), the handle is skipped but other profile fields (display_name, avatar, about) are still synced. | -| **Group creation (kind:9007)** | ✅ | NIP-29; include `name` tag, optional `visibility` and `channel_type` | +| **Group creation (kind:9007)** | ✅ | NIP-29; include `name` tag, optional `visibility`, `channel_type` and label `t` tags | | **Add user (kind:9000)** | ✅ | Open: any user, subject to target's `channel_add_policy` (`owner_only`/`nobody` can block). Private: owner/admin only. Self-add bypasses agent policy but not private-channel auth. | | **Remove user (kind:9001)** | ✅ | Self-remove allowed (with last-owner guard). Removing others: owner/admin only. | -| **Edit group metadata (kind:9002)** | ✅ | `name`/`about` tags: owner/admin. `topic`/`purpose` tags: any member. | +| **Edit group metadata (kind:9002)** | ✅ | `name`/`about`/label `t` tags: owner/admin. `topic`/`purpose` tags: any member. | | **Admin delete event (kind:9005)** | ✅ | Event author can always delete own. Otherwise owner/admin required. Target must be in same channel. | | **Group deletion (kind:9008)** | ✅ | Owner only. | | **Leave group (kind:9022)** | ✅ | Any member. Last-owner guard prevents orphaned groups. | -| **Group metadata (kind:39000)** | ✅ | Relay-signed; always `d`, `name`, `closed` tags; `about` only if description non-empty; `private` if applicable; `hidden` for DM channels | -| **Group admins (kind:39001)** | ✅ | Relay-signed; `d` tag + `p` tags with roles (`owner`, `admin`) | -| **Group members (kind:39002)** | ✅ | Relay-signed; `d` tag + `p` tags for all members | +| **Group metadata (kind:39000)** | ✅ | Relay-signed; always `d`, `name`, `closed`, `["t", ]`, `["P", ]` and `["created_at", ]` tags; `about` only if description non-empty; `private` if applicable; `hidden` for DM channels and private system channels | +| **Group admins (kind:39001)** | ✅ | Relay-signed; `d`, channel type `t` and creator `P` tags + `p` tags with roles (`owner`, `admin`) | +| **Group members (kind:39002)** | ✅ | Relay-signed; `d`, channel type `t` and creator `P` tags + `p` tags for all members | | **Membership notifications** | ✅ | kind:44100 (added) / kind:44101 (removed); relay-signed, community-global scope (`channel_id=None` inside the connected community) | | **Presence (kind:20001)** | ✅ | Ephemeral; arbitrary status string (truncated to 128 chars); writes to Redis (`set_presence`/`clear_presence` on `"offline"`), then fan-out to local subscribers. In multi-community mode presence is scoped to the connected community. | +| **Agent presence (kind:20003)** | ✅ | Ephemeral; an owner's presence for the agents it owns, named by `p` tags (at most 256); `online`/`away` set and `offline` clears each agent's presence as its own kind:20001 would. Not fanned out. | | **Typing indicators (kind:20002)** | ✅ | Ephemeral, not stored; published via Redis pub/sub (multi-node capable unlike presence fan-out) | | **NIP-42 authentication** | ✅ | Proactive challenge; optional pubkey allowlist | | **NIP-11 relay info** | ✅ | `GET /` with `Accept: application/nostr+json` | | **Blossom media** | ✅ | `PUT /media/upload` (BUD-02), `GET /media/{sha256}.{ext}` (BUD-01) | -| **NIP-50 search** | ✅ | One-shot search REQs: `{"search":"query","kinds":[9],"#h":[""]}` → relevance-sorted results → EOSE. Not registered as persistent subscriptions. | +| **NIP-50 search** | ✅ | One-shot search REQs: `{"search":"query","kinds":[9],"#h":[""]}` → relevance-sorted results → EOSE. Not registered as persistent subscriptions. HTTP `POST /query` also accepts `search_sort: "newest"` (advertised as `buzz-search-sort` in NIP-11 `supported_extensions`) for newest-first results, paged with `page`. | | **NIP-10 threads** | ✅ | WS-submitted replies with `["e","","","reply"]` tags create `thread_metadata` atomically. Visible in REST thread queries. Unknown parents rejected. | | **NIP-17 DMs (gift wrap)** | ✅ | kind:1059 accepted with ephemeral signing keys. Stored community-globally (`channel_id=None` inside the connected community). Delivered via `#p`-filtered subscriptions. Not indexed in search. | | **DM discovery** | ✅ | DM creation emits kind:39000 (with `hidden` tag) + kind:44100 membership notifications. NIP-29 clients discover DMs via standard group discovery flow. | @@ -102,13 +103,56 @@ relay to specific external Nostr identities without granting full access. ### Group Discovery The relay emits NIP-29 group state events when channels are created, updated, or membership changes. +[NIP-CL](docs/nips/NIP-CL.md) defines the channel identity tags on these events and how clients +use them to find channels. All discovery events include a `d` tag set to the channel UUID (NIP-29 addressable event convention): | Kind | Tags | Content | |------|------|---------| -| **39000** | `d=`, `name`, `closed` (always); `about` (if description non-empty); `private` (if applicable); `hidden` (DM channels only) | Group metadata. **Note:** `closed` is always emitted per NIP-29 convention (Buzz channels require explicit membership), but open channels are still readable/writable by non-members at runtime. The tag reflects the membership model, not access enforcement. | -| **39001** | `d=`, `p` tags with role label (`owner`, `admin`) | Admin list | -| **39002** | `d=`, `p` tags for all members | Member list | +| **39000** | `d=`, `name`, `closed`, `t=`, `P=`, `created_at=` (always); `about` (if description non-empty); `private` (if applicable); `hidden` (DM channels and private system channels) | Group metadata. **Note:** `closed` is always emitted per NIP-29 convention (Buzz channels require explicit membership), but open channels are still readable/writable by non-members at runtime. The tag reflects the membership model, not access enforcement. | +| **39001** | `d=`, `t=`, `P=`, `p` tags with role label (`owner`, `admin`) | Admin list | +| **39002** | `d=`, `t=`, `P=`, `p` tags for all members | Member list | + +On all three kinds the channel type `t` tag comes first, then one `t` tag +per channel label, then `P`. Clients read the first `t` value as the +channel type. `P` is +the public key that signed the channel's kind:9007. The relay writes it +from the database, and it does not change when ownership moves. Uppercase +`P` follows NIP-22, NIP-34 and NIP-72, where it names the author of the root +object; lowercase `p` already lists members and DM participants on these +kinds. + +kind:39000 also carries `["created_at", ]`: the time the +channel was created. The event's own `created_at` is the time of the last +edit, so use the tag to find the older of two channels. + +**Channel labels.** A label groups channels across channel types, for +example `["t", "workspace"]`. Set labels with `["t",
.sql` per table plus +its types, functions, partitions, triggers, and seed rows. +That is the default and is appropriate for data-access behavior. + +Tests in `migration::postgres_tests` receive an empty database and own the +embedded migration lifecycle. A test outside that module that intentionally +depends on migration-created triggers or seed rows must prefix its function +name with `migration_schema_`; it also receives an empty database with +`BUZZ_TEST_SCHEMA_MODE=migration`. + +Helpers that normally run migrations honor `BUZZ_TEST_SCHEMA_MODE=desired` in +the default lane. Do not rerun migrations against a desired-state database. +When behavior should match in both schema paths, add explicit desired-state and +migration-applied coverage rather than making the bootstrap implicit. + +Tests that inspect cluster-wide PostgreSQL state or open least-privilege +sessions include `cluster_global_` in the function name. Migration-backed cases +use `migration_schema_cluster_global_`. Nextest serializes this small group +because separate databases still share `pg_stat_activity` and roles. + +## Run the lane locally + +Start native PostgreSQL and Redis, activate Hermit, and run: + +```bash +. ./bin/activate-hermit +scripts/test-postgres-test-discovery.sh +scripts/postgres-test-run.sh +``` + +Set `BUZZ_POSTGRES_ADMIN_URL` to a PostgreSQL maintenance database owned by a +role that can create and drop databases. Set `PGHOST`, `PGPORT`, `PGUSER`, and +`PGPASSWORD` for desired-state bootstrap, plus `REDIS_URL` for Redis-backed +tests. The complete privilege-boundary inventory also needs `CREATEROLE` and +membership in `pg_read_all_stats`, or an ephemeral superuser as CI uses. + +The runner creates one desired-state source database per invocation and clones +it for ordinary tests. Migration-mode tests start empty. Cleanup retries +transient disconnect races before reporting a warning. diff --git a/crates/buzz-db/src/error.rs b/crates/buzz-db/src/error.rs index 4f4e6b105c5..e27b319bed4 100644 --- a/crates/buzz-db/src/error.rs +++ b/crates/buzz-db/src/error.rs @@ -45,6 +45,11 @@ pub enum DbError { #[error("invalid data: {0}")] InvalidData(String), + /// A partition the catalog audit had already listed was dropped before the + /// audit finished. A fresh snapshot sees a consistent catalog. + #[error("partition catalog changed mid-audit: {0}")] + PartitionDroppedMidAudit(String), + /// A serving write admitted before the lifecycle transition is still live. /// This is an ordinary retryable drain condition, not a safety violation. #[error( @@ -64,6 +69,14 @@ pub enum DbError { #[error("deletion safety error: {0}")] DeletionSafety(String), + /// A complete read-state snapshot exceeds its bounded resource budget. + #[error("read-state snapshot exceeds event or byte limit")] + ReadStateSnapshotTooLarge, + + /// A complete thread window exceeds its request-wide work allowance. + #[error("thread window exceeds {0} budget")] + ThreadWindowBudgetExceeded(&'static str), + /// A stored timestamp value could not be interpreted. #[error("invalid timestamp: {0}")] InvalidTimestamp(i64), @@ -76,5 +89,52 @@ pub enum DbError { LastOperator, } +impl DbError { + /// Whether Postgres cancelled the statement (SQLSTATE 57014: + /// `statement_timeout` or an explicit cancel). Re-running such a query on + /// the writer would only repeat the same expensive work. + pub fn is_statement_cancelled(&self) -> bool { + matches!( + self, + DbError::Sqlx(sqlx::Error::Database(db)) if db.code().as_deref() == Some("57014") + ) + } + + /// Whether the failure is about reaching the database at all (pool + /// acquire timeout, closed pool, or socket I/O) rather than about the + /// statement or its tenant. Every later query on the pool is expected to + /// fail the same way. + pub fn is_connection_unavailable(&self) -> bool { + matches!( + self, + DbError::Sqlx(sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Io(_)) + ) + } +} + /// Convenience alias for `Result`. pub type Result = std::result::Result; + +#[cfg(test)] +mod tests { + use super::DbError; + + #[test] + fn connection_unavailable_covers_only_pool_and_io_failures() { + for error in [ + sqlx::Error::PoolTimedOut, + sqlx::Error::PoolClosed, + sqlx::Error::Io(std::io::Error::from(std::io::ErrorKind::ConnectionReset)), + ] { + assert!(DbError::Sqlx(error).is_connection_unavailable()); + } + for error in [ + DbError::Sqlx(sqlx::Error::RowNotFound), + DbError::Sqlx(sqlx::Error::Protocol("bad frame".into())), + DbError::AccessDenied("write-fenced".into()), + DbError::InvalidData("bad row".into()), + ] { + assert!(!error.is_connection_unavailable(), "{error:?}"); + } + } +} diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 4226fbf8cbb..d264f108454 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -27,18 +27,49 @@ mod store; /// Database error types. pub mod error; +#[cfg(test)] +mod test_support; + pub use runtime::{ - insert_mentions, migration, replica_fence, Db, DbConfig, DbPoolStats, ReadSession, + insert_mentions, migration, replica_fence, AdmittedTx, ColdStartError, Db, DbConfig, + DbConnectionOutcome, DbConnectionStep, DbPoolRole, DbPoolStats, DbReadinessOutcome, + ReadSession, }; + +/// Valid low-cardinality `(pool_role, operation)` pairs for pool-acquisition telemetry. +pub const DB_POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 12] = + runtime::observability::POOL_ACQUIRE_VALID_PAIRS; + +/// Raw Prometheus series ceiling per relay pod for the operation-aware contract. +pub const DB_POOL_ACQUIRE_RAW_SERIES_PER_POD: usize = + runtime::observability::POOL_ACQUIRE_RAW_SERIES_PER_POD; + +/// Valid database connection role/step pairs with a start counter. +pub const DB_CONNECTION_STARTED_STEPS: [(DbPoolRole, DbConnectionStep); 4] = + runtime::CONNECTION_STARTED_STEPS; + +/// Valid database connection role/step pairs with a duration histogram. +pub const DB_CONNECTION_DURATION_STEPS: [(DbPoolRole, DbConnectionStep); 4] = + runtime::CONNECTION_DURATION_STEPS; + +/// Valid database connection role/step/outcome terminal combinations. +pub const DB_CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutcome); 15] = + runtime::CONNECTION_TERMINALS; + +/// Raw Prometheus series ceiling per pod for connection-step telemetry. +pub const DB_CONNECTION_RAW_SERIES_PER_POD: usize = runtime::CONNECTION_RAW_SERIES_PER_POD; pub(crate) use runtime::{ - insert_mentions_in_transaction, observability, route_proof, ReadSessionInner, RouteDecision, - RoutePredicate, + begin_community_event_write_transaction, + begin_community_event_write_transaction_with_legacy_metrics, begin_community_sweep_transaction, + begin_community_write_transaction, insert_mentions_in_transaction, observability, route_proof, + sweep_admitted_communities, ReadSessionInner, RouteDecision, RoutePredicate, }; pub use store::{ - admin_moderation, allowlist, api_token, archived_identities, channel, channel_event_sequence, - channel_members, community, deletion, dm, event, feed, git_repo, managed_publication, - moderation, partition, product_feedback, push, reaction, relay_admin_actions, relay_invite, - relay_members, relay_operators, reminder, replaceable, thread, usage, user, user_stop, + admin_moderation, allowlist, api_token, archived_identities, artifact, channel, + channel_event_sequence, channel_members, community, deletion, dm, event, feed, git_repo, + managed_publication, moderation, operator_listener, partition, personal_read, product_feedback, + push, reaction, read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, + reminder, replaceable, storage_accounting, thread, thread_window, usage, user, user_stop, workflow, }; @@ -46,13 +77,15 @@ pub use allowlist::AllowlistEntry; pub use api_token::{ApiTokenRecord, TokenSummary}; pub use community::{ ArchivedCommunityRecord, CommunityRecord, CreateCommunityWithOwnerResult, - CreatedCommunityRecord, EnsuredCommunityRecord, OwnedCommunityRecord, + CreatedCommunityRecord, EnsuredCommunityRecord, OwnedCommunityRecord, UnarchiveCommunityResult, UnarchivedCommunityRecord, }; pub use error::{DbError, Result}; +pub use event::{ChannelHeadPrecondition, ChannelHeadWriteStatus}; pub use event::{EventQuery, DEFAULT_MAX_PAGE_LIMIT}; pub use reaction::ReactionEventInsertOutcome; pub use reminder::DueReminder; +pub use store::event_follow_up::PUSH_MATCH_KINDS; pub use usage::UsageMetricsLeader; use buzz_core::CommunityId; diff --git a/crates/buzz-db/src/runtime/admitted_tx.rs b/crates/buzz-db/src/runtime/admitted_tx.rs new file mode 100644 index 00000000000..d1e266d3fe9 --- /dev/null +++ b/crates/buzz-db/src/runtime/admitted_tx.rs @@ -0,0 +1,193 @@ +//! Community-admitted write transactions. + +use std::collections::BTreeSet; + +use buzz_core::CommunityId; +use sqlx::{PgConnection, Postgres, Transaction}; +use uuid::Uuid; + +use crate::deletion::{DeletionStore, ServingWriteLease}; +use crate::Result; + +/// A transaction that has passed community write admission. +/// +/// Its only constructors take the shared community admission lock (or +/// validate a serving write lease) on the transaction they wrap, for the +/// community they record, so construction and admission are one step. +/// Write helpers take `&mut AdmittedTx` and read the community from it, +/// so the compiler rejects a raw [`sqlx::Transaction`] or a transaction +/// admitted for a different community. +/// +/// Outside this crate the value exposes neither the inner transaction nor its +/// connection, so code there can't swap in another connection or run +/// statements on it, and [`AdmittedTx::commit`] and [`AdmittedTx::rollback`] +/// are the only ways it can end the transaction. Inside the crate, the +/// `conn()` accessor hands statements the connection; the type can't stop +/// crate code from issuing a raw `COMMIT` through it, so the database +/// community write fences remain the backstop while deployed. Internal writers +/// must preserve this boundary and use `commit()` for staged follow-up work. +/// Dropping the value without committing rolls back, as with [`sqlx::Transaction`]. +/// +/// These are live regressions for the guarantee. Event-write helpers accept an +/// admitted transaction: +/// +/// ```no_run +/// async fn write(tx: &mut buzz_db::AdmittedTx, event: &nostr::Event) { +/// let _ = buzz_db::event::insert_event_in_transaction(tx, event, None).await; +/// } +/// ``` +/// +/// but not a raw transaction, which carries no proof of admission: +/// +/// ```compile_fail +/// async fn write(tx: &mut sqlx::Transaction<'static, sqlx::Postgres>, event: &nostr::Event) { +/// let _ = buzz_db::event::insert_event_in_transaction(tx, event, None).await; +/// } +/// ``` +/// +/// Code outside the crate cannot construct one through a conversion: +/// +/// ```compile_fail +/// fn forge(tx: sqlx::Transaction<'static, sqlx::Postgres>) -> buzz_db::AdmittedTx { +/// tx.into() +/// } +/// ``` +/// +/// and cannot reach the connection to swap it out, through a dereference: +/// +/// ```compile_fail +/// fn swap(tx: &mut buzz_db::AdmittedTx, other: &mut sqlx::PgConnection) { +/// std::mem::swap(&mut **tx, other); +/// } +/// ``` +/// +/// or through `AsMut`: +/// +/// ```compile_fail +/// fn swap(tx: &mut buzz_db::AdmittedTx, other: &mut sqlx::PgConnection) { +/// std::mem::swap(AsMut::::as_mut(tx), other); +/// } +/// ``` +#[must_use = "dropping an AdmittedTx rolls it back; call commit()"] +pub struct AdmittedTx { + tx: Transaction<'static, Postgres>, + community: CommunityId, + /// Channels whose TTL deadline [`AdmittedTx::commit`] refreshes. + ttl_refresh_channels: BTreeSet, + push_enqueue: Option, + push_events: Vec>, +} + +impl AdmittedTx { + /// Take the shared community admission lock on `tx` and wrap it. + pub(super) async fn admit( + mut tx: Transaction<'static, Postgres>, + store: &DeletionStore, + community: CommunityId, + ) -> Result { + store.guard_transaction(&mut tx, community).await?; + Ok(Self { + tx, + community, + ttl_refresh_channels: BTreeSet::new(), + push_enqueue: None, + push_events: Vec::new(), + }) + } + + /// Validate `lease` on `tx` under the community admission lock and wrap + /// it for the lease's community. + pub(super) async fn admit_with_serving_lease( + mut tx: Transaction<'static, Postgres>, + store: &DeletionStore, + lease: &ServingWriteLease, + ) -> Result { + store + .guard_transaction_with_serving_lease(&mut tx, lease) + .await?; + Ok(Self { + tx, + community: lease.community_id, + ttl_refresh_channels: BTreeSet::new(), + push_enqueue: None, + push_events: Vec::new(), + }) + } + + pub(crate) fn set_push_enqueue(&mut self, producer: Option) { + self.push_enqueue = producer; + } + + pub(crate) fn record_push_event(&mut self, event_id: &[u8], kind: i32) { + if self.push_enqueue.is_some() + && crate::store::event_follow_up::PUSH_MATCH_KINDS.contains(&kind) + { + // Bound transaction-local staging as well as the shared worker queue. + if self.push_events.len() < super::push_enqueue::CAPACITY { + self.push_events.push(event_id.to_vec()); + } else { + super::push_enqueue::record_drop("transaction_full"); + } + } + } + + /// The community this transaction was admitted for. + pub fn community(&self) -> CommunityId { + self.community + } + + /// The admitted connection, for statements inside this crate. + /// + /// Crate-private on purpose: a public `&mut PgConnection` would let safe + /// code `std::mem::swap` another connection in while keeping the proof of + /// admission. + pub(crate) fn conn(&mut self) -> &mut PgConnection { + &mut self.tx + } + + /// Record that an event committed with this transaction belongs to + /// `channel_id`, so [`AdmittedTx::commit`] refreshes the channel's TTL. + pub(crate) fn record_channel_event(&mut self, channel_id: Option, kind: i32) { + if let Some(channel) = crate::store::event_follow_up::ttl_refresh_channel(channel_id, kind) + { + self.ttl_refresh_channels.insert(channel); + } + } + + /// Commit the transaction. This is the only commit path for admitted + /// writes. + /// + /// Refreshes the TTL of every channel that received an event first, as + /// the last statement before COMMIT. + pub async fn commit(mut self) -> Result<()> { + if !self.ttl_refresh_channels.is_empty() { + crate::store::event_follow_up::refresh_channel_ttls( + &mut self.tx, + self.community, + &self.ttl_refresh_channels, + ) + .await?; + } + self.tx.commit().await?; + if let Some(producer) = self.push_enqueue { + for event_id in self.push_events { + producer.submit(self.community, event_id); + } + } + Ok(()) + } + + /// Roll the transaction back explicitly. + pub async fn rollback(self) -> Result<()> { + self.tx.rollback().await?; + Ok(()) + } +} + +impl std::fmt::Debug for AdmittedTx { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AdmittedTx") + .field("community", &self.community) + .finish_non_exhaustive() + } +} diff --git a/crates/buzz-db/src/runtime/cold_start.rs b/crates/buzz-db/src/runtime/cold_start.rs new file mode 100644 index 00000000000..5ddcd3ccf17 --- /dev/null +++ b/crates/buzz-db/src/runtime/cold_start.rs @@ -0,0 +1,204 @@ +//! Bounded cold database startup for run-once operator workers. +//! +//! A freshly scheduled worker pod (no mesh sidecar, cold DNS) can need more +//! than the relay's three-second acquisition budget to open its first +//! connection. Workers that start, do bounded work, and exit share this +//! connector so a slow first connection is waited out and transient transport +//! failures are retried, while configuration, authentication, TLS, and +//! protocol errors during the dial still fail immediately. SQLx treats a +//! failed session-setup hook (`after_connect`) as retryable until the +//! acquire deadline, so such failures surface here as timeouts and are +//! retried within the same bounded budget. +//! +//! Startup attempts are reported as JSON lines on stderr because these +//! command-line workers do not install a tracing subscriber. + +use std::future::Future; +use std::io::ErrorKind; +use std::time::Duration; + +use tokio::time::{sleep, timeout, Instant}; + +use super::{Db, DbConfig}; +use crate::DbError; + +const ACQUIRE_TIMEOUT: Duration = Duration::from_secs(30); +const RETRY_DELAYS: [Duration; 2] = [Duration::from_secs(2), Duration::from_secs(5)]; + +/// A run-once worker could not establish its database pool. +/// +/// The message carries only a bounded classification: driver messages and +/// URLs can contain credentials. The driver error stays available as the +/// [`std::error::Error::source`]. +#[derive(Debug, thiserror::Error)] +#[error( + "{worker} database startup failed after {attempts} attempt(s) and {elapsed_ms}ms ({class})" +)] +pub struct ColdStartError { + worker: &'static str, + attempts: usize, + elapsed_ms: u128, + class: &'static str, + #[source] + source: DbError, +} + +impl Db { + /// Connect a run-once worker's pool with a bounded cold-start budget. + /// + /// The pool keeps the caller's size and session policy, opens no idle + /// spare connections, and waits up to 30 seconds per acquisition. Startup + /// timeouts and transient transport failures are retried at most twice, + /// after two and five seconds, so startup waits at most 97 seconds. + /// `worker` prefixes the stderr startup events, for example + /// `deletion_db_connect_failed`. + /// + /// Only initial connection establishment is retried. Once a caller holds + /// a session-bound lock or lease, reconnecting would lose that fence. + pub async fn connect_cold_start( + config: DbConfig, + worker: &'static str, + ) -> std::result::Result { + let config = cold_start_config(config); + connect_with_retry(worker, || Db::new(&config)).await + } +} + +fn cold_start_config(config: DbConfig) -> DbConfig { + DbConfig { + // A run-once worker only needs connections it actually uses; idle + // replacements would also contend with a slow cold start. + min_connections: 0, + acquire_timeout_secs: ACQUIRE_TIMEOUT.as_secs(), + ..config + } +} + +async fn connect_with_retry( + worker: &'static str, + mut connect: Connect, +) -> std::result::Result +where + Connect: FnMut() -> Attempt, + Attempt: Future>, +{ + let started = Instant::now(); + // Three attempts of at most 30s, plus 2s and 5s backoffs: at most 97s. + for attempt in 0..=RETRY_DELAYS.len() { + let attempt_started = Instant::now(); + eprintln!( + "{}", + serde_json::json!({ + "event": format!("{worker}_db_connect_started"), + "stage": "db_connect", + "attempt": attempt + 1, + "timeout_ms": ACQUIRE_TIMEOUT.as_millis(), + }) + ); + // Bound the entire initialization future, including session setup. + let result = timeout(ACQUIRE_TIMEOUT, connect()) + .await + .unwrap_or_else(|_| Err(sqlx::Error::PoolTimedOut.into())); + match result { + Ok(db) => { + eprintln!( + "{}", + serde_json::json!({ + "event": format!("{worker}_db_connect_completed"), + "stage": "db_connect", + "attempt": attempt + 1, + "attempt_elapsed_ms": attempt_started.elapsed().as_millis(), + "elapsed_ms": started.elapsed().as_millis(), + }) + ); + return Ok(db); + } + Err(error) => { + let delay = RETRY_DELAYS + .get(attempt) + .copied() + .filter(|_| retryable(&error)); + let class = error_class(&error); + // Avoid raw connection errors/URLs: configuration and driver + // messages can contain credentials. Keep the source on the + // returned error, but print only this bounded classification. + eprintln!( + "{}", + serde_json::json!({ + "event": format!("{worker}_db_connect_failed"), + "stage": "db_connect", + "attempt": attempt + 1, + "attempt_elapsed_ms": attempt_started.elapsed().as_millis(), + "elapsed_ms": started.elapsed().as_millis(), + "error_class": class, + "io_kind": match &error { + DbError::Sqlx(sqlx::Error::Io(error)) => Some(format!("{:?}", error.kind())), + _ => None, + }, + "sqlstate": match &error { + DbError::Sqlx(sqlx::Error::Database(error)) => error.code(), + _ => None, + }, + "retry_in_ms": delay.map(|value| value.as_millis()), + }) + ); + match delay { + Some(delay) => sleep(delay).await, + None => { + return Err(ColdStartError { + worker, + attempts: attempt + 1, + elapsed_ms: started.elapsed().as_millis(), + class, + source: error, + }); + } + } + } + } + } + unreachable!("the last connection attempt always returns") +} + +fn retryable(error: &DbError) -> bool { + match error { + DbError::Sqlx(sqlx::Error::PoolTimedOut) => true, + // SQLx already backs off on connection refusal and transient server + // errors. Other transport/resolver failures may also be transient; + // allow only the bounded startup retries, excluding local input and + // permission errors. Unknown resolver errors are not labeled as DNS. + DbError::Sqlx(sqlx::Error::Io(error)) => !matches!( + error.kind(), + ErrorKind::InvalidInput + | ErrorKind::InvalidData + | ErrorKind::PermissionDenied + | ErrorKind::NotFound + | ErrorKind::Unsupported + ), + // Includes authentication, TLS, URL configuration and protocol errors + // raised while dialing. Session-setup failures arrive as + // `PoolTimedOut` (see the module docs). + _ => false, + } +} + +fn error_class(error: &DbError) -> &'static str { + match error { + DbError::Sqlx(sqlx::Error::PoolTimedOut) => "timeout", + DbError::Sqlx(sqlx::Error::Io(_)) => "io", + DbError::Sqlx(sqlx::Error::Tls(_)) => "tls", + DbError::Sqlx(sqlx::Error::Configuration(_)) => "configuration", + DbError::Sqlx(sqlx::Error::Database(error)) => { + if error.code().is_some_and(|code| code.starts_with("28")) { + "authentication" + } else { + "database" + } + } + DbError::Sqlx(sqlx::Error::Protocol(_)) => "protocol", + _ => "other", + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/buzz-db/src/runtime/cold_start/tests.rs b/crates/buzz-db/src/runtime/cold_start/tests.rs new file mode 100644 index 00000000000..5060c7c9809 --- /dev/null +++ b/crates/buzz-db/src/runtime/cold_start/tests.rs @@ -0,0 +1,204 @@ +use std::borrow::Cow; +use std::cell::Cell; + +use super::*; + +const WORKER: &str = "test_worker"; + +#[test] +fn cold_start_overrides_do_not_change_relay_defaults_pool_size_or_session_policy() { + let defaults = DbConfig::default(); + let worker = cold_start_config(DbConfig { + max_connections: 7, + lock_timeout_ms: 123, + idle_txn_timeout_ms: 456, + statement_timeout_ms: 789, + ..defaults.clone() + }); + assert_eq!(worker.max_connections, 7); + assert_eq!(worker.min_connections, 0); + assert_eq!(worker.acquire_timeout_secs, 30); + assert_eq!(worker.lock_timeout_ms, 123); + assert_eq!(worker.idle_txn_timeout_ms, 456); + assert_eq!(worker.statement_timeout_ms, 789); + assert_eq!(defaults.max_connections, 20); + assert_eq!(defaults.min_connections, 2); + assert_eq!(defaults.acquire_timeout_secs, 3); +} + +#[tokio::test(start_paused = true)] +async fn cold_connection_can_exceed_the_old_three_second_budget() { + let started = Instant::now(); + connect_with_retry(WORKER, || async { + sleep(Duration::from_secs(6)).await; + Ok(()) + }) + .await + .expect("cold startup succeeds"); + assert_eq!(started.elapsed(), Duration::from_secs(6)); +} + +#[tokio::test(start_paused = true)] +async fn transient_failure_backs_off_before_a_successful_attempt() { + let attempts = Cell::new(0); + let started = Instant::now(); + let result = connect_with_retry(WORKER, || { + attempts.set(attempts.get() + 1); + let attempt = attempts.get(); + async move { + if attempt == 1 { + Err(sqlx::Error::Io(ErrorKind::ConnectionReset.into()).into()) + } else { + Ok(42) + } + } + }) + .await; + assert_eq!(result.expect("second attempt succeeds"), 42); + assert_eq!(attempts.get(), 2); + assert_eq!(started.elapsed(), Duration::from_secs(2)); +} + +#[tokio::test(start_paused = true)] +async fn retry_exhaustion_propagates_the_last_error_after_three_attempts() { + let attempts = Cell::new(0); + let started = Instant::now(); + let error = connect_with_retry(WORKER, || { + attempts.set(attempts.get() + 1); + async { Err::<(), _>(sqlx::Error::Io(ErrorKind::ConnectionReset.into()).into()) } + }) + .await + .expect_err("exhausted startup must fail"); + assert_eq!(attempts.get(), 3); + assert_eq!(started.elapsed(), Duration::from_secs(7)); + assert!(error + .to_string() + .starts_with("test_worker database startup")); + assert!(error.to_string().contains("3 attempt(s)")); + assert!(matches!(error.source, DbError::Sqlx(sqlx::Error::Io(_)))); +} + +#[tokio::test(start_paused = true)] +async fn hung_initialization_is_bounded_to_97_seconds_including_backoff() { + let attempts = Cell::new(0); + let started = Instant::now(); + let error = connect_with_retry(WORKER, || { + attempts.set(attempts.get() + 1); + std::future::pending::>() + }) + .await + .expect_err("hung connection setup must time out"); + assert_eq!(attempts.get(), 3); + assert_eq!(started.elapsed(), Duration::from_secs(97)); + assert!(matches!( + error.source, + DbError::Sqlx(sqlx::Error::PoolTimedOut) + )); +} + +#[tokio::test(start_paused = true)] +async fn permanent_errors_fail_immediately_and_do_not_expose_connection_details() { + let attempts = Cell::new(0); + let started = Instant::now(); + for driver_error in [ + sqlx::Error::Configuration("sensitive-url".into()), + sqlx::Error::Tls("sensitive-certificate".into()), + sqlx::Error::Protocol("sensitive-server-reply".into()), + sqlx::Error::Io(ErrorKind::PermissionDenied.into()), + ] { + let mut error = Some(driver_error); + let result = connect_with_retry(WORKER, || { + attempts.set(attempts.get() + 1); + let error = error.take().expect("permanent errors must not retry"); + async move { Err::<(), _>(error.into()) } + }) + .await + .expect_err("permanent error"); + assert!(!result.to_string().contains("sensitive")); + } + assert_eq!(attempts.get(), 4); + assert_eq!(started.elapsed(), Duration::ZERO); +} + +#[derive(Debug, thiserror::Error)] +#[error("sensitive server message")] +struct ServerError(&'static str); + +impl sqlx::error::DatabaseError for ServerError { + fn message(&self) -> &str { + "sensitive server message" + } + + fn code(&self) -> Option> { + Some(Cow::Borrowed(self.0)) + } + + fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) { + self + } + + fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) { + self + } + + fn into_error(self: Box) -> Box { + self + } + + fn kind(&self) -> sqlx::error::ErrorKind { + sqlx::error::ErrorKind::Other + } +} + +#[test] +fn classifier_table_covers_every_retry_and_class_arm() { + let io = |kind: ErrorKind| DbError::Sqlx(sqlx::Error::Io(kind.into())); + let cases: Vec<(DbError, bool, &str)> = vec![ + (DbError::Sqlx(sqlx::Error::PoolTimedOut), true, "timeout"), + (io(ErrorKind::ConnectionReset), true, "io"), + (io(ErrorKind::ConnectionRefused), true, "io"), + (io(ErrorKind::ConnectionAborted), true, "io"), + (io(ErrorKind::TimedOut), true, "io"), + (io(ErrorKind::UnexpectedEof), true, "io"), + (io(ErrorKind::Other), true, "io"), + (io(ErrorKind::InvalidInput), false, "io"), + (io(ErrorKind::InvalidData), false, "io"), + (io(ErrorKind::PermissionDenied), false, "io"), + (io(ErrorKind::NotFound), false, "io"), + (io(ErrorKind::Unsupported), false, "io"), + (DbError::Sqlx(sqlx::Error::Tls("x".into())), false, "tls"), + ( + DbError::Sqlx(sqlx::Error::Configuration("x".into())), + false, + "configuration", + ), + ( + DbError::Sqlx(sqlx::Error::Protocol("x".into())), + false, + "protocol", + ), + ( + DbError::Sqlx(sqlx::Error::Database(Box::new(ServerError("28P01")))), + false, + "authentication", + ), + ( + DbError::Sqlx(sqlx::Error::Database(Box::new(ServerError("28000")))), + false, + "authentication", + ), + ( + DbError::Sqlx(sqlx::Error::Database(Box::new(ServerError("53300")))), + false, + "database", + ), + (DbError::Sqlx(sqlx::Error::RowNotFound), false, "other"), + ]; + for (error, retry, class) in cases { + assert_eq!( + (retryable(&error), error_class(&error)), + (retry, class), + "{error:?}" + ); + } +} diff --git a/crates/buzz-db/src/runtime/connection_observability.rs b/crates/buzz-db/src/runtime/connection_observability.rs new file mode 100644 index 00000000000..a1ab04022fd --- /dev/null +++ b/crates/buzz-db/src/runtime/connection_observability.rs @@ -0,0 +1,344 @@ +//! Fixed-vocabulary metrics for writer-pool connection setup. +//! +//! SQLx exposes the point immediately after a physical connection succeeds, +//! but it does not expose a callback immediately before each physical dial. +//! Consequently, `physical_connect` is a success milestone rather than a +//! duration phase. The aggregate `writer_pool` phase owns failures that occur +//! before `after_connect`, while the session phases own their exact failures. + +use std::time::{Duration, Instant}; + +use super::DbPoolRole; + +/// Fixed writer connection-setup steps. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DbConnectionStep { + /// Construct the writer pool and satisfy its initial minimum size. + WriterPool, + /// A physical connection has completed DNS/network/TLS/authentication. + PhysicalConnect, + /// Install the created-at replica-fence floor. + CreatedAtFloor, + /// Install lock, idle-transaction, and statement timeouts. + SessionTimeouts, + /// Verify READ COMMITTED transaction isolation. + Isolation, + /// The physical connection passed every required session premise. + Ready, +} + +impl DbConnectionStep { + /// Complete metric-label vocabulary. + pub const ALL: [Self; 6] = [ + Self::WriterPool, + Self::PhysicalConnect, + Self::CreatedAtFloor, + Self::SessionTimeouts, + Self::Isolation, + Self::Ready, + ]; + + /// Stable metric label. + pub const fn as_str(self) -> &'static str { + match self { + Self::WriterPool => "writer_pool", + Self::PhysicalConnect => "physical_connect", + Self::CreatedAtFloor => "created_at_floor", + Self::SessionTimeouts => "session_timeouts", + Self::Isolation => "isolation", + Self::Ready => "ready", + } + } +} + +/// Bounded terminal outcome for a connection-setup step. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DbConnectionOutcome { + /// The step completed successfully. + Succeeded, + /// The step failed. + Failed, + /// The aggregate pool deadline expired. + TimedOut, + /// The owning future was dropped before a terminal. + Cancelled, +} + +impl DbConnectionOutcome { + /// Stable metric label. + pub const fn as_str(self) -> &'static str { + match self { + Self::Succeeded => "succeeded", + Self::Failed => "failed", + Self::TimedOut => "timed_out", + Self::Cancelled => "cancelled", + } + } +} + +/// Valid role/step pairs with an explicit start counter. +pub const CONNECTION_STARTED_STEPS: [(DbPoolRole, DbConnectionStep); 4] = [ + (DbPoolRole::Writer, DbConnectionStep::WriterPool), + (DbPoolRole::Writer, DbConnectionStep::CreatedAtFloor), + (DbPoolRole::Writer, DbConnectionStep::SessionTimeouts), + (DbPoolRole::Writer, DbConnectionStep::Isolation), +]; + +/// Valid role/step pairs with a duration histogram. +pub const CONNECTION_DURATION_STEPS: [(DbPoolRole, DbConnectionStep); 4] = CONNECTION_STARTED_STEPS; + +/// Valid role/step/outcome terminal combinations. +pub const CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutcome); 15] = [ + ( + DbPoolRole::Writer, + DbConnectionStep::WriterPool, + DbConnectionOutcome::Succeeded, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::WriterPool, + DbConnectionOutcome::Failed, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::WriterPool, + DbConnectionOutcome::TimedOut, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::WriterPool, + DbConnectionOutcome::Cancelled, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::PhysicalConnect, + DbConnectionOutcome::Succeeded, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::CreatedAtFloor, + DbConnectionOutcome::Succeeded, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::CreatedAtFloor, + DbConnectionOutcome::Failed, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::CreatedAtFloor, + DbConnectionOutcome::Cancelled, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::SessionTimeouts, + DbConnectionOutcome::Succeeded, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::SessionTimeouts, + DbConnectionOutcome::Failed, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::SessionTimeouts, + DbConnectionOutcome::Cancelled, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::Isolation, + DbConnectionOutcome::Succeeded, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::Isolation, + DbConnectionOutcome::Failed, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::Isolation, + DbConnectionOutcome::Cancelled, + ), + ( + DbPoolRole::Writer, + DbConnectionStep::Ready, + DbConnectionOutcome::Succeeded, + ), +]; + +/// Four start counters + four 13-series histograms + fifteen terminal counters. +pub const CONNECTION_RAW_SERIES_PER_POD: usize = 4 + (4 * 13) + 15; + +pub(crate) struct DbConnectionStepAttempt { + pool_role: DbPoolRole, + step: DbConnectionStep, + started: Instant, + finished: bool, +} + +impl DbConnectionStepAttempt { + pub(crate) fn start(pool_role: DbPoolRole, step: DbConnectionStep) -> Self { + metrics::counter!( + "buzz_db_connection_step_started_total", + "pool_role" => pool_role.as_str(), + "step" => step.as_str(), + ) + .increment(1); + Self { + pool_role, + step, + started: Instant::now(), + finished: false, + } + } + + pub(crate) fn succeed(self) { + self.finish(DbConnectionOutcome::Succeeded); + } + + pub(crate) fn fail(self) { + self.finish(DbConnectionOutcome::Failed); + } + + pub(crate) fn time_out(self) { + self.finish(DbConnectionOutcome::TimedOut); + } + + fn finish(mut self, outcome: DbConnectionOutcome) { + record_terminal( + self.pool_role, + self.step, + outcome, + Some(self.started.elapsed()), + ); + self.finished = true; + } +} + +impl Drop for DbConnectionStepAttempt { + fn drop(&mut self) { + if self.finished { + return; + } + let outcome = if std::thread::panicking() { + DbConnectionOutcome::Failed + } else { + DbConnectionOutcome::Cancelled + }; + record_terminal( + self.pool_role, + self.step, + outcome, + Some(self.started.elapsed()), + ); + self.finished = true; + } +} + +pub(crate) fn record_milestone(pool_role: DbPoolRole, step: DbConnectionStep) { + record_terminal(pool_role, step, DbConnectionOutcome::Succeeded, None); +} + +fn record_terminal( + pool_role: DbPoolRole, + step: DbConnectionStep, + outcome: DbConnectionOutcome, + elapsed: Option, +) { + metrics::counter!( + "buzz_db_connection_step_attempts_total", + "pool_role" => pool_role.as_str(), + "step" => step.as_str(), + "outcome" => outcome.as_str(), + ) + .increment(1); + if let Some(elapsed) = elapsed { + metrics::histogram!( + "buzz_db_connection_step_duration_seconds", + "pool_role" => pool_role.as_str(), + "step" => step.as_str(), + ) + .record(elapsed.as_secs_f64()); + } +} + +pub(crate) fn classify_pool_outcome(error: &sqlx::Error) -> DbConnectionOutcome { + if matches!(error, sqlx::Error::PoolTimedOut) { + DbConnectionOutcome::TimedOut + } else { + DbConnectionOutcome::Failed + } +} + +#[cfg(test)] +mod tests { + use super::*; + use metrics_util::debugging::{DebugValue, DebuggingRecorder}; + + #[test] + fn vocabulary_and_series_budget_are_frozen() { + assert_eq!( + DbConnectionStep::ALL.map(DbConnectionStep::as_str), + [ + "writer_pool", + "physical_connect", + "created_at_floor", + "session_timeouts", + "isolation", + "ready", + ] + ); + assert_eq!(CONNECTION_RAW_SERIES_PER_POD, 71); + } + + #[test] + fn dropped_step_is_cancelled_exactly_once_without_sensitive_labels() { + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let attempt = + DbConnectionStepAttempt::start(DbPoolRole::Writer, DbConnectionStep::CreatedAtFloor); + drop(attempt); + + let metrics = snapshotter.snapshot().into_vec(); + assert_eq!(metrics.len(), 3); + for (key, _, _, value) in metrics { + let labels = key + .key() + .labels() + .map(|label| (label.key(), label.value())) + .collect::>(); + assert_eq!(labels.get("pool_role"), Some(&"writer")); + assert_eq!(labels.get("step"), Some(&"created_at_floor")); + assert!(!labels.contains_key("reason")); + assert!(!labels.contains_key("connection_ordinal")); + match value { + DebugValue::Counter(value) => { + assert_eq!(value, 1); + if key.key().name() == "buzz_db_connection_step_attempts_total" { + assert_eq!(labels.get("outcome"), Some(&"cancelled")); + } + } + DebugValue::Histogram(values) => assert_eq!(values.len(), 1), + DebugValue::Gauge(_) => panic!("connection setup has no gauges"), + } + } + } + + #[test] + fn pool_timeout_is_distinguished_from_other_failures() { + assert_eq!( + classify_pool_outcome(&sqlx::Error::PoolTimedOut), + DbConnectionOutcome::TimedOut + ); + assert_eq!( + classify_pool_outcome(&sqlx::Error::PoolClosed), + DbConnectionOutcome::Failed + ); + let io = sqlx::Error::Io(std::io::Error::new( + std::io::ErrorKind::ConnectionRefused, + "postgres://secret-user:secret-password@example.invalid/private", + )); + assert_eq!(classify_pool_outcome(&io), DbConnectionOutcome::Failed); + } +} diff --git a/crates/buzz-db/src/runtime/follow_up_retirement_tests.rs b/crates/buzz-db/src/runtime/follow_up_retirement_tests.rs new file mode 100644 index 00000000000..7f04c118b3e --- /dev/null +++ b/crates/buzz-db/src/runtime/follow_up_retirement_tests.rs @@ -0,0 +1,188 @@ +//! Upgrade contracts for the event follow-up trigger retirements: push +//! (0068), then channel TTL (0070). +use super::postgres_tests::{connect_test_pool, reset_public_schema}; +use super::run_migrations_through; +use sqlx::PgPool; + +async fn ttl_definitions(pool: &PgPool) -> Vec<(String, String)> { + sqlx::query_as( + "SELECT tgrelid::regclass::text, pg_get_triggerdef(oid) FROM pg_trigger \ + WHERE tgname = 'events_refresh_channel_ttl' ORDER BY 1", + ) + .fetch_all(pool) + .await + .expect("read TTL triggers") +} + +async fn push_trigger_count(pool: &PgPool) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM pg_trigger WHERE tgname = 'events_enqueue_push_match'") + .fetch_one(pool) + .await + .expect("count push triggers") +} + +/// Insert a channel with an expired TTL deadline, then a raw `INSERT INTO +/// events` on it that bypasses the application follow-up. Returns whether the +/// database itself pushed the deadline forward. +async fn raw_insert_refreshes_expired_ttl(pool: &PgPool, content: &str) -> bool { + let community = uuid::Uuid::new_v4(); + let channel = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("retirement-{community}.example")) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO channels (id, community_id, name, created_by, ttl_seconds, ttl_deadline) \ + VALUES ($1, $2, 'ttl', $3, 60, clock_timestamp() - interval '1 day')", + ) + .bind(channel) + .bind(community) + .bind([11_u8; 32]) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, channel_id) \ + VALUES ($1, $2, $3, now(), 9, '[]', $4, $5, $6)", + ) + .bind(community) + .bind([12_u8; 32]) + .bind([11_u8; 32]) + .bind(content) + .bind([13_u8; 64]) + .bind(channel) + .execute(pool) + .await + .unwrap(); + sqlx::query_scalar( + "SELECT ttl_deadline > clock_timestamp() FROM channels WHERE id=$1 AND community_id=$2", + ) + .bind(channel) + .bind(community) + .fetch_one(pool) + .await + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_push_retirement_preserves_ttl_and_published_checksums() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 67) + .await + .expect("apply published migrations"); + assert!( + push_trigger_count(&pool).await > 1, + "parent and partition triggers exist before upgrade" + ); + let ttl_before = ttl_definitions(&pool).await; + assert!(ttl_before.len() > 1); + let function_before: String = sqlx::query_scalar( + "SELECT pg_get_functiondef('refresh_channel_ttl_after_event_insert()'::regprocedure)", + ) + .fetch_one(&pool) + .await + .unwrap(); + let checksums_before: Vec<(i64, Vec)> = sqlx::query_as( + "SELECT version, checksum FROM _sqlx_migrations WHERE version <= 67 ORDER BY version", + ) + .fetch_all(&pool) + .await + .unwrap(); + + run_migrations_through(&pool, 68) + .await + .expect("retire push trigger"); + assert_eq!( + push_trigger_count(&pool).await, + 0, + "retired on parent and every partition" + ); + let function_absent: bool = + sqlx::query_scalar("SELECT to_regprocedure('enqueue_push_match_job()') IS NULL") + .fetch_one(&pool) + .await + .unwrap(); + assert!(function_absent); + assert_eq!(ttl_definitions(&pool).await, ttl_before); + let function_after: String = sqlx::query_scalar( + "SELECT pg_get_functiondef('refresh_channel_ttl_after_event_insert()'::regprocedure)", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(function_after, function_before); + let checksums_after: Vec<(i64, Vec)> = sqlx::query_as( + "SELECT version, checksum FROM _sqlx_migrations WHERE version <= 67 ORDER BY version", + ) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(checksums_after, checksums_before); + + // A raw writer has no application TTL follow-up. The preserved deferred + // trigger must still refresh its channel when the event commits. + assert!( + raw_insert_refreshes_expired_ttl(&pool, "TTL survives push retirement").await, + "raw inserts still refresh TTL after push retirement" + ); + pool.close().await; +} + +async fn ttl_function_present(pool: &PgPool) -> bool { + sqlx::query_scalar( + "SELECT to_regprocedure('refresh_channel_ttl_after_event_insert()') IS NOT NULL", + ) + .fetch_one(pool) + .await + .expect("look up TTL function") +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_ttl_retirement_drops_every_partition_trigger_and_keeps_checksums() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 69) + .await + .expect("apply published migrations"); + assert!( + ttl_definitions(&pool).await.len() > 1, + "parent and partition TTL triggers exist before upgrade" + ); + assert!(ttl_function_present(&pool).await); + let checksums_before: Vec<(i64, Vec)> = sqlx::query_as( + "SELECT version, checksum FROM _sqlx_migrations WHERE version <= 69 ORDER BY version", + ) + .fetch_all(&pool) + .await + .unwrap(); + + run_migrations_through(&pool, 70) + .await + .expect("retire TTL trigger"); + assert!( + ttl_definitions(&pool).await.is_empty(), + "retired on parent and every partition" + ); + assert!(!ttl_function_present(&pool).await); + assert_eq!(push_trigger_count(&pool).await, 0); + let checksums_after: Vec<(i64, Vec)> = sqlx::query_as( + "SELECT version, checksum FROM _sqlx_migrations WHERE version <= 69 ORDER BY version", + ) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(checksums_after, checksums_before); + + // With both triggers gone, a raw writer that skips the application + // follow-up no longer extends an ephemeral channel's deadline. + assert!( + !raw_insert_refreshes_expired_ttl(&pool, "TTL no longer refreshed by the database").await, + "raw inserts must not refresh TTL after 0070" + ); + pool.close().await; +} diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 4fa700ad411..aca69eb504b 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -82,9 +82,21 @@ where F: FnOnce(PgConnection) -> Fut, Fut: Future)>, { - let mut lock_conn = crate::observability::acquire(pool, crate::observability::PoolRole::Writer) - .await? - .detach(); + let mut lock_conn = crate::observability::acquire_writer_with_legacy_metrics( + pool, + crate::observability::WriterOperation::Bootstrap, + ) + .await? + .detach(); + // This dedicated connection intentionally waits for the current migration + // or schema-destruction owner and may then run long DDL. Exempt those two + // phases from runtime lock/statement budgets. Keep the idle-in-transaction + // timeout: a client wedged idle mid-migration is still a lock holder that + // should be reaped. The detached connection is closed below and never + // returns these session settings to the pool. + sqlx::raw_sql("SET lock_timeout = 0; SET statement_timeout = 0") + .execute(&mut lock_conn) + .await?; crate::observability::observe_advisory_lock( crate::observability::LockType::MigrationSchemaSafety, sqlx::query("SELECT pg_advisory_lock($1)") @@ -174,7 +186,11 @@ async fn reject_legacy_nip_rs_cardinality_ambiguity(conn: &mut PgConnection) -> } #[cfg(test)] -mod tests { +#[path = "follow_up_retirement_tests.rs"] +mod retirement_postgres_tests; + +#[cfg(test)] +mod postgres_tests { use super::*; use std::{ collections::BTreeSet, @@ -184,8 +200,8 @@ mod tests { const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 - /// Connection parameters parsed out of a `postgres://user:pass@host:port/db` - /// URL so the parity test can pass them to the `bin/pgschema` binary, which + /// Connection parameters parsed out of a PostgreSQL URL so the parity test + /// can pass them to the `bin/pgschema` binary, which /// takes discrete `--host/--port/--user/--password/--db` flags rather than a /// URL. Only the shapes this test emits (`BUZZ_TEST_DATABASE_URL` / /// `DATABASE_URL` / `TEST_DB_URL`) are supported. @@ -477,6 +493,9 @@ mod tests { "relay_admin_actions", "relay_admin_outbox", "relay_operator_audit", + "storage_accounting_snapshots", + "operator_listener_pubkeys", + "operator_listener_outbox", ] { if normalized[insert_pos..].contains(&format!("'{value}'")) { globals.insert(value.to_owned()); @@ -690,7 +709,81 @@ mod tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 45); + assert_eq!(migrations.len(), 70); + assert_eq!(migrations[69].version, 70); + let retire_ttl = strip_sql_comments(migrations[69].sql.as_str()); + for statement in [ + "SET LOCAL lock_timeout = '5s';", + "DROP TRIGGER events_refresh_channel_ttl ON events;", + "DROP FUNCTION refresh_channel_ttl_after_event_insert();", + ] { + assert!(retire_ttl.contains(statement), "0070 must run {statement}"); + } + let desired_schema = crate::test_support::desired_state_schema_sql(); + assert!(!desired_schema.contains("events_refresh_channel_ttl")); + assert!(!desired_schema.contains("refresh_channel_ttl_after_event_insert")); + assert_eq!(migrations[63].version, 64); + assert!(migrations[63].sql.as_str().contains("buzz.push_enabled")); + assert_eq!(migrations[64].version, 65); + assert!(migrations[64] + .sql + .as_str() + .contains("ALTER TABLE push_leases DROP COLUMN app_profile")); + assert_eq!(migrations[65].version, 66); + assert!(migrations[65].sql.as_str().contains("ADD COLUMN labels")); + assert_eq!(migrations[66].version, 67); + assert!(migrations[66] + .sql + .as_str() + .contains("ALTER TYPE channel_type ADD VALUE IF NOT EXISTS 'system'")); + assert_eq!(migrations[68].version, 69); + assert!(migrations[68] + .sql + .as_str() + .contains("CREATE FUNCTION profile_name_fields")); + assert_eq!(migrations[60].version, 61); + assert!(migrations[60] + .sql + .as_str() + .contains("CREATE TABLE personal_read_accounts")); + assert_eq!(migrations[61].version, 62); + assert!(migrations[61] + .sql + .as_str() + .contains("ALTER TABLE personal_read_accounts ADD COLUMN started_at")); + assert_eq!(migrations[62].version, 63); + assert!(migrations[62] + .sql + .as_str() + .contains("ADD COLUMN through_message_id")); + assert_eq!(migrations[53].version, 54); + assert_eq!(migrations[54].version, 55); + assert_eq!(migrations[55].version, 56); + assert_eq!(migrations[56].version, 57); + assert_eq!(migrations[57].version, 58); + assert_eq!(migrations[58].version, 59); + assert_eq!(migrations[59].version, 60); + assert!(migrations[53] + .sql + .as_str() + .contains("idx_thread_metadata_window")); + assert!(migrations[55] + .sql + .as_str() + .contains("community_deletion_owner_provenance")); + assert!(migrations[57].sql.as_str().contains("approval_origin")); + assert!(migrations[57] + .sql + .as_str() + .contains("community_deletion_requests_owner_preparable")); + assert!(migrations[58] + .sql + .as_str() + .contains("community_deletion_requests_owner_quota_reservations")); + assert!(migrations[59] + .sql + .as_str() + .contains("idx_relay_admin_actions_direct_request")); assert_eq!(migrations[0].version, 1); assert_eq!(&*migrations[0].description, "initial schema"); assert!(migrations[0] @@ -762,6 +855,11 @@ mod tests { .as_str() .contains("CREATE INDEX idx_events_tags_gin")); assert!(!migrations[0].sql.as_str().contains("idx_events_tags_gin")); + // schema.sql (CI / isolated relay bootstrap) must carry the same index, + // or e-tag reads there run on plans prod never sees. + assert!(crate::test_support::desired_state_schema_sql().contains( + "CREATE INDEX idx_events_tags_gin ON events USING GIN (tags jsonb_path_ops)" + )); // NIP-AM (kind 44200) FTS exclusion: additive migration, never folded // into 0001 — folding would change 0001's checksum and break brownfield @@ -918,7 +1016,7 @@ mod tests { assert!(migrations[32].sql.as_str().contains("kind = 30179")); assert!(migrations[32].sql.as_str().contains("search_tsv")); assert!(!migrations[0].sql.as_str().contains("30179")); - assert!(include_str!("../../../../schema/schema.sql") + assert!(crate::test_support::desired_state_schema_sql() .contains("kind IN (1059, 30179, 30300, 30350, 30622, 44100, 44101, 44200)")); // Public push-gateway authority is intentionally deployment-global and @@ -1061,7 +1159,7 @@ mod tests { .contains("CREATE INDEX relay_invites_expires_at_idx ON relay_invites (expires_at)")); assert!(!relay_invites.contains("_operator_global_tables")); - let desired_schema = include_str!("../../../../schema/schema.sql"); + let desired_schema = crate::test_support::desired_state_schema_sql(); assert!( desired_schema.contains("CREATE TABLE join_policy_acceptances"), "desired-state schema must include join-policy evidence used by invite claims", @@ -1152,17 +1250,28 @@ mod tests { // Fresh desired-state bootstrap must install the identical executable // fence as migration 0032. CI and isolated relay startup use schema.sql // without running migrations, so drift reopens rolling-deploy races. - fn extract_roster_fence(sql: &str) -> &str { - let fence_start = "CREATE OR REPLACE FUNCTION guard_channel_roster_snapshot()"; - let fence_end = " FOR EACH ROW EXECUTE FUNCTION guard_channel_roster_snapshot();"; - let start = sql.find(fence_start).expect("roster fence function"); - let relative_end = sql[start..].find(fence_end).expect("roster fence trigger"); - &sql[start..start + relative_end + fence_end.len()] + // The desired state keeps the function and its trigger in separate + // files, so compare each statement rather than one contiguous span. + fn extract_span<'a>(sql: &'a str, start: &str, end: &str) -> &'a str { + let begin = sql.find(start).expect("span start"); + let relative_end = sql[begin..].find(end).expect("span end"); + &sql[begin..begin + relative_end + end.len()] + } + for (start, end) in [ + ( + "CREATE OR REPLACE FUNCTION guard_channel_roster_snapshot()", + "$$ LANGUAGE plpgsql;", + ), + ( + "CREATE TRIGGER trg_events_guard_channel_roster_snapshot", + " FOR EACH ROW EXECUTE FUNCTION guard_channel_roster_snapshot();", + ), + ] { + assert_eq!( + extract_span(roster_fence, start, end), + extract_span(&desired_schema, start, end) + ); } - assert_eq!( - extract_roster_fence(roster_fence), - extract_roster_fence(desired_schema) - ); // The single-row heartbeat table is updated continuously. Prevent // autovacuum from truncating its heap so standby queries are not @@ -1199,8 +1308,6 @@ mod tests { "events_p_future", ] { for trigger in [ - "events_enqueue_push_match", - "events_refresh_channel_ttl", "events_created_at_floor", "community_write_fence_events", "trg_events_guard_channel_roster_snapshot", @@ -1284,6 +1391,112 @@ mod tests { "migration 39 must register relay_operator_audit in _operator_global_tables" ); + assert_eq!(migrations[45].version, 46); + let identity_foundation = migrations[45].sql.as_str(); + assert!(identity_foundation.contains("CREATE TABLE identity_bindings")); + assert!(identity_foundation.contains("CREATE TABLE identity_lifecycle_history")); + + assert_eq!(migrations[46].version, 47); + let authorization_foundation = migrations[46].sql.as_str(); + assert!(authorization_foundation.contains("CREATE TABLE authorization_events")); + assert!(authorization_foundation.contains("CREATE TABLE protected_object_authority")); + + // Brownfield relay databases created through SQLx still carry the + // production/sandbox constraint from 0015. Converge them to the same + // dogfood-only authority declared by the desired-state schema. + assert_eq!(migrations[47].version, 48); + let dogfood_profile = migrations[47].sql.as_str(); + assert!(dogfood_profile.contains("DELETE FROM push_gateway_delegations")); + assert!(dogfood_profile.contains("DELETE FROM push_gateway_installations")); + assert!(dogfood_profile + .contains("DROP CONSTRAINT push_gateway_installations_app_profile_check")); + assert!(dogfood_profile.contains("CHECK (app_profile = 'buzz-ios-dogfood')")); + assert!(!desired_schema.contains("app_profile")); + + // Drop the Phase-A NIP-FI relay-side authority ledger (0046 + 0047). + // OSS Buzz is stateless for identity (spec v2, PR #7214); the durable + // ledger tables are dead code. Restores community_write_fence_excluded_table + // to its pre-0046 body so the deletion catalog no longer includes the + // removed relations. + assert_eq!(migrations[48].version, 49); + let ledger_removal = migrations[48].sql.as_str(); + assert!(ledger_removal.contains("DROP TABLE authorization_operation_receipts")); + assert!(ledger_removal.contains("DROP TABLE identity_bindings")); + assert!(ledger_removal.contains("DROP TABLE authorization_events")); + assert!(ledger_removal + .contains("CREATE OR REPLACE FUNCTION community_write_fence_excluded_table")); + // The restored exclusion function must NOT list any NIP-FI relation. + assert!(!ledger_removal.contains("'authorization_operation_receipts'")); + assert!(!ledger_removal.contains("'identity_bindings'")); + assert_eq!(migrations[50].version, 51); + assert!(migrations[50] + .sql + .as_str() + .contains("CREATE TABLE storage_accounting_snapshots")); + assert_eq!(migrations[52].version, 53); + assert!(migrations[52] + .sql + .as_str() + .contains("ADD COLUMN hash_version SMALLINT")); + assert_eq!(migrations[54].version, 55); + assert!(migrations[54] + .sql + .as_str() + .contains("CREATE TABLE operator_listener_pubkeys")); + assert!(migrations[54] + .sql + .as_str() + .contains("CREATE TABLE operator_listener_outbox")); + assert!(migrations[54] + .sql + .as_str() + .contains("CREATE OR REPLACE FUNCTION community_write_fence_excluded_table")); + assert!(migrations[54] + .sql + .as_str() + .contains("'rate_limit_violations', 'operator_listener_outbox'")); + for index in [ + "operator_listener_pubkeys_target", + "operator_listener_pubkeys_created_at", + "operator_listener_outbox_due", + "operator_listener_outbox_recovery", + "operator_listener_outbox_created_at", + ] { + assert!( + migrations[54].sql.as_str().contains(index), + "migration 0055 must declare {index}" + ); + assert!( + desired_schema.contains(index), + "schema.sql must declare {index}" + ); + } + for index_shape in [ + "ON operator_listener_outbox (next_attempt_at, created_at, id)", + "ON operator_listener_outbox (lease_until, created_at, id)", + ] { + assert!( + migrations[54].sql.as_str().contains(index_shape), + "migration 0055 must declare {index_shape}" + ); + assert!( + desired_schema.contains(index_shape), + "schema.sql must declare {index_shape}" + ); + } + // schema.sql keeps the restored (pre-0046) deletion exclusions and also + // leaves the deployment-global listener outbox outside tenant fencing. + assert!( + desired_schema + .contains("'rate_limit_violations', 'operator_listener_outbox'\n ]::TEXT[])"), + "schema.sql must exclude the deployment-global listener outbox from tenant fencing" + ); + assert_eq!(migrations[56].version, 57); + assert!(migrations[56] + .sql + .as_str() + .contains("CREATE TABLE artifact_heads")); + assert_eq!(migrations[42].version, 43); let user_stop_events = migrations[42].sql.as_str(); assert!(user_stop_events.contains("CREATE TABLE user_stop_events")); @@ -1378,7 +1591,162 @@ mod tests { .sql .as_str() .contains("error_code")); - assert!(include_str!("../../../../schema/schema.sql").contains("error_code TEXT")); + assert!( + crate::test_support::desired_state_schema_sql().contains("error_code TEXT") + ); + } + + /// `schema/schema.sql` includes every desired-state file exactly once, and + /// `schema/tables/public/` (the SchemaBot schema directory's `public` + /// namespace) holds only one table per file: its CREATE TABLE plus the + /// CREATE INDEX statements on it. Types, functions, partitions, triggers + /// and seed rows belong in the sibling directories SchemaBot never reads. + #[test] + fn desired_state_schema_layout_is_complete_and_schemabot_shaped() { + use std::collections::BTreeSet; + + fn sql_files(dir: &std::path::Path, root: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read schema directory") { + let path = entry.expect("schema directory entry").path(); + if path.is_dir() { + sql_files(&path, root, out); + } else if path.extension().is_some_and(|ext| ext == "sql") { + let relative = path.strip_prefix(root).expect("schema-relative path"); + out.push(relative.to_str().expect("utf-8 path").replace('\\', "/")); + } + } + } + + let schema_dir = crate::test_support::desired_state_schema_dir(); + let manifest = + std::fs::read_to_string(schema_dir.join("schema.sql")).expect("read schema/schema.sql"); + let mut included = Vec::new(); + for line in manifest.lines() { + if let Some(include) = line.strip_prefix("\\i ") { + included.push(include.trim().to_owned()); + } + } + let included_set: BTreeSet<_> = included.iter().cloned().collect(); + assert_eq!( + included.len(), + included_set.len(), + "schema.sql includes a file twice" + ); + + let mut on_disk = Vec::new(); + sql_files(&schema_dir, &schema_dir, &mut on_disk); + let on_disk: BTreeSet<_> = on_disk.into_iter().filter(|f| f != "schema.sql").collect(); + assert_eq!( + on_disk, included_set, + "every schema/ file must be included by schema/schema.sql exactly once" + ); + + fn strip_comments(text: &str) -> String { + text.lines() + .map(|line| line.split_once("--").map_or(line, |(code, _)| code)) + .collect::>() + .join("\n") + } + + // Table and index DDL must live in its table file, where SchemaBot + // reads it. A merge conflict resolved by pasting DDL into the manifest, + // or DDL in a sibling directory, would still build and pass CI. + for line in strip_comments(&manifest).lines().map(str::trim) { + assert!( + line.is_empty() + || line.starts_with("\\i ") + || line.to_ascii_uppercase().starts_with("CREATE EXTENSION "), + "schema/schema.sql may only hold \\i includes and CREATE EXTENSION; \ + put table DDL in tables/public/
.sql: {line:.80}" + ); + } + let non_table_files = std::iter::once("schema.sql").chain( + included + .iter() + .map(String::as_str) + .filter(|f| !f.starts_with("tables/public/")), + ); + for file in non_table_files { + let text = std::fs::read_to_string(schema_dir.join(file)).expect("read schema file"); + for statement in strip_comments(&text).to_ascii_uppercase().split(';') { + let tokens: Vec<_> = statement.split_whitespace().collect(); + assert!( + !tokens.windows(2).any(|pair| matches!( + pair, + ["CREATE" | "UNIQUE", "INDEX"] | ["DROP" | "ALTER", "TABLE" | "INDEX"] + )), + "{file} may not create, alter or drop tables or indexes; \ + change tables/public/
.sql instead" + ); + let creates_table = tokens.iter().enumerate().any(|(i, token)| { + *token == "CREATE" + && tokens[i + 1..].iter().find(|t| { + !matches!(**t, "UNLOGGED" | "TEMP" | "TEMPORARY" | "GLOBAL" | "LOCAL") + }) == Some(&"TABLE") + }); + assert!( + !creates_table + || (file.starts_with("partitions/") + && tokens.windows(2).any(|pair| pair == ["PARTITION", "OF"])), + "{file} may not CREATE TABLE; only partitions/ may, and only PARTITION OF. \ + Declare tables in tables/public/
.sql" + ); + } + } + + let tables_dir = schema_dir.join("tables"); + for entry in std::fs::read_dir(&tables_dir).expect("read schema/tables") { + let path = entry.expect("schema/tables entry").path(); + assert!( + path.is_dir() && path.file_name().is_some_and(|name| name == "public"), + "schema/tables may contain only the `public` namespace: {}", + path.display() + ); + } + let mut tables = 0; + for file in included.iter().filter(|f| f.starts_with("tables/public/")) { + let table = file + .strip_prefix("tables/public/") + .and_then(|name| name.strip_suffix(".sql")) + .expect("table file name"); + let text = std::fs::read_to_string(schema_dir.join(file)).expect("read table file"); + let code = strip_comments(&text); + let mut creates = 0; + for statement in code + .split(';') + .map(|s| s.split_whitespace().collect::>().join(" ")) + { + if statement.is_empty() { + continue; + } + if let Some(rest) = statement.strip_prefix("CREATE TABLE ") { + assert!( + rest.starts_with(&format!("{table} (")) && !rest.contains(" PARTITION OF "), + "{file} may only create table {table}: {statement:.80}" + ); + creates += 1; + } else { + let index = statement + .strip_prefix("CREATE INDEX ") + .or_else(|| statement.strip_prefix("CREATE UNIQUE INDEX ")) + .unwrap_or_else(|| { + panic!("{file} may only hold CREATE TABLE/INDEX: {statement:.80}") + }); + assert!( + !index.starts_with("IF NOT EXISTS ") + && !index.starts_with("CONCURRENTLY "), + "{file} must use a plain CREATE INDEX (SchemaBot refuses IF NOT EXISTS and CONCURRENTLY): {statement:.80}" + ); + assert!( + index.contains(&format!(" ON {table} ")), + "{file} may only index {table}: {statement:.80}" + ); + } + } + assert_eq!(creates, 1, "{file} must create exactly one table"); + tables += 1; + } + assert!(tables > 0, "schema/tables/public declares no tables"); } #[test] @@ -1392,10 +1760,17 @@ mod tests { assert!(sql.contains("NEW.kind IN (9, 40002, 45001, 45003)")); assert!(!sql.contains("NEW.kind IN (7, 9, 1059, 40007, 46010)")); - let desired_schema = include_str!("../../../../schema/schema.sql"); + let desired_schema = crate::test_support::desired_state_schema_sql(); + assert!(!desired_schema.contains("enqueue_push_match_job")); + assert!(!desired_schema.contains("events_enqueue_push_match")); assert!(!desired_schema.contains("NEW.kind IN (7, 9, 1059, 40007, 46010)")); } + /// Fork migration 0045 (applied in production) widened the legacy push + /// trigger to the guest-notification kinds. Upstream's rollback gate + /// (renumbered 0064) resets that function and 0068 retires the trigger, so + /// 46040/46042 push eligibility now lives in the application allowlist + /// (`event_follow_up::PUSH_MATCH_KINDS`). 0045 stays byte-for-byte as history. #[test] fn push_match_trigger_adds_guest_notification_kinds_additively() { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); @@ -1408,8 +1783,16 @@ mod tests { let predicate = "NEW.kind IN (9, 40002, 45001, 45003, 46040, 46042)"; assert!(sql.contains("CREATE OR REPLACE FUNCTION enqueue_push_match_job")); assert!(sql.contains(predicate)); - let desired_schema = include_str!("../../../../schema/schema.sql"); - assert!(desired_schema.contains(predicate)); + let retire = migrations + .iter() + .find(|migration| migration.version == 68) + .expect("embedded migration 0068"); + assert!(retire + .sql + .as_str() + .contains("DROP TRIGGER events_enqueue_push_match ON events")); + let desired_schema = crate::test_support::desired_state_schema_sql(); + assert!(!desired_schema.contains(predicate)); } #[test] @@ -1669,6 +2052,48 @@ mod tests { ); } + #[test] + fn owner_deletion_auto_approval_migration_matches_desired_schema() { + let migration = MIGRATOR + .iter() + .find(|migration| migration.version == 58) + .expect("embedded migration 0058") + .sql + .as_ref() + .to_ascii_lowercase(); + let schema = crate::test_support::desired_state_schema_sql().to_ascii_lowercase(); + + for sql in [&migration, &schema] { + assert!(sql.contains("approval_origin text not null default 'operator'")); + assert!(sql.contains("approval_origin in ('operator', 'owner_automatic')")); + assert!(sql.contains("'submitted', 'approved', 'fenced'")); + assert!(sql.contains("community_deletion_requests_owner_preparable")); + assert!(sql.contains("request_origin = 'owner'")); + assert!(sql.contains("stage = 'submitted'")); + } + assert!(migration.contains("set local lock_timeout = '5s'")); + } + + #[test] + fn owner_deletion_quota_reservation_index_matches_desired_schema() { + let migration = MIGRATOR + .iter() + .find(|migration| migration.version == 59) + .expect("embedded migration 0059") + .sql + .as_ref() + .to_ascii_lowercase(); + let schema = crate::test_support::desired_state_schema_sql().to_ascii_lowercase(); + + for sql in [&migration, &schema] { + assert!(sql.contains("community_deletion_requests_owner_quota_reservations")); + assert!(sql.contains("request_origin = 'owner'")); + assert!(sql.contains("stage <> 'aborted'")); + assert!(sql.contains("include (community_id, completed_at)")); + } + assert!(migration.contains("set local lock_timeout = '5s'")); + } + /// Structural parity between migration 0029's deletion surface and the /// desired-state bootstrap schema (`schema/schema.sql`). /// @@ -1782,14 +2207,16 @@ mod tests { .expect("embedded migration 0029") .sql .as_ref(); - let workspace_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .and_then(std::path::Path::parent) - .expect("workspace root"); - let schema_sql = std::fs::read_to_string(workspace_root.join("schema/schema.sql")) - .expect("read schema/schema.sql"); + let migration_0056: &str = MIGRATOR + .iter() + .find(|migration| migration.version == 56) + .expect("embedded migration 0056") + .sql + .as_ref(); + let schema_sql = crate::test_support::desired_state_schema_sql(); let migration = surface(migration_0029); + let owner_admission_migration = surface(migration_0056); let managed_publication = surface( MIGRATOR .iter() @@ -1856,25 +2283,91 @@ mod tests { .tables .get(table) .unwrap_or_else(|| panic!("schema.sql is missing deletion table {table}")); - if table != "community_deletion_requests" { + if table != "community_deletion_requests" && table != "community_deletion_approvals" { assert_eq!( in_schema, definition, "schema.sql definition of {table} drifted from its additive migration" ); } } + let migration_approval_table = migration + .tables + .get("community_deletion_approvals") + .expect("0029 approval table"); + let schema_approval_table = schema + .tables + .get("community_deletion_approvals") + .expect("schema.sql approval table"); + for invariant in [ + "inventory_digest bytea not null check (length(inventory_digest) = 32)", + "foreign key (request_id, community_id, inventory_digest) references community_deletion_requests(id, community_id, inventory_digest) on delete restrict", + ] { + assert!( + migration_approval_table.contains(invariant), + "0029 deletion approvals are missing {invariant}" + ); + assert!( + schema_approval_table.contains(invariant), + "schema.sql deletion approvals are missing {invariant}" + ); + } + let migration_request_table = migration + .tables + .get("community_deletion_requests") + .expect("0029 deletion request table"); + for request_table in [ + migration_request_table, + schema + .tables + .get("community_deletion_requests") + .expect("schema.sql deletion request table"), + ] { + assert!( + request_table.contains("unique (id, community_id, inventory_digest)"), + "deletion requests must expose the exact composite approval target" + ); + } for (function, definition) in &migration.functions { let in_schema = schema .functions .get(function) .unwrap_or_else(|| panic!("schema.sql is missing deletion function {function}")); - if function != "community_write_fence_excluded_table" { + if function != "community_write_fence_excluded_table" + && function != "prevent_community_deletion_request_retargeting" + { assert_eq!( in_schema, definition, "schema.sql definition of {function}() drifted from migration 0029" ); } } + assert_eq!( + schema + .functions + .get("prevent_community_deletion_request_retargeting") + .expect("schema.sql deletion retargeting guard"), + owner_admission_migration + .functions + .get("prevent_community_deletion_request_retargeting") + .expect("0056 deletion retargeting guard"), + "schema.sql must carry the latest immutable owner-provenance guard" + ); + let request_table = schema + .tables + .get("community_deletion_requests") + .expect("schema.sql deletion request table"); + for owner_provenance_fragment in [ + "request_origin text not null default 'operator'", + "owner_pubkey text", + "mediating_operator_pubkey text", + "acknowledgement_version integer", + "constraint community_deletion_owner_provenance check", + ] { + assert!( + request_table.contains(owner_provenance_fragment), + "schema.sql deletion requests are missing {owner_provenance_fragment}" + ); + } for (trigger, definition) in &migration.triggers { let in_schema = schema .triggers @@ -1903,6 +2396,61 @@ mod tests { expected_fences.extend(managed_publication.fence_attachments); expected_fences.extend(user_stop_events.fence_attachments); expected_fences.extend(channel_event_sequence.fence_attachments); + let personal = surface( + MIGRATOR + .iter() + .find(|m| m.version == 61) + .expect("personal read migration") + .sql + .as_ref(), + ); + // 0062 adds personal_read_accounts.started_at after 0061's CREATE TABLE. + let started_at_column = "started_at timestamptz, "; + assert!(MIGRATOR + .iter() + .find(|m| m.version == 62) + .expect("personal read start migration") + .sql + .as_str() + .contains("ADD COLUMN started_at TIMESTAMPTZ")); + assert!(schema + .tables + .get("personal_read_accounts") + .expect("schema.sql personal read accounts") + .contains(started_at_column)); + // 0063 replaces the frontier's whole-channel cut with its anchor ID. + let threads_through_column = "threads_through_timestamp timestamptz \ + check (threads_through_timestamp is null or root_id = ''::bytea), "; + let through_message_column = + "through_message_id bytea check (octet_length(through_message_id) = 32), "; + let through_message = MIGRATOR + .iter() + .find(|m| m.version == 63) + .expect("personal read anchor migration") + .sql + .as_str(); + assert!(through_message.contains("DROP COLUMN threads_through_timestamp")); + for (table, definition) in personal.tables { + let in_schema = schema.tables.get(&table).map(|schema_definition| { + if table == "personal_read_accounts" { + schema_definition.replacen(started_at_column, "", 1) + } else { + schema_definition.clone() + } + }); + let definition = if table == "personal_read_frontiers" { + definition.replacen(threads_through_column, through_message_column, 1) + } else { + definition + }; + assert_eq!( + in_schema.as_ref(), + Some(&definition), + "personal read table {table} differs" + ); + } + expected_fences.extend(personal.fence_attachments); + expected_fences.extend(["artifact_heads", "artifact_revisions"].map(str::to_owned)); assert_eq!( expected_fences, schema.fence_attachments, "write-fence attachment targets differ after recovery policy" @@ -2161,7 +2709,7 @@ mod tests { .expect("drop probe database"); } - async fn connect_test_pool() -> PgPool { + pub(super) async fn connect_test_pool() -> PgPool { let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) .unwrap_or_else(|_| TEST_DB_URL.to_owned()); @@ -2171,7 +2719,7 @@ mod tests { .expect("connect to test DB") } - async fn reset_public_schema(pool: &PgPool) { + pub(super) async fn reset_public_schema(pool: &PgPool) { sqlx::query("DROP SCHEMA IF EXISTS public CASCADE") .execute(pool) .await @@ -2334,9 +2882,9 @@ mod tests { .await .expect("connect migrated probe database"); MIGRATOR - .run_to(39, &migrated) + .run_to(60, &migrated) .await - .expect("apply migrations 1-39"); + .expect("apply migrations 1-60"); for table in [ "relay_admin_actions", @@ -2527,6 +3075,22 @@ mod tests { assert_eq!(after, vec![(1, Some(true)), (30_179, None), (30_350, None)]); } + /// Migration-upgrade half of the owner-provenance contract. + /// + /// The desired-state bootstrap half lives in + /// `store::deletion::postgres_tests` and asserts the same shared case + /// table, so `schema/schema.sql` cannot admit owner rows the migration + /// path refuses (or the reverse). + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migrated_schema_enforces_owner_provenance_contract() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations(&pool).await.expect("run migrations"); + + crate::store::deletion::owner_provenance_contract::assert_contract(&pool).await; + } + #[tokio::test] #[ignore = "requires Postgres"] async fn run_migrations_applies_consolidated_initial_schema_on_fresh_database() { @@ -2745,4 +3309,184 @@ mod tests { .await .expect("drop late-table fixtures"); } + + /// Verify migration 0049 applies cleanly against a DB that has rows in + /// the NIP-FI 0046+0047 tables. The immutability guards (no_delete, + /// no_truncate) are enforced via triggers; DROP TABLE bypasses them and + /// must succeed even when rows are present. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_0049_drops_populated_nip_fi_ledger_cleanly() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + MIGRATOR + .run_to(47, &pool) + .await + .expect("apply migrations 1-47"); + + // Seed a community and minimal rows in a selection of 0046+0047 tables. + let community_id = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community_id) + .bind(format!("drop-test-{}.example", community_id.simple())) + .execute(&pool) + .await + .expect("seed community"); + + // Seed a receipt (used as FK anchor for several 0047 tables). + let operation_id = uuid::Uuid::new_v4(); + sqlx::query( + "INSERT INTO authorization_operation_receipts \ + (community_id, operation_id, request_fingerprint, operation_kind, \ + actor_fingerprint, outcome_code, result_digest) \ + VALUES ($1, $2, $3, 12, $4, 1, $5)", + ) + .bind(community_id) + .bind(operation_id) + .bind(vec![0xAA_u8; 32]) + .bind(vec![0xBB_u8; 32]) + .bind(vec![0xCC_u8; 32]) + .execute(&pool) + .await + .expect("seed operation receipt"); + + // Seed an invalidation domain (0047 table with no FK to receipts). + sqlx::query( + "INSERT INTO authorization_invalidation_domains \ + (community_id, current_generation) VALUES ($1, 0)", + ) + .bind(community_id) + .execute(&pool) + .await + .expect("seed invalidation domain"); + + // Apply migration 0048 (dogfood profile) and 0049 (ledger removal). + MIGRATOR + .run_to(49, &pool) + .await + .expect("migration 0049 must apply cleanly against a populated NIP-FI DB"); + + // All NIP-FI tables must be gone. + let nip_fi_tables = [ + "authorization_admission_results", + "authorization_authentication_denial_attempts", + "authorization_authority_epochs", + "authorization_event_capacity", + "authorization_events", + "authorization_invalidation_domains", + "authorization_invalidation_floors", + "authorization_operation_receipts", + "authorization_operation_version_delta_manifests", + "authorization_operation_version_deltas", + "identity_bindings", + "identity_enrollment_policies", + "identity_lifecycle_history", + "identity_lifecycle_selectors", + "protected_object_authority", + ]; + let present: Vec = sqlx::query_scalar( + "SELECT table_name FROM information_schema.tables \ + WHERE table_schema = 'public' AND table_name = ANY($1)", + ) + .bind(&nip_fi_tables[..]) + .fetch_all(&pool) + .await + .expect("catalog check after ledger removal"); + assert!( + present.is_empty(), + "all NIP-FI tables must be absent after migration 0049: {present:?}" + ); + + // Complete later additive migrations before comparing to the current + // binary's complete tenant-table inventory. + run_migrations(&pool) + .await + .expect("complete current migrations"); + // The deletion catalog must validate with ledger relations gone. + crate::deletion::DeletionStore::new(pool.clone()) + .validate_catalog() + .await + .expect("deletion catalog validates after migration 0049"); + } + + /// Migration 0060's `relay_admin_actions_direct_shape` rejects a direct + /// timeout carrying only one of duration and expiry on the migrated + /// schema. The desired-state (pgschema + reconcile) path is covered by + /// `direct_timeout_shape_check_holds_on_desired_state_schema` in buzz-relay. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_0060_rejects_half_filled_direct_timeout() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + MIGRATOR + .run_to(60, &pool) + .await + .expect("apply migrations 1-60"); + for (secs, until) in [(Some(60i64), None), (None, Some(chrono::Utc::now()))] { + let err = sqlx::query( + "INSERT INTO relay_admin_actions (report_community_id, request_id, actor_pubkey, \ + actor_role, action, timeout_secs, timeout_until, enforcement_target_pubkey) \ + VALUES (gen_random_uuid(), gen_random_uuid(), $1, 'operator', 'timeout', $2, $3, $1)", + ) + .bind([9u8; 32].as_slice()) + .bind(secs) + .bind(until) + .execute(&pool) + .await + .expect_err("half-filled timeout must violate the CHECK"); + assert!( + err.to_string().contains("relay_admin_actions_direct_shape"), + "{err}" + ); + } + } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_0065_refuses_active_legacy_leases_without_mutation() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 64) + .await + .expect("legacy schema"); + let community = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO communities(id,host) VALUES($1,'push-cutover.example')") + .bind(community) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO push_leases(community_id,author,installation_id,source_event_id,source_created_at,generation,active,app_profile,endpoint_hash,endpoint_grant,max_class,subscriptions,expires_at) VALUES($1,$2,'legacy',$3,1,1,true,'buzz-ios-dogfood',$4,'opaque','default','[]',2000000000)") + .bind(community).bind(vec![1_u8;32]).bind(vec![2_u8;32]).bind(vec![3_u8;32]) + .execute(&pool).await.unwrap(); + let error = run_migrations(&pool) + .await + .expect_err("active legacy lease blocks cutover"); + assert!( + error.to_string().contains("no active legacy push leases"), + "{error}" + ); + let preserved: (bool, String) = + sqlx::query_as("SELECT active,app_profile FROM push_leases WHERE community_id=$1") + .bind(community) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(preserved, (true, "buzz-ios-dogfood".to_owned())); + sqlx::query("UPDATE push_leases SET active=false,app_profile=NULL,endpoint_hash=NULL,endpoint_grant=NULL,max_class=NULL,subscriptions=NULL WHERE community_id=$1") + .bind(community).execute(&pool).await.unwrap(); + run_migrations(&pool) + .await + .expect("inactive legacy lease permits cutover"); + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM push_leases WHERE community_id=$1 AND NOT active", + ) + .bind(community) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 1); + assert!(sqlx::query("SELECT app_profile FROM push_leases") + .execute(&pool) + .await + .is_err()); + } } diff --git a/crates/buzz-db/src/runtime/mod.rs b/crates/buzz-db/src/runtime/mod.rs index 29eef884024..4bda0d71a9c 100644 --- a/crates/buzz-db/src/runtime/mod.rs +++ b/crates/buzz-db/src/runtime/mod.rs @@ -1,7 +1,19 @@ +mod admitted_tx; +mod cold_start; +mod connection_observability; pub mod migration; pub(crate) mod observability; +pub(crate) mod push_enqueue; pub mod replica_fence; +pub use admitted_tx::AdmittedTx; +pub use cold_start::ColdStartError; +pub use connection_observability::{DbConnectionOutcome, DbConnectionStep}; +pub(crate) use connection_observability::{ + CONNECTION_DURATION_STEPS, CONNECTION_RAW_SERIES_PER_POD, CONNECTION_STARTED_STEPS, + CONNECTION_TERMINALS, +}; + use crate::{deletion, event, DbError, EventQuery, Result}; use buzz_datastore_tracing::datastore_span; use chrono::{DateTime, Utc}; @@ -14,31 +26,39 @@ use buzz_core::{CommunityId, StoredEvent}; /// Extract p-tag mentions from an event and insert into the `event_mentions` table. /// -/// This pool-owning wrapper propagates failures to its caller. Replacement writes -/// use the transaction-bound helper below so event storage and mention indexing -/// commit or roll back together. Duplicate inserts are silently skipped with -/// `INSERT ... ON CONFLICT DO NOTHING`. +/// This pool-owning wrapper indexes mentions in its own admitted transaction, +/// after the event has already committed. Writes that need event storage and +/// mention indexing to commit or roll back together should open +/// `begin_community_event_write_transaction` and call +/// `insert_mentions_in_transaction` instead. +/// +/// Duplicate inserts are silently skipped with `INSERT ... ON CONFLICT DO +/// NOTHING`. pub async fn insert_mentions( pool: &PgPool, community_id: CommunityId, event: &nostr::Event, channel_id: Option, ) -> Result<()> { - let mut tx = pool.begin().await?; - insert_mentions_in_transaction(&mut tx, community_id, event, channel_id).await?; - tx.commit().await?; - Ok(()) + let mut tx = begin_community_event_write_transaction( + pool, + community_id, + observability::WriterOperation::EventWrite, + ) + .await?; + insert_mentions_in_transaction(&mut tx, event, channel_id).await?; + tx.commit().await } -/// Insert mention rows on the caller's transaction. Replacement writes use -/// this so the authoritative event and its discovery index commit or roll back -/// as one unit. +/// Insert mention rows on the caller's admitted transaction. Replacement +/// writes use this so the authoritative event and its discovery index commit +/// or roll back as one unit. pub(crate) async fn insert_mentions_in_transaction( - tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, - community_id: CommunityId, + tx: &mut AdmittedTx, event: &nostr::Event, channel_id: Option, ) -> Result<()> { + let community_id = tx.community(); let p_tags: Vec<&str> = event .tags .iter() @@ -107,15 +127,141 @@ pub(crate) async fn insert_mentions_in_transaction( qb.push(" ON CONFLICT DO NOTHING"); - qb.build().execute(&mut **tx).await?; + qb.build().execute(tx.conn()).await?; } Ok(()) } +/// Start a tenant-local write transaction and take the shared community +/// deletion lock before any serving mutation. +async fn begin_community_write_transaction_with_metric_population( + pool: &PgPool, + community: CommunityId, + operation: observability::WriterOperation, + metric_population: CommunityEventWriteMetricPopulation, +) -> Result { + let connection = match metric_population { + CommunityEventWriteMetricPopulation::TypedOnly => { + observability::acquire_writer(pool, operation).await? + } + CommunityEventWriteMetricPopulation::LegacyCompatibility => { + observability::acquire_writer_with_legacy_metrics(pool, operation).await? + } + }; + let tx = sqlx::Transaction::begin(connection, None).await?; + AdmittedTx::admit(tx, &deletion::DeletionStore::new(pool.clone()), community).await +} + +#[derive(Clone, Copy)] +enum CommunityEventWriteMetricPopulation { + TypedOnly, + LegacyCompatibility, +} + +pub(crate) async fn begin_community_event_write_transaction( + pool: &PgPool, + community: CommunityId, + operation: observability::WriterOperation, +) -> Result { + begin_community_write_transaction_with_metric_population( + pool, + community, + operation, + CommunityEventWriteMetricPopulation::TypedOnly, + ) + .await +} + +pub(crate) async fn begin_community_event_write_transaction_with_legacy_metrics( + pool: &PgPool, + community: CommunityId, + operation: observability::WriterOperation, +) -> Result { + begin_community_write_transaction_with_metric_population( + pool, + community, + operation, + CommunityEventWriteMetricPopulation::LegacyCompatibility, + ) + .await +} + +/// Begin a community write before any tenant mutation or row lock. The +/// admission lock is held by the returned transaction until commit or rollback. +pub(crate) async fn begin_community_write_transaction( + pool: &PgPool, + community: CommunityId, + operation: observability::WriterOperation, +) -> Result { + begin_community_write_transaction_with_metric_population( + pool, + community, + operation, + CommunityEventWriteMetricPopulation::TypedOnly, + ) + .await +} + +/// Begin a fleet sweep's tenant-local mutation, skipping communities whose +/// deletion lifecycle no longer admits writes. All other failures propagate. +pub(crate) async fn begin_community_sweep_transaction( + pool: &PgPool, + community: CommunityId, + operation: observability::WriterOperation, +) -> Result> { + match begin_community_write_transaction(pool, community, operation).await { + Ok(tx) => Ok(Some(tx)), + Err(DbError::AccessDenied(_)) => Ok(None), + Err(error) => Err(error), + } +} + +/// Run one admitted mutation per community for a periodic fleet sweep and +/// return the committed results in order. Fenced communities are skipped. +/// A tenant-local failure is logged and the sweep moves on; that tenant's +/// rows retry next tick. A connection-level failure stops the sweep instead, +/// because every remaining tenant would wait out the same acquire timeout. +pub(crate) async fn sweep_admitted_communities( + pool: &PgPool, + communities: impl IntoIterator, + operation: observability::WriterOperation, + sweep: &'static str, + mut mutate: F, +) -> Vec +where + F: FnMut(Uuid, AdmittedTx) -> Fut, + Fut: std::future::Future>, +{ + let mut committed = Vec::new(); + for id in communities { + let result = + match begin_community_sweep_transaction(pool, CommunityId::from_uuid(id), operation) + .await + { + Ok(None) => continue, + Ok(Some(tx)) => mutate(id, tx).await, + Err(error) => Err(error), + }; + match result { + Ok(value) => committed.push(value), + Err(error) if error.is_connection_unavailable() => { + tracing::warn!(sweep, community_id = %id, error = %error, + "Fleet sweep stopped: database unavailable; remaining tenants retry next tick"); + break; + } + Err(error) => tracing::warn!(sweep, community_id = %id, error = %error, + "Fleet sweep tenant failed; retained rows retry next tick"), + } + } + committed +} + /// Database handle. Clone is cheap (Arc-backed pool). #[derive(Clone, Debug)] pub struct Db { pub(crate) pool: PgPool, + /// Optional bounded post-commit producer, shared across handle clones. + pub(crate) push_enqueue: Option, /// Maximum connections configured for this pool (from [`DbConfig::max_connections`]). pub(crate) max_connections: u32, /// Optional read-replica pool (from [`DbConfig::read_database_url`]). @@ -146,6 +292,10 @@ pub struct Db { /// bounded-stale read semantics are a product decision, not an /// invariant, so the gate ships off. pub(crate) replica_read_max_age: Option, + /// Replica freshness budget used only by the leader's fleet telemetry + /// queries. This is independent of serving-read rollout policy: telemetry + /// may be stale or skipped, but it must never fall back to the writer. + pub(crate) usage_metrics_replica_max_age: Option, /// Whether the reader endpoint supports the Aurora PostgreSQL identity /// function ([`replica_fence::AURORA_IDENTITY_FN`]) — probed /// once per process on the first routed read (on a plain autocommit @@ -192,6 +342,8 @@ impl ReadSession { /// /// If the proved replica transaction fails mid-request, the session /// permanently degrades to the writer and the query is re-run there. + /// Exception: a statement cancelled by `statement_timeout` (57014) is + /// returned as-is, since the writer would run the same slow statement. /// The writer is always at or ahead of any replica replay position, so /// the degraded follow-up can only observe *more* than the proof-time /// snapshot, never less — fresher aux rows, the same failure semantics @@ -202,6 +354,9 @@ impl ReadSession { ReadSessionInner::Replica { tx, writer } => { match event::query_events_on(tx, q).await { Ok(rows) => return Ok(rows), + // A cancelled statement (timeout) would be just as slow on + // the writer; surface it instead of doubling the cost. + Err(e) if e.is_statement_cancelled() => return Err(e), Err(e) => { tracing::warn!( error = %e, @@ -425,9 +580,78 @@ pub struct DbPoolStats { pub max: u32, } +impl DbPoolStats { + /// Read a utilization snapshot from a physical SQLx pool handle. + pub fn from_pool(pool: &sqlx::PgPool) -> Self { + Self { + size: pool.size(), + idle: pool.num_idle() as u32, + max: pool.options().get_max_connections(), + } + } + + /// Connections currently checked out from the pool. + pub const fn active(self) -> u32 { + self.size.saturating_sub(self.idle) + } +} + +/// Physical role of a Postgres connection pool owned by the relay. +/// +/// This vocabulary is intentionally closed so metrics labels remain bounded. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub enum DbPoolRole { + /// Primary pool used for authoritative writes and consistency-sensitive reads. + Writer, + /// Optional read-replica pool used for eligible lag-tolerant reads. + Reader, + /// Optional independent pool used by the hash-chain audit service. + Audit, + /// Independent pool used for Postgres full-text search queries. + Search, +} + +impl DbPoolRole { + /// Every physical pool role, in stable metrics-contract order. + pub const ALL: [Self; 4] = [Self::Writer, Self::Reader, Self::Audit, Self::Search]; + + /// Stable low-cardinality metrics label for this role. + pub const fn as_str(self) -> &'static str { + match self { + Self::Writer => "writer", + Self::Reader => "reader", + Self::Audit => "audit", + Self::Search => "search", + } + } +} + +/// Bounded outcome of the Postgres portion of a relay readiness check. +/// +/// The variants deliberately separate waiting for a pooled connection from +/// executing the health query. Callers may safely use the variant names as +/// low-cardinality metric labels; detailed SQLx errors remain in logs rather +/// than becoming labels. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DbReadinessOutcome { + /// A writer-pool connection was acquired and `SELECT 1` succeeded. + Success, + /// No writer-pool connection became available before the readiness deadline. + PoolTimeout, + /// The writer pool returned a non-timeout acquisition error. + PoolError, + /// A connection was acquired, but `SELECT 1` exceeded the readiness deadline. + QueryTimeout, + /// A connection was acquired, but `SELECT 1` returned an error. + QueryError, +} + /// Configuration for the Postgres connection pool. #[derive(Debug, Clone)] pub struct DbConfig { + /// Enable push producers on every writer connection. Defaults to false. + /// Relay startup copies `BUZZ_PUSH_ENABLED`; auxiliary writers stay off. + pub push_enabled: bool, /// Postgres connection URL (usually sourced from `DATABASE_URL`). pub database_url: String, /// Optional read-replica connection URL (usually sourced from @@ -454,6 +678,23 @@ pub struct DbConfig { /// than the staleness gate never routes anyway, so a larger budget /// would only misrepresent the config. pub replica_read_max_age_ms: u64, + /// Replica freshness budget for usage telemetry, in milliseconds + /// (`BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS`). `0` disables fleet database + /// telemetry. This does not enable replica routing for serving reads. + pub usage_metrics_replica_max_age_ms: u64, + /// Session `lock_timeout` in milliseconds for writer connections (env + /// `BUZZ_DB_LOCK_TIMEOUT_MS`). `0` disables the timeout. + pub lock_timeout_ms: u64, + /// Session `idle_in_transaction_session_timeout` in milliseconds for + /// writer connections (env `BUZZ_DB_IDLE_TXN_TIMEOUT_MS`). `0` disables. + pub idle_txn_timeout_ms: u64, + /// Session `statement_timeout` in milliseconds for writer connections + /// (env `BUZZ_DB_STATEMENT_TIMEOUT_MS`). `0` disables it and is the + /// default because migrations and backfills may legitimately run long. + pub statement_timeout_ms: u64, + /// Whether every new writer-pool connection defaults all transactions to + /// read-only. Intended for operator audit commands, never the relay pool. + pub default_transaction_read_only: bool, } impl Default for DbConfig { @@ -462,6 +703,7 @@ impl Default for DbConfig { /// At 20 main + 5 audit = 25/pod, four relay pods fit within the PG limit. fn default() -> Self { Self { + push_enabled: false, database_url: "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string(), // sadscan:disable np.postgres.1 read_database_url: None, max_connections: 20, @@ -471,7 +713,46 @@ impl Default for DbConfig { max_lifetime_secs: 1800, idle_timeout_secs: 600, replica_read_max_age_ms: 0, + usage_metrics_replica_max_age_ms: 30_000, + lock_timeout_ms: DEFAULT_LOCK_TIMEOUT_MS, + idle_txn_timeout_ms: DEFAULT_IDLE_TXN_TIMEOUT_MS, + statement_timeout_ms: 0, + default_transaction_read_only: false, + } + } +} + +/// Default writer `lock_timeout` in milliseconds. +pub const DEFAULT_LOCK_TIMEOUT_MS: u64 = 5_000; + +/// Default writer `idle_in_transaction_session_timeout` in milliseconds. +pub const DEFAULT_IDLE_TXN_TIMEOUT_MS: u64 = 60_000; + +impl DbConfig { + /// Overlay writer session timeouts from the shared `BUZZ_DB_*_TIMEOUT_MS` + /// environment variables. Missing or invalid values retain the existing + /// configuration; explicit zeroes pass through to disable a timeout. + /// + /// This belongs in `buzz-db` so relay, admin, deletion, and audit writers + /// share one policy. The separately deployed push gateway owns its own + /// database and session policy. + pub fn with_session_timeouts_from_env(mut self) -> Self { + fn parse(key: &str) -> Option { + std::env::var(key) + .ok() + .and_then(|value| value.parse::().ok()) + } + + if let Some(value) = parse("BUZZ_DB_LOCK_TIMEOUT_MS") { + self.lock_timeout_ms = value; } + if let Some(value) = parse("BUZZ_DB_IDLE_TXN_TIMEOUT_MS") { + self.idle_txn_timeout_ms = value; + } + if let Some(value) = parse("BUZZ_DB_STATEMENT_TIMEOUT_MS") { + self.statement_timeout_ms = value; + } + self } } @@ -486,7 +767,7 @@ impl Db { /// `buzz.created_at_floor` GUC — this is what makes the replica fence /// proof hold for every insert path that goes through this pool. pub async fn new(config: &DbConfig) -> Result { - let pool = Self::connect_pool(config, &config.database_url).await?; + let pool = Self::connect_writer_pool(config).await?; let read_max_connections = config .read_max_connections .unwrap_or(config.max_connections); @@ -495,13 +776,20 @@ impl Db { None => None, }; let replica_read_max_age = read_budget_from_ms(config.replica_read_max_age_ms); + let usage_metrics_replica_max_age = + read_budget_from_ms(config.usage_metrics_replica_max_age_ms); + let push_enqueue = config + .push_enabled + .then(|| push_enqueue::PushEnqueue::new(&pool)); Ok(Self { + push_enqueue, pool, max_connections: config.max_connections, read_pool, read_max_connections, fence: std::sync::Arc::new(replica_fence::ReplicaFence::new()), replica_read_max_age, + usage_metrics_replica_max_age, reader_aurora_identity: std::sync::Arc::new(std::sync::OnceLock::new()), }) } @@ -511,24 +799,101 @@ impl Db { /// SQLx stores one `after_connect` hook, so the floor guard and transaction /// isolation assertion must remain in this single closure. Registering a /// second hook replaces the first and silently disarms the floor trigger. - async fn connect_pool(config: &DbConfig, url: &str) -> Result { + /// Additional writer pools, including the relay audit pool, must use this + /// constructor so they inherit the timeout, floor-guard, and isolation + /// policy installed by [`Db::new`]. + pub async fn connect_writer_pool(config: &DbConfig) -> Result { + use connection_observability::{ + classify_pool_outcome, record_milestone, DbConnectionStep, DbConnectionStepAttempt, + }; + + let push_enabled = config.push_enabled; + let lock_timeout_ms = config.lock_timeout_ms; + let idle_txn_timeout_ms = config.idle_txn_timeout_ms; + let statement_timeout_ms = config.statement_timeout_ms; + let default_transaction_read_only = config.default_transaction_read_only; let options = PgPoolOptions::new() .max_connections(config.max_connections) .min_connections(config.min_connections) .acquire_timeout(Duration::from_secs(config.acquire_timeout_secs)) .max_lifetime(Duration::from_secs(config.max_lifetime_secs)) .idle_timeout(Duration::from_secs(config.idle_timeout_secs)) - .after_connect(|conn, _meta| { + .after_connect(move |conn, _meta| { Box::pin(async move { + // SQLx 0.9 exposes no callback immediately before each raw + // physical dial. Entering `after_connect` is the truthful + // point at which DNS/network/TLS/authentication succeeded. + record_milestone(DbPoolRole::Writer, DbConnectionStep::PhysicalConnect); + // `SET` cannot take bind parameters; `set_config` can. - sqlx::query("SELECT set_config('buzz.created_at_floor', $1, false)") + let floor = DbConnectionStepAttempt::start( + DbPoolRole::Writer, + DbConnectionStep::CreatedAtFloor, + ); + if let Err(error) = + sqlx::query("SELECT set_config('buzz.created_at_floor', $1, false)") .bind(replica_fence::CREATED_AT_FLOOR_SECS.to_string()) .execute(&mut *conn) - .await?; - let isolation: String = sqlx::query_scalar("SHOW transaction_isolation") + .await + { + floor.fail(); + return Err(error); + } + floor.succeed(); + + // `lock_timeout` fails the waiting statement; it does not + // cancel the holder. `idle_in_transaction_session_timeout` + // reaps only holders idling inside an open transaction, + // while actively executing holders are bounded only by + // `statement_timeout` (off by default). Bare values are + // milliseconds. Migration/schema-destruction connections + // reset lock and statement timeouts before their intentional + // long wait (see `with_exclusive_schema_destruction_lock`). + let timeouts = DbConnectionStepAttempt::start( + DbPoolRole::Writer, + DbConnectionStep::SessionTimeouts, + ); + if let Err(error) = sqlx::query( + "SELECT set_config('lock_timeout', $1, false), \ + set_config('idle_in_transaction_session_timeout', $2, false), \ + set_config('statement_timeout', $3, false), \ + set_config('default_transaction_read_only', $4, false), \ + set_config('buzz.push_enabled', $5, false), \ + set_config('buzz.push_async_enqueue', 'on', false)", + ) + .bind(lock_timeout_ms.to_string()) + .bind(idle_txn_timeout_ms.to_string()) + .bind(statement_timeout_ms.to_string()) + .bind(if default_transaction_read_only { + "on" + } else { + "off" + }) + .bind(if push_enabled { "on" } else { "off" }) + .execute(&mut *conn) + .await + { + timeouts.fail(); + return Err(error); + } + timeouts.succeed(); + + let isolation_step = DbConnectionStepAttempt::start( + DbPoolRole::Writer, + DbConnectionStep::Isolation, + ); + let isolation: String = match sqlx::query_scalar("SHOW transaction_isolation") .fetch_one(&mut *conn) - .await?; + .await + { + Ok(isolation) => isolation, + Err(error) => { + isolation_step.fail(); + return Err(error); + } + }; if isolation != "read committed" { + isolation_step.fail(); return Err(sqlx::Error::Configuration( format!( "writer pool requires READ COMMITTED transaction isolation, got {isolation}" @@ -536,10 +901,29 @@ impl Db { .into(), )); } + isolation_step.succeed(); + record_milestone(DbPoolRole::Writer, DbConnectionStep::Ready); Ok(()) }) }); - Ok(options.connect(url).await?) + + let pool_attempt = + DbConnectionStepAttempt::start(DbPoolRole::Writer, DbConnectionStep::WriterPool); + match options.connect(&config.database_url).await { + Ok(pool) => { + pool_attempt.succeed(); + Ok(pool) + } + Err(error) => { + let outcome = classify_pool_outcome(&error); + if outcome == connection_observability::DbConnectionOutcome::TimedOut { + pool_attempt.time_out(); + } else { + pool_attempt.fail(); + } + Err(error.into()) + } + } } /// Reader acquire timeout — deliberately far below the writer's @@ -596,36 +980,59 @@ impl Db { return; }; let aurora_identity = self.reader_aurora_identity.clone(); - tokio::spawn(async move { - match observability::acquire(&read_pool, observability::PoolRole::Reader).await { - Ok(mut conn) => { - tracing::info!("read replica reachable at boot"); - match replica_fence::reader_supports_aurora_identity(&mut conn).await { - Ok(supported) => { - let _ = aurora_identity.set(supported); - } - Err(e) => tracing::debug!( - error = %e, - "aurora identity boot prime failed; first routed read will probe" - ), + tokio::spawn(Self::read_pool_boot_ping_once(read_pool, aurora_identity)); + } + + async fn read_pool_boot_ping_once( + read_pool: PgPool, + aurora_identity: std::sync::Arc>, + ) { + match observability::acquire_reader_with_legacy_metrics( + &read_pool, + observability::ReaderOperation::Bootstrap, + ) + .await + { + Ok(mut conn) => { + tracing::info!("read replica reachable at boot"); + match replica_fence::reader_supports_aurora_identity(&mut conn).await { + Ok(supported) => { + let _ = aurora_identity.set(supported); } + Err(e) => tracing::debug!( + error = %e, + "aurora identity boot prime failed; first routed read will probe" + ), } - Err(e) => tracing::warn!( - "read replica unreachable at boot; serving all-writer until it recovers: {e}" - ), } - }); + Err(e) => tracing::warn!( + "read replica unreachable at boot; serving all-writer until it recovers: {e}" + ), + } + } + + #[cfg(test)] + pub(crate) async fn read_pool_boot_ping_for_tests(&self) { + let Some(read_pool) = self.read_pool.clone() else { + return; + }; + Self::read_pool_boot_ping_once(read_pool, self.reader_aurora_identity.clone()).await; } /// Creates a `Db` from an existing `PgPool` (useful in tests). + /// + /// Does not start a push producer or configure sessions. Serving writers + /// that need push must use [`Db::new`] with `push_enabled` instead. pub fn from_pool(pool: PgPool) -> Self { Self { + push_enqueue: None, max_connections: pool.options().get_max_connections(), read_max_connections: pool.options().get_max_connections(), pool, read_pool: None, fence: std::sync::Arc::new(replica_fence::ReplicaFence::new()), replica_read_max_age: None, + usage_metrics_replica_max_age: None, reader_aurora_identity: std::sync::Arc::new(std::sync::OnceLock::new()), } } @@ -639,12 +1046,14 @@ impl Db { /// [`Db::fence`]). pub fn from_pools(pool: PgPool, read_pool: PgPool) -> Self { Self { + push_enqueue: None, max_connections: pool.options().get_max_connections(), read_max_connections: read_pool.options().get_max_connections(), pool, read_pool: Some(read_pool), fence: std::sync::Arc::new(replica_fence::ReplicaFence::new()), replica_read_max_age: None, + usage_metrics_replica_max_age: Some(replica_fence::FENCE_STALENESS), reader_aurora_identity: std::sync::Arc::new(std::sync::OnceLock::new()), } } @@ -680,8 +1089,7 @@ impl Db { if self.read_pool.is_none() { return Ok(false); } - replica_fence::verify_floor_guard_catalog(&self.pool).await?; - replica_fence::verify_floor_guard_behavior(&self.pool).await?; + self.verify_replica_fence_at_boot().await?; tokio::spawn(replica_fence::run_probe( self.pool.clone(), std::sync::Arc::clone(&self.fence), @@ -689,6 +1097,17 @@ impl Db { Ok(true) } + /// Verify replica-fence catalog shape and behavior through attributed + /// writer/bootstrap acquisitions without starting the recurring probe. + pub(crate) async fn verify_replica_fence_at_boot(&self) -> Result<()> { + let mut connection = + observability::acquire_writer(&self.pool, observability::WriterOperation::Bootstrap) + .await?; + replica_fence::verify_floor_guard_catalog(&mut *connection).await?; + drop(connection); + replica_fence::verify_floor_guard_behavior(&self.pool).await + } + /// The pool for lag-tolerant reads: the read replica when configured, /// otherwise the writer pool. /// @@ -726,6 +1145,7 @@ impl Db { async fn proved_reader( &self, read_pool: &PgPool, + operation: observability::ReaderOperation, ) -> std::result::Result< ( sqlx::Transaction<'static, sqlx::Postgres>, @@ -739,18 +1159,24 @@ impl Db { // `read_pool` separately would spend a second budget whenever the // capability is uncached — i.e. after a failed boot ping, which is // precisely the reader-unavailable case the bound must hold for. - let conn = match observability::acquire(read_pool, observability::PoolRole::Reader).await { - Ok(conn) => conn, - Err(sqlx::Error::PoolTimedOut) => { - tracing::warn!("reader pool acquire timed out; routing to writer"); - return Err("reader_acquire_timeout"); - } - Err(e) => { - tracing::warn!(error = %e, "reader connection acquire failed; routing to writer"); - return Err("reader_validation_error"); - } - }; + let conn = + match observability::acquire_reader_with_legacy_metrics(read_pool, operation).await { + Ok(conn) => conn, + Err(sqlx::Error::PoolTimedOut) => { + tracing::warn!("reader pool acquire timed out"); + return Err("reader_acquire_timeout"); + } + Err(e) => { + tracing::warn!(error = %e, "reader connection acquire failed"); + return Err("reader_validation_error"); + } + }; let mut conn = conn; + if operation.bounded_release() { + // Must precede the first post-acquire await: a caller deadline + // can drop this checkout at any of them. + conn.close_on_drop(); + } let aurora = self.reader_aurora_capability_on(&mut conn).await; let mut tx = match sqlx::Transaction::begin( conn, @@ -785,11 +1211,11 @@ impl Db { // between samples entirely, so absence of elevated active is // NOT evidence of a cold connect. Err(sqlx::Error::PoolTimedOut) => { - tracing::warn!("reader pool acquire timed out; routing to writer"); + tracing::warn!("reader pool acquire timed out"); return Err("reader_acquire_timeout"); } Err(e) => { - tracing::warn!(error = %e, "reader transaction begin failed; routing to writer"); + tracing::warn!(error = %e, "reader transaction begin failed"); return Err("reader_validation_error"); } }; @@ -797,7 +1223,7 @@ impl Db { Ok(Some(observation)) => observation, Ok(None) => return Err("reader_validation_error"), Err(e) => { - tracing::warn!(error = %e, "heartbeat observation failed; routing to writer"); + tracing::warn!(error = %e, "heartbeat observation failed"); return Err("reader_validation_error"); } }; @@ -860,9 +1286,62 @@ impl Db { migration::run_migrations(&self.pool).await } - /// Returns `true` if the database is reachable (used by readiness probes). + /// Returns `true` if the database is reachable. pub async fn ping(&self) -> bool { - sqlx::query("SELECT 1").execute(&self.pool).await.is_ok() + let Ok(mut connection) = + observability::acquire_writer(&self.pool, observability::WriterOperation::Readiness) + .await + else { + return false; + }; + sqlx::query("SELECT 1") + .execute(&mut *connection) + .await + .is_ok() + } + + /// Checks writer-pool acquisition and query execution against one deadline. + /// + /// Unlike [`Self::ping`], this preserves whether readiness was blocked while + /// borrowing a connection or failed after a connection had been acquired. + /// The query runs on the already-acquired connection so the two phases + /// cannot be collapsed into a second implicit pool acquisition. + pub async fn readiness_check(&self, deadline: tokio::time::Instant) -> DbReadinessOutcome { + self.readiness_check_sql(deadline, "SELECT 1").await + } + + /// Production-bound seam for classifying failures after pool acquisition. + /// Tests vary only the SQL so timeout/error/cancellation paths execute the + /// same acquisition and classification code as [`Self::readiness_check`]. + async fn readiness_check_sql( + &self, + deadline: tokio::time::Instant, + query: &'static str, + ) -> DbReadinessOutcome { + let mut connection = match observability::acquire_writer_until( + &self.pool, + observability::WriterOperation::Readiness, + deadline, + ) + .await + { + Err(sqlx::Error::PoolTimedOut) => return DbReadinessOutcome::PoolTimeout, + Err(error) => { + tracing::debug!(error = %error, "Postgres readiness pool acquisition failed"); + return DbReadinessOutcome::PoolError; + } + Ok(connection) => connection, + }; + + match tokio::time::timeout_at(deadline, sqlx::query(query).execute(&mut *connection)).await + { + Err(_) => DbReadinessOutcome::QueryTimeout, + Ok(Err(error)) => { + tracing::debug!(error = %error, "Postgres readiness query failed"); + DbReadinessOutcome::QueryError + } + Ok(Ok(_)) => DbReadinessOutcome::Success, + } } /// Returns pool utilisation stats for metrics emission. @@ -878,6 +1357,25 @@ impl Db { } } + /// Return a reference to the writer pool. + /// + /// Callers that need a pool handle for standalone free functions (e.g., + /// `buzz_db::insert_mentions`) can use this. Prefer the `Db` method + /// equivalents when they exist; use `pool()` only for functions that have + /// no `Db` wrapper yet. + pub fn pool(&self) -> &PgPool { + &self.pool + } + + /// Refresh all expected operation-specific waiter gauges, including zero. + /// + /// The relay pool sampler calls this periodically so an exporter idle + /// timeout cannot make a healthy zero indistinguishable from missing + /// telemetry. + pub fn refresh_pool_waiter_metrics(&self) { + observability::refresh_pool_waiters(self.read_pool.is_some()); + } + /// Pool utilisation stats for the read-replica pool, when configured. /// /// `max` is the **reader's** ceiling ([`Db::read_max_connections`]), not @@ -887,23 +1385,50 @@ impl Db { /// exactly the ratio of the two pool sizes — in the direction that hides /// the problem. pub fn read_pool_stats(&self) -> Option { - self.read_pool.as_ref().map(|p| DbPoolStats { - size: p.size(), - idle: p.num_idle() as u32, + self.read_pool.as_ref().map(|pool| DbPoolStats { + size: pool.size(), + idle: pool.num_idle() as u32, max: self.read_max_connections, }) } - /// Begin a database transaction for atomic multi-statement operations. + /// Begin an event-write transaction admitted for `community`. /// - /// Returns a `'static` transaction because `PgPool` is `Arc`-backed internally. - /// The transaction holds an owned pool handle, not a borrow. - pub async fn begin_transaction(&self) -> Result> { - let connection = - observability::acquire(&self.pool, observability::PoolRole::Writer).await?; - sqlx::Transaction::begin(connection, None) - .await - .map_err(Into::into) + /// This is the only `Db` constructor for event-write transactions. It takes + /// the shared community admission lock before returning, so callers that use + /// it cannot take domain or row locks ahead of tenant admission, and a + /// quiescing community rejects the write at entry rather than at its first + /// fenced statement. The returned [`AdmittedTx`] is the only type the + /// event-write `*_in_transaction` helpers accept, and it carries + /// `community`, so the compiler rejects a raw transaction or one admitted + /// for another community. Outside this crate, [`AdmittedTx::commit`] is + /// the only commit path; see [`AdmittedTx`] for the in-crate limit. + pub async fn begin_event_write_transaction( + &self, + community: CommunityId, + ) -> Result { + let mut tx = begin_community_event_write_transaction_with_legacy_metrics( + &self.pool, + community, + observability::WriterOperation::EventWrite, + ) + .await?; + tx.set_push_enqueue(self.push_enqueue.clone()); + Ok(tx) + } + + /// Stop accepting best-effort push enqueue work and cancel in-flight work. + pub fn cancel_push_enqueue(&self) { + if let Some(producer) = &self.push_enqueue { + producer.cancel(); + } + } + + /// Wait for the cancelled producer to release its dedicated connection. + pub async fn join_push_enqueue(&self) { + if let Some(producer) = &self.push_enqueue { + producer.join().await; + } } /// Insert an event while holding and validating an admitted serving-write @@ -918,7 +1443,6 @@ impl Db { event: &nostr::Event, channel_id: Option, ) -> Result<(StoredEvent, bool)> { - let community_id = lease.community_id; let kind_u16 = event.kind.as_u16(); let kind_u32 = u32::from(kind_u16); if kind_u32 == buzz_core::kind::KIND_AUTH { @@ -928,27 +1452,75 @@ impl Db { return Err(DbError::EphemeralEventRejected(kind_u16)); } - let mut tx = self.pool.begin().await?; - self.deletion_store() - .guard_transaction_with_serving_lease(&mut tx, lease) - .await?; - let result = event::insert_event_with_thread_metadata_tx( - &mut tx, - community_id, - event, - channel_id, - None, - ) - .await?; - tx.commit().await?; + let connection = + observability::acquire_writer(&self.pool, observability::WriterOperation::EventWrite) + .await?; + let tx = sqlx::Transaction::begin(connection, None).await?; + let mut tx = + AdmittedTx::admit_with_serving_lease(tx, &self.deletion_store(), lease).await?; + tx.set_push_enqueue(self.push_enqueue.clone()); + event::acquire_canvas_event_write_lock_if_needed(&mut tx, event, channel_id).await?; + let result = + event::insert_event_with_thread_metadata_tx(&mut tx, event, channel_id, None).await?; if result.1 { - if let Err(e) = insert_mentions(&self.pool, community_id, event, channel_id).await { - tracing::warn!(event_id = %event.id, "Failed to insert mentions: {e}"); + // Index mentions in the event's own transaction so a concurrent + // deletion cannot strand an orphan row. A savepoint keeps the + // existing best-effort contract: an indexing failure never rejects + // an otherwise valid event. + sqlx::query("SAVEPOINT serving_write_mentions") + .execute(tx.conn()) + .await?; + match insert_mentions_in_transaction(&mut tx, event, channel_id).await { + Ok(()) => { + sqlx::query("RELEASE SAVEPOINT serving_write_mentions") + .execute(tx.conn()) + .await?; + } + Err(e) => { + sqlx::query("ROLLBACK TO SAVEPOINT serving_write_mentions") + .execute(tx.conn()) + .await?; + tracing::warn!(event_id = %event.id, "Failed to insert mentions: {e}"); + } } } + tx.commit().await?; Ok(result) } + /// Route a usage-telemetry query only to a proved, sufficiently fresh + /// reader. Unlike serving reads, an unavailable reader is recorded as + /// skipped and never represented as or executed on the writer. + pub(crate) async fn route_usage_read( + &self, + path: &'static str, + ) -> Option<(sqlx::Transaction<'static, sqlx::Postgres>, &'static str)> { + let skip = |reason| { + Self::record_route(path, "skipped", reason); + None + }; + let Some(read_pool) = &self.read_pool else { + return skip("disabled"); + }; + let Some(budget) = self.usage_metrics_replica_max_age else { + return skip("disabled"); + }; + let Some(newest) = self.fence.newest() else { + return skip("uninitialized"); + }; + if newest.committed_at.elapsed() > budget { + return skip("stale"); + } + match self + .proved_reader(read_pool, observability::ReaderOperation::Maintenance) + .await + { + Ok((tx, entry)) if entry.committed_at.elapsed() <= budget => Some((tx, "fresh")), + Ok((_tx, _entry)) => skip("stale"), + Err(reason) => skip(reason), + } + } + /// Shared route decision for one read: evaluate the predicate against a /// proved reader session and record the decision. Fail closed to the /// writer everywhere. @@ -956,6 +1528,7 @@ impl Db { &self, path: &'static str, predicate: RoutePredicate, + operation: observability::ReaderOperation, ) -> RouteDecision { let Some(read_pool) = &self.read_pool else { Self::record_route(path, "writer", "disabled"); @@ -998,7 +1571,7 @@ impl Db { Self::record_route(path, "writer", reason); return RouteDecision::Writer; } - match self.proved_reader(read_pool).await { + match self.proved_reader(read_pool, operation).await { Ok((tx, entry)) => { // Re-evaluate against the entry the session actually proved // (it may be older than the shared newest). @@ -1041,4 +1614,56 @@ impl Db { } #[cfg(test)] -mod tests; +mod pool_role_tests { + use super::{DbPoolRole, DbPoolStats}; + + #[test] + fn database_pool_role_vocabulary_is_exact() { + assert_eq!( + DbPoolRole::ALL.map(DbPoolRole::as_str), + ["writer", "reader", "audit", "search"] + ); + } + + #[test] + fn database_pool_active_connections_use_saturating_arithmetic() { + assert_eq!( + DbPoolStats { + size: 12, + idle: 5, + max: 20, + } + .active(), + 7 + ); + assert_eq!( + DbPoolStats { + size: 2, + idle: 3, + max: 20, + } + .active(), + 0 + ); + } + + /// `from_pool` must read the live SQLx handle rather than a cached copy. + /// A lazy pool never opens a connection, so this stays infrastructure-free. + #[tokio::test] + async fn database_pool_stats_are_read_from_the_physical_pool_handle() { + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(7) + .connect_lazy(&crate::test_support::database_url()) + .expect("construct lazy pool"); + + let stats = DbPoolStats::from_pool(&pool); + assert_eq!(stats.size, 0); + assert_eq!(stats.idle, 0); + assert_eq!(stats.active(), 0); + assert_eq!(stats.max, 7); + } +} + +#[cfg(test)] +#[path = "tests.rs"] +mod postgres_tests; diff --git a/crates/buzz-db/src/runtime/observability.rs b/crates/buzz-db/src/runtime/observability.rs index afe1d20b305..d487b9a3621 100644 --- a/crates/buzz-db/src/runtime/observability.rs +++ b/crates/buzz-db/src/runtime/observability.rs @@ -4,26 +4,179 @@ //! never derive labels from tenant data, events, SQL text, or query identifiers. use std::future::Future; +use std::sync::Mutex; use std::time::{Duration, Instant}; +use super::DbPoolRole; + +/// One valid pool/operation acquisition family. +/// +/// Keeping role and operation in one enum makes invalid combinations +/// unrepresentable at call sites and gives the series budget one exhaustive +/// source of truth. +#[repr(usize)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum PoolOperation { + WriterBootstrap, + ReaderBootstrap, + WriterReadiness, + WriterTenantResolution, + WriterAuthentication, + WriterAuthorization, + ReaderAuthorization, + WriterSubscriptionHistory, + ReaderSubscriptionHistory, + WriterEventWrite, + WriterMaintenance, + ReaderMaintenance, +} + +/// Writer-pool operations. Reader-only combinations cannot be constructed. #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(crate) enum PoolRole { - Writer, - Reader, +pub(crate) enum WriterOperation { + Bootstrap, + Readiness, + TenantResolution, + Authentication, + Authorization, + SubscriptionHistory, + EventWrite, + Maintenance, } -impl PoolRole { +impl WriterOperation { #[cfg(test)] - pub(crate) const ALL: [Self; 2] = [Self::Writer, Self::Reader]; + const ALL: [Self; 8] = [ + Self::Bootstrap, + Self::Readiness, + Self::TenantResolution, + Self::Authentication, + Self::Authorization, + Self::SubscriptionHistory, + Self::EventWrite, + Self::Maintenance, + ]; - pub(crate) const fn as_str(self) -> &'static str { + const fn pair(self) -> PoolOperation { + match self { + Self::Bootstrap => PoolOperation::WriterBootstrap, + Self::Readiness => PoolOperation::WriterReadiness, + Self::TenantResolution => PoolOperation::WriterTenantResolution, + Self::Authentication => PoolOperation::WriterAuthentication, + Self::Authorization => PoolOperation::WriterAuthorization, + Self::SubscriptionHistory => PoolOperation::WriterSubscriptionHistory, + Self::EventWrite => PoolOperation::WriterEventWrite, + Self::Maintenance => PoolOperation::WriterMaintenance, + } + } +} + +/// Reader-pool operations. Writer-only combinations cannot be constructed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ReaderOperation { + Bootstrap, + Authorization, + SubscriptionHistory, + /// Leader-only background reads such as fleet usage telemetry. + Maintenance, +} + +impl ReaderOperation { + #[cfg(test)] + const ALL: [Self; 4] = [ + Self::Bootstrap, + Self::Authorization, + Self::SubscriptionHistory, + Self::Maintenance, + ]; + + const fn pair(self) -> PoolOperation { + match self { + Self::Bootstrap => PoolOperation::ReaderBootstrap, + Self::Authorization => PoolOperation::ReaderAuthorization, + Self::SubscriptionHistory => PoolOperation::ReaderSubscriptionHistory, + Self::Maintenance => PoolOperation::ReaderMaintenance, + } + } + + /// Whether a dropped checkout must close the connection under SQLx's + /// bounded `close_on_drop` instead of returning it to the pool. + /// + /// Maintenance reads run under relay-side deadlines that drop them + /// mid-query when a reader goes dark. SQLx's return-to-pool path pings + /// that connection with no timeout while still holding a pool slot, and + /// the reader pool is shared with serving reads, so each abandoned read + /// would strand a serving slot until the kernel gives up on the socket. + /// Serving reads keep pooled reuse. + pub(crate) const fn bounded_release(self) -> bool { + matches!(self, Self::Maintenance) + } +} + +impl PoolOperation { + pub(crate) const ALL: [Self; 12] = [ + Self::WriterBootstrap, + Self::ReaderBootstrap, + Self::WriterReadiness, + Self::WriterTenantResolution, + Self::WriterAuthentication, + Self::WriterAuthorization, + Self::ReaderAuthorization, + Self::WriterSubscriptionHistory, + Self::ReaderSubscriptionHistory, + Self::WriterEventWrite, + Self::WriterMaintenance, + Self::ReaderMaintenance, + ]; + + pub(crate) const fn pool_role(self) -> &'static str { + match self { + Self::ReaderBootstrap + | Self::ReaderAuthorization + | Self::ReaderSubscriptionHistory + | Self::ReaderMaintenance => DbPoolRole::Reader.as_str(), + _ => DbPoolRole::Writer.as_str(), + } + } + + pub(crate) const fn operation(self) -> &'static str { match self { - Self::Writer => "writer", - Self::Reader => "reader", + Self::WriterBootstrap | Self::ReaderBootstrap => "bootstrap", + Self::WriterReadiness => "readiness", + Self::WriterTenantResolution => "tenant_resolution", + Self::WriterAuthentication => "authentication", + Self::WriterAuthorization | Self::ReaderAuthorization => "authorization", + Self::WriterSubscriptionHistory | Self::ReaderSubscriptionHistory => { + "subscription_history" + } + Self::WriterEventWrite => "event_write", + Self::WriterMaintenance | Self::ReaderMaintenance => "maintenance", } } + + const fn index(self) -> usize { + self as usize + } } +pub(crate) const POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 12] = [ + (DbPoolRole::Writer.as_str(), "bootstrap"), + (DbPoolRole::Reader.as_str(), "bootstrap"), + (DbPoolRole::Writer.as_str(), "readiness"), + (DbPoolRole::Writer.as_str(), "tenant_resolution"), + (DbPoolRole::Writer.as_str(), "authentication"), + (DbPoolRole::Writer.as_str(), "authorization"), + (DbPoolRole::Reader.as_str(), "authorization"), + (DbPoolRole::Writer.as_str(), "subscription_history"), + (DbPoolRole::Reader.as_str(), "subscription_history"), + (DbPoolRole::Writer.as_str(), "event_write"), + (DbPoolRole::Writer.as_str(), "maintenance"), + (DbPoolRole::Reader.as_str(), "maintenance"), +]; + +/// Twelve valid pairs × (12 histogram series + 1 start counter + 4 outcome counters + 1 gauge). +pub(crate) const POOL_ACQUIRE_RAW_SERIES_PER_POD: usize = POOL_ACQUIRE_VALID_PAIRS.len() * 18; + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum LockType { Replacement, @@ -31,16 +184,18 @@ pub(crate) enum LockType { PushGate, Deletion, MigrationSchemaSafety, + PartitionMaintenance, } impl LockType { #[cfg(test)] - pub(crate) const ALL: [Self; 5] = [ + pub(crate) const ALL: [Self; 6] = [ Self::Replacement, Self::Membership, Self::PushGate, Self::Deletion, Self::MigrationSchemaSafety, + Self::PartitionMaintenance, ]; pub(crate) const fn as_str(self) -> &'static str { @@ -50,6 +205,7 @@ impl LockType { Self::PushGate => "push_gate", Self::Deletion => "deletion", Self::MigrationSchemaSafety => "migration_schema_safety", + Self::PartitionMaintenance => "partition_maintenance", } } } @@ -59,17 +215,19 @@ pub(crate) enum Outcome { Success, Error, Timeout, + Cancelled, } impl Outcome { #[cfg(test)] - pub(crate) const ALL: [Self; 3] = [Self::Success, Self::Error, Self::Timeout]; + pub(crate) const ALL: [Self; 4] = [Self::Success, Self::Error, Self::Timeout, Self::Cancelled]; pub(crate) const fn as_str(self) -> &'static str { match self { Self::Success => "success", Self::Error => "error", Self::Timeout => "timeout", + Self::Cancelled => "cancelled", } } @@ -92,17 +250,21 @@ pub(crate) enum TransactionOperation { AcceptPushLeaseEvent, BeginCommunityDeletionQuiescing, FenceCommunityDeletion, + CommunityArchiveFence, + InactiveCommunityFence, } impl TransactionOperation { #[cfg(test)] - pub(crate) const ALL: [Self; 6] = [ + pub(crate) const ALL: [Self; 8] = [ Self::ReplaceParameterizedEvent, Self::ReplaceAddressableEvent, Self::PublishNip43MembershipLocked, Self::AcceptPushLeaseEvent, Self::BeginCommunityDeletionQuiescing, Self::FenceCommunityDeletion, + Self::CommunityArchiveFence, + Self::InactiveCommunityFence, ]; pub(crate) const fn as_str(self) -> &'static str { @@ -113,44 +275,288 @@ impl TransactionOperation { Self::AcceptPushLeaseEvent => "accept_push_lease_event", Self::BeginCommunityDeletionQuiescing => "begin_community_deletion_quiescing", Self::FenceCommunityDeletion => "fence_community_deletion", + Self::CommunityArchiveFence => "community_archive_fence", + Self::InactiveCommunityFence => "inactive_community_fence", + } + } + + /// Whether this transaction's writer checkout also feeds the legacy + /// `buzz_db_pool_acquire_wait_seconds` / `buzz_db_pool_acquisitions_total` + /// families. Only seams that predate operation-labelled pool metrics do; + /// later seams must not change those families' observed population. + const fn emits_legacy_pool_metrics(self) -> bool { + match self { + Self::ReplaceParameterizedEvent + | Self::ReplaceAddressableEvent + | Self::PublishNip43MembershipLocked + | Self::AcceptPushLeaseEvent + | Self::BeginCommunityDeletionQuiescing + | Self::FenceCommunityDeletion => true, + Self::CommunityArchiveFence | Self::InactiveCommunityFence => false, + } + } + + const fn writer_operation(self) -> WriterOperation { + match self { + Self::ReplaceParameterizedEvent + | Self::ReplaceAddressableEvent + | Self::PublishNip43MembershipLocked + | Self::AcceptPushLeaseEvent => WriterOperation::EventWrite, + Self::BeginCommunityDeletionQuiescing + | Self::FenceCommunityDeletion + | Self::CommunityArchiveFence + | Self::InactiveCommunityFence => WriterOperation::Maintenance, } } } -pub(crate) fn record_pool_acquire(role: PoolRole, outcome: Outcome, elapsed: Duration) { +fn record_pool_acquire( + pair: PoolOperation, + outcome: Outcome, + elapsed: Duration, + emit_legacy: bool, +) { + // Preserve the original observed population for existing dashboards. + // Newly instrumented raw-pool seams must not create a deployment-time + // discontinuity in these compatibility families. + if emit_legacy && outcome != Outcome::Cancelled { + metrics::histogram!( + "buzz_db_pool_acquire_wait_seconds", + "pool_role" => pair.pool_role(), + "outcome" => outcome.as_str(), + ) + .record(elapsed.as_secs_f64()); + metrics::counter!( + "buzz_db_pool_acquisitions_total", + "pool_role" => pair.pool_role(), + "outcome" => outcome.as_str(), + ) + .increment(1); + } + metrics::histogram!( - "buzz_db_pool_acquire_wait_seconds", - "pool_role" => role.as_str(), - "outcome" => outcome.as_str(), + "buzz_db_pool_acquire_duration_seconds", + "pool_role" => pair.pool_role(), + "operation" => pair.operation(), ) .record(elapsed.as_secs_f64()); metrics::counter!( - "buzz_db_pool_acquisitions_total", - "pool_role" => role.as_str(), + "buzz_db_pool_acquire_attempts_total", + "pool_role" => pair.pool_role(), + "operation" => pair.operation(), "outcome" => outcome.as_str(), ) .increment(1); } -pub(crate) async fn acquire( +static POOL_WAITERS: [Mutex; PoolOperation::ALL.len()] = + [const { Mutex::new(0) }; PoolOperation::ALL.len()]; + +#[cfg(test)] +static POOL_METRICS_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +#[cfg(test)] +#[derive(Clone)] +struct WaiterPublishTestHook { + pair: PoolOperation, + value: u64, + entered: std::sync::Arc, + release: std::sync::Arc, + armed: std::sync::Arc, +} + +#[cfg(test)] +static WAITER_PUBLISH_TEST_HOOK: Mutex> = Mutex::new(None); + +#[cfg(test)] +static WAITER_LAST_PUBLISHED: [Mutex; PoolOperation::ALL.len()] = + [const { Mutex::new(u64::MAX) }; PoolOperation::ALL.len()]; + +fn publish_waiters(pair: PoolOperation, value: u64) { + #[cfg(test)] + { + let hook = WAITER_PUBLISH_TEST_HOOK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + if let Some(hook) = hook { + if hook.pair == pair + && hook.value == value + && hook.armed.swap(false, std::sync::atomic::Ordering::SeqCst) + { + hook.entered.wait(); + hook.release.wait(); + } + } + *WAITER_LAST_PUBLISHED[pair.index()] + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = value; + } + metrics::gauge!( + "buzz_db_pool_waiters", + "pool_role" => pair.pool_role(), + "operation" => pair.operation(), + ) + .set(value as f64); +} + +/// Re-publish every valid waiter pair, including healthy zero, so exporter +/// idle eviction cannot turn an expected zero into ambiguous missing data. +pub(crate) fn refresh_pool_waiters(include_reader: bool) { + for pair in PoolOperation::ALL { + if pair.pool_role() == DbPoolRole::Reader.as_str() && !include_reader { + continue; + } + let waiters = POOL_WAITERS[pair.index()] + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + publish_waiters(pair, *waiters); + } +} + +/// Owns one polled connection acquisition until exactly one terminal. +/// +/// Because async function bodies do not run until first poll, a future that is +/// constructed and immediately dropped emits nothing. Once armed, dropping it +/// while awaiting SQLx records `cancelled`, duration, and the balanced waiter +/// decrement. +struct PoolAcquireAttempt { + pair: PoolOperation, + started: Instant, + emit_legacy: bool, + terminal: bool, +} + +impl PoolAcquireAttempt { + fn start(pair: PoolOperation, emit_legacy: bool) -> Self { + metrics::counter!( + "buzz_db_pool_acquire_started_total", + "pool_role" => pair.pool_role(), + "operation" => pair.operation(), + ) + .increment(1); + { + let mut waiters = POOL_WAITERS[pair.index()] + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + *waiters += 1; + publish_waiters(pair, *waiters); + } + Self { + pair, + started: Instant::now(), + emit_legacy, + terminal: false, + } + } + + fn finish(mut self, outcome: Outcome) { + self.terminal = true; + record_pool_acquire(self.pair, outcome, self.started.elapsed(), self.emit_legacy); + self.release_waiter(); + } + + fn release_waiter(&self) { + let mut waiters = POOL_WAITERS[self.pair.index()] + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + debug_assert!(*waiters > 0, "pool waiter balance underflow"); + *waiters = waiters.saturating_sub(1); + publish_waiters(self.pair, *waiters); + } +} + +impl Drop for PoolAcquireAttempt { + fn drop(&mut self) { + if !self.terminal { + record_pool_acquire( + self.pair, + Outcome::Cancelled, + self.started.elapsed(), + self.emit_legacy, + ); + self.release_waiter(); + self.terminal = true; + } + } +} + +async fn acquire( pool: &sqlx::PgPool, - role: PoolRole, + pair: PoolOperation, + emit_legacy: bool, ) -> sqlx::Result> { - let started = Instant::now(); + let attempt = PoolAcquireAttempt::start(pair, emit_legacy); let result = pool.acquire().await; let outcome = result .as_ref() .map(|_| Outcome::Success) .unwrap_or_else(Outcome::from_sqlx_error); - record_pool_acquire(role, outcome, started.elapsed()); + attempt.finish(outcome); result } +/// Acquire from an authoritative writer pool for one valid writer operation. +pub(crate) async fn acquire_writer( + pool: &sqlx::PgPool, + operation: WriterOperation, +) -> sqlx::Result> { + acquire(pool, operation.pair(), false).await +} + +/// Acquire from a writer seam already covered by the pre-operation metric. +pub(crate) async fn acquire_writer_with_legacy_metrics( + pool: &sqlx::PgPool, + operation: WriterOperation, +) -> sqlx::Result> { + acquire(pool, operation.pair(), true).await +} + +/// Acquire from a reader seam already covered by the pre-operation metric. +pub(super) async fn acquire_reader_with_legacy_metrics( + pool: &sqlx::PgPool, + operation: ReaderOperation, +) -> sqlx::Result> { + acquire(pool, operation.pair(), true).await +} + +/// Acquire within an operation-owned absolute deadline. +/// +/// A deadline expiry is a timeout terminal. Dropping the enclosing future +/// before that deadline remains a cancellation terminal. +pub(crate) async fn acquire_writer_until( + pool: &sqlx::PgPool, + operation: WriterOperation, + deadline: tokio::time::Instant, +) -> sqlx::Result> { + let pair = operation.pair(); + let attempt = PoolAcquireAttempt::start(pair, false); + match tokio::time::timeout_at(deadline, pool.acquire()).await { + Err(_) => { + attempt.finish(Outcome::Timeout); + Err(sqlx::Error::PoolTimedOut) + } + Ok(result) => { + let outcome = result + .as_ref() + .map(|_| Outcome::Success) + .unwrap_or_else(Outcome::from_sqlx_error); + attempt.finish(outcome); + result + } + } +} + pub(crate) async fn begin_transaction( pool: &sqlx::PgPool, operation: TransactionOperation, ) -> sqlx::Result<(sqlx::Transaction<'static, sqlx::Postgres>, TransactionTimer)> { - let connection = acquire(pool, PoolRole::Writer).await?; + let writer = operation.writer_operation(); + let connection = if operation.emits_legacy_pool_metrics() { + acquire_writer_with_legacy_metrics(pool, writer).await? + } else { + acquire_writer(pool, writer).await? + }; let transaction = sqlx::Transaction::begin(connection, None).await?; Ok((transaction, TransactionTimer::start(operation))) } @@ -221,16 +627,45 @@ impl Drop for TransactionTimer { #[cfg(test)] mod tests { use super::{ - acquire, observe_advisory_lock, record_pool_acquire, LockType, Outcome, PoolRole, - TransactionOperation, TransactionTimer, + acquire_reader_with_legacy_metrics, acquire_writer, acquire_writer_with_legacy_metrics, + begin_transaction, observe_advisory_lock, record_pool_acquire, refresh_pool_waiters, + LockType, Outcome, PoolAcquireAttempt, PoolOperation, ReaderOperation, + TransactionOperation, TransactionTimer, WriterOperation, }; use metrics_util::debugging::{DebugValue, DebuggingRecorder}; use std::collections::{BTreeMap, BTreeSet}; + use std::sync::{Arc, Barrier}; use std::time::Duration; #[test] fn label_vocabularies_are_closed_and_documented() { - assert_eq!(PoolRole::ALL.map(PoolRole::as_str), ["writer", "reader"]); + assert_eq!( + PoolOperation::ALL.map(|pair| (pair.pool_role(), pair.operation())), + super::POOL_ACQUIRE_VALID_PAIRS + ); + assert_eq!( + WriterOperation::ALL.map(WriterOperation::pair), + [ + PoolOperation::WriterBootstrap, + PoolOperation::WriterReadiness, + PoolOperation::WriterTenantResolution, + PoolOperation::WriterAuthentication, + PoolOperation::WriterAuthorization, + PoolOperation::WriterSubscriptionHistory, + PoolOperation::WriterEventWrite, + PoolOperation::WriterMaintenance, + ] + ); + assert_eq!( + ReaderOperation::ALL.map(ReaderOperation::pair), + [ + PoolOperation::ReaderBootstrap, + PoolOperation::ReaderAuthorization, + PoolOperation::ReaderSubscriptionHistory, + PoolOperation::ReaderMaintenance, + ] + ); + assert_eq!(super::POOL_ACQUIRE_RAW_SERIES_PER_POD, 216); assert_eq!( LockType::ALL.map(LockType::as_str), [ @@ -239,11 +674,12 @@ mod tests { "push_gate", "deletion", "migration_schema_safety", + "partition_maintenance", ] ); assert_eq!( Outcome::ALL.map(Outcome::as_str), - ["success", "error", "timeout"] + ["success", "error", "timeout", "cancelled"] ); assert_eq!( TransactionOperation::ALL.map(TransactionOperation::as_str), @@ -254,6 +690,8 @@ mod tests { "accept_push_lease_event", "begin_community_deletion_quiescing", "fence_community_deletion", + "community_archive_fence", + "inactive_community_fence", ] ); } @@ -311,14 +749,16 @@ mod tests { let _guard = metrics::set_default_local_recorder(&recorder); record_pool_acquire( - PoolRole::Writer, + PoolOperation::WriterReadiness, Outcome::Success, Duration::from_millis(12), + false, ); record_pool_acquire( - PoolRole::Reader, + PoolOperation::ReaderSubscriptionHistory, Outcome::Timeout, Duration::from_millis(34), + true, ); let lock_ok: sqlx::Result<()> = observe_advisory_lock(LockType::Replacement, async { Ok(()) }).await; @@ -353,18 +793,10 @@ mod tests { .collect::>(); for expected in [ - ( - "buzz_db_pool_acquire_wait_seconds", - [("outcome", "success"), ("pool_role", "writer")], - ), ( "buzz_db_pool_acquire_wait_seconds", [("outcome", "timeout"), ("pool_role", "reader")], ), - ( - "buzz_db_pool_acquisitions_total", - [("outcome", "success"), ("pool_role", "writer")], - ), ( "buzz_db_pool_acquisitions_total", [("outcome", "timeout"), ("pool_role", "reader")], @@ -410,6 +842,65 @@ mod tests { "missing metric series {expected:?}; got {keys:?}" ); } + for name in [ + "buzz_db_pool_acquire_wait_seconds", + "buzz_db_pool_acquisitions_total", + ] { + assert!( + !keys.contains(&( + name.to_owned(), + [ + ("outcome".to_owned(), "success".to_owned()), + ("pool_role".to_owned(), "writer".to_owned()), + ] + .into_iter() + .collect(), + )), + "newly instrumented seams must not expand legacy metric population" + ); + } + + for (name, labels) in [ + ( + "buzz_db_pool_acquire_duration_seconds", + [("operation", "readiness"), ("pool_role", "writer")], + ), + ( + "buzz_db_pool_acquire_duration_seconds", + [ + ("operation", "subscription_history"), + ("pool_role", "reader"), + ], + ), + ] { + let labels = labels + .into_iter() + .map(|(key, value)| (key.to_owned(), value.to_owned())) + .collect(); + assert!( + keys.contains(&(name.to_owned(), labels)), + "missing operation-aware pool duration for {name}" + ); + } + for (pool_role, operation, outcome) in [ + ("writer", "readiness", "success"), + ("reader", "subscription_history", "timeout"), + ] { + assert!(keys.contains(&( + "buzz_db_pool_acquire_attempts_total".to_owned(), + [ + ("operation".to_owned(), operation.to_owned()), + ("outcome".to_owned(), outcome.to_owned()), + ("pool_role".to_owned(), pool_role.to_owned()), + ] + .into_iter() + .collect(), + ))); + } + assert!(keys.iter().all(|(name, labels)| { + name != "buzz_db_pool_acquire_duration_seconds" + || (!labels.contains_key("outcome") && !labels.contains_key("result")) + })); for (key, _, _, value) in snapshot { if key.key().name().ends_with("_seconds") { @@ -426,43 +917,438 @@ mod tests { } } + #[test] + fn cancelled_attempt_records_terminal_and_refreshes_zero() { + let _test_guard = super::POOL_METRICS_TEST_LOCK.blocking_lock(); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + + let attempt = PoolAcquireAttempt::start(PoolOperation::WriterTenantResolution, false); + let in_flight = snapshotter.snapshot().into_vec(); + assert!(in_flight.iter().any(|(key, _, _, value)| { + let labels = key + .key() + .labels() + .map(|label| (label.key(), label.value())) + .collect::>(); + matches!(value, DebugValue::Counter(1)) + && key.key().name() == "buzz_db_pool_acquire_started_total" + && labels.get("pool_role") == Some(&"writer") + && labels.get("operation") == Some(&"tenant_resolution") + })); + assert!( + in_flight.iter().all(|(key, _, _, _)| { + key.key().name() != "buzz_db_pool_acquire_attempts_total" + }), + "the request-start signal must be observable before its terminal" + ); + drop(attempt); + refresh_pool_waiters(true); + + let mut saw_cancelled = false; + let mut saw_zero = false; + for (key, _, _, value) in snapshotter.snapshot().into_vec() { + let labels = key + .key() + .labels() + .map(|label| (label.key(), label.value())) + .collect::>(); + if labels.get("operation") != Some(&"tenant_resolution") { + continue; + } + match key.key().name() { + "buzz_db_pool_acquire_attempts_total" => { + let DebugValue::Counter(value) = value else { + panic!("attempt terminals must be a counter"); + }; + saw_cancelled = labels.get("outcome") == Some(&"cancelled") && value == 1; + } + "buzz_db_pool_waiters" => { + let DebugValue::Gauge(value) = value else { + panic!("pool waiters must be a gauge"); + }; + saw_zero = value.into_inner() == 0.0; + } + _ => {} + } + } + assert!( + saw_cancelled, + "dropped armed attempt must terminalize cancellation" + ); + assert!(saw_zero, "periodic refresh must publish a healthy zero"); + } + + #[test] + fn waiter_refresh_omits_reader_pairs_when_no_reader_pool_is_configured() { + let _test_guard = super::POOL_METRICS_TEST_LOCK.blocking_lock(); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + + refresh_pool_waiters(false); + + let published = snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter_map(|(key, _, _, value)| { + if key.key().name() != "buzz_db_pool_waiters" { + return None; + } + let DebugValue::Gauge(value) = value else { + panic!("pool waiters must be gauges"); + }; + assert_eq!(value.into_inner(), 0.0); + let labels = key + .key() + .labels() + .map(|label| (label.key().to_owned(), label.value().to_owned())) + .collect::>(); + Some((labels["pool_role"].clone(), labels["operation"].clone())) + }) + .collect::>(); + let expected = WriterOperation::ALL + .into_iter() + .map(|operation| { + let pair = operation.pair(); + (pair.pool_role().to_owned(), pair.operation().to_owned()) + }) + .collect::>(); + + assert_eq!(published, expected); + assert!(published.iter().all(|(pool_role, _)| pool_role == "writer")); + } + #[tokio::test(flavor = "current_thread")] - #[ignore = "requires Postgres"] + async fn compatibility_metrics_only_cover_preexisting_acquisition_seams() { + let _test_guard = super::POOL_METRICS_TEST_LOCK.lock().await; + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let pool = sqlx::postgres::PgPoolOptions::new() + .connect_lazy(&crate::test_support::database_url()) + .expect("construct lazy compatibility test pool"); + pool.close().await; + + let error = acquire_writer(&pool, WriterOperation::EventWrite) + .await + .expect_err("closed newly instrumented seam errors"); + assert!(matches!(error, sqlx::Error::PoolClosed)); + assert_eq!( + legacy_acquisition_count(&snapshotter.snapshot().into_vec()), + 0 + ); + + for operation in [ + TransactionOperation::CommunityArchiveFence, + TransactionOperation::InactiveCommunityFence, + ] { + let Err(error) = begin_transaction(&pool, operation).await else { + panic!("closed newly instrumented transaction seam errors"); + }; + assert!(matches!(error, sqlx::Error::PoolClosed)); + } + assert_eq!( + legacy_acquisition_count(&snapshotter.snapshot().into_vec()), + 0, + "community lifecycle fences must not expand the legacy pool families" + ); + + let error = acquire_writer_with_legacy_metrics(&pool, WriterOperation::EventWrite) + .await + .expect_err("closed legacy seam errors"); + assert!(matches!(error, sqlx::Error::PoolClosed)); + assert_eq!( + legacy_acquisition_count(&snapshotter.snapshot().into_vec()), + 1 + ); + + let Err(error) = + begin_transaction(&pool, TransactionOperation::FenceCommunityDeletion).await + else { + panic!("closed legacy transaction seam errors"); + }; + assert!(matches!(error, sqlx::Error::PoolClosed)); + // `snapshot()` drains counters, so each assertion sees only the + // acquisitions recorded since the previous snapshot. + assert_eq!( + legacy_acquisition_count(&snapshotter.snapshot().into_vec()), + 1, + "pre-existing deletion fences keep their legacy pool population" + ); + } + + fn legacy_acquisition_count( + snapshot: &[( + metrics_util::CompositeKey, + Option, + Option, + DebugValue, + )], + ) -> u64 { + snapshot + .iter() + .filter_map(|(key, _, _, value)| { + (key.key().name() == "buzz_db_pool_acquisitions_total") + .then_some(value) + .map(|value| match value { + DebugValue::Counter(value) => *value, + _ => panic!("legacy acquisitions must be a counter"), + }) + }) + .sum() + } + + #[test] + fn concurrent_attempts_publish_an_exact_balanced_waiter_count() { + const ATTEMPTS: usize = 8; + + let _test_guard = super::POOL_METRICS_TEST_LOCK.blocking_lock(); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let armed = Arc::new(Barrier::new(ATTEMPTS + 1)); + let release = Arc::new(Barrier::new(ATTEMPTS + 1)); + let threads = (0..ATTEMPTS) + .map(|_| { + let armed = Arc::clone(&armed); + let release = Arc::clone(&release); + std::thread::spawn(move || { + let attempt = + PoolAcquireAttempt::start(PoolOperation::WriterTenantResolution, false); + armed.wait(); + release.wait(); + drop(attempt); + }) + }) + .collect::>(); + + armed.wait(); + refresh_pool_waiters(true); + let live = waiter_value( + &snapshotter.snapshot().into_vec(), + "writer", + "tenant_resolution", + ); + assert_eq!(live, Some(ATTEMPTS as f64)); + + release.wait(); + for thread in threads { + thread.join().expect("waiter thread completes"); + } + refresh_pool_waiters(true); + let balanced = waiter_value( + &snapshotter.snapshot().into_vec(), + "writer", + "tenant_resolution", + ); + assert_eq!(balanced, Some(0.0)); + } + + #[test] + fn waiter_publication_is_serialized_with_state_mutation() { + let _test_guard = super::POOL_METRICS_TEST_LOCK.blocking_lock(); + let pair = PoolOperation::WriterTenantResolution; + let first = PoolAcquireAttempt::start(pair, false); + let second = PoolAcquireAttempt::start(pair, false); + let entered = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + *super::WAITER_PUBLISH_TEST_HOOK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + Some(super::WaiterPublishTestHook { + pair, + value: 1, + entered: Arc::clone(&entered), + release: Arc::clone(&release), + armed: Arc::new(std::sync::atomic::AtomicBool::new(true)), + }); + + let first_drop = std::thread::spawn(move || drop(first)); + entered.wait(); + let mutation_lock_held = super::POOL_WAITERS[pair.index()].try_lock().is_err(); + release.wait(); + first_drop.join().expect("first drop completes"); + drop(second); + *super::WAITER_PUBLISH_TEST_HOOK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = None; + + assert!( + mutation_lock_held, + "waiter state mutation must remain locked until its publication completes" + ); + assert_eq!( + *super::WAITER_LAST_PUBLISHED[pair.index()] + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner), + 0, + "the final directly published waiter value must be balanced without a refresh" + ); + } + + fn waiter_value( + snapshot: &[( + metrics_util::CompositeKey, + Option, + Option, + DebugValue, + )], + pool_role: &str, + operation: &str, + ) -> Option { + snapshot.iter().find_map(|(key, _, _, value)| { + let labels = key.key().labels().collect::>(); + if key.key().name() != "buzz_db_pool_waiters" + || !labels + .iter() + .any(|label| label.key() == "pool_role" && label.value() == pool_role) + || !labels + .iter() + .any(|label| label.key() == "operation" && label.value() == operation) + { + return None; + } + let DebugValue::Gauge(value) = value else { + panic!("pool waiters must be gauges"); + }; + Some(value.into_inner()) + }) + } + async fn pool_acquire_records_success_timeout_and_error_with_wait_time() { - let database_url = std::env::var("TEST_DATABASE_URL") - .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_owned()); // sadscan:disable np.postgres.1 -- local test-only credentials + // This timeout also bounds the pool's initial connection. Leave enough + // headroom for a cold PostgreSQL start under the lane's eight workers; + // the assertion below cares about classification, not a sub-second + // synthetic timeout budget. + let database_url = crate::test_support::database_url(); let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(1) - .acquire_timeout(Duration::from_millis(75)) + .acquire_timeout(Duration::from_secs(5)) .connect(&database_url) .await .expect("connect size-one test pool"); + let reader_pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(Duration::from_secs(5)) + .connect(&database_url) + .await + .expect("connect size-one reader test pool"); let recorder = DebuggingRecorder::new(); let snapshotter = recorder.snapshotter(); let _guard = metrics::set_default_local_recorder(&recorder); - let held = acquire(&pool, PoolRole::Writer) + let held = acquire_writer_with_legacy_metrics(&pool, WriterOperation::EventWrite) .await .expect("writer acquire succeeds"); - let timeout = acquire(&pool, PoolRole::Reader) + let mut cancelled = Box::pin(acquire_writer_with_legacy_metrics( + &pool, + WriterOperation::Authentication, + )); + tokio::select! { + result = &mut cancelled => panic!("blocked acquisition unexpectedly completed: {result:?}"), + () = tokio::time::sleep(Duration::from_millis(40)) => {} + } + let before_cancel = snapshotter.snapshot().into_vec(); + let live_waiter = before_cancel.iter().find_map(|(key, _, _, value)| { + let labels = key.key().labels().collect::>(); + if key.key().name() != "buzz_db_pool_waiters" + || !labels + .iter() + .any(|label| label.key() == "pool_role" && label.value() == "writer") + || !labels + .iter() + .any(|label| label.key() == "operation" && label.value() == "authentication") + { + return None; + } + let DebugValue::Gauge(value) = value else { + panic!("pool waiters must be a gauge"); + }; + Some(value.into_inner()) + }); + assert_eq!(live_waiter, Some(1.0)); + let legacy_before_cancel = legacy_acquisition_count(&before_cancel); + assert_eq!( + legacy_before_cancel, 1, + "the completed legacy acquisition must be counted exactly once" + ); + let writer_success = before_cancel.iter().any(|(key, _, _, value)| { + if key.key().name() != "buzz_db_pool_acquire_wait_seconds" { + return false; + } + let labels = key.key().labels().collect::>(); + let DebugValue::Histogram(samples) = value else { + panic!("pool wait must be a histogram"); + }; + labels + .iter() + .any(|label| label.key() == "pool_role" && label.value() == "writer") + && labels + .iter() + .any(|label| label.key() == "outcome" && label.value() == "success") + && !samples.is_empty() + }); + drop(cancelled); + let after_cancel = snapshotter.snapshot().into_vec(); + let legacy_after_cancel = legacy_acquisition_count(&after_cancel); + let mut cancelled_terminal = None; + let mut balanced_waiter = None; + for (key, _, _, value) in after_cancel { + let labels = key.key().labels().collect::>(); + let label = |name: &str| { + labels + .iter() + .find(|label| label.key() == name) + .map(|label| label.value()) + }; + if label("pool_role") != Some("writer") || label("operation") != Some("authentication") + { + continue; + } + match key.key().name() { + "buzz_db_pool_waiters" => { + let DebugValue::Gauge(value) = value else { + panic!("pool waiters must be a gauge"); + }; + balanced_waiter = Some(value.into_inner()); + } + "buzz_db_pool_acquire_attempts_total" if label("outcome") == Some("cancelled") => { + let DebugValue::Counter(value) = value else { + panic!("cancelled acquisition terminal must be a counter"); + }; + cancelled_terminal = Some(value); + } + _ => {} + } + } + assert_eq!(balanced_waiter, Some(0.0)); + assert_eq!(cancelled_terminal, Some(1)); + assert_eq!( + legacy_after_cancel, 0, + "cancelling a legacy seam must not expand its historical population" + ); + let held_reader = reader_pool + .acquire() .await - .expect_err("reader-labeled checkout times out while pool is saturated"); + .expect("hold the reader test connection"); + let timeout = + acquire_reader_with_legacy_metrics(&reader_pool, ReaderOperation::SubscriptionHistory) + .await + .expect_err("reader-labeled checkout times out while pool is saturated"); assert!(matches!(timeout, sqlx::Error::PoolTimedOut)); + drop(held_reader); drop(held); pool.close().await; - let closed = acquire(&pool, PoolRole::Writer) + let closed = acquire_writer_with_legacy_metrics(&pool, WriterOperation::Readiness) .await .expect_err("closed pool acquire errors"); assert!(matches!(closed, sqlx::Error::PoolClosed)); let mut outcomes = BTreeMap::<(String, String), Vec>::new(); for (key, _, _, value) in snapshotter.snapshot().into_vec() { - if key.key().name() != "buzz_db_pool_acquire_wait_seconds" { - continue; - } - let DebugValue::Histogram(samples) = value else { - panic!("pool wait must be a histogram"); - }; let labels = key.key().labels().collect::>(); let label = |name: &str| { labels @@ -471,15 +1357,27 @@ mod tests { .map(|label| label.value().to_owned()) .unwrap_or_default() }; - outcomes.insert( - (label("pool_role"), label("outcome")), - samples - .into_iter() - .map(|sample| sample.into_inner()) - .collect(), - ); + if key.key().name() == "buzz_db_pool_acquire_wait_seconds" { + let DebugValue::Histogram(samples) = value else { + panic!("pool wait must be a histogram"); + }; + if samples.is_empty() { + continue; + } + outcomes.insert( + (label("pool_role"), label("outcome")), + samples + .into_iter() + .map(|sample| sample.into_inner()) + .collect(), + ); + } } - assert!(outcomes.contains_key(&("writer".to_owned(), "success".to_owned()))); + assert!(writer_success); + assert!( + !outcomes.contains_key(&("writer".to_owned(), "cancelled".to_owned())), + "legacy compatibility families must not add a cancellation population" + ); assert!(outcomes.contains_key(&("writer".to_owned(), "error".to_owned()))); let timeout_samples = outcomes .get(&("reader".to_owned(), "timeout".to_owned())) @@ -490,11 +1388,391 @@ mod tests { ); } - #[tokio::test(flavor = "current_thread")] - #[ignore = "requires Postgres"] + async fn deletion_catalog_readiness_records_timeout_and_recovers() { + let _test_guard = super::POOL_METRICS_TEST_LOCK.lock().await; + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(Duration::from_secs(5)) + .connect(&crate::test_support::database_url()) + .await + .expect("connect size-one deletion readiness pool"); + let db = crate::Db::from_pool(pool.clone()); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + + let held = pool.acquire().await.expect("hold the only pool connection"); + let timeout = db + .validate_deletion_serving_catalog_for_readiness( + tokio::time::Instant::now() + Duration::from_millis(40), + ) + .await + .expect_err("saturated deletion catalog checkout must time out"); + assert!(matches!( + timeout, + crate::DbError::Sqlx(sqlx::Error::PoolTimedOut) + )); + drop(held); + db.validate_deletion_serving_catalog_for_readiness( + tokio::time::Instant::now() + Duration::from_secs(2), + ) + .await + .expect("deletion catalog readiness must recover after pool release"); + + let snapshot = snapshotter.snapshot().into_vec(); + assert_eq!( + waiter_value(&snapshot, "writer", "readiness"), + Some(0.0), + "deadline terminal must directly balance the readiness waiter" + ); + for outcome in ["timeout", "success"] { + assert!( + snapshot.iter().any(|(key, _, _, value)| { + if key.key().name() != "buzz_db_pool_acquire_attempts_total" { + return false; + } + let labels = key.key().labels().collect::>(); + let has = |name: &str, expected: &str| { + labels + .iter() + .any(|label| label.key() == name && label.value() == expected) + }; + has("pool_role", "writer") + && has("operation", "readiness") + && has("outcome", outcome) + && matches!(value, DebugValue::Counter(1)) + }), + "missing writer/readiness/{outcome} acquisition terminal" + ); + } + } + + async fn production_db_methods_emit_exact_pool_operation_labels() { + use buzz_core::CommunityId; + use chrono::Utc; + use uuid::Uuid; + + let database_url = crate::test_support::database_url(); + let writer_pool = crate::Db::connect_writer_pool(&crate::DbConfig { + database_url: database_url.clone(), + max_connections: 4, + min_connections: 0, + acquire_timeout_secs: 5, + ..crate::DbConfig::default() + }) + .await + .expect("connect production-method writer pool"); + let reader_pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(4) + .acquire_timeout(Duration::from_secs(5)) + .connect(&database_url) + .await + .expect("connect production-method reader pool"); + let writer_db = crate::Db::from_pool(writer_pool.clone()); + let mut routed_db = crate::Db::from_pools(writer_pool.clone(), reader_pool); + routed_db.set_replica_read_max_age_for_tests(Some(Duration::from_secs(5))); + + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let test_scope = CommunityId::from_uuid(Uuid::new_v4()); + let query = crate::EventQuery::for_community(test_scope); + + routed_db.read_pool_boot_ping_for_tests().await; + routed_db + .verify_replica_fence_at_boot() + .await + .expect("real startup fence verification succeeds"); + let _ = crate::replica_fence::probe_once(&writer_pool, routed_db.fence()).await; + routed_db.fence().force_open_for_tests(Utc::now()); + assert_eq!( + writer_db + .readiness_check(tokio::time::Instant::now() + Duration::from_secs(1)) + .await, + crate::DbReadinessOutcome::Success + ); + let _ = writer_db + .lookup_community_by_host("pool-operation-matrix.invalid") + .await; + let _ = writer_db + .lookup_community_by_host_for_management("pool-operation-matrix.invalid") + .await; + let _ = writer_db.list_communities_owned_by(&"a".repeat(64)).await; + let _ = writer_db.lookup_community_host(test_scope).await; + let _ = writer_db + .set_community_icon(test_scope, Some("pool-operation-matrix")) + .await; + let _ = writer_db + .create_community_with_owner( + &format!("pool-operation-matrix-{}.invalid", Uuid::new_v4().simple()), + &"b".repeat(64), + ) + .await; + let _ = writer_db + .archive_community_owned_by( + "pool-operation-matrix.invalid", + &"c".repeat(64), + "protected.invalid", + ) + .await; + let _ = writer_db + .unarchive_community_owned_by("pool-operation-matrix.invalid", &"c".repeat(64)) + .await; + let _ = writer_db.community_of_channel(Uuid::new_v4()).await; + let _ = writer_db.communities_of_channels(&[Uuid::new_v4()]).await; + let _ = writer_db + .ensure_user_for_authorization(test_scope, &[17; 32]) + .await; + let _ = writer_db + .set_agent_owner_for_authorization(test_scope, &[18; 32], &[19; 32]) + .await; + let _ = writer_db.is_pubkey_allowed(test_scope, &[7; 32]).await; + let _ = writer_db + .is_agent_owner(test_scope, &[8; 32], &[9; 32]) + .await; + let _ = writer_db + .moderation_restriction_state(test_scope, &[14; 32]) + .await; + let _ = writer_db + .get_agent_channel_policy(test_scope, &[15; 32]) + .await; + let _ = writer_db + .get_thread_metadata_by_event(test_scope, &[10; 32]) + .await; + let _ = writer_db.get_thread_summary(test_scope, &[16; 32]).await; + let _ = writer_db + .get_channel_for_event_write(test_scope, Uuid::new_v4()) + .await; + let _ = writer_db + .get_members_for_event_write(test_scope, Uuid::new_v4()) + .await; + let _ = writer_db + .get_users_bulk_for_event_write(test_scope, &[vec![11; 32]]) + .await; + let _ = writer_db + .huddle_started_link_exists_for_event_write( + test_scope, + Uuid::new_v4(), + Uuid::new_v4(), + &[12; 32], + ) + .await; + let _ = writer_db + .huddle_started_link_exists(test_scope, Uuid::new_v4(), Uuid::new_v4(), &[13; 32]) + .await; + let _ = writer_db.list_archived(test_scope).await; + let _ = writer_db + .query_events_routed("pool_operation_matrix_writer", &query) + .await; + // The scope is not a live community, so admission rejects it after the + // writer acquisition has been attributed to `event_write`. + let _ = writer_db.begin_event_write_transaction(test_scope).await; + let _ = writer_db + .with_inactive_community_fence(test_scope, |_| ()) + .await; + let _ = writer_db.usage_community_count().await; + let _ = writer_db.reap_expired_ephemeral_channels().await; + let deletion_store = writer_db.deletion_store(); + let _ = deletion_store.reap_expired_serving_write_leases(1).await; + let _ = deletion_store.serving_lease_stats().await; + let _ = routed_db.is_relay_member(test_scope, &"a".repeat(64)).await; + let _ = routed_db + .query_events_routed("pool_operation_matrix_reader", &query) + .await; + let _ = routed_db.usage_fleet_stock_snapshot().await; + routed_db.refresh_pool_waiter_metrics(); + + let snapshot = snapshotter.snapshot().into_vec(); + let attempt_labels = snapshot + .iter() + .filter_map(|(key, _, _, value)| { + if key.key().name() != "buzz_db_pool_acquire_attempts_total" { + return None; + } + let DebugValue::Counter(value) = value else { + panic!("acquisition attempts must be counters"); + }; + if *value == 0 { + return None; + } + let labels = key + .key() + .labels() + .map(|label| (label.key().to_owned(), label.value().to_owned())) + .collect::>(); + assert_eq!(labels.get("outcome").map(String::as_str), Some("success")); + Some((labels["pool_role"].clone(), labels["operation"].clone())) + }) + .collect::>(); + let expected = super::POOL_ACQUIRE_VALID_PAIRS + .into_iter() + .map(|(pool_role, operation)| (pool_role.to_owned(), operation.to_owned())) + .collect::>(); + assert_eq!( + attempt_labels, expected, + "real production Db/store methods must emit every exact valid operation pair" + ); + + let duration_labels = snapshot + .iter() + .filter_map(|(key, _, _, value)| { + if key.key().name() != "buzz_db_pool_acquire_duration_seconds" { + return None; + } + let DebugValue::Histogram(samples) = value else { + panic!("acquisition duration must be a histogram"); + }; + assert!(!samples.is_empty()); + let labels = key + .key() + .labels() + .map(|label| (label.key(), label.value())) + .collect::>(); + assert!(!labels.contains_key("outcome")); + Some(( + labels["pool_role"].to_owned(), + labels["operation"].to_owned(), + )) + }) + .collect::>(); + assert_eq!(duration_labels, expected); + + let waiter_labels = snapshot + .iter() + .filter_map(|(key, _, _, value)| { + if key.key().name() != "buzz_db_pool_waiters" { + return None; + } + let DebugValue::Gauge(value) = value else { + panic!("pool waiters must be gauges"); + }; + assert_eq!(value.into_inner(), 0.0); + let labels = key + .key() + .labels() + .map(|label| (label.key(), label.value())) + .collect::>(); + Some(( + labels["pool_role"].to_owned(), + labels["operation"].to_owned(), + )) + }) + .collect::>(); + assert_eq!(waiter_labels, expected); + } + + async fn serving_write_gate_records_cancel_timeout_success_and_recovery() { + let _test_guard = super::POOL_METRICS_TEST_LOCK.lock().await; + let database_url = crate::test_support::database_url(); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + // The same budget also covers the pool's initial physical + // connection. Keep enough headroom for a cold CI database; the + // held size-one connection below still deterministically drives + // the checkout timeout terminal. + .acquire_timeout(Duration::from_secs(1)) + .connect(&database_url) + .await + .expect("connect size-one serving-write test pool"); + let db = crate::Db::from_pool(pool.clone()); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + db.migrate().await.expect("migrate serving-write test DB"); + } + let test_scope = db + .ensure_configured_community(&format!( + "pool-observability-{}.example", + uuid::Uuid::new_v4().simple() + )) + .await + .expect("create serving-write test community") + .id; + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let held = pool.acquire().await.expect("hold sole writer connection"); + + let store = db.deletion_store(); + let mut cancelled = Box::pin(store.is_serving_active(test_scope)); + tokio::select! { + result = &mut cancelled => panic!("blocked serving-write gate unexpectedly completed: {result:?}"), + () = tokio::time::sleep(Duration::from_millis(25)) => {} + } + assert_eq!( + waiter_value(&snapshotter.snapshot().into_vec(), "writer", "event_write"), + Some(1.0) + ); + drop(cancelled); + + let timeout = store + .is_serving_active(test_scope) + .await + .expect_err("saturated serving-write gate times out"); + assert!(matches!( + timeout, + crate::DbError::Sqlx(sqlx::Error::PoolTimedOut) + )); + drop(held); + + assert!(store + .is_serving_active(test_scope) + .await + .expect("serving-write gate recovers after release")); + let lease = store + .acquire_serving_write_lease( + test_scope, + "pool_observability", + "pool-observability-test", + Duration::from_secs(5), + ) + .await + .expect("serving-write lease acquires through event-write seam"); + assert!(store + .release_serving_write_lease(&lease) + .await + .expect("serving-write lease release")); + refresh_pool_waiters(false); + + let snapshot = snapshotter.snapshot().into_vec(); + assert_eq!(waiter_value(&snapshot, "writer", "event_write"), Some(0.0)); + assert_eq!(attempt_count(&snapshot, "event_write", "cancelled"), 1); + assert_eq!(attempt_count(&snapshot, "event_write", "timeout"), 1); + assert!( + attempt_count(&snapshot, "event_write", "success") >= 3, + "gate recovery plus lease acquire/release must emit successes" + ); + } + + fn attempt_count( + snapshot: &[( + metrics_util::CompositeKey, + Option, + Option, + DebugValue, + )], + operation: &str, + outcome: &str, + ) -> u64 { + snapshot + .iter() + .find_map(|(key, _, _, value)| { + let labels = key.key().labels().collect::>(); + (key.key().name() == "buzz_db_pool_acquire_attempts_total" + && labels + .iter() + .any(|label| label.key() == "operation" && label.value() == operation) + && labels + .iter() + .any(|label| label.key() == "outcome" && label.value() == outcome)) + .then(|| match value { + DebugValue::Counter(value) => *value, + _ => panic!("pool attempts must be a counter"), + }) + }) + .unwrap_or(0) + } + async fn advisory_lock_records_success_contention_timeout_and_error() { - let database_url = std::env::var("TEST_DATABASE_URL") - .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_owned()); // sadscan:disable np.postgres.1 -- local test-only credentials + let database_url = crate::test_support::database_url(); let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(4) .connect(&database_url) @@ -633,4 +1911,36 @@ mod tests { "lock timer must include the holder wait: {contention:?}" ); } + + mod postgres_tests { + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn pool_acquire_records_success_timeout_and_error_with_wait_time() { + super::pool_acquire_records_success_timeout_and_error_with_wait_time().await; + } + + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn production_db_methods_emit_exact_pool_operation_labels() { + super::production_db_methods_emit_exact_pool_operation_labels().await; + } + + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn deletion_catalog_readiness_records_timeout_and_recovers() { + super::deletion_catalog_readiness_records_timeout_and_recovers().await; + } + + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn serving_write_gate_records_cancel_timeout_success_and_recovery() { + super::serving_write_gate_records_cancel_timeout_success_and_recovery().await; + } + + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn advisory_lock_records_success_contention_timeout_and_error() { + super::advisory_lock_records_success_contention_timeout_and_error().await; + } + } } diff --git a/crates/buzz-db/src/runtime/push_enqueue.rs b/crates/buzz-db/src/runtime/push_enqueue.rs new file mode 100644 index 00000000000..3cbfd7cc802 --- /dev/null +++ b/crates/buzz-db/src/runtime/push_enqueue.rs @@ -0,0 +1,312 @@ +//! Bounded best-effort push production, strictly after event commit. + +use std::sync::Arc; +use std::time::Duration; + +use buzz_core::CommunityId; +use sqlx::{postgres::PgPoolOptions, PgPool}; +use tokio::sync::{mpsc, Mutex}; +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; + +pub(crate) const CAPACITY: usize = 256; +const ENQUEUE_TIMEOUT: Duration = Duration::from_secs(2); + +#[derive(Clone, Debug)] +pub(crate) struct PushEnqueue { + sender: mpsc::Sender, + cancel: CancellationToken, + task: Arc>>>, +} + +#[derive(Debug)] +struct Job { + community: CommunityId, + event_id: Vec, + #[cfg(test)] + barrier: Option>, +} + +impl PushEnqueue { + pub(crate) fn new(writer: &PgPool) -> Self { + // No connection from the serving pool is ever consumed by push work. + // This lazy pool cannot make relay startup depend on push availability. + let pool = PgPoolOptions::new() + .max_connections(1) + .min_connections(0) + .acquire_timeout(ENQUEUE_TIMEOUT) + .connect_lazy_with( + (*writer.connect_options()) + .clone() + .application_name("buzz-push-enqueue"), + ); + let (sender, mut receiver) = mpsc::channel::(CAPACITY); + let cancel = CancellationToken::new(); + let stopped = cancel.clone(); + let task = tokio::spawn(async move { + loop { + let job = tokio::select! { + biased; + _ = stopped.cancelled() => break, + job = receiver.recv() => match job { + Some(job) => job, + None => break, + }, + }; + #[cfg(test)] + if let Some(barrier) = job.barrier { + let _ = barrier.send(()); + continue; + } + let result = tokio::select! { + biased; + _ = stopped.cancelled() => { + record_drop("shutdown"); + break; + }, + result = tokio::time::timeout(ENQUEUE_TIMEOUT, enqueue(&pool, &job, #[cfg(test)] None)) => result, + }; + match result { + Ok(Ok(())) => { + metrics::counter!("buzz_push_enqueue_total", "result" => "completed") + .increment(1); + } + Ok(Err(error)) => { + record_drop("error"); + tracing::warn!(%error, community = %job.community, "push enqueue failed after message commit"); + } + Err(_) => record_drop("timeout"), + } + } + receiver.close(); + while receiver.try_recv().is_ok() { + record_drop("shutdown"); + } + if tokio::time::timeout(ENQUEUE_TIMEOUT, pool.close()) + .await + .is_err() + { + tracing::warn!("push enqueue pool close exceeded shutdown deadline"); + } + }); + Self { + sender, + cancel, + task: Arc::new(Mutex::new(Some(task))), + } + } + + pub(crate) fn submit(&self, community: CommunityId, event_id: Vec) { + if self.cancel.is_cancelled() { + record_drop("shutdown"); + return; + } + if let Err(error) = self.sender.try_send(Job { + community, + event_id, + #[cfg(test)] + barrier: None, + }) { + record_drop(match error { + mpsc::error::TrySendError::Full(_) => "full", + mpsc::error::TrySendError::Closed(_) => "closed", + }); + } + } + + #[cfg(test)] + pub(crate) async fn flush(&self) { + let (sender, receiver) = tokio::sync::oneshot::channel(); + self.sender + .send(Job { + community: CommunityId::from_uuid(uuid::Uuid::nil()), + event_id: Vec::new(), + barrier: Some(sender), + }) + .await + .expect("producer open"); + receiver.await.expect("producer completed preceding work"); + } + + pub(crate) fn cancel(&self) { + self.cancel.cancel(); + } + + pub(crate) async fn join(&self) { + if let Some(task) = self.task.lock().await.take() { + if let Err(error) = task.await { + tracing::warn!(%error, "push enqueue worker failed"); + } + } + } +} + +pub(crate) fn record_drop(reason: &'static str) { + metrics::counter!("buzz_push_enqueue_total", "result" => reason).increment(1); +} + +#[cfg(test)] +type GateBarrier = ( + tokio::sync::oneshot::Sender, + tokio::sync::oneshot::Receiver<()>, +); + +/// Pause the real enqueue transaction after it acquires the production gate. +#[cfg(test)] +pub(crate) async fn enqueue_with_gate_barrier( + pool: &PgPool, + community: CommunityId, + event_id: Vec, + barrier: GateBarrier, +) -> crate::Result<()> { + enqueue( + pool, + &Job { + community, + event_id, + barrier: None, + }, + Some(barrier), + ) + .await +} + +async fn enqueue( + pool: &PgPool, + job: &Job, + #[cfg(test)] gate_barrier: Option, +) -> crate::Result<()> { + let mut tx = pool.begin().await?; + // Server-side deadlines also bound work if the client disconnects or the + // task is cancelled. These apply only to the dedicated push connection. + sqlx::query("SELECT set_config('lock_timeout', '500ms', true), set_config('statement_timeout', '1500ms', true)") + .execute(&mut *tx).await?; + crate::deletion::DeletionStore::new(pool.clone()) + .guard_transaction(&mut tx, job.community) + .await?; + sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))") + .bind(crate::push::push_gate_lock_key(job.community)) + .execute(&mut *tx) + .await?; + #[cfg(test)] + if let Some((held, release)) = gate_barrier { + let pid = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *tx) + .await?; + held.send(pid) + .expect("race test observes enqueue transaction"); + release + .await + .expect("race test releases enqueue transaction"); + } + // Compare recorded receipt/update times without imposing commit ordering. + // Registration overlapping message arrival may send or suppress a wake. + // This bounded job never scans historical messages on lease activation. + sqlx::query( + "INSERT INTO push_match_queue (community_id, event_id) \ + SELECT $1, $2 FROM events e \ + WHERE e.community_id = $1 AND e.id = $2 AND e.deleted_at IS NULL \ + AND EXISTS (SELECT 1 FROM push_leases l \ + WHERE l.community_id = $1 AND l.active AND l.endpoint_enabled \ + AND l.updated_at <= e.received_at \ + AND l.expires_at > EXTRACT(EPOCH FROM now())::bigint) \ + ON CONFLICT DO NOTHING", + ) + .bind(job.community.as_uuid()) + .bind(&job.event_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn saturation_and_shutdown_never_wait_for_a_receiver() { + let (sender, mut receiver) = mpsc::channel(CAPACITY); + let producer = PushEnqueue { + sender, + cancel: CancellationToken::new(), + task: Arc::new(Mutex::new(None)), + }; + let community = CommunityId::from_uuid(uuid::Uuid::new_v4()); + for _ in 0..CAPACITY + 1 { + producer.submit(community, vec![1; 32]); + } + assert_eq!(receiver.len(), CAPACITY); + receiver.try_recv().unwrap(); + producer.cancel(); + producer.submit(community, vec![2; 32]); + assert_eq!(receiver.len(), CAPACITY - 1); + producer.join().await; + } + + mod postgres_tests { + use super::*; + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn enqueue_admits_active_tenant_and_rejects_quiescing_tenant() { + let (db, communities) = crate::test_support::admission_fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + for (index, community) in communities[..2].iter().enumerate() { + sqlx::query( + "INSERT INTO events \ + (community_id, id, pubkey, created_at, kind, tags, content, sig) \ + VALUES ($1, $2, $3, to_timestamp(1), 9, '[]', '', $4)", + ) + .bind(community.as_uuid()) + .bind(vec![index as u8; 32]) + .bind(vec![1_u8; 32]) + .bind(vec![2_u8; 64]) + .execute(&db.pool) + .await + .expect("seed event"); + sqlx::query( + "INSERT INTO push_leases (community_id, author, installation_id, \ + source_event_id, source_created_at, generation, active, endpoint_hash, \ + endpoint_grant, max_class, subscriptions, expires_at, updated_at) \ + VALUES ($1, $2, 'test', $3, 1, 1, true, $4, 'grant', 'default', '[]', \ + EXTRACT(EPOCH FROM now())::bigint + 3600, now() - interval '1 hour')", + ) + .bind(community.as_uuid()) + .bind(vec![3_u8; 32]) + .bind(vec![4_u8; 32]) + .bind(vec![5_u8; 32]) + .execute(&db.pool) + .await + .expect("seed lease"); + } + let active = Job { + community: communities[0], + event_id: vec![0_u8; 32], + barrier: None, + }; + let quiescing = Job { + community: communities[1], + event_id: vec![1_u8; 32], + barrier: None, + }; + let err = enqueue(&db.pool, &quiescing, None) + .await + .expect_err("quiescing enqueue"); + assert!(crate::test_support::is_admission_rejection(&err)); + enqueue(&db.pool, &active, None) + .await + .expect("admitted enqueue"); + for (community, expected) in [(communities[0], 1), (communities[1], 0)] { + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM push_match_queue WHERE community_id = $1", + ) + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .expect("read enqueue state"); + assert_eq!(count, expected, "queue state for {community}"); + } + } + } +} diff --git a/crates/buzz-db/src/runtime/replica_fence.rs b/crates/buzz-db/src/runtime/replica_fence.rs index cf9b46ddd8b..520ff9e8698 100644 --- a/crates/buzz-db/src/runtime/replica_fence.rs +++ b/crates/buzz-db/src/runtime/replica_fence.rs @@ -10,10 +10,12 @@ //! is armed per session via the `buzz.created_at_floor` GUC, which the //! relay's writer pool sets on every connection. //! 2. **Ordered heartbeat handshake** (this module): on one pinned writer -//! connection, separately-awaited statements sample -//! `S = clock_timestamp()`, then scan `pg_stat_activity` for the oldest -//! open transaction, then — **last** — commit heartbeat token `M` via a -//! single-row `UPDATE replica_heartbeat ... RETURNING token, epoch` +//! connection, one transaction first takes the exclusive replica-floor +//! advisory lock (draining compliant shared-lock channel writers), then +//! separately-awaited statements sample `S = clock_timestamp()`, scan +//! `pg_stat_activity` for the oldest open transaction, and — **last** — +//! commit heartbeat token `M` via a single-row +//! `UPDATE replica_heartbeat ... RETURNING token, epoch` //! (migration 0026). Because the single-row UPDATE serializes all pods' //! probes, tokens are globally commit-ordered. A reader **session** that //! observes `token >= M` on its own connection has, by WAL/storage replay @@ -73,6 +75,14 @@ use buzz_datastore_tracing::datastore_span; /// and the fence subtracts it; the two uses must never diverge. pub const CREATED_AT_FLOOR_SECS: i64 = 960; +/// Deployment-global advisory-lock key ordering compliant channel-event write +/// transactions against the writer probe handshake. +/// +/// Shared holders are channel-event write transactions validating `created_at` +/// under the armed floor contract; the probe takes the exclusive lock before +/// sampling and publishing its heartbeat token. +pub const REPLICA_FLOOR_LOCK_KEY: i64 = 0x62757a7a666c6f72; + /// Safety margin subtracted from the fence on top of the floor. /// /// All proof timestamps (`clock_timestamp()`, `xact_start`, the guard's @@ -395,7 +405,12 @@ pub async fn verify_floor_guard_behavior(pool: &PgPool) -> crate::Result<()> { } }; - let mut tx = pool.begin().await?; + let connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::Bootstrap, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; // 1. Pool arming (Perci: assert the effective value, not the intent). let armed: String = sqlx::query_scalar("SHOW buzz.created_at_floor") @@ -545,18 +560,28 @@ pub enum ProbeError { HeartbeatRowMissing, } -/// Take one ordered writer sample: S, then activity scan, then commit the -/// heartbeat token **last**. +/// Take one ordered writer sample: under the exclusive replica-floor lock, +/// sample S, then activity scan, then commit the heartbeat token **last**. /// -/// The statements are separately awaited on a single pinned connection; +/// The statements are separately awaited on one pinned writer transaction; /// a single SELECT would not guarantee evaluation order across the /// subexpressions, reopening the race this ordering exists to close. async fn sample_writer(writer: &PgPool) -> Result { - let mut conn = writer.acquire().await?; + let connection = crate::observability::acquire_writer( + writer, + crate::observability::WriterOperation::Maintenance, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(REPLICA_FLOOR_LOCK_KEY) + .execute(&mut *tx) + .await?; // 1. S first. let sampled_at: DateTime = sqlx::query_scalar("SELECT clock_timestamp()") - .fetch_one(&mut *conn) + .fetch_one(&mut *tx) .await?; // 2. Activity scan. Classification (fail closed on anything unknown): @@ -603,7 +628,7 @@ async fn sample_writer(writer: &PgPool) -> Result { ) AS masked "#, ) - .fetch_one(&mut *conn) + .fetch_one(&mut *tx) .await?; let masked: i64 = row.get("masked"); if masked > 0 { @@ -620,17 +645,19 @@ async fn sample_writer(writer: &PgPool) -> Result { let row = sqlx::query( "UPDATE replica_heartbeat SET token = token + 1 WHERE id = 1 RETURNING token, epoch", ) - .fetch_optional(&mut *conn) + .fetch_optional(&mut *tx) .await? .ok_or(ProbeError::HeartbeatRowMissing)?; - Ok(WriterSample { + let sample = WriterSample { sampled_at, oldest_xact_start, token: row.get("token"), epoch: row.get("epoch"), committed_at, - }) + }; + tx.commit().await?; + Ok(sample) } /// The fence wall proved by one handshake: @@ -671,11 +698,16 @@ pub async fn probe_once(writer: &PgPool, fence: &ReplicaFence) -> Result) { } #[cfg(test)] -mod tests { +mod postgres_tests { use super::*; - const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 - - fn test_db_url() -> String { - std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.into()) - } - /// A private scratch database with migrations applied: the probe tests /// mutate the singleton heartbeat row (rewind/rotate), which must never /// race the shared dev database or each other. async fn scratch_db() -> (PgPool, PgPool, String) { - let admin = PgPool::connect(&test_db_url()) + let admin = PgPool::connect(&crate::test_support::database_url()) .await .expect("connect admin"); let name = format!("fence_probe_{}", uuid::Uuid::new_v4().simple()); @@ -810,7 +836,7 @@ mod tests { .execute(&admin) .await .expect("create scratch db"); - let base = test_db_url(); + let base = crate::test_support::database_url(); let idx = base.rfind('/').expect("db url has a path segment"); let pool = PgPool::connect(&format!("{}/{}", &base[..idx], name)) .await @@ -973,17 +999,27 @@ mod tests { /// sessions, per the agreed classification. #[tokio::test] #[ignore = "requires Postgres"] - async fn sample_writer_sees_open_transactions_and_ignores_idle() { - let pool = PgPool::connect(&test_db_url()).await.expect("connect"); + async fn migration_schema_cluster_global_sample_writer_sees_open_transactions_and_ignores_idle() + { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect"); + crate::migration::run_migrations(&pool) + .await + .expect("apply migration schema"); // A plain idle session: pinned connection, no transaction. - let idle_pool = PgPool::connect(&test_db_url()).await.expect("connect idle"); + let idle_pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect idle"); let _idle_conn = idle_pool.acquire().await.expect("idle conn"); let before = sample_writer(&pool).await.expect("sample without tx"); // Now hold a transaction open on a second connection. - let tx_pool = PgPool::connect(&test_db_url()).await.expect("connect tx"); + let tx_pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect tx"); let mut tx = tx_pool.begin().await.expect("begin"); sqlx::query("SELECT 1") .execute(&mut *tx) @@ -1010,18 +1046,70 @@ mod tests { tx.rollback().await.expect("rollback"); } + /// The sample must not capture `S` while a compliant shared writer lock is + /// still held. It must block until release, then sample. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn sample_writer_waits_for_shared_floor_lock_before_sampling_time() { + let (admin, pool, name) = scratch_db().await; + + let mut blocker = pool.begin().await.expect("begin shared-lock blocker"); + sqlx::query("SELECT pg_advisory_xact_lock_shared($1)") + .bind(REPLICA_FLOOR_LOCK_KEY) + .execute(&mut *blocker) + .await + .expect("hold shared floor lock"); + + let sample_pool = pool.clone(); + let mut sampling = tokio::spawn(async move { sample_writer(&sample_pool).await }); + assert!( + tokio::time::timeout(Duration::from_millis(100), &mut sampling) + .await + .is_err(), + "sample_writer should block while a shared floor lock is held" + ); + + let marker_before_release: DateTime = sqlx::query_scalar("SELECT clock_timestamp()") + .fetch_one(&pool) + .await + .expect("capture marker while lock held"); + + blocker + .rollback() + .await + .expect("release shared-lock blocker"); + + let sample = tokio::time::timeout(Duration::from_secs(5), sampling) + .await + .expect("sample should complete after shared lock release") + .expect("sampling task") + .expect("sample writer"); + assert!( + sample.sampled_at >= marker_before_release, + "sample time {:?} must be at or after marker {:?}", + sample.sampled_at, + marker_before_release + ); + + drop_scratch_db(&admin, pool, &name).await; + } + /// An unprivileged probe role sees NULL `state`/`xact_start` for other /// sessions' rows in `pg_stat_activity`. The oldest-xact term is then /// untrustworthy and the sample must fail closed (`MaskedActivity`) — /// never silently `MIN()` the hidden row away. #[tokio::test] #[ignore = "requires Postgres"] - async fn sample_writer_fails_closed_when_activity_is_masked() { - let admin = PgPool::connect(&test_db_url()).await.expect("connect"); + async fn cluster_global_sample_writer_fails_closed_when_activity_is_masked() { + let admin = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect"); // Hold a transaction open as the privileged user: this is the row // the unprivileged probe must notice it cannot classify. - let tx_pool = PgPool::connect(&test_db_url()).await.expect("connect tx"); + let tx_pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect tx"); let mut tx = tx_pool.begin().await.expect("begin"); sqlx::query("SELECT 1") .execute(&mut *tx) @@ -1038,7 +1126,7 @@ mod tests { .await .expect("create unprivileged role"); - let base = test_db_url(); + let base = crate::test_support::database_url(); let unpriv_url = { let rest = base.strip_prefix("postgres://").expect("pg url"); let at = rest.rfind('@').expect("credentials in url"); @@ -1079,7 +1167,9 @@ mod tests { #[tokio::test] #[ignore = "requires Postgres"] async fn aurora_identity_probe_reports_false_on_plain_postgres() { - let pool = PgPool::connect(&test_db_url()).await.expect("connect"); + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect"); let mut conn = pool.acquire().await.expect("conn"); assert!( !reader_supports_aurora_identity(&mut conn) @@ -1100,7 +1190,7 @@ mod tests { /// same database observes a token/epoch that resolves that entry. #[tokio::test] #[ignore = "requires Postgres"] - async fn probe_commits_tokens_and_sessions_prove_coverage() { + async fn cluster_global_probe_commits_tokens_and_sessions_prove_coverage() { let (admin, pool, name) = scratch_db().await; let fence = ReplicaFence::new(); @@ -1155,7 +1245,7 @@ mod tests { /// epoch — fails the epoch check instead of proving stale coverage. #[tokio::test] #[ignore = "requires Postgres"] - async fn probe_rotates_epoch_on_same_epoch_token_regression() { + async fn cluster_global_probe_rotates_epoch_on_same_epoch_token_regression() { let (admin, pool, name) = scratch_db().await; let fence = ReplicaFence::new(); diff --git a/crates/buzz-db/src/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index 0c1f8e0f2e9..7ab06cbecc7 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -1,19 +1,412 @@ use super::*; use crate::{relay_members, thread}; use buzz_core::CommunityId; -use sqlx::PgPool; +use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter}; +use sqlx::{Connection, PgPool}; use uuid::Uuid; -const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; +const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials + +type ConnectionCounters = std::collections::BTreeMap<(String, String, Option), u64>; + +fn connection_counters(snapshotter: &Snapshotter) -> ConnectionCounters { + snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter_map(|(key, _, _, value)| { + let metric_name = key.key().name(); + if ![ + "buzz_db_connection_step_started_total", + "buzz_db_connection_step_attempts_total", + ] + .contains(&metric_name) + { + return None; + } + let DebugValue::Counter(value) = value else { + panic!("{metric_name} must be a counter"); + }; + let labels = key + .key() + .labels() + .map(|label| (label.key().to_owned(), label.value().to_owned())) + .collect::>(); + assert_eq!(labels.get("pool_role").map(String::as_str), Some("writer")); + Some(( + ( + metric_name.to_owned(), + labels + .get("step") + .expect("connection step label") + .to_owned(), + labels.get("outcome").cloned(), + ), + value, + )) + }) + .collect() +} + +fn connection_counter( + counters: &ConnectionCounters, + metric_name: &str, + step: DbConnectionStep, + outcome: Option, +) -> u64 { + counters + .get(&( + metric_name.to_owned(), + step.as_str().to_owned(), + outcome.map(|outcome| outcome.as_str().to_owned()), + )) + .copied() + .unwrap_or_default() +} async fn setup_db() -> Db { let database_url = std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.into()); let pool = PgPool::connect(&database_url) .await .expect("connect to test DB"); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() == Ok("migration") { + crate::migration::run_migrations(&pool) + .await + .expect("apply migration schema"); + } Db::from_pool(pool) } +/// A pool that becomes unavailable after the candidate read must end the +/// sweep at the first tenant, not cost one acquire attempt per tenant. +#[tokio::test] +async fn fleet_sweep_stops_at_first_unavailable_connection() { + let pool = sqlx::postgres::PgPoolOptions::new() + .connect_lazy(&crate::test_support::database_url()) + .expect("construct lazy sweep pool"); + pool.close().await; + let attempted = std::cell::Cell::new(0); + let candidates = (0..3).map(|_| { + attempted.set(attempted.get() + 1); + Uuid::new_v4() + }); + + let committed = sweep_admitted_communities( + &pool, + candidates, + observability::WriterOperation::Maintenance, + "test_sweep", + |_, _| async { Ok(()) }, + ) + .await; + + assert!(committed.is_empty()); + assert_eq!(attempted.get(), 1, "sweep must stop after the outage"); +} + +#[tokio::test] +async fn event_write_transaction_preserves_legacy_acquisition_metrics() { + use metrics_util::debugging::{DebugValue, DebuggingRecorder}; + + let pool = sqlx::postgres::PgPoolOptions::new() + .connect_lazy(&crate::test_support::database_url()) + .expect("construct lazy compatibility pool"); + pool.close().await; + let db = Db::from_pool(pool); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + + let result = db + .begin_event_write_transaction(CommunityId::from_uuid(Uuid::new_v4())) + .await; + assert!(matches!( + result, + Err(DbError::Sqlx(sqlx::Error::PoolClosed)) + )); + + let counters = snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter_map(|(key, _, _, value)| { + let name = key.key().name(); + if ![ + "buzz_db_pool_acquire_attempts_total", + "buzz_db_pool_acquisitions_total", + ] + .contains(&name) + { + return None; + } + let DebugValue::Counter(value) = value else { + panic!("pool acquisition terminals must be counters"); + }; + let labels = key + .key() + .labels() + .map(|label| (label.key().to_owned(), label.value().to_owned())) + .collect::>(); + Some(((name.to_owned(), labels), value)) + }) + .collect::>(); + let expected = [ + ( + ( + "buzz_db_pool_acquire_attempts_total".to_owned(), + [ + ("operation".to_owned(), "event_write".to_owned()), + ("outcome".to_owned(), "error".to_owned()), + ("pool_role".to_owned(), "writer".to_owned()), + ] + .into_iter() + .collect(), + ), + 1, + ), + ( + ( + "buzz_db_pool_acquisitions_total".to_owned(), + [ + ("outcome".to_owned(), "error".to_owned()), + ("pool_role".to_owned(), "writer".to_owned()), + ] + .into_iter() + .collect(), + ), + 1, + ), + ] + .into_iter() + .collect::>(); + assert_eq!(counters, expected); +} + +#[test] +fn nip43_reconciliation_compatibility_alias_is_preserved() { + #[allow(deprecated)] + async fn call( + db: &Db, + community_id: CommunityId, + relay_pubkey: &nostr::PublicKey, + ) -> crate::Result { + db.nip43_membership_snapshot_needs_reconciliation(community_id, relay_pubkey) + .await + } + + let _ = call; +} + +#[tokio::test] +async fn community_write_transaction_compatibility_metrics_are_limited_to_legacy_entrypoints() { + use metrics_util::debugging::DebuggingRecorder; + + let pool = sqlx::postgres::PgPoolOptions::new() + .connect_lazy(&crate::test_support::database_url()) + .expect("construct lazy compatibility pool"); + pool.close().await; + let db = Db::from_pool(pool); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let community = CommunityId::from_uuid(Uuid::new_v4()); + + let direct = begin_community_event_write_transaction( + &db.pool, + community, + observability::WriterOperation::EventWrite, + ) + .await; + assert!(matches!( + direct, + Err(DbError::Sqlx(sqlx::Error::PoolClosed)) + )); + assert_eq!( + legacy_acquisition_count(&snapshotter.snapshot().into_vec()), + 0, + "typed-only tenant-local chokepoint must not emit legacy compatibility metrics" + ); + + let legacy = db.begin_event_write_transaction(community).await; + assert!(matches!( + legacy, + Err(DbError::Sqlx(sqlx::Error::PoolClosed)) + )); + assert_eq!( + legacy_acquisition_count(&snapshotter.snapshot().into_vec()), + 1, + "Db::begin_event_write_transaction must preserve the legacy compatibility population" + ); +} + +fn legacy_acquisition_count( + snapshot: &[( + metrics_util::CompositeKey, + Option, + Option, + metrics_util::debugging::DebugValue, + )], +) -> u64 { + snapshot + .iter() + .filter_map(|(key, _, _, value)| { + (key.key().name() == "buzz_db_pool_acquisitions_total") + .then_some(value) + .map(|value| match value { + metrics_util::debugging::DebugValue::Counter(value) => *value, + _ => panic!("legacy acquisitions must be a counter"), + }) + }) + .sum() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn readiness_check_distinguishes_pool_exhaustion_from_success() { + let database_url = crate::test_support::database_url(); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&database_url) + .await + .expect("connect size-one readiness test pool"); + let held = pool + .acquire() + .await + .expect("hold the only readiness test connection"); + let db = Db::from_pool(pool); + + let exhausted = db + .readiness_check(tokio::time::Instant::now() + std::time::Duration::from_millis(25)) + .await; + assert_eq!(exhausted, DbReadinessOutcome::PoolTimeout); + + drop(held); + let recovered = db + .readiness_check(tokio::time::Instant::now() + std::time::Duration::from_secs(1)) + .await; + assert_eq!(recovered, DbReadinessOutcome::Success); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn readiness_check_classifies_closed_pool_query_timeout_and_query_error() { + let database_url = crate::test_support::database_url(); + + let closed_pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&database_url) + .await + .expect("connect closed readiness test pool"); + closed_pool.close().await; + let closed = Db::from_pool(closed_pool) + .readiness_check(tokio::time::Instant::now() + std::time::Duration::from_secs(1)) + .await; + assert_eq!(closed, DbReadinessOutcome::PoolError); + + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&database_url) + .await + .expect("connect query classification test pool"); + let db = Db::from_pool(pool); + + let timed_out = db + .readiness_check_sql( + tokio::time::Instant::now() + std::time::Duration::from_millis(25), + "SELECT pg_sleep(0.2)", + ) + .await; + assert_eq!(timed_out, DbReadinessOutcome::QueryTimeout); + + let query_error = db + .readiness_check_sql( + tokio::time::Instant::now() + std::time::Duration::from_secs(1), + "SELECT 1 / 0", + ) + .await; + assert_eq!(query_error, DbReadinessOutcome::QueryError); + + assert_eq!( + db.readiness_check(tokio::time::Instant::now() + std::time::Duration::from_secs(1)) + .await, + DbReadinessOutcome::Success, + "query failures must return the acquired connection to the pool" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn readiness_check_cancellation_balances_waiter_and_inflight_connection() { + let database_url = crate::test_support::database_url(); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&database_url) + .await + .expect("connect cancellation readiness test pool"); + let held = pool + .acquire() + .await + .expect("hold sole connection before waiter cancellation"); + let db = Db::from_pool(pool); + + let waiting_db = db.clone(); + let waiting = tokio::spawn(async move { + waiting_db + .readiness_check(tokio::time::Instant::now() + std::time::Duration::from_secs(5)) + .await + }); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + waiting.abort(); + assert!(waiting + .await + .expect_err("waiting check must be cancelled") + .is_cancelled()); + drop(held); + + assert_eq!( + db.readiness_check(tokio::time::Instant::now() + std::time::Duration::from_secs(1)) + .await, + DbReadinessOutcome::Success, + "cancelled pool waiter must not consume the released connection" + ); + + let querying_db = db.clone(); + let querying = tokio::spawn(async move { + querying_db + .readiness_check_sql( + tokio::time::Instant::now() + std::time::Duration::from_secs(5), + "SELECT pg_sleep(5)", + ) + .await + }); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + querying.abort(); + assert!(querying + .await + .expect_err("querying check must be cancelled") + .is_cancelled()); + + let recovered = tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let outcome = db + .readiness_check( + tokio::time::Instant::now() + std::time::Duration::from_millis(250), + ) + .await; + match outcome { + DbReadinessOutcome::Success => break outcome, + DbReadinessOutcome::PoolTimeout => tokio::task::yield_now().await, + unexpected => panic!( + "cancelled in-flight query produced unexpected recovery outcome: {unexpected:?}" + ), + } + } + }) + .await + .expect("cancelled in-flight query must return or replace its connection"); + assert_eq!(recovered, DbReadinessOutcome::Success); +} + async fn make_community(pool: &PgPool) -> Uuid { let id = Uuid::new_v4(); let host = format!("communities-of-channels-{}.example", id.simple()); @@ -28,7 +421,7 @@ async fn make_community(pool: &PgPool) -> Uuid { #[tokio::test] #[ignore = "requires Postgres"] -async fn database_guard_covers_legacy_writer_and_nip09_deletion() { +async fn migration_schema_database_guard_covers_legacy_writer_and_nip09_deletion() { use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; let db = setup_db().await; @@ -336,6 +729,26 @@ async fn database_guard_covers_legacy_writer_and_nip09_deletion() { assert_eq!(watermark.1, c.id.as_bytes().as_slice()); } +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_operator_listener_outbox_is_not_tenant_scoped() { + let db = setup_db().await; + let community = CommunityId::from_uuid(make_community(&db.pool).await); + let inventory = db + .deletion_store() + .inventory_schema(community) + .await + .expect("migrated deletion catalog should validate"); + + assert!( + !inventory + .scoped_tables + .iter() + .any(|table| table == "operator_listener_outbox"), + "operator-listener outbox is deployment-global, not tenant-scoped" + ); +} + // ---- Read-replica routing ------------------------------------------------ // // These tests pin the routing contract of `Db::read()` and the two routed @@ -394,8 +807,104 @@ async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { .await; } +#[tokio::test] +#[ignore = "requires Postgres"] +async fn push_gateway_profile_migration_converges_brownfield_authority() { + let admin = PgPool::connect(&admin_url().await) + .await + .expect("connect admin database"); + let (pool, name) = create_scratch_db_through(&admin, "push_profile", Some(47)).await; + let installation_id = Uuid::new_v4(); + let now = chrono::Utc::now(); + + sqlx::query( + "INSERT INTO push_gateway_installations(\ + id, app_attest_key_id, app_attest_public_key, assertion_counter, app_profile, \ + token_ciphertext, token_fingerprint, endpoint_epoch, expires_at) \ + VALUES($1, $2, $3, 0, 'buzz-ios-production', $4, $5, 1, $6)", + ) + .bind(installation_id) + .bind(vec![1_u8]) + .bind(vec![2_u8; 33]) + .bind(vec![3_u8]) + .bind(vec![4_u8; 32]) + .bind(now + chrono::Duration::days(1)) + .execute(&pool) + .await + .expect("insert legacy production installation"); + sqlx::query( + "INSERT INTO push_gateway_delegations(\ + id, installation_id, relay_pubkey, endpoint_epoch, generation, not_before, expires_at) \ + VALUES($1, $2, $3, 1, 1, $4, $5)", + ) + .bind(Uuid::new_v4()) + .bind(installation_id) + .bind(vec![5_u8; 32]) + .bind(now) + .bind(now + chrono::Duration::hours(1)) + .execute(&pool) + .await + .expect("insert delegation for legacy installation"); + + migration::run_migrations_through(&pool, 48) + .await + .expect("apply historical profile migration"); + + let legacy_installations: i64 = + sqlx::query_scalar("SELECT count(*) FROM push_gateway_installations") + .fetch_one(&pool) + .await + .expect("count legacy installations"); + let legacy_delegations: i64 = + sqlx::query_scalar("SELECT count(*) FROM push_gateway_delegations") + .fetch_one(&pool) + .await + .expect("count legacy delegations"); + assert_eq!(legacy_installations, 0); + assert_eq!(legacy_delegations, 0); + + sqlx::query( + "INSERT INTO push_gateway_installations(\ + id, app_attest_key_id, app_attest_public_key, assertion_counter, app_profile, \ + token_ciphertext, token_fingerprint, endpoint_epoch, expires_at) \ + VALUES($1, $2, $3, 0, 'buzz-ios-dogfood', $4, $5, 1, $6)", + ) + .bind(Uuid::new_v4()) + .bind(vec![6_u8]) + .bind(vec![7_u8; 33]) + .bind(vec![8_u8]) + .bind(vec![9_u8; 32]) + .bind(now + chrono::Duration::days(1)) + .execute(&pool) + .await + .expect("dogfood installation is accepted after migration"); + + let sandbox = sqlx::query( + "INSERT INTO push_gateway_installations(\ + id, app_attest_key_id, app_attest_public_key, assertion_counter, app_profile, \ + token_ciphertext, token_fingerprint, endpoint_epoch, expires_at) \ + VALUES($1, $2, $3, 0, 'buzz-ios-sandbox', $4, $5, 1, $6)", + ) + .bind(Uuid::new_v4()) + .bind(vec![10_u8]) + .bind(vec![11_u8; 33]) + .bind(vec![12_u8]) + .bind(vec![13_u8; 32]) + .bind(now + chrono::Duration::days(1)) + .execute(&pool) + .await; + assert!(sandbox.is_err(), "legacy sandbox profile must be rejected"); + + drop_scratch_db(&admin, pool, &name).await; + admin.close().await; +} + /// Insert identical community + channel rows into a database so the same /// (community, channel) ids resolve in both writer and replica. +/// +/// Raw SQL with only columns from the initial schema: some callers seed a +/// scratch database migrated to an older version, which lacks columns that +/// the current channel store writes (for example `labels`). async fn seed_community_channel( pool: &PgPool, community: Uuid, @@ -408,19 +917,28 @@ async fn seed_community_channel( .execute(pool) .await .expect("insert community"); - crate::channel::create_channel_with_id( - pool, - CommunityId::from_uuid(community), - channel, - &format!("replica-routing-{channel}"), - crate::channel::ChannelType::Stream, - crate::channel::ChannelVisibility::Open, - None, - author.public_key().to_bytes().as_slice(), - None, + let author = author.public_key().to_bytes(); + sqlx::query( + "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) \ + VALUES ($1, $2, $3, 'stream', 'open', $4)", ) + .bind(channel) + .bind(community) + .bind(format!("replica-routing-{channel}")) + .bind(author.as_slice()) + .execute(pool) .await .expect("create channel"); + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) \ + VALUES ($1, $2, $3, 'owner', $3)", + ) + .bind(community) + .bind(channel) + .bind(author.as_slice()) + .execute(pool) + .await + .expect("add channel owner"); } fn signed_event_at(keys: &nostr::Keys, content: &str, secs: u64) -> nostr::Event { @@ -2189,10 +2707,10 @@ async fn created_at_floor_guard_aborts_old_channel_rows_at_commit() { fn writer_pool_safety_hook_is_single_and_composed() { let source = include_str!("mod.rs"); let connect_pool = source - .split("async fn connect_pool") + .split("async fn connect_writer_pool") .nth(1) .and_then(|tail| tail.split("const READER_ACQUIRE_TIMEOUT").next()) - .expect("connect_pool source block"); + .expect("connect_writer_pool source block"); assert_eq!( connect_pool.matches(".after_connect(").count(), 1, @@ -2200,6 +2718,9 @@ fn writer_pool_safety_hook_is_single_and_composed() { ); assert!(connect_pool.contains("buzz.created_at_floor")); assert!(connect_pool.contains("SHOW transaction_isolation")); + assert!(connect_pool.contains("'lock_timeout'")); + assert!(connect_pool.contains("'idle_in_transaction_session_timeout'")); + assert!(connect_pool.contains("'statement_timeout'")); assert!(!connect_pool.contains("arm_floor_guard")); assert!(!connect_pool.contains("_arm_floor_guard")); assert!(!connect_pool.contains("allow(unused_variables)")); @@ -2211,12 +2732,154 @@ fn writer_pool_safety_hook_is_single_and_composed() { .expect("reader pool documentation"); assert!(reader_doc.contains("replica sessions are")); assert!(reader_doc.contains("read-only")); - assert!(!reader_doc.contains("Db::connect_pool")); + assert!(!reader_doc.contains("Db::connect_writer_pool")); } -#[tokio::test] +#[tokio::test(flavor = "current_thread")] +#[ignore = "requires Postgres"] +async fn writer_pool_metrics_record_every_initial_connection_ready() { + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let db = Db::new(&DbConfig { + database_url: crate::test_support::database_url(), + max_connections: 2, + min_connections: 2, + ..DbConfig::default() + }) + .await + .expect("connect instrumented writer pool"); + let counters = connection_counters(&snapshotter); + + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_started_total", + DbConnectionStep::WriterPool, + None, + ), + 1 + ); + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::WriterPool, + Some(DbConnectionOutcome::Succeeded), + ), + 1 + ); + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::PhysicalConnect, + Some(DbConnectionOutcome::Succeeded), + ), + 2 + ); + for step in [ + DbConnectionStep::CreatedAtFloor, + DbConnectionStep::SessionTimeouts, + DbConnectionStep::Isolation, + ] { + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_started_total", + step, + None, + ), + 2, + "every initial connection must start {}", + step.as_str(), + ); + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + step, + Some(DbConnectionOutcome::Succeeded), + ), + 2, + "every initial connection must complete {}", + step.as_str(), + ); + } + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::Ready, + Some(DbConnectionOutcome::Succeeded), + ), + 2 + ); + db.pool.close().await; +} + +#[tokio::test(flavor = "current_thread")] +#[ignore = "requires Postgres"] +async fn writer_pool_metrics_record_connection_created_after_startup() { + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let pool = Db::connect_writer_pool(&DbConfig { + database_url: crate::test_support::database_url(), + max_connections: 2, + min_connections: 1, + ..DbConfig::default() + }) + .await + .expect("connect instrumented size-one writer pool"); + let startup_counters = connection_counters(&snapshotter); + assert_eq!( + connection_counter( + &startup_counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::Ready, + Some(DbConnectionOutcome::Succeeded), + ), + 1 + ); + + let first = pool.acquire().await.expect("hold initial connection"); + let second = pool + .acquire() + .await + .expect("grow pool with a second connection"); + let growth_counters = connection_counters(&snapshotter); + assert_eq!( + connection_counter( + &growth_counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::Ready, + Some(DbConnectionOutcome::Succeeded), + ), + 1, + "a post-startup pool growth connection must traverse the same instrumented safety hook" + ); + assert_eq!( + connection_counter( + &growth_counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::PhysicalConnect, + Some(DbConnectionOutcome::Succeeded), + ), + 1, + ); + + drop(second); + drop(first); + pool.close().await; +} + +#[tokio::test(flavor = "current_thread")] #[ignore = "requires Postgres"] async fn writer_pool_rejects_non_read_committed_database_default() { + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); let admin = PgPool::connect(&admin_url().await) .await .expect("connect admin"); @@ -2246,6 +2909,26 @@ async fn writer_pool_rejects_non_read_committed_database_default() { || error.to_string().contains("pool timed out"), "unexpected isolation rejection: {error}" ); + let counters = connection_counters(&snapshotter); + assert!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::Isolation, + Some(DbConnectionOutcome::Failed), + ) > 0, + "the failing production hook must record the isolation failure" + ); + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::Ready, + Some(DbConnectionOutcome::Succeeded), + ), + 0, + "an isolation-rejected connection must never reach ready" + ); sqlx::query(sqlx::AssertSqlSafe(format!( "DROP DATABASE {name} WITH (FORCE)" @@ -2255,35 +2938,228 @@ async fn writer_pool_rejects_non_read_committed_database_default() { .expect("drop isolation test database"); } -/// The armed writer pool (`Db::new`) must enforce the floor end-to-end -/// through the public insert APIs, and the session GUC must be verifiably -/// set on pooled connections. -#[tokio::test] +#[tokio::test(flavor = "current_thread")] #[ignore = "requires Postgres"] -async fn armed_pool_rejects_old_channel_inserts_through_public_api() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed_pool, name) = create_scratch_db(&admin, "floor_pool").await; - - let author = nostr::Keys::generate(); - let community = Uuid::new_v4(); - let channel = Uuid::new_v4(); - seed_community_channel(&seed_pool, community, channel, &author).await; - - // Connect a Db the production way: after_connect arms the guard. - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); - let db = Db::new(&DbConfig { - database_url: scratch_url, - max_connections: 2, +async fn writer_pool_metrics_stop_after_session_timeout_setup_failure() { + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let error = Db::new(&DbConfig { + database_url: crate::test_support::database_url(), + max_connections: 1, + min_connections: 1, + acquire_timeout_secs: 1, + statement_timeout_ms: u64::MAX, ..DbConfig::default() }) .await - .expect("connect armed Db"); - let cid = CommunityId::from_uuid(community); - + .expect_err("Postgres must reject an out-of-range statement timeout"); + assert!( + error.to_string().contains("pool timed out") + || error.to_string().contains("invalid value for parameter") + ); + let counters = connection_counters(&snapshotter); + + assert!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::SessionTimeouts, + Some(DbConnectionOutcome::Failed), + ) > 0, + "the failing production hook must record the timeout-setup failure" + ); + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_started_total", + DbConnectionStep::Isolation, + None, + ), + 0, + "a timeout-setup failure must stop before isolation" + ); + assert_eq!( + connection_counter( + &counters, + "buzz_db_connection_step_attempts_total", + DbConnectionStep::Ready, + Some(DbConnectionOutcome::Succeeded), + ), + 0, + "a timeout-setup failure must never reach ready" + ); +} + +/// Session-timeout environment overrides retain PostgreSQL's `0 = disabled` +/// semantics and ignore invalid values. +#[test] +fn session_timeout_env_overlay_zero_passthrough_and_invalid_fallback() { + static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _guard = ENV_LOCK.lock().unwrap(); + let keys = [ + "BUZZ_DB_LOCK_TIMEOUT_MS", + "BUZZ_DB_IDLE_TXN_TIMEOUT_MS", + "BUZZ_DB_STATEMENT_TIMEOUT_MS", + ]; + let previous: Vec<_> = keys.iter().map(std::env::var_os).collect(); + let read = |config: DbConfig| { + ( + config.lock_timeout_ms, + config.idle_txn_timeout_ms, + config.statement_timeout_ms, + ) + }; + + for key in keys { + std::env::remove_var(key); + } + let unset = read(DbConfig::default().with_session_timeouts_from_env()); + + std::env::set_var("BUZZ_DB_LOCK_TIMEOUT_MS", "2000"); + std::env::set_var("BUZZ_DB_IDLE_TXN_TIMEOUT_MS", "30000"); + std::env::set_var("BUZZ_DB_STATEMENT_TIMEOUT_MS", "10000"); + let overridden = read(DbConfig::default().with_session_timeouts_from_env()); + + for key in keys { + std::env::set_var(key, "0"); + } + let zero = read(DbConfig::default().with_session_timeouts_from_env()); + + for key in keys { + std::env::set_var(key, "not-a-number"); + } + let junk = read(DbConfig::default().with_session_timeouts_from_env()); + + for (key, value) in keys.iter().zip(previous) { + match value { + Some(value) => std::env::set_var(key, value), + None => std::env::remove_var(key), + } + } + + let defaults = (DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_IDLE_TXN_TIMEOUT_MS, 0); + assert_eq!(unset, defaults, "unset env must keep the defaults"); + assert_eq!(overridden, (2000, 30000, 10000)); + assert_eq!(zero, (0, 0, 0), "explicit 0 must disable each timeout"); + assert_eq!(junk, defaults, "junk env must keep the defaults"); +} + +/// The production writer constructor installs all three timeout GUCs, bounds +/// ordinary lock waits, and exempts the intentional migration lock wait. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn session_timeouts_install_through_db_new_and_bound_lock_waits() { + let admin = PgPool::connect(&admin_url().await) + .await + .expect("connect admin"); + let (seed_pool, name) = create_scratch_db(&admin, "session_timeouts").await; + seed_pool.close().await; + + let base = admin_url().await; + let idx = base.rfind('/').expect("db url has a path segment"); + let scratch_url = format!("{}/{}", &base[..idx], name); + let db = Db::new(&DbConfig { + database_url: scratch_url.clone(), + max_connections: 2, + lock_timeout_ms: 500, + idle_txn_timeout_ms: 60_000, + statement_timeout_ms: 0, + ..DbConfig::default() + }) + .await + .expect("connect Db with session timeouts"); + + let (lock, idle, statement): (String, String, String) = sqlx::query_as( + "SELECT current_setting('lock_timeout'), \ + current_setting('idle_in_transaction_session_timeout'), \ + current_setting('statement_timeout')", + ) + .fetch_one(&db.pool) + .await + .expect("read effective GUCs"); + assert_eq!(lock, "500ms"); + assert_eq!(idle, "1min"); + assert_eq!(statement, "0"); + + let mut holder = db.pool.acquire().await.expect("holder connection"); + sqlx::raw_sql("BEGIN; LOCK TABLE events IN ACCESS EXCLUSIVE MODE") + .execute(&mut *holder) + .await + .expect("hold relation lock"); + let waited = std::time::Instant::now(); + let mut waiter_txn = db.pool.begin().await.expect("waiter transaction"); + let error = sqlx::query("LOCK TABLE events IN ACCESS SHARE MODE") + .execute(&mut *waiter_txn) + .await + .expect_err("waiter must time out, not park"); + drop(waiter_txn); + let code = match &error { + sqlx::Error::Database(db_error) => db_error.code().map(|code| code.to_string()), + other => panic!("expected database error, got {other:?}"), + }; + assert_eq!(code.as_deref(), Some("55P03")); + assert!(waited.elapsed() < std::time::Duration::from_secs(5)); + + let mut advisory_holder = PgPool::connect(&scratch_url) + .await + .expect("advisory holder pool") + .acquire() + .await + .expect("advisory holder conn") + .detach(); + sqlx::query("SELECT pg_advisory_lock($1)") + .bind(crate::deletion::SCHEMA_DESTRUCTION_LOCK_KEY) + .execute(&mut advisory_holder) + .await + .expect("hold schema advisory lock"); + let release = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(1_500)).await; + let _ = sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(crate::deletion::SCHEMA_DESTRUCTION_LOCK_KEY) + .execute(&mut advisory_holder) + .await; + let _ = advisory_holder.close().await; + }); + db.migrate() + .await + .expect("migrate must wait out the advisory holder"); + release.await.expect("release task"); + + let _ = sqlx::query("ROLLBACK").execute(&mut *holder).await; + drop(holder); + drop_scratch_db(&admin, db.pool.clone(), &name).await; +} + +/// The armed writer pool (`Db::new`) must enforce the floor end-to-end +/// through the public insert APIs, and the session GUC must be verifiably +/// set on pooled connections. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn armed_pool_rejects_old_channel_inserts_through_public_api() { + let admin = PgPool::connect(&admin_url().await) + .await + .expect("connect admin"); + let (seed_pool, name) = create_scratch_db(&admin, "floor_pool").await; + + let author = nostr::Keys::generate(); + let community = Uuid::new_v4(); + let channel = Uuid::new_v4(); + seed_community_channel(&seed_pool, community, channel, &author).await; + + // Connect a Db the production way: after_connect arms the guard. + let base = admin_url().await; + let idx = base.rfind('/').expect("db url has a path segment"); + let scratch_url = format!("{}/{}", &base[..idx], name); + let db = Db::new(&DbConfig { + database_url: scratch_url, + max_connections: 2, + ..DbConfig::default() + }) + .await + .expect("connect armed Db"); + let cid = CommunityId::from_uuid(community); + // Perci nit: assert the effective session value, not the intent. let effective: String = sqlx::query_scalar("SHOW buzz.created_at_floor") .fetch_one(&db.pool) @@ -2355,6 +3231,141 @@ async fn armed_pool_rejects_old_channel_inserts_through_public_api() { db.pool.close().await; } +/// A writer transaction holding the shared replica-floor advisory lock, the +/// shape a floor-compliant writer takes before the exclusive probe can run. +async fn begin_replica_floor_locked_writer(db: &Db) -> sqlx::Transaction<'static, sqlx::Postgres> { + let mut tx = db + .pool + .begin() + .await + .expect("begin floor-guarded writer tx"); + sqlx::query("SELECT pg_advisory_xact_lock_shared($1)") + .bind(crate::replica_fence::REPLICA_FLOOR_LOCK_KEY) + .execute(&mut *tx) + .await + .expect("take shared replica-floor lock"); + tx +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn replica_floor_writer_transaction_holds_shared_lock() { + let admin = PgPool::connect(&admin_url().await) + .await + .expect("connect admin"); + let (seed_pool, name) = create_scratch_db(&admin, "floor_writer_foundation").await; + + let base = admin_url().await; + let idx = base.rfind('/').expect("db url has a path segment"); + let scratch_url = format!("{}/{}", &base[..idx], name); + let db = Db::new(&DbConfig { + database_url: scratch_url, + max_connections: 3, + ..DbConfig::default() + }) + .await + .expect("connect armed Db"); + + let writer = begin_replica_floor_locked_writer(&db).await; + + let mut shared_contender = db.pool.begin().await.expect("begin shared contender"); + let shared_taken: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock_shared($1)") + .bind(crate::replica_fence::REPLICA_FLOOR_LOCK_KEY) + .fetch_one(&mut *shared_contender) + .await + .expect("probe shared floor lock"); + assert!( + shared_taken, + "compliant writer must allow another shared replica-floor lock holder" + ); + shared_contender + .rollback() + .await + .expect("rollback shared contender"); + + let mut contender = db.pool.begin().await.expect("begin exclusive contender"); + let exclusive_taken: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)") + .bind(crate::replica_fence::REPLICA_FLOOR_LOCK_KEY) + .fetch_one(&mut *contender) + .await + .expect("probe exclusive floor lock"); + assert!( + !exclusive_taken, + "compliant writer must hold the shared replica-floor advisory lock" + ); + + contender + .rollback() + .await + .expect("rollback exclusive contender"); + writer.rollback().await.expect("rollback writer tx"); + db.pool.close().await; + drop_scratch_db(&admin, seed_pool, &name).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn replica_floor_probe_waits_for_shared_writer_and_records_after_release() { + let admin = PgPool::connect(&admin_url().await) + .await + .expect("connect admin"); + let (seed_pool, name) = create_scratch_db(&admin, "floor_probe_foundation").await; + + let base = admin_url().await; + let idx = base.rfind('/').expect("db url has a path segment"); + let scratch_url = format!("{}/{}", &base[..idx], name); + let db = Db::new(&DbConfig { + database_url: scratch_url, + max_connections: 2, + ..DbConfig::default() + }) + .await + .expect("connect armed Db"); + + let token_before: i64 = sqlx::query_scalar("SELECT token FROM replica_heartbeat WHERE id = 1") + .fetch_one(&db.pool) + .await + .expect("read token before probe"); + + let writer = begin_replica_floor_locked_writer(&db).await; + + let probe_pool = db.pool.clone(); + let probe_fence = std::sync::Arc::clone(db.fence()); + let mut probing = tokio::spawn(async move { + crate::replica_fence::probe_once(&probe_pool, probe_fence.as_ref()).await + }); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(100), &mut probing) + .await + .is_err(), + "probe must wait for the exclusive floor lock while compliant writer is open" + ); + + writer + .rollback() + .await + .expect("release shared floor writer"); + let entry = tokio::time::timeout(std::time::Duration::from_secs(5), probing) + .await + .expect("probe must complete after writer release") + .expect("probe task") + .expect("probe succeeds"); + + assert_eq!( + entry.token, + token_before + 1, + "existing handshake must publish one token via probe_once" + ); + assert_eq!( + db.fence().verified_through(), + Some(entry.fence_wall), + "probe entry must be retained in the in-memory fence ring" + ); + + db.pool.close().await; + drop_scratch_db(&admin, seed_pool, &name).await; +} + /// `spawn_fence_probe` must verify the floor guard before letting the /// probe run — catalog shape AND observed behavior — and refuse on /// sabotage. This is the production gate for a relay running with @@ -2549,3 +3560,459 @@ async fn floor_guard_blocks_updates_that_move_rows_below_the_fence() { drop_scratch_db(&admin, pool, &name).await; } + +// ---- Statement-deadline cancellation vs. replica fallback ---------------- +// +// A replica read cancelled by `statement_timeout` (SQLSTATE 57014) must be +// surfaced, not re-run on the writer: the writer would be just as slow and +// the relay maps it to a distinct non-retried "query timed out". Every other +// replica failure keeps failing closed to the writer. + +/// Writer and replica scratch DBs holding one root plus an `e`-tagged reply +/// that mentions `mentioned` — the writer copy says "writer-reply" so a +/// writer re-run is observable. Returns the reply-targeted query shape. +struct EtagFixture { + admin: PgPool, + writer: PgPool, + wname: String, + replica: PgPool, + rname: String, + cid: CommunityId, + root_hex: String, + mentioned_hex: String, +} + +async fn e_tag_fixture(prefix: &str) -> EtagFixture { + let admin = PgPool::connect(&admin_url().await) + .await + .expect("connect admin"); + let (writer, wname) = create_scratch_db(&admin, &format!("{prefix}_w")).await; + let (replica, rname) = create_scratch_db(&admin, &format!("{prefix}_r")).await; + let author = nostr::Keys::generate(); + let mentioned = nostr::Keys::generate(); + let community = Uuid::new_v4(); + let channel = Uuid::new_v4(); + let base = 1_700_000_000u64; + let root = signed_event_at(&author, "root", base); + for (pool, content) in [(&writer, "writer-reply"), (&replica, "replica-reply")] { + seed_community_channel(pool, community, channel, &author).await; + insert_top_level(pool, community, channel, &root).await; + let reply = nostr::EventBuilder::new(nostr::Kind::Custom(9), content) + .tags([ + nostr::Tag::event(root.id), + nostr::Tag::public_key(mentioned.public_key()), + ]) + .custom_created_at(nostr::Timestamp::from(base + 10)) + .sign_with_keys(&author) + .expect("sign reply"); + insert_top_level(pool, community, channel, &reply).await; + crate::insert_mentions( + pool, + CommunityId::from_uuid(community), + &reply, + Some(channel), + ) + .await + .expect("insert mentions"); + } + EtagFixture { + admin, + writer, + wname, + replica, + rname, + cid: CommunityId::from_uuid(community), + root_hex: root.id.to_hex(), + mentioned_hex: mentioned.public_key().to_hex(), + } +} + +impl EtagFixture { + fn e_tag_query(&self) -> EventQuery { + let mut q = EventQuery::for_community(self.cid); + q.e_tags = Some(vec![self.root_hex.clone(), "00".repeat(32)]); + q + } + + /// A routed `Db` whose reader pool connects fresh (so it picks up any + /// `ALTER DATABASE` settings made on the replica), with the fence open + /// and a bounded budget so unpinned reads route to the replica. + async fn routed_db(&self) -> Db { + let base = admin_url().await; + let url = format!("{}/{}", &base[..base.rfind('/').expect("path")], self.rname); + let reader = PgPool::connect(&url).await.expect("connect reader"); + let mut db = Db::from_pools(self.writer.clone(), reader); + db.fence().force_open_for_tests(chrono::Utc::now()); + db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(5))); + db + } + + async fn drop(self) { + drop_scratch_db(&self.admin, self.replica, &self.rname).await; + drop_scratch_db(&self.admin, self.writer, &self.wname).await; + } +} + +fn contents(rows: &[StoredEvent]) -> Vec<&str> { + rows.iter().map(|e| e.event.content.as_str()).collect() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn replica_statement_cancel_propagates_without_writer_rerun() { + let fx = e_tag_fixture("cxl").await; + // A short operator cap on the replica (kept, not raised, by the e-tag + // deadline), plus a lock that parks every `events` read past it: the + // heartbeat proof still succeeds, then the routed read is cancelled. + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER DATABASE {} SET statement_timeout = '300ms'", + fx.rname + ))) + .execute(&fx.admin) + .await + .expect("set replica statement_timeout"); + let db = fx.routed_db().await; + let q = fx.e_tag_query(); + + // Healthy control: the replica serves before it is locked. + let rows = db.query_events_routed("t_cxl", &q).await.expect("healthy"); + assert!( + contents(&rows).contains(&"replica-reply"), + "fixture must route to replica" + ); + + let mut locker = fx.replica.begin().await.expect("begin locker"); + sqlx::query("LOCK TABLE events IN ACCESS EXCLUSIVE MODE") + .execute(&mut *locker) + .await + .expect("lock replica events"); + + let cancelled = |r: crate::Result<()>, what: &str| match r { + Err(e) => assert!(e.is_statement_cancelled(), "{what}: want 57014, got {e}"), + Ok(()) => panic!("{what}: replica cancel was re-run on the writer"), + }; + cancelled( + db.query_events_routed("t_cxl", &q).await.map(drop), + "query_events_routed", + ); + cancelled( + db.query_events_routed_bounded("t_cxl", &q).await.map(drop), + "query_events_routed_bounded", + ); + cancelled( + db.count_events_routed("t_cxl", &q).await.map(drop), + "count_events_routed", + ); + let root_id = hex::decode(&fx.root_hex).expect("hex"); + cancelled( + db.get_events_by_ids_routed("t_cxl", fx.cid, &[root_id.as_slice()]) + .await + .map(drop), + "get_events_by_ids_routed", + ); + + locker.rollback().await.expect("unlock"); + drop(db); + fx.drop().await; +} + +/// [`replica_statement_cancel_propagates_without_writer_rerun`] for the +/// request-scoped [`ReadSession`]: a cancelled aux read inside the proved +/// replica transaction surfaces 57014 and does not degrade to the writer. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn read_session_statement_cancel_propagates_without_writer_rerun() { + let fx = e_tag_fixture("scxl").await; + let db = fx.routed_db().await; + let reader_tx = db + .read_pool + .as_ref() + .expect("reader pool") + .begin() + .await + .expect("begin reader tx"); + let mut session = ReadSession { + inner: ReadSessionInner::Replica { + tx: reader_tx, + writer: fx.writer.clone(), + }, + }; + let rows = session + .query_events(&fx.e_tag_query()) + .await + .expect("healthy"); + assert_eq!(contents(&rows), vec!["replica-reply"]); + + // Force the next statement in the session over a short cap. + let ReadSessionInner::Replica { tx, .. } = &mut session.inner else { + unreachable!() + }; + sqlx::query("SET LOCAL statement_timeout = '50ms'") + .execute(&mut **tx) + .await + .expect("cap session"); + let mut locker = fx.replica.begin().await.expect("begin locker"); + sqlx::query("LOCK TABLE events IN ACCESS EXCLUSIVE MODE") + .execute(&mut *locker) + .await + .expect("lock replica events"); + + match session.query_events(&fx.e_tag_query()).await { + Err(e) => assert!(e.is_statement_cancelled(), "want 57014, got {e}"), + Ok(rows) => panic!("cancel re-ran on the writer: {:?}", contents(&rows)), + } + assert!( + session.is_replica(), + "a cancel must not degrade the session" + ); + + locker.rollback().await.expect("unlock"); + drop(session); + drop(db); + fx.drop().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn replica_non_cancel_failure_still_falls_back_to_writer() { + let fx = e_tag_fixture("nfb").await; + let db = fx.routed_db().await; + let q = fx.e_tag_query(); + let rows = db.query_events_routed("t_nfb", &q).await.expect("healthy"); + assert!( + contents(&rows).contains(&"replica-reply"), + "fixture must route to replica" + ); + + // Break the replica after the proof point (heartbeat table intact). + sqlx::query("DROP TABLE events CASCADE") + .execute(&fx.replica) + .await + .expect("drop replica events"); + + for rows in [ + db.query_events_routed("t_nfb", &q).await, + db.query_events_routed_bounded("t_nfb", &q).await, + ] { + let rows = rows.expect("non-cancel failure must fall back"); + assert!( + contents(&rows).contains(&"writer-reply"), + "{:?}", + contents(&rows) + ); + } + assert_eq!( + db.count_events_routed("t_nfb", &q) + .await + .expect("count falls back"), + 1 + ); + + drop(db); + fx.drop().await; +} + +/// The `#p`-joined SELECT (fenced, `e.` column prefix) and the COUNT `ANY` +/// path, executed with real bound values rather than only rendered SQL. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn e_tag_any_runs_with_real_binds_on_p_join_and_count() { + let fx = e_tag_fixture("pjn").await; + let mut q = fx.e_tag_query(); + + let rows = event::query_events(&fx.writer, &q) + .await + .expect("e-tag select"); + assert_eq!(contents(&rows), vec!["writer-reply"]); + assert_eq!( + event::count_events(&fx.writer, &q) + .await + .expect("e-tag count"), + 1 + ); + + q.p_tag_hex = Some(fx.mentioned_hex.clone()); + let rows = event::query_events(&fx.writer, &q) + .await + .expect("#p + e-tag select"); + assert_eq!(contents(&rows), vec!["writer-reply"]); + assert_eq!( + event::count_events(&fx.writer, &q) + .await + .expect("#p + e-tag count"), + 1 + ); + + q.p_tag_hex = Some("11".repeat(32)); + assert!(event::query_events(&fx.writer, &q) + .await + .expect("miss") + .is_empty()); + assert_eq!( + event::count_events(&fx.writer, &q) + .await + .expect("miss count"), + 0 + ); + + fx.drop().await; +} + +#[path = "tests/thread_window_postgres_tests.rs"] +mod thread_window_postgres_tests; + +/// `insert_event_with_serving_write_guard` indexes mentions in the event's own +/// transaction, and an indexing failure stays best-effort: the savepoint rolls +/// back only the mention rows, never the event. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn serving_write_guard_insert_indexes_mentions_in_event_transaction() { + use nostr::{EventBuilder, Keys, Kind, Tag}; + + let db = setup_db().await; + let community = db + .ensure_configured_community(&format!( + "serving-mentions-{}.example", + Uuid::new_v4().simple() + )) + .await + .expect("create serving-write mention community") + .id; + let store = db.deletion_store(); + let lease = store + .acquire_serving_write_lease( + community, + "mention_index_test", + "mention-index-test", + std::time::Duration::from_secs(30), + ) + .await + .expect("acquire serving-write lease"); + let mentioned = Keys::generate().public_key().to_hex(); + let build = |content: &str| { + EventBuilder::new(Kind::TextNote, content) + .tags([Tag::parse(["p", mentioned.as_str()]).expect("p tag")]) + .sign_with_keys(&Keys::generate()) + .expect("sign event") + }; + let counts = |event_id: Vec| { + let pool = db.pool.clone(); + async move { + let live: i64 = sqlx::query_scalar( + "SELECT count(*) FROM events \ + WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(&event_id) + .fetch_one(&pool) + .await + .expect("count live events"); + let mentions: i64 = sqlx::query_scalar( + "SELECT count(*) FROM event_mentions WHERE community_id = $1 AND event_id = $2", + ) + .bind(community.as_uuid()) + .bind(&event_id) + .fetch_one(&pool) + .await + .expect("count mentions"); + (live, mentions) + } + }; + + // Pin in-transaction indexing: the mention insert must run in the same + // top-level transaction that inserted the event row. A post-commit index + // runs in a later transaction, raises here, is logged as a warning, and + // leaves zero mentions. + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION test_require_event_tx_mentions() RETURNS trigger AS $$ \ + BEGIN \ + IF NEW.community_id = '{}'::uuid AND NOT EXISTS ( \ + SELECT 1 FROM events \ + WHERE community_id = NEW.community_id AND id = NEW.event_id \ + AND xmin = pg_current_xact_id()::xid) THEN \ + RAISE EXCEPTION 'test: post-commit mention'; \ + END IF; \ + RETURN NEW; \ + END; $$ LANGUAGE plpgsql", + community.as_uuid() + ))) + .execute(&db.pool) + .await + .expect("create same-transaction mention function"); + sqlx::query( + "CREATE TRIGGER trg_test_require_event_tx_mentions BEFORE INSERT ON event_mentions \ + FOR EACH ROW EXECUTE FUNCTION test_require_event_tx_mentions()", + ) + .execute(&db.pool) + .await + .expect("install same-transaction mention trigger"); + + let indexed = build("indexed"); + let result = db + .insert_event_with_serving_write_guard(&lease, &indexed, None) + .await; + + sqlx::query("DROP TRIGGER trg_test_require_event_tx_mentions ON event_mentions") + .execute(&db.pool) + .await + .expect("drop same-transaction mention trigger"); + sqlx::query("DROP FUNCTION test_require_event_tx_mentions()") + .execute(&db.pool) + .await + .expect("drop same-transaction mention function"); + + let (_, inserted) = result.expect("guarded insert"); + assert!(inserted); + assert_eq!( + counts(indexed.id.as_bytes().to_vec()).await, + (1, 1), + "mentions must be indexed in the event's own transaction" + ); + + // Make mention indexing fail for this community only. Without the + // savepoint the aborted statement poisons the event transaction and the + // commit fails. + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION test_reject_mentions() RETURNS trigger AS $$ \ + BEGIN \ + IF NEW.community_id = '{}'::uuid THEN \ + RAISE EXCEPTION 'test: mention indexing rejected'; \ + END IF; \ + RETURN NEW; \ + END; $$ LANGUAGE plpgsql", + community.as_uuid() + ))) + .execute(&db.pool) + .await + .expect("create mention rejection function"); + sqlx::query( + "CREATE TRIGGER trg_test_reject_mentions BEFORE INSERT ON event_mentions \ + FOR EACH ROW EXECUTE FUNCTION test_reject_mentions()", + ) + .execute(&db.pool) + .await + .expect("install mention rejection trigger"); + + let rejected = build("mention indexing fails"); + let result = db + .insert_event_with_serving_write_guard(&lease, &rejected, None) + .await; + + sqlx::query("DROP TRIGGER trg_test_reject_mentions ON event_mentions") + .execute(&db.pool) + .await + .expect("drop mention rejection trigger"); + sqlx::query("DROP FUNCTION test_reject_mentions()") + .execute(&db.pool) + .await + .expect("drop mention rejection function"); + + let (_, inserted) = result.expect("mention failure must not reject the event"); + assert!(inserted); + assert_eq!(counts(rejected.id.as_bytes().to_vec()).await, (1, 0)); + + assert!(store + .release_serving_write_lease(&lease) + .await + .expect("release serving-write lease")); +} diff --git a/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs new file mode 100644 index 00000000000..767a4affc1c --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs @@ -0,0 +1,326 @@ +use super::*; +use crate::thread_window::{AuxQuery, ScanBudget}; +use buzz_core::thread_window::Request; +use nostr::{EventBuilder, Kind, Tag, Timestamp}; + +fn request(channel: Uuid, root: &nostr::Event, upper: u64) -> Request { + Request::parse(&serde_json::json!({"thread_window":true,"#h":[channel], + "#e":[root.id.to_hex()],"kinds":[9],"limit":50, + "until":upper,"before_id":"00".repeat(32)})) + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { + let admin = PgPool::connect(&admin_url().await).await.unwrap(); + let (writer, wname) = create_scratch_db(&admin, "tw_writer").await; + let (replica, rname) = create_scratch_db(&admin, "tw_replica").await; + let keys = nostr::Keys::generate(); + let cid = Uuid::new_v4(); + let channel = Uuid::new_v4(); + let base = 1_700_000_000; + let root = signed_event_at(&keys, "root", base); + let old = signed_event_at(&keys, "old", base + 10); + let middle = signed_event_at(&keys, "missing-middle", base + 20); + for pool in [&writer, &replica] { + seed_community_channel(pool, cid, channel, &keys).await; + insert_top_level(pool, cid, channel, &root).await; + insert_thread_reply(pool, cid, channel, &root, &old).await; + } + insert_thread_reply(&writer, cid, channel, &root, &middle).await; + let db = Db::from_pools(writer.clone(), replica.clone()); + let community = CommunityId::from_uuid(cid); + let mut req = request(channel, &root, base + 30); + // An old delivered tail does not justify an uncovered request upper bound. + db.fence() + .force_open_for_tests(chrono::DateTime::from_timestamp(base as i64 + 15, 0).unwrap()); + let (page, session) = db + .get_thread_window_with_session(community, &req, &mut ScanBudget::default()) + .await + .unwrap(); + assert!(!session.is_replica()); + assert_eq!( + page.rows.iter().map(|e| e.event.id).collect::>(), + [middle.id, old.id] + ); + assert!(!page.has_more); + drop(session); + // Counterfactual: over-claiming coverage demonstrably loses the middle row. + db.fence().force_open_for_tests(chrono::Utc::now()); + let (page, session) = db + .get_thread_window_with_session(community, &req, &mut ScanBudget::default()) + .await + .unwrap(); + assert!(session.is_replica()); + assert_eq!(page.rows.len(), 1); + assert_eq!(page.rows[0].event.id, old.id); + assert!(!page.has_more && page.next_cursor.is_none()); + drop(session); + // Default head route remains writer despite an open fence. + req.cursor = None; + let (head, session) = db + .get_thread_window_with_session(community, &req, &mut ScanBudget::default()) + .await + .unwrap(); + assert!(!session.is_replica()); + assert_eq!(head.rows[0].event.id, middle.id); + drop(session); + + // Complete the reply fixture, then lag *recent* edits and channel-less + // deletions. Coverage of old replies is not a freshness proof for aux. + insert_thread_reply(&replica, cid, channel, &root, &middle).await; + req = request(channel, &root, base + 30); + let (_, mut session) = db + .get_thread_window_with_session(community, &req, &mut ScanBudget::default()) + .await + .unwrap(); + assert!(session.is_replica()); + let edit = EventBuilder::new(Kind::Custom(40003), "new edit") + .tags([Tag::parse(["e", &old.id.to_hex()]).unwrap()]) + .custom_created_at(Timestamp::from(base + 1000)) + .sign_with_keys(&keys) + .unwrap(); + let deletion = EventBuilder::new(Kind::Custom(5), "") + .tags([Tag::parse(["e", &edit.id.to_hex()]).unwrap()]) + .custom_created_at(Timestamp::from(base + 1001)) + .sign_with_keys(&keys) + .unwrap(); + for pool in [&writer, &replica] { + event::insert_event(pool, community, &edit, Some(channel)) + .await + .unwrap(); + event::insert_event(pool, community, &deletion, None) + .await + .unwrap(); + } + let targets = [old.id.to_hex(), edit.id.to_hex()]; + let query = AuxQuery { + community, + targets: &targets, + kinds: &[5, 40003], + accessible: &[channel], + cursor: None, + }; + let mut budget = ScanBudget::default(); + let stale = session + .thread_window_aux(&query, &mut budget) + .await + .unwrap(); + assert!( + stale.events.is_empty(), + "held snapshot must not advance after page proof" + ); + let (_, mut fresh) = db + .get_thread_window_with_session(community, &req, &mut ScanBudget::default()) + .await + .unwrap(); + assert_eq!( + fresh + .thread_window_aux(&query, &mut budget) + .await + .unwrap() + .events + .len(), + 2, + "control: recent aux is visible on a fresh snapshot, with no reply timestamp bound" + ); + drop(fresh); + sqlx::query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=$1 AND pid<>pg_backend_pid()") + .bind(&rname).execute(&admin).await.unwrap(); + let degraded = session + .thread_window_aux(&query, &mut budget) + .await + .unwrap(); + assert_eq!(degraded.events.len(), 2); + assert!( + !session.is_replica(), + "fallback must permanently release the failed snapshot" + ); + drop(session); + // The shared router's reader acquisition failure must also reach the writer, + // not reinterpret an unavailable reader as an empty terminal window. + replica.close().await; + let (page, session) = db + .get_thread_window_with_session(community, &req, &mut ScanBudget::default()) + .await + .unwrap(); + assert!(!session.is_replica()); + assert_eq!(page.rows.len(), 2); + assert!(!page.has_more); + drop(session); + drop_scratch_db(&admin, replica, &rname).await; + drop_scratch_db(&admin, writer, &wname).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_thread_window_prebuild_validation_and_old_ledger() { + let admin = PgPool::connect(&admin_url().await).await.unwrap(); + let (pool, name) = create_scratch_db_through(&admin, "tw_prebuild", Some(53)).await; + for setup in [ + "CREATE INDEX idx_thread_metadata_window ON thread_metadata (community_id,root_event_id,event_created_at ASC,event_id ASC)", + // Simulate an invalid concurrent-build remnant only in this disposable superuser DB. + "CREATE INDEX idx_thread_metadata_window ON thread_metadata (community_id,root_event_id,event_created_at DESC,event_id ASC); \ + UPDATE pg_index SET indisvalid=false WHERE indexrelid='idx_thread_metadata_window'::regclass", + ] { + sqlx::raw_sql(setup).execute(&pool).await.unwrap(); + let error = migration::run_migrations(&pool).await.unwrap_err(); + assert!(error.to_string().contains("invalid or wrong definition"), + "must reject catalog shape, not merely time out: {error}"); + let version: i64 = sqlx::query_scalar("SELECT max(version) FROM _sqlx_migrations") + .fetch_one(&pool).await.unwrap(); + assert_eq!(version, 53); + sqlx::query("DROP INDEX CONCURRENTLY idx_thread_metadata_window").execute(&pool).await.unwrap(); + } + sqlx::query("CREATE INDEX CONCURRENTLY idx_thread_metadata_window ON thread_metadata (community_id,root_event_id,event_created_at DESC,event_id ASC)") + .execute(&pool).await.unwrap(); + let oid: i64 = sqlx::query_scalar("SELECT 'idx_thread_metadata_window'::regclass::oid::bigint") + .fetch_one(&pool) + .await + .unwrap(); + migration::run_migrations(&pool).await.unwrap(); + assert_eq!( + oid, + sqlx::query_scalar::<_, i64>("SELECT 'idx_thread_metadata_window'::regclass::oid::bigint") + .fetch_one(&pool) + .await + .unwrap() + ); + // Model the previous binary's exact embedded ledger, not run_to(53), + // which would still know version 54 and cannot test VersionMissing. + let current = sqlx::migrate::Migrator::new( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../migrations"), + ) + .await + .unwrap(); + let old = sqlx::migrate::Migrator::with_migrations( + current + .iter() + .filter(|m| m.version <= 53) + .cloned() + .collect(), + ); + assert!(matches!( + old.run(&pool).await, + Err(sqlx::migrate::MigrateError::VersionMissing(54)) + )); + drop_scratch_db(&admin, pool, &name).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_thread_window_prebuild_does_not_queue_behind_writer() { + let admin = PgPool::connect(&admin_url().await).await.unwrap(); + let (pool, name) = create_scratch_db_through(&admin, "tw_prebuild_writer", Some(53)).await; + let community = Uuid::new_v4(); + let channel = Uuid::new_v4(); + seed_community_channel(&pool, community, channel, &nostr::Keys::generate()).await; + sqlx::query("CREATE INDEX CONCURRENTLY idx_thread_metadata_window ON thread_metadata (community_id,root_event_id,event_created_at DESC,event_id ASC)") + .execute(&pool).await.unwrap(); + let oid: i64 = sqlx::query_scalar("SELECT 'idx_thread_metadata_window'::regclass::oid::bigint") + .fetch_one(&pool) + .await + .unwrap(); + + // Model an ingestion transaction already holding the table's writer lock. + // It stays held through every control: releasing it would hide the convoy. + let mut writer = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE thread_metadata IN ROW EXCLUSIVE MODE") + .execute(&mut *writer) + .await + .unwrap(); + let insert = + "INSERT INTO thread_metadata (community_id, channel_id, event_created_at, event_id) \ + VALUES ($1, $2, now(), $3)"; + let mut witness = pool.acquire().await.unwrap(); + sqlx::query("SET lock_timeout = '200ms'") + .execute(&mut *witness) + .await + .unwrap(); + sqlx::query(insert) + .bind(community) + .bind(channel) + .bind(vec![1_u8; 32]) + .execute(&mut *witness) + .await + .unwrap(); + + // Keep the exact migration transaction open after its SQL finishes so a + // second insert observes *all* locks it acquired. This is an explicit + // overlap barrier, not a race against a fast catalog-only migration. + let mut migration_tx = pool.begin().await.unwrap(); + let result = sqlx::raw_sql(include_str!( + "../../../../../migrations/0054_thread_window_index.sql" + )) + .execute(&mut *migration_tx) + .await; + let concurrent_insert = sqlx::query(insert) + .bind(community) + .bind(channel) + .bind(vec![2_u8; 32]) + .execute(&mut *witness) + .await; + migration_tx.rollback().await.unwrap(); + sqlx::query(insert) + .bind(community) + .bind(channel) + .bind(vec![3_u8; 32]) + .execute(&mut *witness) + .await + .unwrap(); + + // Also bind the public migrator: the advisory schema/destruction lock, + // ledger write and post-migration catalog checks must work with ingestion. + let production_result = migration::run_migrations(&pool).await; + sqlx::query(insert) + .bind(community) + .bind(channel) + .bind(vec![4_u8; 32]) + .execute(&mut *witness) + .await + .unwrap(); + let version: i64 = sqlx::query_scalar("SELECT max(version) FROM _sqlx_migrations") + .fetch_one(&mut *witness) + .await + .unwrap(); + let final_oid: i64 = + sqlx::query_scalar("SELECT 'idx_thread_metadata_window'::regclass::oid::bigint") + .fetch_one(&mut *witness) + .await + .unwrap(); + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM thread_metadata WHERE community_id=$1") + .bind(community) + .fetch_one(&mut *witness) + .await + .unwrap(); + drop(witness); + writer.rollback().await.unwrap(); + drop_scratch_db(&admin, pool, &name).await; + + assert!( + result.is_ok(), + "valid prebuild must bypass write-conflicting CREATE: {result:?}" + ); + assert!( + concurrent_insert.is_ok(), + "migration must allow metadata inserts: {concurrent_insert:?}" + ); + assert!( + production_result.is_ok(), + "production migrator must preserve ingestion progress: {production_result:?}" + ); + let latest = sqlx::migrate::Migrator::new( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../migrations"), + ) + .await + .unwrap() + .iter() + .map(|m| m.version) + .max() + .unwrap(); + assert_eq!(version, latest); + assert_eq!(final_oid, oid, "prebuild must not be replaced"); + assert_eq!(count, 4, "all writer witnesses must persist"); +} diff --git a/crates/buzz-db/src/store/admin_moderation.rs b/crates/buzz-db/src/store/admin_moderation.rs index f38231787bf..7ff6eabdfd7 100644 --- a/crates/buzz-db/src/store/admin_moderation.rs +++ b/crates/buzz-db/src/store/admin_moderation.rs @@ -4,6 +4,7 @@ //! [`CommunityId`](buzz_core::CommunityId). Keep ordinary moderation reads in //! [`crate::moderation`] tenant-fenced. +use buzz_core::kind::{AUTHOR_ONLY_KINDS, P_GATED_KINDS, RESULT_GATED_KINDS, SHARED_GATED_KINDS}; use buzz_datastore_tracing::datastore_span; use chrono::{DateTime, Utc}; use serde::Serialize; @@ -16,6 +17,27 @@ use crate::Db; /// Maximum rows accepted by one admin query. pub const MAX_PAGE_SIZE: i64 = 200; +/// Kinds no admin read may reveal: author-only, result-gated, `#p`-gated and +/// shared-gated events. The whole shared-gated set is hidden, shared or not. +/// Moderators can still act on these kinds (direct delete by event ID, report +/// enforcement); they just cannot read them, so admin reads treat them as absent. +fn admin_hidden_kinds() -> Vec { + AUTHOR_ONLY_KINDS + .iter() + .chain(RESULT_GATED_KINDS) + .chain(P_GATED_KINDS) + .chain(SHARED_GATED_KINDS) + .map(|&kind| kind as i32) + .collect() +} + +/// `k` values that make a NIP-09 deletion as private as the author-only event +/// it deletes (see `buzz_core::kind::is_author_only_event_kind`). Admin reads +/// hide such deletions with `NOT (kind = 5 AND tags name one of these)`. +fn private_deletion_k_values() -> Vec { + AUTHOR_ONLY_KINDS.iter().map(u32::to_string).collect() +} + fn bounded_limit(limit: i64) -> i64 { limit.clamp(1, MAX_PAGE_SIZE) } @@ -38,6 +60,10 @@ pub struct AdminReport { pub target_kind: String, /// Hex target identifier. pub target: String, + /// Author of the reported event when `target_kind` is `"event"` and the + /// event is stored (deleted events included), so a list row can name the + /// reported person without a per-report detail read. + pub target_author_pubkey: Option, /// Optional channel. pub channel_id: Option, /// NIP-56 report category. @@ -195,9 +221,23 @@ pub async fn list_reports( r.report_event_id, r.reporter_pubkey, r.target_kind, r.target_event_id, r.target_pubkey, r.target_blob_sha256, r.channel_id, r.report_type, r.note, r.status, r.resolved_by, - r.resolved_at, r.action_id, r.created_at + r.resolved_at, r.action_id, r.created_at, + target.pubkey AS target_author_pubkey FROM moderation_reports r JOIN communities c ON c.id = r.community_id + LEFT JOIN LATERAL ( + SELECT e.pubkey + FROM events e + WHERE r.target_kind = 'event' + AND e.community_id = r.community_id + AND e.id = r.target_event_id + AND e.kind <> ALL($10) + AND NOT (e.kind = 5 AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(e.tags) t + WHERE t->>0 = 'k' AND t->>1 = ANY($11::text[]))) + ORDER BY e.created_at DESC + LIMIT 1 + ) target ON TRUE WHERE ($1::uuid IS NULL OR r.community_id = $1) AND ($2::text IS NULL OR r.status = $2) AND ($3::text IS NULL OR r.report_type = $3) @@ -218,13 +258,22 @@ pub async fn list_reports( .bind(cursor_time) .bind(cursor_id) .bind(bounded_limit(limit)) + .bind(admin_hidden_kinds()) + .bind(private_deletion_k_values()) .fetch_all(pool) .await?; rows.into_iter().map(row_to_report).collect() } /// Fetch one report globally by its row id, including its event target content. -pub async fn get_report(pool: &PgPool, report_id: Uuid) -> Result> { +/// Targets whose kind is in `hidden_kinds`, and deletions whose `k` tag names +/// one of `private_deletion_ks`, come back as `message: None`. +async fn get_report( + pool: &PgPool, + report_id: Uuid, + hidden_kinds: &[i32], + private_deletion_ks: &[String], +) -> Result> { let row = sqlx::query( r#" SELECT r.id, r.community_id, c.host AS community_host, @@ -233,6 +282,7 @@ pub async fn get_report(pool: &PgPool, report_id: Uuid) -> Result Result ALL($2) + AND NOT (e.kind = 5 AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(e.tags) t + WHERE t->>0 = 'k' AND t->>1 = ANY($3::text[]))) ORDER BY e.created_at DESC LIMIT 1 ) target ON TRUE @@ -275,6 +329,8 @@ pub async fn get_report(pool: &PgPool, report_id: Uuid) -> Result Result { reporter_pubkey: hex::encode(row.try_get::, _>("reporter_pubkey")?), target_kind, target: hex::encode(target), + target_author_pubkey: row + .try_get::>, _>("target_author_pubkey")? + .map(hex::encode), channel_id: row.try_get("channel_id")?, report_type: row.try_get("report_type")?, note: row.try_get("note")?, @@ -406,6 +465,120 @@ fn row_to_feedback(row: sqlx::postgres::PgRow) -> Result { }) } +/// Active community row in the admin community directory. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdminCommunity { + /// Community identifier. + pub id: Uuid, + /// Served host. + pub host: String, + /// Workspace icon URL, when set. + pub icon: Option, +} + +/// List active communities whose host starts with `prefix` (case-insensitive, +/// matched literally), ordered by `lower(host)` and resumed after the +/// lowercased host `after`. `lower(host)` is unique, so it alone is a total +/// order. Uses the tenant binder's liveness rule, so every row can be bound. +pub async fn list_communities( + pool: &PgPool, + prefix: &str, + after: Option<&str>, + limit: i64, +) -> Result> { + let rows = sqlx::query( + r#" + SELECT id, host, icon + FROM communities + WHERE archived_at IS NULL + AND deleted_at IS NULL + AND deletion_state = 'active' + AND lower(host) LIKE lower($1) || '%' ESCAPE '\' + AND lower(host) > COALESCE($2, '') + ORDER BY lower(host) + LIMIT $3 + "#, + ) + .bind(crate::user::escape_like(prefix)) + .bind(after) + .bind(bounded_limit(limit)) + .fetch_all(pool) + .await?; + rows.into_iter() + .map(|row| { + Ok(AdminCommunity { + id: row.try_get("id")?, + host: row.try_get("host")?, + icon: row.try_get("icon")?, + }) + }) + .collect() +} + +/// One stored event, read inside a single community for a delete preview. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdminEventPreview { + /// Event id (hex). + pub id: String, + /// Author public key (hex). + pub author_pubkey: String, + /// Event kind. + pub kind: i32, + /// Event content. + pub content: String, + /// Timestamp signed into the event. + pub created_at: DateTime, + /// Soft-deletion time, when deleted. + pub deleted_at: Option>, + /// Channel the event belongs to, if any. + pub channel_id: Option, +} + +/// Fetch event `id` from `community` only (same lookup as the report detail). +/// +/// Kinds in [`admin_hidden_kinds`] are never returned: the relay must not +/// reveal that such an event exists to anyone but its permitted readers, so a +/// matching row is reported as absent, exactly as the report list and detail +/// treat a hidden target. +pub async fn get_event_preview( + pool: &PgPool, + community_id: Uuid, + id: &[u8], +) -> Result> { + let row = sqlx::query( + r#" + SELECT id, pubkey, kind, content, created_at, deleted_at, channel_id + FROM events + WHERE community_id = $1 AND id = $2 AND kind <> ALL($3) + AND NOT (kind = 5 AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(tags) t + WHERE t->>0 = 'k' AND t->>1 = ANY($4::text[]))) + ORDER BY created_at DESC + LIMIT 1 + "#, + ) + .bind(community_id) + .bind(id) + .bind(admin_hidden_kinds()) + .bind(private_deletion_k_values()) + .fetch_optional(pool) + .await?; + row.map(|row| { + Ok(AdminEventPreview { + id: hex::encode(row.try_get::, _>("id")?), + author_pubkey: hex::encode(row.try_get::, _>("pubkey")?), + kind: row.try_get("kind")?, + content: row.try_get("content")?, + created_at: row.try_get("created_at")?, + deleted_at: row.try_get("deleted_at")?, + channel_id: row.try_get("channel_id")?, + }) + }) + .transpose() +} + impl Db { /// List reports for the deployment-global read-only admin plane. #[allow(clippy::too_many_arguments)] @@ -435,10 +608,28 @@ impl Db { .await } - /// Fetch one report for the deployment-global read-only admin plane. + /// Fetch one report for any admin HTTP response. Hidden-kind targets come + /// back as `message: None`, exactly like a missing event. #[datastore_span(name = "admin_get_report", system = "postgresql")] pub async fn admin_get_report(&self, id: Uuid) -> Result> { - get_report(&self.pool, id).await + get_report( + &self.pool, + id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + } + + /// Fetch one report with its target unfiltered, for report enforcement and + /// action recovery only, which need the real target author. Never serialize + /// this result into an HTTP response; use [`Self::admin_get_report`]. + #[datastore_span(name = "admin_get_report_for_enforcement", system = "postgresql")] + pub async fn admin_get_report_for_enforcement( + &self, + id: Uuid, + ) -> Result> { + get_report(&self.pool, id, &[], &[]).await } /// List feedback for the deployment-global read-only admin plane. @@ -452,10 +643,31 @@ impl Db { pub async fn admin_get_feedback(&self, id: Uuid) -> Result> { get_feedback(&self.pool, id).await } + + /// Page the admin community directory. + #[datastore_span(name = "admin_list_communities", system = "postgresql")] + pub async fn admin_list_communities( + &self, + prefix: &str, + after: Option<&str>, + limit: i64, + ) -> Result> { + list_communities(&self.pool, prefix, after, limit).await + } + + /// Fetch one event inside one community for the admin delete preview. + #[datastore_span(name = "admin_get_event_preview", system = "postgresql")] + pub async fn admin_get_event_preview( + &self, + community_id: Uuid, + id: &[u8], + ) -> Result> { + get_event_preview(&self.pool, community_id, id).await + } } #[cfg(test)] -mod tests { +mod postgres_tests { use super::*; const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 @@ -602,10 +814,15 @@ mod tests { .await; let report_id = insert_event_report(&pool, report_community, &event_id).await; - let detail = get_report(&pool, report_id) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); let message = detail.message.expect("reported message exists"); assert_eq!(message.content, "reported message"); assert_eq!(message.author_pubkey, hex::encode([5_u8; 32])); @@ -630,15 +847,240 @@ mod tests { #[tokio::test] #[ignore = "requires Postgres"] - async fn report_detail_has_no_message_for_non_event_target() { + async fn list_reports_names_same_community_event_author_including_deleted() { let pool = setup_pool().await; - let community_id = insert_community(&pool, "pubkey-target").await; - let report_id = insert_pubkey_report(&pool, community_id).await; + let report_community = insert_community(&pool, "list-author").await; + let other_community = insert_community(&pool, "list-author-other").await; + let event_id = vec![2_u8; 32]; + insert_event( + &pool, + report_community, + &event_id, + &[5_u8; 32], + "gone", + Some(Utc::now()), + ) + .await; + insert_event( + &pool, + other_community, + &event_id, + &[6_u8; 32], + "wrong tenant", + None, + ) + .await; + let event_report = insert_event_report(&pool, report_community, &event_id).await; + let pubkey_report = insert_pubkey_report(&pool, report_community).await; - let detail = get_report(&pool, report_id) + let reports = list_reports( + &pool, + Some(report_community), + None, + None, + None, + None, + None, + None, + 50, + ) + .await + .expect("list reports"); + let author_of = |id: Uuid| { + reports + .iter() + .find(|r| r.id == id) + .expect("report listed") + .target_author_pubkey + .clone() + }; + assert_eq!(author_of(event_report), Some(hex::encode([5_u8; 32]))); + assert_eq!(author_of(pubkey_report), None); + + sqlx::query("DELETE FROM events WHERE community_id = ANY($1)") + .bind(vec![report_community, other_community]) + .execute(&pool) + .await + .expect("delete event fixtures"); + delete_report_fixture(&pool, report_community).await; + delete_report_fixture(&pool, other_community).await; + } + + /// A report on a hidden-kind event exposes neither the event's content nor + /// its author, in the list or the detail; a report on a message does. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn report_reads_hide_private_kind_targets() { + let pool = setup_pool().await; + let community_id = insert_community(&pool, "hidden-target").await; + let author = [5_u8; 32]; + let mut hidden = Vec::new(); + // Enumerate the core sets directly so a set dropped from + // `admin_hidden_kinds()` still gets a fixture and fails the test. + let private_kinds = AUTHOR_ONLY_KINDS + .iter() + .chain(RESULT_GATED_KINDS) + .chain(P_GATED_KINDS) + .chain(SHARED_GATED_KINDS) + .map(|&kind| kind as i32); + for (i, kind) in private_kinds.enumerate() { + let event_id = vec![0x40 + i as u8; 32]; + sqlx::query( + r#" + INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig) + VALUES ($1, $2, $3, now(), $4, '[["shared","true"]]'::jsonb, 'private', $5) + "#, + ) + .bind(community_id) + .bind(&event_id) + .bind(author) + .bind(kind) + .bind(vec![3_u8; 64]) + .execute(&pool) + .await + .expect("insert hidden event"); + hidden.push(( + kind, + insert_event_report(&pool, community_id, &event_id).await, + )); + } + // Deletions of author-only events are private by their `k` tag alone, + // live or soft-deleted; a deletion with a public or non-canonical `k` + // stays readable, matching `buzz_core::kind::k_tag_kinds`. + // An unrelated tag that merely contains `"k"` and an author-only kind + // is not a marker: matching is positional, as in Rust. + let mut public_deletions = Vec::new(); + let cases = AUTHOR_ONLY_KINDS + .iter() + .map(|k| (format!(r#"[["k","{k}"]]"#), true)) + .chain( + [ + r#"[["k","1"]]"#, + r#"[["k","030300"]]"#, + r#"[["k","+30300"]]"#, + r#"[["k","1"],["meta","k","30300"]]"#, + ] + .map(|tags| (tags.to_string(), false)), + ); + for (i, (tags, private)) in cases.enumerate() { + let event_id = vec![0x60 + i as u8; 32]; + sqlx::query( + r#" + INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, deleted_at) + VALUES ($1, $2, $3, now(), 5, $4::jsonb, '', $5, CASE WHEN $6 THEN now() END) + "#, + ) + .bind(community_id) + .bind(&event_id) + .bind(author) + .bind(&tags) + .bind(vec![3_u8; 64]) + .bind(i % 2 == 1) + .execute(&pool) + .await + .expect("insert deletion event"); + let report = insert_event_report(&pool, community_id, &event_id).await; + let preview = get_event_preview(&pool, community_id, &event_id) + .await + .expect("preview"); + assert_eq!(preview.is_none(), private, "preview, deletion tags {tags}"); + if private { + hidden.push((5, report)); + } else { + public_deletions.push((tags, report)); + } + } + let visible_id = vec![0x3f_u8; 32]; + insert_event(&pool, community_id, &visible_id, &author, "public", None).await; + let visible = insert_event_report(&pool, community_id, &visible_id).await; + + let reports = list_reports( + &pool, + Some(community_id), + None, + None, + None, + None, + None, + None, + 100, + ) + .await + .expect("list reports"); + let author_of = |id: Uuid| { + reports + .iter() + .find(|r| r.id == id) + .expect("report listed") + .target_author_pubkey + .clone() + }; + for &(kind, report_id) in &hidden { + assert_eq!(author_of(report_id), None, "list, kind {kind}"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); + assert!(detail.message.is_none(), "detail, kind {kind}"); + } + assert_eq!(author_of(visible), Some(hex::encode(author))); + for (tags, report_id) in public_deletions { + assert_eq!( + author_of(report_id), + Some(hex::encode(author)), + "list, deletion tags {tags}" + ); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) .await .expect("query report") .expect("report exists"); + assert!(detail.message.is_some(), "detail, deletion tags {tags}"); + } + let detail = get_report( + &pool, + visible, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); + assert_eq!(detail.message.expect("message shown").content, "public"); + + sqlx::query("DELETE FROM events WHERE community_id = $1") + .bind(community_id) + .execute(&pool) + .await + .expect("delete event fixtures"); + delete_report_fixture(&pool, community_id).await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn report_detail_has_no_message_for_non_event_target() { + let pool = setup_pool().await; + let community_id = insert_community(&pool, "pubkey-target").await; + let report_id = insert_pubkey_report(&pool, community_id).await; + + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert_eq!(detail.report.target_kind, "pubkey"); assert!(detail.message.is_none()); @@ -653,10 +1095,15 @@ mod tests { let missing_event_id = vec![8_u8; 32]; let report_id = insert_event_report(&pool, community_id, &missing_event_id).await; - let detail = get_report(&pool, report_id) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert_eq!(detail.report.target_kind, "event"); assert_eq!(detail.report.target, hex::encode(missing_event_id)); assert!(detail.message.is_none()); @@ -720,10 +1167,15 @@ mod tests { .await; set_report_status(&pool, community_id, report_id, "dismissed").await; - let detail = get_report(&pool, report_id) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert_eq!(detail.report.status, "dismissed"); let action = detail .active_action @@ -760,10 +1212,15 @@ mod tests { .await; set_report_status(&pool, community_id, report_id, "resolved").await; - let detail = get_report(&pool, report_id) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); let action = detail.active_action.expect("an action surfaces"); assert_eq!( action.id, @@ -794,10 +1251,15 @@ mod tests { ) .await; - let detail = get_report(&pool, report_id) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert!( detail.active_action.is_none(), "reopen audit row must not surface as an enforcement action" diff --git a/crates/buzz-db/src/store/admission_postgres_tests.rs b/crates/buzz-db/src/store/admission_postgres_tests.rs new file mode 100644 index 00000000000..9ae81f3a830 --- /dev/null +++ b/crates/buzz-db/src/store/admission_postgres_tests.rs @@ -0,0 +1,1306 @@ +//! Live writer-admission regressions. A one-connection pool runs with ordinary +//! PostgreSQL triggers disabled, so a missing application check is observable. + +use crate::{Db, DbError}; +use buzz_core::CommunityId; +use uuid::Uuid; + +use crate::test_support::admission_fixture as fixture; + +fn assert_fenced(error: DbError) { + assert!( + matches!(&error, DbError::AccessDenied(message) if message.contains("write-fenced")), + "expected application admission rejection, got {error:?}" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn api_token_writers_require_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + super::api_token::create_api_token( + &db.pool, + *community.as_uuid(), + &[1; 32], + &[2; 32], + "test", + &[], + None, + None, + ) + .await + .expect_err("token create must reject"), + ); + assert_fenced( + super::api_token::revoke_all_tokens(&db.pool, *community.as_uuid(), &[2; 32], &[2; 32]) + .await + .expect_err("token revoke must reject"), + ); + } + super::api_token::create_api_token( + &db.pool, + *communities[0].as_uuid(), + &[3; 32], + &[2; 32], + "active", + &[], + None, + None, + ) + .await + .expect("active token create succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn archived_identity_writers_require_application_admission() { + let (db, communities) = fixture().await; + let pubkey = "a".repeat(64); + let actor = "b".repeat(64); + let event = "c".repeat(64); + for community in &communities[1..] { + assert_fenced( + super::archived_identities::archive( + &db.pool, *community, &pubkey, "self", &actor, None, None, &event, + ) + .await + .expect_err("archive must reject"), + ); + assert_fenced( + super::archived_identities::unarchive(&db.pool, *community, &pubkey) + .await + .expect_err("unarchive must reject"), + ); + } + assert!(super::archived_identities::archive( + &db.pool, + communities[0], + &pubkey, + "self", + &actor, + None, + None, + &event, + ) + .await + .expect("active archive succeeds")); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn allowlist_writers_require_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + db.add_to_allowlist(*community, &[1; 32], &[2; 32], None) + .await + .expect_err("allowlist add must reject"), + ); + assert_fenced( + db.remove_from_allowlist(*community, &[1; 32]) + .await + .expect_err("allowlist remove must reject"), + ); + } + assert!(db + .add_to_allowlist(communities[0], &[1; 32], &[2; 32], None) + .await + .expect("active allowlist add succeeds")); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn git_name_writers_require_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + super::git_repo::reserve_repo_name(&db.pool, *community, "repo", "owner") + .await + .expect_err("repo reserve must reject"), + ); + assert_fenced( + super::git_repo::release_repo_name(&db.pool, *community, "repo", "owner") + .await + .expect_err("repo release must reject"), + ); + } + assert_eq!( + super::git_repo::reserve_repo_name(&db.pool, communities[0], "repo", "owner") + .await + .expect("active repo reserve succeeds"), + super::git_repo::ReserveOutcome::Reserved + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn relay_member_writers_require_application_admission() { + let (db, communities) = fixture().await; + let pubkey = "d".repeat(64); + for community in &communities[1..] { + assert_fenced( + super::relay_members::add_relay_member(&db.pool, *community, &pubkey, "member", None) + .await + .expect_err("member add must reject"), + ); + assert_fenced( + super::relay_members::remove_relay_member(&db.pool, *community, &pubkey) + .await + .expect_err("member remove must reject"), + ); + } + assert!(super::relay_members::add_relay_member( + &db.pool, + communities[0], + &pubkey, + "member", + None, + ) + .await + .expect("active member add succeeds")); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn relay_invite_writers_require_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + super::relay_invite::mint_relay_invite( + &db.pool, + *community, + &"e".repeat(64), + 3600, + Some(1), + ) + .await + .expect_err("invite mint must reject"), + ); + assert_fenced( + super::relay_invite::claim_relay_invite( + &db.pool, + *community, + &[3; 32], + &"f".repeat(64), + None, + ) + .await + .expect_err("invite claim must reject before row lock"), + ); + } + super::relay_invite::mint_relay_invite( + &db.pool, + communities[0], + &"e".repeat(64), + 3600, + Some(1), + ) + .await + .expect("active invite mint succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn user_writers_require_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + super::user::ensure_user(&db.pool, *community, &[1; 32]) + .await + .expect_err("user ensure must reject"), + ); + assert_fenced( + super::user::update_user_profile( + &db.pool, + *community, + &[1; 32], + Some("name"), + None, + None, + None, + ) + .await + .expect_err("profile update must reject"), + ); + } + assert!(super::user::ensure_user(&db.pool, communities[0], &[1; 32]) + .await + .expect("active user ensure succeeds")); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn moderation_writers_require_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + super::moderation::insert_report( + &db.pool, + *community, + super::moderation::NewReport { + report_event_id: &[3; 32], + reporter_pubkey: &[1; 32], + target: super::moderation::ReportTarget::Pubkey(vec![2; 32]), + channel_id: None, + report_type: "spam", + note: None, + }, + ) + .await + .expect_err("moderation report must reject"), + ); + assert_fenced( + super::moderation::insert_action( + &db.pool, + *community, + super::moderation::NewAction { + actor_pubkey: &[1; 32], + action: "ban", + target_pubkey: Some(&[2; 32]), + target_event_id: None, + channel_id: None, + reason_code: None, + public_reason: None, + private_reason: None, + matched_principal: None, + actor_authority: None, + }, + ) + .await + .expect_err("moderation action must reject"), + ); + assert_fenced( + super::moderation::ban_member(&db.pool, *community, &[1; 32], &[2; 32], None, None) + .await + .expect_err("ban must reject"), + ); + assert_fenced( + super::moderation::unban_member(&db.pool, *community, &[1; 32], &[2; 32]) + .await + .expect_err("unban must reject"), + ); + } + super::moderation::ban_member(&db.pool, communities[0], &[1; 32], &[2; 32], None, None) + .await + .expect("active ban succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn workflow_writers_require_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + super::workflow::create_workflow( + &db.pool, *community, None, &[1; 32], "workflow", "{}", &[2; 32], + ) + .await + .expect_err("workflow create must reject"), + ); + assert_fenced( + super::workflow::create_workflow_run(&db.pool, *community, Uuid::new_v4(), None, None) + .await + .expect_err("workflow run create must reject"), + ); + assert_fenced( + super::workflow::claim_scheduled_workflow_fire( + &db.pool, + *community, + Uuid::new_v4(), + chrono::Utc::now(), + ) + .await + .expect_err("schedule claim must reject"), + ); + assert_fenced( + super::workflow::attach_scheduled_workflow_run( + &db.pool, + *community, + Uuid::new_v4(), + chrono::Utc::now(), + Uuid::new_v4(), + ) + .await + .expect_err("schedule attach must reject"), + ); + assert_fenced( + super::workflow::create_approval( + &db.pool, + super::workflow::CreateApprovalParams { + community_id: *community, + token: "fenced-approval", + workflow_id: Uuid::new_v4(), + run_id: Uuid::new_v4(), + step_id: "step", + step_index: 0, + approver_spec: "owner", + expires_at: chrono::Utc::now() + chrono::Duration::hours(1), + }, + ) + .await + .expect_err("approval create must reject"), + ); + assert_fenced( + super::workflow::update_approval_by_stored_hash( + &db.pool, + *community, + &[4; 32], + super::workflow::ApprovalStatus::Granted, + Some(&[1; 32]), + None, + ) + .await + .expect_err("approval update must reject"), + ); + } + super::workflow::create_workflow( + &db.pool, + communities[0], + None, + &[1; 32], + "active", + "{}", + &[2; 32], + ) + .await + .expect("active workflow create succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn push_writers_require_application_admission() { + let (db, communities) = fixture().await; + let version = super::push::LeaseVersion { + source_event_id: &[3; 32], + source_created_at: chrono::Utc::now().timestamp(), + generation: 1, + expires_at: chrono::Utc::now().timestamp() + 3600, + }; + for community in &communities[1..] { + assert_fenced( + super::push::revoke_lease(&db.pool, *community, &[1; 32], "install", version) + .await + .expect_err("lease revoke must reject"), + ); + assert_fenced( + super::push::complete_match_batch(&db.pool, *community, Uuid::new_v4(), &[vec![2; 32]]) + .await + .expect_err("matcher complete must reject"), + ); + assert_fenced( + super::push::complete_wake(&db.pool, *community, Uuid::new_v4(), Uuid::new_v4()) + .await + .expect_err("wake complete must reject"), + ); + } + super::push::revoke_lease(&db.pool, communities[0], &[1; 32], "install", version) + .await + .expect("active lease revoke succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn channel_and_membership_writers_require_application_admission() { + let (db, communities) = fixture().await; + let creator = [1_u8; 32]; + for community in &communities[1..] { + assert_fenced( + super::channel::create_channel( + &db.pool, + *community, + "fenced", + super::channel::ChannelType::Stream, + super::channel::ChannelVisibility::Open, + None, + &creator, + None, + &[], + ) + .await + .expect_err("channel create must reject"), + ); + assert_fenced( + super::channel::set_canvas(&db.pool, *community, Uuid::new_v4(), Some("text")) + .await + .expect_err("canvas update must reject"), + ); + assert_fenced( + super::channel_members::add_member( + &db.pool, + *community, + Uuid::new_v4(), + &[2; 32], + super::channel::MemberRole::Member, + None, + ) + .await + .expect_err("membership add must reject"), + ); + } + let channel = super::channel::create_channel( + &db.pool, + communities[0], + "active", + super::channel::ChannelType::Stream, + super::channel::ChannelVisibility::Open, + None, + &creator, + None, + &[], + ) + .await + .expect("active channel create succeeds"); + super::channel_members::add_member( + &db.pool, + communities[0], + channel.id, + &[2; 32], + super::channel::MemberRole::Member, + None, + ) + .await + .expect("active membership add succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dm_writers_require_application_admission() { + let (db, communities) = fixture().await; + let participants: [&[u8]; 2] = [&[1; 32], &[2; 32]]; + for community in &communities[1..] { + assert_fenced( + super::dm::create_dm(&db.pool, *community, &participants, participants[0]) + .await + .expect_err("DM create must reject"), + ); + assert_fenced( + super::dm::hide_dm(&db.pool, *community, Uuid::new_v4(), participants[0]) + .await + .expect_err("DM hide must reject"), + ); + } + super::dm::create_dm(&db.pool, communities[0], &participants, participants[0]) + .await + .expect("active DM create succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn thread_metadata_writer_requires_application_admission() { + let (db, communities) = fixture().await; + let timestamp = chrono::Utc::now(); + for community in &communities[1..] { + assert_fenced( + super::thread::insert_thread_metadata( + &db.pool, + *community, + &[1; 32], + timestamp, + Uuid::new_v4(), + None, + None, + None, + None, + 0, + false, + ) + .await + .expect_err("thread metadata must reject"), + ); + } + let channel = super::channel::create_channel( + &db.pool, + communities[0], + "thread", + super::channel::ChannelType::Stream, + super::channel::ChannelVisibility::Open, + None, + &[1; 32], + None, + &[], + ) + .await + .expect("active channel"); + super::thread::insert_thread_metadata( + &db.pool, + communities[0], + &[1; 32], + timestamp, + channel.id, + None, + None, + None, + None, + 0, + false, + ) + .await + .expect("active thread metadata insert succeeds"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn relay_admin_domain_writer_requires_application_admission() { + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_fenced( + super::relay_admin_actions::deploy_kick_member( + &db.pool, + *community, + Uuid::new_v4(), + &[1; 32], + &[2; 32], + ) + .await + .expect_err("deployment kick must reject"), + ); + } + let channel = super::channel::create_channel( + &db.pool, + communities[0], + "kick", + super::channel::ChannelType::Stream, + super::channel::ChannelVisibility::Open, + None, + &[1; 32], + None, + &[], + ) + .await + .expect("active channel"); + assert!(matches!( + super::relay_admin_actions::deploy_kick_member( + &db.pool, + communities[0], + channel.id, + &[1; 32], + &[2; 32], + ) + .await + .expect("active kick succeeds"), + super::relay_admin_actions::KickResult::Removed + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn personal_read_writer_requires_application_admission() { + use nostr::{EventBuilder, Keys, Kind}; + let (db, communities) = fixture().await; + let actor = Keys::generate(); + let target = super::personal_read::ReadTarget { + channel_id: Uuid::new_v4(), + root_id: None, + }; + let intent = super::personal_read::ReadIntent::MarkThrough { + target, + message_id: "a".repeat(64), + }; + for community in &communities[1..] { + assert_fenced( + db.apply_personal_read_intent(*community, &actor.public_key(), &intent) + .await + .expect_err("personal read must reject before account lock"), + ); + } + let channel = super::channel::create_channel( + &db.pool, + communities[0], + "reads", + super::channel::ChannelType::Stream, + super::channel::ChannelVisibility::Open, + None, + &actor.public_key().to_bytes(), + None, + &[], + ) + .await + .expect("active channel"); + let event = EventBuilder::new(Kind::Custom(9), "read") + .sign_with_keys(&Keys::generate()) + .expect("sign event"); + db.insert_event(communities[0], &event, Some(channel.id)) + .await + .expect("insert active event"); + let intent = super::personal_read::ReadIntent::MarkThrough { + target: super::personal_read::ReadTarget { + channel_id: channel.id, + root_id: None, + }, + message_id: event.id.to_hex(), + }; + assert_eq!( + db.apply_personal_read_intent(communities[0], &actor.public_key(), &intent) + .await + .expect("active personal read succeeds"), + super::personal_read::IntentOutcome::Applied + ); +} + +async fn count_relay_members(db: &Db, community: CommunityId) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM relay_members WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .expect("count relay members") +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn allowlist_backfill_requires_application_admission() { + let (db, communities) = fixture().await; + for community in &communities { + sqlx::query("INSERT INTO pubkey_allowlist (community_id, pubkey) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(vec![0x5a_u8; 32]) + .execute(&db.pool) + .await + .expect("seed legacy allowlist row"); + } + for community in &communities[1..] { + assert_fenced( + super::relay_members::backfill_from_allowlist(&db.pool, *community) + .await + .expect_err("backfill into a write-fenced community must reject"), + ); + assert_eq!(count_relay_members(&db, *community).await, 0); + } + assert_eq!( + super::relay_members::backfill_from_allowlist(&db.pool, communities[0]) + .await + .expect("active backfill succeeds"), + 1 + ); + assert_eq!(count_relay_members(&db, communities[0]).await, 1); + + // A community that already has members needs no write, so startup does + // not fail on admission even while the community is quiescing. + sqlx::query("INSERT INTO relay_members (community_id, pubkey, role) VALUES ($1, $2, 'member')") + .bind(communities[1].as_uuid()) + .bind("e".repeat(64)) + .execute(&db.pool) + .await + .expect("seed existing member"); + assert_eq!( + super::relay_members::backfill_from_allowlist(&db.pool, communities[1]) + .await + .expect("no-op backfill does not need admission"), + 0 + ); + assert_eq!(count_relay_members(&db, communities[1]).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn empty_allowlist_backfill_skips_admission() { + // No members and no legacy allowlist rows: there is nothing to write, so + // startup must not fail on admission while the community is fenced. + let (db, communities) = fixture().await; + for community in &communities[1..] { + assert_eq!( + super::relay_members::backfill_from_allowlist(&db.pool, *community) + .await + .expect("empty-allowlist backfill does not need admission"), + 0 + ); + assert_eq!(count_relay_members(&db, *community).await, 0); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn owner_mutations_report_pending_deletion_when_admission_refuses() { + let (db, communities) = fixture().await; + let quiescing = communities[1]; + sqlx::query( + "INSERT INTO community_deletion_requests (community_id, community_host, requested_by) \ + SELECT id, host, 'admission-test' FROM communities WHERE id = $1", + ) + .bind(quiescing.as_uuid()) + .execute(&db.pool) + .await + .expect("seed deletion request"); + let owner = "f".repeat(64); + let next_owner = "1".repeat(64); + + assert_eq!( + super::relay_members::transfer_ownership(&db.pool, quiescing, &next_owner, &owner) + .await + .expect("transfer returns a result"), + super::relay_members::TransferResult::DeletionPending + ); + assert_eq!( + db.provision_owner(quiescing, &owner) + .await + .expect("provision returns a result"), + super::relay_members::ProvisionOwnerResult::DeletionPending + ); + + // Without a deletion request the refusal stays a lifecycle conflict. + let fenced = communities[2]; + assert_eq!( + super::relay_members::transfer_ownership(&db.pool, fenced, &next_owner, &owner) + .await + .expect("transfer returns a result"), + super::relay_members::TransferResult::LifecycleConflict + ); + assert_eq!( + db.provision_owner(fenced, &owner) + .await + .expect("provision returns a result"), + super::relay_members::ProvisionOwnerResult::LifecycleConflict + ); + assert_eq!(count_relay_members(&db, quiescing).await, 0); + assert_eq!(count_relay_members(&db, fenced).await, 0); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn invite_sweep_admits_active_tenant_and_skips_quiescing_tenant() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + let cutoff = chrono::Utc::now(); + for (index, community) in communities[..2].iter().enumerate() { + sqlx::query( + "INSERT INTO relay_invites (community_id, token_hash, expires_at, created_by) \ + VALUES ($1, $2, $3, 'test')", + ) + .bind(community.as_uuid()) + .bind(vec![index as u8; 32]) + .bind(cutoff - chrono::Duration::minutes(1)) + .execute(&db.pool) + .await + .expect("seed invite"); + } + assert_eq!( + super::relay_invite::reap_expired_relay_invites(&db.pool, cutoff) + .await + .unwrap(), + 1 + ); + for (community, expected) in [(communities[0], 0), (communities[1], 1)] { + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM relay_invites WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(count, expected, "invite state for {community}"); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn workflow_prune_admits_active_tenant_and_skips_quiescing_tenant() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + let cutoff = chrono::Utc::now(); + for community in &communities[..2] { + sqlx::query( + "INSERT INTO scheduled_workflow_fires \ + (community_id, workflow_id, scheduled_for, claimed_at) VALUES ($1, $2, $3, $4)", + ) + .bind(community.as_uuid()) + .bind(Uuid::new_v4()) + .bind(cutoff - chrono::Duration::hours(2)) + .bind(cutoff - chrono::Duration::hours(1)) + .execute(&db.pool) + .await + .expect("seed fire"); + } + assert_eq!( + super::workflow::prune_scheduled_workflow_fires_before(&db.pool, cutoff) + .await + .unwrap(), + 1 + ); + for (community, expected) in [(communities[0], 0), (communities[1], 1)] { + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM scheduled_workflow_fires WHERE community_id = $1", + ) + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(count, expected, "fire state for {community}"); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn channel_reap_admits_active_tenant_and_skips_quiescing_tenant() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + for community in &communities[..2] { + sqlx::query( + "INSERT INTO channels (community_id, name, created_by, ttl_seconds, ttl_deadline) \ + VALUES ($1, 'expired', $2, 60, now() - interval '1 minute')", + ) + .bind(community.as_uuid()) + .bind(vec![1_u8; 32]) + .execute(&db.pool) + .await + .expect("seed channel"); + } + let reaped = super::channel::reap_expired_ephemeral_channels(&db.pool) + .await + .unwrap(); + assert_eq!(reaped.len(), 1); + assert_eq!(reaped[0].community_id, communities[0]); + for (community, expected) in [(communities[0], true), (communities[1], false)] { + let archived: bool = sqlx::query_scalar( + "SELECT archived_at IS NOT NULL FROM channels WHERE community_id = $1", + ) + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(archived, expected, "archive state for {community}"); + } +} + +/// Keep every failure-injection object, including the ALWAYS trigger's table, +/// in this call's shadow schema so a shared-database run cannot leak it. +async fn fail_tenant_mutations(pool: &sqlx::PgPool, schema: &str, table: &str, id: Uuid) { + // Dynamic identifiers come only from our UUID schema and literal table names. + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE TABLE {schema}.{table} (LIKE public.{table} INCLUDING ALL)" + ))) + .execute(pool) + .await + .expect("create test-local serving table"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE TABLE {schema}.fail_tenant (id uuid PRIMARY KEY)" + ))) + .execute(pool) + .await + .expect("create failure target"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "INSERT INTO {schema}.fail_tenant (id) VALUES ($1)" + ))) + .bind(id) + .execute(pool) + .await + .expect("select failing tenant"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION {schema}.fail_tenant_mutation() RETURNS trigger \ + LANGUAGE plpgsql AS $$ BEGIN \ + IF EXISTS (SELECT 1 FROM {schema}.fail_tenant \ + WHERE id = COALESCE(NEW.community_id, OLD.community_id)) \ + THEN RAISE EXCEPTION 'tenant mutation failed'; END IF; \ + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END $$", + ))) + .execute(pool) + .await + .expect("create failure trigger function"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE TRIGGER fail_tenant_mutation BEFORE UPDATE OR DELETE ON {schema}.{table} \ + FOR EACH ROW EXECUTE FUNCTION {schema}.fail_tenant_mutation()", + ))) + .execute(pool) + .await + .expect("create test-local failure trigger"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER TABLE {schema}.{table} ENABLE ALWAYS TRIGGER fail_tenant_mutation" + ))) + .execute(pool) + .await + .expect("enable trigger with replica role"); +} + +async fn two_active_tenants(db: &Db, first: CommunityId) -> [Uuid; 2] { + let extra = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(extra) + .bind(format!("admission-extra-{extra}.example")) + .execute(&db.pool) + .await + .expect("seed second active tenant"); + let mut ids = [*first.as_uuid(), extra]; + ids.sort(); + ids +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn channel_reap_returns_committed_rows_after_earlier_tenant_error() { + let (db, communities) = fixture().await; + let schema = crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + let ids = two_active_tenants(&db, communities[0]).await; + fail_tenant_mutations(&db.pool, &schema, "channels", ids[0]).await; + for id in ids { + sqlx::query( + "INSERT INTO channels (community_id, name, created_by, ttl_seconds, ttl_deadline) \ + VALUES ($1, 'expired', $2, 60, now() - interval '1 minute')", + ) + .bind(id) + .bind(vec![1_u8; 32]) + .execute(&db.pool) + .await + .expect("seed expired channel"); + } + let reaped = super::channel::reap_expired_ephemeral_channels(&db.pool) + .await + .expect("tenant failure must not stop the fleet sweep"); + assert_eq!(reaped.len(), 1); + assert_eq!(*reaped[0].community_id.as_uuid(), ids[1]); + for (id, expected) in [(ids[0], false), (ids[1], true)] { + let archived: bool = sqlx::query_scalar( + "SELECT archived_at IS NOT NULL FROM channels WHERE community_id = $1", + ) + .bind(id) + .fetch_one(&db.pool) + .await + .expect("read archive state"); + assert_eq!(archived, expected, "archive state for {id}"); + } + sqlx::query(sqlx::AssertSqlSafe(format!( + "DELETE FROM {schema}.fail_tenant" + ))) + .execute(&db.pool) + .await + .unwrap(); + let retried = super::channel::reap_expired_ephemeral_channels(&db.pool) + .await + .unwrap(); + assert_eq!(retried.len(), 1); + assert_eq!(*retried[0].community_id.as_uuid(), ids[0]); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn fleet_sweep_returns_committed_results_when_database_drops_mid_page() { + let (db, communities) = fixture().await; + let [first, second] = two_active_tenants(&db, communities[0]).await; + let candidates = [first, second, Uuid::new_v4()]; + let pulled = std::cell::Cell::new(0); + let pool = db.pool.clone(); + let committed = crate::sweep_admitted_communities( + &db.pool, + candidates + .iter() + .copied() + .inspect(|_| pulled.set(pulled.get() + 1)), + crate::observability::WriterOperation::Maintenance, + "test_sweep", + |id, tx| { + let pool = pool.clone(); + async move { + tx.commit().await?; + pool.close().await; + Ok(id) + } + }, + ) + .await; + assert_eq!(committed, vec![first], "rows committed before the outage"); + assert_eq!( + pulled.get(), + 2, + "the sweep must stop at the unavailable tenant" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn d_tag_backfill_admits_active_tenant_and_skips_quiescing_tenant() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + for (index, community) in communities[..2].iter().enumerate() { + sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig) \ + VALUES ($1, $2, $3, to_timestamp(1), 30023, '[[\"d\",\"tag\"]]'::jsonb, '', $4)", + ) + .bind(community.as_uuid()) + .bind(vec![index as u8; 32]) + .bind(vec![2_u8; 32]) + .bind(vec![3_u8; 64]) + .execute(&db.pool) + .await + .expect("seed addressable event"); + } + assert_eq!(db.backfill_d_tags().await.unwrap(), 1); + let active: Option = + sqlx::query_scalar("SELECT d_tag FROM events WHERE community_id = $1") + .bind(communities[0].as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + let quiescing: Option = + sqlx::query_scalar("SELECT d_tag FROM events WHERE community_id = $1") + .bind(communities[1].as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(active.as_deref(), Some("tag")); + assert_eq!(quiescing, None); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn match_claim_admits_active_tenant_and_skips_quiescing_tenant() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + for (index, community) in communities[..2].iter().enumerate() { + sqlx::query( + "INSERT INTO push_match_queue (community_id, event_id, next_attempt_at) \ + VALUES ($1, $2, now() - make_interval(mins => $3))", + ) + .bind(community.as_uuid()) + .bind(vec![index as u8; 32]) + .bind(if index == 0 { 1 } else { 2 }) + .execute(&db.pool) + .await + .expect("seed match job"); + } + // The production claim is exercised; absent source events are its normal + // terminal cleanup case, so it returns None after claiming and pruning. + assert!(super::push::claim_due_match_batch( + &db.pool, + 8, + chrono::Utc::now() + chrono::Duration::minutes(1) + ) + .await + .unwrap() + .is_none()); + for (community, expected) in [(communities[0], 0), (communities[1], 1)] { + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM push_match_queue WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(count, expected, "match job for {community}"); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn match_reap_admits_active_tenant_and_skips_quiescing_tenant() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + for (index, community) in communities[..2].iter().enumerate() { + sqlx::query( + "INSERT INTO push_match_queue (community_id, event_id, attempts) VALUES ($1, $2, $3)", + ) + .bind(community.as_uuid()) + .bind(vec![index as u8; 32]) + .bind(super::push::MAX_MATCH_ATTEMPTS) + .execute(&db.pool) + .await + .expect("seed exhausted match job"); + } + assert_eq!( + super::push::reap_exhausted_matches(&db.pool).await.unwrap(), + 1 + ); + for (community, expected) in [(communities[0], 0), (communities[1], 1)] { + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM push_match_queue WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(count, expected, "exhausted job for {community}"); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn invite_sweep_rechecks_admission_after_candidate_read() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + let community = communities[0]; + let cutoff = chrono::Utc::now(); + sqlx::query( + "INSERT INTO relay_invites (community_id, token_hash, expires_at, created_by) \ + VALUES ($1, $2, $3, 'test')", + ) + .bind(community.as_uuid()) + .bind(vec![0_u8; 32]) + .bind(cutoff - chrono::Duration::minutes(1)) + .execute(&db.pool) + .await + .unwrap(); + let pool = db.pool.clone(); + let reaped = crate::test_support::fence_while_sweep_waits(community, async move { + super::relay_invite::reap_expired_relay_invites(&pool, cutoff).await + }) + .await + .unwrap(); + assert_eq!(reaped, 0); + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM relay_invites WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(count, 1, "newly fenced tenant's invite must remain"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn channel_reap_rechecks_admission_after_candidate_read() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + let community = communities[0]; + sqlx::query( + "INSERT INTO channels (community_id, name, created_by, ttl_seconds, ttl_deadline) \ + VALUES ($1, 'expired', $2, 60, now() - interval '1 minute')", + ) + .bind(community.as_uuid()) + .bind(vec![1_u8; 32]) + .execute(&db.pool) + .await + .unwrap(); + let pool = db.pool.clone(); + let reaped = crate::test_support::fence_while_sweep_waits(community, async move { + super::channel::reap_expired_ephemeral_channels(&pool).await + }) + .await + .unwrap(); + assert!(reaped.is_empty()); + let archived: bool = + sqlx::query_scalar("SELECT archived_at IS NOT NULL FROM channels WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .unwrap(); + assert!( + !archived, + "newly fenced tenant's channel must remain unarchived" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn match_claim_rechecks_admission_and_continues_after_candidate_read() { + let (db, communities) = fixture().await; + crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + let ids = two_active_tenants(&db, communities[0]).await; + for (index, id) in ids.iter().enumerate() { + sqlx::query( + "INSERT INTO push_match_queue (community_id, event_id, next_attempt_at) \ + VALUES ($1, $2, now() - make_interval(mins => $3))", + ) + .bind(id) + .bind(vec![index as u8; 32]) + .bind(if index == 0 { 2 } else { 1 }) + .execute(&db.pool) + .await + .unwrap(); + } + let pool = db.pool.clone(); + // Missing source events take the production claim's terminal cleanup path. + crate::test_support::fence_while_sweep_waits(CommunityId::from_uuid(ids[0]), async move { + super::push::claim_due_match_batch( + &pool, + 8, + chrono::Utc::now() + chrono::Duration::minutes(1), + ) + .await + }) + .await + .unwrap(); + for (id, expected) in [(ids[0], 1), (ids[1], 0)] { + let state: Vec<(String, i32)> = + sqlx::query_as("SELECT state, attempts FROM push_match_queue WHERE community_id = $1") + .bind(id) + .fetch_all(&db.pool) + .await + .unwrap(); + assert_eq!(state.len(), expected, "queue state for {id}"); + if expected == 1 { + assert_eq!(state[0], ("pending".to_owned(), 0)); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn periodic_reaps_continue_after_tenant_error_and_retry_retained_rows() { + for table in [ + "relay_invites", + "scheduled_workflow_fires", + "push_match_queue", + ] { + let (db, communities) = fixture().await; + let schema = crate::test_support::reject_legacy_sql_fence_predicate(&db.pool).await; + let ids = two_active_tenants(&db, communities[0]).await; + fail_tenant_mutations(&db.pool, &schema, table, ids[0]).await; + let cutoff = chrono::Utc::now(); + for id in ids { + match table { + "relay_invites" => { + sqlx::query( + "INSERT INTO relay_invites (community_id, token_hash, expires_at, created_by) \ + VALUES ($1, $2, $3, 'test')", + ) + .bind(id).bind(vec![1_u8; 32]) + .bind(cutoff - chrono::Duration::minutes(if id == ids[0] { 2 } else { 1 })) + .execute(&db.pool).await.unwrap(); + } + "scheduled_workflow_fires" => { + sqlx::query( + "INSERT INTO scheduled_workflow_fires \ + (community_id, workflow_id, scheduled_for, claimed_at) \ + VALUES ($1, $2, $3, $3)", + ) + .bind(id) + .bind(Uuid::new_v4()) + .bind(cutoff - chrono::Duration::hours(1)) + .execute(&db.pool) + .await + .unwrap(); + } + "push_match_queue" => { + sqlx::query( + "INSERT INTO push_match_queue (community_id, event_id, attempts) \ + VALUES ($1, $2, $3)", + ) + .bind(id) + .bind(vec![1_u8; 32]) + .bind(super::push::MAX_MATCH_ATTEMPTS) + .execute(&db.pool) + .await + .unwrap(); + } + _ => unreachable!(), + } + } + for retry in [false, true] { + if retry { + sqlx::query(sqlx::AssertSqlSafe(format!( + "DELETE FROM {schema}.fail_tenant" + ))) + .execute(&db.pool) + .await + .unwrap(); + } + let count = match table { + "relay_invites" => { + super::relay_invite::reap_expired_relay_invites(&db.pool, cutoff).await + } + "scheduled_workflow_fires" => { + super::workflow::prune_scheduled_workflow_fires_before(&db.pool, cutoff).await + } + "push_match_queue" => super::push::reap_exhausted_matches(&db.pool).await, + _ => unreachable!(), + } + .expect("per-tenant failures must not stop recurring sweeps"); + assert_eq!(count, 1, "{table}, retry={retry}"); + for (id, expected) in [(ids[0], i64::from(!retry)), (ids[1], 0)] { + let remaining: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table} WHERE community_id = $1", + ))) + .bind(id) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(remaining, expected, "{table} state for {id}, retry={retry}"); + } + } + } +} diff --git a/crates/buzz-db/src/store/allowlist.rs b/crates/buzz-db/src/store/allowlist.rs index 6b213d5cce8..c493cab22f5 100644 --- a/crates/buzz-db/src/store/allowlist.rs +++ b/crates/buzz-db/src/store/allowlist.rs @@ -28,12 +28,17 @@ impl Db { /// Check if a pubkey is in the allowlist for `community`. #[datastore_span(name = "is_pubkey_allowed", system = "postgresql")] pub async fn is_pubkey_allowed(&self, community: CommunityId, pubkey: &[u8]) -> Result { + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authentication, + ) + .await?; let row = sqlx::query( "SELECT COUNT(*) as cnt FROM pubkey_allowlist WHERE community_id = $1 AND pubkey = $2", ) .bind(community.as_uuid()) .bind(pubkey) - .fetch_one(&self.pool) + .fetch_one(&mut *connection) .await?; let cnt: i64 = row.try_get("cnt")?; Ok(cnt > 0) @@ -42,10 +47,15 @@ impl Db { /// Check if the community allowlist has any entries (i.e. is enforcement active). #[datastore_span(name = "has_allowlist_entries", system = "postgresql")] pub async fn has_allowlist_entries(&self, community: CommunityId) -> Result { + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authentication, + ) + .await?; let row = sqlx::query("SELECT COUNT(*) as cnt FROM pubkey_allowlist WHERE community_id = $1") .bind(community.as_uuid()) - .fetch_one(&self.pool) + .fetch_one(&mut *connection) .await?; let cnt: i64 = row.try_get("cnt")?; Ok(cnt > 0) @@ -60,6 +70,12 @@ impl Db { added_by: &[u8], note: Option<&str>, ) -> Result { + let mut tx = crate::begin_community_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::Authorization, + ) + .await?; let result = sqlx::query( "INSERT INTO pubkey_allowlist (community_id, pubkey, added_by, note) VALUES ($1, $2, $3, $4) \ ON CONFLICT DO NOTHING", @@ -68,8 +84,9 @@ impl Db { .bind(pubkey) .bind(added_by) .bind(note) - .execute(&self.pool) + .execute(tx.conn()) .await?; + tx.commit().await?; Ok(result.rows_affected() > 0) } @@ -80,23 +97,35 @@ impl Db { community: CommunityId, pubkey: &[u8], ) -> Result { + let mut tx = crate::begin_community_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::Authorization, + ) + .await?; let result = sqlx::query("DELETE FROM pubkey_allowlist WHERE community_id = $1 AND pubkey = $2") .bind(community.as_uuid()) .bind(pubkey) - .execute(&self.pool) + .execute(tx.conn()) .await?; + tx.commit().await?; Ok(result.rows_affected() > 0) } /// List all pubkeys in the community allowlist. #[datastore_span(name = "list_allowlist", system = "postgresql")] pub async fn list_allowlist(&self, community: CommunityId) -> Result> { + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; let rows = sqlx::query( "SELECT pubkey, added_by, added_at, note FROM pubkey_allowlist WHERE community_id = $1 ORDER BY added_at DESC", ) .bind(community.as_uuid()) - .fetch_all(&self.pool) + .fetch_all(&mut *connection) .await?; let mut out = Vec::with_capacity(rows.len()); @@ -113,7 +142,7 @@ impl Db { } #[cfg(test)] -mod tests { +mod postgres_tests { use super::*; use sqlx::PgPool; use uuid::Uuid; diff --git a/crates/buzz-db/src/store/api_token.rs b/crates/buzz-db/src/store/api_token.rs index ec380d9e5e7..6c0eab0bf25 100644 --- a/crates/buzz-db/src/store/api_token.rs +++ b/crates/buzz-db/src/store/api_token.rs @@ -38,6 +38,12 @@ pub async fn create_api_token( }) .transpose()?; + let mut tx = crate::begin_community_write_transaction( + pool, + CommunityId::from_uuid(community_id), + crate::observability::WriterOperation::Authentication, + ) + .await?; sqlx::query( r#" INSERT INTO api_tokens @@ -53,9 +59,9 @@ pub async fn create_api_token( .bind(&scopes_json) .bind(&channel_ids_json) .bind(expires_at) - .execute(pool) + .execute(tx.conn()) .await?; - + tx.commit().await?; Ok(id) } @@ -94,6 +100,12 @@ pub async fn create_api_token_if_under_limit( // Conditional INSERT: only inserts if active (non-revoked, non-expired) token count < 10 // **for this (community, owner) pair**. The subquery and insert execute atomically -- // no separate count + insert race. + let mut tx = crate::begin_community_write_transaction( + pool, + CommunityId::from_uuid(community_id), + crate::observability::WriterOperation::Authentication, + ) + .await?; let result = sqlx::query( r#" INSERT INTO api_tokens @@ -118,8 +130,9 @@ pub async fn create_api_token_if_under_limit( .bind(&channel_ids_json) .bind(expires_at) .bind(owner_pubkey) - .execute(pool) + .execute(tx.conn()) .await?; + tx.commit().await?; if result.rows_affected() == 0 { // Limit exceeded -- the WHERE clause prevented the INSERT. @@ -279,6 +292,12 @@ pub async fn revoke_token( owner_pubkey: &[u8], revoked_by: &[u8], ) -> Result { + let mut tx = crate::begin_community_write_transaction( + pool, + CommunityId::from_uuid(community_id), + crate::observability::WriterOperation::Authentication, + ) + .await?; let result = sqlx::query( r#" UPDATE api_tokens @@ -293,9 +312,9 @@ pub async fn revoke_token( .bind(community_id) .bind(id) .bind(owner_pubkey) - .execute(pool) + .execute(tx.conn()) .await?; - + tx.commit().await?; Ok(result.rows_affected() > 0) } @@ -309,6 +328,12 @@ pub async fn revoke_all_tokens( owner_pubkey: &[u8], revoked_by: &[u8], ) -> Result { + let mut tx = crate::begin_community_write_transaction( + pool, + CommunityId::from_uuid(community_id), + crate::observability::WriterOperation::Authentication, + ) + .await?; let result = sqlx::query( r#" UPDATE api_tokens @@ -321,9 +346,9 @@ pub async fn revoke_all_tokens( .bind(revoked_by) .bind(community_id) .bind(owner_pubkey) - .execute(pool) + .execute(tx.conn()) .await?; - + tx.commit().await?; Ok(result.rows_affected()) } @@ -504,13 +529,20 @@ impl Db { /// Record a token usage (update `last_used_at`), scoped to community. #[datastore_span(name = "touch_api_token", system = "postgresql")] pub async fn touch_api_token(&self, community_id: CommunityId, hash: &[u8]) -> Result<()> { + let mut tx = crate::begin_community_write_transaction( + &self.pool, + community_id, + crate::observability::WriterOperation::Authentication, + ) + .await?; sqlx::query( "UPDATE api_tokens SET last_used_at = NOW() WHERE community_id = $1 AND token_hash = $2", ) .bind(community_id.as_uuid()) .bind(hash) - .execute(&self.pool) + .execute(tx.conn()) .await?; + tx.commit().await?; Ok(()) } @@ -606,7 +638,7 @@ impl Db { } #[cfg(test)] -mod tests { +mod postgres_tests { //! Row-44 conformance: API token lookups MUST be keyed on //! `(community_id, token_hash)`, not on `token_hash` alone. The storage //! UNIQUE index is a *storage* guarantee; the WHERE clause here is the @@ -625,10 +657,8 @@ mod tests { use crate::{ApiTokenRecord, Db}; use sqlx::PgPool; - const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials - async fn setup_db() -> Db { - let pool = PgPool::connect(TEST_DB_URL) + let pool = PgPool::connect(&crate::test_support::database_url()) .await .expect("connect to test DB"); Db::from_pool(pool) diff --git a/crates/buzz-db/src/store/archived_identities.rs b/crates/buzz-db/src/store/archived_identities.rs index 810c8c0aa1f..986985bc464 100644 --- a/crates/buzz-db/src/store/archived_identities.rs +++ b/crates/buzz-db/src/store/archived_identities.rs @@ -34,11 +34,16 @@ pub struct ArchivedIdentity { /// Returns `true` if `pubkey` (64-char hex) is archived in `community_id`. pub async fn is_archived(pool: &PgPool, community_id: CommunityId, pubkey: &str) -> Result { + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::EventWrite, + ) + .await?; let row = sqlx::query("SELECT 1 FROM archived_identities WHERE community_id = $1 AND pubkey = $2") .bind(community_id.as_uuid()) .bind(pubkey) - .fetch_optional(pool) + .fetch_optional(&mut *connection) .await?; Ok(row.is_some()) } @@ -59,6 +64,12 @@ pub async fn archive( replaced_by: Option<&str>, request_event_id: &str, ) -> Result { + let mut tx = crate::begin_community_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; let result = sqlx::query( "INSERT INTO archived_identities \ (community_id, pubkey, consent_path, actor, reason, replaced_by, request_event_id) \ @@ -72,9 +83,9 @@ pub async fn archive( .bind(reason) .bind(replaced_by) .bind(request_event_id) - .execute(pool) + .execute(tx.conn()) .await?; - + tx.commit().await?; Ok(result.rows_affected() > 0) } @@ -83,13 +94,19 @@ pub async fn archive( /// Returns `true` if a row was deleted, `false` if the identity was not archived /// in that community. pub async fn unarchive(pool: &PgPool, community_id: CommunityId, pubkey: &str) -> Result { + let mut tx = crate::begin_community_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; let result = sqlx::query("DELETE FROM archived_identities WHERE community_id = $1 AND pubkey = $2") .bind(community_id.as_uuid()) .bind(pubkey) - .execute(pool) + .execute(tx.conn()) .await?; - + tx.commit().await?; Ok(result.rows_affected() > 0) } @@ -98,12 +115,17 @@ pub async fn list_archived( pool: &PgPool, community_id: CommunityId, ) -> Result> { + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::EventWrite, + ) + .await?; let rows = sqlx::query( "SELECT pubkey, consent_path, actor, reason, replaced_by, request_event_id, archived_at \ FROM archived_identities WHERE community_id = $1 ORDER BY archived_at ASC", ) .bind(community_id.as_uuid()) - .fetch_all(pool) + .fetch_all(&mut *connection) .await?; rows.into_iter() @@ -176,13 +198,11 @@ impl Db { } #[cfg(test)] -mod tests { +mod postgres_tests { use super::*; - const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 - async fn setup_pool() -> PgPool { - PgPool::connect(TEST_DB_URL) + PgPool::connect(&crate::test_support::database_url()) .await .expect("connect to test DB") } diff --git a/crates/buzz-db/src/store/artifact.rs b/crates/buzz-db/src/store/artifact.rs new file mode 100644 index 00000000000..a8a49ac602b --- /dev/null +++ b/crates/buzz-db/src/store/artifact.rs @@ -0,0 +1,210 @@ +//! NIP-AR atomic artifact acceptance. Payloads remain opaque signed events. +//! +//! Channel write permission is checked by the relay's ordinary ingest gates +//! before this transaction; here the relay only serializes each identity and +//! compares the expected head. +use crate::{Db, DbError, Result}; +use buzz_core::artifact::{ArtifactEnvelope, ArtifactOp}; +use buzz_core::{CommunityId, StoredEvent}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use sqlx::Row; +use uuid::Uuid; + +/// Acceptance outcome. Only a stale-`prev` conflict carries the current head, +/// which the caller discloses after authorizing its channel. +#[derive(Debug)] +pub enum ArtifactOutcome { + /// Accepted once; stored events to publish (the revision, plus the source + /// removal on a move). + Accepted(Vec), + /// Identical previously accepted event; no repeated side effects. + Duplicate, + /// `prev` or identity no longer matches; the client should reconcile. + Conflict(&'static str), + /// Protocol violation with a public-safe reason. + Rejected(&'static str), +} + +/// Conflict for a non-create revision whose artifact is missing or lives +/// outside every channel the sender was authorized for. +pub const HEAD_UNAVAILABLE: &str = "artifact head unavailable"; + +fn invalid(message: &str) -> DbError { + DbError::InvalidData(message.into()) +} + +/// The replaced revision (`prev`) was readable in the source, so it +/// distinguishes repeated moves without revealing other activity. +fn removal_marker(keys: &Keys, artifact: Uuid, source: Uuid, prev: &[u8]) -> Result { + let tags = [ + ["ar", "1"].map(str::to_owned), + ["d".into(), artifact.to_string()], + ["h".into(), source.to_string()], + ["reason".into(), "moved".into()], + ["prev".into(), hex::encode(prev)], + ] + .into_iter() + .map(Tag::parse) + .collect::, _>>() + .map_err(|e| invalid(&e.to_string()))?; + EventBuilder::new(Kind::Custom(45011), "") + .tags(tags) + .sign_with_keys(keys) + .map_err(|e| invalid(&e.to_string())) +} + +impl Db { + /// Check the durable acceptance ledger, which survives redaction and retention. + pub async fn artifact_accepted(&self, community: CommunityId, id: &[u8]) -> Result { + let mut conn = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + Ok(sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND event_id=$2)", + ) + .bind(community.as_uuid()) + .bind(id) + .fetch_one(&mut *conn) + .await?) + } + + /// Current home channel, read before authorizing a move's source. + pub async fn artifact_home( + &self, + community: CommunityId, + artifact: Uuid, + ) -> Result> { + let mut conn = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + Ok(sqlx::query_scalar( + "SELECT channel_id FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2", + ) + .bind(community.as_uuid()) + .bind(artifact) + .fetch_optional(&mut *conn) + .await?) + } + + /// Atomically compare the expected head, store the full revision, advance + /// the head, and on a move store the source removal. `authorized_source` is + /// the move source the caller authorized; a head that has since moved elsewhere + /// conflicts. Relay keys only sign removals. + pub async fn accept_artifact( + &self, + community: CommunityId, + event: &Event, + env: &ArtifactEnvelope, + authorized_source: Option, + relay_keys: &Keys, + ) -> Result { + let mut tx = self.begin_event_write_transaction(community).await?; + sqlx::query("SET LOCAL statement_timeout='5s'") + .execute(tx.conn()) + .await?; + // A coordinate lock handles the missing-row create race as well as edits. + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))") + .bind(format!("artifact:{}:{}", community.as_uuid(), env.id)) + .execute(tx.conn()) + .await?; + let duplicate: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND event_id=$2)", + ) + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .fetch_one(tx.conn()) + .await?; + if duplicate { + return Ok(ArtifactOutcome::Duplicate); + } + let head = sqlx::query( + "SELECT event_id,channel_id,artifact_type,root,deleted FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2 FOR UPDATE", + ) + .bind(community.as_uuid()) + .bind(env.id) + .fetch_optional(tx.conn()) + .await?; + let source = head.as_ref().map(|h| h.get::("channel_id")); + let old_root = head + .as_ref() + .and_then(|h| h.get::>, _>("root")); + match (&head, env.op) { + (Some(_), ArtifactOp::Create) => { + return Ok(ArtifactOutcome::Conflict("artifact identity is taken")) + } + (None, ArtifactOp::Create) => {} + (None, _) => return Ok(ArtifactOutcome::Conflict(HEAD_UNAVAILABLE)), + // The caller authorized writes only in `h`, or for a move in the + // source it read before this transaction. A head anywhere else + // answers like a missing one, before any check that describes it. + (Some(_), op) + if source + != match op { + ArtifactOp::Move => authorized_source, + _ => Some(env.home), + } => + { + return Ok(ArtifactOutcome::Conflict(HEAD_UNAVAILABLE)) + } + (Some(head), op) => { + let current: Vec = head.get("event_id"); + if env.prev.as_deref() != Some(current.as_slice()) { + return Ok(ArtifactOutcome::Conflict("artifact head changed")); + } + if env.artifact_type != head.get::("artifact_type") { + return Ok(ArtifactOutcome::Rejected("artifact type is immutable")); + } + if head.get::("deleted") != (op == ArtifactOp::Restore) { + return Ok(ArtifactOutcome::Rejected( + "deleted artifacts require restore; live artifacts cannot restore", + )); + } + if (op == ArtifactOp::Move) != (source != Some(env.home)) { + return Ok(ArtifactOutcome::Rejected( + "only move changes home and move must change home", + )); + } + if op == ArtifactOp::Delete && env.root != old_root { + return Ok(ArtifactOutcome::Rejected("delete preserves root")); + } + } + } + if head.is_none() || env.root != old_root || source != Some(env.home) { + if let Some(root) = &env.root { + let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND id=$2 AND channel_id=$3 AND deleted_at IS NULL AND kind IN (9,40002,45001,45003))") + .bind(community.as_uuid()).bind(root).bind(env.home).fetch_one(tx.conn()).await?; + if !exists { + return Ok(ArtifactOutcome::Rejected( + "root must be an existing conversation anchor in home", + )); + } + } + } + sqlx::query( + "INSERT INTO artifact_revisions (community_id,event_id,artifact_id) VALUES ($1,$2,$3)", + ) + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .bind(env.id) + .execute(tx.conn()) + .await?; + sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted") + .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(env.home).bind(&env.artifact_type).bind(&env.root).bind(env.op == ArtifactOp::Delete).execute(tx.conn()).await?; + let (stored, _) = + crate::event::insert_event_in_transaction(&mut tx, event, Some(env.home)).await?; + crate::insert_mentions_in_transaction(&mut tx, event, Some(env.home)).await?; + let mut accepted = vec![stored]; + if let (ArtifactOp::Move, Some(source), Some(prev)) = (env.op, source, &env.prev) { + let removal = removal_marker(relay_keys, env.id, source, prev)?; + let (stored, _) = + crate::event::insert_event_in_transaction(&mut tx, &removal, Some(source)).await?; + accepted.push(stored); + } + tx.commit().await?; + Ok(ArtifactOutcome::Accepted(accepted)) + } +} diff --git a/crates/buzz-db/src/store/artifact_postgres_tests.rs b/crates/buzz-db/src/store/artifact_postgres_tests.rs new file mode 100644 index 00000000000..90aaf69272e --- /dev/null +++ b/crates/buzz-db/src/store/artifact_postgres_tests.rs @@ -0,0 +1,581 @@ +//! PostgreSQL regression tests for the production artifact transaction/query seams. +use super::artifact::ArtifactOutcome; +use crate::Db; +use buzz_core::{artifact, CommunityId}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use sqlx::PgPool; +use uuid::Uuid; + +struct Fixture { + db: Db, + community: CommunityId, + a: Uuid, + b: Uuid, + owner: Keys, + peer: Keys, + relay: Keys, +} +impl Fixture { + async fn new() -> Self { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + crate::migration::run_migrations(&pool).await.unwrap(); + } + let db = Db::from_pool(pool); + db.maintain_partitions( + 1, + crate::partition::PartitionMaintenancePolicy { + create_enabled: true, + advance_enabled: false, + }, + ) + .await + .unwrap(); + let community = CommunityId::from_uuid(Uuid::new_v4()); + sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)") + .bind(community.as_uuid()) + .bind(format!("artifact-{}.test", community.as_uuid())) + .execute(&db.pool) + .await + .unwrap(); + let owner = Keys::generate(); + let peer = Keys::generate(); + let a = Uuid::new_v4(); + let b = Uuid::new_v4(); + for (id, visibility) in [(a, "open"), (b, "private")] { + sqlx::query("INSERT INTO channels(community_id,id,name,visibility,channel_type,created_by) VALUES($1,$2,$3,$4::channel_visibility,'stream',$5)") + .bind(community.as_uuid()).bind(id).bind(id.to_string()).bind(visibility).bind(owner.public_key().to_bytes().as_slice()).execute(&db.pool).await.unwrap(); + sqlx::query("INSERT INTO channel_members(community_id,channel_id,pubkey,role) VALUES($1,$2,$3,'owner')") + .bind(community.as_uuid()).bind(id).bind(owner.public_key().to_bytes().as_slice()).execute(&db.pool).await.unwrap(); + } + Self { + db, + community, + a, + b, + owner, + peer, + relay: Keys::generate(), + } + } + fn revision( + &self, + d: Uuid, + op: &str, + home: Uuid, + prev: Option<&Event>, + key: &Keys, + extra: Vec>, + ) -> Event { + let mut tags = vec![ + vec!["ar".into(), "1".into()], + vec!["d".into(), d.to_string()], + vec!["h".into(), home.to_string()], + vec!["type".into(), "buzz.task".into()], + vec!["op".into(), op.into()], + ]; + if op != "delete" { + tags.push(vec!["title".into(), "Test".into()]); + } + if let Some(e) = prev { + tags.push(vec!["prev".into(), e.id.to_hex()]); + } + tags.extend(extra); + EventBuilder::new( + Kind::Custom(45010), + if op == "delete" { "" } else { "secret" }, + ) + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .sign_with_keys(key) + .unwrap() + } + async fn accept(&self, e: &Event, source: Option) -> ArtifactOutcome { + let env = artifact::validate(e).unwrap(); + self.db + .accept_artifact(self.community, e, &env, source, &self.relay) + .await + .unwrap() + } + async fn count(&self, key: &Keys, value: serde_json::Value) -> i64 { + self.query(key, value, true).await.1 + } + async fn query( + &self, + key: &Keys, + value: serde_json::Value, + count: bool, + ) -> (Vec, i64) { + self.db + .query_artifacts( + self.community, + key.public_key().as_bytes(), + &artifact::parse_query(&value).unwrap(), + count, + ) + .await + .unwrap() + } +} +#[tokio::test] +#[ignore = "requires Postgres"] +async fn lifecycle_cas_queries_move_redaction_and_retention() { + let f = Fixture::new().await; + let d = Uuid::new_v4(); + let project = |v: &str| vec![vec!["project".to_string(), v.to_string()]]; + let create = f.revision(d, "create", f.a, None, &f.owner, project("A")); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Accepted(_) + )); + let x = f.revision(d, "update", f.a, Some(&create), &f.owner, project("B")); + let y = f.revision(d, "update", f.a, Some(&create), &f.peer, project("B")); + let (rx, ry) = tokio::join!(f.accept(&x, None), f.accept(&y, None)); + let head = match (rx, ry) { + (ArtifactOutcome::Accepted(_), ArtifactOutcome::Conflict(..)) => &x, + (ArtifactOutcome::Conflict(..), ArtifactOutcome::Accepted(_)) => &y, + other => panic!("exactly one CAS winner: {other:?}"), + }; + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Duplicate + )); + let current = |p: &str| serde_json::json!({"artifact":"current","#d":[d],"#project":[p]}); + assert_eq!(f.count(&f.owner, current("A")).await, 0); + assert_eq!(f.count(&f.owner, current("B")).await, 1); + // First value in the same tag, never an annotation or reverse-name match. + let wrong = f.revision( + d, + "update", + f.a, + Some(head), + &f.owner, + vec![ + vec!["project".into(), "C".into(), "B".into()], + vec!["B".into(), "project".into()], + ], + ); + assert!(matches!( + f.accept(&wrong, None).await, + ArtifactOutcome::Accepted(_) + )); + assert_eq!(f.count(&f.owner, current("B")).await, 0); + + // A move commits only against the source the relay authorized. + let moved = f.revision(d, "move", f.b, Some(&wrong), &f.owner, vec![]); + assert!(matches!( + f.accept(&moved, Some(f.b)).await, + ArtifactOutcome::Conflict(..) + )); + let ArtifactOutcome::Accepted(stored) = f.accept(&moved, Some(f.a)).await else { + panic!("move accepted"); + }; + let removal = &stored[1]; + assert_eq!(removal.event.kind.as_u16(), 45011); + assert_eq!(removal.channel_id, Some(f.a)); + assert!(!serde_json::to_string(&removal.event) + .unwrap() + .contains(&f.b.to_string())); + let all = serde_json::json!({"artifact":"current","#d":[d]}); + let history = serde_json::json!({"artifact":"history","#d":[d]}); + assert_eq!(f.count(&f.peer, all.clone()).await, 0); + assert_eq!(f.count(&f.peer, history.clone()).await, 3); + assert_eq!(f.count(&f.owner, history.clone()).await, 4); + + // Expiring an earlier payload keeps its identity reserved. + let retention = |id: nostr::EventId| { + sqlx::query("DELETE FROM events WHERE community_id=$1 AND id=$2") + .bind(f.community.as_uuid()) + .bind(id.as_bytes().to_vec()) + }; + assert_eq!( + retention(create.id) + .execute(&f.db.pool) + .await + .unwrap() + .rows_affected(), + 1 + ); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Duplicate + )); + + // Redaction is the generic soft delete: the head stays, its payload is hidden + // everywhere and may then be purged. + assert!(f + .db + .soft_delete_event_and_update_thread(f.community, moved.id.as_bytes(), None, None) + .await + .unwrap()); + assert_eq!(f.count(&f.owner, all.clone()).await, 0); + assert_eq!(f.count(&f.owner, history.clone()).await, 2); + assert_eq!( + retention(moved.id) + .execute(&f.db.pool) + .await + .unwrap() + .rows_affected(), + 1 + ); + assert!(f + .db + .soft_delete_event_and_update_thread(f.community, removal.event.id.as_bytes(), None, None) + .await + .is_err()); + + let deleted = f.revision(d, "delete", f.b, Some(&moved), &f.owner, vec![]); + assert!(matches!( + f.accept(&deleted, None).await, + ArtifactOutcome::Accepted(_) + )); + assert_eq!(f.count(&f.owner, all.clone()).await, 0); + let update = f.revision(d, "update", f.b, Some(&deleted), &f.owner, vec![]); + assert!(matches!( + f.accept(&update, None).await, + ArtifactOutcome::Rejected(_) + )); + let restore = f.revision(d, "restore", f.b, Some(&deleted), &f.peer, vec![]); + assert!(matches!( + f.accept(&restore, None).await, + ArtifactOutcome::Accepted(_) + )); + assert_eq!(f.count(&f.owner, all.clone()).await, 1); + // Reads observe removed private membership. + sqlx::query( + "UPDATE channel_members SET removed_at=now() WHERE community_id=$1 AND channel_id=$2", + ) + .bind(f.community.as_uuid()) + .bind(f.b) + .execute(&f.db.pool) + .await + .unwrap(); + assert_eq!(f.count(&f.owner, all).await, 0); + f.db.validate_deletion_serving_catalog().await.unwrap(); +} + +/// An artifact in a system channel is read only by a query whose `#h` names +/// that channel (NIP-CL), even when the channel is open. +/// Mutation: drop the `channel_type` condition from `query_artifacts` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn system_channel_artifacts_are_read_only_by_name() { + let f = Fixture::new().await; + let system = Uuid::new_v4(); + sqlx::query("INSERT INTO channels(community_id,id,name,visibility,channel_type,created_by) VALUES($1,$2,$3,'open','system',$4)") + .bind(f.community.as_uuid()) + .bind(system) + .bind(system.to_string()) + .bind(f.owner.public_key().to_bytes().as_slice()) + .execute(&f.db.pool) + .await + .unwrap(); + for home in [f.a, system] { + let create = f.revision(Uuid::new_v4(), "create", home, None, &f.owner, vec![]); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Accepted(_) + )); + } + for reader in [&f.owner, &f.peer] { + let (events, _) = f + .query(reader, serde_json::json!({"artifact":"current"}), false) + .await; + let homes: Vec<_> = events.iter().map(|e| e.channel_id).collect(); + assert_eq!(homes, [Some(f.a)], "no #h"); + assert_eq!( + f.count(reader, serde_json::json!({"artifact":"current"})) + .await, + 1 + ); + let named = serde_json::json!({"artifact":"current","#h":[system.to_string()]}); + let (events, _) = f.query(reader, named.clone(), false).await; + let homes: Vec<_> = events.iter().map(|e| e.channel_id).collect(); + assert_eq!(homes, [Some(system)], "#h names the system channel"); + assert_eq!(f.count(reader, named).await, 1); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn repeated_moves_get_distinct_source_safe_markers() { + let f = Fixture::new().await; + let d = Uuid::new_v4(); + let create = f.revision(d, "create", f.a, None, &f.owner, vec![]); + let there = f.revision(d, "move", f.b, Some(&create), &f.owner, vec![]); + let back = f.revision(d, "move", f.a, Some(&there), &f.owner, vec![]); + let again = f.revision(d, "move", f.b, Some(&back), &f.owner, vec![]); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Accepted(_) + )); + let mut markers = Vec::new(); + for (event, source, replaced) in [ + (&there, f.a, &create), + (&back, f.b, &there), + (&again, f.a, &back), + ] { + let ArtifactOutcome::Accepted(stored) = f.accept(event, Some(source)).await else { + panic!("move accepted"); + }; + let marker = stored[1].event.clone(); + // Only `prev` distinguishes same-second markers for one source. + let tags: Vec<_> = marker.tags.iter().map(|t| t.as_slice().to_vec()).collect(); + assert_eq!( + tags, + [ + vec!["ar".to_string(), "1".into()], + vec!["d".into(), d.to_string()], + vec!["h".into(), source.to_string()], + vec!["reason".into(), "moved".into()], + vec!["prev".into(), replaced.id.to_hex()], + ] + ); + markers.push(marker.id); + } + assert_ne!(markers[0], markers[2]); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn root_anchor_and_tenant_boundaries() { + let f = Fixture::new().await; + let d = Uuid::new_v4(); + let invalid = f.revision( + d, + "create", + f.a, + None, + &f.owner, + vec![vec!["root".into(), "a".repeat(64)]], + ); + assert!(matches!( + f.accept(&invalid, None).await, + ArtifactOutcome::Rejected(_) + )); + let anchor = EventBuilder::new(Kind::Custom(9), "anchor") + .tags([Tag::parse(["h", &f.a.to_string()]).unwrap()]) + .sign_with_keys(&f.owner) + .unwrap(); + f.db.insert_event(f.community, &anchor, Some(f.a)) + .await + .unwrap(); + let root = || vec![vec!["root".to_string(), anchor.id.to_hex()]]; + let create = f.revision(d, "create", f.a, None, &f.owner, root()); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Accepted(_) + )); + // Later loss of the anchor does not block edits that keep it. + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(f.community.as_uuid()) + .bind(anchor.id.as_bytes().as_slice()) + .execute(&f.db.pool) + .await + .unwrap(); + let update = f.revision(d, "update", f.a, Some(&create), &f.peer, root()); + assert!(matches!( + f.accept(&update, None).await, + ArtifactOutcome::Accepted(_) + )); + let bad_delete = f.revision(d, "delete", f.a, Some(&update), &f.owner, vec![]); + assert!(matches!( + f.accept(&bad_delete, None).await, + ArtifactOutcome::Rejected(_) + )); + let other = Fixture::new().await; + assert!(!other + .db + .artifact_accepted(other.community, create.id.as_bytes()) + .await + .unwrap()); + let same_id = other.revision(d, "create", other.a, None, &other.owner, vec![]); + assert!(matches!( + other.accept(&same_id, None).await, + ArtifactOutcome::Accepted(_) + )); + assert_eq!( + other + .count( + &other.owner, + serde_json::json!({"artifact":"history","#d":[d]}) + ) + .await, + 1 + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn concurrent_artifacts_on_ttl_channel_commit() { + let f = Fixture::new().await; + sqlx::query("UPDATE channels SET ttl_seconds=60 WHERE community_id=$1 AND id=$2") + .bind(f.community.as_uuid()) + .bind(f.a) + .execute(&f.db.pool) + .await + .unwrap(); + let a = f.revision(Uuid::new_v4(), "create", f.a, None, &f.owner, vec![]); + let b = f.revision(Uuid::new_v4(), "create", f.a, None, &f.peer, vec![]); + let (a, b) = tokio::join!(f.accept(&a, None), f.accept(&b, None)); + assert!(matches!(a, ArtifactOutcome::Accepted(_))); + assert!(matches!(b, ArtifactOutcome::Accepted(_))); + let live: bool = sqlx::query_scalar( + "SELECT ttl_deadline>now() FROM channels WHERE community_id=$1 AND id=$2", + ) + .bind(f.community.as_uuid()) + .bind(f.a) + .fetch_one(&f.db.pool) + .await + .unwrap(); + assert!(live); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn quiescing_community_rejects_artifact_at_admission_before_coordinate_lock() { + let f = Fixture::new().await; + let d = Uuid::new_v4(); + let create = f.revision(d, "create", f.a, None, &f.owner, vec![]); + let env = artifact::validate(&create).unwrap(); + crate::test_support::quiesce_community_for_tests(&f.db.pool, f.community).await; + + // Hold the artifact coordinate lock. Admission must reject before + // `accept_artifact` reaches it, so the write cannot queue behind it. + let mut holder = f.db.pool.begin().await.unwrap(); + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))") + .bind(format!("artifact:{}:{}", f.community.as_uuid(), env.id)) + .execute(&mut *holder) + .await + .unwrap(); + let error = tokio::time::timeout( + std::time::Duration::from_secs(5), + f.db.accept_artifact(f.community, &create, &env, None, &f.relay), + ) + .await + .expect("admission must reject before waiting on the coordinate lock") + .expect_err("a quiescing community must reject artifact writes"); + holder.rollback().await.unwrap(); + assert!( + crate::test_support::is_admission_rejection(&error), + "expected entry admission rejection, got: {error:#}" + ); + + let persisted: (i64, i64) = sqlx::query_as( + "SELECT (SELECT count(*) FROM events WHERE community_id=$1 AND id=$2), \ + (SELECT count(*) FROM artifact_heads WHERE community_id=$1 AND artifact_id=$3)", + ) + .bind(f.community.as_uuid()) + .bind(create.id.as_bytes().as_slice()) + .bind(env.id) + .fetch_one(&f.db.pool) + .await + .unwrap(); + assert_eq!( + persisted, + (0, 0), + "a rejected artifact must persist nothing" + ); +} + +/// A non-create revision whose head lives outside the channel the caller +/// authorized answers exactly like a missing artifact, before the revision, +/// type, deleted and root checks could describe the head. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn head_outside_authorized_channel_matches_missing_head() { + let f = Fixture::new().await; + let d = Uuid::new_v4(); + let create = f.revision(d, "create", f.a, None, &f.owner, vec![]); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Accepted(_) + )); + let gone = Uuid::new_v4(); + let deleted_d = Uuid::new_v4(); + let deleted_create = f.revision(deleted_d, "create", f.a, None, &f.owner, vec![]); + assert!(matches!( + f.accept(&deleted_create, None).await, + ArtifactOutcome::Accepted(_) + )); + let deleted = f.revision( + deleted_d, + "delete", + f.a, + Some(&deleted_create), + &f.owner, + vec![], + ); + assert!(matches!( + f.accept(&deleted, None).await, + ArtifactOutcome::Accepted(_) + )); + let retyped = { + let mut tags: Vec> = vec![ + vec!["ar".into(), "1".into()], + vec!["d".into(), d.to_string()], + vec!["h".into(), f.b.to_string()], + vec!["type".into(), "buzz.note".into()], + vec!["op".into(), "update".into()], + vec!["title".into(), "Test".into()], + ]; + tags.push(vec!["prev".into(), create.id.to_hex()]); + EventBuilder::new(Kind::Custom(45010), "secret") + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .sign_with_keys(&f.peer) + .unwrap() + }; + let cases = [ + ( + "missing", + f.revision(gone, "update", f.b, Some(&create), &f.peer, vec![]), + None, + ), + ( + "current prev", + f.revision(d, "update", f.b, Some(&create), &f.peer, vec![]), + None, + ), + ( + "stale prev", + f.revision(d, "update", f.b, Some(&deleted), &f.peer, vec![]), + None, + ), + ("other type", retyped, None), + ( + "delete", + f.revision(d, "delete", f.b, Some(&create), &f.peer, vec![]), + None, + ), + ( + "restore deleted", + f.revision(deleted_d, "restore", f.b, Some(&deleted), &f.peer, vec![]), + None, + ), + ( + "update deleted", + f.revision(deleted_d, "update", f.b, Some(&deleted), &f.peer, vec![]), + None, + ), + ( + "move from unauthorized source", + f.revision(d, "move", f.b, Some(&create), &f.peer, vec![]), + Some(f.b), + ), + ]; + for (case, event, source) in cases { + match f.accept(&event, source).await { + ArtifactOutcome::Conflict(reason) => { + assert_eq!(reason, super::artifact::HEAD_UNAVAILABLE, "{case}") + } + other => panic!("{case}: {other:?}"), + } + } + // Positive control: the same revision homed where the head lives. + let update = f.revision(d, "update", f.a, Some(&create), &f.peer, vec![]); + assert!(matches!( + f.accept(&update, None).await, + ArtifactOutcome::Accepted(_) + )); +} diff --git a/crates/buzz-db/src/store/artifact_query.rs b/crates/buzz-db/src/store/artifact_query.rs new file mode 100644 index 00000000000..fcc46695759 --- /dev/null +++ b/crates/buzz-db/src/store/artifact_query.rs @@ -0,0 +1,90 @@ +//! Permission-scoped NIP-AR queries. Predicates precede pagination and counts. +use crate::{Db, Result}; +use buzz_core::{ + artifact::{ArtifactQuery, ArtifactView}, + CommunityId, StoredEvent, +}; +use sqlx::QueryBuilder; + +impl Db { + /// Execute a bounded query against current artifacts or revision history. + /// Permission is resolved in the query snapshot. + pub async fn query_artifacts( + &self, + community: CommunityId, + reader: &[u8], + query: &ArtifactQuery, + count: bool, + ) -> Result<(Vec, i64)> { + // Read-only: a plain writer-pool snapshot transaction, labeled as the + // history read it is, so it neither takes community admission nor + // counts as an event write. + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::SubscriptionHistory, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(&mut *tx) + .await?; + let mut qb = QueryBuilder::::new(if count { + "SELECT count(*) AS count FROM events e " + } else { + "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id FROM events e " + }); + if query.view == ArtifactView::Current { + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND NOT a.deleted "); + } + // A system channel is read only by a query whose `#h` names it + // (NIP-CL); malformed `#h` values name no channel. + let named_channels: Vec = query + .tags + .iter() + .filter(|(name, _)| name == "h") + .flat_map(|(_, values)| values.iter().filter_map(|value| value.parse().ok())) + .collect(); + // The explicit kind lets the community/kind index exclude chat before + // the join, even for an unfiltered current-state page. + qb.push("WHERE e.community_id=").push_bind(community.as_uuid()).push(" AND e.kind=45010 AND e.deleted_at IS NULL AND EXISTS (SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id AND c.deleted_at IS NULL AND (c.channel_type<>'system' OR c.id=ANY(") + .push_bind(named_channels) + .push(")) AND (c.visibility='open' OR EXISTS (SELECT 1 FROM channel_members m WHERE m.community_id=c.community_id AND m.channel_id=c.id AND m.pubkey=") + .push_bind(reader.to_vec()).push(" AND m.removed_at IS NULL)))"); + for (name, values) in &query.tags { + // GIN-usable necessary prefilter; retain the positional recheck + // because JSON array containment alone also matches swapped values. + qb.push(" AND ("); + for (index, value) in values.iter().enumerate() { + if index != 0 { + qb.push(" OR "); + } + qb.push("e.tags @> ") + .push_bind(serde_json::json!([[name, value]])); + } + qb.push(")"); + qb.push(" AND EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) tag WHERE tag->>0=") + .push_bind(name) + .push(" AND tag->>1=ANY(") + .push_bind(values) + .push("))"); + } + if count { + let n: i64 = qb.build_query_scalar().fetch_one(&mut *tx).await?; + tx.commit().await?; + return Ok((vec![], n)); + } + qb.push(" ORDER BY e.received_at DESC,e.id ASC LIMIT ") + .push_bind(query.limit) + .push(" OFFSET ") + .push_bind(query.offset); + let rows = qb.build().fetch_all(&mut *tx).await?; + let mut events = vec![]; + for row in rows { + if let Some(event) = crate::event::row_to_stored_event(row)? { + events.push(event); + } + } + tx.commit().await?; + Ok((events, 0)) + } +} diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index a93ffb36c6a..cf8d15094ed 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -26,7 +26,7 @@ pub use crate::channel_members::{ get_users_bulk, is_member, list_large_channel_rosters_needing_reconciliation, lock_member_snapshot, membership_pairs, remove_member, verify_channel_roster_fence_behavior, verify_channel_roster_fence_catalog, AccessibleChannel, BotChannelEntry, BotMemberRecord, - LargeChannelRoster, LockedMemberSnapshot, MemberRecord, UserRecord, + ChannelIdentity, LargeChannelRoster, LockedMemberSnapshot, MemberRecord, UserRecord, }; /// A channel row as returned from the database. @@ -76,6 +76,19 @@ pub struct ChannelRecord { pub ttl_seconds: Option, /// Deadline by which a new message must arrive or the channel is auto-archived. pub ttl_deadline: Option>, + /// Labels published as `["t",