Skip to content

OncoPrint: sort by case list order with a user-defined case list (ONC-SO-3) - #468

Merged
alisman merged 2 commits into
masterfrom
session/onc-case-list-order
Nov 19, 2026
Merged

alisman merged 2 commits into
masterfrom
session/onc-case-list-order

Conversation

@alisman

@alisman alisman commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

OncoPrint › sort gets the portal's case list order (ONC-SO-3): with a user-defined case list, the columns in the order its ids were typed (ResultsViewOncoprint sortOrder 1776-1800, ResultsViewPageStore givenSampleOrder 2960-2989). As in the portal (caseListSortPossible, OncoprintControls 795-815), the option is always listed and disabled unless the query uses a user-defined list.

  • Stored order. A typed list (POST /api/id-sets, lib/id-set-import.ts) now keeps each study's ids in the order given, once each; it used to sort them. Other sets (a lock's, from a query) stay sorted (tidyIdSet(m, ordered), moved from lib/id-set-store.ts to the pure lib/id-sets.ts). The query dialog's User-defined Case List (Query page: genomic profiles and case set beside the gene query #167) saves through it, so typed order survives, and "Modify query" reads the list back in that order. An unowned typed list is now stored by its ids and their order, so the same ids in another order are another set.
  • The order. lib/oncoprint-case-list.ts:
    • caseListOf takes the first sampleList / patientList clause of the cohort's all, from a stored set or from inline ids.
    • caseListRanks gives each column's place:
      • A sample column takes its own place.
      • A patient column takes its first listed sample's place (the portal's uniq of the samples' patients).
      • With a patient list, a sample column takes its patient's place.
      • Columns the list doesn't reach go last, in either direction.
  • The sort key. It's "caseList" in the engine (lib/oncoprint-assemble.ts, Python assemble_contract(case_list_rank=…)).
    • Without a list it's refused, with the reason.
    • With one, conventions.caseList says the order is on offer, and the figure enables the option.
    • Like a clustering, the engine applies it; the browser can't, since the contract carries no list. So choosing it re-runs the view (isEngineSortKey, dataPart).
  • Server SVG. It now carries the cohort definition beside its compiled SQL (lib/views/oncoprint/run.ts), so the order works there too.
  • Reference. lib/dsl-reference.ts documents the "caseList" key and the kept order.

Spec IDs

Covered: ONC-SO-3.
Ours alone:

  • A list spanning several studies keeps each study's typed order, but not how the studies' ids were interleaved. The Results page queries one study.
  • A descending "-caseList" exists through the DSL; the portal's menu has no such choice.

Verification

  • Unit: test/oncoprint-case-list.test.ts CL1-CL8, 15 cases, from the legacy functions above; python/tests/test_case_list_sort.py mirrors CL6-CL7.
  • npm test: 6915 pass, 0 fail (test/id-set-import.test.ts now expects the typed order and has a case for it). npm run test:python: OK.
  • Browser (dev server), coadread_tcga_pan_can_atlas_2018 KRAS TP53, User-defined Case List typed as TCGA-AA-3502-01, TCGA-3L-AA1B-01, TCGA-A6-2671-01, TCGA-AG-3732-01, TCGA-AA-3662-01 (no such sample), TCGA-CM-4743-01, TCGA-4N-A93T-01, TCGA-AZ-6599-01:
    • The stored set reads back in that order.
    • Sort lists "case list order". Choosing it draws TCGA-AA-3502, 3L-AA1B, A6-2671, AG-3732, CM-4743, 4N-A93T, AZ-6599 (the staircase drew 4N-A93T, AA-3502, AZ-6599, …).
    • Without a typed list the option is disabled: "case list order (with a user-defined case list)".
    • No console errors.
  • Planted bugs: scripts/mutants/oncoprint/case-list-order.ts (3: the set saved sorted, a patient at its last sample, unlisted columns first when descending). Each is caught by hand. All 678 sites are found once.

Review fixes (fa0464a)

  • Blocking: a track's Sort a-Z / Z-a, the sort select and a clustering now drop the case-list key (isEngineSortKey in trackSort, selectSort, clusterSort), as the portal's sortByData leaves case-list mode. Before, ["SEX","caseList"] neither re-ran nor re-sorted. Covered by CL9 (5 cases). Browser: case list order, then patient id, re-runs with sort: ["id"] and draws id order.
  • A stored set the request did not read is refused by name (loadedIdSet), not taken for "no list".
  • "caseList" is refused when a federation peer draws some columns, instead of drawing them last.
  • The select shows a DSL-only "-caseList" as "case list order, reversed".
  • npm test: 6920 pass, 0 fail. The planted bugs track-sort-keeps-clustering and cluster-keeps-other-profile follow the moved code; each is still caught by hand. All 678 sites are found once.

Left as they are:

  • A caseList sort with no list in the cohort: Modify query builds a fresh Results link without the page's changes, so the sort doesn't carry over. Only a hand-edited document reaches the engine's refusal, which names the reason (invariant 1).
  • Sets saved before this PR: they read back sorted, and nothing marks them as unordered. Typed lists from before today are few, and re-submitting the query saves the list in typed order.
  • The staircase switches under a case-list sort: they only order the ties (unlisted columns, a patient's samples), as with a clustering.
  • The extra sample-to-patient query: it runs only with a patient-level list over sample columns.

Tracker

PORTAL-PARITY, under Results → OncoPrint, the default view, Sort menu item, tick

- [ ] "Case list order" (ONC-SO-3): the portal offers it only for a query naming sample ids, which no Results query here can yet

as

- [x] "Case list order" with a User-defined Case List: the columns in typed order, a patient at its first listed sample; listed and disabled otherwise, as the portal's (ONC-SO-3) (#468)

and, under Tracks › Clinical (user's decision 2026-11-19, ONC-STM-4: keep ours), replace

  - [ ] The spectrum's Freq differs in Q1 too: coadread_tcga_pan_can_atlas_2018 KRAS NRAS BRAF TP53 APC shows 89.9 % (534 of 594, the mutation profile's `sample_profile` rows: `app/portal/study-known.ts:92`, `lib/explore.ts:1474-1481`), the portal 99.7 %; the five-study list above is not the whole difference (ONC-STM-4, re-measured 2026-11-18) ([01-oncoprint](legacy-spec/parity/01-oncoprint.md))

with

  - Ours alone (user's decision, 2026-11-19): Q1's spectrum Freq is 89.9 % (534 of 594, the samples in the study's mutation profile and its own `_sequenced` list), the portal's 99.7 % (592). The portal reads `sample_derived.sequenced`, which populate_derived_tables.sql sets by bare sample id against every study's `_sequenced` list, so 58 TCGA samples count because a same-named sample is sequenced in another study (ONC-STM-4)

Scorecard 01-oncoprint.md rows:

| ONC-SO-3 | ✅ | C | Sort › "case list order", enabled with a User-defined Case List: typed order, kept by the stored set; a patient at its first listed sample; disabled otherwise, as the portal's (lib/oncoprint-case-list.ts, sort key caseList) (#468) |
| ONC-STM-4 | ✅ | B | Q1, 2026-11-18: every attribute's Freq as the portal's, patient-level ones over samples (#264). Mutation spectrum: ours 89.9 %, the portal's 99.7 %; recorded as Ours alone by the user's decision (2026-11-19): the portal's sample_derived.sequenced matches bare sample ids across studies' _sequenced lists, ours counts the samples the study's mutation profile holds |

Preview

Query dialog → User-defined Case List (a few ids, out of order) → Oncoprint → sort → case list order.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q3ezTZqTUJJDrEaiCKckHz

…-SO-3)

The portal's Sort > "Sort by case list order" (ResultsViewOncoprint sortOrder,
ResultsViewPageStore givenSampleOrder): with a User-defined Case List the columns
follow the typed order; listed and disabled otherwise.

- A typed list (lib/id-set-import.ts) is stored with each study's ids in the order
  given, once each; other sets stay sorted (tidyIdSet in lib/id-sets.ts).
- lib/oncoprint-case-list.ts: the cohort's first sampleList/patientList clause, and
  each column's place (a patient at its first listed sample, a sample column of a
  patient list at its patient's, unlisted columns last either way).
- Sort key "caseList" in the engine and the Python port; refused without a list;
  conventions.caseList says when it is on offer. The engine applies it (as a
  clustering), so choosing it re-runs the view; the server SVG carries the cohort
  definition beside its SQL so it works there too.

Verified: npm test 6915/0, Python OK; coadread KRAS TP53 with an 8-id typed list
(one unmatched) draws the 7 columns in typed order; disabled without a list;
3 planted bugs each caught by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q3ezTZqTUJJDrEaiCKckHz
@vercel

vercel Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
cbiolab-genie Ready Ready Preview Nov 19, 2026 7:23pm UTC
cbiolab-new Ready Ready Preview Nov 19, 2026 7:23pm UTC
cohort-lab Ready Ready Preview Nov 19, 2026 7:23pm UTC

Request Review

* clustering (from values the browser never receives) and the case list order (from the cohort's
* typed list, which the contract does not carry).
*/
export const isEngineSortKey = (k: string): boolean => { const t = k.replace(/^-/, ""); return t.startsWith("cluster:") || t === "caseList"; };

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

trackSort and selectSort still drop only cluster keys (isClusterKey), so a caseList key stays on as a secondary key. After that, sorting by a track does nothing.

The user picks "case list order" (sort = ["caseList"]), then uses a clinical row's "Sort a-Z". trackSort returns ["SEX","caseList"]. dataPart's engine keys are still ["caseList"], so the view doesn't re-run. engineSorted is true (keys.some(isEngineSortKey)), so the browser doesn't re-sort either. The columns stay in case-list order and the new sort is silently ignored. The same happens with selectSort from ["X","caseList"]. In the portal, sortByData leaves case list mode. Fix: have trackSort/selectSort/clusterSort filter with isEngineSortKey instead of isClusterKey.

export const pruneSort = (v: V): V => {
const hidden: string[] = v.hideTracks || [];
const keep = new Set(["genomic", "id", ...AUTO_TRACKS.filter((l) => !hidden.includes(l)), ...(v.clinical || []), ...heatmapLabels(v),
const keep = new Set(["genomic", "id", "caseList", ...AUTO_TRACKS.filter((l) => !hidden.includes(l)), ...(v.clinical || []), ...heatmapLabels(v),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

pruneSort always keeps caseList, but the engine throws when the cohort has no user-defined list. Dropping the list from the query therefore breaks the whole OncoPrint instead of falling back to the default order.

The user sorts by case list order, then uses Modify query to switch to a standard case list (no sampleList/patientList in all). The view's sort still holds "caseList". assembleContract throws "sort: 'caseList' needs a cohort chosen by a user-defined case list" and the figure fails. A cluster key is pruned when its heatmap goes; caseList has no matching prune. The same applies to a saved doc that is edited this way.

Comment thread lib/oncoprint-case-list.ts Outdated
if (!leaf) return null;
const level = leaf.kind === "sampleList" ? "sample" : "patient";
if (typeof leaf.set === "string") {
const s = idSetIfLoaded(leaf.set);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

caseListOf uses idSetIfLoaded and returns null without a word when the set isn't loaded. The cohort is then treated as having no list, which goes against invariant 1 (loud rejection) and gives a misleading error.

A caller builds the contract outside the id-set context (or with the set missing from the store). caseListRank is left undefined and the option shows as disabled "(with a user-defined case list)". A view sorted by "caseList" is refused with "needs a cohort chosen by a user-defined case list", even though the cohort names one. loadedIdSet would raise the specific error, as compiling already does.

Comment thread lib/oncoprint.ts
return { s, cols };
}));
}
per = inStudyOrder([...per, ...await Promise.all([...peers.keys()].map((s) => peerColumns(s, gi)))]);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Columns of federated peer studies never get a case-list rank, so they are always drawn after every listed column, with no caveat.

In a multi-study cohort whose user-defined list names samples in a study served by a peer, rankByCaseList runs only for local studies. peerColumns columns aren't in caseListRank, so the comparator puts them last as "unlisted" even though the list names them. The order is silently wrong for those columns. Invariant 1 asks for loud rejection rather than an approximation.

// The staircase switches re-sort here too: the engine's order was drawn with its own.
const keys = sortKeys.length ? sortKeys : data.conventions.sort;
const engineSorted = keys.some((k) => k.replace(/^-/, "").startsWith("cluster:"));
const engineSorted = keys.some(isEngineSortKey);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

With a caseList sort, the staircase switches (driver / mutation type / ignore VUS) no longer change anything. They are FIGURE_KEYS, so they don't re-run the view, and engineSorted stops the browser re-sort.

Sorted by case list order, the unlisted columns (and the patients tied under one listed patient) are ordered by the engine's genomic tie-break. Toggling "driver" or "ignore VUS" neither re-runs the view nor re-sorts in the browser, so those columns keep the staircase drawn with the old switches. The comment above says the switches re-sort here too.

Comment thread lib/id-set-import.ts
const duplicates = ids.length - new Set(ids).size;
const set = await saveIdSet(principal, {
name: String(b.name ?? ""), level: level as IdSetLevel, perStudy,
name: String(b.name ?? ""), level: level as IdSetLevel, perStudy, ordered: true,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sets stored before this change were saved sorted, but they still turn on "case list order", which then draws alphabetical order as if it were the typed order.

Take a User-defined Case List saved before this PR (its ids_gz is sorted). Opening the query offers "case list order" enabled (conventions.caseList is set whenever a list leaf exists). Choosing it draws the ids alphabetically, not in the order typed, and nothing says the stored set predates ordering.

Comment thread lib/oncoprint.ts
if (!list) return;
let patientOf: Map<string, string> | undefined;
if (unit === "sample" && list.level === "patient") {
const r = await lqRows("oncoprint:caseListPatients", "SELECT DISTINCT sid, pid FROM (\n" + rows + "\n)", s);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

For sample columns with a patient list, every study in every group runs an extra oncoprint:caseListPatients query just to map each sample to its patient. The column query it follows already reads the same rows.

columnRowsSql already does SELECT DISTINCT over the same (pid, sid) rows. In sample mode it could also select pid (or the ColumnRows could carry it), which would avoid a second ClickHouse round trip per study per group over the full cohort subquery.

<option value={sortKeys[0]}>{sortKeys[0]}</option>}
<option value="genomic">genomic staircase</option>
<option value="id">{data.unit} id</option>
<option value="caseList" disabled={!data.conventions.caseList}>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The Sort select has no option for "-caseList", which the DSL accepts, so a view sorted descending by case list shows a value the select can't display.

A doc with sort ["-caseList"] makes sortKeys[0] "-caseList". No option matches, so the select shows a blank or the first option, and the user can't tell how the figure is sorted. The cluster key has a fallback <option value={sortKeys[0]}> for the same case.

@alisman

alisman commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Review verdict: changes

Blocking:

  • trackSort / selectSort (app/_oncoprint/track-edits.ts) still drop only cluster keys, so caseList stays on as a secondary key. After "case list order", a track's "Sort a-Z" gives ["SEX","caseList"]: dataPart's engine keys don't change (no re-run), and engineSorted is true (no browser re-sort), so the new sort is silently ignored. The same happens with the select from ["X","caseList"]. In the portal, sorting by data leaves case-list mode. Drop engine keys there (isEngineSortKey), and add a test.

Checked and fine:

  • The option is offered only with a typed list, as legacy's caseListSortPossible.
  • Typed order is kept by createIdSet, with duplicates at their first occurrence and unmatched ids dropped.
  • A patient is placed at its first listed sample.
  • No migration: old sets load unchanged, still sorted.
  • Locks and other sets stay sorted.
  • The order survives the URL/doc round trip and the server SVG.
  • The tests and planted bugs cover the order.

Non-blocking items are inline (nits): pruneSort keeping caseList when the cohort loses its list (the engine refuses loudly), federated peer columns unranked, the staircase switches being inert under an engine sort (as with clustering already), pre-existing sets offering alphabetical order, the extra patient-map query, and no select option for -caseList.

CI: planted-bugs and gate-e2e were still pending at review time.

- trackSort, selectSort and clusterSort drop every engine sort key
  (isEngineSortKey), so a track's Sort a-Z, the sort select or a clustering
  ends the case list order as the portal's sortByData does; before, caseList
  stayed as a second key, the view did not re-run and the new sort was ignored.
- caseListOf reads a stored set with loadedIdSet: a set the request did not
  read is refused by name instead of being taken for no list.
- sort "caseList" is refused when a federation peer draws some columns.
- The sort select shows "-caseList" (DSL only) as "case list order, reversed".
- Planted bugs track-sort-keeps-clustering and cluster-keeps-other-profile
  follow the moved code; each still caught by hand.

Verified: npm test 6920/0; test/oncoprint-case-list.test.ts CL9 (5 cases) and
the refusal case; browser: case list order, then patient id, re-runs with
sort ["id"] and draws id order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q3ezTZqTUJJDrEaiCKckHz
@alisman

alisman commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in fa0464a.

  • Blocking: trackSort, selectSort and clusterSort (app/_oncoprint/track-edits.ts) now drop engine keys with isEngineSortKey, so a track's Sort a-Z / Z-a, the sort select and a clustering all leave case-list mode, as the portal's sortByData does. Sort a-Z after case list order now gives ["SEX"]. New tests: CL9 in test/oncoprint-case-list.test.ts (5 cases). In the browser, choosing case list order and then patient id re-runs with sort: ["id"] and draws id order.
  • Also fixed:
    • A stored set the request did not read is refused by name, not taken for no list.
    • "caseList" is refused when a federation peer draws columns.
    • A DSL-only "-caseList" shows in the select as "case list order, reversed".
  • The nits left as they are have reasons in the description under "Left as they are": pruneSort after the list is gone, pre-PR sets read back sorted, staircase switches, the extra query.

npm test 6920/0. The two planted bugs that followed the moved code are still caught by hand.

@alisman

alisman commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Re-review: pass. fa0464a fixes the blocking finding. trackSort and selectSort drop every engine sort key (isEngineSortKey), so a track's Sort a-Z / Z-a, a pick in the sort select, or a clustering now leaves case-list mode, as the portal's sortByData does. "Don't sort by this" drops only the track's own key. CL9 pins each path, and the two planted bugs are re-pointed at the new lines. Two nits are also addressed:

  • A stored set this request didn't read is refused rather than treated as "no list".
  • A case-list sort over federated peer studies is refused with a reason, rather than leaving their columns unplaced.

The sort select also offers "case list order, reversed" when that's the current key.

@alisman
alisman added this pull request to the merge queue Nov 19, 2026
Merged via the queue into master with commit a2a8097 Nov 19, 2026
12 checks passed
@alisman
alisman deleted the session/onc-case-list-order branch November 19, 2026 20:06

This branch was successfully deployed

1 active deployment
Preview – cohort-lab — fa0464a2 Deployed Nov 19, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant