Repository navigation
Refuse clinical comparisons of attributes stored at different levels; guard the study view against cbioportal#12509 - #432
Conversation
… guard the study view's per-sample counting (cBioPortal/cbioportal#12509) An attribute stored per patient in one study and per sample in another (nsclc_tracerx_2017 vs luad_cas_2020 HISTOLOGY) was pooled by the clinical comparison view: each study counted in its own unit and a cell added them, so "EGFR: MUT" read 66 "patients" = 15 tracerx patients + 51 luad_cas samples, and the chi-squared ran on the mix. The view now refuses such an attribute, naming the studies at each level, as it already refuses a type disagreement. Only answers holding values say which level they read (an empty categorical answer carries the default level), and a single-study view is never refused on level. The row's level is the one its values were read at. The study view (Explore) already counts these attributes per selected sample (STS-MD-5): a patient's value lifted to one row per sample, then filtered by sample id, so it does not have #12509's overcount. Nothing checked that against data: the existing test matched SQL text. New warehouse check scripts/check-conflicting-levels.ts (gate phase "study view conflicting levels") runs Explore on the issue's repro and on selections that leave samples of multi-sample patients out, for HISTOLOGY (categorical) and histiocytosis_cobi_msk_2019 + blca_dfarber_mskcc_2014 TOTAL_MUTATIONS (numeric bins), against its own SQL. Verified: tests written from a spec table by a separate agent; the comparison ones fail on master (A1, A2, A7, A9) and pass now; 47/47 in test/view-clinical.test.ts. The warehouse check passes (16 checks). Planted bugs, each caught: pooling the levels (4 unit failures), reading an empty answer's default level (1), and the legacy filter-by-patient in Explore, which reproduces the issue's Invasive adenocarcinoma 4 for one selected sample (4 warehouse failures). Snapshot two-studies-four-views changes only by the view's note. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q3ezTXrjJkt45AoXSDct6U
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
| const studiesAt = (lvl: string) => [...new Set(vNames.flatMap((n) => cohorts[n].studies | ||
| .filter((st) => { const x = pick(n, st); return !!x && x.per === lvl && (x.kind === "cat" ? !!x.values?.length : !!x.n); })))].sort(); | ||
| const atPatient = studiesAt("patient"), atSample = studiesAt("sample"); | ||
| if (vStudies.length > 1 && atPatient.length && atSample.length) { |
There was a problem hiding this comment.
The same pooling is still in mergedDistribution (lib/analysis.ts:171-191). It feeds splitBy and says it follows "as the clinical view's cross-study comparison does". It refuses only a type disagreement, takes per from perStudyStats[0], and adds each study's values together. So a splitBy on HISTOLOGY over tracerx + luad_cas still adds patients to samples when it sizes the arms against minCount. The fix covers one caller of attributeStats and leaves the other.
| .filter((st) => { const x = pick(n, st); return !!x && x.per === lvl && (x.kind === "cat" ? !!x.values?.length : !!x.n); })))].sort(); | ||
| const atPatient = studiesAt("patient"), atSample = studiesAt("sample"); | ||
| if (vStudies.length > 1 && atPatient.length && atSample.length) { | ||
| rows.push({ attribute, per: all[0].per, kind: kinds[0], cells: [], |
There was a problem hiding this comment.
This departs from legacy, and the PR text says so. The PR body says the portal's Comparison page counts such an attribute per sample, and this PR refuses it instead. /home/ubuntu/projects/CLAUDE.md, standing user rules: "Product questions in cBioLab parity work: follow what legacy cBioPortal does." A deliberate deviation is the user's call. Today, an attribute that was tested before (for example HISTOLOGY over tracerx + luad_cas) disappears from the results and from the q-values. This needs the user's sign-off, or the per-sample lifting used in the study view.
| // A study storing it per patient counts patients and one storing it per sample counts samples; | ||
| // pooled, a cell would add the two. Only answers holding values say which level they read: an | ||
| // empty categorical answer carries the default level, not the study's. | ||
| const studiesAt = (lvl: string) => [...new Set(vNames.flatMap((n) => cohorts[n].studies |
There was a problem hiding this comment.
The level is guessed from the data, not read from the metadata. Each study's level is inferred from its answers' per. The values.length / n filter is there only because attributeStats fills in per: "patient" for an empty categorical answer (lib/federation.ts:1840). attributeStats already queries clinical_attribute_meta for the datatype. It could also return the declared patient_attribute, as conflictingLevels in lib/explore.ts:971 does. Then every answer, empty or not, would carry the study's real level, and this filter (plus the second mutant that guards it) would not be needed.
| atSample.join(", ") + "); its counts would mix patients with samples" }); | ||
| continue; | ||
| } | ||
| const kind = kinds[0], per = atSample.length ? "sample" as const : atPatient.length ? "patient" as const : all[0].per; |
There was a problem hiding this comment.
A study holding the attribute at both levels is not caught. clinicalCountsSql / clinicalMomentsSql group by (a, per). For a categorical attribute, attributeStats then merges both levels' values into one answer and labels it with the first row's per (federation.ts:1833-1836). For a numeric one it emits two AttrStats, and pick() keeps only the first. So a study storing an attribute partly per patient and partly per sample still has patients and samples added in a cell, or silently loses one level's values. The new check sees one per per answer, so it can't refuse this. The vStudies.length > 1 guard also means a single study is never checked.
| assert.deepEqual(r.cells, []); | ||
| }); | ||
|
|
||
| test("A8: a single study is never refused on level", async () => { |
There was a problem hiding this comment.
A8 locks in a mixed-unit test. In one study, cohort A's answer is per patient and cohort B's is per sample, both with values. The test expects the row to be tested (p != null). per then comes out as sample, so the chi-squared compares patient counts with sample counts, and the row calls them samples. A single-study mismatch can only come from mixed-level data (see the comment on run.ts:96). In that case it should be refused just like the cross-study one, not asserted to be tested.
| .filter((st) => { const x = pick(n, st); return !!x && x.per === lvl && (x.kind === "cat" ? !!x.values?.length : !!x.n); })))].sort(); | ||
| const atPatient = studiesAt("patient"), atSample = studiesAt("sample"); | ||
| if (vStudies.length > 1 && atPatient.length && atSample.length) { | ||
| rows.push({ attribute, per: all[0].per, kind: kinds[0], cells: [], |
There was a problem hiding this comment.
The refused row can report the wrong level. It uses per: all[0].per. If all[0] is an empty categorical answer, that is the default patient, not a real level, and it flows into method.attributes[].per. Reporting per here is misleading for a row refused for having two levels anyway. Use the level of the first study that holds values, or leave it out.
| const studiesAt = (lvl: string) => [...new Set(vNames.flatMap((n) => cohorts[n].studies | ||
| .filter((st) => { const x = pick(n, st); return !!x && x.per === lvl && (x.kind === "cat" ? !!x.values?.length : !!x.n); })))].sort(); | ||
| const atPatient = studiesAt("patient"), atSample = studiesAt("sample"); | ||
| if (vStudies.length > 1 && atPatient.length && atSample.length) { |
There was a problem hiding this comment.
Hidden attributes are refused without a trace. Hidden attributes (the survival _MONTHS/_STATUS pairs, AGE_LAST_FU_YEARS, BIRTH_YEAR) also go through this refusal. They are not listed, and untested counts only the shown rows. So a level-mismatched OS_MONTHS drops out of the BH correction with nothing in the note. The q-values of the listed attributes change, and nothing visible explains why.
| "WITH sel AS (" + selectedSql(studies, samples) + "),\n" + | ||
| " c AS (SELECT type, sample_unique_id, patient_unique_id, attribute_value FROM " + db + ".clinical_data_derived\n" + | ||
| " WHERE cancer_study_identifier IN (" + studies.map(q).join(", ") + ") AND attribute_name = " + q(attribute) + "\n" + | ||
| " AND lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan'))\n" + |
There was a problem hiding this comment.
The ground-truth SQL copies the missing-value list instead of importing it. ('', 'na', 'n/a', 'nan') is a copy of CLINICAL_MISSING_VALUES (lib/event-names.ts:89). If the product list changes (say, unknown is added), the truth and the code under test drift apart and B3/B4 fail for no real reason. This is a definition of 'missing', not the logic under test, so building the SQL list from the constant keeps the check independent of the code.
| "SELECT sample_stable_id AS s, patient_stable_id AS p, row_number() OVER (PARTITION BY patient_stable_id ORDER BY sample_stable_id) AS k,\n" + | ||
| " count() OVER (PARTITION BY patient_stable_id) AS m\n" + | ||
| "FROM " + db + ".sample_derived WHERE cancer_study_identifier = " + q(study) + " ORDER BY p, s", conn!); | ||
| const multi = [...new Set(r.data.filter((x) => Number(x.m) > 2).map((x) => x.p))].slice(0, onePer); |
There was a problem hiding this comment.
The selection can come up short without anyone noticing. m > 2 keeps only patients with 3 or more samples, and .slice(0, onePer) takes as many as exist. If a study has fewer than 16 (tracerx) or 8 (histiocytosis) such patients, B3/B6 test a smaller selection than their labels claim ("16 multi-sample tracerx patients"), and still pass. Assert multi.length === onePer, or put the real count in the label.
| async function truthCat(studies: string[], attribute: string, samples?: string[]) { | ||
| const r = await chQuery<{ f: string; n: string }>( | ||
| "SELECT lowerUTF8(trimBoth(v)) AS f, uniqExact(sid) AS n FROM (" + valuesSql(studies, attribute, samples) + ") GROUP BY f", conn!); | ||
| const withValue = Number((await chQuery<{ n: string }>( |
There was a problem hiding this comment.
truthCat scans the warehouse twice. It runs valuesSql once grouped by value and again for uniqExact(sid). One query returns both: SELECT f, uniqExact(sid) ... GROUP BY f WITH TOTALS (the totals row's uniqExact is the distinct-sample count). Alternatively, run the two queries with Promise.all, since they are independent.
|
Review verdict: needs-user (product question, not a code defect) The question for the user: the clinical comparison view now refuses an attribute stored per patient in one study and per sample in another. Legacy cBioPortal's Comparison page counts it per sample instead:
So refusing is a deliberate deviation from legacy. Keep the refusal as built, or count per sample like the portal? Either way, refusing is strictly better than master's silent pooling (patients + samples in one cell, which broke invariant 1). Parked in NEEDS-USER.md. Apart from that question, the code is sound. No blocking findings.
Non-blocking (see inline):
CI at review time: lint, coverage, gate-local green; gate-warehouse and gate-e2e still pending. |
… metadata; name hidden attributes not tested From review of #432. - One rule, attributeLevels (lib/federation.ts), for every pooling of attributeStats answers: the clinical comparison and splitBy's mergedDistribution, which still added patients to samples when sizing arms (tracerx + luad_cas HISTOLOGY: "cannot split by 'HISTOLOGY': ... store it at different levels"). - A study whose answers hold values at both levels is refused too ("s1 stores it both per patient and per sample"), single-study views included; the single-study exemption is gone and A8 asserts the refusal instead of a mixed-unit test. No warehouse study stores or declares an attribute at both levels today. - attributeStats reads the declared patient_attribute, so an empty categorical answer carries the study's level rather than "patient". Only value-holding answers vote, so a peer on older code is still safe. A refused or tested row's level is the first value-holding answer's. - The note names attributes cBioPortal tests but does not list (survival pairs, AGE_LAST_FU_YEARS, BIRTH_YEAR) that were not tested, with the reason; they had dropped out of the q-values without a trace. - check-conflicting-levels: missing values from CLINICAL_MISSING_VALUES; a short multi-sample selection fails instead of passing smaller; truthCat's queries run together. Verified: tests from spec revision 2, written by a separate agent, fail against the previous lib/ and pass now; npm test 6734 pass, 0 fail. Planted bugs caught: pooled levels (9 failures), empty answers voting (4), splitBy pooling (1), the default level for empty answers (2), legacy filter-by-patient in Explore (B1-B3). check:conflicting-levels 16/16. Snapshot answers: the metadata statement's new form recorded for clinical and two-studies-four-views only, merged into the old answers so no warehouse drift enters; rendered snapshots unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q3ezTXrjJkt45AoXSDct6U
|
Re-review: still needs-user. The product question is unchanged; the code is sound. f0f6788 addresses the earlier non-blocking notes:
I found no new defects. The only open item is the user's choice, which is still in NEEDS-USER.md: refuse these attributes (as built), or count them per sample as the portal's Comparison page does. |
|
Verdict: pass. The user answered the product question on 2026-11-19: refuse, as built. A clinical comparison of an attribute stored per patient in one study and per sample in another is refused, naming the studies and levels. This is a deliberate difference from the portal, whose Comparison page counts such attributes per sample. Please record it as such in the parity scorecard (the CMP-STM-7 row, or wherever the level rule is tracked). The code was reviewed at this head (f0f6788) and found sound. See the previous comment. |
Prompted by cBioPortal/cbioportal#12509: in the legacy study view, an attribute stored per patient in one selected study and per sample in another ("conflicting") is counted for every sample of a selected patient, including samples the filters left out. This PR checks how cBioLab handles the same case.
Findings
Study view (Explore): already correct.
conflictingLevels+withSampleLevel(lib/custom-data.ts) lift a patient's value to onetype='sample'row per sample of the patient. Those rows are then filtered by sample id (inClinical), the same as genuinely sample-level rows. So each selected sample counts once, and unselected samples never count. The issue's own repro gives the expected answer here:nsclc_tracerx_2017:CRUK0030-R1+luad_cas_2020:LUAD_01, HISTOLOGYUntil now nothing checked this against data; the existing STS-MD-5 test matched SQL text. This PR adds a warehouse check that guards it.
Clinical comparison view: pooled the two units. Now refused.
runClinicalrefused an attribute only when the studies disagreed on its type. A level disagreement was pooled: each study counted in its own unit, and a cell added them. With cohortEGFR: MUTover tracerx + luad_cas, HISTOLOGY read 66 "patients" = 15 tracerx patients + 51 luad_cas samples, and the chi-squared ran on that mix. That breaks invariant 1 (loud rejection, never silent approximation). The attribute is now refused, like a type disagreement:How this compares with legacy. For almost every attribute the two count alike: each attribute at the level it is stored, patient-level per distinct patient of the group's samples, sample-level per sample (
ClinicalDataServiceImpl.fetchClinicalDataCounts; CMP-STM-6/7). They differ only for a conflicting attribute. Legacy classifies it as conflicting (ClinicalAttributeUtil.extractCategorizedClinicalAttributes) and counts the whole row per sample: the sample-level studies' samples plus the patient-level studies' values copied onto samples. That copy has #12509's overcount on this page too.fetchPatientClinicalDataCountswithDETAILEDtakes the patients of the group's samples and joins each one's value to every sample of the patient (INNER JOIN sample ON patient.internal_id = sample.patient_id, filtered by patient id). So a group holding one of a patient's five samples counts that patient's value five times. This PR refuses the attribute rather than imitate that. Counting it per selected sample, correctly, is possible (find the conflicting attributes up front and have each study copy them onto samples, as Explore does) and is left for a later change.Changes
lib/views/clinical/run.ts: the level refusal. Only answers that hold values say which level they were read at, because an empty categorical answer carries the defaultpatient. A single-study view is never refused on level. A tested row'speris now the level its values were read at, not the first answer's.lib/views/clinical/doc.tsand the view's note say so.test/view-clinical.test.ts: rows A1–A9 below.scripts/check-conflicting-levels.ts(npm run check:conflicting-levels), added togate.sh's warehouse lane after the case-lists check: rows B1–B7 below. Its expected counts come from its own SQL overclinical_data_derived+sample_derived, never from the code under test.scripts/mutants/comparison/conflicting-levels.ts(two) and one more inscripts/mutants/study-view/conflicting-levels.ts, which plants the legacy filter-by-patient logic. Its guard is the new check.test/snapshots/two-studies-four-views.*: only the clinical view's note changed (the SVG caption wraps one more line).Second commit (from review):
attributeLevels(lib/federation.ts), for every place that poolsattributeStatsanswers. That is the clinical comparison and splitBy'smergedDistribution, which still added patients to samples when sizing arms. Live: tracerx + luad_cas, split by HISTOLOGY, now gives "cannot split by 'HISTOLOGY': … store it at different levels …".attributeStatsreads the declaredpatient_attribute, so an empty answer carries the study's real level. Only answers holding values decide whether the levels conflict, so a remote peer on older code is still safe.CLINICAL_MISSING_VALUES; a selection that comes up short now fails;truthCat's two queries run together.clinicalandtwo-studies-four-viewsonly, merged into the old answers so no warehouse drift comes in. The rendered snapshots are unchanged.Spec table
The tests were written from this table by a separate agent, without the implementation in view (TESTING.md).
A. Clinical comparison view (cBioLab's own rule)
Refused when the studies that hold values (cat:
values.length > 0, num:n > 0) report differentper. The type check runs first.(patient in s1; sample in s2), no p, not in qpatient)per: samplepatient in s1, s3; sample in s2B. Study view (STS-MD-5, with #12509's bug absent): each selected sample counted once
Real data: HISTOLOGY (patient-level in
nsclc_tracerx_2017, 447 samples / 100 patients; sample-level inluad_cas_2020) and TOTAL_MUTATIONS (NUMBER; patient-level inhistiocytosis_cobi_msk_2019, 52 / 18; sample-level inblca_dfarber_mskcc_2014).These four studies hold a value for every sample, so NA is checked only at 0.
Revision 2 (from review)
peris the first value-holding answer'sallAttributes, hidden OS_MONTHS refused on levelattributeStats, no rows, declared sample / patientper: "sample"/"patient"Verification
test/view-clinical.test.ts: 47/47. Fullnpm test: the only failure was the snapshot, updated above (all othernot oklines are pre-existing importer TODOs).npm run check:conflicting-levels: 16/16 checks pass.clinical-levels-pooled→ 4 unit failures;clinical-levels-empty-answer-counts→ 1;conflicting-level-filtered-by-patient→ B1/B2/B3 fail, reproducing the issue's Invasive adenocarcinoma 4 for one selected sample.npm testgives 6734 pass, 0 fail. Revision 2's tests fail against the previouslib/and pass now. Planted bugs caught:clinical-levels-pooled(9 failures),clinical-levels-empty-answer-counts(4),splitby-levels-pooled(1),attribute-stats-empty-default-level(2),conflicting-level-filtered-by-patient(B1–B3).check:conflicting-levels16/16.scripts/gate.shwas not run locally; CI runs it.Tracker
docs/legacy-spec/parity/30-study-summary.md, row STS-MD-5: append to its evidencePORTAL-PARITY.md: no change.
🤖 Generated with Claude Code
https://claude.ai/code/session_01Q3ezTXrjJkt45AoXSDct6U
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.