Skip to content

feat(relay): read NIP-CW windows oldest first - #9641

Open
LordMelkor wants to merge 12 commits into
mainfrom
lordmelkor/thread-window-newer
Open

LordMelkor wants to merge 12 commits into
mainfrom
lordmelkor/thread-window-newer

Conversation

@LordMelkor

@LordMelkor LordMelkor commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Someone opening an "Oldest" view on a long thread or channel today waits while the client loads the entire conversation newest first; this PR adds direction: "newer" to NIP-CW thread and channel windows so the first page loads oldest-first in one request.

What changes

  • Capability & compatibility: advertises buzz-window-newer in NIP-11. Default requests and older 39006 bounds are byte-identical; newest-first windows with after or after_id now return 400 per NIP-CW (previously ignored). Also fixes channel windows ignoring since, plain filters missing top-level selection, and #e + depth_limit lacking signed exhaustion, kinds, and mirrored tie-breaking.
  • Thread mode: scans idx_thread_metadata_window backward (no migration), binds direction and forward cursor into tw:1, and rejects mismatched cursor fields.
  • Channel mode: walks monthly partitions forward two months at a time from the later of channel_floor (creation minus 960 s created_at tolerance) or the cursor, stopping under the read deadline (DbError::ReadDeadlineExceeded) if expired and tagging 39006 bounds with newer:. Pre-channel rows (restores/backfills) are read in one Range::Below pass when needed.
  • Expand-only schema (migrations/0106_channel_history_from_creation.sql): adds nullable channels.history_from_creation BOOLEAN with no default or backfill. Relay-created channels set true to skip the pre-floor pass; NULL (existing channels and older relays) and false (raw-SQL imports of older rows) keep it.
  • Writer routing & docs: newer pages always read the writer (forward_scan) so a lagging replica cannot sign has_more: false early (older continuations can still use replicas). Updates NIP-CW.md and bridge docs for the 960 s repair read and BUZZ_REPLICA_READ_MAX_AGE_MS.

What to decide or check

  • Rollout & rollback: expand-and-deploy in one PR (an optional scripts/maintenance/ repair for existing channels follows in its own PR once deployed). Rollback is data-safe if the previous binary starts without running the migrator (docs/database.md Rule 5); clients caching buzz-window-newer receive 400 and fall back to newest-first once NIP-11 clears (on transport reset for native, host restart for browser).
  • Writer load & metrics: watch buzz_db_route_decision{path="channel_newer"}, {path="thread_window_newer"} (forward_scan), and {path="bridge_query"} alongside writer auth-read latency; run testing checks on staging with production replica settings first.
  • Companion & migration number: relay half of block/buzz-app#3818 (app works without it, with slower scans). 0106 overlaps #9690, #9756, #9772, and #9838 (whichever merges later renumbers).
  • Human-test step: this PR has no buzz-review-completed marker. The end-user test was run by the maintainer's agent, not by a person; whether that satisfies the human-test step is the reviewer's call.

Testing

All runs on a separate Linux machine:

  • Head bf4bd04f2 (main d1236080e): cargo fmt --check, cargo clippy -p buzz-core -p buzz-db -p buzz-relay --all-targets -D warnings, cargo nextest (2,394 passed), and Postgres tests (1,634 passed) pass; buzz-admin migrate confirms nullable history_from_creation with no default.
  • End-user test: real Buzz browser app (block/buzz-app#3818 at 3edff2545) against a local relay at bf4bd04f2 passed 35/35 database-oracle checks with zero console or page errors.
  • Earlier heads & revert checks: isolated revert checks fail their targeted tests; just test-unit at 73d76b314 passed changed crates (buzz-voice/buzz-acp/buzz-agent/buzz-app desktop skipped for missing Linux build deps, with git grep confirming no callers of the changed thread-window API).

Necessity and minimality

Change Necessity Minimality
direction: "newer" (after/after_id, newer: 39006 bounds, writer routing) Channel windows only read newest first; #e + depth_limit lacks signed end, kinds, and mirrored tie order. One field and cursor on existing window modes; reuses thread index; default requests unchanged.
buzz-window-newer in NIP-11 Clients cannot tell whether a relay supports direction: "newer" without trying it. One capability string.
channels.history_from_creation (migration 0106) Rows below channel creation sort first, so oldest-first pages can skip older partitions only if stored state confirms none exist (preventing lock failures on empty older partitions). One nullable boolean on a row already fetched; no default, backfill, query, or index.
Size, known limits, database checklist, related PRs, and per-head test details

Size (22 files, +1,972 / −245)

  • Production: +553 / −148 (including migration and schema)
  • Tests: +1,338 / −81
  • Docs: +81 / −16
  • Dropped an earlier root_aux: false flag after confirming on a local 200-reply page that include_aux: false plus a client #e read returns the same 26 live events (block/buzz-app#3818 switches to by-id reads only on a busy-thread 503).

Writer load details

  • Newer pages hit the writer with or without BUZZ_REPLICA_READ_MAX_AGE_MS (without taking replica history concurrency permits). On a 2,500-reply Top scan, the reference plugin sends 7 requests / 14 windows (7 newer + 1 head + 6 replica-eligible older continuations, vs 1 head + 12 continuations newest-first). Busy-thread #e fallback (path="bridge_query") also hits the writer (38 requests for 2,529 replies in e2e). The plugin reads at background priority and reconnects only when visible after up to 10 s random delay.

Known limits

  • Busy threads: ScanBudget (8,192 raw rows/request) plus per-window root aux closure in bridge/thread_window.rs (both on main) can return 503 on busy threads (two 200-reply windows got 200 at 3,750 root reactions and 503 at 4,000; with 500 root reactions, 200 at 16 reactions/reply and 503 at 17). The app's own thread view caps at 2,000 events ("This thread didn't load" at 4,000); the reference plugin falls back to include_aux: false + by-id reads.
  • Short & sparse channels: channels under limit + 1 rows walk forward to the time ceiling; sparse long channels cost one statement per two months walked.
  • No channel row: without a floor, cursor pages walk from the cursor's month and head pages use one unbounded window below.
  • Late rows near present: created_at up to 900 s in the past can sort behind a served newer cursor; clients catch them via the NIP-CW repair read (which can still miss replica-lag rows if BUZZ_REPLICA_READ_MAX_AGE_MS is set).
  • Client fallback on rollback: clients with cached buzz-window-newer whose newest-first bounds fail display "Scan failed" with Retry and "Buzz order" until NIP-11 clears.

Database review checklist (docs/database.md)

  • Phase: expand and deploy; optional scripts/maintenance/ repair follows in its own PR using the community deletion lock (Rule 3).
  • No trigger, function, procedure, rule, or foreign key added; post-0104 migration lint passes.
  • No existing rows mutated and no backfill; not a contract migration.
  • Rule 4 locations: migrations/0106_channel_history_from_creation.sql and schema/tables/public/channels.sql; admin_schema_parity_between_desired_state_and_migrations and the migration count test pass.
  • Deployed relay compatibility: all channels inserts name columns and nothing selects * from channels (git grep on main d1236080e, plus channel_window_pages_rows_older_than_the_channel_from_both_ends with NULL).
  • Locks: SET LOCAL lock_timeout = '5s'; catalog-only nullable column with no default, no table rewrite, and no new index.

Related PRs

  • block/buzz-app#3818: app half (works with or without this PR, slower scans without it).
  • block/buzz#9632: closed PR replaced by this one.
  • block/buzz#8981 (draft, conversation import): pre-channel imported rows returned in both directions.
  • block/buzz#7852 (WebSocket thread windows): conflicts in NIP-CW.md and will need to handle direction.
  • block/buzz#9210: conflicts in recent_pass.rs.
  • block/buzz#9690, block/buzz#9756, block/buzz#9772, block/buzz#9838: also add migration 0106.

Detailed test history

  • Head bf4bd04f2 (main d1236080e, pre-floor review fix on cec39df69): channel_window_pages_of_a_new_channel_skip_older_partitions fails with 55P03 before the fix and passes after. Dropping the mark from any of the three channel inserts, treating NULL as true, walking a marked channel from its cursor, or keeping the below-floor pass for a marked channel each fails its test.
  • Head cec39df69 (main e95d7a950): cargo nextest 2,391 passed; Postgres 1,616 passed; isolated reverts fail tests for floor-clamp bypass, writer routing (forward_scan), spent-deadline stop, boundary cases (00:05 Mar 1 channel with Feb 28 / Mar 2 rows, 1970 cursor with locked pre-channel partition, hidden channel row with locked later partition), 960 s tolerance off by 1 s, 55P03 lock checks, and page-1/no-page-2-aux checks. End-user run against block/buzz-app#3818 (cf121aa92) passed 35/35.
  • Rebases: block/buzz#9667, block/buzz#9549, #9689, #9691, 9ea57cba2 after #9678 (store/event.rs), and e95d7a950.

Made with human guidance from the maintainer driving this work.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

🔐 Codex Security Review

Note: This is an automated, security-focused review generated by Codex.
Use it as a supplement to human review; false positives are possible.

Scope

  • Exact PR diff: d1236080eb0c244ea03323f708e2e85a68e4d8cb...bf4bd04f2d05efb89eeab3dd4c45e0a3a6123bfd
  • Model: gpt-6.1-sol

💡 Click "edited" above to see earlier reviews for this PR.


Review Summary

Overall Risk: NONE

No concrete security, correctness, or reliability findings were identified in the authorized PR range.

Findings

No concrete security, correctness, or reliability findings were identified.

Notes

  • Review used read-only inspection of source, callers, tests, migrations, and history. Builds and tests were not executed.

Generated by Codex Security Review |
Requested by: @LordMelkor |
Workflow run

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

🤖 This is a comment, not an approval. A human maintainer needs to review this PR.

I read the full diff against NIP-CW and the surrounding code and found no blocking bugs.

What checks out:

  • Keyset order is an exact mirror. The newer order created_at ASC, id DESC with created_at > ts OR (= ts AND id < id) matches a backward scan of both idx_thread_metadata_window (created_at DESC, event_id) and the channel index (created_at DESC, id). Both directions use LIMIT+1 as the has_more probe, and next_cursor is the last retained raw row, so skipped rows cannot stall it.
  • The forward partition walk is sound. Windows are disjoint two-month ranges (>= from AND < to), so same-second ties never straddle a window. A cursor's month floor is inclusive, and advance stops at the horizon for regular-kind reads or opens one final window otherwise. The floor and ceiling literals stay in range when a cursor is far in the future.
  • Newest-first callers are unchanged: the default thread binding array, the older 39006 d-tag and content bytes, and the 39007 content are identical, and older channel reads still take split_for.
  • Auth and visibility reuse the existing paths (deleted_at IS NULL, accessible-channel and reader checks). Newer pages are routed as Bounded, so they never take a Covered replica arm.
  • Tests cover same-second ties in both directions, exact-multiple final pages, partition-locking, month and horizon boundaries, malformed and cross-direction cursors, and distinct 39006 d-tags.

Finding (P3, docs): the NIP and bridge doc say reading from both ends meets "without a gap or an overlap". That holds only for quiescent data. Ingest accepts created_at up to 900 s in the past, so a row committed after a newer page was served, with created_at behind that page's cursor, is never returned by later newer pages. In a newest-first read the same late row lands in a not-yet-read older page. Near the live edge, has_more: false therefore means "caught up at read time". A sentence telling clients to keep a live subscription, or to overlap the tail by about 960 s, would make this explicit.

Known limits already listed in the description (channel floor, writer load without a replica budget) look accurately described.

Comment thread docs/nips/NIP-CW.md Resolved
@LordMelkor
LordMelkor force-pushed the lordmelkor/thread-window-newer branch from 73d76b3 to 40814f0 Compare November 18, 2026 08:03
@github-actions github-actions Bot added codex-security-review-current The posted Codex security review matches its recorded range. and removed codex-security-review-current The posted Codex security review matches its recorded range. labels Nov 18, 2026

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

🤖 Follow-up on 40814f0 (rebased onto main; the feature commit is unchanged): no findings.

  • 40814f0: the NIP-CW and bridge-window docs now say that the two ends meet only while no rows are being written. They cite the relay's 900 s past created_at bound, which matches the ingest drift bound, and tell oldest-first clients to keep a live subscription or reread the newest stretch. That closes my P3.
  • 51d1035: refactors the oldest-first window tests' setup. It's test-only, inside postgres_tests.

This still needs a human maintainer's review, because it comes from outside the core maintainer group.

@LordMelkor
LordMelkor requested a review from a team November 18, 2026 16:47
@LordMelkor
LordMelkor force-pushed the lordmelkor/thread-window-newer branch from 40814f0 to 590717a Compare November 18, 2026 19:06
@github-actions github-actions Bot added codex-security-review-current The posted Codex security review matches its recorded range. and removed codex-security-review-current The posted Codex security review matches its recorded range. labels Nov 18, 2026

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

🤖 Follow-up on 590717a2, which is a rebase onto main after #9549. The only change to the feature is the conflict resolution in get_channel_window_on and two test call sites in event.rs. Older pages now bound the cursor with <= and newer pages with >=, and the id tie-break comparisons match each other in both directions. The test refactor and the docs commits are unchanged, and my earlier docs note is addressed. buzz-db builds with tests and the recent_pass tests pass. I didn't run the Postgres-backed tests locally. No new findings.

This is an outside contribution, so a human maintainer still needs to review it before merge.

@LordMelkor
LordMelkor requested a review from a team November 18, 2026 20:41
@LordMelkor
LordMelkor force-pushed the lordmelkor/thread-window-newer branch from 590717a to 2f04e99 Compare November 19, 2026 02:01
@LordMelkor
LordMelkor deployed to codex-review November 19, 2026 02:01 — with GitHub Actions Active
@github-actions github-actions Bot added codex-security-review-current The posted Codex security review matches its recorded range. and removed codex-security-review-current The posted Codex security review matches its recorded range. labels Nov 19, 2026
@LordMelkor
LordMelkor force-pushed the lordmelkor/thread-window-newer branch from 2f04e99 to db22e6d Compare November 19, 2026 04:22
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 19, 2026
@LordMelkor
LordMelkor deployed to codex-review November 19, 2026 04:22 — with GitHub Actions Active
@LordMelkor

LordMelkor commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Head bf4bd04 rebases onto main d123608 and adds one commit for jedwards27's review of cec39df (reply: #9641 (comment)).

  • Pre-floor pass on new channels: migration 0106 adds channels.history_from_creation, nullable with no default, and the relay's three channel inserts set it to true. Only true lets an oldest-first page start at the month of the channel's floor without first reading every older partition. NULL and false keep that pass, so restored and backfilled rows still come first.
  • Imports: runtime/replica_fence.rs and docs/database.md Rule 3 now say a raw-SQL import that stores rows older than a channel sets the column to false.
  • PR body: the Schema and Rollout notes, the core-change table, Size and Testing are updated, and the database review checklist is added.

Verified at bf4bd04 on a separate Linux machine: cargo fmt and clippy are clean, and 2,394 unit tests and 1,634 Postgres tests pass; the new test fails with 55P03 before the fix and passes after it; each mutant listed in Testing fails a test; the end-user test with block/buzz-app#3818 at 3edff2545 passes 35/35, with no console or page errors. CI: green, 59 passed and 32 skipped.

Latest app head: the end-user test with block/buzz-app#3818 at e1527f2ef against this head bf4bd04 passes 35/35 on a separate Linux machine, with no console or page errors.

Current main: main 0e7fd48 includes #9848, which reverts #9591 in two files this PR also changes, crates/buzz-db/src/store/event.rs and crates/buzz-db/src/runtime/tests.rs. The merge is clean. At bf4bd04 merged with 0e7fd48, on a separate Linux machine: cargo fmt and clippy are clean, 2,394 unit tests and 1,634 Postgres tests pass, and the end-user test with block/buzz-app#3818 at 3edff2545 passes 35/35, with no console or page errors.

Older relay: as partial evidence toward the desktop check in jedwards27's approval, the end-user test of block/buzz-app#3818 at 3edff2545 ran against relay main d123608, which has no buzz-window-newer. It used the browser host and #3818's test fixture plugin on a separate Linux machine. 31 of its 35 checks pass, with no console or page errors. Two don't apply to that relay because both expect the partial read that only buzz-window-newer allows: a filter submitted after only the first 200 replies were read, and a total that stays 200+ while late replies arrive. When the relay lacks the capability, #3818's fixture reads the whole thread before it shows a window, so its totals are exact. In the late-replies check the total went from 2,499 to 2,529 while window 1 stayed the same. The other two call direction: "newer" on the relay directly, so they were left out. Not run: the Thread Sort plugin the review names, the native desktop app, a stale capability with Retry, a relay rolled back during a session, native iOS and Android, and a mixed-version rollback rehearsal.

Earlier: head cec39df rebases 80036cc onto main e95d7a9 with identical patches and adds one test-only commit ("test(db): pin the channel floor's tolerance and the newer pages' failures"); no production code changed.

  • Lock-timeout error check: channel_window_newer_pages_forward_across_partitions and channel_window_newer_head_plans_only_the_partitions_it_reads now require SQLSTATE 55P03 instead of accepting any error.
  • Write-tolerance boundary: channel_floor_allows_the_write_tolerance pins the 960 s boundary (March at 960 s after midnight March 1, February 1 s earlier) and drops the self-recomputing first assertion.
  • Page-1 aux check: thread_window_newer_pages_forward also checks that page 1 carries no aux for a reply on page 2.
  • Duplicate row removed: dropped the duplicate "channel floor" row from oldest_window_follows_the_earliest_month (covered by the tolerance test above).

Verified at cec39df on a separate Linux machine: cargo fmt --check, clippy, 2,391 cargo nextest tests, and 1,616 Postgres tests pass; reverting the tolerance by one second either way, the SQLSTATE 55P03 check, or the page-1 aux check fails its test; end-user test with block/buzz-app#3818 at cf121aa92: 35/35 database-oracle checks pass, with no console or page errors.

Earlier, head 80036cc answered the review of 72a6f51df (4 findings fixed, each replied to on its thread; earlier heads answered reviews of 2f04e99 and db22e6d36). Summary of changes across these rounds:

  • Writer routing for newer pages: all newer pages read the writer (route reason forward_scan), preventing continuations from hitting a lagging replica.
  • Shared deadline on floor lookup: the floor lookup runs inside the read's transaction under the shared deadline, stopping before the next statement once expired.
  • Bounded oldest-first walk: oldest-first channel pages start at the later month of the cursor or channel floor, planning at most one window per two months of the channel's life. Tested with a locked partition older than the channel and after: 0 (fails without the clamp).
  • Missing channel row on cursor pages: when the channel row is invisible (e.g., lagging replica), cursor pages walk from the cursor's month instead of an unbounded window (channel_window_newer_cursor_without_the_channel_row_walks_from_the_cursor fails without the fix).
  • Pre-channel rows (72a6f51df follow-up): when the cursor is below the floor's month, a page first reads all rows below that month in one pass, then walks forward. Tested in both directions.
  • 960 s allowance: tested by channel_window_newer_head_reads_rows_older_than_the_channel_within_the_floor (fails if removed).
  • Late rows & reconnects: NIP-CW now requires a repair read (from first-request time minus 960 s) when an oldest-first scan reaches the newest rows, with a live subscription opened beforehand (since no later than that start), and documents what replica reads (BUZZ_REPLICA_READ_MAX_AGE_MS) can miss. Both client recipes cover "newer" reconnects.
  • root_aux removed: include_aux: false plus a client #e read of a 200-reply page's reply ids returned the same 26/26 live reactions, edits, and deletions as the relay closure on a local relay.
  • Busy threads: shared 8,192-row window scan budget and per-window root aux closure (both on main) can return 503 on busy threads read from both ends. feat(messages): let a plugin sort, filter and page a reader's rows buzz-app#3818's reference plugin falls back to reading reactions by id (measured numbers in Known limits).
  • PR body: added Rollout (turning off, writer load, metrics, pre-enable checks), the newest-first 400 change, and related PRs.

Verified on a separate Linux machine at 80036cc: cargo fmt, clippy, 2,381 unit tests, and 1,581 Postgres tests pass; reverting any review fix fails its test; the end-user test by the maintainer's agent with block/buzz-app#3818 passes 35/35 checks (details in Testing).

@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 19, 2026

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

🤖 Follow-up on 590717a. Besides the rebase, three new commits:

  • Each oldest-first channel page now starts its forward walk at max(channel floor, cursor) instead of at the cursor's month. Before, a cursor of 0 walked from 1970. Two Postgres tests cover this.
  • root_aux is dropped from the thread-window request, binding and NIP-CW.
  • NIP-CW now says the late-row subscription must start before the scan.

The new code reads correctly. The buzz-core thread_window and buzz-db recent_pass unit tests pass, and buzz-relay builds. I didn't run the Postgres-backed tests locally. One optional P3 is inline.

This needs approval from a human maintainer.

Comment thread crates/buzz-db/src/store/thread.rs Resolved
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 19, 2026
@LordMelkor
LordMelkor deployed to codex-review November 19, 2026 19:51 — with GitHub Actions Active
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 19, 2026

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

🤖 This is a follow-up to my review at 72a6f51. The branch was rebased onto main, and the first seven commits are unchanged. The three new commits (ebf6b7c, 7e867a8, 80036cc) address the four findings from the other review:

  • Rows below the floor are now read in a single Range::Below pass.
  • Requests for newer pages always go to the writer.
  • The floor lookup and every later pass share one deadline (ReadDeadlineExceeded).
  • NIP-CW now requires a repair read.

My earlier point, a cursor page that came back without its channel row, is still fixed. I checked the new code against the previous keyset and routing logic and found no bugs. The 35 buzz-db tests that cover this code pass on a fresh Postgres 17: channel_window*, recent_pass, thread_window, read_statements_share and routing.

This is a contribution from outside the core maintainer group, so a human maintainer still needs to review and approve it before merge.

@LordMelkor
LordMelkor requested a review from a team November 19, 2026 21:25
@LordMelkor
LordMelkor force-pushed the lordmelkor/thread-window-newer branch from 80036cc to cec39df Compare November 20, 2026 19:18
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 20, 2026
@LordMelkor
LordMelkor deployed to codex-review November 20, 2026 19:18 — with GitHub Actions Active
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 20, 2026

@jedwards27 jedwards27 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 ⚠️ Needs a desktop and mobile check before merge
NIP-CW adds direction: newer, after/after_id, direction-bound 39006 and 39007 overlays, and NIP-11 buzz-window-newer. Check Desktop Thread Sort against the enforcing relay and an older/rolled-back relay, and iOS/Android channel history against both, including cursor/Retry and accessibility.

:bot: Jude’s code review agent — recommendation: request changes (this agent submits COMMENT reviews under this repository’s policy).

Reviewed: 9f49216f8beb1af33a8f57d2c175de95033925ca..cec39df69dea867b2ce7ff45a07f668766f5a11b (clean worktree). Risk: high — cursor and partition routing change a messaging-read contract.

Blocking finding — new oldest-first channel head unnecessarily depends on all pre-channel partitions. crates/buzz-db/src/store/recent_pass.rs:305-320 selects Range::Below(channel_floor_month) unconditionally on a newer head with no cursor; :159-187 gives that pass only an upper bound, and crates/buzz-db/src/store/thread.rs:720-751 runs it before the bounded forward windows. Thus a young channel whose entire history is recent still plans/locks unrelated old partitions before returning page one. On isolated PostgreSQL 17.12 at this head, with eight recent roots and an empty January partition held in ACCESS EXCLUSIVE, newer heads at limits 1/2/4 all failed with SQLSTATE 55P03 at the test’s 200 ms lock timeout in both automatic and forced-generic plan modes; older heads succeeded in 0.485–0.718 ms, and newer heads recovered after unlock. Plain EXPLAIN also blocked, confirming the dependency arises during planning. This is an availability regression under old-partition maintenance/lock contention, not evidence of fleet-wide latency or data loss. thread.rs:2863-2957 tests locks on later partitions, not this pre-floor case.

Author action: preserve restored/backfilled pre-channel row correctness while avoiding the all-history prepass on the ordinary newer head, or provide a bounded design plus production-like partition-count/lock-contention evidence showing this cost acceptable. Add a regression test that locks an empty pre-floor partition for a young channel and contrasts older/newer first-page behavior. A simple deletion of the prepass would lose backfilled rows and is not the requested fix.

Other contracts traced: strict inverse keyset/cursor validation; signed, direction-distinct bounds; writer-only newer routing and shared read deadline. No separate ordering/signing defect found in these paths. Mobile currently sends only the older channel-window request, while the Desktop counterpart is block/buzz-app#3818 (separately reviewed).

Validation: GitHub Actions run 44800846738 at exact head completed success (attempt 1): Rust/PostgreSQL/relay E2E/backend/desktop integration and macOS Desktop build passed; mobile jobs skipped. Independent Blox carl-9641-forward-read: isolated desired-state PostgreSQL, focused temporary production-path test cargo test -p buzz-db --lib review_newer_head_empty_pre_floor_partition_lock -- --ignored --nocapture --test-threads=1 passed (1/1); no committed test change. Author-reported full crate suites and browser oracle are not independent checks. Manual/native evidence: none; no Desktop/iOS/Android or rollout/rollback device run performed.

Verification owner: author for the partition-read defect and regression test; reviewer/tooling for the Desktop + iOS/Android enforcing/older-relay/rollback matrix before merge (capability admission, same-second cursor chain, failed-page Retry, keyboard/VoiceOver/TalkBack). The latter is an unmet merge check, not a second code defect. Residual risk: production partition counts and native client journeys remain unmeasured.

LordMelkor and others added 12 commits November 21, 2026 08:34
Add `direction: "newer"` to both NIP-CW window modes. A newer window pages
from the oldest row in `created_at ASC, id DESC` order, continued by
`after`/`after_id`; the other direction's cursor fields are rejected.

- Thread mode scans idx_thread_metadata_window backward (no migration),
  binds the direction and cursor into the tw:1 hash, and accepts
  `root_aux: false` to leave the root's aux out of the closure. Default
  requests keep their exact binding.
- Channel mode walks the monthly partitions forward two months at a time
  (`oldest_for`, `Forward::advance`), mirroring the recent-first split, and
  stops at the first window that fills the page. The head page starts at the
  month the channel was created, less the write path's created_at tolerance
  (`channel_floor`), so it never plans the older partitions. Newer 39006
  bounds carry a `newer:` d-tag prefix and a `direction` field; older bounds
  are byte-identical.
- Newer pages route to the writer: no cursor bounds the rows they read.
- NIP-11 advertises `buzz-window-newer`; NIP-CW and the bridge channel
  window doc describe both directions.

Made with human guidance from the maintainer driving this work.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
The two Postgres tests of oldest-first windows built the same dated
channel, paged with the same eight-argument read, and locked partitions
the same way. They now share helpers for each, with the same assertions.

Made with human guidance from the maintainer driving this work.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
A row accepted with a past created_at after a newer page was served can
sort behind that page's cursor, so the gapless meeting holds only while
no rows are being written.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
A continuation page walked forward two months at a time from its cursor's
month with no lower limit, so a cursor at 0 walked from 1970: hundreds of
statements, each with its own SQL text. Every page now starts at the later
of its cursor and the channel's floor, so a page walks at most one window
per two months of the channel's life.

Tests cover a row inside the 960 s allowance before the channel's creation
on the head page, and a cursor below the floor, which must not plan the
partitions under it. The floor rule is documented beside the replica
fence's created_at floor, which it rests on.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
A plugin gets the same rows and the same edits, reactions and deletions
with include_aux false and one read of the page's aux by #e, so the relay
does not need a flag that leaves the root's aux out of later pages.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
Live delivery drops rows older than a subscription's since, so a
subscription opened with since: now misses the same late rows an
oldest-first scan misses. Drop root_aux from the spec.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
When the channel's row is not visible to the connection, as on a replica
behind the writer, there is no floor, and the clamp dropped the cursor
too: a continuation page read one window unbounded below and planned
every partition up to the ceiling. Fall back to the cursor, as before
the clamp.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
Four review findings on oldest-first (`direction: "newer"`) windows:

- Rows older than the channel's floor. A restore or backfill can store
  rows in months before the channel's creation, and the walk from the
  floor's month skipped them while the relay signed exhaustion. A page
  whose cursor is below that month, the head page included, now reads
  every row below it in one pass (`Range::Below`), then walks from it. A
  cursor at 0 still costs one statement plus the walk over the channel's
  life, not one window per two months since 1970.
- Coverage before advancing a cursor. With the head budget on, a newer
  continuation could land on a replica that had yet to replay the row
  the previous page probed, and sign `has_more: false`. Thread and
  channel newer pages now always read the writer (route reason
  `forward_scan`).
- One deadline for the whole walk. The channel's floor is now read
  inside the read's transaction, under its deadline, and a read whose
  deadline is spent stops before its next statement
  (`DbError::ReadDeadlineExceeded`, reported as a cancelled statement)
  instead of running each later pass under a 1 ms timeout.

- Late rows. The past-timestamp check runs when a row is accepted, not
  when it commits, so a row can land any distance behind a served
  cursor. NIP-CW now asks an oldest-first reader for a live subscription
  with no `since`, established before its first page, or a repair read
  of the crossed range when its scan reaches the newest rows.

Tests: both directions over rows dated before the channel, for every
limit, from the head and from a cursor at 0; the newer routing tests
turn the head budget on; the shared-deadline test spends the deadline.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
A REQ's EOSE does not mean that every relay node delivers to the
subscription: another node starts when Redis confirms it, which can be
after EOSE. A late row that commits in between reaches neither the
subscription nor a later page, so a live subscription cannot replace the
repair read of the crossed range.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
The repair read catches every row that committed before it only when
the relay serves it from its writer. Buzz does unless the operator sets
BUZZ_REPLICA_READ_MAX_AGE_MS; then a read without `until` can come from
a replica up to that age behind. Say so.

A live subscription with `since: now` never delivers a row dated before
now, and the relay accepts rows dated up to 900 seconds back. A newer
reader's subscription therefore starts at the repair range's start.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
…ures

The floor test now checks both sides of the write path's tolerance: a
channel created exactly that long after midnight starts its first window
that month, and one second earlier starts it the month before. A table
row that repeated another row's shape is gone.

The two newer-page tests that lock a partition now require the lock
timeout, not any error. The thread test checks that the first page leaves
out the aux of a reply on the second.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
An oldest-first channel head read every row below the month of the
channel's floor in one pass before walking forward, because a restore
or backfill can store rows older than the channel. That pass has no
lower bound, so a young channel's first newer page planned and locked
every older partition, and failed while maintenance held one of them.

A new nullable channels.history_from_creation column records which
channels can have no such rows. The three insert paths that create a
channel set it true; existing rows stay NULL, and the column has no
default in the migration or the declarative schema, so adding it marks
nothing. Only true lets a head, or a cursor below the floor's month,
walk from that month with nothing read below it. NULL and false keep
the pass, so restored and backfilled rows still page. A repair that
stores an older row must set the channel false, as the replica-fence
docs and docs/database.md now say.

Tests: a channel, a channel with its own id and a DM, each created on
the write path, page both heads and a newer page from a cursor at 0
with every partition before July 2026 locked, in custom and generic
plans; the rows-older-than-the-channel test runs for NULL and false.

Co-authored-by: Clod <c7b21872e9ddb79ca62967d0e21e6a4518a669eb04648e963cdfb2426e62fafb@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Krish Ray <kray@block.xyz>
@LordMelkor
LordMelkor force-pushed the lordmelkor/thread-window-newer branch from cec39df to bf4bd04 Compare November 21, 2026 14:24
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 21, 2026
@LordMelkor
LordMelkor deployed to codex-review November 21, 2026 14:24 — with GitHub Actions Active
@LordMelkor

Copy link
Copy Markdown
Contributor Author

🤖 Thanks, jedwards27. Fixed in bf4bd04, rebased on main at d123608.

Why the fix stores a mark: rows from before a channel's creation sort first, so a head page can skip the older partitions only if something already stored says the channel has no rows there. No unpartitioned table covers every row a page can return: thread_metadata is a LEFT JOIN, and a top-level message with no replies has no row in it. A lock timeout, or a walk one partition at a time, would still plan the locked partition once.

The fix:

  • Migration 0106 adds channels.history_from_creation BOOLEAN, nullable with no default, so no existing row changes. schema/tables/public/channels.sql matches it, and the parity test compares both bootstrap paths.
  • The relay's three channel inserts (create_channel, insert_channel_rows and find_or_create_dm) set it to true.
  • Only true lets a newer head, or a cursor below the month of the channel's floor (its creation less the 960 s tolerance), start its walk at that month (ChannelFloor::FromCreation in recent_pass.rs). NULL and false keep today's pass below the floor, so restored and backfilled rows still come first. That covers every existing channel, and any channel an older relay creates during a rollout or rollback.
  • A raw-SQL repair or import that stores rows older than a channel's creation, less the floor's tolerance, must set the column to false in the same transaction. This is written next to the bypass note in runtime/replica_fence.rs and in Rule 3 of docs/database.md.
  • A repair that marks existing channels true is left for its own PR after rollout, as Rule 3 asks. Until then, existing channels keep today's cost and stay correct.

Tests:

  • channel_window_pages_of_a_new_channel_skip_older_partitions creates a channel through each of the three inserts and locks every partition below July 2026 in ACCESS EXCLUSIVE mode. It reads the older head, the newer head and a newer page from an epoch cursor, at limits 1, 2 and 4, with automatic and forced generic plans. Before the fix, the newer head fails with 55P03. After it, every read returns its rows.
  • channel_window_pages_rows_older_than_the_channel_from_both_ends now runs with the mark NULL and false, and still returns the pre-channel rows from both ends at every limit.
  • Each of these changes fails a test: dropping the mark from any one of the three inserts, treating NULL as true, walking a marked channel from its cursor, or keeping the pass for a marked channel.

Checked on a separate Linux machine at bf4bd04: cargo fmt and clippy are clean, and 2,394 unit tests and 1,634 Postgres tests pass. The end-user test with block/buzz-app#3818 at 3edff2545 passes 35/35, with no console or page errors. An automated review of the change found nothing.

The Desktop, iOS and Android matrix your review lists as a merge check is still open.

@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 21, 2026

@jedwards27 jedwards27 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 ⚠️ Needs a desktop and mobile check before merge
NIP-CW adds direction: newer/after, direction-bound newer: 39006 cursors, and a channel-history floor optimization; check Desktop Thread Sort and iOS/Android history against enforcing and older/rolled-back relays.

Verdict: APPROVE — no unresolved author-actionable defect found in the integrated source review. The earlier pre-floor blocker at cec39df is fixed at this head; this approval does not close the client/native or release rehearsal gates.

Reviewed: base d1236080eb0c244ea03323f708e2e85a68e4d8cb → head bf4bd04f2d05efb89eeab3dd4c45e0a3a6123bfd; clean local review checkout. Risk: high — relay cursor/history semantics, partition reads, and an additive migration are shared client/persistence contracts.

Behavior/contracts traced: recent_pass.rs:318–353 skips the pre-floor scan only for Some(true); NULL/false still scan pre-floor rows. store/channel.rs:146,391 and store/dm.rs:385 set true for newly created channels/DMs; migration 0106 has no default, so old writers and existing rows remain NULL. thread.rs:721–761 reads the floor and pages in one transaction/deadline; its channel_window_pages_of_a_new_channel_skip_older_partitions regression locks old partitions and covers normal, explicit-ID, and DM creation in custom and generic plans. The documented raw pre-floor repair must set false in the same transaction and fence replica routing (docs/database.md:263–274). Older mobile cursors and 39006 remain compatible; Desktop gates forward requests on NIP-11 buzz-window-newer, and an in-session stale capability after relay rollback produces a visible scan failure/Retry and Buzz-order escape rather than a silently plausible wrong order (see block/buzz-app#3818).

Findings: no blocking source defect. Legacy/old-writer channels intentionally retain the potentially expensive historical scan; do not backfill their mark to true without a row-bound proof. Author action: none. Verification owner: reviewer/tooling for Desktop Thread Sort on the enforcing and older relay, including in-session rollback/stale-capability and Retry; reviewer/tooling for iOS and Android history/continuation/failure and accessibility on both; release operator for mixed-binary migration/rollback, especially auto-migration VersionMissing on older binaries (docs/database.md:326–340). These are outstanding external verification gates, not claims that those journeys passed.

Validation: at local HEAD bf4bd04 with clean worktree, git diff --check d1236080...HEAD passed. Exact-head CI attempt 1 succeeded: Rust lint/unit tests, PostgreSQL tests, relay and backend integration E2E, all three Desktop E2E integration shards, security and DCO; some duplicate matrix jobs were skipped by selection, not reported as tests run. Independent local PostgreSQL suite, native Desktop/iOS/Android device journeys, and mixed-version deployment/rollback not run in this review. Manual/native evidence: none at the exact artifact. Residual risk: client/release gates above must be owned before merge; green CI does not establish native behavior or rollback safety.

@LordMelkor
LordMelkor requested a review from a team November 23, 2026 15:03

This branch was successfully deployed

1 active deployment
codex-review — bf4bd04f Deployed Nov 21, 2026 by LordMelkor via Run Codex Security Review #17132
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex-security-review-current The posted Codex security review matches its recorded range.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants