fix: do not sort in descending locally if the other is explicitly specified
Tier 2 medium go · local · real merged PR from SigNoz/signoz #10033
Ground-truth defects
In applyFormulas (pkg/querier/postprocess.go), the new RequestTypeScalar branch calls applySeriesLimit on the result of processScalarFormula, but that result's Value is a *qbtypes.ScalarData while applySeriesLimit type-asserts result.Value.(*qbtypes.TimeSeriesData) and returns the result unchanged when the assertion fails. So for scalar/formula query results the call is effectively dead code: the configured order-by and limit on the formula are silently ignored, and scalar formula results come back unordered with no limit applied.
The new `HasOrderSpecified()` type-switches over the trace, log, metric and formula query types and omits `QueryBuilderTraceOperator`, which carries its own `Order` field and is a first-class member of the same pipeline. `applyDefaultSort` is therefore true for a trace-operator query that did specify an order, and the scalar formatter re-sorts by the first aggregation -- the descending re-sort this PR exists to suppress.
The change under review
diff (truncated — full diff)
@@ -318,13 +318,14 @@ func (q *querier) applyFormulas(ctx context.Context, results map[string]*qbtypes } // Check if we're dealing with time series or scalar data - if req.RequestType == qbtypes.RequestTypeTimeSeries { + switch req.RequestType { + case qbtypes.RequestTypeTimeSeries: result := q.processTimeSeriesFormula(ctx, results, formula, req) if result != nil { result = q.applySeriesLimit(result, formula.Limit, formula.Order) results[name] = result } - } else if req.RequestType == qbtypes.RequestTypeScalar { + case qbtypes.RequestTypeScalar: result := q.processScalarFormula(ctx, results, formula, req) if result != nil { result = q.applySeriesLimit(result, formula.Limit, formula.Order) @@ -581,11 +582,14 @@ func (q *querier) filterDisabledQueries(results map[string]*qbtypes.Result, req } // formatScalarResultsAsTable formats scalar results as a unified table for UI display -func (q *querier) formatScalarResultsAsTable(results map[string]*qbtypes.Result, _ *qbtypes.QueryRangeRequest) map[string]any { +func (q *querier) formatScalarResultsAsTable(results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) map[string]any { if len(results) == 0 { return map[string]any{"table": &qbtypes.ScalarData{}} } + // apply default sorting if no order specified + applyDefaultSort := !req.HasOrderSpecified() + // Convert all results to ScalarData first scalarResults := make(map[string]*qbtypes.ScalarData) for name, result := range results { @@ -600,13 +604,13 @@ func (q *querier) formatScalarResultsAsTable(results map[string]*qbtypes.Result, if len(scalarResults) == 1 { for _, sd := range scalarResults { if hasMultipleQueries(sd) { - return map[string]any{"table": deduplicateRows(sd)} + return map[string]any{"table": deduplicateRows(sd, applyDefaultSort)} } } } // Otherwise merge all results - merged := mergeScalarData(scalarResults) + merged := mergeScalarData(scalarResults, applyDefaultSort) return map[string]any{"table": merged} } @@ -687,7 +691,7 @@ func hasMultipleQueries(sd *qbtypes.ScalarData) bool { } // deduplicateRows removes duplicate rows based on group columns -func deduplicateRows(sd *qbtypes.ScalarData) *qbtypes.ScalarData { +func deduplicateRows(sd *qbtypes.ScalarData, applyDefaultSort bool) *qbtypes.ScalarData { // Find group column indices groupIndices := []int{} for i, col := range sd.Columns { @@ -696,8 +700,9 @@ func deduplicateRows(sd *qbtypes.ScalarData) *qbtypes.ScalarData { } } - // Build unique rows map + // Build unique rows map, preserve order uniqueRows := make(map[string][]any) + var keyOrder []string for _, row := range sd.Data { key := buildRowKey(row, groupIndices) if existing, found := uniqueRows[key]; found { @@ -711,17 +716,20 @@ func deduplicateRows(sd *qbtypes.ScalarData) *qbtypes.ScalarData { rowCopy := make([]any, len(row)) copy(rowCopy, row) uniqueRows[key] = rowCopy + keyOrder = append(keyOrder, key) } } - // Convert back to slice + // Convert back to slice, preserve the original order data := make([][]any, 0, len(uniqueRows)) - for _, row := range uniqueRows { - data = append(data, row) + for _, key := range keyOrder { + data = append(data, uniqueRows[key]) } - // Sort by first aggregation column - sortByFirstAggregation(data, sd.Columns) + // sort by first aggregation (descending) if no order was specified + if applyDefaultSort { + sortByFirstAggregation(data, sd.Columns) + } return &qbtypes.ScalarData{ Columns: sd.Columns, @@ -730,7 +738,7 @@ func deduplicateRows(sd *qbtypes.ScalarData) *qbtypes.ScalarData { } // mergeScalarData merges multiple scalar data results -func mergeScalarData(results map[string]*qbtypes.ScalarData) *qbtypes.ScalarData { +func mergeScalarData(results map[string]*qbtypes.ScalarData, applyDefaultSort bool) *qbtypes.ScalarData { // Collect unique group columns groupCols := []string{} groupColMap := make(map[string]*qbtypes.ColumnDescriptor) @@ -770,10 +778,12 @@ func mergeScalarData(results map[string]*qbtypes.ScalarData) *qbtypes.ScalarData } } - // Merge rows + // Merge rows, preserve order rowMap := make(map[string][]any) + var keyOrder []string - for queryName, sd := range results { + for _, queryName := range queryNames { + sd := results[queryName] // Create index mappings groupMap := make(map[string]int) for i, col := range sd.Columns { @@ -802,6 +812,7 @@ func mergeScalarData(results map[string]*qbtypes.ScalarData) *qbtypes.ScalarData newRow[i] = "n/a" } rowMap[key] = newRow + keyOrder = append(keyOrder, key) } // Set aggregation values for this query @@ -825,14 +836,16 @@ func mergeScalarData(results map[string]*qbtypes.ScalarData) *qbtypes.ScalarData } } - // Convert to slice + // Convert to slice, preserving insertion order data := make([][]any, 0, len(rowMap)) - for _, row := range rowMap { - data = append(data, row) + for _, key := range keyOrder { + data = append(data, rowMap[key]) } - // Sort by first aggregation column - sortByFirstAggregation(data, columns) + // sort by first aggregation (descending) if no order was specified + if applyDefaultSort { + sortByFirstAggregation(data, columns) + } return &qbtypes.ScalarData{ Columns: columns, @@ -888,7 +901,7 @@ func sortByFirstAggregation(data [][]any, columns []*qbtypes.ColumnDescriptor) { // compareValues compares two values for sorting (handles n/a and numeric types) func compareValues(a, b any) int { - // Handle n/a values + // n/a values gets pushed to the end if a == "n/a" && b == "n/a" { return 0 } @@ -276,6 +276,31 @@ func (r *QueryRangeRequest) NumAggregationForQuery(name string) int64 { return int64(numAgg) } +// HasOrderSpecified returns true if any query has an explicit order provided. +func (r *QueryRangeRequest) HasOrderSpecified() bool { + for _, query := range r.CompositeQuery.Queries { + switch spec := query.Spec.(type) { + case QueryBuilderQuery[TraceAggregation]: + if len(spec.Order) > 0 { + return true + } + case QueryBuilderQuery[LogAggregation]: + if len(spec.Order) > 0 { + return true + } + case QueryBuilderQuery[MetricAggregation]: + if len(spec.Order) > 0 { + return true + } + case QueryBuilderFormula: + if len(spec.Order) > 0 { + return true + } + } + } + return false +} + func (r *QueryRangeRequest) FuncsForQuery(name string) []Function { funcs := []Function{} for _, query := range r.CompositeQuery.Queries { @@ -122,7 +122,7 @@ def _create_saml_client(client_id: str, callback_path: str) -> None: "config": { "full.path": "false", "attribute.nameformat": "Basic", - "single": "true", # ! this was changed to true as we need the groups in the single attribute section + "single": "true", # ! this was changed to true as we need the groups in the single attribute section "friendly.name": "groups", "attribute.name": "groups", }, @@ -322,7 +322,9 @@ def _get_oidc_settings(client_id: str) -> dict: @pytest.fixture(name="create_user_idp", scope="function") -def create_user_idp(idp: types.TestContainerIDP) -> Callable[[str, str, bool, str, str], None]: +def create_user_idp( + idp: types.TestContainerIDP, +) -> Callable[[str, str, bool, str, str], None]: client = KeycloakAdmin( server_url=idp.container.host_configs["6060"].base(), username=IDP_ROOT_USERNAME, @@ -332,7 +334,13 @@ def create_user_idp(idp: types.TestContainerIDP) -> Callable[[str, str, bool, st created_users = [] - def _create_user_idp(email: str, password: str, verified: bool = True, first_name: str = "", last_name: str = "") -> None: + def _create_user_idp( + email: str, + password: str, + verified: bool = True, + first_name: str = "", + last_name: str = "", + ) -> None: payload = { "username": email, "email": email, @@ -400,14 +408,14 @@ def _create_group_idp(group_name: str) -> str: for group_id in created_groups: try: client.delete_group(group_id) - except Exception: # pylint: disable=broad-exception-caught + except Exception: # pylint: disable=broad-exception-caught pass @pytest.fixture(name="create_user_idp_with_groups", scope="function") def create_user_idp_with_groups( idp: types.TestContainerIDP, - create_group_idp: Callable[[str], str], # pylint: disable=redefined-outer-name + create_group_idp: Callable[[str], str], # pylint: disable=redefined-outer-name ) -> Callable[[str, str, bool, List[str]], None]: """Creates a user in Keycloak IDP with specified groups.""" client = KeycloakAdmin( @@ -450,14 +458,14 @@ def _create_user_idp_with_groups( for user_id in created_users: try: client.delete_user(user_id) - except Exception: # pylint: disable=broad-exception-caught + except Exception: # pylint: disable=broad-exception-caught pass @pytest.fixture(name="add_user_to_group", scope="function") def add_user_to_group( idp: types.TestContainerIDP, - create_group_idp: Callable[[str], str], # pylint: disable=redefined-outer-name + create_group_idp: Callable[[str], str], # pylint: disable=redefined-outer-name ) -> Callable[[str, str], None]: """Adds an existing user to a group.""" client = KeycloakAdmin( @@ -478,7 +486,7 @@ def _add_user_to_group(email: str, group_name: str) -> None: @pytest.fixture(name="create_user_idp_with_role", scope="function") def create_user_idp_with_role( idp: types.TestContainerIDP, - create_group_idp: Callable[[str], str], # pylint: disable=redefined-outer-name + create_group_idp: Callable[[str], str], # pylint: disable=redefined-outer-name ) -> Callable[[str, str, bool, str, List[str]], None]: """Creates a user in Keycloak IDP with a custom role attribute and optional groups.""" client = KeycloakAdmin( @@ -524,13 +532,14 @@ def _create_user_idp_with_role( for user_id in created_users: try: client.delete_user(user_id) - except Exception: # pylint: disable=broad-exception-caught + except Exception: # pylint: disable=broad-exception-caught pass @pytest.fixture(name="setup_user_profile", scope="package") def setup_user_profile(idp: types.TestContainerIDP) -> Callable[[], None]: """Setup Keycloak User Profile with signoz_role attribute.""" + def _setup_user_profile() -> None: client = KeycloakAdmin( server_url=idp.container.host_configs["6060"].base(), @@ -538,35 +547,36 @@ def _setup_user_profile() -> None: password=IDP_ROOT_PASSWORD, realm_name="master", ) - + # Get current user profile config profile = client.get_realm_users_profile() - + # Check if signoz_role attribute already exists attributes = profile.get("attributes", []) - signoz_role_exists = any(attr.get("name") == "signoz_role" for attr in attributes) - + signoz_role_exists = any( + attr.get("name") == "signoz_role" for attr in attributes + ) + if not signoz_role_exists: # Add signoz_role attribute to user profile - attributes.append({ - "name": "signoz_role", - "displayName": "SigNoz Role", - "validations": {}, - "annotations": {}, - # "required": { - # "roles": [] # Not required - # }, - "permissions": { - "view": ["admin", "user"], - "edit": ["admin"] - }, - "multivalued": False - }) + attributes.append( + { + "name": "signoz_role", + "displayName": "SigNoz Role", + "validations": {}, + "annotations": {}, + # "required": { + # "roles": [] # Not required + # }, + "permissions": {"view": ["admin", "user"], "edit": ["admin"]}, + "multivalued": False, + } + ) profile["attributes"] = attributes - + # Update the realm user profile client.update_realm_users_profile(payload=profile) - + return _setup_user_profile @@ -575,7 +585,7 @@ def _ensure_groups_client_scope(client: KeycloakAdmin) -> None: # Check if groups scope exists scopes = client.get_client_scopes() groups_scope_exists = any(s.get("name") == "groups" for s in scopes) - + if not groups_scope_exists: # Create the groups client scope client.create_client_scope( @@ -652,11 +662,11 @@ def get_user_by_email(signoz: types.SigNoz, admin_token: str, email: str) -> dic def perform_oidc_login( - signoz: types.SigNoz, # pylint: disable=unused-argument + signoz: types.SigNoz, # pylint: disable=unused-argument idp: types.TestContainerIDP, driver: webdriver.Chrome, get_session_context: Callable[[str], str], - idp_login: Callable[[str, str], None], # pylint: disable=redefined-outer-name + idp_login: Callable[[str, str], None], # pylint: disable=redefined-outer-name email: str, password: str, ) -> None: @@ -688,10 +698,10 @@ def get_saml_domain(signoz: types.SigNoz, admin_token: str) -> dict: def perform_saml_login( - signoz: types.SigNoz, # pylint: disable=unused-argument + signoz: types.SigNoz, # pylint: disable=unused-argument driver: webdriver.Chrome, get_session_context: Callable[[str], str], - idp_login: Callable[[str, str], None], # pylint: disable=redefined-outer-name + idp_login: Callable[[str, str], None], # pylint: disable=redefined-outer-name email: str, password: str, ) -> None: @@ -329,3 +329,130 @@ def find_named_result( ), None, ) + + +def build_scalar_query( + name: str, + signal: str, + aggregations: List[Dict], + *, + group_by: Optional[List[Dict]] = None, + order: Optional[List[Dict]] = None, + limit: Optional[int] = None, + filter_expression: Optional[str] = None, + having_expression: Optional[str] = None, + step_interval: int = DEFAULT_STEP_INTERVAL, + disabled: bool = False, +) -> Dict: + spec: Dict[str, Any] = { + "name": name, + "signal": signal, + "stepInterval": step_interval, + "disabled": disabled, + "aggregations": aggregations, + } + + if group_by: + spec["groupBy"] = group_by + + if order: + spec["order"] = order + + if limit is not None: + spec["limit"] = limit + + if filter_expression: + spec["filter"] = {"expression": filter_expression} + + if having_expression: + spec["having"] = {"expression": having_expression} + + return {"type": "builder_query", "spec": spec} + + +def build_group_by_field( + name: str, + field_data_type: str = "string", + field_context: str = "resource", +) -> Dict: + return { + "name": name, + "fieldDataType": field_data_type, + "fieldContext": field_context, + } + + +def build_order_by(name: str, direction: str = "desc") -> Dict: + return {"key": {"name": name}, "direction": direction} + + +def build_logs_aggregation(expression: str, alias: Optional[str] = None) -> Dict: + agg: Dict[str, Any] = {"expression": expression} + if alias: + agg["alias"] = alias + return agg + + +def build_metrics_aggregation( + metric_name: str, + time_aggregation: str, + space_aggregation: str, + temporality: str = "cumulative", +) -> Dict: + return { + "metricName": metric_name, + "temporality": temporality, + "timeAggregation": time_aggregation, + "spaceAggregation": space_aggregation, + } + + +def get_scalar_table_data(response_json: Dict) -> List[List[Any]]: + results = response_json.get("data", {}).get("data", {}).get("results", []) + if not results: + return [] + return results[0].get("data", []) + + +def get_scalar_columns(response_json: Dict) -> List[Dict]: + results = response_json.get("data", {}).get("data", {}).get("results", []) + if not results: + return [] + return results[0].get("columns", []) + + +def assert_scalar_result_order( + data: List[List[Any]], + expected_order: List[tuple], + context: str = "", +) -> None: + assert len(data) == len(expected_order), ( + f"{context}: Expected {len(expected_order)} rows, got {len(data)}. " + f"Data: {data}" + ) + + for i, (row, expected) in enumerate(zip(data, expected_order)):
Leaderboard for this case
medium · 3 of 9 bots fully caught it (33% solve rate) · 56% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Drape (Deep Review) | solved | 2/2 | 100.0% | 4 | 0 |
| 2 | qodo | solved | 2/2 | 100.0% | 3 | 0 |
| 3 | Cubic | solved | 2/2 | 100.0% | 5 | 1 |
| 4 | cursor | partial | 1/2 | 50.0% | 1 | 0 |
| 5 | Drape (Review) | partial | 1/2 | 50.0% | 3 | 0 |
| 6 | greptile | partial | 1/2 | 50.0% | 2 | 0 |
| 7 | Mjolnir (Opus 5.5) | partial | 1/2 | 50.0% | 3 | 0 |
| 8 | Claude Code (Opus 5.5) | miss | 0/2 | 0.0% | 2 | 0 |
| 9 | Mjolnir (Sonnet 5.5) | miss | 0/2 | 0.0% | 0 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✗ | — |
queryNames is sorted alphabetically, and keyOrder is filled in that order. When HasOrderSpecified is true, no re-sort happens, so the table keeps the first query's row order. An order set only on a later query or formula (e.g. F1) is lost, and rows found only in later queries go at the end. The new no-sort path added by this change causes this. [grounded: diff] [consensus 3/3: valid=3]
HasOrderSpecified loops over every query and never checks Disabled. filterDisabledQueries drops disabled results before formatting, so an order on a disabled query still turns off the default sort for the visible results. The PromQL/ClickHouse part of the finding is a side detail, but the main failure is real. [grounded: diff] [consensus 3/3: valid=3]
raw comments (2)
When any query has an explicit order, `mergeScalarData` skips the default sort and keeps rows in insertion order. Insertion order follows `queryNames`, which is sorted alphabetically, so the first query's rows set the order of the whole table. If the order is on a later query or a formula (for example `F1` ordered by its value, merged with `A` and `B`), the table comes back in `A`'s order and the user's order is lost. Rows that exist only in later queries are tacked onto the end. The merged table should be ordered by the query or formula that carries the order (or re-sorted with the requested order keys), not by whichever query name sorts first.
`HasOrderSpecified` looks at every query, including disabled ones, and turns off the default sort for the entire table. A disabled query that still has an order (disabled results are filtered out before formatting) therefore leaves the visible results unsorted, even though none of them asked for an order. It also never looks at ClickHouse SQL or PromQL specs. Disabled queries should be skipped here, and the decision should probably be made per query.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | medium | ✓ | exact |
These helpers are meant for responses formatted with formatTableResultForUI. In that mode the server merges every query into one table and returns it as a single result under the first query's name, so results[0] is the right result. No test in this change sends more than one query. [invalid: contradiction] [consensus 5/5: invalid=5]
HasOrderSpecified never checks spec.Disabled. If a disabled query still carries an order, default sorting is turned off for the merged table even though that query's results are filtered out and its order applies to nothing shown. [grounded: diff] [consensus 5/5: valid=5]
Every log body is unique, so count_distinct(body) equals count() for each service. The expected descending order is therefore the same as the default count() desc order, and the test cannot tell ordering by the second aggregation apart from the default sort. [grounded: diff] [consensus 5/5: valid=5]
raw comments (6)
<!-- cubic:v=81ccb2c2-9d38-4a03-b79a-d74e8f262a5a -->
<!-- cubic:review-run=8d6b6af1-cfad-57f2-9fce-eaeb1a0b42b7 -->
<!-- metadata:{"confidence":8} -->
P2: `get_scalar_table_data` and `get_scalar_columns` silently take `results[0]`, while every other result accessor in this module (`get_series_values`, `get_all_series`, `get_scalar_value`) resolves the result by query name via `find_named_result`. Once a test sends more than one query in a request, these helpers will assert against the wrong query's data with no error. Accept a `query_name` parameter and resolve through `find_named_result`, falling back to `results[0]` only when a single result exists.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At tests/integration/fixtures/querier.py, line 414:
<comment>`get_scalar_table_data` and `get_scalar_columns` silently take `results[0]`, while every other result accessor in this module (`get_series_values`, `get_all_series`, `get_scalar_value`) resolves the result by query name via `find_named_result`. Once a test sends more than one query in a request, these helpers will assert against the wrong query's data with no error. Accept a `query_name` parameter and resolve through `find_named_result`, falling back to `results[0]` only when a single result exists.</comment>
<file context>
@@ -329,3 +329,130 @@ def find_named_result(
+ results = response_json.get("data", {}).get("data", {}).get("results", [])
+ if not results:
+ return []
+ return results[0].get("data", [])
+
+
</file context>
```
</details>
<!-- cubic:v=7ac3b843-217d-4c89-94e1-3ae782aff5a1 -->
<!-- cubic:review-run=8d6b6af1-cfad-57f2-9fce-eaeb1a0b42b7 -->
<!-- metadata:{"confidence":9} -->
P2: When a disabled query retains an `order`, table formatting disables default sorting for the enabled results. Ignore disabled queries when deciding whether an order is present.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At pkg/types/querybuildertypes/querybuildertypesv5/req.go, line 280:
<comment>When a disabled query retains an `order`, table formatting disables default sorting for the enabled results. Ignore disabled queries when deciding whether an order is present.</comment>
<file context>
@@ -276,6 +276,31 @@ func (r *QueryRangeRequest) NumAggregationForQuery(name string) int64 {
}
+// HasOrderSpecified returns true if any query has an explicit order provided.
+func (r *QueryRangeRequest) HasOrderSpecified() bool {
+ for _, query := range r.CompositeQuery.Queries {
+ switch spec := query.Spec.(type) {
</file context>
```
</details>
<!-- cubic:v=44f58492-7aef-45ac-bf4b-0119d33b1425 -->
<!-- cubic:review-run=8d6b6af1-cfad-57f2-9fce-eaeb1a0b42b7 -->
<!-- metadata:{"confidence":8} -->
P2: When a scalar formula specifies `Order`, `processScalarFormula` never applies it because the result is `ScalarData`, yet this line disables the fallback sort. Apply the formula order to scalar rows before suppressing the default sort, otherwise the table order is unspecified rather than requested.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At pkg/querier/postprocess.go, line 591:
<comment>When a scalar formula specifies `Order`, `processScalarFormula` never applies it because the result is `ScalarData`, yet this line disables the fallback sort. Apply the formula order to scalar rows before suppressing the default sort, otherwise the table order is unspecified rather than requested.</comment>
<file context>
@@ -581,11 +582,14 @@ func (q *querier) filterDisabledQueries(results map[string]*qbtypes.Result, req
}
+ // apply default sorting if no order specified
+ applyDefaultSort := !req.HasOrderSpecified()
+
// Convert all results to ScalarData first
</file context>
```
</details>
<!-- cubic:v=e0cb898d-aa32-48c3-83e8-b22eecbf443f -->
<!-- cubic:review-run=8d6b6af1-cfad-57f2-9fce-eaeb1a0b42b7 -->
<!-- metadata:{"confidence":9} -->
P2: When a scalar trace-operator query specifies `order`, `HasOrderSpecified` returns false because it does not handle `QueryBuilderTraceOperator`, so table formatting reapplies descending first-aggregation sorting. Handle `QueryBuilderTraceOperator.Order` in this switch.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At pkg/types/querybuildertypes/querybuildertypesv5/req.go, line 295:
<comment>When a scalar trace-operator query specifies `order`, `HasOrderSpecified` returns false because it does not handle `QueryBuilderTraceOperator`, so table formatting reapplies descending first-aggregation sorting. Handle `QueryBuilderTraceOperator.Order` in this switch.</comment>
<file context>
@@ -276,6 +276,31 @@ func (r *QueryRangeRequest) NumAggregationForQuery(name string) int64 {
+ if len(spec.Order) > 0 {
+ return true
+ }
+ case QueryBuilderFormula:
+ if len(spec.Order) > 0 {
+ return true
</file context>
```
</details>
<!-- cubic:v=8a8c350a-661c-4cb8-b25c-5cf4e5dd0232 -->
<!-- cubic:review-run=8d6b6af1-cfad-57f2-9fce-eaeb1a0b42b7 -->
<!-- metadata:{"confidence":7} -->
P3: This test cannot detect a broken 'order by second aggregation' feature. Because each log body is unique, count_distinct(body) equals count() for every service, so the expected descending order is identical to the default count() desc order already asserted in the no-order test. Use an ascending direction, or make bodies duplicate per service, so the expected order diverges from the default and the assertion actually exercises the order-by clause.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At tests/integration/src/querier/06_order_by_table_querier.py, line 420:
<comment>This test cannot detect a broken 'order by second aggregation' feature. Because each log body is unique, count_distinct(body) equals count() for every service, so the expected descending order is identical to the default count() desc order already asserted in the no-order test. Use an ascending direction, or make bodies duplicate per service, so the expected order diverges from the default and the assertion actually exercises the order-by clause.</comment>
<file context>
@@ -0,0 +1,1004 @@
+ data = querier.get_scalar_table_data(response.json())
+ # count_distinct(body) should equal count() since each log has unique body
+ querier.assert_scalar_column_order(
+ data, 0, ["service-c", "service-a", "service-b", "service-d"], "First column"
+ )
+
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**5 issues found** across 8 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="tests/integration/fixtures/querier.py">
<violation number="1" location="tests/integration/fixtures/querier.py:414">
P2: `get_scalar_table_data` and `get_scalar_columns` silently take `results[0]`, while every other result accessor in this module (`get_series_values`, `get_all_series`, `get_scalar_value`) resolves the result by query name via `find_named_result`. Once a test sends more than one query in a request, these helpers will assert against the wrong query's data with no error. Accept a `query_name` parameter and resolve through `find_named_result`, falling back to `results[0]` only when a single result exists.</violation>
</file>
<file name="pkg/types/querybuildertypes/querybuildertypesv5/req.go">
<violation number="1" location="pkg/types/querybuildertypes/querybuildertypesv5/req.go:280">
P2: When a disabled query retains an `order`, table formatting disables default sorting for the enabled results. Ignore disabled queries when deciding whether an order is present.</violation>
<violation number="2" location="pkg/types/querybuildertypes/querybuildertypesv5/req.go:295">
P2: When a scalar trace-operator query specifies `order`, `HasOrderSpecified` returns false because it does not handle `QueryBuilderTraceOperator`, so table formatting reapplies descending first-aggregation sorting. Handle `QueryBuilderTraceOperator.Order` in this switch.</violation>
</file>
<file name="pkg/querier/postprocess.go">
<violation number="1" location="pkg/querier/postprocess.go:591">
P2: When a scalar formula specifies `Order`, `processScalarFormula` never applies it because the result is `ScalarData`, yet this line disables the fallback sort. Apply the formula order to scalar rows before suppressing the default sort, otherwise the table order is unspecified rather than requested.</violation>
</file>
<file name="tests/integration/src/querier/06_order_by_table_querier.py">
<violation number="1" location="tests/integration/src/querier/06_order_by_table_querier.py:420">
P3: This test cannot detect a broken 'order by second aggregation' feature. Because each log body is unique, count_distinct(body) equals count() for every service, so the expected descending order is identical to the default count() desc order already asserted in the no-order test. Use an ascending direction, or make bodies duplicate per service, so the expected order diverges from the default and the assertion actually exercises the order-by clause.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/97/ai_pr_review_github_delivery_ce3b782879bd525b7b0d49f9137e21f83386c1349f9e6ed435f15e908921fbcb?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F97)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_ce3b782879bd525b7b0d49f9137e21f83386c1349f9e6ed435f15e908921fbcb:ebcdeb82f0dfa91dc3b001601c6c6ec7d12961c1:8d6b6af1-cfad-57f2-9fce-eaeb1a0b42b7 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✓ | exact |
raw comments (2)
### Order check skips some query types
**Medium Severity**
<!-- DESCRIPTION START -->
`HasOrderSpecified` never inspects `QueryBuilderTraceOperator` or `QueryBuilderJoin`, even though both carry an `Order` field. Scalar table formatting then treats those requests as unordered and re-sorts by the first aggregation, overwriting the order already applied in SQL.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 77b324fe-7f44-4c94-b924-e77d07a58f16 -->
<!-- LOCATIONS START
pkg/types/querybuildertypes/querybuildertypesv5/req.go#L279-L302
pkg/querier/postprocess.go#L590-L591
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`pkg/querier/postprocess.go#L590-L591`](https://github.com/drape-io/crbench-cursor-2026-09/blob/1477348e1b5672f28d632987dd3e26b8ff91a628/pkg/querier/postprocess.go#L590-L591)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjVhNTNiNDlhLWVjMzgtNGUwYi1hMWRhLTNkY2RiMmUzNTQ4NSIsImVuY3J5cHRpb25LZXkiOiJSZUxIcWk1RVREU3Q1aktOX2ZLSXR5b3pLLVB5cXg0QlVVTzVXbHJmcU5rIiwiYnJhbmNoIjoidDItc2lnbm96LTEwMDMzIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjVhNTNiNDlhLWVjMzgtNGUwYi1hMWRhLTNkY2RiMmUzNTQ4NSIsImVuY3J5cHRpb25LZXkiOiJSZUxIcWk1RVREU3Q1aktOX2ZLSXR5b3pLLVB5cXg0QlVVTzVXbHJmcU5rIiwiYnJhbmNoIjoidDItc2lnbm96LTEwMDMzIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6NzksImNvbW1pdFNoYSI6IjE0NzczNDhlMWI1NjcyZjI4ZDYzMjk4N2RkM2UyNmI4ZmY5MWE2MjgiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 1477348e1b5672f28d632987dd3e26b8ff91a628. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aToxOTg5MGZjNS1hNTVkLTQwZjMtYjA4ZC1mNzg0NjIwNGFmMDIiLCJlbmNyeXB0aW9uS2V5IjoiY1RCQXppeVlWaUg0NlhROXFrZ3hJNDJiaUZRV3dhZ1ZDRk9uZll0dHcwSSIsImJyYW5jaCI6InQyLXNpZ25vei0xMDAzMyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 1477348e1b5672f28d632987dd3e26b8ff91a628. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | medium | ✓ | exact |
The new HasOrderSpecified loops over every query and never checks Disabled. filterDisabledQueries later drops disabled results, so an order set only on a hidden query still turns off the default sort for the queries that are shown. [grounded: tree pkg/types/querybuildertypes/querybuildertypesv5/req.go] [consensus 3/3: valid=3]
When an order is set, mergeScalarData skips sorting and keeps rows in insertion order. Rows are inserted query by query in alphabetical order, so the first query's row order wins. An order set only on B is never applied, and the change also removes the default sort that used to run. [grounded: tree pkg/querier/postprocess.go] [consensus 3/3: valid=3]
raw comments (4)
**Trace operator order ignored, table still re-sorted**
`HasOrderSpecified` checks builder queries and formulas but not `QueryBuilderTraceOperator`, which also has an `Order` field. A scalar table whose only explicit order is on a trace operator still gets the default sort, which discards that order. Add a `QueryBuilderTraceOperator` case that checks `spec.Order`.
```
pkg/types/querybuildertypes/querybuildertypesv5/req.go:280 func (r *QueryRangeRequest) HasOrderSpecified() bool {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:281 for _, query := range r.CompositeQuery.Queries {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:282 switch spec := query.Spec.(type) {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:283 case QueryBuilderQuery[TraceAggregation]:
pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go:49 Order []OrderBy `json:"order,omitempty"`
pkg/querier/postprocess.go:75 case qbtypes.QueryBuilderTraceOperator:
pkg/querier/postprocess.go:76 if result, ok := typedResults[spec.Name]; ok {
pkg/querier/postprocess.go:77 result = postProcessTraceOperator(q, result, spec, req)
pkg/querier/postprocess.go:78 typedResults[spec.Name] = result
pkg/querier/postprocess.go:79 }
```
**Disabled query's order switches off default sort**
`HasOrderSpecified` also looks at disabled queries, whose results are dropped from the table. If a hidden query has an order, the shown queries lose the default descending sort. Skip disabled queries in `HasOrderSpecified`.
```
pkg/types/querybuildertypes/querybuildertypesv5/req.go:280 func (r *QueryRangeRequest) HasOrderSpecified() bool {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:281 for _, query := range r.CompositeQuery.Queries {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:282 switch spec := query.Spec.(type) {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:283 case QueryBuilderQuery[TraceAggregation]:
pkg/querier/postprocess.go:569 func (q *querier) filterDisabledQueries(results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) map[string]*qbtypes.Result {
pkg/querier/postprocess.go:570 filtered := make(map[string]*qbtypes.Result)
pkg/querier/postprocess.go:572 for _, query := range req.CompositeQuery.Queries {
pkg/querier/postprocess.go:573 info := getqueryInfo(query.Spec)
pkg/querier/postprocess.go:574 if !info.Disabled {
pkg/querier/postprocess.go:575 if result, ok := results[info.Name]; ok {
```
**Merged table ignores which query's order was requested**
If only one merged query (e.g. B) has an order, rows keep the alphabetically first query's row order and the default sort is skipped, so B's order is never applied. When an order is set, sort merged rows by that query's order keys.
```
pkg/querier/postprocess.go:591 applyDefaultSort := !req.HasOrderSpecified()
pkg/querier/postprocess.go:782 rowMap := make(map[string][]any)
pkg/querier/postprocess.go:783 var keyOrder []string
pkg/querier/postprocess.go:785 for _, queryName := range queryNames {
pkg/querier/postprocess.go:770 sort.Strings(queryNames)
pkg/querier/postprocess.go:786 sd := results[queryName]
pkg/querier/postprocess.go:787 // Create index mappings
pkg/querier/postprocess.go:788 groupMap := make(map[string]int)
pkg/querier/postprocess.go:789 for i, col := range sd.Columns {
pkg/querier/postprocess.go:790 if col.Type == qbtypes.ColumnTypeGroup {
```
**Ordered scalar formula table rows come back unsorted**
The formula's order turns off the default sort, but applySeriesLimit skips ScalarData, so that order is never applied. Rows keep EvaluateFormula's arbitrary goroutine completion order. Apply the formula order to the scalar rows, or keep the default sort.
```
pkg/querier/postprocess.go:590 // apply default sorting if no order specified
pkg/querier/postprocess.go:591 applyDefaultSort := !req.HasOrderSpecified()
pkg/querier/postprocess.go:845 // sort by first aggregation (descending) if no order was specified
pkg/querier/postprocess.go:846 if applyDefaultSort {
pkg/querier/postprocess.go:264 func (q *querier) applySeriesLimit(result *qbtypes.Result, limit int, orderBy []qbtypes.OrderBy) *qbtypes.Result {
pkg/querier/postprocess.go:265 tsData, ok := result.Value.(*qbtypes.TimeSeriesData)
pkg/querier/postprocess.go:266 if !ok {
pkg/querier/postprocess.go:267 return result
pkg/querier/postprocess.go:268 }
pkg/querier/postprocess.go:464 labelKeys := make([]string, 0, len(rowsByLabels))
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✓ | exact |
Take two queries where only the one that sorts later by name (B) has an order. HasOrderSpecified then returns true, so the default sort is skipped. mergeScalarData inserts rows in sorted query-name order, so the rows follow A's unordered output and B's order is never applied. Before this change the table at least got the default sort by first aggregation. [grounded: tree pkg/querier/postprocess.go] [consensus 3/3: valid=3]
The new HasOrderSpecified never checks spec.Disabled. filterDisabledQueries drops disabled results before formatting, so an order on a disabled query still turns off the default sort for the queries that remain visible. [grounded: tree pkg/types/querybuildertypes/querybuildertypesv5/req.go] [consensus 3/3: valid=3]
raw comments (3)
**Trace operator order ignored by HasOrderSpecified**
`HasOrderSpecified` checks builder queries and formulas but not `QueryBuilderTraceOperator`, which also has an `Order` field. A scalar table request ordered only on a trace operator gets the default descending sort applied over it. Add a `case QueryBuilderTraceOperator:` branch that checks `len(spec.Order) > 0`.
```
pkg/types/querybuildertypes/querybuildertypesv5/req.go:280 func (r *QueryRangeRequest) HasOrderSpecified() bool {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:281 for _, query := range r.CompositeQuery.Queries {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:282 switch spec := query.Spec.(type) {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:283 case QueryBuilderQuery[TraceAggregation]:
pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go:37 type QueryBuilderTraceOperator struct {
pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go:38 Name string `json:"name"`
pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go:39 Disabled bool `json:"disabled,omitempty"`
pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go:41 Expression string `json:"expression"`
pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go:43 Filter *Filter `json:"filter,omitempty"`
pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go:45 // User-configurable span return strategy - which query's spans to return
```
**Merged table ignores a later query's order**
When only a query that sorts later by name has an order, rows follow the first query's order and that query's rows are appended. The default sort is skipped too. Sort merged rows by the ordered query's spec, or keep the default sort.
```
pkg/querier/postprocess.go:785 for _, queryName := range queryNames {
pkg/querier/postprocess.go:786 sd := results[queryName]
pkg/querier/postprocess.go:839 // Convert to slice, preserving insertion order
pkg/querier/postprocess.go:840 data := make([][]any, 0, len(rowMap))
```
**Disabled queries' order disables default sort**
HasOrderSpecified counts queries that are disabled. filterDisabledQueries drops their results before formatting, so an order on a disabled query turns off the default sort for the remaining unordered queries. Skip queries whose spec is disabled when checking for an order.
```
pkg/types/querybuildertypes/querybuildertypesv5/req.go:281 for _, query := range r.CompositeQuery.Queries {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:282 switch spec := query.Spec.(type) {
pkg/types/querybuildertypes/querybuildertypesv5/req.go:283 case QueryBuilderQuery[TraceAggregation]:
pkg/types/querybuildertypes/querybuildertypesv5/req.go:284 if len(spec.Order) > 0 {
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | medium | ✗ | — |
The new HasOrderSpecified loops over every query in the request and never checks spec.Disabled. Disabled results are removed by filterDisabledQueries before formatting, so a disabled query that has an order still sets applyDefaultSort=false, and the visible table's rows stay unsorted. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Disabled Queries Suppress Sorting**
A disabled query with an `order` still makes `HasOrderSpecified` return true. Disabled results are removed before table formatting, but this method scans the original request without checking `Disabled`. As a result, an unrelated disabled query suppresses the visible table's default descending aggregation sort and leaves its rows in insertion order.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Formula Order Is Lost**
When a scalar formula has an `order`, this method disables the table's fallback sort. However, scalar formula processing rebuilds rows in lexicographically sorted label order, and `applySeriesLimit` does not apply the formula order because it only handles `TimeSeriesData`. The table can therefore return an ordered scalar formula in label order instead of the requested aggregation order.
<h3>Greptile Summary</h3>
This PR changes scalar UI-table postprocessing to retain upstream row order whenever a request contains an explicit order, while retaining the existing descending aggregation fallback for unordered requests. It also adds integration-test builders and broad ordering coverage for log, trace, and metric scalar queries, alongside formatting-only authentication test changes.
- Preserves first-seen row order while deduplicating and merging scalar results.
- Adds request-level detection of explicit builder-query and formula ordering.
- Adds integration coverage for aggregation/group-key ordering and limits.
- The request-wide detection currently includes disabled queries and incorrectly assumes scalar formula order survives formula processing.
<h3>Confidence Score: 3/5</h3>
The PR is not yet safe to merge because disabled query ordering and scalar formula ordering can both produce incorrectly ordered UI tables.
The new request-wide order check suppresses fallback sorting even when the ordered query was filtered out, and scalar formulas are rebuilt in label order without applying their requested order before that fallback is disabled.
**Files Needing Attention:** pkg/types/querybuildertypes/querybuildertypesv5/req.go, pkg/querier/postprocess.go
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| pkg/querier/postprocess.go | Preserves scalar row insertion order and conditionally skips fallback sorting, but this exposes formula and request-wide ordering mismatches. |
| pkg/types/querybuildertypes/querybuildertypesv5/req.go | Adds explicit-order detection that includes disabled queries and treats formula ordering as already preserved. |
| tests/integration/src/querier/06_order_by_table_querier.py | Adds extensive single-builder-query ordering tests but does not cover disabled ordered queries or scalar formulas. |
| tests/integration/fixtures/querier.py | Adds focused request builders and scalar table assertion helpers for integration tests. |
</details>
<details open><summary><h3>Flowchart</h3></summary>
```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Scalar query results] --> B[Apply formulas]
B --> C[Filter disabled results]
C --> D{HasOrderSpecified on original request?}
D -->|No| E[Merge or deduplicate rows]
E --> F[Sort by first aggregation descending]
D -->|Yes| G[Merge or deduplicate preserving input order]
F --> H[UI table result]
G --> H
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update pkg/querier/postprocess.go and 7 ..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/aa516bda31032fefba8c9b9a723a872ecde7c430) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64289070)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✓ | exact |
HasOrderSpecified handles builder queries and formulas but not QueryBuilderTraceOperator, even though that type has an Order field. A trace operator's explicit order therefore still gets overridden by the default descending sort. This is an incomplete change: the PR covers some query types and leaves this one out. [grounded: tree pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go] [consensus 3/3: valid=3]
keyOrder is filled in the order of the alphabetically sorted query names. Rows therefore come out in the first query's order, and HasOrderSpecified turns off the default sort if any query has an order. So when only a later query or formula specifies an order, that order is ignored and the rows follow the first query's order. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
[P2] `HasOrderSpecified` ignores trace operator queries, so their explicit order is overridden
`HasOrderSpecified` only checks the trace, log and metric builder queries and formulas. It never checks `QueryBuilderTraceOperator`, even though that spec has its own `Order` field (trace_operator.go:49) and the CTE builder uses it to build the SQL `ORDER BY`. Take a scalar table request with `formatTableResultForUI` whose queries carry no order except a trace operator with an explicit order (e.g. `service.name asc`, or an aggregation `asc`). In that case `applyDefaultSort` stays true, and `deduplicateRows`/`mergeScalarData` re-sort the rows by the first aggregation in descending order. The user's chosen order for trace operator tables is still lost, which is the problem this change is meant to fix. Adding a `QueryBuilderTraceOperator` case that checks `spec.Order` would cover it.
[P2] Trace operator queries are not covered by `HasOrderSpecified`, so the table still re-sorts them by default
`QueryBuilderTraceOperator` has its own `Order []OrderBy` field (trace_operator.go:49), and it is handled in `postProcessQueryRangeResult` and in the querier. The new type switch has no case for it, though. When a scalar table request contains a trace operator with an explicit order, such as ascending by count, `HasOrderSpecified()` returns false. `formatScalarResultsAsTable` then runs `sortByFirstAggregation`, which sorts the rows descending by the first aggregation and discards the order the user asked for. Before this change that was true for every query type; this PR fixes it for builder queries and formulas but leaves trace operators out.
[P2] With several queries, the merged table only keeps the row order of the alphabetically-first query, and explicit orders on the other queries are dropped
`mergeScalarData` walks `queryNames` in sorted order and records `keyOrder` the first time each row key appears. Because every query usually returns the same group keys, the final row order comes almost entirely from the query whose name sorts first (e.g. `A`). Take a table with query `A` that has no order and formula `F1` (or query `B`) ordered `asc`. `HasOrderSpecified()` returns true, so the default sort is turned off, but the rows come out in A's order, not F1's/B's requested ascending order. The explicit order is never applied, and the default descending sort that used to run is skipped. The order needs to come from the query or formula that actually specifies it, or the merged rows need to be sorted by that order. The new integration tests cover only single-query requests, so they don't catch this.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✗ | — |
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | medium | ✓ | off by one |
The new HasOrderSpecified loops over every query in CompositeQuery.Queries and returns true for any non-empty Order. It never checks Disabled. formatScalarResultsAsTable runs after filterDisabledQueries has already dropped the disabled results, so a disabled query that has an order still turns off the default descending sort for the enabled results that get shown. Nothing in the shown code guards against this. The change introduced the behavior. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. Formula ordering is ignored in tables <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>HasOrderSpecified</i></b> treats formula ordering as satisfied, but <b><i>processScalarFormula</i></b> constructs rows
in sorted label-key order and <b><i>applySeriesLimit</i></b> ignores <b><i>ScalarData</i></b>. When a scalar formula
supplies <b><i>Order</i></b>, table formatting now skips default sorting even though no formula sort occurs,
leaving rows in label order rather than the requested aggregation order.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
Scalar formula orders disable table fallback sorting without being applied to the formula rows, so explicit aggregation ordering is lost.
## Fix Focus Areas
- pkg/querier/postprocess.go[328-332]
- pkg/querier/postprocess.go[464-497]
- pkg/querier/postprocess.go[515-565]
- pkg/types/querybuildertypes/querybuildertypesv5/req.go[295-298]
## Recommended Fix
Apply the formula's order and limit to evaluated scalar formula series before converting them into `ScalarData`, or implement equivalent scalar-row ordering. Add tests for ascending and descending formula orders with labels whose lexical order differs from their values.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
3\. Disabled queries change visible table order <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>HasOrderSpecified</i></b> scans every query for a non-empty <b><i>Order</i></b> without checking <b><i>Disabled</i></b>, while
<b><i>formatScalarResultsAsTable</i></b> uses that request-wide result after <b><i>filterDisabledQueries</i></b> has removed
disabled results. When a disabled ordered query accompanies enabled unordered scalar results, the
formatter skips its default descending sort and preserves backend insertion order, so toggling an
otherwise invisible query changes the table returned to users.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
`HasOrderSpecified` treats disabled queries as active ordering instructions even though their results are filtered out before scalar table formatting. Consequently, an ordered disabled query can suppress the default descending sort for enabled unordered results.
## Fix Focus Areas
- pkg/types/querybuildertypes/querybuildertypesv5/req.go[279-302]
- pkg/querier/postprocess.go[83-104]
- pkg/querier/postprocess.go[568-591]
## Recommended Fix
Update order detection to ignore disabled builder queries, formulas, and trace operators. Check each supported query type's `Disabled` field before considering its `Order`, so sorting depends only on results that can reach the response. Add a test with an ordered disabled query and an unordered enabled query, and verify that the enabled scalar table retains its default descending sort.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
2\. Trace tables ignore requested ordering <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>HasOrderSpecified</i></b> omits <b><i>QueryBuilderTraceOperator</i></b>, even though that scalar-capable query type
exposes <b><i>Order</i></b> and passes it to post-processing. When an enabled scalar trace-operator query has a
non-empty explicit order, table formatting receives <b><i>applyDefaultSort=true</i></b> and re-sorts rows
descending by the first aggregation, overriding both ascending and descending requested order.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
`HasOrderSpecified` does not inspect `QueryBuilderTraceOperator.Order`, causing scalar trace-operator table formatting to overwrite explicitly requested row ordering with its default descending first-aggregation sort.
## Fix Focus Areas
- pkg/types/querybuildertypes/querybuildertypesv5/req.go[279-302]
- pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go[37-59]
- pkg/querier/postprocess.go[220-237]
## Recommended Fix
Add a `QueryBuilderTraceOperator` case to `HasOrderSpecified` that returns true when the trace-operator query is enabled and its `Order` slice is non-empty. Add coverage for scalar trace-operator table output proving that both ascending and descending explicit orders are retained.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<h3>PR Summary by Qodo</h3>
Preserve explicit ordering in scalar table results
<code>🐞 Bug fix</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Preserve explicit scalar table ordering while retaining defaults for unordered requests.
>• Keep merged and deduplicated scalar rows in their original query-result order.
>• Test aggregation, grouping-key, and limit ordering across all telemetry signals.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
graph TD
A["Scalar request"] --> B["Signal query"] --> C["Scalar results"] --> D["Table formatter"] --> E{"Explicit order?"}
E -->|Yes| F["Preserve rows"] --> H["UI table"]
E -->|No| G["Default descending"] --> H
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The approach is appropriate: query execution already applies explicit ordering and limits, so post-processing should preserve that row order rather than duplicate ordering semantics. Reconstructing and reapplying every order clause in the table formatter was considered but would be more invasive and risk diverging from signal-specific query behavior; retaining the existing default sort only for unordered requests is simpler and backward compatible.
</dd>
</dl>
</details>
<details>
<summary> Files changed (8) <code> +1340 / -108 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Bug fix (2) <code> +59 / -21 </code></summary>
<dl>
<dd>
<details>
<summary>postprocess.go<code>Preserve explicit scalar result ordering during table formatting</code> <code>+34/-21</code></summary>
<br/>
>Preserve explicit scalar result ordering during table formatting
>
><pre>
>• Detects whether the request contains explicit ordering and only applies the default aggregation sort when none exists. Deduplication and multi-result merging now retain insertion order instead of rebuilding rows through nondeterministic map iteration. Formula request dispatch is also expressed as a request-type switch.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-607aeb957d880e2851b920f66fdcb855b9552f23eeb6e002ce25e185d287cf63'>pkg/querier/postprocess.go</a>
</details>
<details>
<summary>req.go<code>Detect explicit ordering across query specifications</code> <code>+25/-0</code></summary>
<br/>
>Detect explicit ordering across query specifications
>
><pre>
>• Adds 'HasOrderSpecified' to inspect trace, log, metric, and formula specifications for order clauses. Scalar table post-processing uses this signal to decide whether default sorting is appropriate.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-16818cff9136ae965e63d1fe769aa177da55dbc47e0ad5eb0e4319af684a65bc'>pkg/types/querybuildertypes/querybuildertypesv5/req.go</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Refactor (4) <code> +150 / -87 </code></summary>
<dl>
<dd>
<details>
<summary>idputils.py<code>Format identity-provider integration fixtures</code> <code>+44/-34</code></summary>
<br/>
>Format identity-provider integration fixtures
>
><pre>
>• Reformats fixture signatures, comments, profile configuration, and whitespace for consistent Python style. Fixture behavior remains unchanged.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-306962cd2435defef4f031ad1f2ee740837769efcabac0148f67e531ec328d98'>tests/integration/fixtures/idputils.py</a>
</details>
<details>
<summary>01_domain.py<code>Format callback domain assertions</code> <code>+5/-2</code></summary>
<br/>
>Format callback domain assertions
>
><pre>
>• Reformats the accepted-domain assertion and removes trailing whitespace without changing test behavior.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-1423c3897b803eb972a9e31163d7faf51e73e82e0057a5c6a39c4d553bf14044'>tests/integration/src/callbackauthn/01_domain.py</a>
</details>
<details>
<summary>02_saml.py<code>Clean up SAML integration test formatting</code> <code>+52/-24</code></summary>
<br/>
>Clean up SAML integration test formatting
>
><pre>
>• Reorders and groups imports, removes an unused fixture import, and reformats long fixture and login calls. Existing SAML role and name-mapping assertions are unchanged.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-9dd1a0829629da1ae03fd634c9e430e09003a166883ba83a42878a5ad47b0cd7'>tests/integration/src/callbackauthn/02_saml.py</a>
</details>
<details>
<summary>03_oidc.py<code>Clean up OIDC integration test formatting</code> <code>+49/-27</code></summary>
<br/>
>Clean up OIDC integration test formatting
>
><pre>
>• Removes an unused fixture import and reformats long setup, login, and assertion expressions. Existing OIDC role and display-name test behavior remains unchanged.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-e7067e79f77320481b853b5fb357f7d659a047b397fe1a8155d0a7f86abbd4ab'>tests/integration/src/callbackauthn/03_oidc.py</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Tests (2) <code> +1131 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>querier.py<code>Add scalar query builders and ordering assertions</code> <code>+127/-0</code></summary>
<br/>
>Add scalar query builders and ordering assertions
>
><pre>
>• Adds reusable builders for scalar queries, grouping fields, order clauses, and log or metric aggregations. Also adds response extraction and row/column ordering assertion helpers for querier integration tests.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-8a59096c83e3d6f65eb5c1992f10c29b1fd896cea0a2e388bffea46841b41532'>tests/integration/fixtures/querier.py</a>
</details>
<details>
<summary>06_order_by_table_querier.py<code>Cover scalar table ordering across telemetry signals</code> <code>+1004/-0</code></summary>
<br/>
>Cover scalar table ordering across telemetry signals
>
><pre>
>• Adds end-to-end scalar table tests for logs, traces, and metrics using deterministic grouped datasets. Coverage verifies default descending behavior, explicit ascending and descending aggregation or grouping-key order, multiple aggregations, and order-plus-limit combinations.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-e20f153ece4f00b82d00da6d5e070c92c2804399e8e1faa662ea205b452adf9d'>tests/integration/src/querier/06_order_by_table_querier.py</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<h3>Code Review by Qodo</h3>
<code>🐞 Bugs (3)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<br/>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
<details>
<summary> 1. Formula ordering is ignored in tables <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>HasOrderSpecified</i></b> treats formula ordering as satisfied, but <b><i>processScalarFormula</i></b> constructs rows
>in sorted label-key order and <b><i>applySeriesLimit</i></b> ignores <b><i>ScalarData</i></b>. When a scalar formula
>supplies <b><i>Order</i></b>, table formatting now skips default sorting even though no formula sort occurs,
>leaving rows in label order rather than the requested aggregation order.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[pkg/types/querybuildertypes/querybuildertypesv5/req.go[R295-298]](https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-16818cff9136ae965e63d1fe769aa177da55dbc47e0ad5eb0e4319af684a65bcR295-R298)</code>
>
>```diff
>+ case QueryBuilderFormula:
>+ if len(spec.Order) > 0 {
>+ return true
>+ }
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>Formula rows originate from lexicographically sorted label keys, while the only subsequent order
>application calls a helper that immediately returns for non-time-series results. The new formula
>case nevertheless prevents the formatter from applying its fallback sort.
></pre>
>
> <code>[pkg/querier/postprocess.go[263-273]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L263-L273)</code>
> <code>[pkg/querier/postprocess.go[464-497]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L464-L497)</code>
> <code>[pkg/querier/postprocess.go[515-565]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L515-L565)</code>
> <code>[pkg/querier/postprocess.go[590-613]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L590-L613)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>Scalar formula orders disable table fallback sorting without being applied to the formula rows, so explicit aggregation ordering is lost.
>
>## Fix Focus Areas
>- pkg/querier/postprocess.go[328-332]
>- pkg/querier/postprocess.go[464-497]
>- pkg/querier/postprocess.go[515-565]
>- pkg/types/querybuildertypes/querybuildertypesv5/req.go[295-298]
>
>## Recommended Fix
>Apply the formula's order and limit to evaluated scalar formula series before converting them into `ScalarData`, or implement equivalent scalar-row ordering. Add tests for ascending and descending formula orders with labels whose lexical order differs from their values.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 2. Trace tables ignore requested ordering <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>HasOrderSpecified</i></b> omits <b><i>QueryBuilderTraceOperator</i></b>, even though that scalar-capable query type
>exposes <b><i>Order</i></b> and passes it to post-processing. When an enabled scalar trace-operator query has a
>non-empty explicit order, table formatting receives <b><i>applyDefaultSort=true</i></b> and re-sorts rows
>descending by the first aggregation, overriding both ascending and descending requested order.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[pkg/types/querybuildertypes/querybuildertypesv5/req.go[R281-299]](https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-16818cff9136ae965e63d1fe769aa177da55dbc47e0ad5eb0e4319af684a65bcR281-R299)</code>
>
>```diff
>+ for _, query := range r.CompositeQuery.Queries {
>+ switch spec := query.Spec.(type) {
>+ case QueryBuilderQuery[TraceAggregation]:
>+ if len(spec.Order) > 0 {
>+ return true
>+ }
>+ case QueryBuilderQuery[LogAggregation]:
>+ if len(spec.Order) > 0 {
>+ return true
>+ }
>+ case QueryBuilderQuery[MetricAggregation]:
>+ if len(spec.Order) > 0 {
>+ return true
>+ }
>+ case QueryBuilderFormula:
>+ if len(spec.Order) > 0 {
>+ return true
>+ }
>+ }
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>Trace operators define an <b><i>Order</i></b> field and use it in the scalar execution and post-processing path,
>while the <b><i>HasOrderSpecified</i></b> switch checks only the other builder-query types and formulas. Because
>it has no <b><i>QueryBuilderTraceOperator</i></b> case, it returns false, enabling the table formatter's default
>descending first-aggregation sort despite the trace operator's explicit order.
></pre>
>
> <code>[pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go[37-59]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go/#L37-L59)</code>
> <code>[pkg/querier/querier.go[333-348]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/querier.go/#L333-L348)</code>
> <code>[pkg/querier/postprocess.go[220-237]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L220-L237)</code>
> <code>[pkg/types/querybuildertypes/querybuildertypesv5/req.go[281-299]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/types/querybuildertypes/querybuildertypesv5/req.go/#L281-L299)</code>
> <code>[pkg/querier/postprocess.go[590-614]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L590-L614)</code>
> <code>[pkg/querier/postprocess.go[845-848]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L845-L848)</code>
> <code>[pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go[37-50]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go/#L37-L50)</code>
> <code>[pkg/querier/postprocess.go[220-229]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L220-L229)</code>
> <code>[pkg/types/querybuildertypes/querybuildertypesv5/req.go[279-301]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/types/querybuildertypes/querybuildertypesv5/req.go/#L279-L301)</code>
> <code>[pkg/querier/postprocess.go[729-732]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L729-L732)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>`HasOrderSpecified` does not inspect `QueryBuilderTraceOperator.Order`, causing scalar trace-operator table formatting to overwrite explicitly requested row ordering with its default descending first-aggregation sort.
>
>## Fix Focus Areas
>- pkg/types/querybuildertypes/querybuildertypesv5/req.go[279-302]
>- pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go[37-59]
>- pkg/querier/postprocess.go[220-237]
>
>## Recommended Fix
>Add a `QueryBuilderTraceOperator` case to `HasOrderSpecified` that returns true when the trace-operator query is enabled and its `Order` slice is non-empty. Add coverage for scalar trace-operator table output proving that both ascending and descending explicit orders are retained.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<br/>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
<details>
<summary> 3. Disabled queries change visible table order <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>HasOrderSpecified</i></b> scans every query for a non-empty <b><i>Order</i></b> without checking <b><i>Disabled</i></b>, while
><b><i>formatScalarResultsAsTable</i></b> uses that request-wide result after <b><i>filterDisabledQueries</i></b> has removed
>disabled results. When a disabled ordered query accompanies enabled unordered scalar results, the
>formatter skips its default descending sort and preserves backend insertion order, so toggling an
>otherwise invisible query changes the table returned to users.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[pkg/types/querybuildertypes/querybuildertypesv5/req.go[R281-285]](https://github.com/drape-io/crbench-qodo-2026-09/pull/77/files#diff-16818cff9136ae965e63d1fe769aa177da55dbc47e0ad5eb0e4319af684a65bcR281-R285)</code>
>
>```diff
>+ for _, query := range r.CompositeQuery.Queries {
>+ switch spec := query.Spec.(type) {
>+ case QueryBuilderQuery[TraceAggregation]:
>+ if len(spec.Order) > 0 {
>+ return true
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>Every supported query type carries disabled state, but <b><i>HasOrderSpecified</i></b> checks only whether its
>order is non-empty. The post-processing pipeline filters disabled results before invoking the scalar
>table formatter, while the request-wide order flag directly controls whether the final table
>receives its default sort, allowing an order from a result absent from the response to determine the
>ordering of visible rows.
></pre>
>
> <code>[pkg/querier/postprocess.go[83-104]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L83-L104)</code>
> <code>[pkg/querier/postprocess.go[568-581]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L568-L581)</code>
> <code>[pkg/types/querybuildertypes/querybuildertypesv5/req.go[279-301]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/types/querybuildertypes/querybuildertypesv5/req.go/#L279-L301)</code>
> <code>[pkg/querier/postprocess.go[845-848]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L845-L848)</code>
> <code>[pkg/querier/postprocess.go[584-614]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L584-L614)</code>
> <code>[pkg/querier/postprocess.go[839-848]](https://github.com/drape-io/crbench-qodo-2026-09/blob/16e4fede56b77cae1dd4f39870d69de77439c31c/pkg/querier/postprocess.go/#L839-L848)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>`HasOrderSpecified` treats disabled queries as active ordering instructions even though their results are filtered out before scalar table formatting. Consequently, an ordered disabled query can suppress the default descending sort for enabled unordered results.
>
>## Fix Focus Areas
>- pkg/types/querybuildertypes/querybuildertypesv5/req.go[279-302]
>- pkg/querier/postprocess.go[83-104]
>- pkg/querier/postprocess.go[568-591]
>
>## Recommended Fix
>Update order detection to ignore disabled builder queries, formulas, and trace operators. Check each supported query type's `Disabled` field before considering its `Order`, so sorting depends only on results that can reach the response. Add a test with an ordered disabled query and an unordered enabled query, and verify that the enabled scalar table retains its default descending sort.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-context:start -->
<details><summary><strong>Context sources</strong></summary>
<div>Review mode: <code>🧠 Deep</code>: This is a bug-dense behavioral change spanning querier production logic, a public request helper, and extensive independent integration-test paths, with 48 hunks and many subtle ordering/aggregation cases.</div>
<!-- qodo-context:end -->
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:start -->
<details>
<summary><strong>Tip of the day</strong></summary>
<br/>
<pre>💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper</pre>
<a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:end -->
<!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/16e4fede56b77cae1dd4f39870d69de77439c31c -->
<a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>