You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(relay): index tag filters instead of comparing every tag with every value - #1287
Cherry-picked from @saket0187's fork (saket0187/nostream#4, commit 5f460c6b) with -x, so the authorship and message are his.
Two defects, one diff.
The crash.src/utils/event.ts:52 did tag[1].startsWith(...) for a #g prefix criterion. A tag with no value (["g"], which any client can publish) has no tag[1], so the comparison throws — inside the broadcast loop and inside the stored read, which means one malformed tag cut a live broadcast short and stopped a REQ before EOSE. Every non-string or absent tag value is now skipped at index time instead of dereferenced.
The cost. Generic tag matching was event.tags.some(tag => criteria.some(criterion => isMatching(...)(tag))) per filter — |tags| × |criteria| predicate calls, with both sides attacker-sized: the event comes off the wire and the criteria come from a subscription the poster opened. Several subscriptions per connection multiply it, on the worker's event loop.
What changes. Tag criteria compile once per subscription (and once per REQ on the stored read); the event's single-letter tags are indexed once per broadcast and shared by every filter and every client. Exact criteria become a set intersection that probes the smaller side; #g prefixes binary-search a sorted value list. A tag name is never scanned against every criterion again.
Evidence
Applies to main at ccf6690; pnpm run test:unit — 3664 passing, including 19 new cases in test/unit/utils/event.spec.ts and the adapters/handler specs.
Red check, run by hand on both trees: isEventMatchingFilter({ '#g': ['u4*'] })(event with tags [['g'], ['t', 'valueless-g']])throws on main — Cannot read properties of undefined (reading 'startsWith') — and returns false here, while { '#t': ['valueless-g'] } still matches true on both.
The acceptance cases are pinned as tests: probes grow with the smaller of the two sides rather than their product, and 10 000 criteria are rejected in at most 10 000 probes.
Two cucumber scenarios: a live broadcast into a subscription filtered on a different tag than the valueless one, and a stored read whose first g tag has no value. Both exercise the throw on main.
A case pins that a trailing * is a prefix only for #g, so exact-match criteria elsewhere still treat * literally.
Scope decision. The issue's third fix-shape bullet — an aggregate matching budget per connection — is dropped, and the issue records it (signed 2026-11-29): maxSubscriptions, maxFilters and maxFilterValues already bound what one subscription can carry, and a connection-wide budget has no default anyone specified. The bounded-time acceptance line stays, and this diff meets it without a budget.
Known, non-blocking.src/app/peering-sync-worker.ts still calls isEventMatchingFilter(filter)(event) per event, so it recompiles criteria per event rather than per filter. It is correct and still cheaper than before; moving it to createSubscriptionMatcher is a follow-up, not a change to fold into a security fix.
Summary by CodeRabbit
Bug Fixes
Tag-filtered live and stored-event subscriptions now handle events with missing or malformed tag values without blocking valid matches.
Geohash prefix filters match events when a later g tag contains a matching value, even if an earlier g tag has no value.
Performance
Tag-filter matching reuses compiled filters and event tag data, reducing repeated work during delivery.
No actionable comments were generated in the recent review.
Walkthrough
Generic tag criteria are compiled for matching, and event tag values are indexed for reuse across filters and WebSocket clients. Live and stored subscription paths use the matcher. Tests cover geohash prefixes, malformed or valueless tags, and index reuse.
Changes: Tag-filter matching
Layer / File(s)
Summary
Compile and match generic tag criteria src/utils/event.ts, src/utils/filter.ts, test/unit/utils/event.spec.ts
Generic tag criteria are compiled by tag name. EventTagIndex indexes valid tag values, and lowerBound supports geohash-prefix matching. Unit tests cover matching rules and lookup counts.
Reuse matchers and tag indexes in subscription paths src/handlers/subscribe-message-handler.ts, src/adapters/web-socket-*.ts, test/unit/handlers/subscribe-message-handler.spec.ts, test/unit/adapters/web-socket-*.spec.ts, test/integration/features/nip-01/*, .changeset/index-tag-filter-matching.md
Subscription handling and WebSocket delivery use compiled matchers. A broadcast shares one event tag index across connected adapters. Unit and integration tests cover index reuse and matching events with valueless tags.
This change replaces per-event comparison of every tag against every filter value with compiled, indexed matching. It also stops valueless tags from crashing geohash prefix matching. No concrete defect was found, and the reported tests cover the new behavior. Merge readiness risk is minimal.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title names the primary change: tag filter matching now uses an index instead of comparing every event tag with every filter value. The changeset matches this. It adds EventTagIndex, compiles tag …
Linked Issues check
Issue #1256 requires (1) exact-match criteria keyed by tag name with value sets, (2) separate prefix handling with bounded comparison counts, (3) predicate calls that grow with |tags| + |criteria|, an…
Out of Scope Changes check
All changed areas support the issue objective or its tests. src/utils/event.ts holds the matching rewrite. src/utils/filter.ts adds isGenericTagName, which the index uses. src/adapters/web-socket-adap…
Full details: Title check
Explanation
The title names the primary change: tag filter matching now uses an index instead of comparing every event tag with every filter value. The changeset matches this. It adds EventTagIndex, compiles tag criteria once, and uses binary search for #g prefixes. The title uses the conventional fix(relay) prefix. It also says fix, and the PR reports a crash fix for valueless tags, so the title covers the main change and the stated bug fix.
Full details: Linked Issues check
Explanation
Issue #1256 requires (1) exact-match criteria keyed by tag name with value sets, (2) separate prefix handling with bounded comparison counts, (3) predicate calls that grow with |tags| + |criteria|, and (4) bounded-time rejection with 10k criteria. The reviewed head meets these in src/utils/event.ts. EventTagIndex builds a Map of single-letter tag names to value sets once per event. intersects() iterates only the smaller of the criteria set and the tag value set. The #g prefix path sorts values once and uses lowerBound (binary search) per prefix. Tags with non-array shape, non-string name, non-string value, or multi-letter name are skipped, so the valueless-tag throw on main is removed. compileTagCriteria compiles criteria once per filter, and createSubscriptionMatcher compiles once per subscription. web-socket-adapter.ts and web-socket-server-adapter.ts share one EventTagIndex per broadcast. The aggregate matching budget in the issue is explicitly out of scope per the issue text, so its absence is not a gap. Acceptance tests (probe-count growth, 10k criteria, valueless-g cucumber scenarios) are reported in the PR and in the changed test files; I did not open the spec files, so test behavior rests on the reported test evidence and the code read. Peering-sync-worker per-event compilation is not part of the issue requirements.
Full details: Out of Scope Changes check
Explanation
All changed areas support the issue objective or its tests. src/utils/event.ts holds the matching rewrite. src/utils/filter.ts adds isGenericTagName, which the index uses. src/adapters/web-socket-adapter.ts and web-socket-server-adapter.ts pass a shared EventTagIndex, which implements the once-per-broadcast indexing. src/handlers/subscribe-message-handler.ts switches to createSubscriptionMatcher, which is the same matching path. The changeset documents the change. The feature file, its step file, and unit specs cover the valueless-tag crash and the probe-count behavior. The PR does not add an aggregate connection budget, consistent with the issue's out-of-scope note. No unrelated behavior change was identified in the reviewed summaries. Not inspected: the spec file contents and the subscribe handler diff directly.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
A rabbit checks the tags in flight, It sorts the geohashes just right. One index serves the broadcast queue, And compiled filters speed things through. Valueless tags no longer stall, The rabbit hops and matches all.
Recent review info
Automatic approval policy
Commit: 4925f702ec68.
Setting
Effective value
Source
Automatic approvals
Enabled
Global configuration
Merge risk
Minimal
Global configuration
Security risk
Not set
Global configuration
Not set means no limit was configured after inheritance. Use @coderabbitai configuration to inspect the resolved settings and their sources.
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 7e6ade59-8db1-4486-9d79-f0f8065fca31
Commits
Reviewing files that changed from the base of the PR and between ccf6690 and 4925f70.
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1256.
Cherry-picked from @saket0187's fork (
saket0187/nostream#4, commit5f460c6b) with-x, so the authorship and message are his.Two defects, one diff.
The crash.
src/utils/event.ts:52didtag[1].startsWith(...)for a#gprefix criterion. A tag with no value (["g"], which any client can publish) has notag[1], so the comparison throws — inside the broadcast loop and inside the stored read, which means one malformed tag cut a live broadcast short and stopped a REQ beforeEOSE. Every non-string or absent tag value is now skipped at index time instead of dereferenced.The cost. Generic tag matching was
event.tags.some(tag => criteria.some(criterion => isMatching(...)(tag)))per filter — |tags| × |criteria| predicate calls, with both sides attacker-sized: the event comes off the wire and the criteria come from a subscription the poster opened. Several subscriptions per connection multiply it, on the worker's event loop.What changes. Tag criteria compile once per subscription (and once per REQ on the stored read); the event's single-letter tags are indexed once per broadcast and shared by every filter and every client. Exact criteria become a set intersection that probes the smaller side;
#gprefixes binary-search a sorted value list. A tag name is never scanned against every criterion again.Evidence
mainatccf6690;pnpm run test:unit— 3664 passing, including 19 new cases intest/unit/utils/event.spec.tsand the adapters/handler specs.isEventMatchingFilter({ '#g': ['u4*'] })(event with tags [['g'], ['t', 'valueless-g']])throws onmain—Cannot read properties of undefined (reading 'startsWith')— and returnsfalsehere, while{ '#t': ['valueless-g'] }still matchestrueon both.gtag has no value. Both exercise the throw onmain.*is a prefix only for#g, so exact-match criteria elsewhere still treat*literally.Scope decision. The issue's third fix-shape bullet — an aggregate matching budget per connection — is dropped, and the issue records it (signed 2026-11-29):
maxSubscriptions,maxFiltersandmaxFilterValuesalready bound what one subscription can carry, and a connection-wide budget has no default anyone specified. The bounded-time acceptance line stays, and this diff meets it without a budget.Known, non-blocking.
src/app/peering-sync-worker.tsstill callsisEventMatchingFilter(filter)(event)per event, so it recompiles criteria per event rather than per filter. It is correct and still cheaper than before; moving it tocreateSubscriptionMatcheris a follow-up, not a change to fold into a security fix.Summary by CodeRabbit
gtag contains a matching value, even if an earliergtag has no value.