Skip to content

fix: include target relays and request lifetime in the request dedup key - #705

Open
nogringo wants to merge 1 commit into
masterfrom
fix/concurrency-check-dedup-key
Open

fix: include target relays and request lifetime in the request dedup key#705
nogringo wants to merge 1 commit into
masterfrom
fix/concurrency-check-dedup-key

Conversation

@nogringo

@nogringo nogringo commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Fixed concurrent queries with identical filters so results remain correctly separated by relay.
    • Improved subscription and query behavior when accessing the same data concurrently, preventing stalled requests and ensuring live events continue to arrive.
    • Refined request matching to account for relay selection and other request options, reducing incorrect cache reuse.
  • Tests

    • Added coverage for concurrent relay queries, subscriptions, live updates, and timeout scenarios.

@nogringo
nogringo requested review from 1-leo and frnandu August 9, 2026 21:56
@nogringo nogringo self-assigned this Aug 9, 2026
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The concurrency key now represents the complete request, including relay configuration and lifecycle behavior. New scenarios test relay isolation and subscription-cache interactions. One local-first deletion test is skipped because cache visibility remains incorrect when cacheWrite is disabled.

Changes

Request concurrency and cache behavior

Layer / File(s) Summary
Complete request identity hashing
packages/ndk/lib/domain_layer/usecases/requests/concurrency_check.dart
Concurrency checks hash filters, closeOnEOSE, explicit relays, and relay-set identity and URLs in sorted order.
Relay-specific concurrent query validation
packages/ndk/test/scenarios/concurrent_same_filter_different_relays_test.dart
The scenario verifies that identical filters queried against different explicit relays return only the corresponding relay’s event.
Subscription cache deduplication validation
packages/ndk/test/scenarios/subscription_cache_read_dedup_test.dart, packages/ndk/test/usecases/local_first/local_first_test.dart
Tests cover live events after an overlapping query and query completion alongside an open subscription. A local-first deletion test is skipped because cache visibility is bypassed when cacheWrite is disabled.

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

Suggested reviewers: 1-leo, frnandu

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change to include target relays and request lifetime in the request deduplication key.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/concurrency-check-dedup-key

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/ndk/lib/domain_layer/usecases/requests/concurrency_check.dart`:
- Around line 45-58: Update the JSON payload used by the concurrency-check
deduplication hash to include stable representations of request.timeoutDuration
and request.desiredCoverage alongside the existing filters and relay fields.
Keep the existing hashing flow and ordering behavior unchanged so queries
differing in either value produce distinct keys.

In
`@packages/ndk/test/scenarios/concurrent_same_filter_different_relays_test.dart`:
- Around line 63-72: Strengthen the assertions in the concurrent query test so
each result contains only its target relay’s event: update the checks for
results[0] and results[1] to compare their complete ID sets against
noteOnRelay1.id and noteOnRelay2.id respectively, excluding the other relay
event.

In `@packages/ndk/test/usecases/local_first/local_first_test.dart`:
- Around line 593-598: The cacheRead=true, cacheWrite=false query path is
returning tombstoned events because visibility filtering is skipped. Update the
cache visibility/filtering logic used by this query path to exclude tombstoned
events, then remove the skip from the tombstone-visibility test so the scenario
remains enabled.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0bca4f76-3686-437a-9a7c-393bfcfaa0d0

📥 Commits

Reviewing files that changed from the base of the PR and between 4e28d2e and 416f098.

📒 Files selected for processing (4)
  • packages/ndk/lib/domain_layer/usecases/requests/concurrency_check.dart
  • packages/ndk/test/scenarios/concurrent_same_filter_different_relays_test.dart
  • packages/ndk/test/scenarios/subscription_cache_read_dedup_test.dart
  • packages/ndk/test/usecases/local_first/local_first_test.dart

Comment on lines +45 to 58
final jsonString = json.encode({
'filters': request.filters,
'closeOnEOSE': request.closeOnEOSE,
'explicitRelays': _sorted(request.explicitRelays),
'relaySet': request.relaySet == null
? null
: {
'id': request.relaySet!.id,
'urls': _sorted(request.relaySet!.urls),
},
});
final bytes = utf8.encode(jsonString);
final hash = sha256.convert(bytes);
return hash.toString();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Include timeout and coverage in the deduplication key.

timeoutDuration and desiredCoverage are omitted from the key. Two queries with the same filters and relays but different values can share one request. The source request can then close before the longer query timeout, or collect fewer relays than the other query requires.

Add a stable representation of request.timeoutDuration and request.desiredCoverage to the encoded payload.

Proposed fix
       'filters': request.filters,
       'closeOnEOSE': request.closeOnEOSE,
+      'timeoutDurationMicros': request.timeoutDuration?.inMicroseconds,
+      'desiredCoverage': request.desiredCoverage,
       'explicitRelays': _sorted(request.explicitRelays),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
final jsonString = json.encode({
'filters': request.filters,
'closeOnEOSE': request.closeOnEOSE,
'explicitRelays': _sorted(request.explicitRelays),
'relaySet': request.relaySet == null
? null
: {
'id': request.relaySet!.id,
'urls': _sorted(request.relaySet!.urls),
},
});
final bytes = utf8.encode(jsonString);
final hash = sha256.convert(bytes);
return hash.toString();
final jsonString = json.encode({
'filters': request.filters,
'closeOnEOSE': request.closeOnEOSE,
'timeoutDurationMicros': request.timeoutDuration?.inMicroseconds,
'desiredCoverage': request.desiredCoverage,
'explicitRelays': _sorted(request.explicitRelays),
'relaySet': request.relaySet == null
? null
: {
'id': request.relaySet!.id,
'urls': _sorted(request.relaySet!.urls),
},
});
final bytes = utf8.encode(jsonString);
final hash = sha256.convert(bytes);
return hash.toString();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ndk/lib/domain_layer/usecases/requests/concurrency_check.dart`
around lines 45 - 58, Update the JSON payload used by the concurrency-check
deduplication hash to include stable representations of request.timeoutDuration
and request.desiredCoverage alongside the existing filters and relay fields.
Keep the existing hashing flow and ordering behavior unchanged so queries
differing in either value produce distinct keys.

Comment on lines +63 to +72
expect(
results[0].map((e) => e.id),
contains(noteOnRelay1.id),
reason: 'query on relay 1 should return the event stored on relay 1',
);
expect(
results[1].map((e) => e.id),
contains(noteOnRelay2.id),
reason: 'query on relay 2 should return the event stored on relay 2',
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that each result excludes the other relay event.

The current assertions only require the target event to be present. They also pass if both queries return events from both relays. Assert the complete ID set for each result.

Proposed fix
       expect(
-        results[0].map((e) => e.id),
-        contains(noteOnRelay1.id),
+        results[0].map((e) => e.id),
+        unorderedEquals([noteOnRelay1.id]),
         reason: 'query on relay 1 should return the event stored on relay 1',
       );
       expect(
-        results[1].map((e) => e.id),
-        contains(noteOnRelay2.id),
+        results[1].map((e) => e.id),
+        unorderedEquals([noteOnRelay2.id]),
         reason: 'query on relay 2 should return the event stored on relay 2',
       );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expect(
results[0].map((e) => e.id),
contains(noteOnRelay1.id),
reason: 'query on relay 1 should return the event stored on relay 1',
);
expect(
results[1].map((e) => e.id),
contains(noteOnRelay2.id),
reason: 'query on relay 2 should return the event stored on relay 2',
);
expect(
results[0].map((e) => e.id),
unorderedEquals([noteOnRelay1.id]),
reason: 'query on relay 1 should return the event stored on relay 1',
);
expect(
results[1].map((e) => e.id),
unorderedEquals([noteOnRelay2.id]),
reason: 'query on relay 2 should return the event stored on relay 2',
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/ndk/test/scenarios/concurrent_same_filter_different_relays_test.dart`
around lines 63 - 72, Strengthen the assertions in the concurrent query test so
each result contains only its target relay’s event: update the checks for
results[0] and results[1] to compare their complete ID sets against
noteOnRelay1.id and noteOnRelay2.id respectively, excluding the other relay
event.

Comment on lines +593 to +598
skip:
'Was green only because the last query got merged into the previous '
'one by ConcurrencyCheck, whose dedup key ignored the target relays. '
'With the key fixed the query runs for real and exposes that '
'visibility filtering is skipped when cacheWrite is false, so the '
'tombstoned event comes back. See the cacheWrite visibility issue.',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not skip the tombstone-visibility scenario.

The skip reason confirms that a cacheRead: true, cacheWrite: false query returns a tombstoned event. This violates the public query contract tested above. Fix visibility filtering for this cache path, remove skip, and keep the scenario enabled.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ndk/test/usecases/local_first/local_first_test.dart` around lines
593 - 598, The cacheRead=true, cacheWrite=false query path is returning
tombstoned events because visibility filtering is skipped. Update the cache
visibility/filtering logic used by this query path to exclude tombstoned events,
then remove the skip from the tombstone-visibility test so the scenario remains
enabled.

@1-leo 1-leo added this to the 0.9.0 milestone Aug 12, 2026
@frnandu

frnandu commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator

address the issues coderabbit raised, since my clanker also point out similar stuff

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