Skip to content

Advanced Query Processing Architecture#5

Closed
ShashankFC wants to merge 1 commit into
query-splitting-baselinefrom
query-splitting-enhancements
Closed

Advanced Query Processing Architecture#5
ShashankFC wants to merge 1 commit into
query-splitting-baselinefrom
query-splitting-enhancements

Conversation

@ShashankFC

@ShashankFC ShashankFC commented Dec 31, 2025

Copy link
Copy Markdown
Collaborator

Test 4nn

Summary by CodeRabbit

  • Bug Fixes

    • Fixed template variable interpolation in Loki queries. Variables such as $__auto and time intervals are now properly substituted before query execution on a per-query basis, ensuring accurate query processing and results.
  • Tests

    • Added and updated test coverage to verify template variable interpolation occurs correctly before query execution.

✏️ Tip: You can customize this high-level summary in your review settings.

nn---n*Replicated from [ai-code-review-evaluation/grafana-coderabbit#4](https://github.com/ai-code-review-evaluation/grafana-coderabbit/pull/4)*

…7534)

* Loki query splitting: interpolate queries before execution

* Update tests

* Prettier

* shardQuerySplitting: remove unnecessary call
@ShashankFC

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jan 12, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jan 12, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The changes replace batch-level query template variable substitution with per-query interpolation in Loki's query splitting logic. The datasource now applies template variables individually to each query before execution, changing from a single batch operation to a mapped per-query approach.

Changes

Cohort / File(s) Summary
Per-Query Template Variable Interpolation Implementation
public/app/plugins/datasource/loki/querySplitting.ts, public/app/plugins/datasource/loki/shardQuerySplitting.ts
Implementation files updated to replace interpolateVariablesInQueries(queries[]) calls with per-query applyTemplateVariables(query) mapping. Template variables now applied individually to each query using request.scopedVars and request.filters before query processing.
Per-Query Template Variable Interpolation Tests
public/app/plugins/datasource/loki/querySplitting.test.ts, public/app/plugins/datasource/loki/shardQuerySplitting.test.ts
New test added in querySplitting.test.ts verifying placeholder substitution (e.g., $__auto, $step). Existing tests in shardQuerySplitting.test.ts updated to expect per-query applyTemplateVariables calls instead of batch interpolateVariablesInQueries invocations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Templates now split per query, not in bulk,
Each variable finds its place with a gentle muck,
Filters and scopes dance round and round,
Per-query magic—interpolation profound! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Advanced Query Processing Architecture' is vague and overly broad, failing to convey the specific main change of shifting query interpolation to occur before execution in the Loki query splitting process. Use a more specific title such as 'Apply template variable interpolation before query execution in Loki' or 'Refactor Loki query splitting to interpolate at query start'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

@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: 0

🧹 Nitpick comments (3)
public/app/plugins/datasource/loki/shardQuerySplitting.ts (1)

49-52: Filter order inconsistency with querySplitting.ts.

The filter order here is .filter(expr) then .filter(!hide), but in querySplitting.ts (lines 296-298) the order is reversed: .filter(!hide) then .filter(expr). While both achieve the same end result, maintaining consistent filter ordering across the codebase improves readability and reduces cognitive overhead.

Suggested fix to align filter order with querySplitting.ts
 export function runShardSplitQuery(datasource: LokiDatasource, request: DataQueryRequest<LokiQuery>) {
   const queries = request.targets
-    .filter((query) => query.expr)
     .filter((query) => !query.hide)
+    .filter((query) => query.expr)
     .map((query) => datasource.applyTemplateVariables(query, request.scopedVars, request.filters));

   return splitQueriesByStreamShard(datasource, request, queries);
 }
public/app/plugins/datasource/loki/shardQuerySplitting.test.ts (2)

56-59: Mock mutates input instead of returning a new object.

The mock implementation mutates the input query object directly. While this works for the test, production applyTemplateVariables typically returns a new object to avoid side effects. Consider returning a new object to better simulate production behavior.

Suggested improvement
     datasource.applyTemplateVariables = jest.fn().mockImplementation((query: LokiQuery) => {
-      query.expr = query.expr.replace('$SELECTOR', '{a="b"}');
-      return query;
+      return {
+        ...query,
+        expr: query.expr.replace('$SELECTOR', '{a="b"}'),
+      };
     });

173-176: Same mutation pattern as the earlier mock.

This mock also mutates the input object directly. Consider using the same immutable pattern suggested earlier for consistency.

Suggested improvement
     datasource.applyTemplateVariables = jest.fn().mockImplementation((query: LokiQuery) => {
-      query.expr = query.expr.replace('$SELECTOR', '{service_name="test", filter="true"}');
-      return query;
+      return {
+        ...query,
+        expr: query.expr.replace('$SELECTOR', '{service_name="test", filter="true"}'),
+      };
     });
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dcb853d and 3ba2457.

📒 Files selected for processing (4)
  • public/app/plugins/datasource/loki/querySplitting.test.ts
  • public/app/plugins/datasource/loki/querySplitting.ts
  • public/app/plugins/datasource/loki/shardQuerySplitting.test.ts
  • public/app/plugins/datasource/loki/shardQuerySplitting.ts
🧰 Additional context used
🧬 Code graph analysis (3)
public/app/plugins/datasource/loki/querySplitting.ts (1)
public/app/plugins/datasource/loki/datasource.ts (1)
  • query (299-344)
public/app/plugins/datasource/loki/querySplitting.test.ts (1)
public/app/plugins/datasource/loki/querySplitting.ts (1)
  • runSplitQuery (291-357)
public/app/plugins/datasource/loki/shardQuerySplitting.test.ts (2)
public/app/plugins/datasource/loki/types.ts (1)
  • LokiQuery (24-33)
public/app/plugins/datasource/loki/shardQuerySplitting.ts (1)
  • runShardSplitQuery (48-55)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Postgres (7/8)
🔇 Additional comments (4)
public/app/plugins/datasource/loki/querySplitting.test.ts (1)

75-88: LGTM!

The test correctly verifies that template variable interpolation occurs before query execution. It properly mocks the template service's replace function and validates that both expr and step fields contain interpolated values in the first runQuery call.

public/app/plugins/datasource/loki/querySplitting.ts (1)

296-299: LGTM!

The per-query interpolation approach correctly applies template variables to each individual query after filtering out hidden and empty queries. This aligns with the PR objective and ensures variables are resolved before query processing.

public/app/plugins/datasource/loki/shardQuerySplitting.test.ts (2)

84-101: LGTM!

The test correctly verifies that template variable interpolation occurs before query execution in the shard splitting path. It validates that both the expression (with shard selector added) and step values are properly interpolated.


110-112: The expected call count of 5 is correct.

applyTemplateVariables is called once initially in runShardSplitQuery (line 52), then called 4 additional times inside runSplitQuery (line 299 in querySplitting.ts)—once for each of the 4 groups created during shard cycling (1 empty group + 3 shard cycles from the 5 shards).

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed in 2 weeks if no further activity occurs. Please feel free to give a status update or ping for review. Thank you for your contributions!

@github-actions github-actions Bot added the stale label Feb 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically closed because it has not had any further activity in the last 2 weeks. Thank you for your contributions!

@github-actions github-actions Bot closed this Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants