Repository navigation
p1: feat(relay): support explicit operator listener thread watches - #8877
mcdickenson wants to merge 7 commits into
Conversation
Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
🔐 Codex Security Review
|
joahg
left a comment
There was a problem hiding this comment.
🤖 Read the watch registration, enqueue guards, and migration 0080 (additive, no backfill). Two things to handle before merge: migration 0080_operator_listener_threads.sql collides with 0080_channel_auto_join.sql already on main and the branch is currently DIRTY, so it needs a rebase and renumber; and the PR body still lists full-stack integration and human acceptance as pending.
Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
wpfleger96
left a comment
There was a problem hiding this comment.
🤖 the explicit-watch model makes sense to me: agent-signed consent, one thread per watch, and the re-checks before delivery are the right shape, and I'd rather keep per-thread opt-out than wake agents on every reply in threads they've touched. comments below are mostly about cost at ingest, the reaper, and trimming pieces that aren't load-bearing. this also needs a rebase, and the migration needs renumbering since main is at 0111.
| if !seen.insert(id) { | ||
| continue; | ||
| } | ||
| let mut tx = crate::begin_community_write_transaction( |
There was a problem hiding this comment.
🤖 if one of these communities starts quiescing or deleting between the SELECT above and this call, begin_community_write_transaction returns AccessDenied and the ? aborts the whole sweep, so every community after it gets skipped on every run until that deletion finishes. sweep_admitted_communities / begin_community_sweep_transaction in buzz-db/src/runtime/mod.rs already handle this by skipping fenced communities and isolating per-tenant errors. could this use that instead?
|
|
||
| Ok(query.build().execute(tx.conn()).await?.rows_affected()) | ||
| let mentions = query.build().execute(tx.conn()).await?.rows_affected(); | ||
| let replies = super::operator_listener_threads::enqueue_thread_replies(tx, event).await?; |
There was a problem hiding this comment.
🤖 this runs the thread-watch INSERT ... SELECT for every top-level message too, inside the event's write transaction, even though only replies can match. could we gate it on the event actually being a reply? passing in the root that insert_event_with_thread_metadata_tx already resolved would skip the call for top-level messages and also remove the thread_metadata lookup inside enqueue_thread_replies. same applies to the early return at line 106.
| JOIN channel_members m ON m.community_id = w.community_id AND m.channel_id = w.channel_id \ | ||
| AND m.pubkey = w.target_pubkey AND m.removed_at IS NULL \ | ||
| JOIN channels c ON c.community_id = w.community_id AND c.id = w.channel_id AND c.deleted_at IS NULL AND c.archived_at IS NULL \ | ||
| JOIN events root ON root.community_id = w.community_id AND root.channel_id = w.channel_id \ |
There was a problem hiding this comment.
🤖 this looks up the root by id without its created_at, and events is range-partitioned on created_at, so the planner has to probe every partition. this runs on every reply at ingest (and again in the delivery re-check in load_deliverable_event). thread_metadata already has root_event_created_at, so joining on root.created_at = tm.root_event_created_at should let it prune to one partition.
| AND w.root_event_id = COALESCE(tm.root_event_id, tm.parent_event_id) \ | ||
| JOIN operator_listener_pubkeys r ON r.listener_pubkey = w.listener_pubkey AND r.target_pubkey = w.target_pubkey \ | ||
| AND r.created_at >= $5 \ | ||
| JOIN users u ON u.community_id = w.community_id AND u.pubkey = w.target_pubkey AND u.deactivated_at IS NULL \ |
There was a problem hiding this comment.
🤖 channel_members has no FK to users, and adding an agent to a channel doesn't create a users row, so I think an agent that's a channel member but has never had a users row gets a 403 on registration and silently loses replies here. mention delivery deliberately avoids an inner join on users (the principals CTE in load_deliverable_event). could the three watch queries (here, line 48, and operator_listener.rs:310) exclude deactivated users with NOT EXISTS (... u.deactivated_at IS NOT NULL) instead, so they match the mention path?
| AND COALESCE(tm.root_event_id, tm.parent_event_id) = w.root_event_id \ | ||
| WHERE w.community_id = $3 AND w.listener_pubkey = $1 AND w.target_pubkey = $2 \ | ||
| AND w.root_event_id = $9 AND w.channel_id = e.channel_id AND w.expires_at > now() \ | ||
| AND r.created_at >= now() - interval '30 days')) \ |
There was a problem hiding this comment.
🤖 nit: this hard-codes interval '30 days' where operator_listener_threads.rs binds PUBKEY_RETENTION. binding the constant here too keeps them from drifting.
| #[derive(Deserialize)] | ||
| #[serde(deny_unknown_fields)] | ||
| struct Registration { | ||
| registrations: Vec<nostr::Event>, |
There was a problem hiding this comment.
🤖 nit: registrations is a list but MAX_REGISTRATIONS = 1 means it must have exactly one, and the handler then loops over it. a single registration: nostr::Event field would drop the length check, the constant and the loop.
| &event_id(&request.root_event_id)?, | ||
| ) | ||
| .await | ||
| .map_err(|_| internal_error("remove operator-listener thread failed"))?; |
There was a problem hiding this comment.
🤖 both handlers map every DbError to an unlogged 500, including AccessDenied for a community that's quiescing or deleting, which is a normal lifecycle state. could we map AccessDenied to a 4xx and log the unexpected ones? also, DELETE skips the nil-UUID check that parse_registration does on POST, so nil IDs go all the way to write admission.
| if let Err(error) = state.db.reap_operator_listener_deliveries().await { | ||
| warn!(%error, "operator-listener outbox reap failed"); | ||
| } | ||
| if let Err(error) = state.db.reap_operator_listener_threads().await { |
There was a problem hiding this comment.
🤖 nit: this runs every 5 minutes on the outbox reap cadence, but watches expire after 30 days. it fits better on the daily REGISTRATION_REAP_INTERVAL loop next to delete_expired_operator_listener_pubkeys.
| CREATE INDEX operator_listener_threads_match | ||
| ON operator_listener_threads (community_id, channel_id, root_event_id, expires_at); | ||
|
|
||
| ALTER TABLE operator_listener_outbox ADD COLUMN thread_root_event_id BYTEA; |
There was a problem hiding this comment.
🤖 I don't think this column (or the thread_root_event_id payload field) is needed. the v2 payload already carries the full signed event, whose e tags name the root, and the doc already tells consumers to verify the root from the event. dropping both avoids altering the existing outbox table and removes the payload-shape mixed-version issue the rollout notes call out. if it stays, it should get CHECK (thread_root_event_id IS NULL OR length(thread_root_event_id) = 32) like the other 32-byte outbox columns.
| recovery must issue bounded standard signed queries for their watched thread and | ||
| feed the same durable intake path. Do not widen webhook freshness as recovery. | ||
|
|
||
| ## Rollout and validation |
There was a problem hiding this comment.
🤖 nit: about a third of this doc restates general consumer and contributor-checklist policy (e.g. the human-testing line at the end). I think it can be cut to roughly half, keeping the API contract, limits and delivery semantics.
Conflicts resolved: - crates/buzz-db/src/lib.rs: added operator_listener_threads alongside main's pins, search_backfill, search_outbox module exports - crates/buzz-db/src/runtime/migration.rs: renumbered migration from 87 to 112 (main took 87-111), updated count and assertions, added both PR's and main's new tables to the schema parity test list - migrations/0087_operator_listener_threads.sql renamed to migrations/0112_operator_listener_threads.sql The PR's migration creates operator_listener_threads and adds thread_root_event_id to operator_listener_outbox. None of main's migrations 87-111 touch these tables, so the renumbering is safe. Co-authored-by: Matt Dickenson <10949904+mcdickenson@users.noreply.github.com> Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
…go fmt The table was added after the community_write_fence rule was dropped (migration 0090), so it was never fenced. Add it to the never_fenced exclusion list in the migration test. Co-authored-by: Matt Dickenson <10949904+mcdickenson@users.noreply.github.com> Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
…bhooks-1031-883db6fa * origin/main: feat(search): people-only search filter, and the agent owner on each indexed message (block#10021) fix(search): drop the community label from indexer metrics (block#10019) relay: advertise the build's source SHA in NIP-11 (block#9827) feat(mobile): record a push baseline when Android enrolls (block#10038) Show deletion evidence to the requester (block#10076) Give single photos the stack card style in mobile chat (block#10071) fix(search): do not return expired AWS credentials after a failed reload (block#10042) feat(mobile): unify the Android conversation composer (block#10015) feat(mobile): check the relay key on Android push channel titles (block#10037) chore(devex): streamline local OpenSearch and Postgres test workflows (block#10034) feat(mobile): record messages the app shows so Android wakes skip them (block#10039) feat(search): remove a deleted community's messages from OpenSearch (block#9999) Preview user deletion from the original saved inventory (block#10028) Add queued follow-ups to the mobile Solo composer (block#10018) Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
…sertions The deletion catalog drift tests expected only search_backfill and search_outbox in the missing-tables message, but operator_listener_threads is also added after the retirement migration. Update both assertions to match the actual drift output. Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
Review brief
Add explicit, target-consented listener watches for replies in a shared thread.
Agent-prepared from the existing PR description and reported validation.
New persisted watches and signed callbacks must preserve membership, scope and lifecycle fencing.
Evidence
Use the schema and listener regression evidence below; migration, explicit enrollment and live rollout remain separate steps.
Change details
A plain reply in an agent's shared thread currently has no target
ptag and cannot reach the operator listener. Add an explicit, target-consented watch for one community/channel/root, delivered through the existing signed notification outbox. Existing mention behavior and default listener configuration remain unchanged.The new
POST /operator/listener/threadsaccepts one existing-kind target-signed registration proof, bound to the configured listener and exact canonical endpoint. Its signed content names{community_id,channel_id,root_event_id}. Watches require a current target registration, active user/channel membership and a canonical live root; they expire after 30 days, are capped at 128 per listener/target/community, and support exact authenticated deletion. Current membership, watch/registration expiry and active root/user/channel are rechecked before delivery. Target-authored output, other roots/channels/communities and channel chatter do not match. Explicit mention plus watch shares one existing outbox identity.Thread-only v2 payloads add optional
thread_root_event_idwithin the signed body; fixed outbox retention/retry and delivery fencing are reused. No scheduler, generic broadcast, enrollment, deployment or live schema operation is added. Clients must renew owned bindings using existing listener maintenance and explicitly seed reviewed legacy thread tuples before cutover; seeding does not change history. Expiry and recovery limits are documented indocs/operator-listener-threads.md.Schema phase: expand. Migration 0087 adds a tenant-owned table and indexes plus a nullable outbox metadata column. It adds no trigger, function, foreign key or backfill. All serving writers use community admission; deletion catalog/purge and actual desired-state versus migration catalog parity are covered. Old code ignores the added schema, but its exact-set community-deletion check refuses deletion during the expand/deploy gap. Deploy compatible consumers and all delivery workers before registering watches; auto-migration rollback requires the documented unknown-migration handling.
Validation on 2026-11-09 at
48a703df2874b182d382a068995f3d822ec239eaafter merging main at22d96d94ef043292803b6d5c929652abd69612dd:just cipassed, including Rust checks and unit tests, desktop frontend/native tests and builds, web build, and mobile tests.The merge and fixes are pushed at the SHA above. All normal pre-push hooks passed on retry without further code changes. An earlier concurrent hook run failed in auth tests, including a local proxy-server shutdown hang; the isolated proxy test, full
just ci, and complete hook retry passed.The required DCO and Desktop Release Candidate checks pass. The required Security check fails on newly published RustSec advisories affecting dependencies unchanged from main:
libsqlite3-sys 0.38.2(RUSTSEC-2026-0459) andrmcp 1.8.0/3.4.1(RUSTSEC-2026-0457/0461/0462). Main passed this security check before the advisory records were published today. Clearing these requires an rmcp client major migration to at least 3.9 plus a Mesh/rusqlite dependency backport; latest stable Mesh still requires the affected rusqlite0.40/sys0.38 chain. Existing SQLx SQLite-links compatibility must be preserved. These broader dependency changes are recorded as follow-ups; no advisories were suppressed. Other full-CI jobs are still running.The nonrequired Codex security workflow still fails before review because
actions/checkoutrefuses fork code in the privilegedpull_request_targetcontext. This requires a safe base-workflow repair; unsafe checkout was not enabled. GitHub reports the PR mergeable, with a fresh review required. No merge, deployment, live registration or external schema apply was performed.Human acceptance remains open under the repository contributor checklist. An agent exercised the current changed endpoint; a human must still test and explicitly confirm before the contributor-checklist attestation can be added or this PR can merge. No attestation was added.
Review priority
P1 — Enables delivery of ordinary replies in explicitly watched threads.
Opened for review at the author's request. Remaining merge/rollout requirements: required dependency-security remediation, full-stack integration, human acceptance and current-range security review remain outstanding. Opening review does not attest completion of the contributor checklist.