Skip to content

feat(relay): implement nip-sl send later and nip-fi deferred actions - #10036

Open
kalvinnchau wants to merge 12 commits into
am/nip-sl-relay-compatfrom
am/nip-sl-relay-feature
Open

kalvinnchau wants to merge 12 commits into
am/nip-sl-relay-compatfrom
am/nip-sl-relay-feature

Conversation

@kalvinnchau

@kalvinnchau kalvinnchau commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements relay support for NIP-SL (Send Later, kind:30360 instructions and relay-signed kind:30361 statuses) and NIP-FI § Deferred actions (durable cross-community disconnect records and admission-time fencing), stacked on #10020.

Key changes

  • Schema & migrations (migrations/0112_scheduled_sends.sql, schema/):
    • Adds tenant-scoped scheduled_sends table (PRIMARY KEY (community_id, author, schedule_id)) and operator-global nip_fi_disconnects table with declarative schema (schema/tables/public/, schema/seeds/, schema/schema.sql) and live catalog parity in admin_schema_parity_between_desired_state_and_migrations.
  • Database store & operator rollback CLI (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/):
    • Atomic schedule acceptance (store_schedule_instruction), per-author advisory lock (lock_author_schedules) + SELECT … FOR UPDATE quota 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 (including kind:30361 status event_mentions).
    • Operator rollback primitive Db::withdraw_all_pending_schedules and buzz-admin scheduled-sends withdraw-all to cancel all pending sends across active communities as cancelled/withdrawn, erase their instructions, and fail non-zero if any reversibly fenced community still holds pending sends.
    • Acyclic global lock ordering (lock_nip_fi_issuer → community admission via AdmittedTx in ascending community_id order on disconnect → lock_author_schedules → row locks). AdmittedTx::try_admit routes through DeletionStore::guard_transaction_classified.
    • #[datastore_span] instrumentation on impl Db methods; fenced/quiescing communities are skipped in due-schedule and status-publication scans.
  • Cross-pod wake nudges (crates/buzz-pubsub/src/scheduled_send.rs, crates/buzz-pubsub/src/lib.rs):
    • Global Redis pub/sub wake channel (buzz:scheduled-send:wake) carrying { wake_at } latency hints from pods that accept near-term kind:30360 schedules (within 65 s of now) 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.
  • Relay handlers & NIP-FI integration (crates/buzz-relay/):
    • Plaintext kind:30360 acceptance in spec order (handlers/scheduled_send.rs) with duplicate-head check ahead of ±900 s timestamp drift, check-4 MAX_CONTENT_LEN (384 KiB, skipping generic 256 KiB pre-check), check-10 invalid: message: vs check-11 restricted: message: refusal mapping (passing error: through unchanged), compile-time const limit assertions (60 < RELEASE_WINDOW <= MAX_TIMESTAMP_DRIFT_SECS, STATUS_RETENTION > TEXT_RETENTION), NIP-OA owner time/kind bounds evaluated at not_before, and read-only inner media validation (check_media_references_readonly).
    • Single-leader horizon-sleep release loop (handlers/scheduled_release.rs) spawned only when relay_private_key is configured and NIP-FI deferred actions are not blocked:
      • Elects one active leader via Db::try_lock_session_leader(SCHEDULED_RELEASE_LOCK_KEY) (reusing Buzz's SessionLeader pattern; exposes buzz_scheduled_release_is_leader). Standby pods probe only the session advisory lock every 12–15 s and execute zero queries against scheduled_sends.
      • Leader sleeps until min(next_schedule_wake_at, now + 60s) (single-seek O(log N) against idx_scheduled_sends_work) and pulls its deadline forward immediately on buzz:scheduled-send:wake nudges; wall-clock retention runs every 10 min.
      • Publishes cancellations ahead of due releases with bounded concurrency (for_each_concurrent(8)) and per-row status claims on both cancellations and missed; treats error:-prefixed ingest errors as transient retries; rechecks author/owner bans & timeouts, relay membership, allowlist, channel permissions, and live validate_media_references; commits message and sent status atomically via transactional CAS so even brief handoff overlap cannot duplicate sends.
    • NIP-11 send_later descriptor and buzz-send-later extension, accept(), and is_enabled() all gated on configured relay_private_key, feature flags (buzz.relay.scheduled-sends.enabled / buzz.relay.scheduled-sends.accepting, default off; accepting implies enabled, turning accepting off drains), and BUZZ_NIP_FI_DEFERRED_ACTIONS (default false) when NIP-FI evaluates.
    • Scoped storage-clock (T0) admission sampling: HTTP samples clock_timestamp() only on POST /api/events after NIP-98, assertion verification, and key pairing and right before the deny-set check; WebSocket samples after shutdown and conn_semaphore refusals and before on_upgrade and the normative deny-set check in handlers/auth.rs, failing closed if absent.
    • Durable disconnect commit before session close in POST /api/nip-fi/disconnect across both Enforce and Shadow modes when BUZZ_NIP_FI_DEFERRED_ACTIONS=true (bounded at DEFERRED_DISCONNECT_CAPACITY_PER_ISSUER = 50_000), skipping only permanently tombstoned/missing communities and failing closed (503) on reversibly fenced/quiescing communities with Prometheus counter buzz_nip_fi_deferred_disconnect_failures_total{reason="capacity"|"storage"}.
    • Deferred NIP-OA credential provenance in handlers/auth.rs and api/bridge.rs populates nip_oa_auth_tag only when NIP-OA verified the admitted owner without a superseding NIP-FI token owner.

Rollout & Rollback Procedure

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_cancel is a deliberate exception documented in ARCHITECTURE.md and crates/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 acquires lock_nip_fi_issuer exclusively, admits each affected community via AdmittedTx::try_admit in ascending community_id order, skips permanently tombstoned/missing communities, and rolls back (failing closed with 503) if any affected community is reversibly write-fenced (quiescing/fenced).

Database Review Checklist (docs/database.md)

  • Rollout phase & sequencing: Expand + deploy (step 2 of 2). Prerequisite PR feat(relay): reserve nip-sl private kinds and deletion catalog #10020 (step 1: registers scheduled_sends in PENDING_SCOPED_TABLES and APPROVAL_FORWARD_TABLES, excludes 30360/30361 from search and NIP-09 deletion) must be deployed to every relay, deletion executor, and operator CLI before migration 0112_scheduled_sends.sql runs. No follow-up contract migration or backfill is needed because both tables are net-new.
  • No triggers, functions, procedures, rules, or foreign keys: Confirmed in migrations/0112_scheduled_sends.sql and schema/tables/public/{scheduled_sends,nip_fi_disconnects}.sql (enforced by migrations_after_retirement_add_no_triggers_functions_or_foreign_keys and admin_schema_parity_between_desired_state_and_migrations).
  • No data backfills: Migration 0112_scheduled_sends.sql creates only empty tables and indexes plus the constant _operator_global_tables registry row for nip_fi_disconnects (schema metadata per docs/database.md Rule 3). No existing rows are mutated.
  • Contract migration fail-closed: N/A (expand-only migration).
  • All Rule 4 schema locations updated & catalog parity tested: Updated 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), and crates/buzz-db/src/store/deletion.rs (EXPECTED_SCOPED_TABLES, PURGE_SCOPED_TABLES, kept in APPROVAL_FORWARD_TABLES, plus fence-refusal and purge test scheduled_sends_refuse_writes_after_the_fence_and_are_purged). Live catalog parity (columns, index shapes, and constraints) for both scheduled_sends and nip_fi_disconnects is asserted in admin_schema_parity_between_desired_state_and_migrations.
  • Backward compatibility with the running relay: Once prerequisite PR feat(relay): reserve nip-sl private kinds and deletion catalog #10020 is deployed everywhere, the running relay accepts scheduled_sends as an optional pending tenant table, purges and verifies it during community deletion, and reads neither new table; nip_fi_disconnects is operator-global and ignored by older binaries. Verified by pending_scoped_tables_are_optional_purged_and_verified (feat(relay): reserve nip-sl private kinds and deletion catalog #10020) and migration-mode catalog tests.
  • Lock timeouts & index build mode: migrations/0112_scheduled_sends.sql sets SET 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

  • Stacked on feat(relay): reserve nip-sl private kinds and deletion catalog #10020 (8bf95daab6); latest commit b14ef9b090.
  • Local validation: cargo fmt --all -- --check, just file-size-check, cargo clippy -p buzz-pubsub -p buzz-db -p buzz-relay --all-targets -- -D warnings, full workspace rust-tests + desktop-tauri-checks pre-push gates, buzz-db --test observability_source (46/46 passed), buzz-pubsub unit + FakeRedis keepalive tests (59/59 passed), buzz-db scheduled-send Postgres tests (12/12 passed, including next_schedule_wake_at_tracks_horizon_retries_and_cancellations), and buzz-relay unit (5/5) + scheduled-send/release Postgres tests (14/14 passed, including leader_horizon_sleep_wakes_on_nudge_and_fails_over_to_standby).

@kalvinnchau
kalvinnchau marked this pull request as ready for review December 1, 2026 12:04
@kalvinnchau
kalvinnchau force-pushed the am/nip-sl-relay-feature branch from 513d458 to c01241c Compare December 1, 2026 12:15
@kalvinnchau
kalvinnchau added this pull request to stack #10080 December 1, 2026 19:22

@wpfleger96 wpfleger96 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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/withdrawn for it, but nothing writes withdrawn today. 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 as withdrawn, named in the rollback steps?
  • Small cleanups: ScheduleHead.instruction_stored is 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 (a const assert 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.

Comment thread crates/buzz-relay/src/nip_fi_config.rs Resolved
Comment thread crates/buzz-relay/src/nip_fi_http.rs Resolved
Comment thread crates/buzz-relay/src/router.rs Resolved
Comment thread crates/buzz-relay/src/api/nip_fi.rs Resolved
Comment thread crates/buzz-relay/src/main.rs Resolved
@kalvinnchau
kalvinnchau force-pushed the am/nip-sl-relay-feature branch from c01241c to fafb00f Compare December 1, 2026 21:22
@kalvinnchau

Copy link
Copy Markdown
Contributor Author

🤖 Addressed all inline threads and top-level review items in fafb00f24b (rebased both #10020 at 8bf95daab6 and #10036 at fafb00f24b onto origin/main at b9cccf87e3):

  • Rollback withdrawal (withdrawn): Added CancelTarget::All and Db::withdraw_all_pending_schedules (crates/buzz-db/src/store/scheduled_send.rs) plus buzz-admin scheduled-sends withdraw-all (crates/buzz-admin/src/main.rs), cancelling all pending sends across active communities as cancelled/withdrawn, erasing their instructions, and exiting non-zero if any non-tombstoned community still holds pending rows. Documented in the PR rollback steps alongside feat(relay): reserve nip-sl private kinds and deletion catalog #10020 as the privacy rollback floor.
  • Small cleanups: Removed unused ScheduleHead.instruction_stored, skipped redundant instruction-event deletes for already-erased rows in expire_in_transaction, skipped duplicate inner verify_event in ingest_event_in_mode for ScheduledCheck/ScheduledRelease, and added compile-time const assertions in scheduled_send.rs enforcing PAST_TOLERANCE_SECS < RELEASE_WINDOW <= MAX_TIMESTAMP_DRIFT_SECS and STATUS_RETENTION > TEXT_RETENTION.
  • Test coverage: Added two_releases_racing_after_hold_lapses_post_message_once, transient_error_during_release_defers_instead_of_failing, transient_ingest_error_catches_error_prefixed_rejections, accept_and_disconnect_serialize_on_issuer_lock (both advisory-lock falsifier and concurrent accept-vs-disconnect race), deferred_actions_off_blocks_release_while_nip_fi_evaluates, nip_fi_disconnect_fails_on_fenced_community_and_skips_tombstoned, withdraw_all_pending_schedules_cancels_as_withdrawn_and_flags_fenced, deferred_clock_read_is_scoped_to_event_submit_and_runs_after_pairing, deferred_actions_defaults_to_false_and_parses_env, and buzz-admin CLI parsing coverage.

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
kalvinnchau force-pushed the am/nip-sl-relay-feature branch from b14ef9b to ff97a50 Compare December 2, 2026 02:48

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants