Repository navigation
Sort task priority by urgency rank instead of alphabetically - #2731
Conversation
…2692) Sorting by `task.priority` was a plain lexicographic sort on the stored string, so ascending order was `high, highest, low, lowest, medium`. Introduces an explicit rank (highest=0 … lowest=4) and sorts on that. User-defined priorities share a single rank one past the core scale, so they sort after every core value, and tie-break on the value string to keep the ordering total. The rank is applied at three sites that must agree: - `TaskPriority::rank()` — the one definition the others derive from. - `QueryService::resolve_order_field` — a CASE in the ORDER BY. Kept separate from `resolve_field`, whose output must stay byte-identical to the expression `idx_task_priority` is built on; wrapping the CASE in there would have traded a working filter index for a working sort. Pinned to `rank()` by `test_sql_priority_rank_matches_enum_rank`. - `compare_priority_values` — the in-Rust re-sort, which runs after the SQL and has the final say. A SQL-only fix would be silently undone here, but SQL still decides which rows survive a LIMIT, so both matter. Scoped to `target_type == "task"` on both paths. A wildcard query resolves the namespace per row, so ranking there would impose the task scale on every type's priority and rank a non-task NULL as a user value; `sort_nodes` now takes the query's target_type so the Rust condition mirrors the SQL one exactly. `project.priority` is a separate scale. The frontend sorts saved queries client-side rather than delegating to QueryService (`NodeQuery` carries no sorting field), so it had the same alphabetical bug in a second implementation. `applySorting` now takes the targetType and ranks priority to match. Note this is a second copy of the rank table with no test spanning both languages — the comments on each side say so. Delegating sorting to the backend would remove the duplication and is worth doing separately. Restores "and sorting" to task.priority's schema description, which #2651 removed because nothing implemented it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Pragmatic Code Review — PR #2731Review Type: Initial Review Scope: Requirements Check (issue #2692)
📝 Scope discipline is good: Verification of the design claimsI checked the load-bearing claims rather than taking them on faith:
Code Review Findings🔴 Critical: SQL ranks an absent priority as a user-defined value; Rust sorts it first — the two layers disagree📁
The doc comment on
That is true of a bare Descending diverges too: SQL gives Why this is Critical rather than Important: the PR's own reasoning establishes that a SQL/Rust disagreement is a correctness bug precisely because Why the test suite misses it: Recommendation — make the CASE handle NULL explicitly, e.g. a searched CASE: let rank = format!(
"CASE WHEN {resolved} IS NULL THEN -1 \
WHEN {resolved} = 'highest' THEN {} ... ELSE {} END",
...
);( Engineering Principle: when one invariant is enforced in two languages, every branch of it must be tested at the layer that actually decides the outcome. Testing an agreement claim only in the configuration where one layer overwrites the other tests nothing about the agreement. Relatedly: SQL three-valued logic means NULL silently fails every 🟡 Important: a non-string priority also diverges between SQL and Rust📁 For a non-string JSON value (e.g. The fallback itself is a defensible choice ("a non-string value cannot be a priority"), and the practical blast radius is far smaller than the NULL case — schema enum validation should keep non-strings out. But the doc comment presents the fallback as safe without noting that it is not what SQL does. If you fix the NULL case with a searched CASE, consider folding this in ( Engineering Principle: a comment that asserts an invariant is a claim under test. An inaccurate one is worse than none, because it stops the next reader from checking. 🟡 Important:
|
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-review verdicts on your own PR).
One 🔴 Critical blocker: the simple CASE in resolve_order_field never matches NULL (SQL NULL = 'highest' is NULL, not true), so an absent task.priority falls to ELSE and is ranked as a user-defined value (5) in SQL, while compare_priority_values sorts it first in Rust. Verified against SQLite with the exact generated expression. Because LIMIT is applied in SQL before the in-Rust re-sort, a limited ascending query silently drops unprioritized tasks that should have led the results — and the default limit is 50. The existing absent-priority test passes no LIMIT, so the Rust pass masks it.
Fix: searched CASE with an explicit IS NULL arm, plus a LIMIT variant of that test.
Everything else is strong — resolve_field and idx_task_priority are provably untouched, the task-only gating is consistent across all three sites, scope discipline vs #2693/#2694 is exact, and test quality is above average. Full findings in the review comment above.
The SQL used a *simple* `CASE <expr> WHEN ...`, which compares with `=`. `NULL = 'highest'` is NULL rather than true, so an absent priority matched no arm and fell to `ELSE` — ranked as a user-defined value, at the opposite end of the scale from where `compare_priority_values` put it. Because LIMIT is applied in SQL before the in-Rust re-sort, a limited ascending query silently dropped unprioritized tasks that should have come back first, and the default limit of 50 makes limited queries the common case. Confirmed against SQLite before fixing: the generated expression returned `highest, low` where the Rust comparator would have returned the unprioritized task first. This is the exact failure class the three-site design exists to prevent, and the doc comment asserting the two agreed on NULL was simply wrong. - Searched CASE with an explicit `IS NULL` arm ranking `TaskPriority::ABSENT_RANK` (-1), pinned by `test_sql_priority_rank_matches_enum_rank`. - `compare_priority_values` now ranks every JSON shape the SQL does: absent/Null → ABSENT_RANK, string → its rank, anything else → USER_RANK tie-broken on the rendered form. Previously a non-string fell through to the generic comparison and sorted among values, while SQL put it in the ELSE block — the same divergence, smaller blast radius. - Replaced `unwrap_or_default()` on the infallible `FromStr` with an explicit `User(_)` fallback. Default is Medium, so a future error arm would have silently ranked an unparseable value mid-scale — the same plausible-looking wrong answer this PR set out to fix. - New test covers absent priority *with* a LIMIT, the combination the existing two each missed: without a LIMIT the Rust pass masks SQL entirely, and the other LIMIT test uses only core values, where the layers agree. Verified failing against the old simple CASE. - Documented the sort-path index cost the CASE introduces; equality filters still hit `idx_task_priority`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Address Review —
|
Pragmatic Code Review — PR #2731 (Re-Review)Review Type: Re-Review Verified locally (not taken on faith):
Previous Review Summary
Verification of each prior finding✅ 🔴 Critical — NULL ranked as user-defined in SQL — FIXED, and verified📁 The searched Two things worth calling out, because both are load-bearing and neither is obvious:
Verified the test is not vacuous. I neutered only the new arm ( Both the behavioural test and the format pin fail, and the other four priority tests still pass — confirming the earlier diagnosis that they were blind to this case. The test design is right: ✅ 🟡 Non-string priority divergence — FIXED for rank; see the new Nit for the tie-break📁
The residual tie-break mismatch within the rank-5 block is unreachable in practice — see Nitpicks. ✅ 🟡
|
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-review verdicts on your own PR).
Scope: 9f7ac0c2 only. 4 of 4 actionable findings addressed; 1 🟢 skipped with a justification I accept; 0 outstanding; 1 new 🟢 Nit that should not gate.
The 🔴 blocker is genuinely fixed. I verified independently rather than taking the claim on faith:
- Ran the generated searched
CASEagainst SQLite over all nine input classes. Absent and JSONnullboth rank -1 (json_extracton a JSON null yields SQL NULL, so oneIS NULLarm covers the pair the Rustkey()collapses). DESC is symmetric:blocker, lowest, highest, none. - Neutered only the new
IS NULLarm and re-ran:test_sort_by_priority_with_limit_keeps_absent_priority_firstandtest_sql_priority_rank_matches_enum_rankboth FAIL, while the four pre-existing priority tests still pass — confirming the test is non-vacuous, the format pin still bites after the= 'x' THEN nchange, and the previously-inferred blind spot was real. bun run rust:test:lib→ 1483 passed, 0 failed. Clippy-D warningsclean.
ABSENT_RANK is the right shape for the fix: one shared constant pinned to the SQL by a test, rather than a -1 literal repeated in two languages. The i8/u8 → i16 widening is lossless and order-preserving. The 🟡 non-string finding was fixed at the root via an exhaustive match on serde_json::Value rather than patched at the symptom.
Remaining Nit: the rank-5 tie-break still diverges for non-string JSON (Rust keys on to_string(), SQLite orders integers before text). Unreachable — task.priority is an enum field and validate_node_with_fields rejects any non-string on every write — so the code is correct as written; only the doc comment's "agree on every input" is broader than what holds. Worth one line whenever the file is next touched, given the last 🔴 was found by disbelieving a comment of exactly that kind.
Full findings in the review comment above.
The comment claimed this pass and the SQL agree "on every input, not just the well-formed ones". True of the rank, and of the tie-break for strings, but not of the tie-break for non-strings: this keys on `to_string()` while SQLite orders integers before text. Left the code alone. `task.priority` is an enum field and `validate_node_with_fields` rejects a non-null non-string on every write path, so no such row exists to sort — the branch is unreachable, not merely unlikely. Verified that validation directly rather than assuming it. Comment-only, because the bug the previous commit fixed hid behind a comment that claimed more than it delivered. An overclaiming comment is what makes the next reader stop checking. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Address Re-Review —
|
Closes #2692.
Sorting by
task.prioritywas a plain lexicographic sort on the stored string, so ascending order washigh, highest, low, lowest, medium. This introduces an explicit urgency rank (highest=0 …lowest=4) and sorts on that.Where the rank lives
#2692 left this open. The deciding constraint turned out to be an index:
db/schema.rsbuildsidx_task_priorityon the exact expressionjson_extract(properties, '$.task.priority'), andtest_resolve_field_matches_indexed_expressionasserts byte-for-byte equality against it. Wrapping the CASE insideresolve_field— the obvious fix — would have broken that test and silently traded a working filter index for a working sort.So the rank is applied at three sites instead, and all three must agree:
TaskPriority::rank()QueryService::resolve_order_fieldCASE;resolve_fieldis left byte-identical to the indexcompare_priority_valuesA SQL-only fix would have been silently undone by the Rust pass; a Rust-only fix would still have been wrong under
LIMIT, which SQL applies before that pass. Hence both, withtest_sql_priority_rank_matches_enum_rankpinning the CASE torank().User-defined priorities
All share one rank past the core scale, so they sort after every core value, and tie-break on the value string to keep the ordering total. Note these are only reachable once added to the schema's
user_values— enum validation rejects an arbitrary priority string outright, which the test exercises viahandle_update_schemarather than faking.A wildcard bug caught along the way
The first version also ranked
target_type: "*". That was wrong: a wildcard query resolves the namespace per row, so it would impose the task scale on every type's priority and rank a non-taskNULLas a user value — while the Rust comparator only ranked when both nodes were tasks. The two layers would disagree, and which one won would depend on whether aLIMITwas present.Both paths are now scoped to
target_type == "task", andsort_nodestakes the query's target type so the Rust condition mirrors the SQL one exactly.test_wildcard_priority_sort_does_not_apply_task_rankcovers it (written failing first).The frontend had the same bug independently
NodeQueryhas nosortingfield at all — saved queries are fetched by type and sorted client-side withlocaleCompare, so the frontend never delegates toQueryServiceand carried the identical alphabetical bug in a second implementation.applySortingnow takes the target type and ranks priority to match.This adds a third copy of the rank table, and unlike the two Rust copies it is pinned by nothing — no test spans both languages, so a one-sided edit would produce a silent disagreement between what the backend returns and what a saved query displays. Comments on both sides record the coupling. #2727 tracks removing the duplication by delegating sorting to the backend, which is the real fix.
Out of scope
project.priority— Decide whether project.priority should match task.priority's 5-level scale #2694 owns whether its scale changes at all;test_resolve_order_field_leaves_non_priority_fields_aloneasserts the task rank does not leak onto itTesting
query-node-model.test.tspassquality:fixclean, including clippy-D warningsDocs
nodespace-docsarchitecture/data-layer.mdnow records the rank semantics, pushed to main separately. It matters there becausesearch_nodesexposessortingto agents — a model asking for a superlative viasorting+limit: 1depends on this ordering.Also restores "and sorting" to
task.priority's schema description, which #2651 deliberately removed because nothing implemented it.🤖 Generated with Claude Code