Skip to content

fix(grpc-e2e): reflection cache & ordering across environment switches - #8832

Merged
vijayh-bruno merged 12 commits into
usebruno:mainfrom
sanish-bruno:fix/grpc-tests
Aug 17, 2026
Merged

vijayh-bruno merged 12 commits into
usebruno:mainfrom
sanish-bruno:fix/grpc-tests

Conversation

@sanish-bruno

@sanish-bruno sanish-bruno commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

BRU-4088

Description

Fixes gRPC reflection when the active environment changes:

  • Key the reflection cache by the resolved URL, so {{host}} doesn't share a slot across envs.
  • Guard against out-of-order reflection responses with a request ID.
  • Debounce the reflection fetch (3s) so rapid URL edits don't spam the network — URL dispatch stays immediate.
  • Stabilize the flaky method-search e2e specs.
  • Adds unit coverage for `useReflectionManagement` (URL dispatch + per-env cache keying).
  • Added gRPC server testbench

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.
  • I've run the claude code review skill locally.

Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • Bug Fixes

    • Improved gRPC reflection when switching environments, preventing outdated results from replacing current data.
    • Updated gRPC method loading to use the appropriate proto-file or reflection results.
    • Improved reflection caching for environment-based URLs and refreshed methods when connection settings change.
    • Added debounced reflection requests to reduce unnecessary loading while editing request URLs.
  • Tests

    • Strengthened checks for gRPC method search and message creation to verify expected UI updates.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

gRPC reflection now resolves environment variables in URLs, uses environment-aware cache entries, debounces URL changes, reloads on environment changes, and ignores stale responses.

Changes

gRPC reflection flow

Layer / File(s) Summary
Interpolated reflection cache keys
packages/bruno-app/src/hooks/useReflectionManagement/index.js, packages/bruno-app/src/hooks/useReflectionManagement/index.spec.js
Reflection loading, lookup, and clearing use resolved URLs. Tests cover interpolation, environment-specific cache entries, cache hits, manual refreshes, and unresolved variables.
Environment-aware query loading
packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js
The query pane passes collection context, debounces reflection requests, reloads for active-environment changes, deduplicates requests, and ignores stale responses.
gRPC test interaction coverage
tests/grpc/method-search/grpc-method-search.spec.ts, tests/utils/page/actions.ts, tests/utils/page/locators.ts
The test setup uses the shared environment selector. The gRPC message helper verifies that one message is added. A message locator supports this assertion.

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

Possibly related PRs

Suggested reviewers: bijin-bruno

Sequence Diagram(s)

sequenceDiagram
  participant GrpcQueryUrl
  participant ReflectionManagement
  participant ReflectionCache
  GrpcQueryUrl->>GrpcQueryUrl: Debounce URL change
  GrpcQueryUrl->>ReflectionManagement: Load methods for active environment
  ReflectionManagement->>ReflectionCache: Resolve and check interpolated URL
  ReflectionCache-->>ReflectionManagement: Return cached methods or load result
  ReflectionManagement-->>GrpcQueryUrl: Return reflection methods
  GrpcQueryUrl->>GrpcQueryUrl: Ignore stale response by request ID
Loading

Poem

Environment URLs resolve,
Cache keys track each call.
New requests lead the flow,
Older responses fall.
gRPC methods load in order.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the primary gRPC reflection cache and response-ordering fixes across environment switches.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js`:
- Around line 290-303: Update the environment-change effect and handleReflection
flow to assign each fetch a monotonically increasing request ID, then verify it
is still the latest before applying any state or toast updates after awaiting.
Ensure stale reflection requests cannot overwrite methods or UI state for the
current environment, while preserving the existing proto-file and
current-request behavior.

In `@packages/bruno-app/src/hooks/useReflectionManagement/index.js`:
- Around line 42-60: Update the loadGrpcMethodsFromReflection call in the
reflection-loading function to pass the resolved cacheKey instead of the raw
url, ensuring the request uses the same interpolated endpoint represented by the
cache key. Preserve the existing loading, error, and caching behavior.
🪄 Autofix (Beta)

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 488c8368-029c-4f06-bb5d-fe05c811a6da

📥 Commits

Reviewing files that changed from the base of the PR and between b48b613 and bedbdb6.

📒 Files selected for processing (2)
  • packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js
  • packages/bruno-app/src/hooks/useReflectionManagement/index.js

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-app/src/hooks/useReflectionManagement/index.js (1)

48-62: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Order cache writes by request.

The component-level request ID only suppresses stale UI updates. Overlapping reflection calls with the same cacheKey can still complete out of order, allowing an older response to overwrite newer methods in reflectionCache[cacheKey]. Track a per-key request/version and only cache the latest response.

Based on the PR objective, reflection calls are intentionally concurrent, so cache writes need the same ordering guarantee.

🤖 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/bruno-app/src/hooks/useReflectionManagement/index.js` around lines
48 - 62, Update the reflection-loading flow in the method containing
setReflectionCache so each cacheKey maintains its own request/version counter.
Increment and capture the version when dispatching
loadGrpcMethodsFromReflection, then only write methods to reflectionCache when
the response’s version is still the latest for that key; preserve concurrent
requests and existing error/UI behavior.
🧹 Nitpick comments (2)
tests/grpc/method-search/grpc-method-search.spec.ts (1)

5-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for environment-driven reflection reloads.

This setup selects GrpcEnv once but never switches environments after reflection methods have loaded. Add a regression test that changes the active environment and verifies the refreshed method list or selected method.

As per coding guidelines, meaningful functionality changes should include behavior-driven coverage for realistic state transitions.

🤖 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 `@tests/grpc/method-search/grpc-method-search.spec.ts` around lines 5 - 10,
Extend the grpc method-search test setup around selectEnvironment and add a
regression test that switches from GrpcEnv to another environment after
reflection methods load, then verifies the method list or selected method
refreshes to match the new environment. Preserve the existing initial
environment setup and use realistic UI state transitions.

Source: Coding guidelines

tests/utils/page/actions.ts (1)

1676-1679: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep assertions in specs, not page actions.

addGrpcMessage now owns the expect(...).toHaveCount() assertion. Move that assertion to the calling spec and let this helper synchronize with a locator wait if needed; this keeps page modules reusable and lets each test define its own pass/fail criteria.

As per path instructions, expect(...) belongs in specs; shared actions should synchronize with waitFor or locator waits.

🤖 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 `@tests/utils/page/actions.ts` around lines 1676 - 1679, Remove the toHaveCount
assertion from addGrpcMessage in the shared page actions module, leaving the
helper to perform only the message addition and any necessary locator-based
synchronization. Add the count assertion in each calling spec, using the
captured container count to define the test-specific expectation.

Source: Path instructions

🤖 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/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js`:
- Around line 123-129: Extend the shared generation token used by
handleReflection to also cover proto-file loading and mode changes. Increment it
when selecting or switching to a proto file, and when starting either load;
after each asynchronous load, ignore results whose captured generation no longer
matches the current token, preventing stale reflection data from changing
protoFilePath, mode, methods, or toasts.

---

Outside diff comments:
In `@packages/bruno-app/src/hooks/useReflectionManagement/index.js`:
- Around line 48-62: Update the reflection-loading flow in the method containing
setReflectionCache so each cacheKey maintains its own request/version counter.
Increment and capture the version when dispatching
loadGrpcMethodsFromReflection, then only write methods to reflectionCache when
the response’s version is still the latest for that key; preserve concurrent
requests and existing error/UI behavior.

---

Nitpick comments:
In `@tests/grpc/method-search/grpc-method-search.spec.ts`:
- Around line 5-10: Extend the grpc method-search test setup around
selectEnvironment and add a regression test that switches from GrpcEnv to
another environment after reflection methods load, then verifies the method list
or selected method refreshes to match the new environment. Preserve the existing
initial environment setup and use realistic UI state transitions.

In `@tests/utils/page/actions.ts`:
- Around line 1676-1679: Remove the toHaveCount assertion from addGrpcMessage in
the shared page actions module, leaving the helper to perform only the message
addition and any necessary locator-based synchronization. Add the count
assertion in each calling spec, using the captured container count to define the
test-specific expectation.
🪄 Autofix (Beta)

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: bfe512a1-9a3e-4206-9543-9dc519f6ee60

📥 Commits

Reviewing files that changed from the base of the PR and between bedbdb6 and f2d04d5.

📒 Files selected for processing (4)
  • packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js
  • packages/bruno-app/src/hooks/useReflectionManagement/index.js
  • tests/grpc/method-search/grpc-method-search.spec.ts
  • tests/utils/page/actions.ts

@sanish-bruno sanish-bruno changed the title fix(grpc): improve reflection fetch logic to handle environment changes test(grpc): fix flaky and failing tests Jul 30, 2026

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

🧹 Nitpick comments (1)
tests/utils/page/locators.ts (1)

345-345: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a stable test selector for individual messages.

Line 345 relies on the CSS class .message-container. A UI refactor can change this class without changing message behavior, which would break addGrpcMessage because it uses this locator for synchronization.

Prefer a dedicated data-testid or semantic selector for each message. Verify that .message-container is an intentional stable test contract before merging.

As per path instructions: E2E selectors must be semantic and stable, and page-module selectors must avoid brittle inline selectors.

🤖 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 `@tests/utils/page/locators.ts` at line 345, Replace the brittle
.message-container selector in the messages locator with a dedicated stable
data-testid or semantic selector for individual messages, and update the
corresponding message markup if necessary. Preserve addGrpcMessage
synchronization by ensuring the locator still targets each message within
grpc-messages-container.

Source: Path instructions

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

Nitpick comments:
In `@tests/utils/page/locators.ts`:
- Line 345: Replace the brittle .message-container selector in the messages
locator with a dedicated stable data-testid or semantic selector for individual
messages, and update the corresponding message markup if necessary. Preserve
addGrpcMessage synchronization by ensuring the locator still targets each
message within grpc-messages-container.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2ee0590f-3082-40c9-b532-6dc4539fa79d

📥 Commits

Reviewing files that changed from the base of the PR and between f2d04d5 and 3ded8dc.

📒 Files selected for processing (4)
  • packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js
  • packages/bruno-app/src/hooks/useReflectionManagement/index.js
  • tests/utils/page/actions.ts
  • tests/utils/page/locators.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/utils/page/actions.ts
  • packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js
  • packages/bruno-app/src/hooks/useReflectionManagement/index.js

@pull-request-size pull-request-size Bot added size/L and removed size/M labels Jul 31, 2026

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js (2)

110-137: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Pending debounced reflection fires with a stale URL after the field is cleared.

debouncedReflection is only invoked when !protoFilePath && value is true. If the user types a URL and clears it again within the 3-second debounce window, this branch is skipped for the empty value, but the previously scheduled debouncedReflection call is never cancelled. It still fires after 3 seconds using the old, now-stale URL, triggering an unwanted reflection request and toast for a URL the user no longer has in the field.

🐛 Proposed fix: cancel the pending debounce when the condition no longer holds
     if (!protoFilePath && value) {
       setIsReflectionMode(true);
       debouncedReflection(finalUrl);
+    } else {
+      debouncedReflection.cancel();
     }
🤖 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/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js` around
lines 110 - 137, Update onUrlChange so any pending debouncedReflection is
cancelled when !protoFilePath && value is false, including when the field is
cleared; preserve the existing scheduling behavior for non-empty values and
ensure no stale reflection request or toast runs afterward.

139-220: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Proto-file load doesn't invalidate a pending reflection response.

handleReflection guards against stale results with latestReflectionRequestIdRef, but handleProtoFileLoad never touches that ref. If a reflection request is in flight and the user then loads a proto file, the proto file load finishes first and sets protoFilePath. When the older handleReflection promise resolves afterward, its requestId still matches latestReflectionRequestIdRef.current (nothing incremented it), so it passes the staleness check at Line 144 and calls setProtoFilePath(''), setIsReflectionMode(true), and setGrpcMethods(methods) — overwriting the user's proto-file selection with stale reflection data.

Use one shared generation counter for both load paths so either one can invalidate the other.

🐛 Proposed fix: share one generation counter between reflection and proto-file loads
-  const handleReflection = async (url, isManualRefresh = false) => {
-    // Concurrent reflection calls (e.g. from rapid env switches) can resolve out of order;
-    // drop any result that isn't from the most recent call so older methods can't clobber newer.
-    const requestId = ++latestReflectionRequestIdRef.current;
+  const handleReflection = async (url, isManualRefresh = false) => {
+    // Concurrent reflection/proto-file loads can resolve out of order; drop any result
+    // that isn't from the most recent load (of either kind) so older methods can't
+    // clobber a newer selection.
+    const requestId = ++latestLoadRequestIdRef.current;
     const { methods, error, fromCache } = await reflectionManagement.loadMethodsFromReflection(url, isManualRefresh);
-    if (requestId !== latestReflectionRequestIdRef.current) return;
+    if (requestId !== latestLoadRequestIdRef.current) return;
     ...
   };

   const handleProtoFileLoad = async (filePath, isManualRefresh = false) => {
+    const requestId = ++latestLoadRequestIdRef.current;
     const { methods, error, fromCache } = await protoFileManagement.loadMethodsFromProtoFile(filePath, isManualRefresh);
+    if (requestId !== latestLoadRequestIdRef.current) return;

     if (error) {
🤖 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/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js` around
lines 139 - 220, Update handleProtoFileLoad to increment the shared
latestReflectionRequestIdRef.current generation before starting its load, and
capture that generation for the proto-file request. In handleReflection, retain
the existing generation check so a reflection response is discarded after a
proto-file load begins; ensure the proto-file path also ignores results if a
newer load starts, preventing either load from overwriting the other.
🤖 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.

Outside diff comments:
In `@packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js`:
- Around line 110-137: Update onUrlChange so any pending debouncedReflection is
cancelled when !protoFilePath && value is false, including when the field is
cleared; preserve the existing scheduling behavior for non-empty values and
ensure no stale reflection request or toast runs afterward.
- Around line 139-220: Update handleProtoFileLoad to increment the shared
latestReflectionRequestIdRef.current generation before starting its load, and
capture that generation for the proto-file request. In handleReflection, retain
the existing generation check so a reflection response is discarded after a
proto-file load begins; ensure the proto-file path also ignores results if a
newer load starts, preventing either load from overwriting the other.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 082a29a8-510c-436f-8a0a-132e9a2ad2db

📥 Commits

Reviewing files that changed from the base of the PR and between 3ded8dc and db7a97a.

📒 Files selected for processing (2)
  • packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js
  • packages/bruno-app/src/hooks/useReflectionManagement/index.spec.js

@sanish-bruno sanish-bruno changed the title test(grpc): fix flaky and failing tests fix(grpc): reflection cache & ordering across environment switches Jul 31, 2026
@sanish-bruno sanish-bruno changed the title fix(grpc): reflection cache & ordering across environment switches fix(grpc-e2e): reflection cache & ordering across environment switches Jul 31, 2026
@sanish-bruno
sanish-bruno force-pushed the fix/grpc-tests branch 2 times, most recently from b75c2f6 to 338c4d3 Compare August 4, 2026 14:11
@sanish-bruno sanish-bruno mentioned this pull request Aug 5, 2026
3 of 7 tasks
@sanish-bruno
sanish-bruno force-pushed the fix/grpc-tests branch 3 times, most recently from b800ab8 to d9d3777 Compare August 10, 2026 08:49
@vijayh-bruno
vijayh-bruno merged commit 1526e39 into usebruno:main Aug 17, 2026
14 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants