Skip to content

p1: feat(relay): support explicit operator listener thread watches - #8877

Open
mcdickenson wants to merge 7 commits into
block:mainfrom
mcdickenson:airspace/bk-thread-webhooks-1031-883db6fa
Open

mcdickenson wants to merge 7 commits into
block:mainfrom
mcdickenson:airspace/bk-thread-webhooks-1031-883db6fa

Conversation

@mcdickenson

@mcdickenson mcdickenson commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Review brief

Add explicit, target-consented listener watches for replies in a shared thread.

Agent-prepared from the existing PR description and reported validation.

Context
Risk 🐱 low · 🔪 medium · 💣 high
New persisted watches and signed callbacks must preserve membership, scope and lifecycle fencing.
Timeline 🟡 P1 — Important integration or monitoring follow-up. The recorded evidence does not establish a launch-stopping failure.
Seller impact Enables watched-thread replies to reach the agent listener; existing explicit mentions retain their current path.
Review requested 👀 Human review requested. Focus: Signed registration, expiry/revocation, live-root checks and duplicate outbox identity.

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 p tag 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/threads accepts 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_id within 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 in docs/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 48a703df2874b182d382a068995f3d822ec239ea after merging main at 22d96d94ef043292803b6d5c929652abd69612dd:

  • Full just ci passed, including Rust checks and unit tests, desktop frontend/native tests and builds, web build, and mobile tests.
  • All 13 focused PostgreSQL tests passed using the repository desired-state setup and per-test isolation wrappers against task-owned PostgreSQL 17/Redis. Coverage includes migration application, actual schema parity, authenticated registration/removal, consent, membership, scope, expiry, capacity, duplicate mention/watch handling, existing listener behavior and tenant purge.
  • The freshly built relay passed real loopback NIP-98 HTTP exercises against a fresh schema: unconfigured listener POST 403, target-consented POST 200 with 2592000-second expiry, exact DELETE 200. This bounded thread-route smoke excludes Git/object-storage behavior and uses the existing Git conformance-probe opt-out. Its process and temporary database were cleaned up afterward.
  • Merge conflict resolution preserves main's media, membership and community-policy wiring. The unmerged listener migration is now 0087; existing main migrations remain unchanged. An independent agent reviewed this integration and found no issues.
  • The full Docker/Compose integration lane was not rerun in this pass. The passing focused database tests and live endpoint exercise above are the current integration evidence.

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) and rmcp 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/checkout refuses fork code in the privileged pull_request_target context. 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.

Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
@github-actions

github-actions Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

🔐 Codex Security Review

Status: review required for the current range.

The current range is a12a9995c458e45c4901763f029fd2ec006f610d...d6ffed5bd4ff3bcedca4e1f73c786be02dbf589e.
A new review must complete for this exact range. When manual authorization
is required, a user with write access must comment exactly
@buzz-security-review d6ffed5bd4ff3bcedca4e1f73c786be02dbf589e to authorize a new review.
Any previous review applies only to its recorded range.

@mcdickenson
mcdickenson marked this pull request as ready for review November 4, 2026 20:13
@mcdickenson
mcdickenson requested a review from a team as a code owner November 4, 2026 20:13
@mcdickenson
mcdickenson requested a review from baxen November 5, 2026 14:57

@joahg joahg 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.

🤖 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>
@mcdickenson
mcdickenson marked this pull request as draft November 5, 2026 23:53
@mcdickenson mcdickenson changed the title feat(relay): support explicit operator listener thread watches feat(relay): [P1] support explicit operator listener thread watches Nov 9, 2026
@mcdickenson
mcdickenson marked this pull request as ready for review November 9, 2026 01:13
Signed-off-by: Matt Dickenson <mdickenson@squareup.com>
@mcdickenson mcdickenson changed the title feat(relay): [P1] support explicit operator listener thread watches p0: feat(relay): support explicit operator listener thread watches Nov 9, 2026
@mcdickenson mcdickenson changed the title p0: feat(relay): support explicit operator listener thread watches p1: feat(relay): support explicit operator listener thread watches Nov 9, 2026

@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.

🤖 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(

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.

🤖 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?;

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.

🤖 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 \

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.

🤖 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 \

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.

🤖 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')) \

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.

🤖 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>,

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.

🤖 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"))?;

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.

🤖 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 {

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.

🤖 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;

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.

🤖 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

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.

🤖 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.

mcdickenson and others added 2 commits December 1, 2026 08:29
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>

This branch had an error being deployed

1 failed deployment
codex-review — d6ffed5b Deployed Dec 1, 2026 by mcdickenson via Run Codex Security Review #19059
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.

3 participants