Skip to content

fix(relay): index tag filters instead of comparing every tag with every value - #1287

Merged
cameri merged 1 commit into
mainfrom
fix/1256-tag-filter-index
Nov 29, 2026
Merged

cameri merged 1 commit into
mainfrom
fix/1256-tag-filter-index

Conversation

@chappie-daemon

@chappie-daemon chappie-daemon commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1256.

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.

@changeset-bot

changeset-bot Bot commented Nov 29, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 4925f70

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
nostream Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Explain Change →

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.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Low

Possibly related issues

Merge Risk: Minimal · up to 4925f

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: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 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 Passed 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 Passed 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.

Share

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.

Files selected for processing: 12

  • .changeset/index-tag-filter-matching.md
  • src/adapters/web-socket-adapter.ts
  • src/adapters/web-socket-server-adapter.ts
  • src/handlers/subscribe-message-handler.ts
  • src/utils/event.ts
  • src/utils/filter.ts
  • test/integration/features/nip-01/nip-01.feature
  • test/integration/features/nip-01/nip-01.feature.ts
  • test/unit/adapters/web-socket-adapter.spec.ts
  • test/unit/adapters/web-socket-server-adapter.spec.ts
  • test/unit/handlers/subscribe-message-handler.spec.ts
  • test/unit/utils/event.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@greptile-apps

greptile-apps Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 · The PR appears safe to merge; no actionable issues were found.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable issues were found.

Summary

The PR compiles tag criteria once per subscription and shares a lazily built EventTagIndex across clients receiving one broadcast.

  • Tag filters reuse indexed values instead of rescanning every tag.
  • Events with empty tags no longer stop matching.

No actionable issues were found. Tests were inspected, not run during this review.

Acknowledged scope decisions:

  • chappie-daemon explicitly dropped a connection-wide matching budget because existing limits bound subscriptions and no default budget was specified.
  • chappie-daemon explicitly deferred reusing compiled matchers in src/app/peering-sync-worker.ts; its current calls remain correct.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  REQ[Accepted REQ filters] --> Compile[Compile tag criteria]
  Compile --> Live[Save live subscription matcher]
  Compile --> Stored[Build stored-read matcher]
  Broadcast[Broadcast event] --> Index[Create one lazy EventTagIndex]
  Index --> Clients[Share index across client matchers]
  Live --> Clients
  Clients --> Send[Send matching EVENT]
  Rows[Stored events] --> Fresh[Create fresh index per event]
  Fresh --> Stored
  Stored --> Results[Send matching EVENTs then EOSE]
Loading

Reviews (1) · Last reviewed commit: "fix(relay): index tag filters instead of..." · Reviewed by Greptile

@coveralls

Copy link
Copy Markdown
Collaborator

Coverage Report for CI Build 46293577724

Coverage increased (+0.07%) to 80.848%

Details

  • Coverage increased (+0.07%) from the base build.
  • Patch coverage: 80 of 80 lines across 5 files are fully covered (100%).
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 15440
Covered Lines: 12983
Line Coverage: 84.09%
Relevant Branches: 8547
Covered Branches: 6410
Branch Coverage: 75.0%
Branches in Coverage %: Yes
Coverage Strength: 714.92 hits per line

💛 - Coveralls

@cameri
cameri merged commit e0deccd into main Nov 29, 2026
21 checks passed
@cameri
cameri deleted the fix/1256-tag-filter-index branch November 29, 2026 18:25
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.

filters: index generic tag criteria instead of scanning every criterion per tag

4 participants