mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
3bd121bc158698a2acf9f3c0d9650b5d03fcbf72
3541 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3bd121bc15 |
Check product_feedback's community in the writing transaction (#9608)
## Summary Third app-side step of retiring the database foreign keys (after #9399 and #9404). After this, every reference the drop migrations will remove is checked in application code. - **`product_feedback -> communities`:** `product_feedback::insert` now runs in a transaction. It locks the community row `FOR KEY SHARE` and returns `NotFound` when the row is missing. This is the same guarantee the foreign key gives. Any lifecycle state still qualifies. `docs/database.md` says provenance-only tables stay writable while their community is being deleted, and the purge clears their provenance. - **Reader tolerance:** `ProductFeedbackRecord.community_id` is now `Option<Uuid>`. The purge sets `community_id = NULL`, and `list` (used by `buzz-admin list-product-feedback`) failed to decode those rows. The JSON output shows `null` for them. - **One home for reference checks:** `require_workflow` and `require_workflow_run` move from `store/workflow.rs` into `store/reference_check.rs`. The workflow owner and channel checks now reuse `require_user` and `require_optional_channel`, so two duplicate helpers are gone. A new `require_community` joins them. - **Stale comments:** comments that justified behavior by the foreign keys now say what holds both before and after the drop. Touched: the purge order (`deletion.rs`), `command_executor.rs`'s `ensure_user`, the `set_agent_owner` doc, the NIP-43 snapshot lock note (`relay_members.rs`), `attach_scheduled_workflow_run`, and one workflow deletion test. ## Writers and readers checked (RPR #2) `product_feedback.community_id` writers: - `store/product_feedback.rs` `insert`: the only insert. It is now checked. - `store/deletion.rs` `purge_postgres`: sets the column to `NULL`. No check is needed. - `store/relay_admin_actions.rs` status update: does not touch `community_id`. Readers: - `product_feedback::list`: fixed to accept `NULL`. - `store/admin_moderation.rs` inbox queries: already `LEFT JOIN` and accept `NULL`. ## Tests All three tests drop `product_feedback -> communities` in the per-test database first, so a pass proves the application check and not the constraint. - `insert_rejects_missing_community_without_foreign_key`: a community that never existed gets `NotFound` and no row. A fenced community still accepts feedback. An active one accepts it, and a replay returns the same row. - `insert_key_share_locks_community_without_foreign_key`: an insert waits while another transaction holds the community `FOR UPDATE`, then proceeds. - `list_returns_rows_with_cleared_provenance`: a row with `community_id = NULL` is listed with `community_id: None`. ## Not in this PR - The foreign key drop migrations. They come after this PR is deployed (`docs/database.md` expand/contract). - Nothing in the database stops `DELETE FROM communities` on an active community once the community foreign keys are gone. The tombstone trigger rejects it only for inactive communities. Production never hard-deletes communities. This is decided with the drop migrations, since a trigger change conflicts with the no-new-triggers rule. ## What got simpler All in-transaction reference checks now live in one module. Two duplicate helpers were removed. `store/workflow.rs` loses about 80 lines. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
0a05330740 |
buzz-db: stop calling the dropped lock-key function in SQL (#9615)
## Summary Main's user content cleanup still calls the SQL function `community_deletion_lock_key`. Migration `0094` (#9598) drops it. On any database at `0094`, every user-deletion content batch fails with `42883 function community_deletion_lock_key(uuid) does not exist`. #9363 added this caller after #9396 moved the key to Rust. This PR binds the Rust-built key with `hashtextextended($1, 0)`, as every other caller does. - `content_batches/execute.rs`: the batch's exclusive advisory lock uses the Rust key. - `content_batches/safety_postgres_tests.rs`: the test blocker takes the same lock the same way. - `docs/trigger-retirement-deployment.md`: builds from #9363 up to this PR are not valid stops before `0094`. Rebased onto main `e894d75d`. The renumber and the `update_channel` test-call fixes this PR first carried are already on main through #9616, so they are gone from this PR. Deployed relays are unaffected: the deployed build predates #9363. ## Tests The 17 `user_deletion::content_batches` PostgreSQL tests fail on main at `0094` with the error above. This PR makes them pass. ## What got simpler One fewer SQL-side copy of the lock key. Every caller now builds the key in Rust. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>mobile-v1.5.0-rc.2 |
||
|
|
8fb0de8d53 |
Clean up account records and refresh member lists (#9364)
## Summary Add bounded, resumable cleanup for a user’s account records and their current direct agents in each selected community. Preview prints the proposed changes without writing; deletion uses the same selectors through the command and workflow handler. Each run and retry discovers agent ownership again. An agent owned by Alice in one community and Bob in another is cleaned only in Alice’s community. Ownership changes stop the current run, and ownership rows remain available for retries and later handlers. Membership removal rebuilds and signs the current channel lists and community roster in the same transaction as each removal. A failed roster write rolls back that membership removal. The command requires the existing relay signing key when channel or community memberships are present, including users with no channel memberships. Preview does not require a key. The relay, account cleanup and admin reconciliation share the kind 39001/39002 tag builders in `buzz-db`. They preserve the existing identity tags, roster order and role positions. Regular unit-test runs now include `buzz-deletion` through both nextest and the Cargo fallback. **Channel ownership policy:** deletion may remove the last channel owner, including when the human and their agents are all owners. The channel, messages and surviving members remain. A surviving admin can manage the channel and grant ownership. If no owner or admin remains, members can continue normal use, but management recovery requires operator intervention on request. Cleanup does not require a channel ownership handoff or assign a replacement owner. The separate community-owner restriction remains. The content handler now on main advances to account cleanup before the remaining agent stage. Content and account workflow progress goes to stderr so stdout remains one JSON inspection document. The direct account command retains NDJSON stdout. Nullable attribution updates use explicit table and SET clauses so the source-policy guard can inspect them. The handler covers credentials, memberships, read progress, supported personal events and their copies, feedback, and explicit global listener/database-role cleanup. It retains shared records and historical signed lists. Scope files select the human and communities; saved agent keys do not authorize deletion. This remains an offline operator feature: stop relay and external writers before deletion. It does not revoke already-connected sessions. Coordinator integration, remaining handlers and final erasure verification are separate; results always report `account_erasure_complete: false`. The real account workflow still stops at an unimplemented successor. ### Related issue Replaces the account scope of #9354 and #9355 with one focused PR. Those earlier PRs remain intact for reference. Agent cleanup belongs within the business handlers; this change does not integrate the historical standalone agent stage in #8959. ### Testing Exercised the real preview and delete commands in an isolated local relay/database with Alice disconnected and Bob’s desktop app open. Preview left the normalized database dump unchanged. Deletion checks covered all 101 tables and all 30 affected channels; 168 newly signed list events verified. Bob refreshed the member dialog and saw Bob, B1 and Carol, then successfully sent and read a message. A1’s membership in the community where Bob owns it remained intact. The live CLI and desktop evidence above predates the latest follow-up. Independent end-to-end checks at `d45759df2` also verified unchanged preview data, signed channel/community lists after deletion, signing-key preflight, and workflow JSON stdout. The shared-builder follow-up was source-reviewed and formatted; local builds, tests and commit/push hooks were skipped at the author’s request. Validation of the new revision and a repeat of the signed-list end-to-end check are pending. Human testing remains pending. For human verification, use an isolated database and its relay signing key. Preview a community-only member, confirm no writes, then delete and verify the current kind 13534 roster omits them. Run an approved account-stage fixture with `user-deletions run <id> --delete --next-step`; the entire stdout must parse as one JSON document, with batch progress on stderr. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Signed-off-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
a26eacde49 |
perf(mobile): save own thread interest once per unread catch-up (#9614)
iOS was killing the app with watchdog terminations (`0x8BADF00D`, "scene-update watchdog transgression" and "Failed to terminate gracefully") because the main thread spent 5 to 10 seconds in unread catch-up. Symbolicated reports from a 1.4.0-rc.1 user all point at the same stack: `UnreadCatchUp._catchUpUnreadEvents` → `ChannelsNotifier._writeThreadInterestStores` → `jsonEncode` / `SharedPreferences.setString`. For every self-authored event in a catch-up batch whose thread was new to the interest sets, the notifier re-encoded **both** whole root-id sets and wrote both to SharedPreferences. That is quadratic in the batch: a fresh sign-in, whose catch-up returns many of the user's own messages, ran thousands of growing encodes and platform-channel writes on the main thread. Now the catch-up adds the whole batch to the in-memory sets and saves once if anything changed. The live single-event path is unchanged (one write per new thread). ### Regressions None expected. The persisted keys, format and contents are identical; only the number of intermediate writes changes. The storage contract is unchanged: saves were and still are fire-and-forget `setString` calls, so neither version guarantees durability before a process kill. A kill before the save lands now loses the whole batch rather than a prefix of it; a later catch-up can re-add those threads only while they are still after the channel's read timestamp and within the catch-up window. ### Validation - **Writes per catch-up**, 50 own messages across 50 threads: 50 writes per key before, 1 after (new test). - Added test: `unread catch-up saves own thread interest once per batch` (channels_provider_thread_interest_cases.dart). It checks the saved sets and the write count; it fails on the old code. - Full mobile check and test suite pass. - Automated full-app run on an iOS simulator (PR head build, signed in to a real community): cold launch and unread catch-up saved both thread-interest sets; background and foreground; Activity rows and unread dots render; opened a thread and sent a reply, and the participation set grew by one (live path still saves). No errors in the app log. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
e894d75d26 |
buzz-db: fix main (renumber the function drop to 0094, update_channel test call) (#9616)
## Summary Main has two migrations numbered `0093`: - `0093_push_gateway_installation_platform.sql` from #9560 - `0093_drop_plain_sql_functions.sql` from #9598 The file names differ, so GitHub showed no conflict between the PRs. sqlx applies the first version-93 migration and then rejects the second as a changed migration 93. Every migrate run on main fails, including relay startup with auto-migration on. This PR moves #9598's migration to `0094`: - `git mv migrations/0093_drop_plain_sql_functions.sql migrations/0094_drop_plain_sql_functions.sql`. The SQL is unchanged. - `embedded_migrator_contains_consolidated_initial_schema` now expects 94 migrations, with the function drop at version 94. - The Postgres test is renamed to `migration_0094_drops_plain_sql_functions`. It finds the migration by description, so its logic is unchanged. - `docs/trigger-retirement-deployment.md` now names `0094`. #9560's `0093` keeps its number. It reached main first and may already be applied on deployments that auto-migrate. ## Second break on main: `update_channel` call sites Main's buzz-db lib tests also stopped compiling. #9581 added a `sender` argument to `update_channel`, and #8320's cross-community test (`deletion.rs`) landed in parallel with the old three-argument call. This PR passes the channel creator as the sender. The test only renames an open channel, so the private-to-open rule does not apply. ## Deployments No deployment has applied #9598's `0093`: no image built from main after #9598 has rolled out yet. A database that applied #9560's `0093` applies `0094` next. Do not promote any image built from `4e8f8365` (the #9598 merge) or later until this PR merges. ## What got simpler Nothing. This is a renumber and a test call fix only. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f158fdd9a1 |
feat(relay): name the agent whose add policy refuses a DM (#9601)
## Problem When an agent's add policy refuses a DM open or add (from #9125), the refusal says only that an agent refused. The person can't tell which agent blocked it, so they don't know whose owner to ask. ## Change The DM refusal now ends with `(agent <hex pubkey>)` for the first agent refused, in the order the request named them. For example: `forbidden: policy:owner_only — only the agent owner can add this agent (agent 3f9a…)` The prefix is unchanged, so existing clients that match on `policy:owner_only` or `policy:nobody` keep working. Desktop and mobile follow-ups will show the agent's name. ## Tests - `adding_an_agent_follows_its_add_policy` asserts the full refusal including the agent. - `opening_with_several_agents_follows_their_add_policy` adds a second refusing agent and checks the first one named is reported. - DM Postgres tests: 297/297 passed. Clippy is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4e8f836576 |
buzz-db: drop the community_deletion_lock_key and profile_name_fields functions (contract) (#9598)
## Summary Phase 2 of retiring the two remaining plain SQL functions. Phase 1 moved their work into the relay: - #9396 builds the community deletion lock key in Rust (`deletion::community_deletion_lock_key`, locked with `hashtextextended($1, 0)`). - #9397 reads profile names with inline SQL (`PROFILE_NAME_FIELDS` in `buzz-search`). No relay at or after #9397's merge (`279a31da`) calls either function. This PR drops them: - **Migration 0093** runs `DROP FUNCTION community_deletion_lock_key(UUID)` and `DROP FUNCTION profile_name_fields(TEXT)` under a 5s `lock_timeout`, with no `IF EXISTS` and no `CASCADE`. If anything still depends on a function, the migration fails instead. Migrations 0029 and 0064 stay frozen. No database function calls either one any more: 0090 dropped the fence functions, which were the only SQL callers of the lock key. - **Desired state:** removes both `schema/functions/` files and their `schema.sql` includes. Both boot paths stay catalog-equivalent (`admin_schema_parity_between_desired_state_and_migrations`). - **Tests:** - New `migration_0093_drops_plain_sql_functions`. It migrates to 0092, checks that both functions exist and that serving and deletion catalog validation pass, then runs 0093 and checks that both functions are gone and that validation still passes. This covers new code on either side of the drop. - The migration listing test pins 0093's statements and that it has no `CASCADE`. - `desired_state_catalog_has_no_universal_fence_and_still_boots` now asserts that both functions are absent. - Replaces the Rust-vs-SQL lock key parity test with `community_deletion_lock_key_bytes_are_fixed`, a unit test that maps fixed UUIDs (nil, max, and one with hex letters) to their exact keys. Older replicas and the repair-script key in `docs/database.md` build the same string, so a changed prefix or UUID format must fail a test. - Removes two relay test-schema wrappers (`bridge.rs`, `ingest.rs`) that forwarded `community_deletion_lock_key` to `public`. Writers no longer call it, and the wrapper's `CREATE FUNCTION` would fail once the function is gone. - **Docs:** `docs/trigger-retirement-deployment.md` gets a `0093` section with the required stop. ## Deploy gate **Required stop:** any relay build at or after `279a31da` (#9397's merge, which follows #9396). `relay-v0.3.0` does not contain it. A relay older than that which still serves after 0093 fails every write and deletion that takes the community deletion lock, with `42883 community_deletion_lock_key(uuid) does not exist`, and its profile name search fails with `42883 profile_name_fields(text) does not exist`. 0093 takes no table locks and needs no cleanup. Migration number: #8696 and #9398 also propose `0093`. Whichever lands second renumbers. ## Review-Proven Rules - **RPR #2 (every path):** I checked every reference on `main` and at the stop build `279a31da`. At both, only test code reads either function: no boot, readiness, catalog or runtime query depends on them. Serving and deletion catalog validation pass before and after 0093, in the new test. - **RPR #3 (falsifiable):** removing the `profile_name_fields` drop from 0093 turns `migration_0093_drops_plain_sql_functions` red. - **RPR #3 (lock key bytes):** a changed prefix, `.simple()` UUID formatting, or uppercase formatting each turns `community_deletion_lock_key_bytes_are_fixed` red. ## What got simpler Two database functions, their desired-state files, a cross-language parity test and two test-only SQL wrappers are gone. After this PR, the only functions left in `schema/functions/` are trigger functions. ## Validation Blox gate at `95ac71c8`: - `cargo fmt --all --check`, and `cargo clippy -p buzz-db -p buzz-relay --all-targets -D warnings`. - `buzz-db --lib` unit tests: 216/216, including the migration listing test. - `buzz-db` Postgres tests (`migration::`, `deletion::`, `nip_fi_binding::` postgres_tests): 130/130. These include `migration_0093_drops_plain_sql_functions`, `admin_schema_parity_between_desired_state_and_migrations` and `deletion_surface_parity_between_migration_0029_and_schema_sql`. - `buzz-search` `profile_names*` Postgres tests: 4/4, on a fully migrated database where `profile_name_fields` no longer exists. - The two relay tests whose test-schema wrapper this PR removes: 2/2. - Must-fail check: with the `profile_name_fields` drop removed from 0093, `migration_0093_drops_plain_sql_functions` fails. Second Blox gate at `e1b5513a` (the lock key vector test): - `cargo fmt --all --check`, and `cargo clippy -p buzz-db --all-targets -D warnings`. - `buzz-db --lib` unit tests: 217/217. - Must-fail checks: a changed prefix, `.simple()` and uppercase UUID formatting each fail `community_deletion_lock_key_bytes_are_fixed`. The first gate run found that `deletion_surface_parity_between_migration_0029_and_schema_sql` still expected `community_deletion_lock_key` in `schema.sql`. The second commit fixes that. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
66b463fb2f |
fix(deps): clear chrono, humantime and zip advisories from the dependency policy (#9609)
## Summary main's `Security` check (`cargo-deny check`) fails on six new advisories: - RUSTSEC-2026-0545, 0546, 0547, 0548: zip 8.6.0 (fix in zip >= 9.0.5). - RUSTSEC-2026-0543: chrono is unmaintained. - RUSTSEC-2026-0542: humantime is unmaintained (it wraps chrono). This PR adds ignore entries with reasons. It changes only `deny.toml`. ## Why ignore and not upgrade **zip.** zip 8 reaches the graph only through the examples-only `buzz-mesh-smoke` crate, via mesh-llm v0.76.2. mesh-llm builds zip with only the `deflate` feature. It reads archives through `ZipArchive` and copies entries by hand. It never calls `extract`, never decrypts AES entries (`aes-crypto` is off), never enables `legacy-zip`, and never uses `ZipStreamReader`. None of the affected code paths run. mesh-llm v0.79.0 ships zip 9.0.5. But that release removes the `client` feature of `mesh-llm-sdk`, which `buzz-mesh-smoke` and desktop use. A bump needs an SDK migration in both places. That is out of scope for a red-main fix. The new IDs join the existing zip block. Its note said the fix was in "unreleased mesh-llm#2471". That is stale, so the note now names the release and the migration it needs. **chrono / humantime.** Both are unmaintained, not vulnerable. Neither has a maintained release. chrono is a direct workspace dependency of most crates. humantime comes only through `buzz-mesh-smoke` → mesh-llm → hf-xet → xet-runtime. Removing them needs a migration to `time` or `jiff`. ## What got simpler Nothing could. The new ignores are the smallest change that makes the check pass. Identified debt: - The mesh-llm SDK migration to v0.79+ would delete all eight zip ignores. - A chrono → `time`/`jiff` migration would delete both unmaintained ignores. ## Test plan - [x] `cargo-deny check` at this tree: `advisories ok, bans ok, licenses ok, sources ok` (exit 0). - [x] `git diff --check` clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>mobile-v1.5.0-rc.1 |
||
|
|
026b203c64 |
docs: define mobile diagnostic reporting (#9600)
## Summary Records the vocabulary, the two hard-to-reverse decisions and the spec for diagnostic reporting in the mobile app, before any code is written. Nothing here changes behavior. - `CONTEXT.md`: two new terms. **Diagnostic reporting** is sending crash, error and performance data from a mobile installation to a reporting destination. A **reporting destination** is where a build sends it, chosen at build time by whoever distributes the build. - [ADR 0007](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0007-diagnostic-reporting-follows-the-destination.md): a build reports if, and only if, it was given a reporting destination, whatever kind of build it is. It also lists what a report may and may never carry. - [ADR 0008](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0008-sentry-for-mobile-diagnostic-reporting.md): the app reports through the Sentry Flutter SDK, with the comparison against Datadog and Bugsnag. - [`docs/mobile-diagnostic-reporting.md`](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/mobile-diagnostic-reporting.md): the spec for step one. It covers crashes, uncaught errors, error reports for unexpected protocol and decoding failures, and networking measurements by backend and endpoint, all through one reporting module. It sits beside the existing mobile push suppression spec. The term avoids "telemetry" because the repository already uses that word for agent session streams and relay rollout signals. ### Related issue N/A. The Swift Package Manager move that ADR 0008 depends on is #9597. ### Regressions Documentation only. No code, configuration or build changes. ### Validation Checked that every link in the four files resolves within the branch, and that the new glossary anchors match the links that point to them. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> |
||
|
|
148585c804 |
build(mobile): link iOS plugins through Swift Package Manager (#9597)
## Summary The iOS app stops opting out of Flutter's Swift Package Manager integration. The 19 iOS plugins that ship a Swift package are now linked through it. The three that don't (`google_mlkit_commons`, `google_mlkit_selfie_segmentation` and `open_filex`) keep installing through CocoaPods, which Flutter supports side by side. Why now: - CocoaPods is winding down: its spec repo [becomes read-only on December 2, 2026](https://blog.cocoapods.org/CocoaPods-Specs-Repo/), and plugin releases have started to ship as Swift packages only. Staying opted out pins those plugins at their last CocoaPods release. - The opt-out dates from the Flutter 3.47 upgrade (#8419), which kept the existing CocoaPods integration. With it removed, the app builds and runs as before. What is in the diff: - `pubspec.yaml`: the opt-out is removed. - `project.pbxproj` and `Runner.xcscheme`: the edits Flutter's own tool makes on the first build with the integration on (a local reference to its generated plugin package, and a scheme pre-action that prepares the Flutter framework). They are committed so a build does not dirty the tree. - `Podfile.lock`: only the three CocoaPods plugins and their dependencies remain. No Dart code, plugin version or remote Swift package changes. All 19 packages resolve to local paths in the pub cache, so `Package.resolved` is untouched and builds fetch nothing new. ### Related issue N/A. No existing issue or PR for this was found. ### Regressions - **App behavior:** the same plugin code at the same versions. The 19 plugins are linked statically into the app binary instead of embedded as dynamic frameworks, which leaves fewer libraries to load at launch and a slightly smaller app (numbers below). One resource bundle is lost; see the second accepted tradeoff. - **Extensions:** the notification service extension links no plugins, so it is unchanged. - **Build and release:** CocoaPods is still required for the three remaining plugins, so the Podfile, its post-install steps and the release tooling are unchanged. The first build after this change spends about 17 extra seconds adding the integration. - **Accepted tradeoff, build warning:** Flutter now prints a warning naming the three plugins without Swift packages. It goes away when those plugins add support or are replaced. - **Accepted tradeoff, one privacy manifest dropped:** the app no longer bundles `app_badge_plus`'s privacy manifest, and Xcode prints `Invalid Resource 'Resources': File not found` for it. Version 1.2.10's Swift package looks for `Resources` under its source directory, but the manifest sits at the package root, so the Swift package bundles nothing where the podspec bundled it. This is harmless: that manifest declares only UserDefaults access, and the plugin's single source file never touches UserDefaults. The other 16 plugin privacy manifests are still in the release app. Fixing it means a plugin bump, which is left out of this PR. - **Android:** unaffected. ### Validation Unsigned release build, this branch against unmodified `main`: | | `main` | This branch | | --- | --- | --- | | App size | 87.0 MB | 85.6 MB | | Embedded frameworks | 31 | 12 | Focused existing validation: the three iOS steps CI runs (simulator debug build, the 116 native `RunnerTests`, and the unsigned release build) pass locally. Full-app run on an iOS 27 simulator (iPhone 17 Pro), driven by an agent, with the debug build from this branch installed over an existing signed-in install: - The app stayed signed in and loaded its channel list and message history (keychain, preferences and local storage plugins). - Photo library picker, attaching a photo, and sending a video, which uploaded and played back. - Image viewer, the share sheet, and saving an image to Photos. - The file picker, and the camera and microphone permission prompts. - A link in a message opened in the browser, and a `buzz://` deep link reached the app. Two failures showed up and both reproduce identically on unmodified `main` on the same simulator, so neither comes from this change: a recorded voice note is empty because the host Mac has no microphone, and saving an image adds it to Photos but then reports "Could not save image". Limits: no physical device run. Camera capture, QR scanning, selfie segmentation and biometric prompts cannot be exercised on a simulator. Voice note playback was not exercised. Human testing is waived for this PR under the author's standing policy for mobile changes; the agent-driven run above stands in for it. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> |
||
|
|
6b4a398829 |
feat(push-gateway): enroll Android installations and send FCM wakes (#9560)
## What and why Ticket 2 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now enrolls Android installations and wakes them through FCM, next to the existing iOS path. Builds on [#9557](https://github.com/block/buzz/pull/9557) (platform-neutral `/v1/deliveries` route), now merged. - **Platform.** The enrollment request has no platform field. The gateway derives it from which attestation is present (App Attest object or Android attestation chain) and records it in a new `push_gateway_installations.platform` column (`ios` or `android`). It lives only in gateway state; the relay never sees it. - **Android enrollment transcript.** Key Attestation fixes the challenge at key generation, so the client signs nothing at enrollment and sends no `key_id`. The attestation challenge must equal SHA-256 of a canonical JSON transcript under domain `buzz.push.enroll.android.v1` with `v`, `audience`, `challenge_id`, `challenge`, `endpoint`, `endpoint_epoch` and `expires_at`. The gateway derives the key id as SHA-256 of the attested 65-byte uncompressed P-256 key. A request whose `key_id` presence doesn't match its platform gets 400. The iOS transcript (`buzz.push.enroll.v1`) is unchanged. - **Signed calls.** iOS keeps App Attest assertions. After enrollment, an Android installation signs every call (delegate, revoke delegation, rotate endpoint, revoke installation) with its attested Keystore key: ECDSA P-256, DER, over the same transcript bytes iOS signs. High-S signatures are accepted since Keystore does not normalize. There is no counter; the single-use challenge inside the transcript is the replay protection. - **FCM sender.** HTTP v1, high priority, data-only, compiled-in payload (no relay-supplied bytes), one constant collapse key, TTL from the delivery expiry. OAuth access tokens come from the service account key (RS256 JWT bearer). Outcomes map onto the existing delivery outcome classes and metrics (`push_gateway_fcm_*`). - **Token refresh.** A cached token keeps serving until it expires. Once it is due for refresh, one background task fetches a new one, so a wake never waits on a refresh while a valid token exists. A failed fetch keeps the current token and backs off 5 s before the next attempt. Only a cold cache (no unexpired token) makes a wake wait on the token request, single-flighted. A 401 discards the cached token only if it is still the one FCM refused, so a late 401 can't drop a newer token. - **Retries.** 429 and `QUOTA_EXCEEDED` retry after at least 60 s (FCM's hint if longer). 500, 502, 503 and 504 retry. - **Attestation seam.** Android Key Attestation verification sits behind a trait. Tests use a test-only verifier compiled under `cfg(test)`, so production configuration cannot select it. The production verifier fails closed: a gateway configured for Android starts but rejects every Android enrollment until ticket 3. - **Migration.** Expand-only `ADD COLUMN platform TEXT NOT NULL DEFAULT 'ios' CHECK (...)`: the deployed gateway's inserts stay valid and existing rows become iOS. `SET LOCAL lock_timeout` (5 s) and `statement_timeout` (30 s) bound the table lock wait and the CHECK validation scan. No triggers, functions, foreign keys or backfills. Mirrored as gateway `0007` and relay `0093` plus `schema/tables/public`, per docs/database.md. ## Configuration All four are optional and must be supplied together (a partial set fails startup). Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only. - `BUZZ_PUSH_ANDROID_PACKAGE_NAME` - `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS` - `BUZZ_PUSH_FCM_PROJECT_ID` - `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` ## Tests - `cargo test -p buzz-push-gateway` (92 passed, 18 ignored; 94 passed with `personal-dev-app-attest`; iOS rows unchanged), `cargo fmt --check`, `cargo clippy -p buzz-push-gateway -p buzz-db --all-targets -- -D warnings`. - New HTTP tests with a fake FCM sender: Android enroll, delegate, deliver, rotate endpoint and revoke; signed-call rows for wrong key, altered transcript and reused challenge; platform derivation and bad attestations. - Postgres (ignored, run locally): gateway migration test (existing and old-gateway inserts become `ios`, bad value rejected); relay `admin_schema_parity_between_desired_state_and_migrations` now covers `push_gateway_installations` columns, indexes and constraints; the `runtime::migration::postgres_tests` set passes single-threaded. - Break check: making signature verification always succeed turned two tests red (the signed-call rejection rows and the signature unit test); restored. - Token cache tests against a local fake token endpoint with a controlled clock: a due refresh keeps serving the valid token even when it fails; a late 401 does not discard a refreshed token; a queued background refresh honors a foreground failure's backoff. The FCM response table covers 429 with and without an error body, and 502/504 HTML pages. - Android enrollment rows: `key_id` present on Android (400), wrong transcript binding, a 65-byte non-point key, an over-long chain, and exact replay. - Break checks for every new guard (no background refresh, blocking while due, failure dropping the token, unconditional 401 clear, no quota floor, no 502/504 retry, the queued-refresh backoff check, Android requiring `key_id`, skipping the P-256 point check): each turned at least one test red; restored. ## Not here (ticket 3) Real Key Attestation verification (Google roots, revocation list, boot state, boot-key list, app identity). Per-key rate limiting is also left for ticket 3, since it did not fall out of this change. The Helm chart does not pass the Android settings yet. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
ff652ed06c |
perf(mobile): cache and animate custom emoji in the iOS picker (#9479)
The iOS emoji picker's custom emoji downloaded again every time the
picker opened, and animated emoji showed only their first frame.
Now each custom emoji downloads once per install and plays its
animation:
- The native picker gets image bytes from Flutter through the same path
as the rest of the app's images: the in-memory custom emoji cache, then
the persistent media disk cache, then one download through the shared
media HTTP client. Relay media is cached as immutable.
- Swift decodes every frame (no Swift-side cache) and shows the image in
a `UIImageView`, since SwiftUI `Image` draws only the first frame of an
animated `UIImage`. With Reduce Motion on, it shows the first frame,
following the setting live.
- At most four picker downloads run at once, and an emoji scrolled off
screen before its turn never starts. Emoji already saved on disk skip
the queue, so reopening a large set stays instant.
- A picker load joins any download of the same image already in flight
elsewhere in the app. A saved copy that fails to decode is evicted and
downloaded again, and only bytes that decoded are kept in memory.
- Swift decodes at most four emoji at once, including ones from cached
bytes. An emoji whose cell scrolls away gives up its place and stops
decoding between frames, and a cell that leaves the screen keeps only
its first frame.
- Each animation frame keeps its own delay. UIKit spaces animated frames
evenly, so a frame repeats for its share of the loop, and a GIF that
holds its last frame for 3 s still does.
### Why it refetched
The native picker loaded images itself with `URLSession.shared` and an
`NSCache` keyed on the whole request. Every request carried a freshly
signed media auth header, so the key never matched and nothing was
cached on disk.
### Validation
Relay media downloads for the 48 custom emoji matching "nod" (local
relay, iPhone 17 Pro simulator):
| Step | main | this PR |
| --- | --- | --- |
| First open | 48 | 48 |
| Leave and re-enter the channel, reopen | 48 | 0 |
| Relaunch the app, reopen | 48 | 0 |
| Reinstall the app, reopen | not measured | 0 |
Before (main): every reopen downloads again, and animated emoji are
still.
https://github.com/user-attachments/assets/7a43dd6a-61e0-495d-abed-6c11f7d4f965
After (this PR): reopening shows cached emoji immediately, and animated
emoji play.
https://github.com/user-attachments/assets/bf45a5c0-77ef-4501-8843-6f42e15de389
Automated app run: signed in to a local relay, opened a channel,
long-pressed a message, opened the full picker, searched, closed, left
and re-entered the channel, reopened, relaunched and reopened. Repeated
on the final head (
|
||
|
|
1059d81fc2 |
fix(ios): end each bold or strikethrough run at its first closing marker (#9559)
Bold and strikethrough runs in iOS push notification bodies now end at their first closing marker, so a message with two bold runs on one line shows both without their markers. Before, the run's optional group was greedy and stretched to the last marker on the line: | Message | Before | After | | --- | --- | --- | | `option **A** or option **B**` | `option A** or option **B` | `option A or option B` | | `~~x~~ and ~~y~~` | `x~~ and ~~y` | `x and y` | | `**😀** and **b**` | `😀** and **b` | `😀 and b` | The fix makes that group lazy (`(?:.*?\S)??`). Found while reviewing the Dart port in [#9556 Dart notification body](https://github.com/block/buzz/pull/9556), which must match these fixtures. That PR takes the same pattern once this one lands. ### Validation - Added tests: three shared rows in `test-fixtures/notification-body.json`, one per row above. All three fail with the old pattern. - All 70 BuzzPushKit tests pass on macOS, including the other 36 fixture rows, which are unchanged. ### Regressions None expected. The pattern still needs non-space characters right inside both markers and still stays on one line. It now stops at the first closing marker where before it reached for the last one. The output changes only where a one-character run is followed by the same marker later on the line, for example `**a** costs 2**3`, which was `a** costs 23` and is now `a costs 2**3`. Worst-case time for unclosed markers is unchanged (measured during review of the Dart port). Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
50cfc54337 |
Apply the private-to-open rule in update_channel too (#9581)
## Summary - Follow-up to https://github.com/block/buzz/pull/9307, which made the relay refuse to open a private channel that has, or once had, any member other than the sender and the sender's own agents. That rule lived only in the channel metadata edit path (kind:9002). The store's other channel-settings function, `update_channel`, could still open such a channel. - Now both paths apply the same rule, because it runs in the one function that writes channel settings for both. `update_channel` takes the authenticated sender so it can decide the rule. Today only tests call `update_channel`, so nothing user-visible changes; the gap is closed before any real caller arrives. - The user-deletion executor doc now says what the rule needs from a purge: if a purge keeps any of a user's messages in a channel, it must also keep that user's membership row there, marked removed. The relay finds former members only through those rows, so dropping the row would let the channel be opened and its history, those messages included, be made public. ## Details - The check moved out of `apply_channel_metadata_event` into `update_channel_on`, which both paths call. It still runs under the membership lock that a visibility change takes, so members cannot be added between the check and the commit. - One ordering change: a single kind:9002 that opens a private channel with other members, archives it and sets `auto_join` to true now gets the `auto_join` refusal instead of the private-to-open one, because the `auto_join` check now runs first. Both refuse, and nothing is stored either way. - This PR also carries doc-comment wording that was reviewed on https://github.com/block/buzz/pull/9307 but not merged with it: the comments now give the reason, that opening publishes the existing history, so removed members count. - Every call site of `update_channel` is a test, and each now passes the channel owner as sender. ### Related issue Follow-up to https://github.com/block/buzz/pull/9307 (review notes on its store gap and on purge). ### Testing - New Postgres test `update_channel_refuses_opening_a_private_channel_with_other_members`: opening fails for both the owner and the other member as sender, while the other member is current and after they are removed, and the channel stays private. A channel that holds only the owner opens. - The existing kind:9002 test `private_to_open_needs_no_other_members` still passes. Both tests fail when the check is removed. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a8f55e637a |
Add real content cleanup for users and agents (#9363)
## Summary Add one shared content-cleanup handler for a user and their agents in a specified community. Preview is the default; deletion commits bounded batches and preserves other people's replies and reactions. Agent selection requires ownership by this user in the target community. Ownership elsewhere is insufficient. The start record reports missing or conflicting ownership, and every batch rechecks the selected agents before deleting anything. ### Reply preservation and live writes Keep erased placeholders for messages needed by surviving reply chains or reactions. Plain links and quotes may point to a deleted message; their signed source messages stay unchanged. Nested reply ancestry uses the existing parent/root indexes. No new permanent index or schema migration is added. Replies without thread metadata use the existing tags GIN index to search for each selected message ID in lowercase and uppercase. The shared marker parser checks which matches are actual replies. Mixed-case references without thread metadata may be missed; metadata-backed replies use binary IDs and remain covered. Planning and hard-delete rechecks each run the probes in one SQL statement with a one-second timeout and a 10,000-match limit. A reply matching several probes counts several times. Exceeding either bound aborts cleanup. This avoids the broad search through unrelated replies; production-scale performance has not been measured. Each batch revalidates its work under the community lock. Transaction-local timeouts apply before locking, including after reconnect. Planned output is written before locking and receipts after commit. A changed row, owner, or surviving reply aborts the batch; retry replans remaining work. Normal reply insertion retains the added indexed parent-existence check. This changes the live write path and prevents saving a reply whose parent disappeared while the writer waited. Erased messages appear unavailable in moderation lookups instead of carrying an empty author key. ### Included content Supported authored events and owned reaction, subscription and notification records are included. Signer-owned personas (30175), team definitions/catalogs (30176/30178), emoji sets/entries (30030/30180), and project groupings (30621) include shared publications and stored revisions. Deleting a project grouping leaves member repositories, their announcements/state and name mappings intact. ### Testing Local runtime tests and hooks are skipped at the owner's request. Source review, Rust formatting and diff checks were completed. The updated revision requires CI validation; earlier test runs and index benchmarks do not validate this replacement. Regression cases cover ownership conflicts/transfers, missing thread records, nested ancestry, plain links, late replies, lookup limits, reconnects, blocked output, and unavailable moderation targets. No new manual relay or UI test was run for this revision. Account blocking remains unfinished; these changes do not establish complete online account erasure. ### Scope and compatibility **Deferred to a separate follow-up PR to keep this PR smaller:** the following work will extend **the same content cleanup handler** (`purge_content` / `content-batches`), rather than introduce another handler: - Workflow database definitions, runs, traces, approvals, schedules and copied inputs; some source events are already covered here. - Canvas revision events and current canvas text. - Artifact events, revision records and current heads. - Channel topics and purposes. - Gift-wrapped DMs and additional huddle history that require different attribution rules. - Git issues, PRs, patches, comments/status and required repository metadata, subject to preservation rules. Repositories themselves stay. - Remaining stored workflow, delivery and projection copies outside this PR's current coverage. These categories remain unfinished. Deferring them is not a permanent retention decision or a claim of complete content erasure. The follow-up must settle shared-document and mixed-owner workflow behavior and test surviving content. Profiles and managed-agent identity definitions belong to profile cleanup. Memberships, personal preferences and access belong to account cleanup. Media cleanup was implemented separately in #9365 and is now on main. Deletion requests, approvals, progress/history and replay protection stay. The workflow orders account gating, global media cleanup, then per-community content cleanup. Real requests still stop at the unfinished account gate; demos simulate every stage without deletion. Other unfinished real workflow stages fail explicitly. Existing demo requests saved with `purge_db` must be recreated for `purge_content`. Bulk client notifications remain separate work. Open views may retain cached content and counts until refresh. The existing missing reply-count button after refresh and ordinary UI access when the root is deleted are outside this PR. Replaces the content portion of #9355 and #9332. Related prior handler: #8698. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
21802f019e |
Keep transparency in mobile avatar photo crops (#9319)
## Summary Choosing a transparent PNG as a profile photo on mobile produced an avatar with a solid background on every client. The crop step always re-encoded to JPEG ([`profile_avatar_crop_page.dart#L507`]( |
||
|
|
6f1eabe4e8 |
fix(mobile): read presence for a person shown again while still covered (#9595)
## Context Follow-up to [#9480 stop following off-screen presence](https://github.com/block/buzz/pull/9480), from [Wes's review comment](https://github.com/block/buzz/pull/9480#discussion_r4591994023). When a person is retired, presence narrows the live subscription to the people still shown. If that narrowing fails, the old wide stream stays live and still covers the retired person. If that person is then shown again, the tracked set matches the live stream's keys, so `_subscribe` returned early without reading their snapshot. Their dot stayed empty until a live event or the next 60 second poll. The same gap happened when a person was shown again before the retirement's resubscribe ran. `_subscribe` now schedules the pending snapshot read before returning in that case, so a person shown again gets their current presence right away. ## Validation - New test: `a key shown again while a failed narrowing left it covered is read`. It failed before the fix (no snapshot read for the re-shown key) and passes after it. - `flutter analyze` clean; full mobile `flutter test` suite passes. - Automated app test (iOS 27 simulator, signed-in debug build): Home Team filter DM rows show presence dots, and they are still correct after switching to Solo for 70 s and back. The Team list stays mounted offstage while hidden, so that run is a smoke check of the presence flows; the retire and re-show path itself is covered by the new unit test. ## Regressions None expected. The extra read happens only when a newly tracked key is already covered by the live stream. `_schedule` already dedupes and skips while a retry is pending, so it adds at most one small snapshot query per re-shown key. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
c0ce4982fc |
buzz-db: check membership, agent-owner and channel references in app code (#9404)
> Builds on #9399 (its two commits are included here until it merges;
review only the commits after `367d3486`).
## What
This is the second app-side step toward retiring every foreign key,
following `docs/database.md` ("Retiring a trigger, function, or foreign
key"). Each writer below now checks its parent inside the writing
transaction and locks it `FOR KEY SHARE`, the same lock an FK check
takes. The FKs stay in place, so both checks run and agree. A later
contract migration drops them.
The shared helpers are in a new `store/reference_check.rs`:
`require_channel`, `require_optional_channel`, `require_user` and
`require_relay_member`, all community-scoped. A missing parent returns
`DbError::NotFound` and nothing is written.
| FK | Writer | Change |
|---|---|---|
| `join_policy_acceptances → relay_members` | `relay_invite.rs` (both
claim paths), `relay_invite/claim_owner.rs` | One helper locks the
member row, then inserts the acceptance. The existing-member read is now
`FOR KEY SHARE`. |
| `users.agent_owner_pubkey → users` | `user.rs`
`set_agent_owner_with_operation` | Reads the agent row `FOR NO KEY
UPDATE`. A missing agent → `NotFound`; an already-owned agent →
`Ok(false)` without examining the owner; otherwise the owner is checked,
then the UPDATE runs. `NotFound` for a missing owner therefore holds
with or without the self-FK. |
| `channel_members → channels` | `channel_members.rs`
`insert_auto_membership`, `lock_channel_archived_at_in_transaction` |
The auto-add checks the channel. The archive lock now returns
`ChannelNotFound` for a missing row instead of reading as not archived.
A soft-deleted channel still reads `None`. |
| `thread_metadata → channels` | `event.rs`, `thread.rs` | Checks the
channel before writing thread metadata, in the event's own transaction.
|
| `moderation_reports/actions → channels` | `moderation.rs`,
`relay_admin_actions.rs` | Checks a non-null `channel_id` before the
write, after the existing rejection outcomes (not-found,
already-claimed, not-open, replay). |
**Real race closed.** Member removal locks the member row `FOR UPDATE`,
deletes the acceptances, then deletes the member. The acceptance insert
used to follow an unlocked member read, and a membership `INSERT … ON
CONFLICT DO NOTHING` locks nothing when the member already exists. Today
only the FK's implicit `KEY SHARE` stops an orphan acceptance; this
change makes that lock explicit.
**Caller-visible behavior.**
- The huddle join in `audio/handler.rs` maps `ChannelNotFound`, meaning
the channel was purged between the pre-join check and the lock, to
`MembershipLost` before any write.
- `set_agent_owner` has one production caller, `api::write_agent_owner`.
It runs `ensure_user_for_authorization` on both the agent and the owner
first, so its behavior is unchanged.
- `put_members` keeps its existing error.
## Tests
- `store/reference_check_postgres_tests.rs`: 9 tests, one missing-parent
test per writer plus a `KEY SHARE` lock test. Each drops the covered FK
in its per-test DB (`test_support::drop_foreign_keys_between`), so it
proves the app check. The `insert_report` upsert test pins precedence: a
missing channel beats an existing report, and the stored row is
unchanged.
- `relay_members.rs`:
- Two new race tests: a membership claim racing member removal, and an
invite claim racing member removal.
- The existing
`member_removal_waits_for_and_removes_concurrent_acceptance` now runs
against the explicit lock.
- The `wait_for_put_member_behind` query pattern in `api/invites.rs`
tests was updated to the new query text.
- `relay_members.rs`
`invite_claim_conflicting_with_a_member_added_mid_claim_waits_for_removal`:
a `#[cfg(test)]` pause before the membership INSERT
(`relay_invite::test_hook`) lets a member commit mid-claim and a removal
hold it `FOR UPDATE`. The claim must wait, then return `NotFound` with
no acceptance, no orphan, and no invite use.
- `set_agent_owner_rejects_missing_owner_with_and_without_foreign_key`:
asserts `NotFound` and an unchanged owner with the FK installed, then
with it dropped.
Falsification: removing the check at each of the 10 call sites turns its
test red. So does stripping `FOR KEY SHARE` from each helper and from
the invite member read. Swapping the conflict-branch helper for a raw
acceptance insert, or moving the owner check back after the UPDATE, also
turns its test red.
## Validation
Run on a cloud workstation at this tree (
|
||
|
|
ec778bff9a |
buzz-db: enforce five single-table guards in app writers (phase 1) (#8320)
> **Also carries the catalog expand** (`cdc88edd`) for phase 2 (#9398). `validate_serving_catalog`, used at boot and readiness, no longer requires the `communities_deletion_tombstone` trigger, only `community_deletion_lock_key(uuid)`. Without this, a pod would fail boot after `0090` drops the guards. Regression: `migration_schema_single_table_guards_are_optional_for_serving_and_deletion` migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, and validates again. No schema change. ## What This is phase 1 of 2 for retiring five single-table guard triggers (BUZZ-318). Their invariants now hold in the application writers. **All five triggers and their functions stay** for mixed-version pods. A later PR drops them. | Trigger / function | App-side enforcement | |---|---| | `trg_channels_community_id_immutable` | **By construction.** Inserts bind the tenant once. No production `UPDATE channels` assigns `community_id`, and `ChannelUpdate` has no community field. A source policy pins this. | | `communities_deletion_tombstone` / `enforce_community_tombstone()` | **One state machine.** `begin_quiescing`, `fence`, `purge_postgres` and `abort` all go through `transition_community`, using a `FOR UPDATE` row snapshot in the caller's transaction (quiesce, fence and abort also hold the community deletion advisory lock; purge does not, and its tombstone transition fails if a concurrent abort won). Allowed transitions: active→quiescing (plus a quiescing retry); quiescing→fenced, which increments the generation; fenced→tombstone at the same generation, with a one-way `deleted_at`; active/quiescing/fenced→active on abort, which also increments the generation. Every transition rejects an already-deleted row. The UPDATE is conditioned on the snapshot's state and generation. `set_community_icon` updates only an active, undeleted row and returns `AccessDenied` otherwise. Archive and unarchive lock an active row, and their UPDATEs also carry `deletion_state = 'active'`, so every non-lifecycle `communities` UPDATE or upsert carries the active predicate (policy-pinned: a non-active row is immutable outside the state machine). No production `DELETE FROM communities` exists, and the policy forbids adding one. Executor GUCs are unchanged. | | `community_deletion_request_retargeting_guard` | **Mostly by construction, plus predicates.** No production UPDATE assigns target identity or provenance (policy-pinned). Both initial inventory freezes (`freeze_inventory`, `complete_owner_preparation`) require `stage = 'submitted' AND blocked_at IS NULL AND inventory_frozen_at IS NULL` in their UPDATE. Every request UPDATE that assigns an inventory column must carry `inventory_frozen_at IS NULL`, and one that assigns `destructive_storage_*` must carry the frozen-or-equal guard (policy-pinned). The destructive-manifest freeze now also refuses a row that is marked frozen but is missing its manifest JSON. | | `community_deletion_approval_removal_guard` | **By construction.** Approvals are insert-only (`approve`, `complete_owner_preparation`). The policy forbids any production UPDATE, `ON CONFLICT … DO UPDATE` upsert or DELETE. | | `community_deletion_manifest_keys_guard` | **One shared check.** Append, pre-freeze clear and verified cleanup each lock the request row and check its stage and freeze status through `guard_manifest_chunk_write`. Chunk content is never updated: the policy rejects every chunk UPDATE or conflict upsert except `mark_manifest_chunk_deleted`, the only writer that stamps `deleted_at`. That stamp must be the function's only chunk write, a plain UPDATE of exactly `SET deleted_at = now()`, with `request_id = $1`, `chunk_no = $2` and `deleted_at IS NULL` as plain conjuncts (no `OR`, no subquery), so it stays one-way. | **The app is stricter than the triggers, not equivalent to them.** `enforce_community_tombstone()` admits any change when the executor GUC matches, before it looks at lifecycle columns, so the transition graph above lives only in `transition_community`. The chunk DELETE trigger also allows cleanup when the parent request is missing or unfrozen, while `guard_manifest_chunk_write` allows only fenced-and-unfrozen or verified cleanup. Every current caller already runs at those stages. Writer inventory: I searched every production writer of these tables and columns across all crates, excluding `#[cfg(test)]`. That covers buzz-db, buzz-deletion, buzz-relay handlers, side effects and operator/admin APIs, and buzz-audit. Relay, operator and executor entry points all call the store methods above. No other crate writes these tables directly. ## Tests The six PG tests are in `store::deletion::postgres_tests`. Each disables **only** its own trigger, then checks that the app path rejects the forbidden mutation and permits the allowed one: - `single_table_guard_channels_remain_tenant_bound_without_trigger` - `single_table_guard_community_lifecycle_rejects_deleted_row_without_trigger`: icon refused while quiescing; fence refused on a deleted row; then the full fence→tombstone sequence; abort after tombstone fails. - `single_table_guard_abort_invalidates_generation_without_trigger`: abort from quiescing and from fenced, for unarchived and pre-archived communities; asserts active state, community and request generation = previous + 1, restored `archived_at`, null `deleted_at`. - `single_table_guard_request_inventory_freeze_is_one_way_without_trigger`: re-freeze is refused on both the operator and owner-preparation paths. The owner path leaves no approval evidence behind. Owner request-ID retargeting is refused, and a frozen manifest with missing JSON can't be filled in. - `single_table_guard_approval_evidence_is_append_only_without_trigger`: asserts the exact error. - `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` The source policy lives in `crates/buzz-db/tests/observability_source.rs` (`every_production_single_table_guard_writer_preserves_its_invariants`). It scans every crate's `src` directory and reuses the file's existing cfg-test stripping, comment and literal masking, function slicing and SQL normalization. Each rule is checked per function. A minimum count of discovered writers per table makes the test fail if discovery stops matching, and exact sets of production functions hit by each rule (lifecycle exemption, stamp exemption, chunk-guard callers, active-community writers, request-freeze writers) make it fail if a parser stops matching. The parser handles `ON CONFLICT … DO UPDATE SET` (with or without a space before `(`), tuple `SET (a, b) =`, and rejects column-less community inserts. A guard counts only as a plain conjunct of the statement's own WHERE: it must follow the WHERE start or an `AND` (optionally table-qualified, never `NOT`), with no whole-word `OR` outside the frozen-or-equal groups and no subquery, and every `destructive_storage_*` assignment must preserve a frozen value with `COALESCE`. Negative and accept fixtures cover every rule. The shared source filter now also skips `test_support.rs`, which is compiled only under `cfg(test)`. Each check was confirmed to fail when its fix is removed. Seven mutants each failed on an assertion: the `inventory_frozen_at` predicate removed from each of the two freeze paths, and each of the five policy rules disabled. Review rework also falsified the injected `SET icon = NULL` writer, an unguarded inventory/destructive-storage writer, abort keeping the old generation, and the stamp without `deleted_at IS NULL`; every new fixture test fails against the previous policy. Round 1 also falsified the lifecycle `deleted_at` check, the manifest append guard, the icon predicate and the destructive-manifest predicate. ## What got simpler The four lifecycle UPDATE statements, each with its own generation arithmetic and its own GUC setup, are now one transition function with one SQL writer. Both manifest removal modes share one admission check. For inventory freeze, the check lives in the existing atomic UPDATE, with no new helper or transaction. Channel immutability and approval append-only behavior stay construction rules, not duplicated runtime checks. The source-policy scans now share one Rust crate walker, which this PR extracted into `collect_production_rs_files`. **Known policy limits:** the policy is a textual check of Rust source, not a SQL parser or a control-flow analysis. None of these gaps hides an unsafe writer today, but phase-2 reviewers should not read the policy as more than that: - Only `INSERT`, `UPDATE` and `DELETE` statements are recognized, including CTE and `ON CONFLICT` forms. `MERGE` and `TRUNCATE` are not. `UPDATE ONLY <table>` and `DELETE FROM ONLY <table>` are not recognized either, because the table name must follow the verb directly. - A guard negated *after* itself (`deletion_state = 'active' IS FALSE`, `… = false`) is not caught. - A SQL comment inside the literal (`-- AND deletion_state = 'active'`) can supply the guard text. - The frozen-or-equal `OR` text is removed before the `OR` check without checking how it is grouped. - `guard_manifest_chunk_write(` is checked for presence in the writing function only. The policy does not show the result is awaited and propagated, or that the guard runs in the same transaction as the write. With the trigger disabled, `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` shows append and pre-freeze clear refusing after freeze; verified cleanup has no trigger-disabled test. - Function discovery uses a fixed list of signature prefixes, and dynamic SQL is recognized only in known shapes such as `set_parts.push`. - The shared source filter skips files named `test_support.rs` by name. Both such files are compiled only under `cfg(test)` today. **Phase 2 (not here):** a forward migration plus a desired-state change will drop only these five triggers and functions and update `validate_serving_catalog_on` and the schema assertions. It ships after every serving and executor pod runs these writers. **Identified debt (pre-existing, outside this diff):** purge can take the request-row FK lock (checkpoint insert) before the community lock, while abort locks community then request (`deletion.rs` purge vs abort). PostgreSQL detects that as a deadlock and cancels one side, which fails closed; the order is unchanged from the base. `runtime::postgres_tests::writer_pool_rejects_non_read_committed_database_default` hangs until its 120 s bound on clean `177551dda` as well. Some test-only fallbacks still hardcode `localhost:5432`, and one relay test helper hardcodes Redis 6379. ## Verification (Blox, byte-identical tree to this commit) | Gate | Result | |---|---| | `cargo fmt --all -- --check` | pass | | `cargo clippy --workspace --all-targets -- -D warnings` | pass | | `cargo nextest run -p buzz-db --lib` | 166/166 | | `cargo nextest run -p buzz-db --test observability_source` | 30/30 | | `scripts/test-postgres-test-discovery.sh` | pass | | `scripts/postgres-test-run.sh -p` buzz-admin / audit / deletion / push-gateway / relay / search / workflow | all rc 0 (4, 7, 11, 11, 402, 20, 2) | | `scripts/postgres-test-run.sh -p buzz-db` | 515 pass, 1 fail: the pre-existing hang above | The new PG tests are selected by the `postgres-ci` filter `(test(/postgres_tests::/) or binary(/^postgres_/)) and not test(/(^|::)external_infra[^:]*::/)`. The policy tests run in `just test-unit` (`--test observability_source`). --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c8a1b26345 |
docs(mobile): add REVIEWING.md with mobile review principles (#9298)
Adds `mobile/REVIEWING.md`, the principles we review mobile PRs against, and links it from the Reviewing section of `AGENTS.md` so any reviewer (human or agent) applies them to mobile changes and to relay or push-gateway behavior the app relies on. The principles: land Pareto improvements (better somewhere, worse nowhere), no hangs or stutters, use the network carefully, don't clog the pipe, keep the app usable, and don't regress developer experience (above all, no flaky tests). Each comes with past block/buzz PRs as examples. This tightens one existing rule rather than contradicting it. The Reviewing section blocks only on concrete correctness, security or contract defects with a realistic failure scenario. The new file treats a performance, network, reliability, developer-experience or UI-clarity regression as such a defect, as long as the finding names the mechanism and its effect. It also asks authors to say in the PR description why their change is a Pareto improvement. ### Validation Documentation only. Checked that the links and anchors resolve. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
3d97535120 | buzz-db: check workflow references in app code before FK retirement (#9399) | ||
|
|
833c41863a |
fix(relay): enforce channel owner precedence (#9592)
**Category:** fix **User Impact:** Channel admins can manage the conversation while owners retain control of ownership and owner membership. **Problem:** Channel admins can currently grant themselves ownership, change another owner's role, or remove an owner when another owner remains. A racing promotion can stop a removal after admission while its command is still stored and reported successful. **Solution:** Reserve ownership grants, owner role changes, and owner removal for channel owners, enforced during validation and under the database membership lock. Persist each removal and its signed command together so a locked refusal rejects the receipt without storing or broadcasting the refused command; this applies equally to people and agents, with no new role, migration or protocol field. <details> <summary>File changes</summary> **crates/buzz-core/src/channel.rs** Constrain the shared role policy and member admission decision. Keep same-role additions idempotent and preserve ordinary guest-promotion rules; extend the existing role matrix and cover ownership grants through admission. **crates/buzz-db/src/store/channel_members.rs** Reject non-owner removal of an owner under the existing membership lock, including removal of an agent the actor owns. Reuse those locked checks when storing a removal command and its membership change atomically. Retain database coverage for escalation denials, ordinary owner/admin powers and concurrency; move the target-promotion race to the ingest journey below. **crates/buzz-relay/src/handlers/channel_authz.rs** Make removal authorization aware of the target's role and expose an ownership-specific role-change refusal. Extend the existing authorization tables. **crates/buzz-relay/src/handlers/side_effects.rs** Pass the removal target into admission authorization. Persist removals atomically, then run cache invalidation, eviction and best-effort notices only after commit; duplicates run no second removal or notices. **crates/buzz-relay/src/handlers/ingest.rs** Route kind 9001 through atomic persistence and return locked membership refusals as client rejection before dispatch. **crates/buzz-relay/src/handlers/remove_user_postgres_tests.rs** Exercise the real ingest race with a membership-lock barrier: target promotion causes rejection, leaves the Owner intact and stores/publishes no command. Then verify legitimate removal and duplicate replay after rejoin. This replaces the DB-only target-promotion test rather than duplicating it. **crates/buzz-relay/src/handlers/mod.rs** Register the new PostgreSQL ingest journey for automatic discovery. **NOSTR.md** Document owner precedence, including the agent-owner exception's boundary. </details> ### Try it 1. Run the updated relay and create a disposable channel with two owners, one admin, and one ordinary member. Two owners ensure the last-owner guard cannot mask the new permission check. 2. As the admin, attempt to promote yourself or another member to owner. Both requests should be refused. 3. As the admin, attempt to demote or remove either owner. Both requests should be refused and their memberships should remain unchanged. 4. Confirm the admin can still rename the channel and manage ordinary members/admins. 5. As an owner, confirm ownership delegation and co-owner demotion/removal still work. The sole remaining owner must still be unable to demote or remove themselves. 6. Run the PostgreSQL lane's membership regressions and `removal_receipt_tracks_the_locked_membership_write`. The controlled race must return rejection with the target still Owner and no stored/published removal; the same command must succeed once authorized, and its later replay must preserve a rejoined member. ### Validation and remaining checks - At `e7a8fe405`, all **2,048 infrastructure-free tests** across the complete `buzz-db`/`buzz-relay` package inventory pass with nextest process isolation, plus all **five package doctests**. The monolithic Cargo run stalled in shared-process configuration tests; the same package inventory passes with the repository's preferred isolated runner, without exclusions or assertion changes. - The new ingest journey fails on the original implementation with `accepted:true` after the locked refusal, and passes with atomic removal. Its positive controls verify actual publication for a legitimate removal and no repeated removal/publication after rejoin. The existing demoted-actor lock test retains direct-call concurrency coverage. - At the same head, all **1,425 PostgreSQL cases** across both packages pass through the per-test isolation wrapper (PostgreSQL 17.12, UTC; hosted CI uses 16). A rebuilt isolated native relay passes **24 signed WebSocket operations** plus persisted-state and subscriber checks, including the real promotion/removal race, later legitimate retry and replay after rejoin. Temporary services are stopped; Git/media behavior was not exercised. All mandatory push hooks pass, including the broad Rust suite (709.20s) and native/desktop checks (302.32s). - Test churn is **420 lines** (+399/-21); non-test churn is **196 lines** (186 source, 10 maintained docs), versus 279/69 at the preceding head. The new 207-line ingest journey and two-line registration replace the 68-line DB-only target-promotion race; no other authorization or concurrency coverage is removed. - The implementation tree passed 298 core library tests, 1,979 database/relay library tests, and 76 binary/integration-target tests: 2,353 total. Infrastructure-dependent ignored tests were excluded. These runs preceded publication; the publication commit has the identical source tree, with only its commit subject amended. - Disabling the ownership-grant guard made the admission regression fail with `Ok(Owner)`; restoring the guard returned all 298 core tests to green. - At follow-up head `6d4622d3e`, all 769 PostgreSQL tests in the `buzz-db` package profile passed using the repository's per-test database isolation wrapper (PostgreSQL 17.12, UTC; 245 cases outside the selected profile skipped). This includes both new regressions and the existing owner-management journey retained after removing two repeated positive checks. - An isolated native relay passed 18 signed WebSocket operations plus persisted-state checks: admin escalation, co-owner demotion/removal, retained admin management, owner delegation/demotion/removal, and last-owner protection. This membership workflow used local PostgreSQL and Redis; Git/media behavior was not exercised. - PostgreSQL test discovery, formatting, and hosted CI passed at `6d4622d3e`. Maintainer approval and human acceptance remain pending. This relay permission change does not require a client update. Related history: #3017 established bidirectional elevated-role checks and last-owner protection; #8143 introduced the current shared role predicate. This PR adds the Owner-over-Admin distinction to those rules. --------- Signed-off-by: Taylor Ho <taylorkmho@gmail.com> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz> |
||
|
|
97d5a46cc6 |
feat(relay): grow DMs in place, identified by their people (#9125)
## Summary
Lets a DM grow. Today adding someone to a DM always starts a new DM.
This makes the relay side of "growable DMs" work. Joining an existing
DM, and seeing its history, is always opt-in: without `["history",
"include"]` the relay never puts anyone into an existing DM, so older
clients can't add anyone to one unseen.
- **Opt-in tag on kind:41010 and kind:41011.** `["history", "include"]`,
or `["history", "ask"]` on 41011, is the only way anyone joins an
existing DM. Any other value is refused.
- **41011 with the tag:** people and agents join this DM with its
history. When people join, the DM's identity moves to the grown set of
people, so messaging only the original people afterwards starts a new
DM.
- **A DM of at most one person never gains people in place**, even with
the tag. Adding a person to you-and-your-agents starts or opens a DM of
the people, and the original keeps its members. Agents still join it in
place.
- **41011 without the tag:** finds or makes a DM of the source's people
plus whoever is added, as an untagged 41010 does, and adds no one to an
existing DM. Agents already in the source stay behind; agents named in
the add join the new DM.
- **41011 with `["history", "ask"]`:** part of the protocol, because
desktop and mobile use it to know when to ask about history. Agents
alone, and people added to a DM of at most one person, are handled as
with `include`. People who would join a DM of two or more people are
refused with exactly `needs-choice: history` and nothing changes; the
client asks, then sends the add again tagged `include` or untagged.
Agents can't send it, and it isn't accepted on 41010.
- **41010 with the tag:** finds the DM of the named people and adds any
named agents it lacks. A DM still identified by all its members (made
without the tag) moves to its people's identity when reopened this way.
- **41010 without the tag:** finds the DM of those people, which agents
may have joined, or creates a DM of exactly the named members. There is
one DM per group of people, and agents joining it don't fork it
(Morgan's product decision), so no second DM of the same people is ever
created. A DM made this way with agents named gets an all-members
fingerprint, so it never collides with the people's DM.
- **A DM of people is identified by its people.** Agents don't change
which DM it is and don't count toward the 9-person limit. There is no
agent limit, matching channels. A DM with at most one person (you and
your agents) is identified by all its members: an agent joining it moves
its identity, so reopening the original pair starts a new DM.
- **Collisions.** If people join and a DM of the grown set already
exists, the relay returns it (`response:{"channel_id","created":false}`)
and changes nothing here. Agents named with them join that DM. Agents
alone join in place; if the identity the DM would move to is already
taken (only possible for a DM of at most one person, or one still
identified by all its members), the DM gives up its identity, so
reopening its old members starts a new DM.
- **One locked step.** Every DM membership write rereads the DM's
members under its membership lock, checks the agents actually joining,
and compares the DM's identity with the fingerprint actually stored.
Starting a new DM from a DM uses the members it has at that moment.
`created` is true only when this request made the DM, even if a
concurrent open won the race.
- **Agent add policies.** Putting someone else's agent in a DM with
anyone besides you follows its `channel_add_policy`, the same rule as
channels. That covers every agent in a new DM started from another one,
and only the agents that join when a DM grows or is reopened. Messaging
an agent alone ignores it, as today.
- **Only people grow DMs.** An agent can't send the history tag on 41010
or 41011, so a DM an agent opens is identified by all its members and an
agent can't take over or join a DM of its owner's people. Growing never
reveals a DM the actor isn't in. The relay can't be added to any DM.
- **The 9-person limit counts the caller only if they're a person**, so
an agent can open a DM with nine people.
- **A new DM carries people, not agents.** Every fork (Start new DM, the
tagless 41011, a person added to an agent-only DM) holds the source's
people plus the explicit additions. Agents can be added back later, so
no agent's add policy can block Start new DM.
- **Removing an agent keeps an old DM its people's.** A DM identified by
all its members moves to its people's identity when an agent leaves or
is removed, unless they already have a DM.
- **Leaving and removing agents.** kind:9022 lets anyone leave a DM, and
kind:9001 lets you remove yourself or your own agent (as deleting an
agent does). kind:9000 and every other 9001 are refused on DMs; members
join only through 41010/41011.
- **Removals keep identity in step.** When anyone leaves or is removed,
including moderation kicks (which remove members directly in the
database), the DM keeps its identity only if its remaining members still
match it. Otherwise it gives the identity up under the same membership
lock: it keeps its history, and opening that group again starts a new
DM. Removing an agent from a group DM keeps it that group's DM.
- **The relay's moderation DM stays two-party**, on both 41010 and
41011.
- SDK `build_dm_add_member(..., include_history)`, the opt-in
`build_dm_open_with_history` (`build_dm_open` keeps the exact-members
behavior; neither caps pubkeys, since the relay enforces nine people and
agents do not count), and CLI `buzz dms add-member --include-history`.
Without the flag the CLI keeps the old behavior.
Removing other people (beyond moderation kicks) and DM naming are out of
scope.
Client follow-ups: block/buzz-app#2670 (desktop, sends the tag for
history adds, agent adds, and New message opens that show an existing
DM) and the mobile PR (sends it after its choice dialog).
**Deploy this relay change before the app PR merges:** an older relay
ignores the history tag, so the app's Include history would start a new
DM instead.
### Decisions and known gaps
- **No agent cap, on purpose.** This matches channels. The guard is the
add policy instead: every agent the caller doesn't own needs its
`channel_add_policy` to allow it when it joins a DM that holds anyone
besides the caller and that one agent. So a DM stuffed with 40 agents
whose policy is `nobody` is refused. Covered by
`adding_an_agent_follows_its_add_policy` and
`opening_with_several_agents_follows_their_add_policy`.
- **A tagless add opens the DM of the people plus the additions.** Older
clients forking a DM now leave its existing agents behind, as the new
apps do. That shares less than before, never more.
- **Where the protocol is documented.** kind:41010 and kind:41011 have
no NIP today. The history tag is documented on the SDK builders (the
add-member builder also documents `ask` and its `needs-choice: history`
refusal, which it doesn't send) and in the CLI `--include-history` help,
and the `created` field of the response is documented on the SDK
builder.
- **Known gap: lost announcements on retry.** The membership change and
the idempotency record commit separately, the same pattern main uses for
every DM command. If the membership change commits but the idempotency
commit then fails, a client retry finds the members already there and
returns success without posting the join messages, notifications or the
new-DM announcement. Membership and history are correct. This needs a
commit failure between the two writes, and fixing it means moving the DM
writes into the idempotency transaction for all DM commands, so it's out
of scope here.
### Rollout and rollback
- **No kill switch needed.** The new behavior is opt-in per event:
clients that don't send `["history", "include"]` get the old behavior.
- **If the relay rolls back,** DMs that grew are no longer found by
their people, so opening one starts a new DM. History stays in the grown
DM and no data is corrupted.
### Related issue
None found.
### Testing
- Postgres-backed handler tests (`handlers::dm_growth_postgres_tests`,
44 cases) go through `ingest_event`: growing with and without history,
the tagless 41010 and 41011 paths adding no one to an existing DM,
collisions, agents joining in place only with the tag, per-agent owner
DMs, the people-only limit, add policies (including several agents with
no other person), agent actors, not revealing a DM the actor isn't in,
the moderation DM on both kinds, a person added to an agent-only DM with
the tag starting a separate DM, unknown history values, 9000 refused,
leaving, owners removing their agents, kicks releasing or keeping
identity, legacy fingerprints reconciled on agent join and tagged reopen
(with the collision case), an agent joining a one-person DM whose grown
identity is taken, untagged adds that name a person and an agent
starting a DM of exactly those members, `ask` adding agents and refusing
people, untagged opens of a group's people finding their DM with its
agents (after an agent joined in place, and after one of two agents
left), reopening past an existing `owner_only` agent, concurrent opens
all adding their agents, new DMs carrying only people (and named
agents), live membership, the relay key refused, and an agent opening a
nine-person DM. Each new guard was mutation-checked: removing it turns a
test red.
- At
|
||
|
|
f315c7f31f |
feat(workflow): implement send_dm action (#9402)
## Summary
Workflows using `send_dm` currently fail with `NotImplemented`.
Implement the action by creating or reusing a private DM between the
workflow owner and the resolved recipient, then publishing through the
existing relay message path.
- Preserve community scoping, workflow attribution, and authored mention
provenance. Require channel owner/admin authority, as for outbound
webhooks.
- Accept only a fixed hex recipient or `{{trigger.author}}`, including
for previously stored definitions. Require an existing, unbanned
recipient in the run’s community.
- Reuse private conversations without unhiding them or repeating
member-added notices. Retain replaceable discovery events for recovery,
and validate media before creating a conversation. Propagate failures
rather than reporting success.
- Cover template resolution, signed message persistence, conversation
reuse, recipient restrictions, and both agent-mention policy modes.
- Atomically create DMs by participant hash so concurrent first sends
reuse one conversation and only the inserting caller emits membership
notices. Preserve hidden state on workflow reuse.
- Follow current main’s agent-DM policy and per-run mention-authority
gate, including withheld-mention trace output.
### Related issue
None found after searching open issues and PRs for `send_dm`, `SendDm`,
and `sendDm`.
### Testing
- `cargo test -p buzz-workflow`: 176 passed.
- `cargo test -p buzz-relay --lib workflow_sink::tests`: 23 passed.
- PostgreSQL-backed `workflow_sink` tests against an isolated PostgreSQL
17 database: 8 passed.
- `cargo clippy -p buzz-relay -p buzz-workflow --all-targets -- -D
warnings`: passed.
- Concurrent DM creation PostgreSQL regression: passed. A table-lock
barrier forces both callers to INSERT, covering interactive/interactive
and interactive/workflow races, accurate creation flags, and
hidden-state preservation.
- `cargo test -p buzz-db --lib`: 216 passed (763 PostgreSQL tests
ignored); the new PostgreSQL regression was run explicitly.
- Updated `workflow_sink` suite including PostgreSQL integration tests:
31 passed.
- `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings`:
passed.
- Rust formatting, diff whitespace checks, and PostgreSQL test
discovery: passed.
- Pre-push hooks: passed, including the broader Rust unit suites,
desktop/Tauri checks, and file-size gate.
- Previous full `just ci` attempt stopped at unrelated mobile
dependency/formatting checks. Full `just ci` was not rerun after merging
main; targeted tests, lint, and the repository pre-push hooks cover the
updated branch.
Draft pending human testing and the review checklist. Manual check: as a
channel owner/admin, configure a `message_posted` workflow with `action:
send_dm`, `to: '{{trigger.author}}'`, and `text: 'Notice:
{{trigger.text}}'`; trigger it twice as another user. Both rendered
messages should appear in the same private DM with the workflow owner,
and both runs should return a successful send with an event ID. A second
send must not add membership notices or unhide a hidden DM. Plain
members must not be able to save or run this action; arbitrary recipient
templates and unknown/banned recipients must be rejected.
---------
Signed-off-by: Yissachar Radcliffe <yissachar@squareup.com>
mobile-v1.4.0-rc.2
|
||
|
|
b0e55606f2 |
perf(mobile): stop following presence for people no longer shown (#9480)
[#9444](https://github.com/block/buzz/pull/9444) narrows the live presence subscription (kind 20001) to the people the app has shown this session. That set only grows, so scrolling through a long DM list or opening many profiles keeps receiving presence for people who are no longer on screen, and each new person reopens the subscription with everyone seen so far. This was raised in [Jude's review](https://github.com/block/buzz/pull/9444#pullrequestreview-5896221680). With this change, presence follows only who is on screen now: - `track` returns a release callback. DM rows and profile sheets release when they unmount. Counts are per person, so someone shown in a DM row and an open profile sheet stays followed until both are gone. - A person nobody has shown for at least 30 seconds is retired: dropped from the tracked set and the cache, and the live subscription is replaced with one for the people still shown. A sweep every 30 seconds retires everyone whose own 30 seconds are up, so each person stays followed for 30 to 60 seconds after their release and the subscription narrows at most once per 30 seconds. Scrolling back within 30 seconds keeps the current subscription. - A read that started before someone was retired doesn't fill in their presence if they are shown again; they wait for a read of their own. - When nobody is shown, the stream closes, and the next person shown opens a new one immediately. - Switching communities keeps following people still on screen, instead of dropping everyone. ### Regressions - **Mention picker ranking.** The picker reads the presence cache without tracking anyone itself, so it ranks by presence only for people currently on screen (before, also for anyone shown earlier in the session). Keeping a retired person's last value would show stale presence, which is worse. - **Dot pop-in.** A retired person's dot is missing when they come back (scrolling back after 30 seconds, or switching the Home filter to Solo and back after 30 seconds) until the replacement subscription is ready and their snapshot read returns. On a slow link that can take seconds. Before, the dot stayed for the whole session. - **Network.** A retirement costs one replacement REQ and a CLOSE, at most once per 30 seconds of scrolling. A person shown again after being retired costs one snapshot read, the same as the first time they were shown. - **Reliability.** Narrowing uses #9444's replacement path (the old stream stays until the new one is ready), so a failed narrowing keeps the wider stream and the poll retries it. ### Validation iPhone 12 mini on Builderlab (measured on [ |
||
|
|
b303271ad3 |
[buzz] Classify HTTP event request metrics by event type (#9561)
## What Add an `event_type` label to `/events` request-count and latency metrics so operators can inspect and alert on individual operations. ## Why The existing `/events` latency alert combines message sending, profile updates, reactions, typing and identity archive/unarchive into one p95 signal. Slow archive work can trigger the same generic page as slow message sending. The page does not identify which operation is slow or show whether messaging is affected, so on-call has to inspect traces and logs before deciding what needs attention. This change supplies the event-type dimension needed to name the slow operation and choose its notification urgency. Reusing the kind registry also keeps newly registered operations visible automatically. ## How Classify events from the kind already parsed by the HTTP bridge and pass that classification to the outer request timer. Both `http_requests_total` and `http_request_latency_ms` gain a bounded label: - `message`, `profile_update`, `reaction`, `typing` - `identity_archive`, `identity_unarchive` - `kind_<number>` for other kinds registered in the existing `ALL_KINDS` registry, using `registered_kind_label` - `other` for unregistered kinds, `invalid` for malformed event JSON, and `unknown` for requests that fail before parsing New entries in the shared registry automatically receive a distinct metric label without updating a separate metrics list. Friendly names remain for the common operation groups. Latency continues to cover the full request, including admission and processing. Existing metric names and labels remain available, and other routes retain their current labels. Classification uses the existing parse path without changing admission order. No database migration is required. Closest existing PR: none found. --------- Signed-off-by: Helen Tian <htian@squareup.com> |
||
|
|
7d361d1f6b |
update feedback community invite link (#9588)
Replaces the expired Buzz feedback community invite link in the README with the current one. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Diem Nguyen <diem@squareup.com> Co-authored-by: Fizz <6be7be23ec5bba868f3e1db5ec86013d76bd1a293dce5b435a192158fec13641@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d39545ebd4 |
fix(mobile): name the failing step in sign-in errors (#9263)
Organization sign-in shows the same "Couldn't sign in. Try again." (landing page) or "Sign in failed. Try again." (in-app banner) for every failure after the browser hands control back: a rejected or stale callback, a keychain write that doesn't stick, a code exchange the server refuses, a session for a different account, or a malformed response. Server logs can't tell these apart either, because the exchange can succeed on the server and still fail on the device. So a user's screenshot of the error tells us nothing about which step broke. This appends a short code naming the failure, for example "Couldn't sign in (account-storage). Try again." or "Sign in failed (browser-restartLogin). Try again." The code is the failure's enum name, prefixed by where it came from (`browser-` for the callback, `account-` for the exchange and session). An unexpected failure type throws instead of showing a made-up code. ### Validation - Focused test changes: the sign-in banner's recovery test now checks the code in the message for two account failures and one browser failure, at each text scale. - Full mobile suite (`flutter test`) and `flutter analyze` pass. - Not yet: an automated app run reproducing a failed sign-in to capture the new message on screen. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
aec5710453 |
fix(mobile): order same-second messages by millisecond offsets (#9541)
## Summary Messages sharing a Nostr second can appear in hash order on mobile even when their signed `ms` tags establish a send order. Channel timelines and thread replies now compare `created_at * 1000 + ms`, using the same first-tag and canonical 0–999 validation as desktop. Each comparator retains its existing event-ID tie-break. Effective times are computed once per event and memoized. Relay paging still uses whole seconds and IDs. Legacy history now chooses and filters its cursor with the existing relay-order helpers, independently of display order. The channel-window relay comparator is unchanged. The review fixes from #9550 preserve the original event's millisecond time through edits and provisional thread rendering, so cached replies keep their order when the query lands. Effective edits use the relay's greatest `(created_at, id)` rule, independently of display order. ### Related issue Related desktop symptom: #8192. Desktop implementation: block/buzz-app#249. No matching open mobile PR found in the original searches for same-second/millisecond titles. Review fixes: #9550, merged without rewriting its commit. ### Testing - Original regression run against unchanged production source: four failures covering channel/thread millisecond order, window flattening, and legacy pagination; all 218 focused tests passed after the initial fix. - Review regressions cover `007`/`12a` rejection, same-second edit selection in both input orders, and provisional replies before/after query completion. - Final head, including current main: `f3fdf3fa0fae6e495e6fc1b7b38f4834a1751d56`. - `just mobile-install` passed. The required push hook then passed `just mobile-check && just mobile-test` on that clean head, including formatting, analysis, the full Flutter suite, gateway recipe checks and the crypto-package suite. File-size and diff-whitespace checks passed. Draft pending simulator revalidation and human testing of the merged head. Re-run numbered 60-message channel and thread sequences, then a 200-message burst. Verify send order, the newest message at the end, same-second edits, and cached thread ordering as the query completes. Page backward and confirm the fully loaded history has no missing or duplicate messages. Scope note: during backward paging, the oldest loaded second can temporarily show gaps because relay pages select an ID-ordered subset of that second while rendering uses milliseconds. The next page fills those gaps; fully loaded history is complete. Boundary continuity needs a separate loading contract and remains deferred. --------- Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
0dca767e5e |
fix(acp): saturate observer frame size estimates (#9494)
## Summary Use `saturating_add` for the three additions in the observer frame-size estimate. `serialized_len` returns `usize::MAX` on a serialization error; ordinary addition can panic in debug builds or wrap in release builds. Saturation keeps that estimate above the plaintext limit, so the next event stays queued. This is defensive hardening. The current empty envelope contains only JSON-safe fields, so a normal event cannot trigger that serialization error. ### Related issue Follow-up to #9483, addressing [this review suggestion](https://github.com/block/buzz/pull/9483#discussion_r4569450055). No duplicate issue or PR found. ### Testing Manually ran `observer::packing_tests::publish_queue_drain_probe --exact --ignored --nocapture` on the rebuilt debug test executable. All 10,000 events drained in order into 30 frames within the byte limit, with zero pending bytes. To reproduce: ```sh cargo test -p buzz-acp --lib observer::packing_tests::publish_queue_drain_probe -- --exact --ignored --nocapture ``` Generated with AI assistance Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> Co-authored-by: Codex <codex@openai.com> |
||
|
|
9ccad95344 |
feat(mobile): accept mentions with Tab and send with Enter on hardware keyboards (#8733)
## Summary The mobile composer ignored Tab and Enter from hardware keyboards. Tab and Enter now accept the first selectable mention or channel suggestion while its picker is visible. Otherwise Enter or numpad Enter sends the message when attachment controls are closed. Enter leaves the draft untouched while an attachment surface is open. Tab leaves the draft unchanged while the picker is hidden or the field is read-only. A visible picker with no selectable row consumes Tab and Enter without sending. Only unmodified Tab accepts suggestions. Native attachment and emoji pickers own keyboard input until dismissal. Keyboard suggestion acceptance and sending use the same selection haptic as touch. Modified Enter and active IME composition retain normal text-field handling. Android IMEs can emit Enter as a key event too. Sending requires a mapped physical Enter key on Android, so scan-code-free IME Enter keeps newline handling. ### Related issue None found. ### Testing The composer widget regressions reproduce ignored Tab/Enter before the feature and an unintended send from Android IME Enter before its guard. The picker regressions cover Enter accepting a visible suggestion, Enter and numpad Enter retaining an Android draft while the attachment menu is open, and Tab leaving hidden or read-only suggestions untouched. They verify suggestion acceptance, error-only picker handling, native attachment popover ownership, modified Tab, sending, software Return and Android physical-key handling. Rapid Enter while member scanning is pending sends only once through the existing draft revision guard. Native validation and screenshots use an isolated Android API 28 ComposeBar harness at `09fb673f9`, with an observed send callback and a test-only native key injector. Physical Enter sends once and clears the draft; IME Enter inserts a newline without sending. Native validation of picker acceptance, visibility and read-only handling remains outstanding. ### Screenshots | Physical Enter sends and clears the draft | IME Enter keeps a newline without sending | | --- | --- | |  |  | | Mention suggestions | Tab accepts the suggestion | | --- | --- | |  |  | --------- Signed-off-by: John Tennant <jtennant@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Oliver <e78152627ea32fbacb070e5047afcfb8e409fa3343d9e618227baacca5b5e607@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
6f438202a0 |
Fix remote Huddle ending cleanup (#9376)
## Summary When the final Huddle audio connection was routed through another relay, owner cleanup removed the room without archiving the channel or publishing the ended event, leaving Join visible. Share committed-room finalization across local, remote, and pending-last-slot teardown. Retain the admission gate until finalization and recheck fenced owner authority under the database lock. Relay/database only; mobile history access is separate in #9375. Existing orphaned rooms are not retroactively archived. Existing clients remain responsible for disconnecting agents when the last human device leaves. ### Related issue Related: #4879 / #4918 concern discovery metadata after auto-archive. Searched open Huddle issues/PRs; no exact duplicate found. ### Testing This is the unchanged relay patch previously validated in combined commit `4ec349435151ca11ce92bd0ebe59b845b3465639`, split onto current main (whose intervening change is the relay version/changelog release). - Full PostgreSQL package lane: 1,376 initially passed; both initial failures passed after fixing local psql PATH and using actual joined/teardown completion in the test. Cleanup asserts archival and exactly one ended event. - Remote-control, pending-last-slot, and conditional archival regressions passed. - Full relay/database unit packages: 1,960 passed; five identity/archive and audit fixture failures report missing `artifact_heads` outside changed paths. - Relay/database all-target clippy and legacy desktop clippy/tests passed. Broader pre-push Rust groups passed after rerunning the load-generator group with a higher file-descriptor limit and four test threads (110 passed). - Independent relay review completed; formatting/diff/file-size guards passed. The split reused completed test evidence; no full rebuild was repeated solely for the split. Draft pending human/live-call validation. Start an agent Huddle, leave from the final human device, and verify its card stops offering Join, including connections routed through different relay servers. Not deployed. --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
921a05a379 |
fix(mobile): host Duo long-press menus in native sheets (#9536)
## Summary On unfolded Duo landscape, channel/DM actions and Solo details now open in a UIKit sheet above the app’s native controls, while retaining Buzz’s Flutter tiles, member rows, and grouped cards. Content drags take priority over sheet dragging; the native top bar still supports dismissal. The presentation-only engine starts only when an eligible sheet is presented, without account, camera, audio, or storage plugins. It is destroyed on dismissal; other iPhones pay no second-engine launch cost. The main app retains live permissions and actions, and the native sheet dismisses before opening follow-up screens. Cover-display and portrait postures retain the existing bottom sheet. Pending avatar requests are abandoned on dismissal, including after the display wait expires; the display timeout alone lets the download finish and cache. Confirmed lifecycle actions retire the invisible owner route before waiting for the relay. ### Related issue Follow-up to #8568. No duplicate sheet PR found. ### Testing - `just mobile-install mobile-check mobile-test`: clean analysis; 4,900 Flutter tests passed (71 skipped), plus gateway/package checks. - Mobile file-size and diff checks passed. - Earlier signed device preview built, installed, and launched; owner confirmed its scrolling. The later lazy-start and lifecycle fixes have not been rechecked on the device. - Unsigned iOS release build passed for `4ed94c6eb4` (Xcode 116.7s). - Journeys cover bridge permissions, copy/close callbacks, the content renderer, full profile-to-DM return, and reopening the list during a held archive. Avatar tests cover immediate cancellation, display timeout followed by cancellation, and timeout followed by completion and cache reuse; regression probes fail with the fixes disabled. UIKit drag handling still lacks automated interaction coverage. ### Snapshots Actual Flutter sheet contents at 540×580 points with sample data. These show the content layout; they do not show UIKit’s surrounding sheet or its animation. | Surface | Light | Dark | | --- | --- | --- | | Solo details |  |  | | Channel actions |  |  | --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> |
||
|
|
7b8066fb94 |
fix(mobile): keep the relay session across auth reloads (#9543)
## Summary `RelaySessionNotifier.build()` watched the whole `authProvider` but only read the signed-in status. Every `ref.invalidate(authProvider)` therefore rebuilt the session: the socket and all live subscriptions were dropped, and every screen resubscribed and republished presence and read state at once. An invite join invalidates auth twice for the same identity (3 sockets in about half a second), and each community switch does it again, producing a REQ burst the relay answers with `CLOSED rate-limited`. The session now watches only `(status, community.pubkey)` via `select`, so it still rebuilds when the user signs in or out, or switches identity while signed in. Relay URL and signing key changes continue to rebuild through `relayConfigProvider`, which is unchanged. ### Related issue None found. ### Testing - New regression test in `relay_session_test.dart`: with a connected socket and a live subscription, two auth invalidations for the same identity keep 1 socket, 0 disposes, `connected` status and a working subscription; a pubkey change then rebuilds to a second socket, and signing out disposes it. - The test fails on `main` without the fix (`Expected: an object with length of <1>`) and passes with it. - `just mobile-install mobile-check mobile-test`: format clean, `flutter analyze` no issues, 4909 tests passed (71 skipped), plus the native-secp256k1 package suite (27 passed). ### Before and after: first-launch invite join (simulator) Captured on a freshly erased iPhone 17 simulator with a one-use invite for each run, counting relay traffic for this identity in the first 5 s after launch. Before is `main` at `1a5c6939c`; after is this branch at `8beda6aea`. | | Before | After | |---|---|---| | Relay sockets opened during the join | 3 | **1** | | Relay frames in the first 5 s | 72 | 57 | | `OK false` for kinds 20001/30078 | 2 | **0** | | REQs refused with `quota_exceeded` | 16 | 6 | | Message posted after the join arrives live | yes | yes, on the same socket | The session rebuild is fixed: the join keeps one socket and its subscriptions. The original target of fewer than 50 frames in 5 s is not met. The remaining burst is about 31 separate single-document kind 30078 reads (`limit:1`, `authors` = self) at about +1.1 s, and all 6 remaining `quota_exceeded` refusals are among them. Those reads don't come from session rebuilds, so they'll be handled in a separate change rather than in this PR. - Not yet done: a run on a physical device of the first-launch join flow. Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz> |
||
|
|
65b566ca72 |
feat(deletion): clean up media for users and owned agents (#9365)
## Why
User deletion must remove uploads by the user and their owned agents
while preserving files uploaded by anyone else. Attribution can span
communities and survive only in storage, so cleanup must combine
database and storage evidence.
## What
Add one media handler used by both the direct `user-deletions
media-batches` command and the persisted user-deletion workflow. Preview
is read-only by default; deletion requires `--delete`.
The workflow now always runs `gate_user` → `purge_media` → community
stages. The gate and community handlers remain placeholders. Media
failure stays on the same stage for retry; a saved completed media stage
is not executed again on restart.
## How
- Resolve the human and directly owned agents once across communities.
Sharing within that target set does not protect a file.
- Combine candidate discovery from `media_uploaders` and upload audit
history with a sharing check for those hashes. Check outside uploaders
across all communities. Storage-only candidates receive the same
database check in batches.
- Add four nonunique indexes for uploader and hash lookups. Current
membership cannot safely filter historical discovery: departed members
may have no remaining membership row.
- Scan `_uploads/` for candidates, then candidate claims for outside
ownership. List blob and thumbnail versions by each selected `{hash}.`
prefix. A separate `_meta/` listing preserves sidecar coverage when no
matching claim or current membership remains. There is no whole-bucket
listing.
- Finish all discovery before deletion. Read historical claims using
exact `versionId` values. Delete exclusive file versions and markers,
with upload-attribution objects last. Remove target uploader rows after
storage processing succeeds. Shared storage versions and outside
uploader rows remain.
- Stream one JSON document with file identity, keep/delete status,
versions, and outcome counts. Remove per-file owner queries and owner
arrays. Workflow stdout remains inspection JSON; media reporting goes to
stderr.
Database/inventory pages hold at most 500 rows. Storage listings use at
most 1,000 entries per page and 100,000 pages per listing. A disposable
in-memory inventory has a 128 MiB accounting budget and a 250,000-entry
cap, including candidates, filenames, versions, and listing markers.
Accounting includes string bytes, inline data, and a conservative
allowance for tree/allocator overhead; it is not a process RSS limit.
This removes the SQLite dependency without a security-policy exception.
Large jobs may reach capacity sooner than with the former 1 GiB disk
inventory. Exceeding a discovery limit aborts before mutation; no
truncated inventory is used for deletion.
Migration 0092 and the desired schema add the same indexes. The
migration builds missing indexes under short lock/statement budgets and
verifies existing definitions. Large deployments can prebuild
concurrently using the procedure in [the executor
guide](docs/operator-user-deletion-executor.md). Existing relay writes
remain compatible. A stale workflow test call from the merged main
branch also receives its required run-cause argument.
## Risk
This performs real storage deletion. Writers must remain stopped; the
placeholder gate does not prevent uploads. Immutable version IDs are
required for exclusive objects. All results report
`account_erasure_complete: false`. Existing synthetic progress saved
under the older gate-to-community sequence is not migrated into the new
sequence.
Shared storage claims and audit history remain. They can continue
protecting a blob after both uploaders leave; claim retirement is
separate work. Metadata namespace scans remain proportional to their
sizes. Bare blobs with no surviving attribution cannot be assigned to a
user.
## Testing
Before committing the replacement as
`38c60be7f6c3ee3f6942ab89858ce42e2a536c5d`, exercised the actual
`buzz-admin user-deletions media-batches` command against a fresh local
PostgreSQL database and versioned MinIO bucket. Preview preserved all 23
versions and all database rows. Deletion removed 14 exclusive versions,
preserved nine shared/unrelated versions, and removed only five target
uploader rows. Retry removed no further versions; events and
publications remained unchanged.
A standalone probe of the production inventory reached the default byte
budget after 243,148 short-key versions or 90,933 versions with 1 KiB
keys. Peak process RSS was approximately 108 MiB and 124 MiB on macOS;
these measurements describe the probe, not total command memory.
Manually removed `versionId` from the production adapter's request and
ran `cargo test -p buzz-deletion --lib
historical_claim_protects_shared_file_and_bad_claim_aborts_before_deletion`.
The regression failed because the historical outside uploader no longer
protected the file. Restored the adapter before final validation.
Earlier live-lab evidence used the direct command at
`633fdb2a48dce64f904c0077689704f136c722c1`, before this query/storage
update: 38 exclusive files and 300 versions were deleted; 24 shared
files and 10 unrelated files remained. Authenticated downloads returned
404 for all deleted originals and matching hashes for all preserved
originals. That live deletion was not repeated for this update, and does
not attest concurrent-upload safety or complete account erasure.
## Bigger picture
Media tracking:
[BUZZ-415](https://linear.app/squareup/issue/BUZZ-415/delete-user-and-owned-agent-media-and-storage-objects).
Deleted-image UI is separate work:
[BUZZ-727](https://linear.app/squareup/issue/BUZZ-727/show-a-clear-unavailable-state-for-deleted-images-in-chat-and-image).
Related: #9353. This replaces the media portion of #9329 and #9355;
those branches remain intact.
Generated with Codex
---------
Signed-off-by: Ravneet Arora <rarora@squareup.com>
Signed-off-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: salad <7be12d8db721c3c6d5feccf11f8389e39c6b4b717dc6aa7ce30fc80e45e8788f@buzz.block.builderlab.xyz>
mobile-v1.4.0-rc.1
|
||
|
|
63f1d6918c |
Refuse opening a private channel that has other members (#9307)
## Summary - Turning a private channel open changes who can read and join it for everyone who joined while it was private. The relay now refuses that change when the channel has, or once had, any other member. - Removed members count too, because their posts stay in the history that opening would make public. - Opening is still allowed when every member, current or removed, is the person making the change or one of that person's agents. A Solo chat that holds only its owner and the owner's agents is the main case. - Changing an open channel to private is unchanged. - A refused change stores nothing. The sender gets: `invalid: a private channel with other members cannot be made open; create a new open channel instead`. ## Details - The check is in the channel metadata edit path (kind:9002), for every channel type. An agent counts as the sender's own only when its owner is recorded for it through an owner attestation (NIP-OA). A member who has never signed in, or an agent with no recorded owner, counts as another member. - The check runs under the membership lock that a visibility change already takes. Members cannot be added between the check and the commit. - Disclosure levels for agents do not exist yet, so all of the sender's own agents may stay when the sender opens a channel. When levels land, restricted writers will need to be excluded. - `update_channel` in the store does not apply this rule. Only tests call it. User edits go through kind:9002. Both doc comments say so. - Old desktop builds can still send an opening edit. They now get the refusal as an error. - `NOSTR.md` documents the refusal on the kind:9002 row. ### Related issue None found. The client UX is in https://github.com/block/buzz-app/pull/3145. ### Testing - New Postgres tests in `edit_metadata_postgres_tests.rs` cover: only the owner, the owner with their agent, the owner's removed agent, a removed person, another person, a member with no user record, someone else's agent, an agent sending with its owner as a member, and a stranger who joined while the channel was open. - Each refused case checks that the channel stays private and nothing is stored. The tests fail when the check is removed, when it skips removed members, or when the user join is made inner. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
df21064800 |
feat(auth): tolerate client clocks up to 120 s off (#9485)
Lets clients whose clocks are up to 120 s off sign in to NIP-FI communities and stay connected. **Relay** - NIP-42 AUTH and NIP-98 HTTP Auth accept `created_at` within ±120 s, using a shared `buzz_auth::TIMESTAMP_TOLERANCE_SECS`. This covers relay login, audio admission, bridge, admin, invites, NIP-FI policy and Git. - `DEFAULT_REPLAY_TTL_SECS` goes from 120 to 250 s: a 2 × 120 s window, plus 1 s for the inclusive whole-second bounds, plus a 9 s budget for the clock difference between relay pods. A compile-time assert checks the arithmetic. The 9 s is an operational assumption about NTP-synced pods, and the doc comment says so. No `deploy/` override exists. - Media (kind 24242): - Both modes accept `created_at` up to 120 s in the future and an `expiration` greater than `now − 120`. - Strict: the 120 s age limit and the 60 s lifetime cap. - Permissive: keeps its 3600 s age allowance and has no lifetime cap. - `buzz-auth` and `buzz-media` read the time through a `wall_now()` that tests can pin (a `#[cfg(test)]` thread-local), so boundary tests are exact. - Git transport: comments only. It still reuses one proof per session, so the reuse window now matches ±120 s. **CLI** - The desktop-provider lane asks the desktop app for the assertion every time and keeps no copy, so the desktop's cache owns each token's deadline. It looks the token up again after signing and sends that one, so a provider may hand out a new token on every call. - The direct-mint cache sets its deadline to `min(request_start + (exp − iat), receipt + (exp − local_now))`, on a monotonic clock. `request_start` is when the attempt that got the reply was sent, not the start of the retry loop. - An assertion with no local lifetime left is never returned or sent. The cache asks again, up to 3 times, then fails with an auth error that points at the computer's clock. An assertion without a readable `iat` is refused. `iat` may be fractional (a NumericDate); the lifetime is `max(0, floor(exp − iat))` whole seconds. **Cache reuse (CLI, Flutter, iOS):** each cached token records when it arrived on both the monotonic and the wall clock. It is reused only while `max(monotonic elapsed, wall elapsed)` since arrival is under its budget (`refresh point − receipt`, on the monotonic clock). A negative wall elapsed counts as 0. The monotonic clocks used here stop while the device sleeps, so the wall clock ends reuse after a sleep; setting the wall clock back can't stretch a token, because the monotonic bound still applies. **Mobile** - Flutter `HostedRelayAuth`: the same lifetime rule, on a monotonic clock, for async acquisition and for the synchronous `cachedHeaders` media path. A token with no local lifetime left is never sent: issuance is retried up to 3 times, then fails as `unavailable`. A token without a readable `iat` fails as `invalidResponse`. - Flutter refusal hint: the account client reads `Date` when a 403's headers arrive, before the body (`boundedHttpResponse` gains an `onHeaders` callback). The 403 stays `AccountFailure.denied` even if its body is then lost, late or too large. The hint is stored with the refusal it explains (`HostedRelayAuth.failureClockHint`), cleared when that community next gets a token or the account session changes, and left alone by other communities' issuance. The account client records a 403's hint only for the acquisition whose own request was refused (`BuilderlabAccountClient.observingRefusals`), so an unrelated account call, such as the organization key backup, never supplies a sign-in's hint. When the offset is over 115 s, the reconnect and organization banners add "Your device's clock looks about N minutes off, which can cause this. Check your date and time settings." - iOS `BuzzRelayAssertionIssuer`: the same lifetime rule, on `systemUptime`. An assertion without a readable `iat` is refused. - iOS push enrollment: a new grant's window starts 120 s in the past, so `not_before = now − 120` and `expires_at = now − 120 + lifetime`. A fast phone then neither signs a `not_before` the gateway hasn't reached nor goes over its 30-day maximum. A resumed journal resubmits the installation expiry it already attested, byte for byte. The delegation, which is signed fresh each time, expires at the earlier of that expiry and `not_before + lifetime`, so a journal written by an older client on a fast phone still gets a grant the gateway accepts. The saved grant records the delegation's expiry. - Flutter and iOS already sign a fresh proof with a `nonce` on every issuer attempt, so their retries needed no change. **Specs:** NIP-FA proof bounds (120 s old / 120 s future), plus NIP-FI Git (`±120s`), media freshness, the media read residual and the media trace row. `desktop/` is untouched. Not exercised live: Git clone/push, audio join and push delivery with a skewed client clock. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
5a45b2cdbe |
docs: name the required stop as a relay build, not a release (#9577)
## Summary `docs/trigger-retirement-deployment.md` (added in #8326) named "the first relay release that contains #8325" as the required stop before migrations 0089–0091. Relay deployments run images built from main, and no tagged relay release contains #8325. So the doc now names any relay build at or after `68785206` (the merge of #8325) as the stop. It also tells deployments on a tagged release, such as `relay-v0.3.0`, to move to a stop build first. This is the follow-up promised in the #8326 review thread. ## Changes - `docs/trigger-retirement-deployment.md`: "stop release" becomes "stop build" throughout. The required-stop section names the commit. The `0089_retire_created_at_floor.sql` comment still says "release". That migration has merged, and editing it would change its sqlx checksum, so it stays as is. ## What got simpler The procedure no longer depends on a release being cut. Operators follow the image they already deploy. ## Testing Docs-only. No code or migration changes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
598fcae0cd |
buzz-db: drop the created_at floor, community write-fence and migration-only NIP-RS triggers (contract) (#8326)
> **Combined contract PR.** This PR now carries all three trigger drops that were stacked as #8326 → #8323 → #8211. Each drop's prerequisite app change has already shipped to production, and none of them depends on another, so they ship as one release with one migration per drop: > - `0089`: `events_created_at_floor` (this PR's original scope, BUZZ-316; phase 1 #8325 is on prod) > - `0090`: the universal community write-fence triggers and functions (from #8323, BUZZ-315; app admission #8219/#8318/#8322) > - `0091`: the migration-only NIP-RS, mention-live and mesh-purge triggers (from #8211, BUZZ-312; prerequisite #8128) > > #8323 and #8211 keep their full write-ups. The commits are cherry-picked unchanged except for the renumbering commit at the tip. #8211's post-rollout cleanup SQL still runs after this deploys. ## Summary Phase 2 of BUZZ-316. This is a destructive contract change. Phase 1, #8325 (merged), added the insert-time application floor check. After phase 1, the app check at every channel-bearing `INSERT INTO events` is the only `created_at` floor guard. This PR removes the database backstop and everything that existed only to verify it: - **Migration 0089** drops the deferred constraint trigger `events_created_at_floor` on `events`. That also removes its partition clones. It then loops over `pg_partition_tree('events')` to drop any child copy that was attached separately, and drops the `events_created_at_floor_guard()` function. Every drop uses `IF EXISTS` and none uses `CASCADE`. The migration sets `lock_timeout` to 5s. Migration 0021 stays byte-for-byte unchanged. - **Desired state:** removes the function file, its `schema.sql` include, the trigger in `schema/triggers/events.sql`, and the eight child-copy drops in `scripts/reconcile-schema-after-pgschema.sql`. Both boot paths stay catalog-equivalent, and `admin_schema_parity_between_desired_state_and_migrations` passes. - **Runtime:** deletes `verify_floor_guard_catalog`, `verify_floor_guard_behavior`, and the boot wrapper that gated the probe on them. Also deletes the writer-pool `buzz.created_at_floor` GUC arming and its `CreatedAtFloor` connection-setup metric step. The setup-series ceiling drops from 71 to 54. `spawn_fence_probe` becomes synchronous and returns `bool`, so the relay's startup error branch goes away. `CREATED_AT_FLOOR_SECS` (960s) stays because the app check and the fence wall both use it. - **Kept:** every other fail-closed probe check. That covers writer-pool isolation and timeouts, partition topology, the activity scan, the heartbeat/epoch checks, and closing on probe error. No other trigger, function, FK, or tenant fence is touched. ## Deploy gate (required) **Required stop:** the new `docs/trigger-retirement-deployment.md` names it (docs/database.md Rule 5). Relay deployments track images built from `main` and no release is being cut, so a docs follow-up rewords it as any relay build at or after `68785206` (#8325's merge). `relay-v0.3.0` has the 0090/0091 prerequisites but not #8325, so a deployment on it must move to such a build first. The doc also covers the auto-migration-off order, the pgschema parent-trigger note, the #8211 cleanup, and rollback. 1. Phase 1 must be running on **every** writer pod and job, with no rollback expected. Pods that are already running never recheck the guard, so a rolling deploy on its own is not enough. 2. Stop out-of-band writers: direct SQL, COPY, restores, seed scripts, and anything that prepares transactions. 3. Hold the replica breaker closed from before the drop until replay catches up and the new scheme is verified. 4. Run the migration off-peak. `DROP TRIGGER` takes `ACCESS EXCLUSIVE` on `events` and every partition, so expect `events` reads and writes to stall for up to the 5s `lock_timeout`. A lock timeout aborts the migration transaction and is safe to retry. Under auto-migrate, the pod fails boot, restarts, and retries. Mixed-version behavior: - **A phase-1 pod that restarts after the drop, default config (`migrate.autoMigrate: true` in the chart):** sqlx finds applied migration 89 missing from its embedded set and returns `VersionMissing(89)`. Boot is fatal and the pod **crash-loops**. A binary rollback is therefore unsafe once 0089 has run. - **The same pod with auto-migrate off:** `verify_floor_guard_catalog` fails, the fence starts closed, and the relay degrades the `ReplicaFenceProbe` startup step. It keeps serving, with cursor reads on the writer. - **This binary against a database that still has the trigger:** boots and runs. It neither requires nor arms the guard. ## Tests `crates/buzz-db/src/runtime/tests/floor_retirement.rs` adds four PostgreSQL tests. CI's nextest filter picks them up through `postgres_tests::`: - the migration drops the parent trigger, its partition clones, and the function, and leaves every other trigger and FK unchanged; - the migration removes a separately attached child copy and can safely run twice; - the desired-state catalog has no floor objects; - the production writer pool no longer arms the GUC, and the probe runs against the retired schema. All four fail when the change is reverted (0/4 pass) and pass with it (4/4). Four tests that only exercised the trigger or the probes are deleted. The outbox durable-failure regression is kept: it now injects an isolated `BEFORE INSERT` failure instead of arming the floor. The phase-1 floor fixture no longer disables a trigger that no longer exists. It still asserts that no enabled floor trigger can mask the app check. With the trigger gone, the floor source policy (`every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it`) is the only guard against a writer that skips the app check or rewrites `created_at`/`channel_id` on an existing row. Phase 1 already makes it scan every crate's `src`. This PR closes two matcher gaps the trigger used to cover: - `UPDATE events SET(created_at, …)` written with no space before the parenthesis; - `INSERT INTO events … ON CONFLICT … DO UPDATE SET channel_id = …`, which names no table but can re-home an existing row below the floor. Each `DO UPDATE` is bound to the INSERT it belongs to, so a watermark upsert that sets `created_at` next to a guarded events insert (the replaceable-event writer's shape) is not flagged. Both gaps have negative fixtures, plus controls for a non-floor-column upsert, `DO NOTHING`, and the watermark shape. The policy also now fails closed on SQL the per-function literal scan could not attribute to a writer (`event_floor_policy_fails_closed_on_sql_it_cannot_attribute`): - `include_str!` is expanded from the file it loads, and `concat!` becomes one literal, with an `{opaque}` placeholder for each non-literal argument. Every delimiter (`()`, `[]`, `{}`) and path prefix (`::core::concat!`) is recognized. - Every SQL literal is checked on its own as well as per function. Anything the policy cannot attribute is a violation: a write target or `SET` column that is a placeholder (`concat!` or `format!`); a `SET` list of floor columns whose `UPDATE` is in another literal; an `UPDATE events` or `DO UPDATE` whose `SET` list continues in another literal or argument (empty, or an item with no `=`, as in `format!("UPDATE events SET {}", …)` or `QueryBuilder::new("UPDATE events SET ").push(…)`); an `INSERT INTO` with no table after it in the literal, or an events INSERT with a placeholder tail; `events` written by `MERGE INTO`/`COPY`; and event-write SQL in a `const`, `static`, or macro body outside any function. A placeholder in a `WHERE` or a value is allowed, so the retention deletes (`concat!` around a predicate macro) and the tenant-severing `UPDATE {table} SET community_id = NULL` pass. - An `include_str!` whose path is not one readable literal and any sqlx `query_file*!` macro are violations. Nothing uses `query_file`. - `PREPARE TRANSACTION` in any production literal, including a dangling `PREPARE`, is a violation (see below). - Function slices are cut to their own item, so a trailing `const` is judged at item level instead of being credited to the function before it. **Prepared transactions.** The fence used to bound a prepared (2PC) transaction by `pg_prepared_xacts.prepared`. That only held because the deferred trigger checked its rows at `PREPARE`; the insert-time check runs earlier, at a time `pg_prepared_xacts` does not expose. So the probe no longer folds `prepared` into the wall: any prepared transaction fails the sample closed (`ProbeError::PreparedTransactions`). No supported writer prepares transactions (now source-policy enforced) and `max_prepared_transactions` defaults to 0, so in supported deployments this never fires. `cluster_global_sample_writer_fails_closed_on_prepared_transaction` asserts 2PC is unavailable at the default setting, and asserts the fail-closed error when the server allows it. CI runs only the default branch; the 2PC-enabled branch and a check-removed falsification run are pinned from the Blox gate. The prepared count is cluster-wide, like the activity scan. ## Verification Head `6ef31ef113` (before the fold). On Blox, fmt, clippy and buzz-db unit pass, and the full buzz-db PostgreSQL lane passes except `media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`, which fails only on the Blox host (it passes in CI). The two `floor_retirement` tests were fixed after that run, so they were rerun on their own and pass at this head. ## What got simpler The change is net −600 lines. Gone are one function, one parent constraint trigger plus its partition clones, two startup probes and their scratch helper, one boot wrapper, the per-connection GUC setup, one metric step, and an async startup branch that could no longer be reached. ## Notes - Migration number: `0089`, the first free number after main's `0088` (workflow run cause). The fence drop (`0090`) and NIP-RS drop (`0091`) follow it in this PR. - Restack: `floor_retirement.rs` now snapshots at `0088` and compares after `0089` alone, then runs the later migrations. The held-writer media prebuild test in `migration.rs` now stops at `0088` while the writer is held, then rolls the writer back before applying the rest. Otherwise a later `DROP TRIGGER` migration in the stack waits on that writer's lock (`55P03`). The floor policy's `SET` list ends at a top-level `WHERE` or `RETURNING` (a subquery's `WHERE` no longer hides later assignments). An `UPDATE` `SET` list that runs to the end of its literal fails closed, and an open events upsert list is read on through later literals (`QueryBuilder` pushes). `events_p*` partitions count as `events` in every check. `replacement_scope!` now leaves `WHERE` to its callers so the policy can see the supersede `UPDATE`'s list end; the SQL is unchanged. - Pre-existing, unrelated to this change: three `buzz-relay` `group_state_postgres_tests` hit `PoolTimedOut` on a clean base too. --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
db7d37107a |
Keep community deletion working across a new tenant table's migration (#9304)
## Why The deletion engine compares the live set of `community_id` tables with an exact list. An expand migration that adds a tenant table therefore breaks community deletion for every community on the release that is deployed. It breaks again after a rollback to that release. #9301's migration 0087 adds three such tables. I reproduced this with the actual `buzz-admin` from #9301's merge-base (`838976d6e`): - Once 0087 is applied, that binary blocks every deletion with `catalog drift (missing=, unknown=identity_retirement_actions,…)`. - A request it approved before 0087 then fails permanently on #9301 too, with `approved structural catalog drifted before fencing`. A short gap between migrating and deploying doesn't make this compatible, so this release has to ship first. ## What - **`PENDING_SCOPED_TABLES`**: tables a later migration adds (the three identity retirement tables). - The catalog check accepts each of them whether it exists or not. - Purge and logical verification handle every one that is present. - The lookup runs inside the transaction that uses it, under the shared schema/destruction lock that migrations take exclusively. - **`APPROVAL_FORWARD_TABLES`**: a bounded exception to the approved-catalog check in `validate_approved_schema`. - A live table missing from the frozen inventory is accepted only if it is on this list. The list names only tables this binary purges and verifies. - A removed frozen table is still rejected before fencing, and so is any other addition. - The frozen manifest and digest are never rewritten. - Unlike `EXPECTED_SCOPED_TABLES`, a table stays on this list after the release that ships it moves it into the required catalog. - **`docs/database.md`**: - The table row for a new tenant table now requires this precursor release instead of "keep the gap short". - The checklist adds the matching step. - A paragraph documents the approval exception. #9301 is rebased onto this branch: it moves the three tables to the required catalog, empties `PENDING_SCOPED_TABLES`, and keeps `APPROVAL_FORWARD_TABLES`. ## Evidence All local runs, at head `21df5ece3` (on main `dd9da3ac6`). **Postgres lane** (`scripts/postgres-test-run.sh -p buzz-db -p buzz-deletion --lib --tests`): 782 passed, 258 skipped. **Store test** `pending_scoped_tables_are_optional_purged_and_verified`: - The catalog is accepted with the tables both absent and present. - An unknown table fails. - Purge deletes one target row per pending table. - A straggler row fails verification and names its table. - The bystander's rows survive. **Executor test** `approval_before_an_expand_migration_completes`: - It is in `external_infra_s3_tests` and needs Postgres, Redis and S3. CI doesn't run it; I ran it locally against MinIO. - It drives `execute_claim` on a request approved before the tables exist, through `RetentionPending`. - Target rows are gone and bystander rows survive. - An unlisted added table blocks the request before fencing. - A request whose frozen inventory includes the pending tables is blocked before fencing once those tables are dropped, with `approved structural catalog drifted`. - The test runs in a scratch database of its own, because it changes the catalog. **Falsification**: each of these mutations makes the executor test fail. - An exact approval comparison (the approved-legacy test fails too). - Swapping the forward list for `EXPECTED_SCOPED_TABLES` (the approved-legacy test fails too). - Purge skipping the pending tables. - Removing the catalog tolerance. - Ignoring removed frozen tables. The other S3 executor tests: `drained_stage…` and `final_storage…` pass. `approved_stage_allows_post_inventory_row_churn_before_fencing` fails here, and it fails the same way on `838976d6e`. **CLI exercise**, kept separate from the store tests. These are real `buzz-admin` binaries on a scratch database with local Redis and MinIO: - R0 is `838976d6e` (pre-feature), R1 is this branch, R2 is #9301 rebased onto it. | Step | Result | |---|---| | R0 migrates to 0086, then submits and approves c1, c2, c3 and c8 | `approved`, with 0 of 36 frozen tables being retirement tables | | R2 migrator applies 0087 and 0088 | at 88 | | Retirement-shaped rows inserted for targets c1, c2, c5, c6 and bystander c4 | 3 rows each | | R0 runs c8 | blocked, unknown identity retirement tables (below the floor) | | Unknown `compat_unknown_scoped` table present: R1 runs c3, then R2 runs c3 | both blocked (`unknown=compat_unknown_scoped`), `fence=none` | | R1 runs R0-approved c1 | `retention_pending` | | R2 runs R0-approved c2 | `retention_pending` | | R2 approves c5 (3 of 39 frozen tables are retirement tables), R1 runs it | `retention_pending` | | Rows afterwards | c1, c2, c5: 0; bystander c4: 3 | | R2 approves c6, the three tables are dropped, R1 runs c6 | blocked, `approved structural catalog drifted before fencing`, `fence=none` | **R1 relay restart after 0087**, with `BUZZ_AUTO_MIGRATE=false`: the relay starts, readiness returns 200, and it serves NIP-11 for a configured community. With auto-migration on, the same restart fails with `migration 87 was previously applied but is missing`. That is the existing Rule 5 limitation, and this PR doesn't fix it. Operators keep auto-migration off through the rollout. **Agent review**: an independent review found one blocker. The executor test changed the shared test database's catalog and left the tables behind. It now uses its own database. The review's optional findings on doc wording, checklist placement and removed-table executor coverage are also addressed. ## Limits - The migration of a later release still has to be applied with the documented migrator, which holds the schema lock. - A human has not tested this yet. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Philip Azar <pazar@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0c409e7a6a |
docs: design Android push notifications (#9555)
Design docs for Android push notifications, matching what iOS has today: DM and mention notifications with real message text, grouped per conversation, and tapping one opens it. - **[ADR 0004](docs/adr/0004-push-gateway-hides-device-platform.md):** one push gateway per app distribution serves both platforms, and the relay can't tell an Android installation from an iOS one. - **[ADR 0005](docs/adr/0005-android-push-enrollment-attestation.md):** Android enrollment requires hardware Key Attestation on a locked bootloader, verified offline. Later installation calls are signed with the attested key. - **[ADR 0006](docs/adr/0006-android-notifications-run-app-dart-code.md):** Android builds notifications with the app's own Dart code in a background engine, instead of a native port of the iOS extension. - **[PLANS/ANDROID_PUSH.md](PLANS/ANDROID_PUSH.md):** the spec, plus the tickets it splits into. - **CONTEXT.md:** defines *wake signal* and *push gateway*. The privacy model stays the same: pushes carry a fixed wake signal and nothing about any event. ### Validation A throwaway [prototype](https://github.com/block/buzz/tree/prototype/android-push-headless-dart) checked ADR 0006 against FCM's ~10 s handler budget. It started a headless Dart engine from a killed app, signed in to a local relay and updated a placeholder notification with the real text. | Device | Wake to real text (median, 12 cold runs) | Memory (PSS) | |---|---|---| | Pixel 9a | 0.51 s (worst 0.54 s) | ~45 MB | | Emulator, CPU slowed ~8x | 0.80 s (worst 1.05 s) | ~57 MB | The relay ran on the same machine, so real network latency is still unmeasured. With an unresponsive relay, the placeholder notification stayed and the native watchdog ended the handler. This PR changes documentation only, so no app run applies. ### Regressions None. This PR adds documentation only and changes no behavior. The design keeps iOS push working through the rollout, and the relay learns no more about devices than it does today. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
9398918fa5 |
feat(push-gateway): accept deliveries on a platform-neutral route (#9557)
First slice of the Android push plan ([design PR](https://github.com/block/buzz/pull/9555)). The push gateway should serve every platform from one delivery route, so the relay never learns an installation's platform (see ADR 0004 in the design PR). ### What changes - The gateway accepts deliveries at `POST /v1/deliveries`. `POST /v1/deliveries/apns` keeps working unchanged as an alias until relays have moved over. - `BUZZ_PUSH_GATEWAY_DELIVERY_URL` accepts either path. The deployment guide and NIP-PL describe `/v1/deliveries` as the route to use. `.env.example` and the compose template stay on `/v1/deliveries/apns`, because released relays (`relay-v0.3.0` and older `sha-` images) refuse to start with the new path even with push disabled, and the public gateway doesn't route it yet. A later change moves them over. - Signature binding: the gateway already verified only the method and the signed URL's path (not scheme, host or port). It compared that path to a constant. It now compares it to the route the request arrived on, so a request signed for one route is rejected on the other. Each route accepts only requests signed for its own path. - The lease `transport` value, priority classes and the delivery request body are unchanged, and nothing about the device platform reaches the relay. ### Regressions None expected. iOS keeps working: the alias route behaves exactly as before, and relays configured with the old URL keep signing and sending to it. The signed path check is equivalent on that route, since it now compares against the same path the old constant held. Rollout order matters. Don't point a relay at `/v1/deliveries` until (1) its gateway runs this change and (2) for `push.buzz.xyz`, the edge path allowlist in front of the gateway admits `/v1/deliveries`. Today that edge answers `403 RBAC: access denied` there. The relay also needs a build that includes this parser. An old gateway's 404 or the edge's 403 is a permanent failure for the relay (on a retry, it counts as replay-terminal), so those notifications are dropped, not retried. ### Validation - Gateway delivery tests are table-driven across both routes: path-not-origin binding, signed URL modifiers and non-HTTP schemes, request queries, method and path routing, and new cross-route rows (signed for `/v1/deliveries`, sent to the alias, and the reverse, both rejected). - Relay config tests cover both paths over HTTP and HTTPS, plus rejected variants (trailing slash, query, fragment, credentials, other paths, HTTPS ports). - Ran the gateway crate's tests, the relay crate's unit tests (single-threaded, because the default parallel run of the whole lib hung in untouched tests waiting on shared env locks), formatting and clippy for both crates, and the repository's pre-push checks. - Relay tests that need Postgres were not run locally. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
4ec5efa936 |
fix(mobile): read a Solo chat through its newest message on open (#9515)
Opening a Solo chat now reads it through its newest message, the way opening a DM already does. Before, a Solo chat (a `stream` placed under Solo) was read row by row: holding still at the bottom wrote only the channel catch-up mark, and that mark skips messages addressed to the reader (p-tags, broadcasts) and replies. Each such message needed its own row to be fully on screen. Agent messages in Solo chats tag the reader all the time, so the Solo row stayed bold after the reader opened the chat, jumped to the oldest unread and scrolled around. A Solo chat is all for the reader, like a DM, so it now takes the same open read. The jump to the oldest unread still works: its target is captured before the open read is written. ### Regressions - Opening a Solo chat with a long unread backlog marks it all read even if the reader doesn't scroll through it, as DMs already do. The jump-to-oldest-unread button still appears on that open, so the backlog stays reachable. - No extra relay traffic: it reuses the read mark path DMs use (local first, synced behind the existing debounce), so newer messages loaded while the chat is open advance the mark the same way they do in a DM, and only while the page is in front and the app is in use. ### Validation Added tests: - `opening a Solo chat reads the whole chat`: an agent message that tags the reader sits above the viewport; opening the chat reads through the newest message and the addressed message is no longer unread. Fails on main (no channel mark is written). - `opening an archived Solo chat reads a tall newest mention` (was `reading the bottom of an archived Solo chat ...`): now expects the open read. - Removed `reading the bottom of a Solo chat reads a tall newest inline reply mention`; the open-read test covers it. The tall-newest-mention rule for ordinary channels keeps its own tests. Full mobile check and test suite pass. ### In the app Simulator (iPhone 17 Pro, iOS 27) against a local relay with two synthetic identities: a Solo chat (`buzz.solo`) where a second member posted 17 messages, two of them @mentioning the reader, one tall and above the fold. Before (main): open the Solo chat, tap the up arrow, scroll, go back. The row stays bold. https://github.com/user-attachments/assets/8adf8131-ca0e-499c-ad7c-b45c0f903360 After: the same steps clear the row. The up arrow still appears and jumps to the oldest unread. A DM still reads on open, and an ordinary channel with an unread @mention above the fold stays unread after opening it and going back. https://github.com/user-attachments/assets/ec88914a-a757-47cc-901b-d7cc6a658448 Limitations: run on a local relay, not a hosted community; the Solo chat was created by publishing the same kind:9007 tags the app sends, not through the new-chat flow (which needs an owned agent). buzz-review-completed Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
c16dac2324 |
fix(mobile): keep the Solo header's agent portrait while its roster reloads (#9512)
Opening a Solo chat made the header's agent portrait flash away and come back. The header draws its portraits from the chat's member list. That list (`channelMembersProvider`) is auto-disposed when the page closes, so every open refetched it from the relay. Until the fetch landed, the Solo header fell back to the viewer alone, then swapped to the agent once the roster arrived. The header now watches `latestChannelMembersProvider`: the last roster loaded in this relay, account and channel scope (the existing `watchLatestChannelMembers` snapshot), or before any load, the channel list's member snapshot. The fresh fetch still runs and replaces it when it lands. ### Before / after Opening a Solo chat, slowed 4x and cropped to the header. https://github.com/user-attachments/assets/f42e500e-8b0c-446d-b47c-68b58e98d5d5 https://github.com/user-attachments/assets/b8e63e39-c6ee-4fd6-b195-6327b709b316 ### Validation - Added a step to `Solo and channel headers show bounded roster portraits`: with the roster fetch held pending, the first frame of a Solo chat shows the agent portrait. It fails on main (the header shows the viewer) and passes with the fix. - Full mobile suite and `flutter analyze` pass. One unrelated test (`message_skeleton_geometry_test.dart: image null matches preview at 320.0`) failed once in the full run and passes on its own. - iOS simulator (iPhone 17 Pro, debug build, internal community): opened and closed a Solo chat repeatedly from Messages, before and after. Before, the first frame shows the viewer's avatar; after, the agent's portrait from the first frame, with the rest of the open and back flow unchanged. ### Regressions None expected. The header shows a roster from the last load (or the channel list) for the moment before the fresh fetch lands, the same staleness the page's names and author visibility already accept through `watchLatestChannelMembers`. No extra relay reads; the snapshot is scoped to the relay, account and channel, so another community or account never sees it. buzz-review-completed Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
75d78eab68 |
perf(mobile): pulse the Solo working dots at 12 fps on a shared clock (#9554)
Each working row on Home (the three pulsing dots next to a Solo chat whose agent is working) ran its own 60 fps animation. So an idle Home with any working agent produced a frame on every vsync. Painting the dots is cheap. The frame itself is not: each one costs the app, backboardd and the kernel together, and on the iPhone SE that adds 8.6% of battery per hour over static dots. The rows now step from one shared clock: 17 steps per 1400 ms cycle (about 12 fps), with the same cosine wave. All rows read the same step, so they stay in phase and repaint in the same frame. The clock runs only while a row is visible with `TickerMode` on and the app is in the foreground, so a Home with no working rows, a covered or off-screen Home, or a backgrounded app has no timer. ### Validation Idle Home with working agents, 30 s Time Profiler, % of one core, iPhone 12 mini (release builds of main and this branch; real working agents, 3 rows in the before run and 2 in the after run, which doesn't matter because the cost is per frame, not per row): | | Buzz | backboardd | kernel | Total | |---|---|---|---|---| | Before (60 fps) | 43.3 | 42.0 | 18.9 | 104.2 | | After (12 fps) | 14.9 | 15.7 | 14.8 | 45.4 | Earlier battery runs on the iPhone SE (2nd gen), whole-device gauge, 8 min per variant, same setup: 60 fps +600 mW (+8.6%/h) over static dots; 12 fps +109 mW (+1.6%/h). Two working rows on a simulator: Before (60 fps): <video src="https://github.com/user-attachments/assets/539ce17d-7df4-4508-a981-4d6b31f8f805" width="400"></video> After (12 fps): <video src="https://github.com/user-attachments/assets/18513348-6f24-48c5-bb3b-4ac328d0c983" width="400"></video> - Added tests: `solo_working_dots_test.dart` checks that rows step together at about 12 fps with no frames scheduled between steps, and that the shared timer is gone when the last row is removed, when `TickerMode` is off, and while the app is hidden. - Full mobile suite passes (4912 tests). The one failure is `search_channels_journey_test.dart`, which doesn't compile on main; [#9545](https://github.com/block/buzz/pull/9545) fixes it. - Automated app run (signed-in simulator, every Solo row forced to working with a local-only patch): the rows pulse in phase on Home, keep pulsing after opening a chat and going back, and after backgrounding and resuming the app. ### Regressions - The pulse steps at 12 fps instead of animating smoothly. Side by side in the recordings it reads the same; you notice the steps only if you look for them. - Rows are now in phase with each other instead of each starting its wave when it mounted. - Reduced motion still shows static dots at full opacity, as before. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>mobile-v1.3.0-rc.1 |
||
|
|
c75d812f80 |
test(mobile): match the resumeSince override in the search journey (#9546)
## Summary `main` fails to compile `mobile/test/features/search/search_channels_journey_test.dart`. #9090 added `bool resumeSince = true` to `RelaySessionNotifier.subscribeWithStatus` and updated the existing overrides, while #9513 (merged just before it) added a `_RenamingSession` override without that parameter. Each passed CI alone; together `flutter analyze` reports `invalid_override` at `:933`, and the test shard that loads the file fails. This adds the missing parameter to `_RenamingSession.subscribeWithStatus`. Test-only, one line. ### Related issue None found. ### Testing - Reproduced on a clean checkout of `02535e1b5`: `flutter analyze` on the file reports the single `invalid_override`. - With this change on `02535e1b5`: `just mobile-install mobile-check mobile-test` passes (analyze clean, 4916 tests passed, 71 skipped, plus 27 package tests). Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz> |
||
|
|
a82d596fc2 |
mobile: show account communities in the switcher and sync saved destinations (#9262)
## Summary Switch Community currently shows only device-saved communities, leaving account destinations behind a separate Find step. It now merges saved communities with supported account destinations directly, keeps Add Community, and removes the redundant Find action from that Add route. Initial onboarding and identity recovery keep their discovery entry. Find lists supported account addresses before hosted identity setup; hosted selection still performs binding, backup, and admission, while external selection opens the existing identity flow. Mobile also saves QR/address additions and explicit removals through Builder Lab's existing known-communities account APIs. A per-account local journal retries transient failures, survives restarts, pauses in the background, and fences requests against account changes. External secure addresses use the existing self-hosted entry flow; account destinations never imply membership or bypass admission. Remote list omissions do not delete local identities. Explicit additions store an account owner and revision atomically with local credentials. Legacy/unclaimed destinations remain local-only until explicitly added while signed in; signing into another account never claims retained destinations. Restart reconciliation lets a committed re-add supersede an older removal even if the retry-journal write failed. Local deletion and its credential-free account-removal intent commit in one storage write, independent of the account-only retry journal. Removing one of several local identities owned by the same account at an address retains its account destination until that account’s last identity is removed. Another account’s saved identity does not block removal or lose its credentials during recovery. Offline edits retain the stored account subject without treating it as network authorization. Discovery-only intent survives browser callbacks, app restart, and retry. Onboarding recovery controls have a Material ancestor in the actual route. Pending status is fenced to the current subject; interrupted older removals offer explicit local completion, and denied requests offer browser reauthentication. Same-host ports have distinct labels and confirmations, and unsupported hosted ports are excluded. This changes the mobile client and its public-build CI test list only: no relay endpoints, events, migrations, or backend deployment. ### Related issue No duplicate found among open known-communities/switcher issues and PRs. Related picker editing work: #6632 (renaming communities). ### Testing Validated after merging main (`02535e1b53`) at `c4ee037f7e710962f176540abf88d26e98c2823c`. Wes’s follow-up fixes cover push-revocation commit ordering, same-account removal confirmation, and recovery after completed hosted admission. The merge also preserves main’s toolbar and session protections; a test override now accepts the updated relay subscription parameter. - Formatting, static analysis, and differential file-size checks pass. - Prior full CI and security review passed on `3adb117aae`; security checks also passed on `cf3836ecb`. Fresh CI and security review are required for this head. - Mutation checks fail when either the initiating-account removal guard or the rendered-status subject fence is removed; both guards were restored before final validation. - CI explicitly runs the public-only account discovery and synchronization journeys. - Added journeys cover paused removal across A→B, offline restart, journal read/write failures, duplicate local identities in either removal order, delayed status reads across accounts, real browser handoff after denial, unbound external discovery, and local same-host port removal. - Earlier journeys cover pairing acknowledgement and restart after journal-write failure, same-subject setup completion, offline/rejected removal with reopen/retry, and fresh external-only/mixed account entry. - Regression coverage includes discovery deduplication and retry, hosted and external selection, Add without Find, account-only removal, shared authentication/removal persistence, restart recovery, latest-intent ordering, account changes, and retry pause/resume. - `just mobile-check`, `just file-size-check`, and `just mobile-test`: 4,954 default-build tests passed (71 skipped), plus 27 crypto-package tests. - Full public-account suite: 5,012 passed, 12 skipped, one pre-existing failure in `fullscreen_onboarding_test.dart` ("Home stays hidden until community choice and admission"). The same assertion was reproduced on clean base `8cce12f591`: expected both communities imported, actual only the selected community. - Follow-up regression journeys cover both A/B same-address removal orderings, recovery preserving B’s saved key, the production onboarding widget composition, and retained discovery intent with callback/retry plus normal-sign-in controls. - Native/live-account and human testing remain outstanding. The tests use fake network/storage boundaries; live account API behavior, cross-device synchronization, native accessibility, and timeout/late-server-commit ordering still require integration verification. - The three expanded recovery/removal journeys pass and each fails when the corresponding fix is removed. A durably journaled revocation now finishes the confirmed removal even if the account changes during journaling; pre-journal account mismatches still abort. Confirmation copy counts only same-account identities. Explicit account recovery retires a completed join target while preserving in-progress targets. ### Preview Sample-data Flutter widget renders: saved-only and combined lists. These illustrate the picker layout, not a device session or live account sync. | Saved-only | Combined | | --- | --- | |  |  | ### Manual verification 1. Sign into a public account with a community saved on another device. Open Switch Community; verify it appears alongside local choices and Add. 2. Select a hosted and an external community; verify the existing identity/admission flow opens. Add should not offer Find again. 3. Add a community by QR/address, then check the account list on desktop. Remove it on mobile and verify the account entry disappears while other devices retain their local credentials. 4. Repeat removal offline, restart, then reconnect/resume. Verify the queued removal reaches the account service without switching identities. 5. On a fresh device, verify external-only and mixed account lists offer external entry. Check two ports on the same host remain distinguishable. 6. Sign out of account A and into B; retained A destinations must not upload to B. Explicitly add a B destination and verify it syncs. 7. Reject or interrupt account removal; verify visible pending/failure status. A denied session must open browser sign-in through “Sign in again” and retry after exchange; setup-required accounts retain their setup action. 8. Keep two local identities owned by the same account at one address; removing the first must keep the account entry, and removing the last must queue account removal. Repeat with A and B at that address; removing A must preserve B’s saved credentials and still sync A’s removal. 9. Restart offline with a stored account, add/remove an external community, then reconnect as the same account and verify convergence. Explicit sign-out must not claim new local-only entries. 10. Start Find my communities, restart during browser authentication, then return or retry. External destinations must appear before hosted identity setup; normal sign-in must retain its identity checks. --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>mobile-v1.2.0-rc.5 |
||
|
|
02535e1b53 |
perf(mobile): stop replaying stored read state on every resume (#9090)
Every time the mobile app reconnects (for example after more than 5 seconds in the background), the read-state live subscription asked the relay for up to 500 stored read-state events. That re-downloaded every read-state slot on the account, then the snapshot fetched the same events again right after. On a heavy account (28 slots) that replay alone was about 1.4 MB per resume. The live subscription now uses `limit: 0`, so it only delivers changes. It still opens before the snapshot, so the snapshot covers anything published in between. The subscription can also go live after `subscribe` has returned: on a cold start with slow AUTH, `subscribe` returns on its 500 ms fallback before the REQ is registered, after a transient CLOSED (rate limit, capacity) the session reopens it on the same socket, and a reconnect replays it. With `limit: 0` nothing replays marks published in that gap, so the manager reads the snapshot every time the subscription reports ready, as the channel list's `limit: 0` subscription already does. The session keeps live subscriptions across reconnects and replays them on the new socket, so a reconnect no longer resubscribes: the replay's ready reads the snapshot, once per reconnect. The manager opens a new subscription only after losing one (a terminal CLOSED or a failed subscribe), on the next reconnect. All snapshot reads outside a publish go through one sync loop. Initialize and each ready ask that loop for a snapshot. A request made before the current pass starts its read joins that read, and a request made during the read runs one more pass, so a ready can't be swallowed by a read already in flight. This needs no generation or ready-transition checks, at the cost of an occasional extra read (for example a cold start whose ready lands after the 500 ms fallback, when the first read has already started). Snapshot reads are numbered in start order, including a publish's own read, and only a read newer than every settled one decides whether the last snapshot succeeded. An older read finishing late cannot clear the retry a newer failed read needs. A failed read waits for the next trigger: the publish it schedules, which reads the snapshot in full after a failure, or a later ready, resume or reconnect. A publish with nothing to send skips its snapshot ([#9093 skip redundant publish](https://github.com/block/buzz/pull/9093)) only when the last snapshot succeeded, so after a failed resume snapshot the next publish still retries it. A publish snapshot now notifies readers of the marks it merged, since unchanged slots publish nothing whose echo would. ### Accepted gap If the snapshot fails (timeout, discovery or HTTP error) on a device with no local journal, read state stays local until the next successful snapshot, which every resume, reconnect, subscription recovery and publish retries. Falling back to a stored replay on failure would close the gap, but it adds a late subscription path for a rare failure that already heals on its own. ### Validation - Added test: `live subscription replays nothing and opens before the snapshot`. It fails without the change (`limit` 500). - Added test: `a clean reconnect through the real session replays one REQ and reads the snapshot once, and a lost subscription is reopened` drives the real `RelaySessionNotifier` with a recording socket: the connected listener runs, then the session's replay, then EOSE. It fails against the previous revision of this PR (two `l-2` REQs and two snapshot reads per reconnect). After a terminal CLOSED, the next reconnect opens a new subscription and reads the snapshot. - Added test: `readies during a held snapshot read share one more read`. - Added test: `a mark published while the live subscription retries is read once it recovers` puts the subscription into retry, lets another device publish a mark, then reports it ready. It fails without the read on ready. - Added test: `a failed late-ready read is retried by the next publish`. It fails without the retry. - Added test: `a reconnect while the first snapshot downloads is not swallowed by the cold-start connect` lets the cold-start connect queue behind initialize, then reconnects while the first read is still downloading and has a peer publish a mark. It fails against the previous revision of this PR (the queued pass swallowed the reconnect) and passes with the sync loop. - Added test: `an older snapshot finishing late keeps a newer failed read's retry` holds a publish's snapshot read, fails a newer read, then lets the older one finish. It fails against the previous revision of this PR (the older success cleared the retry) and passes with the read ordering. - Added test: `a mark published before a slow cold-start REQ goes live is read then` lets `subscribe` return before ready, publishes a mark, then reports ready. It fails without the read on ready. - `a publish after a failed snapshot retries it, then skips again` replaces the earlier skipped-publish test and fails without the snapshot check. It also checks that the retried snapshot's new marks notify readers, which fails without the notify. - Read-state suite (95 tests), `flutter analyze` and the full mobile suite pass. - iPhone 12 mini, Profile build with [#9089 gzip snapshot](https://github.com/block/buzz/pull/9089) applied, Home backgrounded 12 s and resumed, websocket bytes received in the 15 s after resume: | | Websocket in | Read-state replay | | --- | --- | --- | | Before (gzip fix only) | 2,087 KB | 1,458 KB (28 events) | | After (gzip fix + this) | 575 KB | none | The table counts websocket bytes only. Each resume reads the read-state snapshot once over HTTP, before and after this change. Automated app run on the same phone: Home, a large channel and search resumed after the reconnect grace period, with no read-state errors logged. Read marks were not compared across devices. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
1a5c6939c5 |
perf(mobile): save the open-channel directory and catch it up (#9513)
Search and invite recovery read a community's open-channel directory (every open, listed channel's kind 39000 metadata) from the relay, and match names on the device. Until now the app kept that directory in memory for 30 seconds only, so every search session after that, and the first search after every launch, downloaded the whole directory again. This follows [#9466 directory-only search load](https://github.com/block/buzz/pull/9466) and [#9457 directory keeps message times](https://github.com/block/buzz/pull/9457), which made each of those downloads cheaper; this one makes most of them unnecessary. Now the directory is saved in a file per community and account, next to the image cache, and search reads it from there: - **What's saved.** Only the latest revision of each open, listed, non-DM channel. The relay's directory read also returns the user's own private, unlisted and DM channels; those are never held or saved as the directory, and a channel whose latest revision is no longer discoverable drops out. - **First read.** The first time search opens, the app downloads the whole directory, as before, and saves it. - **Catch-up.** When search opens later, it shows the saved copy at once. At most once a minute, it asks the relay in the background only for directory changes since the newest saved one, or since the last read started by the device clock if that is earlier (less a minute of overlap), and merges them in. The relay can stamp a busy channel's metadata minutes ahead of wall time, so the newest saved stamp alone could skip channels created meanwhile. A catch-up that brings back nothing new saves nothing and leaves the list alone, and a search opened while a background read is still running shares it rather than starting another. - **Offline open.** A search opened before the session connects shows the saved copy and runs its check on the next connect. - **Daily full read.** Once the last full read is a day old (or dated in the future, by a clock since set back), the next check downloads the whole directory in the background and replaces the saved copy, which drops channels that became private or unlisted or were deleted. A catch-up can't see those: the relay never serves them to a non-member. - **Gone on open.** Opening a saved result that the relay no longer serves (private or deleted) drops it from the directory at once, and no directory read already in flight (background check, list refresh or Retry) brings it back. A restore from disk never overrides a full read already running, and a background read never displaces one. - **Invite recovery** still downloads the whole directory, as on main: it needs fresh memberships, and its read also refreshes the saved copy. - **Cleanup.** Signing out of a community, replacing its account, or leaving it deletes the file. The saved events omit signatures (the relay signed them; the copy is a cache of what it served). The file's JSON is encoded and decoded off the UI isolate, and an unavailable caches directory (or one that takes over 3 seconds) just means no saved copy. A file that is unreadable, from another version, or over 20,000 channels or 16 MiB is discarded and read again from the relay. There is no relay change. `CONTEXT.md` gains an "Open-channel directory" entry. ### Validation | Workflow (small community, 63 open channels) | Directory bytes before | Directory bytes after | | --- | --- | --- | | First search after install | 39.5 KB (2 requests) | 39.5 KB (2 requests) | | Search again 2 minutes later | 39.5 KB (2 requests) | 0.6 KB (2 requests) | | Relaunch, then search | 39.5 KB (2 requests) | 0.6 KB (2 requests) | Measured on an iOS simulator signed in to a test community, with a temporary local counter on each relay query response (not part of this PR), main at [ |
||
|
|
5b92e02e2a |
fix(mobile): sign out from Settings in every build, keeping keys on the device (#9421)
Public and Nostr-only builds had no way to sign out. The only route was
Switch community → Edit, remove every community, then tap Back to get a
"Sign out of BuilderLab?" prompt. Removing a community that way also
deletes its key from the phone, even when the user never exported or
backed it up.
Settings now ends with **Sign out** in every build (internal builds
already had it). After confirming:
- Each community's key is first copied into this device's saved
identities, the same thing internal Sign out already did. Sign-in offers
them again, so signing out never destroys a key that may exist nowhere
else. If saving fails, nothing is removed.
- In a public build, the Builderlab session ends next, before anything
is removed. The Sign in landing that follows never shows the old
session, and nothing started there can be cancelled by it. If the
session or a pending browser sign-in can't be cleared, including a saved
session not yet restored after launch, Sign out stops with an error and
keeps every community. Ending the session never waits behind a pending
account request, such as a stalled session check at launch, and no such
request can restore the session once it finishes later. This path never
shows the hosted setup page over Settings. The removed communities'
push-lease tombstones still publish afterwards: the outbox authenticates
them with the push-stop credential the session leaves behind for 10
minutes, including a saved session that was never restored (an offline
launch), even when a first cleanup attempt failed partway.
- Every community is removed, the active one last, so removing the
others never switches to (and connects) another community on the way
out.
- A Sign out failure now shows its error in Settings. The row used
Settings' outer context, so the snackbar went to the page underneath.
Nothing else changes: the switcher, per-community Remove and the
onboarding landing's Back → "Sign out of BuilderLab?" path behave as
before. Internal Sign out keeps its behavior (one community, key kept,
the landing then ends the organization session). The only new UI is one
row at the bottom of Settings.
| Before | After |
| --- | --- |
| <img width="300" alt="before"
src="https://github.com/user-attachments/assets/f49f7869-3401-4e05-aa7b-debe7a7d425c">
| <img width="300" alt="after"
src="https://github.com/user-attachments/assets/99731c6a-035e-447b-987a-7fa0d8e767cc">
|
Demo (public build, simulator): Sign out → confirm → back at the Buzz
landing, signed out of Builderlab.
https://github.com/user-attachments/assets/da64082b-3b73-46d0-8578-771fca7dec22
### Validation
- Added tests: `settings_sign_out_test.dart`, a Settings journey with
two communities whose keys aren't backed up. Cancelling keeps
everything. Confirming removes both (active last) and both keys end up
in saved identities. The root swaps Settings for the real
`OnboardingAppEntry` as the app does. The authenticated root is wrapped
in the real `HostedAppGate`, and no route may be pushed while Sign out
runs. In a public build it fails three ways, each showing the error in
Settings and removing nothing: a saved session that isn't restored yet
can't be deleted, a restored one can't be deleted, and a pending browser
sign-in can't be cleared. Then, with revocations held pending, the
landing appears with the session already gone and no "Signed in as", and
releasing the revocations changes nothing. It runs in the default lane
and in the CI public-build lane (added to `_ci-clients.yml`). Confirmed
it fails when the key save is removed, when the session ends after the
landing appears, when sign-out goes through the flow's published stages,
when a failed clear is detected only by a missing in-memory session,
when a browser cleanup failure is swallowed, and when the error goes to
the page underneath.
- `organization_relay_auth_test.dart`: a push stop still gets an
assertion after signing out a saved session that was never restored,
including a failed cleanup followed by a successful retry (fails without
the fix).
- Sign-out never waits on a pending account request: the Settings
journey holds `/v1/auth/me` during the final sign-out and checks that
its later completion restores nothing (without the fix, Sign out stalls
and both communities stay). `builderlab_account_test.dart` covers a
session check already pending, one that starts while the session is
being deleted, an exchange queued before the sign-out, and an account
request during the removal that must not share the credential with the
notification extension again.
- Focused existing validation: `internal_build_entry_test.dart` with the
internal-build defines passes.
- Full `just mobile-test` (4,848 passed, 74 skipped) and `just
mobile-check` are clean.
- Automated app run at
([d36150c](
|