Repository navigation
feat(relay): implement nip-sl send later and nip-fi deferred actions - #10036
Open
kalvinnchau wants to merge 12 commits into
Open
kalvinnchau wants to merge 12 commits into
kalvinnchau wants to merge 12 commits into
Conversation
kalvinnchau
marked this pull request as ready for review
December 1, 2026 12:04
kalvinnchau
requested review from
a team,
TheSentinel454,
bradseiler,
ravarora2,
salman1993 and
wpfleger96
as code owners
December 1, 2026 12:04
kalvinnchau
force-pushed
the
am/nip-sl-relay-feature
branch
from
December 1, 2026 12:15
513d458 to
c01241c
Compare
wpfleger96
reviewed
Dec 1, 2026
wpfleger96
left a comment
Member
There was a problem hiding this comment.
🤖 Paul and Thufir (Will's agents) reviewed this together. Inline comments cover the specific issues; two points don't map to one line:
- No way to end pending sends before a rollback. NIP-FI says the operator MUST end every pending deferred action before an older process runs again, and NIP-SL defines
cancelled/withdrawnfor it, but nothing writeswithdrawntoday. An older relay (including #10020 alone) answers disconnects with 200 and cancels nothing. Could this add a store primitive plus an operator command that cancels all pending rows aswithdrawn, named in the rollback steps? - Small cleanups:
ScheduleHead.instruction_storedis read but never used; the retention sweep deletes instruction events that are already gone; the inner signature is verified twice at acceptance and release; and nothing asserts the release window is within the timestamp tolerance, which the spec requires (aconstassert would cover it). - Test gaps: two releases racing after a hold lapses mid-publish; a transient error during release; an acceptance-vs-disconnect race (removing the issuer lock fails no test); the deferred-actions-off release path.
kalvinnchau
force-pushed
the
am/nip-sl-relay-feature
branch
from
December 1, 2026 21:22
c01241c to
fafb00f
Compare
Contributor
Author
|
🤖 Addressed all inline threads and top-level review items in
|
add scheduled_sends (tenant) and nip_fi_disconnects (operator-global) schema, store, plaintext kind:30360 acceptance with nip-oa owner time bounds at T, transactional release loop with nip-11 self-signed kind:30361 statuses, atomic ban/channel-deletion/nip-fi-disconnect cancellation, retention and account-deletion handling, and nip-11 send_later advertisement (default off). Signed-off-by: Kalvin Chau <kalvin@block.xyz>
… findings preserve postgres admission_time in live ws pre_gate and sample before upgrade deny-set check; fail closed without storage admission time; recheck relay_members and pubkey_allowlist at release; record durable disconnects in shadow and enforce modes while disabling deferred actions in db-less route fixtures; enforce nip-oa kind= and created_at clauses on inner messages; serialize per-issuer disconnect capacity with global lock order issuer < target < community; keep check-only media validation read-only and align kind:30360 content cap to 512 kib; skip deleting communities in status publication and preserve unpublished cancellations in retention. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
…e and content cap findings defer media_publications recording on scheduled releases until scheduled_release::store commits (transactional in enforce mode, post-commit best-effort in shadow mode), switch refusal() to read-only media checks, and skip redundant outer kind:30360 media validation ahead of nip-sl checks; populate deferred nip-oa credentials only when nip-oa verified the admitted owner without a superseding nip-fi token owner; align advertised max_content_len to 384 kib below the 512 kib ws frame limit; isolate shared-db postgres tests and add real ws handle_connection, shadow-mode disconnect, and schedule media-immutability regression tests. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
…s and fix postgres ci deduplicate instruction erasure, storage clock, advisory lock keys, nip-oa time-bound checks, media publication hash lookup, and nip-fi deferred guards; simplify postgres row-value timestamp comparisons and drop single-use sql macros. remove redundant parser/hmac/deletion tests, cut test setup boilerplate, speed up fenced-community starvation test, and bind scheduled_release::refusal read-only media check with a deleted-blob refusal step. add migration 110 to pre-retirement tenant test list, update expected missing table lists, and include scheduled_sends in partial-schema ban test helpers. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
index stored kind 30361 status p-tags inside insert_schedule_event so nip-sl complete-read #p queries return stored statuses, and remove their event_mentions rows when expire_schedules deletes expired statuses. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
plan event_mentions rows for scheduled_sends status events before their events rows in user_deletion::content_batches::owned::plan so grouped::children allows erasing kind 30361 statuses after commit 9117771 indexed them, and restrict insert_schedule_event mention indexing to kind 30361 to match delete_schedule_event. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
…fi locks replace slot/retry machinery with per-author advisory lock and select for update, closing the concurrent trim_ended_instructions quota race; drop slot and unused message_id columns and replace channel_tag hmac with plain channel_id uuid so soft_delete_channel_capturing_members cancels schedules directly. use live validate_media_references on release (keeping read-only checks on acceptance and refusal diagnostics), replace releasing_flag with enabled_flag implied by accepting_flag, fold duplicate-head and timestamp checks into scheduled_send::accept, unify author/owner restriction checks in release, simplify ScheduleState/Limits, consolidate nip-fi issuer locking to shared/exclusive hashtextextended, share T0 clock sampling and disconnect cancellation, replace the disconnect capacity env var with a const, and prune overlapping tests. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
copy uuid out of tx.community().as_uuid() in cancel_schedules_in_transaction (fixes E0716) and convert Option<[u8; 32]> via as_ref().map(<[u8; 32]>::as_slice) instead of as_deref() in scheduled_release::release. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
… guidelines drop redundant scheduled_sends author index and lead owner index with community_id in 0112_scheduled_sends.sql and schema/tables/public/scheduled_sends.sql. document the deliberate multi-community nip-fi disconnect exception in architecture.md and admitted_tx.rs. instrument impl db scheduled_send methods with datastore_span. add startup jitter and capped exponential backoff with jitter to scheduled_release::run. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
default buzz_nip_fi_deferred_actions to false, scope http storage-clock sampling to post /api/events after pairing and before deny-set, and move ws storage-clock sampling after shutdown and connection-limit refusals. add buzz_nip_fi_deferred_disconnect_failures_total counter, fail closed on reversibly fenced communities during disconnect while skipping tombstoned ones, preserve check-10 invalid and transient error prefixes, skip generic content-size check and duplicate inner verify for scheduled kinds, require relay_private_key and deferred-actions gate on accept and release, add bounded release concurrency with status claims and idle polling, add withdraw_all_pending_schedules plus buzz-admin scheduled-sends withdraw-all, clean up unused head field and retention deletes, add const limit assertions, and add regression tests. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
…d pubsub wake replace fixed 1s fleet-wide polling in scheduled_release::run with postgres sessionleader election (scheduled_release_lock_key), single-seek horizon sleep via db::next_schedule_wake_at capped at 60s, and fire-and-forget local plus redis pub/sub wake nudges (buzz:scheduled-send:wake) on near-term schedule accepts and relay cancellations (ban, channel deletion, nip-fi disconnect). standby pods poll only the session advisory lock every 12-15s and touch zero scheduled_sends rows, while transactional cas remains the duplicate-proof floor. also route admittedtx::try_admit through deletionstore::guard_transaction_classified so buzz-db observability_source passes all 46 gates, and add unit plus postgres integration tests. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
initialize deferred_nip_fi to none on the new shared lookup test caller added on main. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
kalvinnchau
force-pushed
the
am/nip-sl-relay-feature
branch
from
December 2, 2026 02:48
b14ef9b to
ff97a50
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements relay support for NIP-SL (Send Later,
kind:30360instructions and relay-signedkind:30361statuses) and NIP-FI § Deferred actions (durable cross-community disconnect records and admission-time fencing), stacked on #10020.Key changes
migrations/0112_scheduled_sends.sql,schema/):scheduled_sendstable (PRIMARY KEY (community_id, author, schedule_id)) and operator-globalnip_fi_disconnectstable with declarative schema (schema/tables/public/,schema/seeds/,schema/schema.sql) and live catalog parity inadmin_schema_parity_between_desired_state_and_migrations.crates/buzz-db/src/store/scheduled_send.rs,crates/buzz-admin/src/main.rs,channel.rs,moderation.rs,relay_admin_actions.rs,deletion.rs,user_deletion/):store_schedule_instruction), per-author advisory lock (lock_author_schedules) +SELECT … FOR UPDATEquota and ended-instruction retention enforcement, transactional release (mark_schedule_sent_in_transaction), claim/retry leasing for both releases and status publication (claim_schedule,claim_cancellation_status), single-seek horizon lookup (next_schedule_wake_at), retention expiry preserving unpublished cancellations, and atomic cancellation on ban, channel deletion (channel_id), NIP-FI disconnect, and user deletion (includingkind:30361statusevent_mentions).Db::withdraw_all_pending_schedulesandbuzz-admin scheduled-sends withdraw-allto cancel all pending sends across active communities ascancelled/withdrawn, erase their instructions, and fail non-zero if any reversibly fenced community still holds pending sends.lock_nip_fi_issuer→ community admission viaAdmittedTxin ascendingcommunity_idorder on disconnect →lock_author_schedules→ row locks).AdmittedTx::try_admitroutes throughDeletionStore::guard_transaction_classified.#[datastore_span]instrumentation onimpl Dbmethods; fenced/quiescing communities are skipped in due-schedule and status-publication scans.crates/buzz-pubsub/src/scheduled_send.rs,crates/buzz-pubsub/src/lib.rs):buzz:scheduled-send:wake) carrying{ wake_at }latency hints from pods that accept near-termkind:30360schedules (within 65 s ofnow) or cancel pending schedules (ban, channel deletion, NIP-FI disconnect). Local receivers are notified synchronously without waiting on Redis loopback, and dropped messages are backstopped by the leader's 60 s horizon sleep.crates/buzz-relay/):kind:30360acceptance in spec order (handlers/scheduled_send.rs) with duplicate-head check ahead of ±900 s timestamp drift, check-4MAX_CONTENT_LEN(384 KiB, skipping generic 256 KiB pre-check), check-10invalid: message:vs check-11restricted: message:refusal mapping (passingerror:through unchanged), compile-timeconstlimit assertions (60 < RELEASE_WINDOW <= MAX_TIMESTAMP_DRIFT_SECS,STATUS_RETENTION > TEXT_RETENTION), NIP-OA owner time/kind bounds evaluated atnot_before, and read-only inner media validation (check_media_references_readonly).handlers/scheduled_release.rs) spawned only whenrelay_private_keyis configured and NIP-FI deferred actions are not blocked:Db::try_lock_session_leader(SCHEDULED_RELEASE_LOCK_KEY)(reusing Buzz'sSessionLeaderpattern; exposesbuzz_scheduled_release_is_leader). Standby pods probe only the session advisory lock every 12–15 s and execute zero queries againstscheduled_sends.min(next_schedule_wake_at, now + 60s)(single-seekO(log N)againstidx_scheduled_sends_work) and pulls its deadline forward immediately onbuzz:scheduled-send:wakenudges; wall-clock retention runs every 10 min.for_each_concurrent(8)) and per-row status claims on both cancellations andmissed; treatserror:-prefixed ingest errors as transient retries; rechecks author/owner bans & timeouts, relay membership, allowlist, channel permissions, and livevalidate_media_references; commits message andsentstatus atomically via transactional CAS so even brief handoff overlap cannot duplicate sends.send_laterdescriptor andbuzz-send-laterextension,accept(), andis_enabled()all gated on configuredrelay_private_key, feature flags (buzz.relay.scheduled-sends.enabled/buzz.relay.scheduled-sends.accepting, default off;acceptingimpliesenabled, turningacceptingoff drains), andBUZZ_NIP_FI_DEFERRED_ACTIONS(defaultfalse) when NIP-FI evaluates.T0) admission sampling: HTTP samplesclock_timestamp()only onPOST /api/eventsafter NIP-98, assertion verification, and key pairing and right before the deny-set check; WebSocket samples after shutdown andconn_semaphorerefusals and beforeon_upgradeand the normative deny-set check inhandlers/auth.rs, failing closed if absent.POST /api/nip-fi/disconnectacross bothEnforceandShadowmodes whenBUZZ_NIP_FI_DEFERRED_ACTIONS=true(bounded atDEFERRED_DISCONNECT_CAPACITY_PER_ISSUER = 50_000), skipping only permanently tombstoned/missing communities and failing closed (503) on reversibly fenced/quiescing communities with Prometheus counterbuzz_nip_fi_deferred_disconnect_failures_total{reason="capacity"|"storage"}.handlers/auth.rsandapi/bridge.rspopulatesnip_oa_auth_tagonly when NIP-OA verified the admitted owner without a superseding NIP-FI token owner.Rollout & Rollback Procedure
0112_scheduled_sends.sql, then deploy feat(relay): implement nip-sl send later and nip-fi deferred actions #10036 fleet-wide. Once every relay process runs feat(relay): implement nip-sl send later and nip-fi deferred actions #10036, enableBUZZ_NIP_FI_DEFERRED_ACTIONS=true(on NIP-FI-evaluating relays) together withbuzz.relay.scheduled-sends.enabled/buzz.relay.scheduled-sends.accepting.200and cancels nothing. Before rolling back from feat(relay): implement nip-sl send later and nip-fi deferred actions #10036 to feat(relay): reserve nip-sl private kinds and deletion catalog #10020:buzz.relay.scheduled-sends.accepting(so no new sends are accepted).buzz-admin scheduled-sends withdraw-alluntil it exits0withremaining_pending == 0(cancels all pending sends across active communities ascancelled/withdrawnand erases their instructions).awaiting_statusto drain to0so running feat(relay): implement nip-sl send later and nip-fi deferred actions #10036 pods publish thekind:30361cancelled/withdrawnstatuses, then disablebuzz.relay.scheduled-sends.enabledandBUZZ_NIP_FI_DEFERRED_ACTIONSand roll back to feat(relay): reserve nip-sl private kinds and deletion catalog #10020.30360/30361privacy, search exclusion, NIP-09 refusal, and deletion-catalog cleanup); disable the Send Later flags instead.Intentional architectural exception (
AGENTS.md§ Product Contract #5)ARCHITECTURE.md§ Supported Writer Contract states that ordinary serving transactions never span communities.Db::record_nip_fi_disconnect_and_cancelis a deliberate exception documented inARCHITECTURE.mdandcrates/buzz-db/src/runtime/admitted_tx.rs:docs/nips/NIP-FI.md§ Deferred actions requires committing the issuer disconnect record and cancelling every matching pending scheduled send across all communities in one atomic transaction. It acquireslock_nip_fi_issuerexclusively, admits each affected community viaAdmittedTx::try_admitin ascendingcommunity_idorder, skips permanently tombstoned/missing communities, and rolls back (failing closed with503) if any affected community is reversibly write-fenced (quiescing/fenced).Database Review Checklist (
docs/database.md)scheduled_sendsinPENDING_SCOPED_TABLESandAPPROVAL_FORWARD_TABLES, excludes30360/30361from search and NIP-09 deletion) must be deployed to every relay, deletion executor, and operator CLI before migration0112_scheduled_sends.sqlruns. No follow-up contract migration or backfill is needed because both tables are net-new.migrations/0112_scheduled_sends.sqlandschema/tables/public/{scheduled_sends,nip_fi_disconnects}.sql(enforced bymigrations_after_retirement_add_no_triggers_functions_or_foreign_keysandadmin_schema_parity_between_desired_state_and_migrations).0112_scheduled_sends.sqlcreates only empty tables and indexes plus the constant_operator_global_tablesregistry row fornip_fi_disconnects(schema metadata perdocs/database.mdRule 3). No existing rows are mutated.migrations/0112_scheduled_sends.sql,schema/tables/public/scheduled_sends.sql,schema/tables/public/nip_fi_disconnects.sql,schema/seeds/nip_fi_disconnects.sql,schema/schema.sql,crates/buzz-db/src/runtime/migration.rs(operator_global_tables(),add_catalog_schema_after_fence_retirement, migration count assertion), andcrates/buzz-db/src/store/deletion.rs(EXPECTED_SCOPED_TABLES,PURGE_SCOPED_TABLES, kept inAPPROVAL_FORWARD_TABLES, plus fence-refusal and purge testscheduled_sends_refuse_writes_after_the_fence_and_are_purged). Live catalog parity (columns, index shapes, and constraints) for bothscheduled_sendsandnip_fi_disconnectsis asserted inadmin_schema_parity_between_desired_state_and_migrations.scheduled_sendsas an optional pending tenant table, purges and verifies it during community deletion, and reads neither new table;nip_fi_disconnectsis operator-global and ignored by older binaries. Verified bypending_scoped_tables_are_optional_purged_and_verified(feat(relay): reserve nip-sl private kinds and deletion catalog #10020) and migration-mode catalog tests.migrations/0112_scheduled_sends.sqlsetsSET LOCAL lock_timeout = 5s. All indexes are created inline on the newly created empty tables; no existing table is scanned or locked, so no out-of-band concurrent index prebuild is required.Verification
8bf95daab6); latest commitb14ef9b090.cargo fmt --all -- --check,just file-size-check,cargo clippy -p buzz-pubsub -p buzz-db -p buzz-relay --all-targets -- -D warnings, full workspacerust-tests+desktop-tauri-checkspre-push gates,buzz-db --test observability_source(46/46 passed),buzz-pubsubunit + FakeRedis keepalive tests (59/59 passed),buzz-dbscheduled-send Postgres tests (12/12 passed, includingnext_schedule_wake_at_tracks_horizon_retries_and_cancellations), andbuzz-relayunit (5/5) + scheduled-send/release Postgres tests (14/14 passed, includingleader_horizon_sleep_wakes_on_nudge_and_fails_over_to_standby).