diff --git a/app/lab/api.ts b/app/lab/api.ts index 28adc3fe..c598b242 100644 --- a/app/lab/api.ts +++ b/app/lab/api.ts @@ -17,13 +17,38 @@ interface Opts { signal?: AbortSignal } function post(path: string, body: unknown, signal?: AbortSignal): Promise { return fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal }); } +/** + * POST, sharing one request among callers that send the same body to the same path while it is in flight; each + * gets its own copy of the response, and a caller's signal abandons only its own wait. + */ +const inflight = new Map>(); +function postShared(path: string, body: unknown, signal?: AbortSignal): Promise { + const text = JSON.stringify(body), key = path + "\n" + text; + let p = inflight.get(key); + if (!p) { + p = fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: text }); + inflight.set(key, p); + const drop = () => { if (inflight.get(key) === p) inflight.delete(key); }; + p.then(drop, drop); + } + const mine = p.then((r) => r.clone()); + if (!signal) return mine; + // as fetch rejects an aborted request: an AbortError, so a caller's abort handling is unchanged + const aborted = () => new DOMException("The operation was aborted.", "AbortError"); + if (signal.aborted) return Promise.reject(aborted()); + return new Promise((ok, fail) => { + const stop = () => fail(aborted()); + signal.addEventListener("abort", stop, { once: true }); + mine.finally(() => signal.removeEventListener("abort", stop)).then(ok, fail); + }); +} const send = (method: "PATCH" | "PUT", path: string, body: unknown): Promise => fetch(path, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); export const api = { /** The document's cohorts and views. `query`: "?oncoprint=spec" (the page draws its own figures, the oncoprint included), "?figures=svg". */ analysis: async (doc: AnalysisBody, opts: Opts & { query?: string } = {}) => - post("/api/analysis" + (opts.query || ""), await withCustomData(doc), opts.signal), + postShared("/api/analysis" + (opts.query || ""), await withCustomData(doc), opts.signal), /** One view's Python script, which the page's analysis requests leave out: the body is the one-view document the page sent for it. */ methodScript: async (doc: AnalysisBody, opts: Opts = {}) => diff --git a/app/portal/PortalTabs.tsx b/app/portal/PortalTabs.tsx index a56fec3c..2ba8706c 100644 --- a/app/portal/PortalTabs.tsx +++ b/app/portal/PortalTabs.tsx @@ -109,7 +109,7 @@ export function PortalTabs({ doc, tabs, titles, partial, open, onOpen, onDoc, on useEffect(() => { if (!emptySlice || !chooser?.empties) return; const ctl = new AbortController(); - api.analysis(emptySlice, { signal: ctl.signal }) + api.analysis(emptySlice, { signal: ctl.signal, query: "?oncoprint=spec" }) .then((r) => r.json()) .then((j) => { const v = j?.views?.[0]; if (!j.error && v && !v.error) setGreyed({ sent: emptySent, options: chooser.empties!.empty(v) }); }) .catch(() => { /* no answer: no chip greyed, as before */ }); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7eb4ee7f..cb8632bf 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -206,7 +206,9 @@ no longer match the kind folders and the maps keyed by `ViewKind`. (`columns`/`search`/`filters`/`sort`, type `TableQuery`) is part of the view's spec — the page is not. The rows name patients, so they run only through `PatientLevelResolver.rowsPage`/ `rowsCounts`/`rowsValues`/`rowsRank` (asserted in `test/boundary.test.ts`); `lib/views/rows.ts`'s - `runRows` groups parts per database and pages across them. UI: **`app/_table/DataTable.tsx`**; + `runRows` groups parts per database and pages across them; with one database it asks for the page + beside the counts, and its counts can summarise columns over every row (`summarize`: a range or + the distinct values), which the mutations view's default columns read instead of a statement each. UI: **`app/_table/DataTable.tsx`**; `POST /api/view-page` (a page, or a column's values) and `POST /api/table` (the CSV) serve every table view. A view holding several tables (`alterations`, `datafiles`) names one with `table` in those requests (`RunOpts.table`), and `pagedTable()` in `lib/views/rows.ts` picks it from the result. diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index e94bc22a..4ad9674a 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -1045,3 +1045,36 @@ Every page costs less on cBioLab. cbioportal's JVM grows over a run (1.4 GiB in Still open: on Genomic Alterations the altered/unaltered cohort query (0.54s, 12M rows) runs twice, from two requests sent at once, and the result cache does not share a query that is still running. + +# The Mutations tab's rounds and driver reads (November 2026) + +After #502, a cold Mutations tab still read 139–162M warehouse rows per load against 43–54M on the +pre-parity baseline (`140c9239`), and drew 1.3–2.7× slower. Statement captures showed four causes: +the gene chips' "which genes are empty" request was the lollipop card's own request with one gene, +and ran in full a second time; the lollipop's driver test read all 19M `mutation_derived` rows +(its hotspot keys filtered by `studyId`, which is not in the table's sort key) and all 6.9M OncoKB +rows; and the mutation table ran four rounds one after another — the default columns' facts (two +statements over the row source), counts, page, then the clinical Freq — where without a search none +depends on another. The fix shares an in-flight request with the same body, bounds the driver reads +to the study's profiles and the lollipop's genes, runs the table's statements at once, asks for a +one-database table's page beside its counts, and reads the facts off the counts statement +(`countsSql`'s `summarize`), so the table evaluates its row source twice instead of four times. + +Production builds on one box, one page load at a time, a fresh server per round; cold, fully drawn, +median (min–max), n = 3: + +| | baseline | before | after | rows read before → after | +|---|---|---|---|---| +| coadread_tcga_pan_can_atlas_2018, KRAS | 4.1s (2.5–4.4) | 4.4s (4.1–4.8) | **3.6s** (3.4–4.4) | 139M → 27M | +| msk_chord_2024, TP53 | 3.5s (3.3–3.8) | 7.5s (6.7–7.6) | **4.3s** (4.1–4.6) | 150M → 33M | +| msk_impact_50k_2026, TP53 | 3.6s (3.4–4.1) | 9.7s (8.2–12.2) | **4.8s** (4.5–5.1) | 162M → 41M | + +The table's own request went from 4.5s to 2.1s (msk_chord) and 6.1s to 2.4s (msk_impact_50k); +`/api/analysis` calls per load from 4 to 3. Warm loads (the result cache) are 0.7–1.0s either way. + +What did not help, measured: reading a whole-study cohort as its definition instead of shipping its +ids (`COHORT_IDS_LIMIT=0`: 7.5s vs 7.7s), and a page statement that builds only its key columns +(0.85s vs 0.86s by replay — the cost is in building the row source, not its columns). What remains +above the baseline is mostly the parity work itself: the row source's lookups (copy number, clinical +attributes, structural variants, OncoKB by tumour type) and the provenance SQL in each answer +(about three quarters of the table's bytes). diff --git a/lib/federation.ts b/lib/federation.ts index 1db0a16e..45244fc6 100644 --- a/lib/federation.ts +++ b/lib/federation.ts @@ -39,7 +39,7 @@ export type { PlotData, PlotRequest, PlotGroup, PlotPoint, PlotXYPoint, PlotLaye import { impactSql } from "./lollipop.ts"; import type { Moments } from "./stats.ts"; // a table view's row queries return ids: imported for PatientLevelResolver.rowsPage, never re-exported -import { checkQuery, pageSql, countsSql, valuesSql, rankSql, type RowSource, type TableQuery } from "./table-query.ts"; +import { checkQuery, pageSql, countsSql, valuesSql, rankSql, summaryOf, type ColumnSummary, type RowSource, type SummaryAsk, type TableQuery } from "./table-query.ts"; /** the colour key: the commonest categories, capped, each with the colour every renderer uses */ /** @@ -478,7 +478,9 @@ export function geneCountsSql(cohortSql: string, genes: string[], study: string, * patients (`np`) among those kept. The Mutations and SV tables page only their own instances' rows (no * `remote`), so today a peer's counts never carry `dup`. */ -export interface RowCounts { cohort: string; study: string; n: number; all: number; dup?: number; ns?: number; np?: number } +export interface RowCounts { cohort: string; study: string; n: number; all: number; dup?: number; ns?: number; np?: number; + /** the columns a local count was asked to summarise (countsSql `summarize`), over every row of the part */ + sums?: ColumnSummary[] } /** the query's lines a Mutations tab follows, and how their DRIVER reads */ export interface LollipopOql { lines: string[]; drivers?: DriverSettings } /** @@ -664,7 +666,7 @@ function lollipopCte(cohortSql: string, genes: string[], study: string, minCount const hotspotKeys = pin && hotspotPins ? hotspotKeysSql(db, [study], genes, hotspotPins) : null; const driver = pin ? "if((`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM " + ONCOKB_TABLE + "\n" + - " WHERE oncokb_version = " + sq(pin) + " AND is_driver AND alteration_type = 'MUTATION')" + + " WHERE oncokb_version = " + sq(pin) + " AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN (" + list + "))" + (hotspotKeys ? "\n OR (`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (" + hotspotKeys + ")" : "") + ", 1, 0)" : "1"; return lollipopCteSql(cohortSql, genes, study, floor, pin, db, filters, fusionLines, list, driver, fusionDriver, rowKeys); @@ -685,7 +687,7 @@ function lollipopCteWith(cohortSql: string, genes: string[], study: string, floo if (d.tiers === null) or.push("ifNull(driverTiersFilter, '') != ''"); else if (d.tiers.length) or.push("ifNull(driverTiersFilter, '') IN (" + d.tiers.map(sq).join(", ") + ")"); if (src.oncokb) or.push("(`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM " + ONCOKB_TABLE + "\n" + - " WHERE oncokb_version = " + sq(pin!) + " AND is_driver AND alteration_type = 'MUTATION')"); + " WHERE oncokb_version = " + sq(pin!) + " AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN (" + list + "))"); const hotspotKeys = src.hotspots ? hotspotKeysSql(db, [study], genes, hotspotPins!) : null; if (hotspotKeys) or.push("(`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (" + hotspotKeys + ")"); const annotating = annotatingSql(d, src.sure, db, study); @@ -1464,7 +1466,7 @@ export interface PatientLevelCapable extends AggregateCapable { viewRows(label: string, def: CohortDef | null | undefined, build: (cohortSql: string, study: string, db: string) => string): Promise; /** a table view's rows (lib/table-query.ts) in this instance, with their ids — see PatientLevelResolver.rowsPage */ rowsPage(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], limit: number, offset: number): Promise<{ rows: ChRow[]; total: number }>; - rowsCounts(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[]): Promise; + rowsCounts(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], summarize?: SummaryAsk[]): Promise; rowsValues(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], column: string): Promise; rowsRank(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], study: string, patient: string): Promise; /** one patient's timeline events and samples — see PatientLevelResolver.patientTimeline */ @@ -2492,10 +2494,10 @@ export class PatientLevelResolver extends BaseResolver implements PatientLevelCa return { rows: r.data, total: r.data.length ? Number(r.data[0].total) : 0 }; } /** per part: the rows the query keeps and every row. Counts only. */ - async rowsCounts(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[]): Promise { - const r = await this.runPatientRows(label, countsSql(source(this.instance.conn.db, await materializedCteSupported(this.instance.conn)), q, defaults), this.instance.conn); + async rowsCounts(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], summarize: SummaryAsk[] = []): Promise { + const r = await this.runPatientRows(label, countsSql(source(this.instance.conn.db, await materializedCteSupported(this.instance.conn)), q, defaults, summarize), this.instance.conn); return r.data.map((x) => ({ cohort: String(x.cohort), study: String(x.study), n: Number(x.n), all: Number(x.all), ...(x.dup != null ? { dup: Number(x.dup) } : {}), - ...(x.ns != null && x.np != null ? { ns: Number(x.ns), np: Number(x.np) } : {}) })); + ...(x.ns != null && x.np != null ? { ns: Number(x.ns), np: Number(x.np) } : {}), ...(summarize.length ? { sums: summaryOf(summarize, x) } : {}) })); } /** a column's distinct values with counts, or its range — what its filter offers */ async rowsValues(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], column: string): Promise { diff --git a/lib/hotspots.ts b/lib/hotspots.ts index 88de214d..6e674ebd 100644 --- a/lib/hotspots.ts +++ b/lib/hotspots.ts @@ -50,7 +50,9 @@ export function hotspotKeysSql(db: string, studies: string[], genes: string[] | " INNER JOIN (SELECT cs.cancer_study_identifier AS study, " + sourceOf + " AS src FROM " + db + ".cancer_study cs\n" + " JOIN " + db + ".reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id\n" + " WHERE cs.cancer_study_identifier " + inList(studies) + ") st ON st.study = m.studyId\n" + - " WHERE m.studyId " + inList(studies) + " AND m.`GENE.hugoGeneSymbol` " + inList(wanted) + "\n" + + // the study's profiles' prefix, so the read uses mutation_derived's sort key (molecularProfileId first) + " WHERE " + (studies.length ? "(" + studies.map((st) => "startsWith(m.molecularProfileId, " + sq(st + "_") + ")").join(" OR ") + ") AND " : "") + + "m.studyId " + inList(studies) + " AND m.`GENE.hugoGeneSymbol` " + inList(wanted) + "\n" + // a location only when every part is present and non-empty (MutationUtils.extractGenomicLocation) " AND st.src != '' AND ifNull(m.chr, '') != '' AND ifNull(m.startPosition, 0) != 0 AND ifNull(m.endPosition, 0) != 0\n" + " AND ifNull(m.referenceAllele, '') != '' AND ifNull(m.tumorSeqAllele, '') != '' AND ifNull(m.proteinChange, '') != ''"; diff --git a/lib/table-query.ts b/lib/table-query.ts index 308074f2..d67bb67a 100644 --- a/lib/table-query.ts +++ b/lib/table-query.ts @@ -218,13 +218,65 @@ export function rankSql(src: RowSource, q: TableQuery, defaults: string[], study "WHERE study = " + sq(study) + " AND patient = " + sq(patient) + " LIMIT 1" + (src.settings || "")); } -/** Per cohort and study: the rows the query keeps (`n`) and every row (`all`). Counts only. */ -export function countsSql(src: RowSource, q: TableQuery, defaults: string[]): PatientSql { +/** A column a counts query also summarises over every row, whatever the query (`summarize`). */ +export type SummaryAsk = { column: string; numeric: boolean }; +/** + * A column over every row: a number column's range (nulls left out; null when no row has one), or a + * text column's distinct values, '' included — at most VALUES_MAX, `truncated` when there are more. + */ +export type ColumnSummary = + | { column: string; numeric: true; min: number | null; max: number | null } + | { column: string; numeric: false; values: string[]; truncated: boolean }; + +/** + * Per cohort and study: the rows the query keeps (`n`) and every row (`all`). Counts only. With + * `summarize`, each column's summary over every row as well (`slo`/`shi`, or `sv`: up to + * VALUES_MAX + 1 distinct values, so one past the cap shows), read by summaryOf. + */ +export function countsSql(src: RowSource, q: TableQuery, defaults: string[], summarize: SummaryAsk[] = []): PatientSql { const where = whereSql(src, q, defaults); + const sums = summarize.map((s, i) => { + const col = src.columns.find((c) => c.id === s.column); + if (!col) throw new Error("unknown column " + s.column); + return s.numeric + ? ", min(" + (col.num || col.text) + ") AS s" + i + "lo, max(" + (col.num || col.text) + ") AS s" + i + "hi" + : ", groupUniqArray(" + (VALUES_MAX + 1) + ")(" + col.text + ") AS s" + i + "v"; + }).join(""); return patientSql(src.with + "SELECT cohort, study, countIf(" + where + ") AS n, count() AS all" + (src.duplicateKey ? ", count() - uniqExact(" + src.duplicateKey + ") AS dup" : "") + (src.units ? ", uniqExactIf(" + src.units.sample + ", " + where + ") AS ns, uniqExactIf(" + src.units.patient + ", " + where + ") AS np" : "") + - " FROM rows GROUP BY cohort, study" + (src.settings || "")); + sums + " FROM rows GROUP BY cohort, study" + (src.settings || "")); +} + +/** One part's summaries from its counts row (countsSql with `summarize`). */ +export function summaryOf(summarize: SummaryAsk[], row: Record): ColumnSummary[] { + const num = (x: unknown) => x == null || x === "" || !Number.isFinite(Number(x)) ? null : Number(x); + return summarize.map((s, i) => { + if (s.numeric) return { column: s.column, numeric: true, min: num(row["s" + i + "lo"]), max: num(row["s" + i + "hi"]) }; + const vs = Array.isArray(row["s" + i + "v"]) ? (row["s" + i + "v"] as unknown[]).map((x) => String(x ?? "")) : []; + return { column: s.column, numeric: false, values: [...new Set(vs)].sort().slice(0, VALUES_MAX), truncated: new Set(vs).size > VALUES_MAX }; + }); +} + +/** The parts' summaries of the same columns as one: the widest range, the union of the values. */ +export function mergeSummaries(summarize: SummaryAsk[], parts: ColumnSummary[][]): ColumnSummary[] { + return summarize.map((s) => { + const each = parts.map((p) => p.find((x) => x.column === s.column)).filter((x): x is ColumnSummary => !!x); + if (s.numeric) { + const lo = each.map((x) => x.numeric ? x.min : null).filter((x): x is number => x != null); + const hi = each.map((x) => x.numeric ? x.max : null).filter((x): x is number => x != null); + return { column: s.column, numeric: true, min: lo.length ? Math.min(...lo) : null, max: hi.length ? Math.max(...hi) : null }; + } + const all = new Set(each.flatMap((x) => x.numeric ? [] : x.values)); + return { column: s.column, numeric: false, values: [...all].sort().slice(0, VALUES_MAX), + truncated: each.some((x) => !x.numeric && x.truncated) || all.size > VALUES_MAX }; + }); +} + +/** A column's values as a summary: its range, or its distinct values without their counts. */ +export function summaryOfValues(v: ColumnValues): ColumnSummary { + return v.numeric ? { column: v.column, numeric: true, min: v.min, max: v.max } + : { column: v.column, numeric: false, values: v.values.map((x) => x.value), truncated: v.truncated }; } /** diff --git a/lib/views/mutation-defaults.ts b/lib/views/mutation-defaults.ts index 19b62c01..9a15a185 100644 --- a/lib/views/mutation-defaults.ts +++ b/lib/views/mutation-defaults.ts @@ -6,23 +6,33 @@ import { clinicalColumns, type ClinicalColumn } from "../mutation-clinical.ts"; import { clinicalFreq, clinicalFreqSql } from "../mutation-clinical-freq.ts"; import { tableAttributesSql, TABLE_COLUMNS_MAX } from "../clinical-table.ts"; import type { ViewResolver } from "./shared.ts"; -import type { RowSource } from "../table-query.ts"; +import { summaryOfValues, type ColumnSummary, type RowSource, type SummaryAsk } from "../table-query.ts"; import type { LollipopOql } from "../federation.ts"; import type { ResolvedDrivers } from "../driver-settings.ts"; import { variantPins } from "../variant-annotation.ts"; import type { ViewRun } from "./run.ts"; import { runRows } from "./rows.ts"; +/** The columns the facts read off the rows, which a counts statement can summarise (runRows `summarize`). */ +export const MUTATION_FACT_COLUMNS: SummaryAsk[] = [{ column: "vaf", numeric: true }, { column: "cancerType", numeric: false }]; + /** * Over every row of the gene's table whatever its search and filters (the portal reads its table's * allData): whether a queried study has a discrete CNA profile, whether a row has a non-zero allele * frequency, how many Cancer Type Detailed values the rows hold. A study whose peer did not describe - * its profiles (`unanswered`) leaves the first unknown, unless another study has the profile. + * its profiles (`unanswered`) leaves the first unknown, unless another study has the profile. The + * rows' facts come from `summaries` (Rows.summaries of MUTATION_FACT_COLUMNS) where given; otherwise + * each column's values are asked for. */ -export async function mutationDefaultFacts(ctx: ViewRun, holders: string[], source: (parts: TablePart[]) => (db: string, materialized: boolean) => RowSource): Promise { - const valuesOf = async (column: string, numeric: boolean) => - (await runRows(ctx, "mutations", holders, {}, MUTATION_DEFAULT_COLUMNS, MUTATION_DEFAULT_COLUMNS, 1, source, { column, numeric })).values; - const [vaf, types, studies] = await Promise.all([valuesOf("vaf", true), valuesOf("cancerType", false), +export async function mutationDefaultFacts(ctx: ViewRun, holders: string[], source: (parts: TablePart[]) => (db: string, materialized: boolean) => RowSource, + summaries?: ColumnSummary[]): Promise { + const summaryOf = async (column: string, numeric: boolean): Promise => { + const given = summaries?.find((x) => x.column === column); + if (given) return given; + const v = (await runRows(ctx, "mutations", holders, {}, MUTATION_DEFAULT_COLUMNS, MUTATION_DEFAULT_COLUMNS, 1, source, { column, numeric })).values; + return v && summaryOfValues(v); + }; + const [vaf, types, studies] = await Promise.all([summaryOf("vaf", true), summaryOf("cancerType", false), Promise.all(ctx.vStudies.map((st) => ctx.studyProfiles(st)))]); // a study with the profile settles it; otherwise every study must have answered for "none" to be known const discrete = studies.some((p) => (p.catalog || []).some((x) => x.type === "COPY_NUMBER_ALTERATION" && x.datatype === "DISCRETE")); @@ -30,7 +40,7 @@ export async function mutationDefaultFacts(ctx: ViewRun, holders: string[], sour return { ...(discrete || known ? { discreteCna: discrete } : {}), ...(vaf?.numeric ? { nonZeroVaf: vaf.max != null && vaf.max > 0 } : {}), - ...(types && !types.numeric ? { cancerTypes: types.truncated ? Infinity : types.values.filter((x) => x.value !== "").length } : {}), + ...(types && !types.numeric ? { cancerTypes: types.truncated ? Infinity : types.values.filter((x) => x !== "").length } : {}), }; } diff --git a/lib/views/mutations/run.ts b/lib/views/mutations/run.ts index 581958b0..ee9a7dee 100644 --- a/lib/views/mutations/run.ts +++ b/lib/views/mutations/run.ts @@ -2,8 +2,8 @@ import type { ViewResult } from "../../types.ts"; import { geneSymbols } from "../../gene-tracks.ts"; import { driverSourceText, resolveDrivers, type ResolvedDrivers } from "../../driver-settings.ts"; -import { MUTATION_COLUMNS, mutationRowSource, alterationOf, mutationDefaultColumns, type MutationColumn, type TablePart } from "../../mutation-table.ts"; -import { mutationClinicalColumns, mutationClinicalFreq, mutationDefaultFacts } from "../mutation-defaults.ts"; +import { MUTATION_COLUMNS, MUTATION_DEFAULT_COLUMNS, mutationRowSource, alterationOf, mutationDefaultColumns, type MutationColumn, type TablePart } from "../../mutation-table.ts"; +import { MUTATION_FACT_COLUMNS, mutationClinicalColumns, mutationClinicalFreq, mutationDefaultFacts } from "../mutation-defaults.ts"; import { clinicalValue } from "../../mutation-clinical.ts"; import { checkQuery, describeQuery, shownColumns } from "../../table-query.ts"; import type { ViewRun } from "../run.ts"; @@ -69,6 +69,10 @@ function mutationDetail(r: Record, build: string | undefined): return Object.keys(d).length ? d : undefined; } +/** a promise that never rejects, so one started early cannot go unhandled while others are awaited */ +const settled = (p: Promise): Promise<{ ok: T } | { err: unknown }> => p.then((ok) => ({ ok }), (err) => ({ err })); +const unwrap = (s: { ok: T } | { err: unknown }): T => { if ("err" in s) throw s.err; return s.ok; }; + export async function runMutations(view: MutationsView, ctx: ViewRun): Promise { const { vNames, pin } = ctx; { const e = overLimit("a mutations view", 6, vNames.length); if (e) return refuse("mutations", ctx, e.replace("at most 6", "at most 6 cohorts")); } @@ -91,17 +95,28 @@ export async function runMutations(view: MutationsView, ctx: ViewRun): Promise e.study + ": " + e.reason).join("; ") + ")"); const source = (parts: TablePart[]) => (db: string, materialized: boolean) => keyOnFirstRun(ctx, mutationRowSource(parts, db, gene, pin, pins, lines.oql, drivers, clinical, materialized)); + const values = ctx.values ? { column: ctx.values, numeric: !!columns.find((c) => c.id === ctx.values)?.numeric } : undefined; + // the Columns menu's Clinical tab and its Freq (MUT-TB-5, MUT-STM-15), with the first page only: a later page keeps its columns + const freqAsk = !ctx.page && !ctx.values ? settled(mutationClinicalFreq(ctx, holders, clinical)) : Promise.resolve({ ok: {} as Record }); let r: Rows, defaults: string[]; try { - defaults = mutationDefaultColumns(await mutationDefaultFacts(ctx, holders, source)); - r = await runRows(ctx, "mutations", holders, q, defaults, shownColumns(q, columns, defaults), size, source, - ctx.values ? { column: ctx.values, numeric: !!columns.find((c) => c.id === ctx.values)?.numeric } : undefined); + if ((q.search || "").trim()) { + // a search reads the shown columns, so the defaults are settled before the rows are asked for + defaults = mutationDefaultColumns(await mutationDefaultFacts(ctx, holders, source)); + r = await runRows(ctx, "mutations", holders, q, defaults, shownColumns(q, columns, defaults), size, source, values); + } else if (values) { + // without a search the defaults reach no statement, so a column's values and the facts are asked for at once + const facts = settled(mutationDefaultFacts(ctx, holders, source)); + r = await runRows(ctx, "mutations", holders, q, MUTATION_DEFAULT_COLUMNS, MUTATION_DEFAULT_COLUMNS, size, source, values); + defaults = mutationDefaultColumns(unwrap(await facts)); + } else { + // ... and the rows' counts carry the facts' columns, with the page asked for beside them + r = await runRows(ctx, "mutations", holders, q, MUTATION_DEFAULT_COLUMNS, MUTATION_DEFAULT_COLUMNS, size, source, undefined, undefined, undefined, MUTATION_FACT_COLUMNS); + defaults = mutationDefaultColumns(await mutationDefaultFacts(ctx, holders, source, r.summaries)); + } } catch (e) { return refuse("mutations", ctx, (e as Error).message); } - // the Columns menu's Clinical tab and its Freq (MUT-TB-5, MUT-STM-15), with the first page only: a later page keeps its columns - let freq: Record = {}; - if (!ctx.page && !ctx.values) { - try { freq = await mutationClinicalFreq(ctx, holders, clinical); } catch (e) { return refuse("mutations", ctx, (e as Error).message); } - } + let freq: Record; + try { freq = unwrap(await freqAsk); } catch (e) { return refuse("mutations", ctx, (e as Error).message); } const menuColumns: MutationColumn[] = columns.map((c) => c.id in freq ? { ...c, group: "clinical" as const, freq: freq[c.id] } : c); const rows = r.rows.map((x) => { const detail = mutationDetail(x, x.build == null ? undefined : String(x.build)); diff --git a/lib/views/rows.ts b/lib/views/rows.ts index f8b04540..88cb9071 100644 --- a/lib/views/rows.ts +++ b/lib/views/rows.ts @@ -3,7 +3,7 @@ import { PATIENT_KIND_NAMES, type PatientKind } from "../disclosure.ts"; import { isPatientLevel, peerRowsFor, type PatientLevelCapable, type PeerRowsRequest, type RemotePatientRows, type Resolver, type RowCounts } from "../federation.ts"; import type { TablePart } from "../mutation-table.ts"; -import { cleanQuery, describeQuery, mergeValues, type ColumnValues, type RowSource, type TableQuery } from "../table-query.ts"; +import { cleanQuery, describeQuery, mergeSummaries, mergeValues, type ColumnSummary, type ColumnValues, type RowSource, type SummaryAsk, type TableQuery } from "../table-query.ts"; import type { TableRows, ViewResult } from "../types.ts"; import type { ViewRun } from "./run.ts"; import { plural } from "./shared.ts"; @@ -40,7 +40,9 @@ export type Rows = { rows: Record[]; lists: { cohort: string; s /** the distinct samples and patients among the rows the query keeps (a source with RowSource.units), when every part reports them */ kept?: { samples: number; patients: number }; /** with `locate`: the patient's place in the list's one order and the rows either side of it — null when the query leaves it out */ - position?: { index: number; prev: Record | null; next: Record | null } | null }; + position?: { index: number; prev: Record | null; next: Record | null } | null; + /** with `summarize`: each column over every row of every part, when every database answered it */ + summaries?: ColumnSummary[] }; /** * A table view's rows: its parts grouped per database instance (a group's parts are combined and @@ -49,13 +51,15 @@ export type Rows = { rows: Record[]; lists: { cohort: string; s * `source(parts, reads)` builds the table's row source; `reads` names the columns a query needs * ("all" for a page), so a count need not carry every column. With `locate`, also where that * patient falls in the order and its neighbours (the timeline's prev / next). With `remote`, a - * study whose peer may serve this table (`of`) has its rows paged by that peer, as `table`. + * study whose peer may serve this table (`of`) has its rows paged by that peer, as `table`. With + * `summarize`, the counts also summarise those columns over every row (Rows.summaries), when every + * database answered them. */ export type RemoteRows = { of: (r: Resolver) => RemotePatientRows | null; table: PeerRowsRequest["table"]; subject?: PeerRowsRequest["subject"]; samples?: PeerRowsRequest["samples"]; oncokbPin?: string | null; onAnswer?: (a: { oncokbPin?: string | null }) => void }; export async function runRows(ctx: ViewRun, label: string, holders: string[], q: TableQuery, defaults: string[], shown: string[], size: number, source: (parts: TablePart[], reads: string[] | "all") => (db: string, materialized: boolean) => RowSource, values?: { column: string; numeric: boolean }, - remote?: RemoteRows, locate?: { study: string; patient: string }): Promise { + remote?: RemoteRows, locate?: { study: string; patient: string }, summarize?: SummaryAsk[]): Promise { type PL = Pick; // one backend per database — or per peer, for a view whose rows a peer may page itself (`remote`) type Backend = { @@ -63,12 +67,15 @@ export async function runRows(ctx: ViewRun, label: string, holders: string[], q: counts: (parts: TablePart[], reads: string[]) => Promise; values: (parts: TablePart[], reads: string[], column: string) => Promise[]>; rank: (parts: TablePart[], study: string, patient: string) => Promise; + /** whether its counts answer `summarize` */ + summarizes: boolean; }; const local = (r: PL): Backend => ({ page: async (parts, limit, offset) => (await r.rowsPage(label + ":rows", source(parts, "all"), q, defaults, limit, offset)).rows, - counts: (parts, reads) => r.rowsCounts(label + ":counts", source(parts, reads), q, defaults), + counts: (parts, reads) => r.rowsCounts(label + ":counts", source(parts, reads), q, defaults, ...(summarize?.length ? [summarize] : [])), values: (parts, reads, column) => r.rowsValues(label + ":values", source(parts, reads), q, defaults, column), rank: (parts, study, patient) => r.rowsRank(label + ":rank", source(parts, queryReads(q, shown)), q, defaults, study, patient), + summarizes: true, }); const peer = (r: RemotePatientRows, rr: RemoteRows): Backend => { const ask = async (parts: TablePart[], req: Pick) => { @@ -82,6 +89,7 @@ export async function runRows(ctx: ViewRun, label: string, holders: string[], q: counts: async (parts) => (await ask(parts, { mode: "counts" })).counts || [], values: async (parts, _reads, column) => (await ask(parts, { mode: "values", column })).values || [], rank: async (parts, _study, patient) => (await ask(parts, { mode: "rank", patient })).rank ?? null, + summarizes: false, }; }; const groups: { backend: Backend; parts: TablePart[]; total: number }[] = []; @@ -100,8 +108,15 @@ export async function runRows(ctx: ViewRun, label: string, holders: string[], q: const lists: Rows["lists"] = []; let all = 0, duplicates = 0, dupParts = 0, parts = 0, unitParts = 0; const kept = { samples: 0, patients: 0 }; + const want = ctx.page ? { offset: Math.max(0, Math.floor(ctx.page.offset)), limit: Math.min(TABLE_CHUNK, Math.max(1, Math.floor(ctx.page.limit))) } : { offset: 0, limit: size }; + // one group needs no count to find where its page starts, so the page is asked for beside the counts + const early = groups.length === 1 && !locate ? groups[0].backend.page(groups[0].parts, want.limit, want.offset).then((ok) => ({ ok }), (err: unknown) => ({ err })) : null; + const countReads = summarize?.length ? [...new Set([...reads, ...summarize.map((x) => x.column)])] : reads; + const sums: ColumnSummary[][] = []; + let summarized = !!summarize?.length; await Promise.all(groups.map(async (g) => { - const counts = await g.backend.counts(g.parts, reads); + const counts = await g.backend.counts(g.parts, countReads); + for (const c of counts) { if (c.sums) sums.push(c.sums); else summarized = false; } for (const p of g.parts) { const c = counts.find((x) => x.cohort === p.cohort && x.study === p.study); lists.push({ cohort: p.cohort, study: p.study, total: c?.n || 0, all: c?.all || 0 }); @@ -119,7 +134,6 @@ export async function runRows(ctx: ViewRun, label: string, holders: string[], q: } })); const total = groups.reduce((n, g) => n + g.total, 0); - const want = ctx.page ? { offset: Math.max(0, Math.floor(ctx.page.offset)), limit: Math.min(TABLE_CHUNK, Math.max(1, Math.floor(ctx.page.limit))) } : { offset: 0, limit: size }; // rows `offset` on, in the one order: each group's rows follow the groups before it const pageAt = async (offset: number, limit: number) => { const out: Record[] = []; @@ -131,7 +145,9 @@ export async function runRows(ctx: ViewRun, label: string, holders: string[], q: } return out; }; - const [rows, position] = await Promise.all([pageAt(want.offset, want.limit), locate ? (async () => { + // an offset at or past the end keeps no rows, as pageAt keeps none + const first = early ? early.then((e) => { if ("err" in e) throw e.err; return want.offset < total ? e.ok : []; }) : pageAt(want.offset, want.limit); + const [rows, position] = await Promise.all([first, locate ? (async () => { let before = 0; for (const g of groups) { // ranked among the whole group's rows: they are sorted together @@ -147,7 +163,8 @@ export async function runRows(ctx: ViewRun, label: string, holders: string[], q: })() : Promise.resolve(undefined)]); const order = (l: { cohort: string; study: string }) => ctx.vNames.indexOf(l.cohort) * 1000 + ctx.vStudies.indexOf(l.study); lists.sort((a, b) => order(a) - order(b)); - return { rows, lists, total, all, offset: want.offset, groups: groups.length, ...(position !== undefined ? { position } : {}), ...(parts && dupParts === parts ? { duplicates } : {}), ...(parts && unitParts === parts ? { kept } : {}) }; + return { rows, lists, total, all, offset: want.offset, groups: groups.length, ...(position !== undefined ? { position } : {}), + ...(summarize?.length && summarized && groups.every((g) => g.backend.summarizes) ? { summaries: mergeSummaries(summarize, sums) } : {}), ...(parts && dupParts === parts ? { duplicates } : {}), ...(parts && unitParts === parts ? { kept } : {}) }; } /** A view's query as the document gives it, with an older `sort.attribute` read as `sort.column`. */ diff --git a/scripts/mutants/mutations/tab-rounds.ts b/scripts/mutants/mutations/tab-rounds.ts new file mode 100644 index 00000000..899424f6 --- /dev/null +++ b/scripts/mutants/mutations/tab-rounds.ts @@ -0,0 +1,38 @@ +// Planted bugs: the Mutations tab's statements run at once — the default columns' facts read off the +// counts' column summaries, one database's page asked for beside its counts, the lollipop's driver +// reads bounded to its genes and study, and the page's identical requests shared. How they are +// planted and run: scripts/check-mutants.ts. +import type { GuardCommands, Mutant } from "../types.ts"; + +export const guards: GuardCommands = { + // the summaries and the lollipop's driver flags, run on the fixture study's connection b + "tab-rounds-fixture": ["node", "--test", "test/table-summaries-fixture.test.ts", "test/lollipop-drivers-fixture.test.ts"], +}; + +export const mutants: Mutant[] = [ + { id: "summaries-follow-query", layer: "counts", guard: "tab-rounds-fixture", file: "lib/table-query.ts", + effect: "A column's range is taken over the rows the table's search and filters keep, not every row, so a search can hide the Allele Freq (T) column.", + find: "? \", min(\" + (col.num || col.text) + \") AS s\" + i + \"lo, max(\" + (col.num || col.text) + \") AS s\" + i + \"hi\"", + replace: "? \", minIf(\" + (col.num || col.text) + \", \" + where + \") AS s\" + i + \"lo, maxIf(\" + (col.num || col.text) + \", \" + where + \") AS s\" + i + \"hi\"" }, + { id: "summaries-merge-drops-truncation", layer: "counts", guard: "unit", file: "lib/table-query.ts", + effect: "A part with more than 500 distinct values merges as if it had them all, so the count of cancer types is finite where it is unknown.", + find: "truncated: each.some((x) => !x.numeric && x.truncated) || all.size > VALUES_MAX };", + replace: "truncated: all.size > VALUES_MAX };" }, + { id: "facts-count-blank-type", layer: "counts", guard: "unit", file: "lib/views/mutation-defaults.ts", + effect: "A blank cancer type counts as a type, so a gene whose rows hold one type and some blanks shows Cancer Type Detailed by default.", + find: "types.values.filter((x) => x !== \"\").length", replace: "types.values.length" }, + { id: "rows-summaries-partial", layer: "counts", guard: "unit", file: "lib/views/rows.ts", + effect: "A count that carries no summaries (an older backend) is read as a part with no frequencies and no types, so the defaults drop Allele Freq (T) and Cancer Type Detailed instead of asking.", + find: "for (const c of counts) { if (c.sums) sums.push(c.sums); else summarized = false; }", + replace: "for (const c of counts) { if (c.sums) sums.push(c.sums); }" }, + { id: "early-page-past-end", layer: "counts", guard: "unit", file: "lib/views/rows.ts", + effect: "A page asked for at or past the last row returns the rows the database sent instead of none.", + find: "return want.offset < total ? e.ok : [];", replace: "return e.ok;" }, + { id: "lollipop-drivers-first-gene", layer: "counts", guard: "tab-rounds-fixture", file: "lib/federation.ts", + effect: "The lollipop reads OncoKB's driver calls for its first gene only, so every other gene's OncoKB drivers are drawn as VUS.", + find: "AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN (\" + list + \"))\" +", + replace: "AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN (\" + list.split(\",\")[0] + \"))\" +" }, + { id: "shared-request-ignores-query", layer: "counts", guard: "unit", file: "app/lab/api.ts", + effect: "Two requests for the same document under different query strings share one answer, so a page asking for SVG figures gets the spec-only answer (or the reverse).", + find: "key = path + \"\\n\" + text;", replace: "key = path.split(\"?\")[0] + \"\\n\" + text;" }, +]; diff --git a/test/api-inflight.test.ts b/test/api-inflight.test.ts new file mode 100644 index 00000000..947c9cb1 --- /dev/null +++ b/test/api-inflight.test.ts @@ -0,0 +1,157 @@ +// app/lab/api.ts api.analysis: one request shared by callers that send the same body and query while +// it is in flight. With globalThis.fetch stubbed: +// C1 two identical calls while the first is in flight → one fetch; both responses readable, same JSON +// C2 a different body, or a different query → separate fetches +// C3 once the shared fetch has answered, an identical call fetches again +// C4 a caller whose signal aborts rejects with an AbortError; the other still gets its response; +// the shared fetch was not given that signal; a signal already aborted rejects at once +// C5 a failing fetch rejects every sharer +// api.analysis first attaches uploaded datasets (custom-data-client), which asks /api/auth once; the +// stub answers that as a deployment without sign-in, and only /api/analysis requests are counted. +import { test, beforeEach, after } from "node:test"; +import assert from "node:assert/strict"; +import { api } from "../app/lab/api.ts"; + +type Pending = { url: string; init: RequestInit; resolve: (r: Response) => void; reject: (e: unknown) => void }; +let pending: Pending[] = []; +const realFetch = globalThis.fetch; +globalThis.fetch = ((input: RequestInfo | URL, init: RequestInit = {}) => { + const url = String(input); + if (!url.startsWith("/api/analysis")) { + if (url === "/api/auth") return Promise.resolve(Response.json({ enabled: false, user: null, options: {} })); + return Promise.resolve(new Response("", { status: 404 })); + } + return new Promise((resolve, reject) => { pending.push({ url, init, resolve, reject }); }); +}) as typeof fetch; +after(() => { globalThis.fetch = realFetch; }); +beforeEach(() => { pending = []; }); + +const doc = (n: number) => ({ study: "s" + n, cohorts: { Q: { study: "s" + n } }, views: [] }) as never; +const tick = () => new Promise((r) => setTimeout(r, 5)); +/** let the calls reach fetch (they first await the uploads' attachment) */ +const settle = async () => { for (let i = 0; i < 5; i++) await tick(); }; + +test("C1 two identical calls while the first is in flight: one fetch, both responses readable with the same JSON", async () => { + const a = api.analysis(doc(1)); + const b = api.analysis(doc(1)); + await settle(); + assert.equal(pending.length, 1, "one fetch: " + pending.map((p) => p.url).join(", ")); + pending[0].resolve(Response.json({ ok: 1, views: [] })); + const [ra, rb] = await Promise.all([a, b]); + assert.deepEqual(await ra.json(), { ok: 1, views: [] }); + assert.deepEqual(await rb.json(), { ok: 1, views: [] }); +}); + +test("C1 a third identical call joining later, still in flight, shares it too; status and headers carried", async () => { + const a = api.analysis(doc(7), { query: "?x=1" }); + await settle(); + const b = api.analysis(doc(7), { query: "?x=1" }); + await settle(); + assert.equal(pending.length, 1); + pending[0].resolve(new Response(JSON.stringify({ n: 7 }), { status: 207, headers: { "Content-Type": "application/json", "X-Test": "y" } })); + for (const r of await Promise.all([a, b])) { + assert.equal(r.status, 207); + assert.equal(r.headers.get("X-Test"), "y"); + assert.deepEqual(await r.json(), { n: 7 }); + } +}); + +test("C2 a different body: separate fetches", async () => { + const a = api.analysis(doc(1)); + const b = api.analysis(doc(2)); + await settle(); + assert.equal(pending.length, 2); + for (const p of pending) p.resolve(Response.json({ body: JSON.parse(String(p.init.body)).study })); + assert.deepEqual(await (await a).json(), { body: "s1" }); + assert.deepEqual(await (await b).json(), { body: "s2" }); +}); + +test("C2 the same body with a different query: separate fetches", async () => { + const a = api.analysis(doc(3), { query: "?nocache=1" }); + const b = api.analysis(doc(3)); + const c = api.analysis(doc(3), { query: "?other=1" }); + await settle(); + assert.deepEqual(pending.map((p) => p.url).sort(), ["/api/analysis", "/api/analysis?nocache=1", "/api/analysis?other=1"]); + for (const p of pending) p.resolve(Response.json({ url: p.url })); + assert.deepEqual(await (await a).json(), { url: "/api/analysis?nocache=1" }); + assert.deepEqual(await (await b).json(), { url: "/api/analysis" }); + assert.deepEqual(await (await c).json(), { url: "/api/analysis?other=1" }); +}); + +test("C3 once the shared fetch has answered, an identical call fetches again", async () => { + const a = api.analysis(doc(4)); + await settle(); + assert.equal(pending.length, 1); + pending[0].resolve(Response.json({ round: 1 })); + assert.deepEqual(await (await a).json(), { round: 1 }); + await settle(); + const b = api.analysis(doc(4)); + await settle(); + assert.equal(pending.length, 2, "a second fetch"); + pending[1].resolve(Response.json({ round: 2 })); + assert.deepEqual(await (await b).json(), { round: 2 }); +}); + +test("C3 after a failed fetch, an identical call fetches again", async () => { + const a = api.analysis(doc(8)); + await settle(); + pending[0].reject(new TypeError("network down")); + await assert.rejects(a); + await settle(); + const b = api.analysis(doc(8)); + await settle(); + assert.equal(pending.length, 2); + pending[1].resolve(Response.json({ ok: true })); + assert.deepEqual(await (await b).json(), { ok: true }); +}); + +test("C4 a caller whose signal aborts rejects with an AbortError; the other still gets its response; the fetch kept no signal of it", async () => { + const ctl = new AbortController(); + const a = api.analysis(doc(5), { signal: ctl.signal }); + const b = api.analysis(doc(5)); + await settle(); + assert.equal(pending.length, 1); + const sent = pending[0].init.signal; + assert.ok(sent !== ctl.signal, "the shared fetch is not given a caller's signal"); + ctl.abort(); + await assert.rejects(a, (e: Error) => e.name === "AbortError"); + assert.ok(!sent || !sent.aborted, "the shared fetch is not aborted"); + pending[0].resolve(Response.json({ kept: true })); + assert.deepEqual(await (await b).json(), { kept: true }); +}); + +test("C4 the first caller aborting does not cancel the request for a caller that joined it", async () => { + const ctl = new AbortController(); + const a = api.analysis(doc(9), { signal: ctl.signal }); + await settle(); + const b = api.analysis(doc(9), { signal: new AbortController().signal }); + await settle(); + assert.equal(pending.length, 1); + ctl.abort(); + await assert.rejects(a, (e: Error) => e.name === "AbortError"); + pending[0].resolve(Response.json({ v: 9 })); + assert.deepEqual(await (await b).json(), { v: 9 }); +}); + +test("C4 a signal already aborted rejects at once with an AbortError", async () => { + const ctl = new AbortController(); + ctl.abort(); + const other = api.analysis(doc(6)); + const t0 = Date.now(); + await assert.rejects(api.analysis(doc(6), { signal: ctl.signal }), (e: Error) => e.name === "AbortError"); + assert.ok(Date.now() - t0 < 500, "without waiting for the fetch"); + await settle(); + for (const p of pending) p.resolve(Response.json({})); + await other; +}); + +test("C5 a failing fetch rejects every sharer", async () => { + const a = api.analysis(doc(10)); + const b = api.analysis(doc(10)); + const c = api.analysis(doc(10), { signal: new AbortController().signal }); + await settle(); + assert.equal(pending.length, 1); + const boom = new TypeError("Failed to fetch"); + pending[0].reject(boom); + for (const p of [a, b, c]) await assert.rejects(p, (e: Error) => e.message === "Failed to fetch"); +}); diff --git a/test/lollipop-drivers-fixture.test.ts b/test/lollipop-drivers-fixture.test.ts new file mode 100644 index 00000000..95d22b11 --- /dev/null +++ b/test/lollipop-drivers-fixture.test.ts @@ -0,0 +1,142 @@ +// The lollipop's driver reads, run on the fixture study (test/fixtures/peer-study on connection b), +// against oracles written here from the fixture's own tables: +// L1 hotspotKeysSql(db, [study], genes, pins) gives exactly the (gene, alteration, mutation type) +// keys of the study's mutations that are Cancer Hotspots — a mutation of a gene on the hotspot +// gene list whose variant's stored Genome Nexus record holds a hotspot of its kind (a splice +// mutation a splice-site hotspot; any other a single-residue or in-frame-indel one; 3D never; +// no record, or an empty variant allele, none). Also with a second study id that does not exist. +// L2 the lollipop's driver flags (PatientLevelResolver.lollipopCounts at an OncoKB pin the fixture +// stores) equal: a change is a driver iff its (gene, protein change) is an is_driver MUTATION call +// at the pin, or one of its mutations is a hotspot key — for several genes together and each +// alone (a gene's flags do not change with the other genes asked). +// +// Runs when CLICKHOUSE2_* point at the fixture (`npm run peer-db` prints the lines) and is skipped otherwise. +import { test, describe, before } from "node:test"; +import assert from "node:assert/strict"; +import type { ChConn } from "../lib/ch.ts"; + +const FIXTURE = "cbiolab_peer_fixture"; +/** peer-db.ts stores the fixture's Genome Nexus records and its OncoKB calls under this release */ +const PIN = "fixture"; +process.env.GENOME_NEXUS_PIN = PIN; +process.env.GENOME_NEXUS_GRCH38_PIN = PIN; +delete process.env.CH_RUN_CACHE; +const { secondary, chQuery } = await import("../lib/ch.ts"); +const { hotspotKeysSql, HOTSPOT_GENES } = await import("../lib/hotspots.ts"); +const { PatientLevelResolver } = await import("../lib/federation.ts"); + +const noDb = process.env.CLICKHOUSE2_LABEL === "fixture peer" ? false : "needs the fixture study on connection b: CLICKHOUSE2_* from `npm run peer-db`"; +let conn: ChConn; +const run = async >(sql: string) => (await chQuery(sql, conn)).data; + +type Mut = { gene: string; pc: string; t: string; chr: string; start: number; end: number; ref: string; alt: string }; +let muts: Mut[] = []; +/** the oracle's hotspot keys, "gene|alteration|type" */ +let oracleKeys: string[] = []; +/** OncoKB's driver calls at the pin, "gene|alteration" */ +let oncokbDrivers = new Set(); + +const key = (gene: string, pc: string, t: string) => gene + "|" + pc + "|" + t; +/** the hotspot rule, written from lib/hotspots.ts' header and check-hotspot-drivers' case table */ +function hotspotOracle(gene: string, type: string, hotspots: { type?: string }[]): boolean { + if (!HOTSPOT_GENES.has(gene)) return false; + const kinds = hotspots.map((h) => String(h.type ?? "").toLowerCase()); + if (type.toLowerCase().includes("splice")) return kinds.some((k) => k.includes("splice")); + return kinds.some((k) => k.includes("single residue") || k.includes("in-frame indel") || k.includes("indel")); +} + +before(async () => { + if (noDb) return; + conn = secondary()!; + assert.ok(conn, "CLICKHOUSE2_URL is set but connection b is not configured"); + const db = conn.db; + muts = (await run( + "SELECT g.hugo_gene_symbol AS gene, ifNull(me.protein_change, '') AS pc, ifNull(me.mutation_type, '') AS t, ifNull(me.chr, '') AS chr,\n" + + " ifNull(me.start_position, 0) AS start, ifNull(me.end_position, 0) AS end, ifNull(me.reference_allele, '') AS ref, ifNull(me.tumor_seq_allele, '') AS alt\n" + + "FROM " + db + ".mutation m JOIN " + db + ".mutation_event me ON me.mutation_event_id = m.mutation_event_id\n" + + "JOIN " + db + ".gene g ON g.entrez_gene_id = me.entrez_gene_id\n" + + "JOIN " + db + ".genetic_profile gp ON gp.genetic_profile_id = m.genetic_profile_id\n" + + "JOIN " + db + ".cancer_study cs ON cs.cancer_study_id = gp.cancer_study_id\n" + + "WHERE cs.cancer_study_identifier = '" + FIXTURE + "'")).map((m) => ({ ...m, start: Number(m.start), end: Number(m.end) })); + const records = await run<{ chr: string; start: number; end: number; ref: string; alt: string; data: string }>( + "SELECT chr, start_position AS start, end_position AS end, reference_allele AS ref, variant_allele AS alt, data FROM annotation.variant WHERE source = 'genome_nexus' AND version = '" + PIN + "'"); + const loc = (chr: string, start: number, end: number, ref: string, alt: string) => [chr.replace(/^chr/i, ""), Number(start), Number(end), ref, alt].join(":"); + const byLoc = new Map(records.map((r) => [loc(r.chr, r.start, r.end, r.ref, r.alt), (JSON.parse(r.data).hotspots ?? []) as { type?: string }[]])); + const keys = new Set(); + for (const m of muts) { + if (!m.alt) continue; + const hs = byLoc.get(loc(m.chr, m.start, m.end, m.ref, m.alt)); + if (hs && hotspotOracle(m.gene, m.t, hs)) keys.add(key(m.gene, m.pc, m.t)); + } + oracleKeys = [...keys].sort(); + oncokbDrivers = new Set((await run<{ g: string; a: string }>( + "SELECT hugo_gene_symbol AS g, alteration AS a FROM annotation.oncokb WHERE oncokb_version = '" + PIN + "' AND alteration_type = 'MUTATION' AND is_driver")).map((r) => r.g + "|" + r.a)); +}); + +const keysOf = async (studies: string[], genes: string[] | null) => { + const sql = hotspotKeysSql(conn.db, studies, genes, { hg19: PIN, hg38: null }); + assert.ok(sql, "SQL with the GRCh37 pin set"); + return (await run(sql)).map((r) => Object.values(r).map((v) => String(v ?? "")).join("|")).sort(); +}; + +describe("L1 hotspotKeysSql on the fixture", () => { + test("the oracle finds the fixture's hotspot cases (the comparison says something)", { skip: noDb }, () => { + assert.ok(muts.length > 50, muts.length + " mutations"); + for (const k of ["PIK3CA|H1047R|Missense_Mutation", "STK11|X200_splice|Splice_Site", "PTEN|R130G|Missense_Mutation"]) assert.ok(oracleKeys.includes(k), k + " in " + oracleKeys.join(", ")); + for (const k of ["H3-3A|G35R|Missense_Mutation", "ATM|A1100S|Missense_Mutation", "BRAF|G469A|Missense_Mutation", "SMARCA4|X500_splice|Splice_Site"]) assert.ok(!oracleKeys.includes(k), k); + }); + + test("every gene: exactly the oracle's keys, each once", { skip: noDb }, async () => { + const got = await keysOf([FIXTURE], null); + assert.deepEqual(got, oracleKeys); + assert.equal(new Set(got).size, got.length); + }); + + test("with a second study id that does not exist: the same keys", { skip: noDb }, async () => { + assert.deepEqual(await keysOf([FIXTURE, "no_such_study"], null), oracleKeys); + assert.deepEqual(await keysOf(["no_such_study", FIXTURE], null), oracleKeys); + }); + + for (const genes of [["PIK3CA"], ["KRAS", "TP53", "EGFR"], ["BRAF", "STK11", "ATM"], ["KRAS", "TP53", "EGFR", "BRAF", "PIK3CA", "PTEN"]]) { + test("genes " + genes.join(", ") + ": the oracle's keys of those genes", { skip: noDb }, async () => { + const want = oracleKeys.filter((k) => genes.includes(k.split("|")[0])); + assert.deepEqual(await keysOf([FIXTURE], genes), want); + assert.deepEqual(await keysOf([FIXTURE, "no_such_study"], genes), want); + }); + } +}); + +describe("L2 the lollipop's driver flags on the fixture", () => { + const GENES = ["KRAS", "TP53", "EGFR", "BRAF", "PIK3CA"]; + const resolver = () => new PatientLevelResolver(FIXTURE, { oncokbPin: PIN }, { id: "b-lollipop", mode: "patient-level", label: "fixture", conn: { ...conn, id: "b-lollipop" } } as never); + /** a change is a driver iff OncoKB calls it one at the pin or one of its mutations is a hotspot */ + const expected = (gene: string, change: string) => + oncokbDrivers.has(gene + "|" + change) || muts.some((m) => m.gene === gene && m.pc === change && oracleKeys.includes(key(m.gene, m.pc, m.t))); + const flags = async (genes: string[]) => { + const rep = await resolver().lollipopCounts(null, genes, 1); + assert.equal(rep.annotated, true, "annotated at the pin"); + return new Map(rep.changes.map((c) => [c.gene + "|" + c.change, c.driver])); + }; + let together = new Map(); + + test(GENES.join(", ") + " together: every change's flag is the oracle's", { skip: noDb }, async () => { + together = await flags(GENES); + assert.ok(together.size > 10, together.size + " changes"); + const wrong = [...together].filter(([k, d]) => d !== expected(k.split("|")[0], k.split("|").slice(1).join("|"))); + assert.deepEqual(wrong, [], "flags that differ from the oracle"); + assert.ok([...together.values()].some((d) => d) && [...together.values()].some((d) => !d), "both kinds occur"); + const hotOnly = [...together.keys()].filter((k) => { const [g, ...c] = k.split("|"); return !oncokbDrivers.has(k) && expected(g, c.join("|")); }); + assert.ok(hotOnly.length >= 1, "a change that is a driver by hotspot alone: " + hotOnly.join(", ")); + }); + + for (const gene of GENES) { + test(gene + " alone: the same flags as with the others, and the oracle's", { skip: noDb }, async () => { + if (!together.size) together = await flags(GENES); + const alone = await flags([gene]); + const mine = new Map([...together].filter(([k]) => k.startsWith(gene + "|"))); + assert.deepEqual(new Map([...alone].sort()), new Map([...mine].sort())); + for (const [k, d] of alone) assert.equal(d, expected(gene, k.slice(gene.length + 1)), k); + if (["KRAS", "TP53", "EGFR"].includes(gene)) assert.ok(alone.size > 0, gene + " has mutations in the fixture"); + }); + } +}); diff --git a/test/mutation-default-columns.test.ts b/test/mutation-default-columns.test.ts index 3fe0cc26..0f959bd4 100644 --- a/test/mutation-default-columns.test.ts +++ b/test/mutation-default-columns.test.ts @@ -232,16 +232,37 @@ test("R7 the facts' values queries are asked with an empty query, even when the assert.ok(calls.page.length && calls.page.every((c) => c.q.search === "G12" && !!c.q.filters?.cancerType), "the page itself keeps the view's query: " + JSON.stringify(calls.page.map((c) => c.q))); }); -test("R8 the page and counts queries receive the facts' defaults", async () => { +test("R8 with a search, the page and counts queries receive the facts' defaults", async () => { const calls = newCalls(); - await run({ s1: { catalog: [MUTATIONS, DISCRETE_CNA], answers: { vaf: VAF_NONE, cancerType: TWO_TYPES } } }, {}, calls); + await run({ s1: { catalog: [MUTATIONS, DISCRETE_CNA], answers: { vaf: VAF_NONE, cancerType: TWO_TYPES } } }, { search: "G12" }, calls); assert.ok(calls.page.length >= 1 && calls.counts.length >= 1, "rowsPage " + calls.page.length + ", rowsCounts " + calls.counts.length); for (const c of [...calls.page, ...calls.counts]) assert.deepEqual(c.defaults, without("vaf"), c.label); const none = newCalls(); - await run({ s1: { catalog: [MUTATIONS], answers: { vaf: VAF_NONE, cancerType: ONE_TYPE } } }, {}, none); + await run({ s1: { catalog: [MUTATIONS], answers: { vaf: VAF_NONE, cancerType: ONE_TYPE } } }, { search: "G12" }, none); + assert.ok(none.page.length >= 1 && none.counts.length >= 1); for (const c of [...none.page, ...none.counts]) assert.deepEqual(c.defaults, ["sample", "proteinChange", "annotation", "mutationType", "mutCount"], c.label); }); +test("R8b without a search, the counts are asked with the fact columns and, when they answer them, no values query runs", async () => { + const calls = newCalls(); + const st = standIn("Q", "s1", {}, calls); + const counts = st.rowsCounts; + const asked: unknown[] = []; + const withSums = async (label: string, src: unknown, q: TableQuery, defaults: string[], summarize?: unknown) => { + asked.push(summarize); + const rows = await counts(label, src, q, defaults); + return rows.map((r) => ({ ...r, sums: [{ column: "vaf", numeric: true, min: null, max: null }, { column: "cancerType", numeric: false, values: ["Colon Adenocarcinoma", "Rectal Adenocarcinoma"], truncated: false }] })); + }; + const ctx = ctxFor({ s1: { catalog: [MUTATIONS, DISCRETE_CNA], answers: keep } }, calls); + ctx.resolvers = { s1: { ...st, rowsCounts: withSums } } as never; + const r = await runMutations({ kind: "mutations", gene: "KRAS", cohorts: ["Q"], rows: 100 } as MutationsView, ctx); + const res = (r instanceof Untimed ? r.result : r) as ViewResult & { mutations?: Mutations; error?: string }; + assert.equal(res.error, undefined); + assert.ok(asked.some((a) => JSON.stringify(a) === JSON.stringify([{ column: "vaf", numeric: true }, { column: "cancerType", numeric: false }])), JSON.stringify(asked)); + assert.equal(calls.values.length, 0, "rowsValues called: " + JSON.stringify(calls.values.map((c) => c.column))); + assert.deepEqual(res.mutations!.defaults, without("vaf"), "the defaults follow the counts' summaries, not the values answers"); +}); + test("R9 a study whose peer did not describe its profiles (unanswered) leaves Copy # unknown, so kept; a mutations-only catalog drops it", async () => { const { m } = await run({ s1: { catalog: [], unanswered: true, answers: keep } }); assert.ok(m.defaults.includes("copyNumber"), m.defaults.join(",")); diff --git a/test/mutation-facts.test.ts b/test/mutation-facts.test.ts new file mode 100644 index 00000000..edb65031 --- /dev/null +++ b/test/mutation-facts.test.ts @@ -0,0 +1,328 @@ +// The Mutations view's default-column facts taken from the counts' summaries, and the order of its +// queries (lib/views/mutations/run.ts runMutations, lib/views/mutation-defaults.ts). The rules for +// the defaults themselves are test/mutation-default-columns.test.ts's (R4: Allele Freq (T) is kept +// when some row has a non-zero frequency; R5: Cancer Type Detailed when more than one distinct +// non-empty type); here, where the facts come from and when each query is asked: +// M1 no search, first page, no values: the facts come from the counts' summaries; rowsValues is +// not called; rowsCounts is asked with summarize = MUTATION_FACT_COLUMNS; R4/R5's rules hold +// (a truncated cancer-type list keeps the column; types union across databases) +// M2 no search, counts without `sums` (an older backend): the facts fall back to rowsValues for vaf +// and cancerType, with an empty query, giving the same defaults +// M3 with a search: the facts' values are asked first (empty query); the page and counts get the +// facts' defaults +// M4 the clinical Freq is asked before the rows' counts answer +// M5 a later page or a column's values: no Freq; in values mode without a search the facts are +// asked as values queries and the defaults still follow them +// M6 a failing Freq refuses the view with its message; a failing count refuses the view +// The stand-in harness is test/mutation-default-columns.test.ts's, extended. +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { runMutations } from "../lib/views/mutations/run.ts"; +import * as mutationDefaultsModule from "../lib/views/mutation-defaults.ts"; +import { Untimed, type ViewRun, type EvaluatedCohort } from "../lib/views/run.ts"; +import type { ViewParticipation, ViewResult } from "../lib/types.ts"; +import type { MutationsView } from "../lib/views/mutations/types.ts"; +import type { ProfileInfo } from "../lib/profile-catalog.ts"; +import type { TableQuery } from "../lib/table-query.ts"; + +process.env.GENOME_NEXUS_PIN = "gn-hg19"; +process.env.GENOME_NEXUS_GRCH38_PIN = "gn-hg38"; + +const realFetch = globalThis.fetch; +before(() => { globalThis.fetch = (async () => new Response("", { status: 404 })) as typeof fetch; }); +after(() => { globalThis.fetch = realFetch; }); + +const ALL = ["sample", "cancerType", "proteinChange", "annotation", "mutationType", "copyNumber", "vaf", "mutCount"]; +const without = (...ids: string[]) => ALL.filter((id) => !ids.includes(id)); +const FACT_COLUMNS = [{ column: "vaf", numeric: true }, { column: "cancerType", numeric: false }]; + +const DISCRETE_CNA: ProfileInfo = { profile: "gistic", type: "COPY_NUMBER_ALTERATION", datatype: "DISCRETE", name: "Putative copy-number alterations from GISTIC", order: 0 }; +const MUTATIONS: ProfileInfo = { profile: "mutations", type: "MUTATION_EXTENDED", datatype: "MAF", name: "Mutations", order: 4 }; +const CAT = [MUTATIONS, DISCRETE_CNA]; + +type Summary = + | { column: string; numeric: true; min: number | null; max: number | null } + | { column: string; numeric: false; values: string[]; truncated: boolean }; +/** what rowsValues answers per column: numeric "vaf" as [{lo, hi, n}], text "cancerType" as [{v, n}] */ +type Answers = { vaf?: Record[]; cancerType?: Record[] }; +const VAF_SOME = [{ lo: 0.003, hi: 0.31, n: 4 }]; +const VAF_NONE: Record[] = []; +const TWO_TYPES = [{ v: "Colon Adenocarcinoma", n: 3 }, { v: "Rectal Adenocarcinoma", n: 2 }]; +const ONE_TYPE = [{ v: "Colon Adenocarcinoma", n: 5 }]; + +/** the counts' summaries that say what `answers` say */ +function sumsOf(a: Answers, truncated = false): Summary[] { + const v = (a.vaf ?? []).filter((r) => Number(r.n) > 0); + return [ + { column: "vaf", numeric: true, min: v.length ? Math.min(...v.map((r) => Number(r.lo))) : null, max: v.length ? Math.max(...v.map((r) => Number(r.hi))) : null }, + { column: "cancerType", numeric: false, values: (a.cancerType ?? []).map((r) => String(r.v)), truncated }, + ]; +} + +type Call = { label: string; q: TableQuery; defaults: string[]; column?: string; summarize?: unknown }; +type Calls = { values: Call[]; page: Call[]; counts: Call[]; freq: string[]; events: string[] }; +const newCalls = (): Calls => ({ values: [], page: [], counts: [], freq: [], events: [] }); + +type StudySetup = { + catalog?: ProfileInfo[]; answers: Answers; conn?: string; rows?: Record[]; + /** the counts' sums for this study: given, or none (an older backend's count) */ + sums?: Summary[]; + /** the count waits on this before answering */ + countsWait?: () => Promise; + countsFails?: Error; freqFails?: Error; +}; + +function standIn(cohort: string, study: string, s: StudySetup, calls: Calls, sameDb: [string, StudySetup][] = [[study, s]]) { + const conn = s.conn ?? "c1"; + const rows = s.rows ?? [{ sid: study + "-S1", vaf: 0.3, vafText: "0.30" }]; + return { + instance: { id: conn, mode: "patient-level", label: "Local " + conn, conn: { id: conn, db: conn } }, + cohortSql: () => "SELECT 1", + viewMeta: async () => [], + viewAggregate: async (label: string) => { + calls.events.push("aggregate:" + label); + if (label === "mutations:clinical-freq") { + calls.freq.push(study); + if (s.freqFails) throw s.freqFails; + return [{ a: "", n: 10 }]; + } + return []; + }, + lollipopCounts: async () => ({ changes: [], types: [], totals: [], cohortSamples: 10, minCount: 1, annotated: true }), + rowsPage: async (label: string, _src: unknown, q: TableQuery, defaults: string[]) => { + calls.events.push("page"); + calls.page.push({ label, q, defaults }); + return { rows: rows.map((r) => ({ cohort, study, patient: String(r.sid), ...r })), total: rows.length }; + }, + rowsCounts: async (label: string, _src: unknown, q: TableQuery, defaults: string[], summarize?: unknown) => { + calls.events.push("counts-asked"); + calls.counts.push({ label, q, defaults, summarize }); + if (s.countsWait) await s.countsWait(); + if (s.countsFails) throw s.countsFails; + calls.events.push("counts-done"); + const asked = Array.isArray(summarize) && summarize.length > 0; + // one count per database: it answers for every study held there, as a real one does + return sameDb.map(([st, x]) => { + const n = (x.rows ?? [1]).length; + return { cohort, study: st, n, all: n, ...(asked && x.sums ? { sums: x.sums } : {}) }; + }); + }, + rowsValues: async (label: string, _src: unknown, q: TableQuery, defaults: string[], column: string) => { + calls.events.push("values:" + column); + calls.values.push({ label, q, defaults, column }); + return column === "vaf" ? s.answers.vaf ?? [] : column === "cancerType" ? s.answers.cancerType ?? [] : [{ v: "G12D", n: 1 }]; + }, + rowsRank: async () => null, + }; +} + +function ctxFor(studies: Record, calls: Calls, extra: Partial = {}): ViewRun { + const ids = Object.keys(studies); + const cohort: EvaluatedCohort = { studies: ids, perStudy: Object.fromEntries(ids.map((s) => [s, { sql: "", count: 10, samples: 10, mode: "" }])), count: 10 * ids.length, samples: 10 * ids.length, text: "" }; + return { + doc: { study: ids[0], cohorts: { Q: { study: ids[0] } }, views: [] } as never, + cohorts: { Q: cohort }, + resolvers: Object.fromEntries(ids.map((s) => [s, standIn("Q", s, studies[s], calls, ids.filter((o) => (studies[o].conn ?? "c1") === (studies[s].conn ?? "c1")).map((o) => [o, studies[o]]))])) as never, + vNames: ["Q"], vStudies: ids, + participationFor: (_s: string[], requiresPatientLevel: boolean): ViewParticipation => ({ studies: [], requiresPatientLevel, aggregateOnly: [] }), + pin: "v7", + studyProfiles: async (study: string) => ({ profiles: ["mutations"], gaProfiles: [], ...(studies[study].catalog ? { catalog: studies[study].catalog } : {}) }), + ...extra, + }; +} + +type Mutations = { shown: string[]; defaults: string[]; rows: { sample: string; values: (string | number | null)[] }[] }; +async function attempt(studies: Record, view: Partial = {}, calls = newCalls(), extra: Partial = {}) { + try { + const r = await runMutations({ kind: "mutations", gene: "KRAS", cohorts: ["Q"], rows: 100, ...view } as MutationsView, ctxFor(studies, calls, extra)); + const res = (r instanceof Untimed ? r.result : r) as ViewResult & { mutations?: Mutations; error?: string }; + return { res, error: res.error, calls }; + } catch (e) { + return { res: undefined, error: String((e as Error)?.message ?? e), calls }; + } +} +async function run(studies: Record, view: Partial = {}, calls = newCalls(), extra: Partial = {}) { + const { res, error } = await attempt(studies, view, calls, extra); + assert.equal(error, undefined, JSON.stringify(res ?? error).slice(0, 300)); + return { res: res!, m: res!.mutations!, calls }; +} +/** a study whose counts carry the summaries of `answers`, and whose values queries would say the same */ +const viaSums = (answers: Answers, more: Partial = {}): StudySetup => ({ catalog: CAT, answers, sums: sumsOf(answers), ...more }); +const factsAskedAsValues = (calls: Calls) => calls.values.filter((c) => c.column === "vaf" || c.column === "cancerType"); + +// ---- M1: the facts from the counts' summaries ------------------------------------------------------ + +test("M1 MUTATION_FACT_COLUMNS is vaf (numeric) and cancerType (text)", () => { + assert.deepEqual((mutationDefaultsModule as Record).MUTATION_FACT_COLUMNS, FACT_COLUMNS); +}); + +test("M1 no search, first page: the counts are asked with the fact columns, and no values query runs", async () => { + const calls = newCalls(); + const { m } = await run({ s1: viaSums({ vaf: VAF_SOME, cancerType: TWO_TYPES }) }, {}, calls); + assert.equal(calls.values.length, 0, "rowsValues called: " + JSON.stringify(calls.values.map((c) => c.column))); + assert.ok(calls.counts.length >= 1); + assert.ok(calls.counts.some((c) => JSON.stringify(c.summarize) === JSON.stringify(FACT_COLUMNS)), JSON.stringify(calls.counts.map((c) => c.summarize))); + assert.deepEqual(m.defaults, ALL); +}); + +test("M1 filters and a sort but no search: still from the summaries", async () => { + const calls = newCalls(); + const { m } = await run({ s1: viaSums({ vaf: VAF_NONE, cancerType: TWO_TYPES }) }, { filters: { cancerType: { values: ["Colon Adenocarcinoma"] } }, sort: { column: "proteinChange" } }, calls); + assert.equal(factsAskedAsValues(calls).length, 0, JSON.stringify(calls.values.map((c) => c.column))); + assert.deepEqual(m.defaults, without("vaf")); +}); + +test("M1 Allele Freq (T) from the summaries: max null or 0 drops it; 0.003 keeps it; one of two databases with one keeps it", async (t) => { + const cases: [string, Record, string[]][] = [ + ["no row has one (max null)", { s1: viaSums({ vaf: VAF_NONE, cancerType: TWO_TYPES }) }, without("vaf")], + ["a frequency of 0 is no frequency", { s1: viaSums({ vaf: [{ lo: 0, hi: 0, n: 3 }], cancerType: TWO_TYPES }) }, without("vaf")], + ["max 0.003", { s1: viaSums({ vaf: [{ lo: 0.003, hi: 0.003, n: 1 }], cancerType: TWO_TYPES }) }, ALL], + ["one of two databases has one", { s1: viaSums({ vaf: VAF_NONE, cancerType: TWO_TYPES }), s2: viaSums({ vaf: VAF_SOME, cancerType: TWO_TYPES }, { conn: "c2" }) }, ALL], + ]; + for (const [name, studies, want] of cases) { + await t.test(name, async () => { + const calls = newCalls(); + const { m } = await run(studies, {}, calls); + assert.equal(calls.values.length, 0, "no values query"); + assert.deepEqual(m.defaults, want); + }); + } +}); + +test("M1 Cancer Type Detailed from the summaries: '' is not a type; two keep it; a truncated list keeps it; types union across databases", async (t) => { + const cases: [string, Record, string[]][] = [ + ['["", "Colon Adenocarcinoma"]: one type', { s1: viaSums({ vaf: VAF_SOME, cancerType: [{ v: "", n: 4 }, { v: "Colon Adenocarcinoma", n: 2 }] }) }, without("cancerType")], + ["one type only", { s1: viaSums({ vaf: VAF_SOME, cancerType: ONE_TYPE }) }, without("cancerType")], + ["no types", { s1: viaSums({ vaf: VAF_SOME, cancerType: [] }) }, without("cancerType")], + ["two types", { s1: viaSums({ vaf: VAF_SOME, cancerType: TWO_TYPES }) }, ALL], + ["a truncated list", { s1: { catalog: CAT, answers: {}, sums: sumsOf({ vaf: VAF_SOME, cancerType: ONE_TYPE }, true) } }, ALL], + ["one type in each of two databases, different", { s1: viaSums({ vaf: VAF_SOME, cancerType: [{ v: "Colon Adenocarcinoma", n: 1 }] }), + s2: viaSums({ vaf: VAF_SOME, cancerType: [{ v: "Rectal Adenocarcinoma", n: 1 }] }, { conn: "c2" }) }, ALL], + ["the same one type in each of two databases", { s1: viaSums({ vaf: VAF_SOME, cancerType: ONE_TYPE }), s2: viaSums({ vaf: VAF_SOME, cancerType: ONE_TYPE }, { conn: "c2" }) }, without("cancerType")], + ["two studies in one database, one type each, different", { s1: viaSums({ vaf: VAF_SOME, cancerType: [{ v: "Colon Adenocarcinoma", n: 1 }] }), + s2: viaSums({ vaf: VAF_SOME, cancerType: [{ v: "Rectal Adenocarcinoma", n: 1 }] }) }, ALL], + ]; + for (const [name, studies, want] of cases) { + await t.test(name, async () => { + const calls = newCalls(); + const { m } = await run(studies, {}, calls); + assert.equal(calls.values.length, 0, "no values query"); + assert.deepEqual(m.defaults, want); + }); + } +}); + +test("M1 the page and counts receive the summaries' defaults, shown follows them", async () => { + const calls = newCalls(); + const { m } = await run({ s1: viaSums({ vaf: VAF_NONE, cancerType: ONE_TYPE }) }, {}, calls); + assert.deepEqual(m.defaults, without("vaf", "cancerType")); + assert.deepEqual(m.shown, without("vaf", "cancerType")); +}); + +// ---- M2: counts without sums ------------------------------------------------------------------- + +test("M2 no search, counts without sums: the facts are asked as values queries with an empty query, same defaults", async (t) => { + const cases: [string, Answers, string[]][] = [ + ["no frequency, two types", { vaf: VAF_NONE, cancerType: TWO_TYPES }, without("vaf")], + ["a frequency, one type", { vaf: VAF_SOME, cancerType: ONE_TYPE }, without("cancerType")], + ["both", { vaf: VAF_SOME, cancerType: TWO_TYPES }, ALL], + ]; + for (const [name, answers, want] of cases) { + await t.test(name, async () => { + const calls = newCalls(); + const { m } = await run({ s1: { catalog: CAT, answers } }, { filters: { mutationType: { values: ["Missense_Mutation"] } } }, calls); + assert.deepEqual(m.defaults, want); + for (const col of ["vaf", "cancerType"]) { + const asked = calls.values.filter((c) => c.column === col); + assert.ok(asked.length >= 1, col + " asked: " + JSON.stringify(calls.values.map((c) => c.column))); + for (const c of asked) { + assert.ok(!(c.q.search || "").trim(), col + " with a search"); + assert.deepEqual(Object.keys(c.q.filters || {}), [], col + " with filters"); + } + } + }); + } +}); + +test("M2 one database's counts carry sums and another's do not: the facts still reach every database", async () => { + const calls = newCalls(); + const { m } = await run({ s1: viaSums({ vaf: VAF_NONE, cancerType: ONE_TYPE }), s2: { catalog: CAT, answers: { vaf: VAF_SOME, cancerType: [{ v: "Rectal Adenocarcinoma", n: 1 }] }, conn: "c2" } }, {}, calls); + assert.deepEqual(m.defaults, ALL, "s2's frequency and second type count"); +}); + +// ---- M3: with a search ----------------------------------------------------------------------------- + +test("M3 with a search: the facts' values are asked first, with an empty query; page and counts get their defaults", async () => { + const calls = newCalls(); + await run({ s1: viaSums({ vaf: VAF_NONE, cancerType: TWO_TYPES }) }, { search: "G12" }, calls); + const firstFact = calls.events.findIndex((e) => e === "values:vaf" || e === "values:cancerType"); + const firstRows = calls.events.findIndex((e) => e === "page" || e === "counts-asked"); + assert.ok(firstFact >= 0, "the facts are asked as values: " + calls.events.join(", ")); + assert.ok(firstRows > firstFact, "before the page and counts: " + calls.events.join(", ")); + for (const c of factsAskedAsValues(calls)) assert.ok(!(c.q.search || "").trim(), "the facts' query has no search: " + JSON.stringify(c.q)); + assert.ok(calls.page.length >= 1 && calls.counts.length >= 1); + for (const c of [...calls.page, ...calls.counts]) assert.deepEqual(c.defaults, without("vaf"), c.label); + assert.ok(calls.page.every((c) => c.q.search === "G12"), "the page keeps the search"); +}); + +// ---- M4: the clinical Freq beside the rows --------------------------------------------------------- + +test("M4 the clinical Freq is asked before the rows' counts answer", async () => { + const calls = newCalls(); + let freqBefore = false; + const waitForFreq = async () => { + for (let i = 0; i < 150 && !calls.freq.length; i++) await new Promise((r) => setTimeout(r, 10)); + freqBefore = calls.freq.length > 0; + }; + const t0 = Date.now(); + await run({ s1: viaSums({ vaf: VAF_SOME, cancerType: TWO_TYPES }, { countsWait: waitForFreq }) }, {}, calls); + assert.ok(calls.freq.length >= 1, "the Freq was asked: " + calls.events.join(", ")); + assert.ok(freqBefore, "the Freq was asked while the counts were still waiting: " + calls.events.join(", ")); + assert.ok(Date.now() - t0 < 1400, "no wait for the timeout"); +}); + +// ---- M5: later pages and values mode --------------------------------------------------------------- + +test("M5 a later page: no clinical Freq", async () => { + const calls = newCalls(); + await run({ s1: viaSums({ vaf: VAF_SOME, cancerType: TWO_TYPES }) }, {}, calls, { page: { offset: 100, limit: 100 } }); + assert.deepEqual(calls.freq, []); +}); + +test("M5 a column's values without a search: no Freq; the facts are asked as values queries and the result's defaults follow them", async () => { + const calls = newCalls(); + const { res, error } = await attempt({ s1: viaSums({ vaf: VAF_NONE, cancerType: TWO_TYPES }) }, {}, calls, { values: "proteinChange" }); + assert.equal(error, undefined); + assert.deepEqual(calls.freq, []); + for (const col of ["vaf", "cancerType"]) assert.ok(calls.values.some((c) => c.column === col && !(c.q.search || "").trim()), col + " asked: " + calls.events.join(", ")); + assert.ok(calls.values.some((c) => c.column === "proteinChange"), "the column's values were asked: " + calls.events.join(", ")); + const m = res?.mutations as (Mutations & { defaults?: string[] }) | undefined; + if (m?.defaults) assert.deepEqual(m.defaults, without("vaf"), "the result's defaults"); +}); + +test("M5 a column's values with a search: the facts are asked first, and the column's values query gets their defaults", async () => { + const calls = newCalls(); + const { error } = await attempt({ s1: viaSums({ vaf: VAF_NONE, cancerType: TWO_TYPES }) }, { search: "G12" }, calls, { values: "proteinChange" }); + assert.equal(error, undefined); + assert.deepEqual(calls.freq, []); + const firstFact = calls.events.findIndex((e) => e === "values:vaf" || e === "values:cancerType"); + const col = calls.events.indexOf("values:proteinChange"); + assert.ok(firstFact >= 0 && col > firstFact, calls.events.join(", ")); + for (const c of calls.values.filter((x) => x.column === "proteinChange")) { + assert.equal(c.q.search, "G12"); + assert.deepEqual(c.defaults, without("vaf")); + } +}); + +// ---- M6: failures ---------------------------------------------------------------------------------- + +test("M6 a failing Freq refuses the view with its message", async () => { + const { error } = await attempt({ s1: viaSums({ vaf: VAF_SOME, cancerType: TWO_TYPES }, { freqFails: new Error("freq broke here") }) }); + assert.ok(error && error.includes("freq broke here"), "refused with the Freq's message: " + error); +}); + +test("M6 a failing count refuses the view", async () => { + const { error } = await attempt({ s1: viaSums({ vaf: VAF_SOME, cancerType: TWO_TYPES }, { countsFails: new Error("counts broke here") }) }); + assert.ok(error, "the view is refused"); + assert.ok(error.includes("counts broke here"), error); +}); diff --git a/test/snapshots/answers/hotspots.json.gz b/test/snapshots/answers/hotspots.json.gz index 10edaa4f..2f86d257 100644 Binary files a/test/snapshots/answers/hotspots.json.gz and b/test/snapshots/answers/hotspots.json.gz differ diff --git a/test/snapshots/answers/mutations.json.gz b/test/snapshots/answers/mutations.json.gz index 02ed173f..ea983846 100644 Binary files a/test/snapshots/answers/mutations.json.gz and b/test/snapshots/answers/mutations.json.gz differ diff --git a/test/snapshots/answers/mutcompare.json.gz b/test/snapshots/answers/mutcompare.json.gz index 7d082f1f..2f5f7787 100644 Binary files a/test/snapshots/answers/mutcompare.json.gz and b/test/snapshots/answers/mutcompare.json.gz differ diff --git a/test/snapshots/answers/timeline.json.gz b/test/snapshots/answers/timeline.json.gz index c9a4d3b5..1fbdf01a 100644 Binary files a/test/snapshots/answers/timeline.json.gz and b/test/snapshots/answers/timeline.json.gz differ diff --git a/test/snapshots/hotspots.sql b/test/snapshots/hotspots.sql index e0d2e063..2212dd4b 100644 --- a/test/snapshots/hotspots.sql +++ b/test/snapshots/hotspots.sql @@ -56,7 +56,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic AND smp.stable_id IN (SELECT sid FROM cohort)), m AS (SELECT `GENE.hugoGeneSymbol` AS gene, proteinPosStart AS pos, proteinChange AS change, mutationType AS mtype, patientId AS pid, sampleId AS sid, mutationStatus AS status, if((`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM annotation.oncokb - WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION') + WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN ('KRAS','BRAF','PIK3CA','TP53')) OR (`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (SELECT DISTINCT mu.hugo_gene_symbol AS hugo_gene_symbol, mu.alteration AS alteration, mu.mutation_type AS mutation_type FROM ( SELECT m.`GENE.hugoGeneSymbol` AS hugo_gene_symbol, m.proteinChange AS alteration, ifNull(m.mutationType, '') AS mutation_type, st.src AS src, assumeNotNull(m.chr) AS chr, m.startPosition AS start, m.endPosition AS end, @@ -65,7 +65,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic INNER JOIN (SELECT cs.cancer_study_identifier AS study, multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') AS src FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier IN ('msk_chord_2024')) st ON st.study = m.studyId - WHERE m.studyId IN ('msk_chord_2024') AND m.`GENE.hugoGeneSymbol` IN ('KRAS', 'BRAF', 'PIK3CA', 'TP53') + WHERE (startsWith(m.molecularProfileId, 'msk_chord_2024_')) AND m.studyId IN ('msk_chord_2024') AND m.`GENE.hugoGeneSymbol` IN ('KRAS', 'BRAF', 'PIK3CA', 'TP53') AND st.src != '' AND ifNull(m.chr, '') != '' AND ifNull(m.startPosition, 0) != 0 AND ifNull(m.endPosition, 0) != 0 AND ifNull(m.referenceAllele, '') != '' AND ifNull(m.tumorSeqAllele, '') != '' AND ifNull(m.proteinChange, '') != '' ) mu @@ -206,7 +206,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic AND smp.stable_id IN (SELECT sid FROM cohort)), m AS (SELECT `GENE.hugoGeneSymbol` AS gene, proteinPosStart AS pos, proteinChange AS change, mutationType AS mtype, patientId AS pid, sampleId AS sid, mutationStatus AS status, if((`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM annotation.oncokb - WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION') + WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN ('KRAS','BRAF','PIK3CA','TP53')) OR (`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (SELECT DISTINCT mu.hugo_gene_symbol AS hugo_gene_symbol, mu.alteration AS alteration, mu.mutation_type AS mutation_type FROM ( SELECT m.`GENE.hugoGeneSymbol` AS hugo_gene_symbol, m.proteinChange AS alteration, ifNull(m.mutationType, '') AS mutation_type, st.src AS src, assumeNotNull(m.chr) AS chr, m.startPosition AS start, m.endPosition AS end, @@ -215,7 +215,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic INNER JOIN (SELECT cs.cancer_study_identifier AS study, multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') AS src FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier IN ('msk_chord_2024')) st ON st.study = m.studyId - WHERE m.studyId IN ('msk_chord_2024') AND m.`GENE.hugoGeneSymbol` IN ('KRAS', 'BRAF', 'PIK3CA', 'TP53') + WHERE (startsWith(m.molecularProfileId, 'msk_chord_2024_')) AND m.studyId IN ('msk_chord_2024') AND m.`GENE.hugoGeneSymbol` IN ('KRAS', 'BRAF', 'PIK3CA', 'TP53') AND st.src != '' AND ifNull(m.chr, '') != '' AND ifNull(m.startPosition, 0) != 0 AND ifNull(m.endPosition, 0) != 0 AND ifNull(m.referenceAllele, '') != '' AND ifNull(m.tumorSeqAllele, '') != '' AND ifNull(m.proteinChange, '') != '' ) mu diff --git a/test/snapshots/mutations.sql b/test/snapshots/mutations.sql index 2181359e..63a28a77 100644 --- a/test/snapshots/mutations.sql +++ b/test/snapshots/mutations.sql @@ -248,7 +248,7 @@ clinp AS ( ), rows AS (SELECT r.*, cs.m AS clinS, cp.m AS clinP FROM rows0 AS r LEFT JOIN clins AS cs ON cs.st = r.study AND cs.k = r.sid LEFT JOIN clinp AS cp ON cp.st = r.study AND cp.k = r.patient) -SELECT cohort, study, countIf((match(ifNull(toString(proteinChange), ''), '^G1[23]')) AND (CAST(vaf AS Nullable(Float64)) IS NOT NULL AND CAST(vaf AS Nullable(Float64)) >= 0.2)) AS n, count() AS all, count() - uniqExact((study, patient, ifNull(proteinChange, ''))) AS dup, uniqExactIf(sid, (match(ifNull(toString(proteinChange), ''), '^G1[23]')) AND (CAST(vaf AS Nullable(Float64)) IS NOT NULL AND CAST(vaf AS Nullable(Float64)) >= 0.2)) AS ns, uniqExactIf(patient, (match(ifNull(toString(proteinChange), ''), '^G1[23]')) AND (CAST(vaf AS Nullable(Float64)) IS NOT NULL AND CAST(vaf AS Nullable(Float64)) >= 0.2)) AS np FROM rows GROUP BY cohort, study +SELECT cohort, study, countIf((match(ifNull(toString(proteinChange), ''), '^G1[23]')) AND (CAST(vaf AS Nullable(Float64)) IS NOT NULL AND CAST(vaf AS Nullable(Float64)) >= 0.2)) AS n, count() AS all, count() - uniqExact((study, patient, ifNull(proteinChange, ''))) AS dup, uniqExactIf(sid, (match(ifNull(toString(proteinChange), ''), '^G1[23]')) AND (CAST(vaf AS Nullable(Float64)) IS NOT NULL AND CAST(vaf AS Nullable(Float64)) >= 0.2)) AS ns, uniqExactIf(patient, (match(ifNull(toString(proteinChange), ''), '^G1[23]')) AND (CAST(vaf AS Nullable(Float64)) IS NOT NULL AND CAST(vaf AS Nullable(Float64)) >= 0.2)) AS np, min(CAST(vaf AS Nullable(Float64))) AS s0lo, max(CAST(vaf AS Nullable(Float64))) AS s0hi, groupUniqArray(501)(ifNull(toString(cancerType), '')) AS s1v FROM rows GROUP BY cohort, study -- view 0 mutations: mutations:rows · msk_chord_2024 WITH ann AS (SELECT alteration, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, CAST(NULL AS Nullable(String)) AS diagnostic_level, @@ -462,424 +462,6 @@ WHERE (match(ifNull(toString(proteinChange), ''), '^G1[23]')) AND (CAST(vaf AS N ORDER BY CAST(vaf AS Nullable(Float64)) DESC NULLS LAST, sid, ord, proteinChange LIMIT 25 OFFSET 0 --- view 0 mutations: mutations:values · msk_chord_2024 -WITH ann AS (SELECT alteration, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, CAST(NULL AS Nullable(String)) AS diagnostic_level, - CAST(NULL AS Nullable(String)) AS prognostic_level, toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver - FROM (SELECT alteration, argMax(tuple(toString(oncogenicity), toString(highest_sensitive_level), toString(highest_resistance_level)), resolved_at) AS c - FROM annotation.oncokb WHERE oncokb_version = 'v7.5' AND alteration_type = 'MUTATION' AND hugo_gene_symbol = 'KRAS' - GROUP BY alteration)), -att AS (SELECT alteration, consequence, tumor_type, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, toNullable(c.4) AS diagnostic_level, - toNullable(c.5) AS prognostic_level, toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver, toUInt8(1) AS found - FROM (SELECT alteration, consequence, tumor_type, argMax(tuple(toString(t.oncogenicity), toString(t.highest_sensitive_level), toString(t.highest_resistance_level), - toString(t.highest_diagnostic_level), toString(t.highest_prognostic_level)), t.resolved_at) AS c - FROM annotation.oncokb_tumor_type AS t WHERE oncokb_version = 'v7.5' AND alteration_type = 'MUTATION' AND hugo_gene_symbol = 'KRAS' - GROUP BY alteration, consequence, tumor_type)), -sva AS (SELECT gene, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, CAST(NULL AS Nullable(String)) AS diagnostic_level, CAST(NULL AS Nullable(String)) AS prognostic_level, - toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver - FROM (SELECT hugo_gene_symbol AS gene, argMax(tuple(toString(oncogenicity), toString(highest_sensitive_level), toString(highest_resistance_level)), resolved_at) AS c - FROM annotation.oncokb WHERE oncokb_version = 'v7.5' AND alteration_type = 'SV' AND alteration = 'Fusion' - GROUP BY gene)), -svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, toNullable(c.4) AS diagnostic_level, toNullable(c.5) AS prognostic_level, - toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver, toUInt8(1) AS found - FROM (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, - argMax(tuple(toString(t.oncogenicity), toString(t.highest_sensitive_level), toString(t.highest_resistance_level), toString(t.highest_diagnostic_level), toString(t.highest_prognostic_level)), t.resolved_at) AS c - FROM annotation.oncokb_sv AS t WHERE oncokb_version = 'v7.5' - AND (site1_entrez IN (SELECT toString(entrez_gene_id) FROM (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS'))) OR site2_entrez IN (SELECT toString(entrez_gene_id) FROM (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS')))) - GROUP BY site1_entrez, site2_entrez, sv_type, tumor_type)), -c0 AS ((SELECT replaceOne(patient_unique_id, 'msk_chord_2024_', '') AS pid, replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid FROM snapshot_db.sample_derived - WHERE cancer_study_identifier = 'msk_chord_2024' - AND (('sample', replaceOne(sample_unique_id, 'msk_chord_2024_', '')) IN (SELECT DISTINCT type AS lvl, if(type = 'sample', replaceOne(sample_unique_id, 'msk_chord_2024_', ''), replaceOne(patient_unique_id, 'msk_chord_2024_', '')) AS id - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' - AND attribute_name = 'CANCER_TYPE' AND lowerUTF8(trimBoth(attribute_value)) IN (lowerUTF8(trimBoth('Colorectal Cancer')))) OR ('patient', replaceOne(patient_unique_id, 'msk_chord_2024_', '')) IN (SELECT DISTINCT type AS lvl, if(type = 'sample', replaceOne(sample_unique_id, 'msk_chord_2024_', ''), replaceOne(patient_unique_id, 'msk_chord_2024_', '')) AS id - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' - AND attribute_name = 'CANCER_TYPE' AND lowerUTF8(trimBoth(attribute_value)) IN (lowerUTF8(trimBoth('Colorectal Cancer'))))))), -m0 AS ( - SELECT patientId AS pid, sampleId AS sid, proteinChange, mutationType, variantType, chr, startPosition AS start, endPosition AS end, - referenceAllele AS ref, tumorSeqAllele AS var, tumorAltCount AS altCount, tumorRefCount AS refCount, mutationStatus AS status, proteinPosStart AS pos, - center, validationStatus AS vs, normalAltCount AS nAlt, normalRefCount AS nRef - FROM snapshot_db.mutation_derived - WHERE startsWith(molecularProfileId, 'msk_chord_2024_') AND studyId = 'msk_chord_2024' AND `GENE.hugoGeneSymbol` = 'KRAS' - AND molecularProfileId NOT LIKE '%uncalled%' AND sampleId IN (SELECT sid FROM c0) -), -v0 AS ( - SELECT pt.stable_id AS pid, smp.stable_id AS sid, ifNull(g1.hugo_gene_symbol, '') AS gene1, ifNull(g2.hugo_gene_symbol, '') AS gene2, - sv.class AS class, sv.event_info AS eventInfo, sv.site1_chromosome AS chr, sv.site1_position AS start, sv.sv_status AS status, - if(ifNull(sv.site1_entrez_gene_id, 0) = 0, '', toString(sv.site1_entrez_gene_id)) AS k1, if(ifNull(sv.site2_entrez_gene_id, 0) = 0, '', toString(sv.site2_entrez_gene_id)) AS k2 - FROM snapshot_db.structural_variant sv - JOIN snapshot_db.genetic_profile gp ON gp.genetic_profile_id = sv.genetic_profile_id - JOIN snapshot_db.cancer_study cs ON cs.cancer_study_id = gp.cancer_study_id - JOIN snapshot_db.sample smp ON smp.internal_id = sv.sample_id - JOIN snapshot_db.patient pt ON pt.internal_id = smp.patient_id - LEFT JOIN snapshot_db.gene g1 ON g1.entrez_gene_id = sv.site1_entrez_gene_id - LEFT JOIN snapshot_db.gene g2 ON g2.entrez_gene_id = sv.site2_entrez_gene_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024' AND gp.genetic_alteration_type = 'STRUCTURAL_VARIANT' - AND (sv.site1_entrez_gene_id IN (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS')) OR sv.site2_entrez_gene_id IN (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS'))) - AND smp.stable_id IN (SELECT sid FROM c0) -), -vk0 AS (SELECT s.sid AS sid, - if(ifNull(k.sid, '') = '', (SELECT t.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.type_of_cancer t ON t.type_of_cancer_id = cs.type_of_cancer_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024'), if(ifNull(k.nd, 0) > 0, k.d, '')) AS tumorType - FROM (SELECT DISTINCT sid FROM (SELECT sid FROM v0)) AS s - LEFT JOIN (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, countIf(attribute_name = 'CANCER_TYPE_DETAILED') AS nd, - anyIf(attribute_value, attribute_name = 'CANCER_TYPE_DETAILED') AS d FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CANCER_TYPE', 'CANCER_TYPE_DETAILED') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM v0)) GROUP BY sid) AS k ON k.sid = s.sid), -ct0 AS (SELECT s.sid AS sid, - if(ifNull(k.sid, '') = '', (SELECT t.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.type_of_cancer t ON t.type_of_cancer_id = cs.type_of_cancer_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024'), if(ifNull(k.nd, 0) > 0, k.d, '')) AS tumorType - FROM (SELECT DISTINCT sid FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) AS s - LEFT JOIN (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, countIf(attribute_name = 'CANCER_TYPE_DETAILED') AS nd, - anyIf(attribute_value, attribute_name = 'CANCER_TYPE_DETAILED') AS d FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CANCER_TYPE', 'CANCER_TYPE_DETAILED') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) GROUP BY sid) AS k ON k.sid = s.sid), -mc0 AS (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, any(attribute_value) AS v FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name = 'MUTATION_COUNT' - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) GROUP BY sid), -cta0 AS (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, any(attribute_value) AS v FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name = 'CANCER_TYPE' - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) GROUP BY sid), -cn0 AS (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, hugo_gene_symbol AS g, any(if(isFinite(ifNull(toFloat64OrNull(alteration_value), nan)), toFloat64OrNull(alteration_value), NULL)) AS v - FROM snapshot_db.genetic_alteration_derived - WHERE cancer_study_identifier = 'msk_chord_2024' AND profile_type = (SELECT replaceOne(gp.stable_id, 'msk_chord_2024_', '') FROM snapshot_db.genetic_profile gp - JOIN snapshot_db.cancer_study cs ON cs.cancer_study_id = gp.cancer_study_id WHERE cs.cancer_study_identifier = 'msk_chord_2024' - AND gp.genetic_alteration_type = 'COPY_NUMBER_ALTERATION' AND gp.datatype = 'DISCRETE' ORDER BY gp.genetic_profile_id DESC LIMIT 1) - AND hugo_gene_symbol IN (SELECT gene1 FROM v0 UNION ALL SELECT 'KRAS') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) - GROUP BY sid, g), -k0 AS (SELECT s.sid AS sid, - if(ifNull(k.sid, '') = '', (SELECT t.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.type_of_cancer t ON t.type_of_cancer_id = cs.type_of_cancer_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024'), if(ifNull(k.nd, 0) > 0, k.d, '')) AS tumorType - FROM (SELECT DISTINCT sid FROM (SELECT sid FROM m0)) AS s - LEFT JOIN (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, countIf(attribute_name = 'CANCER_TYPE_DETAILED') AS nd, - anyIf(attribute_value, attribute_name = 'CANCER_TYPE_DETAILED') AS d FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CANCER_TYPE', 'CANCER_TYPE_DETAILED') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0)) GROUP BY sid) AS k ON k.sid = s.sid), -mt0 AS (SELECT m.*, ifNull(m.mutationType, '') AS consequence, positionCaseInsensitive(ifNull(m.status, ''), 'germline') > 0 AS germ, - k.tumorType AS tumorType FROM m0 AS m LEFT JOIN k0 AS k ON k.sid = m.sid), -g0 AS (SELECT chr, start_position AS start, end_position AS end, reference_allele AS ref, variant_allele AS var, any(data) AS gd - FROM annotation.variant - WHERE (source, version) IN (('genome_nexus', '2.2.3-vep116-clinvar20260208+f2'), ('genome_nexus_grch38', '1.4.1-vepNA-clinvar20250106+f2')) AND source = (SELECT multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier = 'msk_chord_2024') - AND (chr, start_position, end_position, reference_allele, variant_allele) IN (SELECT chr, start, end, ref, var FROM m0) - GROUP BY chr, start, end, ref, var), -rows0 AS ( - SELECT 'Colorectal' AS cohort, 'msk_chord_2024' AS study, 0 AS ord, - (SELECT rg.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024') AS build, - m.pid AS patient, m.sid AS sid, nullIf(ct.tumorType, '') AS cancerType, m.proteinChange AS proteinChange, - if(m.germ, '', if(tt.found = 1, tt.oncogenicity, ann.oncogenicity)) AS oncogenicity, if(m.germ, '', if(tt.found = 1, tt.level, ann.level)) AS level, - if(m.germ, '', if(tt.found = 1, tt.resistance_level, ann.resistance_level)) AS resistanceLevel, if(m.germ, '', if(tt.found = 1, tt.diagnostic_level, ann.diagnostic_level)) AS diagnosticLevel, if(m.germ, '', if(tt.found = 1, tt.prognostic_level, ann.prognostic_level)) AS prognosticLevel, - toUInt8((NOT m.germ AND if(tt.found = 1, tt.driver, ifNull(ann.driver, 0))) OR (ifNull(m.chr, '') != '' AND ifNull(m.start, 0) != 0 AND ifNull(m.end, 0) != 0 AND ifNull(m.ref, '') != '' AND ifNull(m.var, '') != '' AND if(positionCaseInsensitive(ifNull(m.mutationType, ''), 'splice') > 0, arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'splice') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots')), arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'single') > 0 OR positionCaseInsensitive(JSONExtractString(h, 'type'), 'indel') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots'))))) AS drv, - toUInt8((ifNull(m.chr, '') != '' AND ifNull(m.start, 0) != 0 AND ifNull(m.end, 0) != 0 AND ifNull(m.ref, '') != '' AND ifNull(m.var, '') != '' AND if(positionCaseInsensitive(ifNull(m.mutationType, ''), 'splice') > 0, arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'splice') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots')), arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'single') > 0 OR positionCaseInsensitive(JSONExtractString(h, 'type'), 'indel') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots'))))) AS hot, - m.mutationType AS mutationType, upper(m.variantType) AS variantType, - if(m.altCount > 0 AND m.refCount >= 0, m.altCount / (m.altCount + m.refCount), NULL) AS vaf, if(vaf IS NULL, '', if(vaf < 0.01, toDecimalString(vaf, 4), toDecimalString(vaf, 2))) AS vafText, - if(m.altCount > 0, m.altCount, NULL) AS altCount, if(m.refCount > 0, m.refCount, NULL) AS refCount, - toInt64OrNull(mc.v) AS mutCount, m.chr AS chr, m.start AS start, m.end AS end, m.ref AS ref, m.var AS var, m.status AS status, m.pos AS pos, - if((ifNull(m.chr, '') != '' AND ifNull(m.start, 0) > 0 AND ifNull(m.end, 0) > 0 AND ifNull(m.ref, '') NOT IN ('', 'NA') AND ifNull(m.var, '') NOT IN ('', 'NA') AND NOT (ifNull(m.ref, '') = '-' AND ifNull(m.var, '') = '-')), concat(ifNull(m.chr, ''), ':g.', multiIf(ifNull(m.ref, '') = '-', concat(toString(ifNull(m.start, 0)), '_', toString(ifNull(m.end, 0)), 'ins', ifNull(m.var, '')), ifNull(m.var, '') = '-', if(ifNull(m.start, 0) = ifNull(m.end, 0), concat(toString(ifNull(m.start, 0)), 'del'), concat(toString(ifNull(m.start, 0)), '_', toString(ifNull(m.end, 0)), 'del')), length(ifNull(m.ref, '')) = 1 AND length(ifNull(m.var, '')) = 1, concat(toString(ifNull(m.start, 0)), ifNull(m.ref, ''), '>', ifNull(m.var, '')), length(ifNull(m.ref, '')) = 1, concat(toString(ifNull(m.start, 0)), 'delins', ifNull(m.var, '')), concat(toString(ifNull(m.start, 0)), '_', toString(ifNull(m.end, 0)), 'delins', ifNull(m.var, '')))), '') AS hgvsg, - JSONExtractBool(ifNull(g.gd, ''), 'ok') AS gnOk, - arrayFirst(t -> JSONExtractString(t, 'transcriptId') = JSONExtractString(ifNull(g.gd, ''), 'canonical', 'KRAS'), JSONExtractArrayRaw(ifNull(g.gd, ''), 'transcripts')) AS tc, - JSONExtractString(tc, 'hgvsc') AS hgvsc, - JSONExtractString(ifNull(g.gd, ''), 'clinvar', 'significance') AS clinvar, JSONExtractString(ifNull(g.gd, ''), 'clinvar', 'conflicting') AS clinvarConflicting, - JSONExtractUInt(ifNull(g.gd, ''), 'clinvar', 'id') AS clinvarId, - arrayLast(e -> position(JSONExtractString(e, 'mutationStatus'), 'germline') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'signal')) AS sig, - if(lower(JSONExtractString(sig, 'mutationStatus')) = 'germline' AND arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) > 0, arraySum(arrayMap(c -> JSONExtractFloat(c, 'variantCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) / arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))), NULL) AS signalFreq, - JSONExtractString(ifNull(g.gd, ''), 'rsid') AS rsid, JSONExtractRaw(ifNull(g.gd, ''), 'gnomad') AS gnomadRaw, JSONExtractRaw(ifNull(g.gd, ''), 'vcf') AS vcfRaw, - JSONExtractString(ifNull(g.gd, ''), 'seqRegion') AS seqRegion, - multiIf(JSONType(ifNull(g.gd, ''), 'gnomad', 'exome') = 'Object' AND JSONType(ifNull(g.gd, ''), 'gnomad', 'genome') = 'Object', if(JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an') > 0, (JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleCount', 'ac') + JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleCount', 'ac')) / (JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an')), 0), JSONType(ifNull(g.gd, ''), 'gnomad', 'exome') = 'Object', coalesce(JSONExtract(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an') > 0, JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleCount', 'ac') / JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an'), 0)), JSONType(ifNull(g.gd, ''), 'gnomad', 'genome') = 'Object', coalesce(JSONExtract(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an') > 0, JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleCount', 'ac') / JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an'), 0)), NULL) AS gnomadFreq, - JSONExtractRaw(ifNull(g.gd, ''), 'mutationAssessor') AS maRaw, - if(ifNull(g.gd, '') != '', concat(concat('MutationAssessor: ', if(JSONType(ifNull(g.gd, ''), 'mutationAssessor') = 'Object', concat('impact: ', multiIf(NOT JSONHas(ifNull(g.gd, ''), 'mutationAssessor', 'prediction'), 'undefined', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'prediction') = 'Null', 'null', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'prediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(ifNull(g.gd, ''), 'mutationAssessor', 'prediction')), JSONExtractString(ifNull(g.gd, ''), 'mutationAssessor', 'prediction')), ', score: ', multiIf(NOT JSONHas(ifNull(g.gd, ''), 'mutationAssessor', 'score'), 'undefined', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'score') = 'Null', 'null', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(ifNull(g.gd, ''), 'mutationAssessor', 'score')), JSONExtractString(ifNull(g.gd, ''), 'mutationAssessor', 'score'))), 'NA')), ';', concat('SIFT: ', if((JSONExtractFloat(tc, 'siftScore') != 0 OR JSONExtractString(tc, 'siftPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'siftPrediction'), 'undefined', JSONType(tc, 'siftPrediction') = 'Null', 'null', JSONType(tc, 'siftPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftPrediction')), JSONExtractString(tc, 'siftPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'siftScore'), 'undefined', JSONType(tc, 'siftScore') = 'Null', 'null', JSONType(tc, 'siftScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftScore')), JSONExtractString(tc, 'siftScore'))), 'NA')), ';', concat('Polyphen-2: ', if((JSONExtractFloat(tc, 'polyphenScore') != 0 OR JSONExtractString(tc, 'polyphenPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'polyphenPrediction'), 'undefined', JSONType(tc, 'polyphenPrediction') = 'Null', 'null', JSONType(tc, 'polyphenPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenPrediction')), JSONExtractString(tc, 'polyphenPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'polyphenScore'), 'undefined', JSONType(tc, 'polyphenScore') = 'Null', 'null', JSONType(tc, 'polyphenScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenScore')), JSONExtractString(tc, 'polyphenScore'))), 'NA')), ';', concat('AlphaMissense: ', if((JSONExtractFloat(tc, 'alphaMissense', 'score') != 0 OR JSONExtractString(tc, 'alphaMissense', 'pathogenicity') != ''), concat('pathogenicity: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'pathogenicity'), 'undefined', JSONType(tc, 'alphaMissense', 'pathogenicity') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'pathogenicity') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'pathogenicity')), JSONExtractString(tc, 'alphaMissense', 'pathogenicity')), ', score: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'score'), 'undefined', JSONType(tc, 'alphaMissense', 'score') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'score')), JSONExtractString(tc, 'alphaMissense', 'score'))), 'NA'))), '') AS functionalImpact, - 'KRAS' AS gene, (SELECT name FROM snapshot_db.cancer_study WHERE cancer_study_identifier = 'msk_chord_2024') AS studyName, cta.v AS cancerTypeAll, - if(cn.v = floor(cn.v), toInt8(cn.v), NULL) AS cnv, multiIf(cnv IS NULL, '', cnv = 2, 'Amp', cnv = 1, 'Gain', cnv = 0, 'Diploid', cnv = -1, 'ShallowDel', 'DeepDel') AS copyNumber, - m.vs AS validationStatus, m.center AS center, - round(if(m.nAlt > 0 AND m.nRef >= 0, m.nAlt / (m.nAlt + m.nRef), NULL), if(if(m.nAlt > 0 AND m.nRef >= 0, m.nAlt / (m.nAlt + m.nRef), NULL) < 0.01, 4, 2)) AS vafNormal, - if(m.nAlt > 0, m.nAlt, NULL) AS normalAltCount, m.nAlt AS normalAltCountRaw, - if(m.nRef > 0, m.nRef, NULL) AS normalRefCount, m.nRef AS normalRefCountRaw, - JSONExtractString(tc, 'exon') AS exon - FROM mt0 AS m - LEFT JOIN ann ON ann.alteration = m.proteinChange - LEFT JOIN att AS tt ON tt.alteration = m.proteinChange AND tt.consequence = m.consequence AND tt.tumor_type = m.tumorType - LEFT JOIN g0 AS g ON g.chr = m.chr AND g.start = m.start AND g.end = m.end AND g.ref = m.ref AND g.var = m.var - LEFT JOIN ct0 AS ct ON ct.sid = m.sid LEFT JOIN mc0 AS mc ON mc.sid = m.sid - LEFT JOIN cta0 AS cta ON cta.sid = m.sid LEFT JOIN cn0 AS cn ON cn.sid = m.sid AND cn.g = 'KRAS' - UNION ALL - SELECT 'Colorectal' AS cohort, 'msk_chord_2024' AS study, 0 AS ord, - (SELECT rg.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024') AS build, - v.pid AS patient, v.sid AS sid, nullIf(ct.tumorType, '') AS cancerType, multiIf(v.gene1 != '' AND v.gene2 != '' AND v.gene1 != v.gene2, concat(v.gene1, '-', v.gene2, ' Fusion'), v.gene1 != '' AND v.gene2 != '', concat(v.gene1, ' intragenic'), v.gene1 != '' OR v.gene2 != '', concat(if(v.gene1 != '', v.gene1, v.gene2), if((upper(ifNull(v.class, '')) = 'INTERGENIC' OR (upper(ifNull(v.class, '')) IN ('', 'UNKNOWN', 'NA') AND upper(ifNull(v.eventInfo, '')) = concat(upper(if(v.gene1 != '', v.gene1, v.gene2)), '-INTERGENIC'))), ' intergenic', ' intragenic')), 'undefined intragenic') AS proteinChange, - if(vp.found = 1, vp.oncogenicity, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.oncogenicity, va1.oncogenicity)) AS oncogenicity, if(vp.found = 1, vp.level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.level, va1.level)) AS level, - if(vp.found = 1, vp.resistance_level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.resistance_level, va1.resistance_level)) AS resistanceLevel, if(vp.found = 1, vp.diagnostic_level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.diagnostic_level, va1.diagnostic_level)) AS diagnosticLevel, if(vp.found = 1, vp.prognostic_level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.prognostic_level, va1.prognostic_level)) AS prognosticLevel, - toUInt8(if(vn.found = 1, vn.driver, greatest(va1.driver, va2.driver))) AS drv, - toUInt8(0) AS hot, - 'Fusion' AS mutationType, upper(v.class) AS variantType, - NULL AS vaf, '' AS vafText, NULL AS altCount, NULL AS refCount, - toInt64OrNull(mc.v) AS mutCount, v.chr AS chr, v.start AS start, NULL AS end, NULL AS ref, NULL AS var, v.status AS status, NULL AS pos, - '' AS hgvsg, - JSONExtractBool('', 'ok') AS gnOk, - arrayFirst(t -> JSONExtractString(t, 'transcriptId') = JSONExtractString('', 'canonical', 'KRAS'), JSONExtractArrayRaw('', 'transcripts')) AS tc, - JSONExtractString(tc, 'hgvsc') AS hgvsc, - JSONExtractString('', 'clinvar', 'significance') AS clinvar, JSONExtractString('', 'clinvar', 'conflicting') AS clinvarConflicting, - JSONExtractUInt('', 'clinvar', 'id') AS clinvarId, - arrayLast(e -> position(JSONExtractString(e, 'mutationStatus'), 'germline') > 0, JSONExtractArrayRaw('', 'signal')) AS sig, - if(lower(JSONExtractString(sig, 'mutationStatus')) = 'germline' AND arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) > 0, arraySum(arrayMap(c -> JSONExtractFloat(c, 'variantCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) / arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))), NULL) AS signalFreq, - JSONExtractString('', 'rsid') AS rsid, JSONExtractRaw('', 'gnomad') AS gnomadRaw, JSONExtractRaw('', 'vcf') AS vcfRaw, - JSONExtractString('', 'seqRegion') AS seqRegion, - multiIf(JSONType('', 'gnomad', 'exome') = 'Object' AND JSONType('', 'gnomad', 'genome') = 'Object', if(JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an') > 0, (JSONExtractFloat('', 'gnomad', 'exome', 'alleleCount', 'ac') + JSONExtractFloat('', 'gnomad', 'genome', 'alleleCount', 'ac')) / (JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an')), 0), JSONType('', 'gnomad', 'exome') = 'Object', coalesce(JSONExtract('', 'gnomad', 'exome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an') > 0, JSONExtractFloat('', 'gnomad', 'exome', 'alleleCount', 'ac') / JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an'), 0)), JSONType('', 'gnomad', 'genome') = 'Object', coalesce(JSONExtract('', 'gnomad', 'genome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an') > 0, JSONExtractFloat('', 'gnomad', 'genome', 'alleleCount', 'ac') / JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an'), 0)), NULL) AS gnomadFreq, - JSONExtractRaw('', 'mutationAssessor') AS maRaw, - if('' != '', concat(concat('MutationAssessor: ', if(JSONType('', 'mutationAssessor') = 'Object', concat('impact: ', multiIf(NOT JSONHas('', 'mutationAssessor', 'prediction'), 'undefined', JSONType('', 'mutationAssessor', 'prediction') = 'Null', 'null', JSONType('', 'mutationAssessor', 'prediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat('', 'mutationAssessor', 'prediction')), JSONExtractString('', 'mutationAssessor', 'prediction')), ', score: ', multiIf(NOT JSONHas('', 'mutationAssessor', 'score'), 'undefined', JSONType('', 'mutationAssessor', 'score') = 'Null', 'null', JSONType('', 'mutationAssessor', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat('', 'mutationAssessor', 'score')), JSONExtractString('', 'mutationAssessor', 'score'))), 'NA')), ';', concat('SIFT: ', if((JSONExtractFloat(tc, 'siftScore') != 0 OR JSONExtractString(tc, 'siftPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'siftPrediction'), 'undefined', JSONType(tc, 'siftPrediction') = 'Null', 'null', JSONType(tc, 'siftPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftPrediction')), JSONExtractString(tc, 'siftPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'siftScore'), 'undefined', JSONType(tc, 'siftScore') = 'Null', 'null', JSONType(tc, 'siftScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftScore')), JSONExtractString(tc, 'siftScore'))), 'NA')), ';', concat('Polyphen-2: ', if((JSONExtractFloat(tc, 'polyphenScore') != 0 OR JSONExtractString(tc, 'polyphenPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'polyphenPrediction'), 'undefined', JSONType(tc, 'polyphenPrediction') = 'Null', 'null', JSONType(tc, 'polyphenPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenPrediction')), JSONExtractString(tc, 'polyphenPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'polyphenScore'), 'undefined', JSONType(tc, 'polyphenScore') = 'Null', 'null', JSONType(tc, 'polyphenScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenScore')), JSONExtractString(tc, 'polyphenScore'))), 'NA')), ';', concat('AlphaMissense: ', if((JSONExtractFloat(tc, 'alphaMissense', 'score') != 0 OR JSONExtractString(tc, 'alphaMissense', 'pathogenicity') != ''), concat('pathogenicity: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'pathogenicity'), 'undefined', JSONType(tc, 'alphaMissense', 'pathogenicity') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'pathogenicity') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'pathogenicity')), JSONExtractString(tc, 'alphaMissense', 'pathogenicity')), ', score: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'score'), 'undefined', JSONType(tc, 'alphaMissense', 'score') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'score')), JSONExtractString(tc, 'alphaMissense', 'score'))), 'NA'))), '') AS functionalImpact, - v.gene1 AS gene, (SELECT name FROM snapshot_db.cancer_study WHERE cancer_study_identifier = 'msk_chord_2024') AS studyName, cta.v AS cancerTypeAll, - if(cn.v = floor(cn.v), toInt8(cn.v), NULL) AS cnv, multiIf(cnv IS NULL, '', cnv = 2, 'Amp', cnv = 1, 'Gain', cnv = 0, 'Diploid', cnv = -1, 'ShallowDel', 'DeepDel') AS copyNumber, - NULL AS validationStatus, 'N/A' AS center, - round(if(NULL > 0 AND NULL >= 0, NULL / (NULL + NULL), NULL), if(if(NULL > 0 AND NULL >= 0, NULL / (NULL + NULL), NULL) < 0.01, 4, 2)) AS vafNormal, - if(NULL > 0, NULL, NULL) AS normalAltCount, NULL AS normalAltCountRaw, - if(NULL > 0, NULL, NULL) AS normalRefCount, NULL AS normalRefCountRaw, - JSONExtractString(tc, 'exon') AS exon - FROM v0 AS v - LEFT JOIN vk0 AS vk ON vk.sid = v.sid - LEFT JOIN sva AS va1 ON va1.gene = v.gene1 AND v.gene1 != '' LEFT JOIN sva AS va2 ON va2.gene = v.gene2 AND v.gene2 != '' - LEFT JOIN svp AS vp ON vp.site1_entrez = v.k1 AND vp.site2_entrez = v.k2 AND vp.sv_type = if((v.gene1 != '') + (v.gene2 != '') >= 2, 'FUSION', if(ifNull(v.class, '') IN ('DELETION', 'TRANSLOCATION', 'DUPLICATION', 'INSERTION', 'INVERSION', 'FUSION'), v.class, 'UNKNOWN')) AND vp.tumor_type = vk.tumorType - LEFT JOIN svp AS vn ON vn.site1_entrez = v.k1 AND vn.site2_entrez = v.k2 AND vn.sv_type = if((v.gene1 != '') + (v.gene2 != '') >= 2, 'FUSION', if(ifNull(v.class, '') IN ('DELETION', 'TRANSLOCATION', 'DUPLICATION', 'INSERTION', 'INVERSION', 'FUSION'), v.class, 'UNKNOWN')) AND vn.tumor_type = '' - LEFT JOIN ct0 AS ct ON ct.sid = v.sid LEFT JOIN mc0 AS mc ON mc.sid = v.sid - LEFT JOIN cta0 AS cta ON cta.sid = v.sid LEFT JOIN cn0 AS cn ON cn.sid = v.sid AND cn.g = v.gene1 -), -clins AS ( - SELECT 'msk_chord_2024' AS st, replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS k, - CAST((groupArray(attribute_name), groupArray(attribute_value)), 'Map(String, String)') AS m - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CLINICAL_GROUP', 'CLINICAL_SUMMARY', 'DIAGNOSIS_DESCRIPTION', 'ICD_O_HISTOLOGY_DESCRIPTION', 'PATHOLOGICAL_GROUP', 'SAMPLE_TYPE', 'MSI_TYPE', 'GENE_PANEL', 'SOMATIC_STATUS', 'SAMPLE_CLASS', 'FRACTION_GENOME_ALTERED', 'TMB_NONSYNONYMOUS', 'GLEASON_SAMPLE_LEVEL', 'MSI_COMMENT', 'MSI_SCORE', 'METASTATIC_SITE', 'ONCOTREE_CODE', 'PRIMARY_SITE', 'PDL1_POSITIVE', 'SAMPLE_COVERAGE', 'TUMOR_PURITY') AND attribute_value != '' - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', x) FROM (SELECT sid AS x FROM m0 UNION ALL SELECT sid AS x FROM v0)) - GROUP BY k -), -clinp AS ( - SELECT 'msk_chord_2024' AS st, replaceOne(patient_unique_id, 'msk_chord_2024_', '') AS k, - CAST((groupArray(attribute_name), groupArray(attribute_value)), 'Map(String, String)') AS m - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'patient' AND attribute_name IN ('OS_STATUS', 'RACE', 'GENDER', 'STAGE_HIGHEST_RECORDED', 'ETHNICITY', 'CURRENT_AGE_DEID', 'SMOKING_PREDICTIONS_3_CLASSES', 'PRIOR_MED_TO_MSK', 'GLEASON_HIGHEST_REPORTED', 'HISTORY_OF_PDL1', 'NUM_ICDO_DX', 'SAMPLE_COUNT', 'GLEASON_FIRST_REPORTED', 'HER2', 'HR', 'OS_MONTHS', 'ADRENAL_GLANDS', 'BONE', 'CNS_BRAIN', 'INTRA_ABDOMINAL', 'LIVER', 'LUNG', 'LYMPH_NODES', 'OTHER', 'PLEURA', 'REPRODUCTIVE_ORGANS') AND attribute_value != '' - AND patient_unique_id IN (SELECT concat('msk_chord_2024_', x) FROM (SELECT pid AS x FROM m0 UNION ALL SELECT pid AS x FROM v0)) - GROUP BY k -), -rows AS (SELECT r.*, cs.m AS clinS, cp.m AS clinP FROM rows0 AS r - LEFT JOIN clins AS cs ON cs.st = r.study AND cs.k = r.sid LEFT JOIN clinp AS cp ON cp.st = r.study AND cp.k = r.patient) -SELECT min(v) AS lo, max(v) AS hi, count() AS n FROM (SELECT CAST(vaf AS Nullable(Float64)) AS v FROM rows WHERE 1) WHERE v IS NOT NULL - --- view 0 mutations: mutations:values · msk_chord_2024 -WITH ann AS (SELECT alteration, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, CAST(NULL AS Nullable(String)) AS diagnostic_level, - CAST(NULL AS Nullable(String)) AS prognostic_level, toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver - FROM (SELECT alteration, argMax(tuple(toString(oncogenicity), toString(highest_sensitive_level), toString(highest_resistance_level)), resolved_at) AS c - FROM annotation.oncokb WHERE oncokb_version = 'v7.5' AND alteration_type = 'MUTATION' AND hugo_gene_symbol = 'KRAS' - GROUP BY alteration)), -att AS (SELECT alteration, consequence, tumor_type, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, toNullable(c.4) AS diagnostic_level, - toNullable(c.5) AS prognostic_level, toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver, toUInt8(1) AS found - FROM (SELECT alteration, consequence, tumor_type, argMax(tuple(toString(t.oncogenicity), toString(t.highest_sensitive_level), toString(t.highest_resistance_level), - toString(t.highest_diagnostic_level), toString(t.highest_prognostic_level)), t.resolved_at) AS c - FROM annotation.oncokb_tumor_type AS t WHERE oncokb_version = 'v7.5' AND alteration_type = 'MUTATION' AND hugo_gene_symbol = 'KRAS' - GROUP BY alteration, consequence, tumor_type)), -sva AS (SELECT gene, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, CAST(NULL AS Nullable(String)) AS diagnostic_level, CAST(NULL AS Nullable(String)) AS prognostic_level, - toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver - FROM (SELECT hugo_gene_symbol AS gene, argMax(tuple(toString(oncogenicity), toString(highest_sensitive_level), toString(highest_resistance_level)), resolved_at) AS c - FROM annotation.oncokb WHERE oncokb_version = 'v7.5' AND alteration_type = 'SV' AND alteration = 'Fusion' - GROUP BY gene)), -svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenicity, c.2 AS level, c.3 AS resistance_level, toNullable(c.4) AS diagnostic_level, toNullable(c.5) AS prognostic_level, - toUInt8(c.1 IN ('Oncogenic', 'Likely Oncogenic', 'Resistance')) AS driver, toUInt8(1) AS found - FROM (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, - argMax(tuple(toString(t.oncogenicity), toString(t.highest_sensitive_level), toString(t.highest_resistance_level), toString(t.highest_diagnostic_level), toString(t.highest_prognostic_level)), t.resolved_at) AS c - FROM annotation.oncokb_sv AS t WHERE oncokb_version = 'v7.5' - AND (site1_entrez IN (SELECT toString(entrez_gene_id) FROM (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS'))) OR site2_entrez IN (SELECT toString(entrez_gene_id) FROM (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS')))) - GROUP BY site1_entrez, site2_entrez, sv_type, tumor_type)), -c0 AS ((SELECT replaceOne(patient_unique_id, 'msk_chord_2024_', '') AS pid, replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid FROM snapshot_db.sample_derived - WHERE cancer_study_identifier = 'msk_chord_2024' - AND (('sample', replaceOne(sample_unique_id, 'msk_chord_2024_', '')) IN (SELECT DISTINCT type AS lvl, if(type = 'sample', replaceOne(sample_unique_id, 'msk_chord_2024_', ''), replaceOne(patient_unique_id, 'msk_chord_2024_', '')) AS id - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' - AND attribute_name = 'CANCER_TYPE' AND lowerUTF8(trimBoth(attribute_value)) IN (lowerUTF8(trimBoth('Colorectal Cancer')))) OR ('patient', replaceOne(patient_unique_id, 'msk_chord_2024_', '')) IN (SELECT DISTINCT type AS lvl, if(type = 'sample', replaceOne(sample_unique_id, 'msk_chord_2024_', ''), replaceOne(patient_unique_id, 'msk_chord_2024_', '')) AS id - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' - AND attribute_name = 'CANCER_TYPE' AND lowerUTF8(trimBoth(attribute_value)) IN (lowerUTF8(trimBoth('Colorectal Cancer'))))))), -m0 AS ( - SELECT patientId AS pid, sampleId AS sid, proteinChange, mutationType, variantType, chr, startPosition AS start, endPosition AS end, - referenceAllele AS ref, tumorSeqAllele AS var, tumorAltCount AS altCount, tumorRefCount AS refCount, mutationStatus AS status, proteinPosStart AS pos, - center, validationStatus AS vs, normalAltCount AS nAlt, normalRefCount AS nRef - FROM snapshot_db.mutation_derived - WHERE startsWith(molecularProfileId, 'msk_chord_2024_') AND studyId = 'msk_chord_2024' AND `GENE.hugoGeneSymbol` = 'KRAS' - AND molecularProfileId NOT LIKE '%uncalled%' AND sampleId IN (SELECT sid FROM c0) -), -v0 AS ( - SELECT pt.stable_id AS pid, smp.stable_id AS sid, ifNull(g1.hugo_gene_symbol, '') AS gene1, ifNull(g2.hugo_gene_symbol, '') AS gene2, - sv.class AS class, sv.event_info AS eventInfo, sv.site1_chromosome AS chr, sv.site1_position AS start, sv.sv_status AS status, - if(ifNull(sv.site1_entrez_gene_id, 0) = 0, '', toString(sv.site1_entrez_gene_id)) AS k1, if(ifNull(sv.site2_entrez_gene_id, 0) = 0, '', toString(sv.site2_entrez_gene_id)) AS k2 - FROM snapshot_db.structural_variant sv - JOIN snapshot_db.genetic_profile gp ON gp.genetic_profile_id = sv.genetic_profile_id - JOIN snapshot_db.cancer_study cs ON cs.cancer_study_id = gp.cancer_study_id - JOIN snapshot_db.sample smp ON smp.internal_id = sv.sample_id - JOIN snapshot_db.patient pt ON pt.internal_id = smp.patient_id - LEFT JOIN snapshot_db.gene g1 ON g1.entrez_gene_id = sv.site1_entrez_gene_id - LEFT JOIN snapshot_db.gene g2 ON g2.entrez_gene_id = sv.site2_entrez_gene_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024' AND gp.genetic_alteration_type = 'STRUCTURAL_VARIANT' - AND (sv.site1_entrez_gene_id IN (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS')) OR sv.site2_entrez_gene_id IN (SELECT entrez_gene_id FROM snapshot_db.gene WHERE hugo_gene_symbol IN ('KRAS'))) - AND smp.stable_id IN (SELECT sid FROM c0) -), -vk0 AS (SELECT s.sid AS sid, - if(ifNull(k.sid, '') = '', (SELECT t.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.type_of_cancer t ON t.type_of_cancer_id = cs.type_of_cancer_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024'), if(ifNull(k.nd, 0) > 0, k.d, '')) AS tumorType - FROM (SELECT DISTINCT sid FROM (SELECT sid FROM v0)) AS s - LEFT JOIN (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, countIf(attribute_name = 'CANCER_TYPE_DETAILED') AS nd, - anyIf(attribute_value, attribute_name = 'CANCER_TYPE_DETAILED') AS d FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CANCER_TYPE', 'CANCER_TYPE_DETAILED') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM v0)) GROUP BY sid) AS k ON k.sid = s.sid), -ct0 AS (SELECT s.sid AS sid, - if(ifNull(k.sid, '') = '', (SELECT t.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.type_of_cancer t ON t.type_of_cancer_id = cs.type_of_cancer_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024'), if(ifNull(k.nd, 0) > 0, k.d, '')) AS tumorType - FROM (SELECT DISTINCT sid FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) AS s - LEFT JOIN (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, countIf(attribute_name = 'CANCER_TYPE_DETAILED') AS nd, - anyIf(attribute_value, attribute_name = 'CANCER_TYPE_DETAILED') AS d FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CANCER_TYPE', 'CANCER_TYPE_DETAILED') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) GROUP BY sid) AS k ON k.sid = s.sid), -mc0 AS (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, any(attribute_value) AS v FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name = 'MUTATION_COUNT' - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) GROUP BY sid), -cta0 AS (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, any(attribute_value) AS v FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name = 'CANCER_TYPE' - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) GROUP BY sid), -cn0 AS (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, hugo_gene_symbol AS g, any(if(isFinite(ifNull(toFloat64OrNull(alteration_value), nan)), toFloat64OrNull(alteration_value), NULL)) AS v - FROM snapshot_db.genetic_alteration_derived - WHERE cancer_study_identifier = 'msk_chord_2024' AND profile_type = (SELECT replaceOne(gp.stable_id, 'msk_chord_2024_', '') FROM snapshot_db.genetic_profile gp - JOIN snapshot_db.cancer_study cs ON cs.cancer_study_id = gp.cancer_study_id WHERE cs.cancer_study_identifier = 'msk_chord_2024' - AND gp.genetic_alteration_type = 'COPY_NUMBER_ALTERATION' AND gp.datatype = 'DISCRETE' ORDER BY gp.genetic_profile_id DESC LIMIT 1) - AND hugo_gene_symbol IN (SELECT gene1 FROM v0 UNION ALL SELECT 'KRAS') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0 UNION ALL SELECT sid FROM v0)) - GROUP BY sid, g), -k0 AS (SELECT s.sid AS sid, - if(ifNull(k.sid, '') = '', (SELECT t.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.type_of_cancer t ON t.type_of_cancer_id = cs.type_of_cancer_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024'), if(ifNull(k.nd, 0) > 0, k.d, '')) AS tumorType - FROM (SELECT DISTINCT sid FROM (SELECT sid FROM m0)) AS s - LEFT JOIN (SELECT replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS sid, countIf(attribute_name = 'CANCER_TYPE_DETAILED') AS nd, - anyIf(attribute_value, attribute_name = 'CANCER_TYPE_DETAILED') AS d FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CANCER_TYPE', 'CANCER_TYPE_DETAILED') - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', sid) FROM (SELECT sid FROM m0)) GROUP BY sid) AS k ON k.sid = s.sid), -mt0 AS (SELECT m.*, ifNull(m.mutationType, '') AS consequence, positionCaseInsensitive(ifNull(m.status, ''), 'germline') > 0 AS germ, - k.tumorType AS tumorType FROM m0 AS m LEFT JOIN k0 AS k ON k.sid = m.sid), -g0 AS (SELECT chr, start_position AS start, end_position AS end, reference_allele AS ref, variant_allele AS var, any(data) AS gd - FROM annotation.variant - WHERE (source, version) IN (('genome_nexus', '2.2.3-vep116-clinvar20260208+f2'), ('genome_nexus_grch38', '1.4.1-vepNA-clinvar20250106+f2')) AND source = (SELECT multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier = 'msk_chord_2024') - AND (chr, start_position, end_position, reference_allele, variant_allele) IN (SELECT chr, start, end, ref, var FROM m0) - GROUP BY chr, start, end, ref, var), -rows0 AS ( - SELECT 'Colorectal' AS cohort, 'msk_chord_2024' AS study, 0 AS ord, - (SELECT rg.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024') AS build, - m.pid AS patient, m.sid AS sid, nullIf(ct.tumorType, '') AS cancerType, m.proteinChange AS proteinChange, - if(m.germ, '', if(tt.found = 1, tt.oncogenicity, ann.oncogenicity)) AS oncogenicity, if(m.germ, '', if(tt.found = 1, tt.level, ann.level)) AS level, - if(m.germ, '', if(tt.found = 1, tt.resistance_level, ann.resistance_level)) AS resistanceLevel, if(m.germ, '', if(tt.found = 1, tt.diagnostic_level, ann.diagnostic_level)) AS diagnosticLevel, if(m.germ, '', if(tt.found = 1, tt.prognostic_level, ann.prognostic_level)) AS prognosticLevel, - toUInt8((NOT m.germ AND if(tt.found = 1, tt.driver, ifNull(ann.driver, 0))) OR (ifNull(m.chr, '') != '' AND ifNull(m.start, 0) != 0 AND ifNull(m.end, 0) != 0 AND ifNull(m.ref, '') != '' AND ifNull(m.var, '') != '' AND if(positionCaseInsensitive(ifNull(m.mutationType, ''), 'splice') > 0, arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'splice') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots')), arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'single') > 0 OR positionCaseInsensitive(JSONExtractString(h, 'type'), 'indel') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots'))))) AS drv, - toUInt8((ifNull(m.chr, '') != '' AND ifNull(m.start, 0) != 0 AND ifNull(m.end, 0) != 0 AND ifNull(m.ref, '') != '' AND ifNull(m.var, '') != '' AND if(positionCaseInsensitive(ifNull(m.mutationType, ''), 'splice') > 0, arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'splice') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots')), arrayExists(h -> positionCaseInsensitive(JSONExtractString(h, 'type'), 'single') > 0 OR positionCaseInsensitive(JSONExtractString(h, 'type'), 'indel') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'hotspots'))))) AS hot, - m.mutationType AS mutationType, upper(m.variantType) AS variantType, - if(m.altCount > 0 AND m.refCount >= 0, m.altCount / (m.altCount + m.refCount), NULL) AS vaf, if(vaf IS NULL, '', if(vaf < 0.01, toDecimalString(vaf, 4), toDecimalString(vaf, 2))) AS vafText, - if(m.altCount > 0, m.altCount, NULL) AS altCount, if(m.refCount > 0, m.refCount, NULL) AS refCount, - toInt64OrNull(mc.v) AS mutCount, m.chr AS chr, m.start AS start, m.end AS end, m.ref AS ref, m.var AS var, m.status AS status, m.pos AS pos, - if((ifNull(m.chr, '') != '' AND ifNull(m.start, 0) > 0 AND ifNull(m.end, 0) > 0 AND ifNull(m.ref, '') NOT IN ('', 'NA') AND ifNull(m.var, '') NOT IN ('', 'NA') AND NOT (ifNull(m.ref, '') = '-' AND ifNull(m.var, '') = '-')), concat(ifNull(m.chr, ''), ':g.', multiIf(ifNull(m.ref, '') = '-', concat(toString(ifNull(m.start, 0)), '_', toString(ifNull(m.end, 0)), 'ins', ifNull(m.var, '')), ifNull(m.var, '') = '-', if(ifNull(m.start, 0) = ifNull(m.end, 0), concat(toString(ifNull(m.start, 0)), 'del'), concat(toString(ifNull(m.start, 0)), '_', toString(ifNull(m.end, 0)), 'del')), length(ifNull(m.ref, '')) = 1 AND length(ifNull(m.var, '')) = 1, concat(toString(ifNull(m.start, 0)), ifNull(m.ref, ''), '>', ifNull(m.var, '')), length(ifNull(m.ref, '')) = 1, concat(toString(ifNull(m.start, 0)), 'delins', ifNull(m.var, '')), concat(toString(ifNull(m.start, 0)), '_', toString(ifNull(m.end, 0)), 'delins', ifNull(m.var, '')))), '') AS hgvsg, - JSONExtractBool(ifNull(g.gd, ''), 'ok') AS gnOk, - arrayFirst(t -> JSONExtractString(t, 'transcriptId') = JSONExtractString(ifNull(g.gd, ''), 'canonical', 'KRAS'), JSONExtractArrayRaw(ifNull(g.gd, ''), 'transcripts')) AS tc, - JSONExtractString(tc, 'hgvsc') AS hgvsc, - JSONExtractString(ifNull(g.gd, ''), 'clinvar', 'significance') AS clinvar, JSONExtractString(ifNull(g.gd, ''), 'clinvar', 'conflicting') AS clinvarConflicting, - JSONExtractUInt(ifNull(g.gd, ''), 'clinvar', 'id') AS clinvarId, - arrayLast(e -> position(JSONExtractString(e, 'mutationStatus'), 'germline') > 0, JSONExtractArrayRaw(ifNull(g.gd, ''), 'signal')) AS sig, - if(lower(JSONExtractString(sig, 'mutationStatus')) = 'germline' AND arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) > 0, arraySum(arrayMap(c -> JSONExtractFloat(c, 'variantCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) / arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))), NULL) AS signalFreq, - JSONExtractString(ifNull(g.gd, ''), 'rsid') AS rsid, JSONExtractRaw(ifNull(g.gd, ''), 'gnomad') AS gnomadRaw, JSONExtractRaw(ifNull(g.gd, ''), 'vcf') AS vcfRaw, - JSONExtractString(ifNull(g.gd, ''), 'seqRegion') AS seqRegion, - multiIf(JSONType(ifNull(g.gd, ''), 'gnomad', 'exome') = 'Object' AND JSONType(ifNull(g.gd, ''), 'gnomad', 'genome') = 'Object', if(JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an') > 0, (JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleCount', 'ac') + JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleCount', 'ac')) / (JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an')), 0), JSONType(ifNull(g.gd, ''), 'gnomad', 'exome') = 'Object', coalesce(JSONExtract(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an') > 0, JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleCount', 'ac') / JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'exome', 'alleleNumber', 'an'), 0)), JSONType(ifNull(g.gd, ''), 'gnomad', 'genome') = 'Object', coalesce(JSONExtract(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an') > 0, JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleCount', 'ac') / JSONExtractFloat(ifNull(g.gd, ''), 'gnomad', 'genome', 'alleleNumber', 'an'), 0)), NULL) AS gnomadFreq, - JSONExtractRaw(ifNull(g.gd, ''), 'mutationAssessor') AS maRaw, - if(ifNull(g.gd, '') != '', concat(concat('MutationAssessor: ', if(JSONType(ifNull(g.gd, ''), 'mutationAssessor') = 'Object', concat('impact: ', multiIf(NOT JSONHas(ifNull(g.gd, ''), 'mutationAssessor', 'prediction'), 'undefined', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'prediction') = 'Null', 'null', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'prediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(ifNull(g.gd, ''), 'mutationAssessor', 'prediction')), JSONExtractString(ifNull(g.gd, ''), 'mutationAssessor', 'prediction')), ', score: ', multiIf(NOT JSONHas(ifNull(g.gd, ''), 'mutationAssessor', 'score'), 'undefined', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'score') = 'Null', 'null', JSONType(ifNull(g.gd, ''), 'mutationAssessor', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(ifNull(g.gd, ''), 'mutationAssessor', 'score')), JSONExtractString(ifNull(g.gd, ''), 'mutationAssessor', 'score'))), 'NA')), ';', concat('SIFT: ', if((JSONExtractFloat(tc, 'siftScore') != 0 OR JSONExtractString(tc, 'siftPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'siftPrediction'), 'undefined', JSONType(tc, 'siftPrediction') = 'Null', 'null', JSONType(tc, 'siftPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftPrediction')), JSONExtractString(tc, 'siftPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'siftScore'), 'undefined', JSONType(tc, 'siftScore') = 'Null', 'null', JSONType(tc, 'siftScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftScore')), JSONExtractString(tc, 'siftScore'))), 'NA')), ';', concat('Polyphen-2: ', if((JSONExtractFloat(tc, 'polyphenScore') != 0 OR JSONExtractString(tc, 'polyphenPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'polyphenPrediction'), 'undefined', JSONType(tc, 'polyphenPrediction') = 'Null', 'null', JSONType(tc, 'polyphenPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenPrediction')), JSONExtractString(tc, 'polyphenPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'polyphenScore'), 'undefined', JSONType(tc, 'polyphenScore') = 'Null', 'null', JSONType(tc, 'polyphenScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenScore')), JSONExtractString(tc, 'polyphenScore'))), 'NA')), ';', concat('AlphaMissense: ', if((JSONExtractFloat(tc, 'alphaMissense', 'score') != 0 OR JSONExtractString(tc, 'alphaMissense', 'pathogenicity') != ''), concat('pathogenicity: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'pathogenicity'), 'undefined', JSONType(tc, 'alphaMissense', 'pathogenicity') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'pathogenicity') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'pathogenicity')), JSONExtractString(tc, 'alphaMissense', 'pathogenicity')), ', score: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'score'), 'undefined', JSONType(tc, 'alphaMissense', 'score') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'score')), JSONExtractString(tc, 'alphaMissense', 'score'))), 'NA'))), '') AS functionalImpact, - 'KRAS' AS gene, (SELECT name FROM snapshot_db.cancer_study WHERE cancer_study_identifier = 'msk_chord_2024') AS studyName, cta.v AS cancerTypeAll, - if(cn.v = floor(cn.v), toInt8(cn.v), NULL) AS cnv, multiIf(cnv IS NULL, '', cnv = 2, 'Amp', cnv = 1, 'Gain', cnv = 0, 'Diploid', cnv = -1, 'ShallowDel', 'DeepDel') AS copyNumber, - m.vs AS validationStatus, m.center AS center, - round(if(m.nAlt > 0 AND m.nRef >= 0, m.nAlt / (m.nAlt + m.nRef), NULL), if(if(m.nAlt > 0 AND m.nRef >= 0, m.nAlt / (m.nAlt + m.nRef), NULL) < 0.01, 4, 2)) AS vafNormal, - if(m.nAlt > 0, m.nAlt, NULL) AS normalAltCount, m.nAlt AS normalAltCountRaw, - if(m.nRef > 0, m.nRef, NULL) AS normalRefCount, m.nRef AS normalRefCountRaw, - JSONExtractString(tc, 'exon') AS exon - FROM mt0 AS m - LEFT JOIN ann ON ann.alteration = m.proteinChange - LEFT JOIN att AS tt ON tt.alteration = m.proteinChange AND tt.consequence = m.consequence AND tt.tumor_type = m.tumorType - LEFT JOIN g0 AS g ON g.chr = m.chr AND g.start = m.start AND g.end = m.end AND g.ref = m.ref AND g.var = m.var - LEFT JOIN ct0 AS ct ON ct.sid = m.sid LEFT JOIN mc0 AS mc ON mc.sid = m.sid - LEFT JOIN cta0 AS cta ON cta.sid = m.sid LEFT JOIN cn0 AS cn ON cn.sid = m.sid AND cn.g = 'KRAS' - UNION ALL - SELECT 'Colorectal' AS cohort, 'msk_chord_2024' AS study, 0 AS ord, - (SELECT rg.name FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id - WHERE cs.cancer_study_identifier = 'msk_chord_2024') AS build, - v.pid AS patient, v.sid AS sid, nullIf(ct.tumorType, '') AS cancerType, multiIf(v.gene1 != '' AND v.gene2 != '' AND v.gene1 != v.gene2, concat(v.gene1, '-', v.gene2, ' Fusion'), v.gene1 != '' AND v.gene2 != '', concat(v.gene1, ' intragenic'), v.gene1 != '' OR v.gene2 != '', concat(if(v.gene1 != '', v.gene1, v.gene2), if((upper(ifNull(v.class, '')) = 'INTERGENIC' OR (upper(ifNull(v.class, '')) IN ('', 'UNKNOWN', 'NA') AND upper(ifNull(v.eventInfo, '')) = concat(upper(if(v.gene1 != '', v.gene1, v.gene2)), '-INTERGENIC'))), ' intergenic', ' intragenic')), 'undefined intragenic') AS proteinChange, - if(vp.found = 1, vp.oncogenicity, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.oncogenicity, va1.oncogenicity)) AS oncogenicity, if(vp.found = 1, vp.level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.level, va1.level)) AS level, - if(vp.found = 1, vp.resistance_level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.resistance_level, va1.resistance_level)) AS resistanceLevel, if(vp.found = 1, vp.diagnostic_level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.diagnostic_level, va1.diagnostic_level)) AS diagnosticLevel, if(vp.found = 1, vp.prognostic_level, if(va2.oncogenicity != '' AND (va1.oncogenicity = '' OR va2.driver > va1.driver), va2.prognostic_level, va1.prognostic_level)) AS prognosticLevel, - toUInt8(if(vn.found = 1, vn.driver, greatest(va1.driver, va2.driver))) AS drv, - toUInt8(0) AS hot, - 'Fusion' AS mutationType, upper(v.class) AS variantType, - NULL AS vaf, '' AS vafText, NULL AS altCount, NULL AS refCount, - toInt64OrNull(mc.v) AS mutCount, v.chr AS chr, v.start AS start, NULL AS end, NULL AS ref, NULL AS var, v.status AS status, NULL AS pos, - '' AS hgvsg, - JSONExtractBool('', 'ok') AS gnOk, - arrayFirst(t -> JSONExtractString(t, 'transcriptId') = JSONExtractString('', 'canonical', 'KRAS'), JSONExtractArrayRaw('', 'transcripts')) AS tc, - JSONExtractString(tc, 'hgvsc') AS hgvsc, - JSONExtractString('', 'clinvar', 'significance') AS clinvar, JSONExtractString('', 'clinvar', 'conflicting') AS clinvarConflicting, - JSONExtractUInt('', 'clinvar', 'id') AS clinvarId, - arrayLast(e -> position(JSONExtractString(e, 'mutationStatus'), 'germline') > 0, JSONExtractArrayRaw('', 'signal')) AS sig, - if(lower(JSONExtractString(sig, 'mutationStatus')) = 'germline' AND arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) > 0, arraySum(arrayMap(c -> JSONExtractFloat(c, 'variantCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))) / arraySum(arrayMap(c -> JSONExtractFloat(c, 'tumorTypeCount'), JSONExtractArrayRaw(sig, 'countsByTumorType'))), NULL) AS signalFreq, - JSONExtractString('', 'rsid') AS rsid, JSONExtractRaw('', 'gnomad') AS gnomadRaw, JSONExtractRaw('', 'vcf') AS vcfRaw, - JSONExtractString('', 'seqRegion') AS seqRegion, - multiIf(JSONType('', 'gnomad', 'exome') = 'Object' AND JSONType('', 'gnomad', 'genome') = 'Object', if(JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an') > 0, (JSONExtractFloat('', 'gnomad', 'exome', 'alleleCount', 'ac') + JSONExtractFloat('', 'gnomad', 'genome', 'alleleCount', 'ac')) / (JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an') + JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an')), 0), JSONType('', 'gnomad', 'exome') = 'Object', coalesce(JSONExtract('', 'gnomad', 'exome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an') > 0, JSONExtractFloat('', 'gnomad', 'exome', 'alleleCount', 'ac') / JSONExtractFloat('', 'gnomad', 'exome', 'alleleNumber', 'an'), 0)), JSONType('', 'gnomad', 'genome') = 'Object', coalesce(JSONExtract('', 'gnomad', 'genome', 'alleleFrequency', 'af', 'Nullable(Float64)'), if(JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an') > 0, JSONExtractFloat('', 'gnomad', 'genome', 'alleleCount', 'ac') / JSONExtractFloat('', 'gnomad', 'genome', 'alleleNumber', 'an'), 0)), NULL) AS gnomadFreq, - JSONExtractRaw('', 'mutationAssessor') AS maRaw, - if('' != '', concat(concat('MutationAssessor: ', if(JSONType('', 'mutationAssessor') = 'Object', concat('impact: ', multiIf(NOT JSONHas('', 'mutationAssessor', 'prediction'), 'undefined', JSONType('', 'mutationAssessor', 'prediction') = 'Null', 'null', JSONType('', 'mutationAssessor', 'prediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat('', 'mutationAssessor', 'prediction')), JSONExtractString('', 'mutationAssessor', 'prediction')), ', score: ', multiIf(NOT JSONHas('', 'mutationAssessor', 'score'), 'undefined', JSONType('', 'mutationAssessor', 'score') = 'Null', 'null', JSONType('', 'mutationAssessor', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat('', 'mutationAssessor', 'score')), JSONExtractString('', 'mutationAssessor', 'score'))), 'NA')), ';', concat('SIFT: ', if((JSONExtractFloat(tc, 'siftScore') != 0 OR JSONExtractString(tc, 'siftPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'siftPrediction'), 'undefined', JSONType(tc, 'siftPrediction') = 'Null', 'null', JSONType(tc, 'siftPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftPrediction')), JSONExtractString(tc, 'siftPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'siftScore'), 'undefined', JSONType(tc, 'siftScore') = 'Null', 'null', JSONType(tc, 'siftScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'siftScore')), JSONExtractString(tc, 'siftScore'))), 'NA')), ';', concat('Polyphen-2: ', if((JSONExtractFloat(tc, 'polyphenScore') != 0 OR JSONExtractString(tc, 'polyphenPrediction') != ''), concat('impact: ', multiIf(NOT JSONHas(tc, 'polyphenPrediction'), 'undefined', JSONType(tc, 'polyphenPrediction') = 'Null', 'null', JSONType(tc, 'polyphenPrediction') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenPrediction')), JSONExtractString(tc, 'polyphenPrediction')), ', score: ', multiIf(NOT JSONHas(tc, 'polyphenScore'), 'undefined', JSONType(tc, 'polyphenScore') = 'Null', 'null', JSONType(tc, 'polyphenScore') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'polyphenScore')), JSONExtractString(tc, 'polyphenScore'))), 'NA')), ';', concat('AlphaMissense: ', if((JSONExtractFloat(tc, 'alphaMissense', 'score') != 0 OR JSONExtractString(tc, 'alphaMissense', 'pathogenicity') != ''), concat('pathogenicity: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'pathogenicity'), 'undefined', JSONType(tc, 'alphaMissense', 'pathogenicity') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'pathogenicity') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'pathogenicity')), JSONExtractString(tc, 'alphaMissense', 'pathogenicity')), ', score: ', multiIf(NOT JSONHas(tc, 'alphaMissense', 'score'), 'undefined', JSONType(tc, 'alphaMissense', 'score') = 'Null', 'null', JSONType(tc, 'alphaMissense', 'score') IN ('Int64', 'UInt64', 'Double'), toString(JSONExtractFloat(tc, 'alphaMissense', 'score')), JSONExtractString(tc, 'alphaMissense', 'score'))), 'NA'))), '') AS functionalImpact, - v.gene1 AS gene, (SELECT name FROM snapshot_db.cancer_study WHERE cancer_study_identifier = 'msk_chord_2024') AS studyName, cta.v AS cancerTypeAll, - if(cn.v = floor(cn.v), toInt8(cn.v), NULL) AS cnv, multiIf(cnv IS NULL, '', cnv = 2, 'Amp', cnv = 1, 'Gain', cnv = 0, 'Diploid', cnv = -1, 'ShallowDel', 'DeepDel') AS copyNumber, - NULL AS validationStatus, 'N/A' AS center, - round(if(NULL > 0 AND NULL >= 0, NULL / (NULL + NULL), NULL), if(if(NULL > 0 AND NULL >= 0, NULL / (NULL + NULL), NULL) < 0.01, 4, 2)) AS vafNormal, - if(NULL > 0, NULL, NULL) AS normalAltCount, NULL AS normalAltCountRaw, - if(NULL > 0, NULL, NULL) AS normalRefCount, NULL AS normalRefCountRaw, - JSONExtractString(tc, 'exon') AS exon - FROM v0 AS v - LEFT JOIN vk0 AS vk ON vk.sid = v.sid - LEFT JOIN sva AS va1 ON va1.gene = v.gene1 AND v.gene1 != '' LEFT JOIN sva AS va2 ON va2.gene = v.gene2 AND v.gene2 != '' - LEFT JOIN svp AS vp ON vp.site1_entrez = v.k1 AND vp.site2_entrez = v.k2 AND vp.sv_type = if((v.gene1 != '') + (v.gene2 != '') >= 2, 'FUSION', if(ifNull(v.class, '') IN ('DELETION', 'TRANSLOCATION', 'DUPLICATION', 'INSERTION', 'INVERSION', 'FUSION'), v.class, 'UNKNOWN')) AND vp.tumor_type = vk.tumorType - LEFT JOIN svp AS vn ON vn.site1_entrez = v.k1 AND vn.site2_entrez = v.k2 AND vn.sv_type = if((v.gene1 != '') + (v.gene2 != '') >= 2, 'FUSION', if(ifNull(v.class, '') IN ('DELETION', 'TRANSLOCATION', 'DUPLICATION', 'INSERTION', 'INVERSION', 'FUSION'), v.class, 'UNKNOWN')) AND vn.tumor_type = '' - LEFT JOIN ct0 AS ct ON ct.sid = v.sid LEFT JOIN mc0 AS mc ON mc.sid = v.sid - LEFT JOIN cta0 AS cta ON cta.sid = v.sid LEFT JOIN cn0 AS cn ON cn.sid = v.sid AND cn.g = v.gene1 -), -clins AS ( - SELECT 'msk_chord_2024' AS st, replaceOne(sample_unique_id, 'msk_chord_2024_', '') AS k, - CAST((groupArray(attribute_name), groupArray(attribute_value)), 'Map(String, String)') AS m - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'sample' AND attribute_name IN ('CLINICAL_GROUP', 'CLINICAL_SUMMARY', 'DIAGNOSIS_DESCRIPTION', 'ICD_O_HISTOLOGY_DESCRIPTION', 'PATHOLOGICAL_GROUP', 'SAMPLE_TYPE', 'MSI_TYPE', 'GENE_PANEL', 'SOMATIC_STATUS', 'SAMPLE_CLASS', 'FRACTION_GENOME_ALTERED', 'TMB_NONSYNONYMOUS', 'GLEASON_SAMPLE_LEVEL', 'MSI_COMMENT', 'MSI_SCORE', 'METASTATIC_SITE', 'ONCOTREE_CODE', 'PRIMARY_SITE', 'PDL1_POSITIVE', 'SAMPLE_COVERAGE', 'TUMOR_PURITY') AND attribute_value != '' - AND sample_unique_id IN (SELECT concat('msk_chord_2024_', x) FROM (SELECT sid AS x FROM m0 UNION ALL SELECT sid AS x FROM v0)) - GROUP BY k -), -clinp AS ( - SELECT 'msk_chord_2024' AS st, replaceOne(patient_unique_id, 'msk_chord_2024_', '') AS k, - CAST((groupArray(attribute_name), groupArray(attribute_value)), 'Map(String, String)') AS m - FROM (SELECT internal_id, sample_unique_id, patient_unique_id, attribute_name, attribute_value, cancer_study_identifier, type - FROM snapshot_db.clinical_data_derived WHERE lowerUTF8(trimBoth(attribute_value)) NOT IN ('', 'na', 'n/a', 'nan')) - WHERE cancer_study_identifier = 'msk_chord_2024' AND type = 'patient' AND attribute_name IN ('OS_STATUS', 'RACE', 'GENDER', 'STAGE_HIGHEST_RECORDED', 'ETHNICITY', 'CURRENT_AGE_DEID', 'SMOKING_PREDICTIONS_3_CLASSES', 'PRIOR_MED_TO_MSK', 'GLEASON_HIGHEST_REPORTED', 'HISTORY_OF_PDL1', 'NUM_ICDO_DX', 'SAMPLE_COUNT', 'GLEASON_FIRST_REPORTED', 'HER2', 'HR', 'OS_MONTHS', 'ADRENAL_GLANDS', 'BONE', 'CNS_BRAIN', 'INTRA_ABDOMINAL', 'LIVER', 'LUNG', 'LYMPH_NODES', 'OTHER', 'PLEURA', 'REPRODUCTIVE_ORGANS') AND attribute_value != '' - AND patient_unique_id IN (SELECT concat('msk_chord_2024_', x) FROM (SELECT pid AS x FROM m0 UNION ALL SELECT pid AS x FROM v0)) - GROUP BY k -), -rows AS (SELECT r.*, cs.m AS clinS, cp.m AS clinP FROM rows0 AS r - LEFT JOIN clins AS cs ON cs.st = r.study AND cs.k = r.sid LEFT JOIN clinp AS cp ON cp.st = r.study AND cp.k = r.patient) -SELECT v, count() AS n FROM (SELECT ifNull(toString(cancerType), '') AS v FROM rows WHERE 1) GROUP BY v ORDER BY n DESC, v LIMIT 500 - -- view 0 mutations: table:attributes · msk_chord_2024 SELECT m.attr_id AS id, m.display_name AS name, m.description AS description, m.datatype AS datatype, m.patient_attribute AS patient, toInt32OrZero(m.priority) AS priority FROM snapshot_db.clinical_attribute_meta m diff --git a/test/snapshots/mutcompare.sql b/test/snapshots/mutcompare.sql index 4a80cca2..251daae1 100644 --- a/test/snapshots/mutcompare.sql +++ b/test/snapshots/mutcompare.sql @@ -65,7 +65,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic AND smp.stable_id IN (SELECT sid FROM cohort)), m AS (SELECT `GENE.hugoGeneSymbol` AS gene, proteinPosStart AS pos, proteinChange AS change, mutationType AS mtype, patientId AS pid, sampleId AS sid, mutationStatus AS status, if((`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM annotation.oncokb - WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION') + WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN ('TP53')) OR (`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (SELECT DISTINCT mu.hugo_gene_symbol AS hugo_gene_symbol, mu.alteration AS alteration, mu.mutation_type AS mutation_type FROM ( SELECT m.`GENE.hugoGeneSymbol` AS hugo_gene_symbol, m.proteinChange AS alteration, ifNull(m.mutationType, '') AS mutation_type, st.src AS src, assumeNotNull(m.chr) AS chr, m.startPosition AS start, m.endPosition AS end, @@ -74,7 +74,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic INNER JOIN (SELECT cs.cancer_study_identifier AS study, multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') AS src FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier IN ('brca_tcga_pan_can_atlas_2018')) st ON st.study = m.studyId - WHERE m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') + WHERE (startsWith(m.molecularProfileId, 'brca_tcga_pan_can_atlas_2018_')) AND m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') AND st.src != '' AND ifNull(m.chr, '') != '' AND ifNull(m.startPosition, 0) != 0 AND ifNull(m.endPosition, 0) != 0 AND ifNull(m.referenceAllele, '') != '' AND ifNull(m.tumorSeqAllele, '') != '' AND ifNull(m.proteinChange, '') != '' ) mu @@ -140,7 +140,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic AND smp.stable_id IN (SELECT sid FROM cohort)), m AS (SELECT `GENE.hugoGeneSymbol` AS gene, proteinPosStart AS pos, proteinChange AS change, mutationType AS mtype, patientId AS pid, sampleId AS sid, mutationStatus AS status, if((`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM annotation.oncokb - WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION') + WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN ('TP53')) OR (`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (SELECT DISTINCT mu.hugo_gene_symbol AS hugo_gene_symbol, mu.alteration AS alteration, mu.mutation_type AS mutation_type FROM ( SELECT m.`GENE.hugoGeneSymbol` AS hugo_gene_symbol, m.proteinChange AS alteration, ifNull(m.mutationType, '') AS mutation_type, st.src AS src, assumeNotNull(m.chr) AS chr, m.startPosition AS start, m.endPosition AS end, @@ -149,7 +149,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic INNER JOIN (SELECT cs.cancer_study_identifier AS study, multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') AS src FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier IN ('brca_tcga_pan_can_atlas_2018')) st ON st.study = m.studyId - WHERE m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') + WHERE (startsWith(m.molecularProfileId, 'brca_tcga_pan_can_atlas_2018_')) AND m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') AND st.src != '' AND ifNull(m.chr, '') != '' AND ifNull(m.startPosition, 0) != 0 AND ifNull(m.endPosition, 0) != 0 AND ifNull(m.referenceAllele, '') != '' AND ifNull(m.tumorSeqAllele, '') != '' AND ifNull(m.proteinChange, '') != '' ) mu @@ -365,7 +365,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic AND smp.stable_id IN (SELECT sid FROM cohort)), m AS (SELECT `GENE.hugoGeneSymbol` AS gene, proteinPosStart AS pos, proteinChange AS change, mutationType AS mtype, patientId AS pid, sampleId AS sid, mutationStatus AS status, if((`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM annotation.oncokb - WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION') + WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN ('TP53')) OR (`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (SELECT DISTINCT mu.hugo_gene_symbol AS hugo_gene_symbol, mu.alteration AS alteration, mu.mutation_type AS mutation_type FROM ( SELECT m.`GENE.hugoGeneSymbol` AS hugo_gene_symbol, m.proteinChange AS alteration, ifNull(m.mutationType, '') AS mutation_type, st.src AS src, assumeNotNull(m.chr) AS chr, m.startPosition AS start, m.endPosition AS end, @@ -374,7 +374,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic INNER JOIN (SELECT cs.cancer_study_identifier AS study, multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') AS src FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier IN ('brca_tcga_pan_can_atlas_2018')) st ON st.study = m.studyId - WHERE m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') + WHERE (startsWith(m.molecularProfileId, 'brca_tcga_pan_can_atlas_2018_')) AND m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') AND st.src != '' AND ifNull(m.chr, '') != '' AND ifNull(m.startPosition, 0) != 0 AND ifNull(m.endPosition, 0) != 0 AND ifNull(m.referenceAllele, '') != '' AND ifNull(m.tumorSeqAllele, '') != '' AND ifNull(m.proteinChange, '') != '' ) mu @@ -440,7 +440,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic AND smp.stable_id IN (SELECT sid FROM cohort)), m AS (SELECT `GENE.hugoGeneSymbol` AS gene, proteinPosStart AS pos, proteinChange AS change, mutationType AS mtype, patientId AS pid, sampleId AS sid, mutationStatus AS status, if((`GENE.hugoGeneSymbol`, proteinChange) IN (SELECT hugo_gene_symbol, alteration FROM annotation.oncokb - WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION') + WHERE oncokb_version = 'v7.5' AND is_driver AND alteration_type = 'MUTATION' AND hugo_gene_symbol IN ('TP53')) OR (`GENE.hugoGeneSymbol`, proteinChange, ifNull(mutationType, '')) IN (SELECT DISTINCT mu.hugo_gene_symbol AS hugo_gene_symbol, mu.alteration AS alteration, mu.mutation_type AS mutation_type FROM ( SELECT m.`GENE.hugoGeneSymbol` AS hugo_gene_symbol, m.proteinChange AS alteration, ifNull(m.mutationType, '') AS mutation_type, st.src AS src, assumeNotNull(m.chr) AS chr, m.startPosition AS start, m.endPosition AS end, @@ -449,7 +449,7 @@ svp AS (SELECT site1_entrez, site2_entrez, sv_type, tumor_type, c.1 AS oncogenic INNER JOIN (SELECT cs.cancer_study_identifier AS study, multiIf(rg.name = 'hg19', 'genome_nexus', rg.name = 'hg38', 'genome_nexus_grch38', '') AS src FROM snapshot_db.cancer_study cs JOIN snapshot_db.reference_genome rg ON rg.reference_genome_id = cs.reference_genome_id WHERE cs.cancer_study_identifier IN ('brca_tcga_pan_can_atlas_2018')) st ON st.study = m.studyId - WHERE m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') + WHERE (startsWith(m.molecularProfileId, 'brca_tcga_pan_can_atlas_2018_')) AND m.studyId IN ('brca_tcga_pan_can_atlas_2018') AND m.`GENE.hugoGeneSymbol` IN ('TP53') AND st.src != '' AND ifNull(m.chr, '') != '' AND ifNull(m.startPosition, 0) != 0 AND ifNull(m.endPosition, 0) != 0 AND ifNull(m.referenceAllele, '') != '' AND ifNull(m.tumorSeqAllele, '') != '' AND ifNull(m.proteinChange, '') != '' ) mu diff --git a/test/snapshots/timeline.sql b/test/snapshots/timeline.sql index 29efaf34..1ea53ac1 100644 --- a/test/snapshots/timeline.sql +++ b/test/snapshots/timeline.sql @@ -773,6 +773,38 @@ g AS ( rows AS (SELECT 'Breast' AS cohort, 'msk_chord_2024' AS study, 0 AS ord, 'P-0000012' AS patient, splitByString(', ', g.samples)[1] AS sid, g.* EXCEPT (rec), '' AS genePanel, '' AS genePanelShown FROM g) SELECT cohort, study, countIf(1) AS n, count() AS all FROM rows GROUP BY cohort, study +-- view 1 alterations: alterations:sv:rows · msk_chord_2024 +WITH s AS ( + SELECT smp.stable_id AS sid, if(indexOf(['P-0000012-T02-IM3', 'P-0000012-T03-IM3'], smp.stable_id) = 0, 1000000, indexOf(['P-0000012-T02-IM3', 'P-0000012-T03-IM3'], smp.stable_id)) AS o, + arrayStringConcat(arraySort([ifNull(toString(g1.hugo_gene_symbol), ''), ifNull(toString(g2.hugo_gene_symbol), ''), ifNull(toString(sv.site1_position), ''), ifNull(toString(sv.site2_position), ''), ifNull(toString(sv.site1_chromosome), ''), ifNull(toString(sv.site2_chromosome), ''), ifNull(toString(sv.class), '')]), '_') AS k, + tuple(o, sv.internal_id) AS r, tuple(gene1, gene2, class, eventInfo, pos1, pos2, breakpointType, connectionType, frame, site1, site2, length, dnaSupport, rnaSupport, status, svAnnotation, comments) AS rec0, + ifNull(g1.hugo_gene_symbol, '') AS gene1, ifNull(g2.hugo_gene_symbol, '') AS gene2, + ifNull(sv.class, '') AS class, ifNull(sv.event_info, '') AS eventInfo, sv.breakpoint_type AS breakpointType, sv.connection_type AS connectionType, + sv.site2_effect_on_frame AS frame, sv.site1_description AS site1, sv.site2_description AS site2, + if(sv.site1_position IS NULL, '', concat(ifNull(sv.site1_chromosome, ''), ':', toString(sv.site1_position))) AS pos1, + if(sv.site2_position IS NULL, '', concat(ifNull(sv.site2_chromosome, ''), ':', toString(sv.site2_position))) AS pos2, + sv.length AS length, sv.tumor_variant_count AS tumorVariantCount, sv.tumor_read_count AS tumorReadCount, + sv.dna_support AS dnaSupport, sv.rna_support AS rnaSupport, sv.sv_status AS status, sv.annotation AS svAnnotation, sv.comments AS comments + FROM snapshot_db.structural_variant sv + JOIN snapshot_db.sample smp ON smp.internal_id = sv.sample_id + LEFT JOIN snapshot_db.gene g1 ON g1.entrez_gene_id = sv.site1_entrez_gene_id + LEFT JOIN snapshot_db.gene g2 ON g2.entrez_gene_id = sv.site2_entrez_gene_id + WHERE sv.sample_id IN (SELECT s.internal_id FROM snapshot_db.sample s JOIN snapshot_db.patient p ON p.internal_id = s.patient_id + JOIN snapshot_db.cancer_study cs ON cs.cancer_study_id = p.cancer_study_id + WHERE cs.cancer_study_identifier = 'msk_chord_2024' AND p.stable_id = 'P-0000012') +), +g AS ( + SELECT k, arrayStringConcat(arraySort(x -> if(indexOf(['P-0000012-T02-IM3', 'P-0000012-T03-IM3'], x) = 0, 1000000, indexOf(['P-0000012-T02-IM3', 'P-0000012-T03-IM3'], x)), groupUniqArray(sid)), ', ') AS samples, min(if(indexOf(['P-0000012-T02-IM3', 'P-0000012-T03-IM3'], sid) = 0, 1000000, indexOf(['P-0000012-T02-IM3', 'P-0000012-T03-IM3'], sid))) AS so, + argMin(rec0, r) AS rec, tupleElement(rec, 1) AS gene1, tupleElement(rec, 2) AS gene2, tupleElement(rec, 3) AS class, tupleElement(rec, 4) AS eventInfo, tupleElement(rec, 5) AS pos1, tupleElement(rec, 6) AS pos2, tupleElement(rec, 7) AS breakpointType, tupleElement(rec, 8) AS connectionType, tupleElement(rec, 9) AS frame, tupleElement(rec, 10) AS site1, tupleElement(rec, 11) AS site2, tupleElement(rec, 12) AS length, tupleElement(rec, 13) AS dnaSupport, tupleElement(rec, 14) AS rnaSupport, tupleElement(rec, 15) AS status, tupleElement(rec, 16) AS svAnnotation, tupleElement(rec, 17) AS comments, + max(tumorVariantCount) AS tumorVariantCount, max(tumorReadCount) AS tumorReadCount + FROM s GROUP BY k +), +rows AS (SELECT 'Breast' AS cohort, 'msk_chord_2024' AS study, 0 AS ord, 'P-0000012' AS patient, splitByString(', ', g.samples)[1] AS sid, g.* EXCEPT (rec), '' AS genePanel, '' AS genePanelShown FROM g) +SELECT * EXCEPT (k), count() OVER () AS total FROM rows +WHERE 1 +ORDER BY gene1, so, gene2, gene1, gene2, pos1, pos2, class, eventInfo, k +LIMIT 25 OFFSET 0 + -- view 1 alterations: alterations:vafs · msk_chord_2024 WITH m AS ( SELECT sampleId AS sid, `GENE.hugoGeneSymbol` AS gene, proteinChange, mutationType, variantType, chr, startPosition AS start, endPosition AS end, diff --git a/test/table-summaries-fixture.test.ts b/test/table-summaries-fixture.test.ts new file mode 100644 index 00000000..e91640dc --- /dev/null +++ b/test/table-summaries-fixture.test.ts @@ -0,0 +1,184 @@ +// The column summaries of a table's counts statement (lib/table-query.ts countsSql `summarize`, read +// by summaryOf), run on the fixture study (test/fixtures/peer-study on connection b): +// S1 per (cohort, study), a numeric column's min and max and a text column's distinct values ('' a +// value) are over every row of the part, whatever the query's search and filters; the row's +// `n` still follows the query +// S2 they equal what valuesSql gives for that part with an empty query (Mutations: vaf's lo/hi, +// cancerType's value set), for KRAS, TP53 and EGFR +// S3 a numeric column with no non-null value in a part: min and max null +// S4 a text column with more than VALUES_MAX distinct values: capped at VALUES_MAX, truncated; at +// VALUES_MAX exactly, not truncated +// +// Runs when CLICKHOUSE2_* point at the fixture (`npm run peer-db` prints the lines) and is skipped otherwise. +import { test, describe, before } from "node:test"; +import assert from "node:assert/strict"; +import type { ChConn } from "../lib/ch.ts"; +import type { CohortDef } from "../lib/types.ts"; +import type { RowSource, TableQuery } from "../lib/table-query.ts"; + +const FIXTURE = "cbiolab_peer_fixture"; +delete process.env.CH_RUN_CACHE; +const { secondary, chQuery } = await import("../lib/ch.ts"); +const { compileCohortDef } = await import("../lib/cohort2.ts"); +const { cohortSubquery } = await import("../lib/sql-kinds.ts"); +const { MUTATION_DEFAULT_COLUMNS, mutationRowSource } = await import("../lib/mutation-table.ts"); +const tq = await import("../lib/table-query.ts"); + +type Summary = + | { column: string; numeric: true; min: number | null; max: number | null } + | { column: string; numeric: false; values: string[]; truncated: boolean }; +type Ask = { column: string; numeric: boolean }; +const T = tq as unknown as { + countsSql: (src: RowSource, q: TableQuery, defaults: string[], summarize?: Ask[]) => unknown; + valuesSql: (src: RowSource, q: TableQuery, defaults: string[], column: string) => unknown; + summaryOf?: (summarize: Ask[], row: Record) => Summary[]; + VALUES_MAX: number; +}; +const summaryOf = (ask: Ask[], row: Record) => { + assert.equal(typeof T.summaryOf, "function", "lib/table-query.ts exports summaryOf"); + return T.summaryOf!(ask, row); +}; + +const noDb = process.env.CLICKHOUSE2_LABEL === "fixture peer" ? false : "needs the fixture study on connection b: CLICKHOUSE2_* from `npm run peer-db`"; +let conn: ChConn; +before(() => { + if (noDb) return; + conn = secondary()!; + assert.ok(conn, "CLICKHOUSE2_URL is set but connection b is not configured"); +}); +const run = async (sql: unknown) => (await chQuery>(String(sql), conn)).data; + +const FACTS: Ask[] = [{ column: "vaf", numeric: true }, { column: "cancerType", numeric: false }]; +const COHORTS: [string, CohortDef | null][] = [ + ["all", null], + ["female", { all: [{ kind: "clinical", attribute: "SEX", op: "=", value: "Female" }] } as unknown as CohortDef], +]; +const parts = () => COHORTS.map(([cohort, def]) => ({ cohort, study: FIXTURE, cohortSql: cohortSubquery(compileCohortDef(def, { study: FIXTURE, db: conn.db })) })); +const source = (gene: string, ps = parts()) => mutationRowSource(ps, conn.db, gene, "fixture", { hg19: "fixture", hg38: null }); +const key = (r: Record) => r.cohort + "|" + r.study; +const sorted = (xs: string[]) => [...xs].sort(); +const textOf = (s: Summary | undefined) => { assert.ok(s && !s.numeric, JSON.stringify(s)); return s; }; +const numOf = (s: Summary | undefined) => { assert.ok(s && s.numeric, JSON.stringify(s)); return s; }; + +/** per part: the summaries of its counts row */ +async function summariesBy(src: RowSource, q: TableQuery, ask: Ask[]) { + const rows = await run(T.countsSql(src, q, MUTATION_DEFAULT_COLUMNS, ask)); + return new Map(rows.map((r) => [key(r), { n: Number(r.n), all: Number(r.all), sums: summaryOf(ask, r) }])); +} + +for (const gene of ["KRAS", "TP53", "EGFR"]) { + describe(gene, () => { + test("S1 the summaries ignore the query's search and filters; n follows the query", { skip: noDb }, async (t) => { + const src = source(gene); + // a query that keeps few rows: a search and a filter on the summarised text column itself + const anyType = (await run(T.valuesSql(src, {}, MUTATION_DEFAULT_COLUMNS, "cancerType"))).map((r) => String(r.v)).find((v) => v !== ""); + assert.ok(anyType, "the fixture has a cancer type on " + gene + "'s rows"); + const q: TableQuery = { search: gene === "KRAS" ? "G12" : "R", filters: { cancerType: { values: [anyType] }, vaf: { min: 0.2 } } }; + const [plain, narrowed] = await Promise.all([summariesBy(src, {}, FACTS), summariesBy(src, q, FACTS)]); + assert.ok(plain.size >= 1, "parts with rows: " + plain.size); + assert.deepEqual(sorted([...narrowed.keys()]), sorted([...plain.keys()]), "one counts row per part either way"); + let narrower = false; + for (const [k, p] of plain) { + const n = narrowed.get(k)!; + const norm = (s: Summary[]) => s.map((x) => x.numeric ? x : { ...x, values: sorted(x.values) }); + assert.deepEqual(norm(n.sums), norm(p.sums), k + ": the summaries are the same with or without the query"); + assert.equal(n.all, p.all, k + ": all is every row"); + assert.ok(n.n <= p.n, k + ": n follows the query"); + if (n.n < p.n) narrower = true; + } + assert.ok(narrower, "the query keeps fewer rows in some part, so the comparison says something"); + t.diagnostic(JSON.stringify([...plain].map(([k, v]) => [k, v.n, v.sums]))); + }); + + test("S2 the summaries equal valuesSql's lo/hi and value set for the same part, empty query", { skip: noDb }, async () => { + const ps = parts(); + const sums = await summariesBy(source(gene, ps), { search: "zzz-no-such-row" }, FACTS); + let compared = 0; + for (const p of ps) { + const one = source(gene, [p]); + const s = sums.get(p.cohort + "|" + p.study); + const [vaf, types] = await Promise.all([run(T.valuesSql(one, {}, MUTATION_DEFAULT_COLUMNS, "vaf")), run(T.valuesSql(one, {}, MUTATION_DEFAULT_COLUMNS, "cancerType"))]); + if (!s) { assert.ok(!types.length, p.cohort + ": no counts row, so no rows"); continue; } + compared++; + const v = numOf(s.sums[0]), c = textOf(s.sums[1]); + const lo = vaf[0]?.lo == null || Number(vaf[0].n) === 0 ? null : Number(vaf[0].lo); + const hi = vaf[0]?.hi == null || Number(vaf[0].n) === 0 ? null : Number(vaf[0].hi); + assert.equal(v.min == null ? null : Number(v.min), lo, p.cohort + ": vaf min"); + assert.equal(v.max == null ? null : Number(v.max), hi, p.cohort + ": vaf max"); + assert.deepEqual(sorted(c.values), sorted(types.map((r) => String(r.v))), p.cohort + ": the cancer types"); + assert.equal(c.truncated, false); + } + assert.ok(compared >= 1, "some part has rows"); + }); + }); +} + +describe("S2 the fixture holds the shapes the comparison needs", () => { + test("some gene's part has a vaf, and some part more than one cancer type", { skip: noDb }, async () => { + const all = await Promise.all(["KRAS", "TP53", "EGFR"].map((g) => summariesBy(source(g), {}, FACTS))); + const sums = all.flatMap((m) => [...m.values()].map((x) => x.sums)); + assert.ok(sums.some((s) => numOf(s[0]).max != null), "a part with a vaf"); + assert.ok(sums.some((s) => textOf(s[1]).values.filter((v) => v !== "").length >= 2), "a part with two cancer types"); + }); +}); + +// ---- synthetic row sources on the same server: the edges ----------------------------------------- + +/** rows of two parts: `p1` with `k` distinct text values and numbers; `p2` with only NULL numbers and '' text */ +function synthetic(k: number): RowSource { + return { + with: "WITH rows AS (\n" + + " SELECT 'c' AS cohort, 'p1' AS study, toNullable(toFloat64(number) / 10) AS x, 'v' || toString(number) AS t FROM numbers(" + k + ")\n" + + " UNION ALL SELECT 'c', 'p1', NULL, '' \n" + + " UNION ALL SELECT 'c', 'p2', CAST(NULL AS Nullable(Float64)), '' FROM numbers(3)\n)\n", + columns: [ + { id: "x", name: "X", numeric: true, text: "ifNull(toString(x), '')", num: "x" }, + { id: "t", name: "T", numeric: false, text: "t" }, + ], + select: "*", defaultOrder: "x", tiebreak: "t", + }; +} +const ASK: Ask[] = [{ column: "x", numeric: true }, { column: "t", numeric: false }]; + +describe("synthetic parts", () => { + test("S3 a part whose numeric column is NULL in every row: min and max null; its text values hold ''", { skip: noDb }, async () => { + const by = await summariesBy(synthetic(3), {}, ASK); + const p2 = by.get("c|p2"); + assert.ok(p2, JSON.stringify([...by.keys()])); + assert.deepEqual(numOf(p2.sums[0]), { column: "x", numeric: true, min: null, max: null }); + assert.deepEqual(textOf(p2.sums[1]).values, [""]); + const p1 = by.get("c|p1")!; + assert.deepEqual({ ...numOf(p1.sums[0]), min: Number(numOf(p1.sums[0]).min), max: Number(numOf(p1.sums[0]).max) }, + { column: "x", numeric: true, min: 0, max: 0.2 }, "a NULL beside values is not a value; 0 is"); + assert.deepEqual(sorted(textOf(p1.sums[1]).values), ["", "v0", "v1", "v2"], "'' is a value"); + }); + + test("S1 a search and filter that keep no row of a part leave its summaries whole", { skip: noDb }, async () => { + const [plain, none] = await Promise.all([summariesBy(synthetic(3), {}, ASK), summariesBy(synthetic(3), { search: "v1", filters: { x: { min: 0.05 } } }, ASK)]); + assert.equal(none.get("c|p2")!.n, 0); + assert.equal(none.get("c|p1")!.n, 1); + for (const k of plain.keys()) { + const norm = (s: Summary[]) => s.map((x) => x.numeric ? { ...x, min: x.min == null ? null : Number(x.min), max: x.max == null ? null : Number(x.max) } : { ...x, values: sorted(x.values) }); + assert.deepEqual(norm(none.get(k)!.sums), norm(plain.get(k)!.sums), k); + } + }); + + test("S4 more than VALUES_MAX distinct text values: capped at VALUES_MAX and truncated", { skip: noDb }, async () => { + const M = T.VALUES_MAX; + const by = await summariesBy(synthetic(M + 10), {}, ASK); // M + 11 distinct with '' + const t = textOf(by.get("c|p1")!.sums[1]); + assert.equal(t.values.length, M); + assert.equal(new Set(t.values).size, M); + assert.equal(t.truncated, true); + }); + + test("S4 exactly VALUES_MAX distinct text values: all of them, not truncated", { skip: noDb }, async () => { + const M = T.VALUES_MAX; + const by = await summariesBy(synthetic(M - 1), {}, ASK); // M - 1 values plus '' + const t = textOf(by.get("c|p1")!.sums[1]); + assert.equal(t.values.length, M); + assert.equal(t.truncated, false); + const one = await summariesBy(synthetic(M), {}, ASK); // M + 1 + assert.equal(textOf(one.get("c|p1")!.sums[1]).truncated, true, "one past the limit is truncated"); + }); +}); diff --git a/test/table-summaries.test.ts b/test/table-summaries.test.ts new file mode 100644 index 00000000..c818ae47 --- /dev/null +++ b/test/table-summaries.test.ts @@ -0,0 +1,176 @@ +// A table's column summaries taken in its counts statement (lib/table-query.ts): countsSql's +// `summarize`, one part's summaries from its counts row (summaryOf), their merge across parts and +// databases (mergeSummaries), and a summary from a column's values (summaryOfValues). The SQL itself +// is run on the fixture in test/table-summaries-fixture.test.ts; here the rules that need no database. +// S3 a numeric column with no value in a part: min and max null +// S5 an unknown column in `summarize` throws; none (or an empty list) leaves the statement as it was +// S6 mergeSummaries: numeric min of mins / max of maxes, nulls ignored, all null → null; text the +// union without duplicates, truncated when a part was or the union passes VALUES_MAX (capped); +// a part without a column contributes nothing +// S7 summaryOfValues: numeric → its min/max; text → its values' strings and its truncated flag +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as tq from "../lib/table-query.ts"; +import type { RowSource, TableQuery } from "../lib/table-query.ts"; + +type Summary = + | { column: string; numeric: true; min: number | null; max: number | null } + | { column: string; numeric: false; values: string[]; truncated: boolean }; +type Ask = { column: string; numeric: boolean }; +const T = tq as unknown as { + countsSql: (src: RowSource, q: TableQuery, defaults: string[], summarize?: Ask[]) => unknown; + summaryOf?: (summarize: Ask[], row: Record) => Summary[]; + mergeSummaries?: (summarize: Ask[], parts: Summary[][]) => Summary[]; + summaryOfValues?: (v: unknown) => Summary; + VALUES_MAX: number; +}; +const need = (k: K) => { + assert.equal(typeof T[k], "function", "lib/table-query.ts exports " + String(k)); + return T[k] as NonNullable<(typeof T)[K]>; +}; + +const SRC: RowSource = { + with: "WITH rows AS (SELECT 'c' AS cohort, 's' AS study, 1.5 AS x, 'a' AS t)\n", + columns: [ + { id: "x", name: "X", numeric: true, text: "toString(x)", num: "x" }, + { id: "t", name: "T", numeric: false, text: "t" }, + ], + select: "*", defaultOrder: "x", tiebreak: "t", +}; +const ASK: Ask[] = [{ column: "x", numeric: true }, { column: "t", numeric: false }]; +const num = (column: string, min: number | null, max: number | null): Summary => ({ column, numeric: true, min, max }); +const txt = (column: string, values: string[], truncated = false): Summary => ({ column, numeric: false, values, truncated }); +const sortedText = (s: Summary | undefined) => { + assert.ok(s && !s.numeric, "a text summary: " + JSON.stringify(s)); + return { ...s, values: [...s.values].sort() }; +}; + +// ---- S5 ------------------------------------------------------------------------------------------ + +test("S5 an unknown column in summarize throws", () => { + assert.throws(() => T.countsSql(SRC, {}, [], [{ column: "nope", numeric: true }])); + assert.throws(() => T.countsSql(SRC, {}, [], [{ column: "t", numeric: false }, { column: "nope", numeric: false }])); +}); + +test("S5 no summarize, or an empty one, gives the statement countsSql gave without the argument", () => { + const plain = String(T.countsSql(SRC, { search: "a" }, ["x", "t"])); + assert.equal(String(T.countsSql(SRC, { search: "a" }, ["x", "t"], [])), plain); + assert.equal(String(T.countsSql(SRC, { search: "a" }, ["x", "t"], undefined)), plain); + assert.notEqual(String(T.countsSql(SRC, { search: "a" }, ["x", "t"], ASK)), plain, "a summarize adds to the statement"); +}); + +// ---- S3: summaryOf ------------------------------------------------------------------------------- + +test("S3 summaryOf on a counts row without the summary columns: numeric min and max null, text no values", () => { + const summaryOf = need("summaryOf"); + const got = summaryOf(ASK, { cohort: "c", study: "s", n: 3, all: 3 }); + assert.equal(got.length, 2); + assert.deepEqual(got[0], num("x", null, null)); + assert.equal(got[1].column, "t"); + assert.equal(got[1].numeric, false); + assert.deepEqual((got[1] as { values: string[] }).values, []); +}); + +test("S3 summaryOf with no summarize asked: no summaries", () => { + assert.deepEqual(need("summaryOf")([], { cohort: "c", study: "s", n: 1, all: 1 }), []); +}); + +// ---- S6: mergeSummaries -------------------------------------------------------------------------- + +test("S6 numeric: the min of the parts' mins and the max of their maxes", () => { + const merge = need("mergeSummaries"); + const got = merge([{ column: "x", numeric: true }], [[num("x", 0.2, 0.5)], [num("x", 0.1, 0.3)], [num("x", 0.4, 0.9)]]); + assert.deepEqual(got, [num("x", 0.1, 0.9)]); +}); + +test("S6 numeric: a part with null is ignored; every part null → null", () => { + const merge = need("mergeSummaries"); + assert.deepEqual(merge([{ column: "x", numeric: true }], [[num("x", null, null)], [num("x", 0, 0.003)]]), [num("x", 0, 0.003)]); + assert.deepEqual(merge([{ column: "x", numeric: true }], [[num("x", 0.7, 0.8)], [num("x", null, null)]]), [num("x", 0.7, 0.8)]); + assert.deepEqual(merge([{ column: "x", numeric: true }], [[num("x", null, null)], [num("x", null, null)]]), [num("x", null, null)]); + assert.deepEqual(merge([{ column: "x", numeric: true }], []), [num("x", null, null)], "no parts at all"); +}); + +test("S6 numeric: negative and zero values merge as numbers, not by truthiness", () => { + const merge = need("mergeSummaries"); + assert.deepEqual(merge([{ column: "x", numeric: true }], [[num("x", 0, 0)], [num("x", -2, -1)]]), [num("x", -2, 0)]); +}); + +test("S6 text: the union of the parts' values without duplicates, '' kept as a value", () => { + const merge = need("mergeSummaries"); + const got = merge([{ column: "t", numeric: false }], [[txt("t", ["Colon", ""])], [txt("t", ["Rectal", "Colon"])], [txt("t", [])]]); + assert.equal(got.length, 1); + assert.deepEqual(sortedText(got[0]), txt("t", ["", "Colon", "Rectal"])); +}); + +test("S6 text: truncated when any part was truncated", () => { + const merge = need("mergeSummaries"); + const got = merge([{ column: "t", numeric: false }], [[txt("t", ["a"], true)], [txt("t", ["b"])]]); + assert.equal((got[0] as { truncated: boolean }).truncated, true); + const none = merge([{ column: "t", numeric: false }], [[txt("t", ["a"])], [txt("t", ["b"])]]); + assert.equal((none[0] as { truncated: boolean }).truncated, false); +}); + +test("S6 text: a union past VALUES_MAX is capped at VALUES_MAX and truncated; exactly VALUES_MAX is not", () => { + const merge = need("mergeSummaries"); + const M = T.VALUES_MAX; + assert.equal(M, 500); + const vals = (from: number, k: number) => Array.from({ length: k }, (_, i) => "v" + (from + i)); + const over = merge([{ column: "t", numeric: false }], [[txt("t", vals(0, 300))], [txt("t", vals(250, 300))]]); // 550 distinct + const o = over[0] as { values: string[]; truncated: boolean }; + assert.equal(o.values.length, M); + assert.equal(new Set(o.values).size, M, "no duplicates"); + assert.equal(o.truncated, true); + const at = merge([{ column: "t", numeric: false }], [[txt("t", vals(0, 300))], [txt("t", vals(100, 400))]]); // 500 distinct + const a = at[0] as { values: string[]; truncated: boolean }; + assert.equal(a.values.length, M); + assert.equal(a.truncated, false); +}); + +test("S6 a part missing a column contributes nothing to it", async (t) => { + const merge = need("mergeSummaries"); + await t.test("a part missing the last column, or every column", () => { + const got = merge(ASK, [[num("x", 1, 2), txt("t", ["a"])], [num("x", 0.5, 1)], []]); + assert.deepEqual(got[0], num("x", 0.5, 2)); + assert.deepEqual(sortedText(got[1]), txt("t", ["a"])); + }); + await t.test("a part missing the first column still contributes its other columns", () => { + const got = merge(ASK, [[num("x", 1, 2), txt("t", ["a"])], [txt("t", ["b"])]]); + assert.deepEqual(got[0], num("x", 1, 2)); + assert.deepEqual(sortedText(got[1]), txt("t", ["a", "b"])); + }); + await t.test("a part listing the columns in another order is read by column", () => { + const got = merge(ASK, [[num("x", 1, 2), txt("t", ["a"])], [txt("t", ["b"]), num("x", 0, 5)]]); + assert.deepEqual(got[0], num("x", 0, 5)); + assert.deepEqual(sortedText(got[1]), txt("t", ["a", "b"])); + }); +}); + +test("S6 the merge follows summarize's order, one summary per asked column", () => { + const merge = need("mergeSummaries"); + const got = merge([{ column: "t", numeric: false }, { column: "x", numeric: true }], [[num("x", 1, 2), txt("t", ["a"])]]); + assert.deepEqual(got.map((s) => s.column), ["t", "x"]); +}); + +// ---- S7: summaryOfValues ------------------------------------------------------------------------- + +test("S7 summaryOfValues: a numeric column's values → its min and max", () => { + const f = need("summaryOfValues"); + assert.deepEqual(f({ column: "vaf", numeric: true, min: 0.003, max: 0.31, n: 4 }), num("vaf", 0.003, 0.31)); + assert.deepEqual(f({ column: "vaf", numeric: true, min: null, max: null, n: 0 }), num("vaf", null, null)); +}); + +test("S7 summaryOfValues: a text column's values → their strings (counts dropped) and its truncated flag", () => { + const f = need("summaryOfValues"); + assert.deepEqual(f({ column: "cancerType", numeric: false, values: [{ value: "Colon", n: 3 }, { value: "", n: 2 }], truncated: false }), + txt("cancerType", ["Colon", ""], false)); + assert.deepEqual(f({ column: "cancerType", numeric: false, values: [{ value: "a", n: 1 }], truncated: true }), txt("cancerType", ["a"], true)); +}); + +test("S7 summaryOfValues agrees with mergeValues' output for the same rows", () => { + const f = need("summaryOfValues"); + const numeric = tq.mergeValues("vaf", true, [[{ lo: 0.1, hi: 0.2, n: 2 }], [{ lo: 0.05, hi: 0.15, n: 1 }]]); + assert.deepEqual(f(numeric), num("vaf", 0.05, 0.2)); + const text = tq.mergeValues("cancerType", false, [[{ v: "A", n: 2 }], [{ v: "B", n: 1 }, { v: "A", n: 1 }]]); + assert.deepEqual(sortedText(f(text)), txt("cancerType", ["A", "B"], false)); +}); diff --git a/test/view-rows-overlap.test.ts b/test/view-rows-overlap.test.ts new file mode 100644 index 00000000..d62c7ad7 --- /dev/null +++ b/test/view-rows-overlap.test.ts @@ -0,0 +1,273 @@ +// lib/views/rows.ts runRows: when the page may be asked for beside the counts, and the column +// summaries the counts carry. Driven with stand-in participants whose answers are held by the test. +// P1 one database, no locate: the page is asked for without waiting for the counts +// P2 one database: the rows are as before — offset below the total, the page's rows; at or past +// it, none, whatever the page returned +// P3 two databases, or a locate: the page is asked for only after every count +// P4 a failing page or count rejects runRows with its error, leaving no unhandled rejection +// P5 summarize: Rows.summaries is the merge over every part when every count carried `sums`; +// absent when one did not, in values mode, and with no summarize; the counts are asked with +// the summary columns among their reads and with the summarize argument +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { runRows } from "../lib/views/rows.ts"; +import type { ViewRun, EvaluatedCohort } from "../lib/views/run.ts"; +import type { ViewParticipation } from "../lib/types.ts"; +import type { TableQuery } from "../lib/table-query.ts"; + +type Row = Record; +type Ask = { column: string; numeric: boolean }; +type Summary = + | { column: string; numeric: true; min: number | null; max: number | null } + | { column: string; numeric: false; values: string[]; truncated: boolean }; +type Counts = { cohort: string; study: string; n: number; all: number; sums?: Summary[] }; +// runRows' trailing summarize argument, called through a loose signature so a build without it still loads +const runRowsAny = runRows as unknown as (...a: unknown[]) => Promise> & { summaries?: Summary[] }>; + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const LONG = 1500; + +type Log = { events: string[]; countsAsked: { conn: string; reads: unknown; summarize: unknown }[]; pageAsked: { conn: string; offset: number; limit: number }[] }; +const newLog = (): Log => ({ events: [], countsAsked: [], pageAsked: [] }); + +/** + * A patient-level participant in database `conn`. `counts` is what its count answers (after + * `countsWait`, which may wait on the test); `page` the rows its page answers whatever is asked. + */ +function standIn(conn: string, log: Log, opts: { + counts: Counts[]; page?: Row[]; countsWait?: () => Promise; pageFails?: Error; countsFails?: Error; countsFailAfter?: number; +}) { + return { + instance: { id: conn, mode: "patient-level", label: conn, conn: { id: conn, db: conn } }, + cohortSql: () => "SELECT 1", + rowsPage: async (_l: string, source: (db: string, m: boolean) => unknown, _q: TableQuery, _d: string[], limit: number, offset: number) => { + source(conn, false); + log.events.push("page:" + conn); + log.pageAsked.push({ conn, offset, limit }); + if (opts.pageFails) throw opts.pageFails; + // the page holds the rows from the asked offset on; the limit is honoured + const rows = opts.page ?? []; + return { rows: rows.slice(0, limit), total: rows.length }; + }, + rowsCounts: async (_l: string, source: (db: string, m: boolean) => unknown, _q: TableQuery, _d: string[], summarize?: unknown) => { + const src = source(conn, false) as { reads?: unknown }; + log.events.push("counts-asked:" + conn); + log.countsAsked.push({ conn, reads: src?.reads, summarize }); + if (opts.countsWait) await opts.countsWait(); + if (opts.countsFails) { await sleep(opts.countsFailAfter ?? 0); throw opts.countsFails; } + log.events.push("counts-done:" + conn); + const ask = (summarize as Ask[] | undefined) || []; + return opts.counts.map((c) => ask.length || !c.sums ? c : { ...c, sums: undefined }); + }, + rowsValues: async (_l: string, source: (db: string, m: boolean) => unknown) => { source(conn, false); log.events.push("values:" + conn); return [{ v: "x", n: 1 }]; }, + rowsRank: async (_l: string, source: (db: string, m: boolean) => unknown) => { source(conn, false); log.events.push("rank:" + conn); return 0; }, + }; +} + +const cohort = (counts: Record): EvaluatedCohort => ({ + studies: Object.keys(counts), + perStudy: Object.fromEntries(Object.entries(counts).map(([st, n]) => [st, { sql: "", count: n, samples: n, mode: "" }])), + count: Object.values(counts).reduce((a, b) => a + b, 0), samples: 0, text: "", +}); +function ctx(cohorts: Record, resolvers: Record, extra: Partial = {}): ViewRun { + const vNames = Object.keys(cohorts); + return { + doc: { study: "s1", cohorts: Object.fromEntries(vNames.map((n) => [n, { study: cohorts[n].studies[0] }])), views: [] } as never, + cohorts, resolvers: resolvers as never, vNames, vStudies: [...new Set(vNames.flatMap((n) => cohorts[n].studies))], + participationFor: (_s: string[], requiresPatientLevel: boolean): ViewParticipation => ({ studies: [], requiresPatientLevel, aggregateOnly: [] }), + pin: null, studyProfiles: async () => ({ profiles: [], gaProfiles: [] }), ...extra, + }; +} +/** the row source factory: what each statement's source was built to read */ +const source = (log: Log) => (_parts: unknown, reads: unknown) => { + log.events.push("source:" + JSON.stringify(reads)); + return () => ({ reads }) as never; +}; +const pts = (cohort: string, study: string, ids: string[]) => ids.map((patient) => ({ cohort, study, patient })); + +/** a deferred the test resolves: `fired` tells whether it was resolved before a timeout */ +function signal() { + let fire!: () => void; + const p = new Promise((r) => { fire = r; }); + let fired = false; + return { fire: () => { fired = true; fire(); }, wait: () => Promise.race([p, sleep(LONG)]), get fired() { return fired; } }; +} + +// ---- P1 / P2: one database ----------------------------------------------------------------------- + +describe("one database, no locate", () => { + test("P1 the page is asked for before the counts answer", async () => { + const log = newLog(); + const pageCalled = signal(); + let pageBeforeCounts = false; + const r = standIn("db1", log, { + counts: [{ cohort: "A", study: "s1", n: 3, all: 3 }, { cohort: "A", study: "s2", n: 2, all: 2 }], + page: pts("A", "s1", ["a1", "a2", "a3"]), + countsWait: async () => { await pageCalled.wait(); pageBeforeCounts = pageCalled.fired; }, + }); + const orig = r.rowsPage; + r.rowsPage = async (...a: Parameters) => { pageCalled.fire(); return orig(...a); }; + const t0 = Date.now(); + const res = await runRows(ctx({ A: cohort({ s1: 3, s2: 2 }) }, { s1: r, s2: r }), "t", ["s1", "s2"], {}, [], [], 10, source(log)); + assert.ok(pageBeforeCounts, "rowsPage was called while rowsCounts was still waiting: " + log.events.join(", ")); + assert.ok(Date.now() - t0 < LONG, "no wait for the timeout"); + assert.equal(res.total, 5); + assert.deepEqual(res.rows.map((x) => x.patient), ["a1", "a2", "a3"]); + }); + + test("P2 an offset below the total gives the page's rows", async () => { + const log = newLog(); + const r = standIn("db1", log, { counts: [{ cohort: "A", study: "s1", n: 5, all: 6 }], page: pts("A", "s1", ["a3", "a4", "a5"]) }); + const res = await runRows(ctx({ A: cohort({ s1: 6 }) }, { s1: r }, { page: { offset: 2, limit: 10 } }), "t", ["s1"], {}, [], [], 10, source(log)); + assert.deepEqual(res.rows.map((x) => x.patient), ["a3", "a4", "a5"]); + assert.equal(res.total, 5); + assert.equal(res.all, 6); + assert.equal(res.offset, 2); + assert.deepEqual(log.pageAsked.map((p) => p.offset), [2]); + }); + + for (const offset of [5, 9]) { + test("P2 an offset " + (offset === 5 ? "at" : "past") + " the total gives no rows, even when the page returned some", async () => { + const log = newLog(); + const r = standIn("db1", log, { counts: [{ cohort: "A", study: "s1", n: 5, all: 5 }], page: pts("A", "s1", ["ghost"]) }); + const res = await runRows(ctx({ A: cohort({ s1: 5 }) }, { s1: r }, { page: { offset, limit: 10 } }), "t", ["s1"], {}, [], [], 10, source(log)); + assert.deepEqual(res.rows, []); + assert.equal(res.total, 5); + }); + } + + test("P2 the first page of an empty list: no rows", async () => { + const log = newLog(); + const r = standIn("db1", log, { counts: [], page: pts("A", "s1", ["ghost"]) }); + const res = await runRows(ctx({ A: cohort({ s1: 5 }) }, { s1: r }), "t", ["s1"], {}, [], [], 10, source(log)); + assert.deepEqual(res.rows, []); + assert.equal(res.total, 0); + }); +}); + +// ---- P3: two databases, or a locate --------------------------------------------------------------- + +describe("the walk needs each group's total", () => { + test("P3 two databases: no page is asked until every count has answered", async () => { + const log = newLog(); + const d1 = standIn("db1", log, { counts: [{ cohort: "A", study: "s1", n: 2, all: 2 }], page: pts("A", "s1", ["a1", "a2"]), countsWait: () => sleep(30) }); + const d2 = standIn("db2", log, { counts: [{ cohort: "A", study: "s2", n: 2, all: 2 }], page: pts("A", "s2", ["b1", "b2"]), countsWait: () => sleep(60) }); + const res = await runRows(ctx({ A: cohort({ s1: 2, s2: 2 }) }, { s1: d1, s2: d2 }), "t", ["s1", "s2"], {}, [], [], 3, source(log)); + const firstPage = log.events.findIndex((e) => e.startsWith("page:")); + assert.ok(firstPage >= 0, log.events.join(", ")); + const lastCount = Math.max(log.events.lastIndexOf("counts-done:db1"), log.events.lastIndexOf("counts-done:db2")); + assert.ok(lastCount >= 0 && lastCount < firstPage, "every count answered before a page: " + log.events.join(", ")); + assert.deepEqual(res.rows.map((x) => x.patient), ["a1", "a2", "b1"]); + }); + + test("P3 one database with a locate: no page is asked until the count has answered", async () => { + const log = newLog(); + const d1 = standIn("db1", log, { counts: [{ cohort: "A", study: "s1", n: 3, all: 3 }], page: pts("A", "s1", ["a1", "a2", "a3"]), countsWait: () => sleep(40) }); + await runRowsAny(ctx({ A: cohort({ s1: 3 }) }, { s1: d1 }), "t", ["s1"], {}, [], [], 10, source(log), undefined, undefined, { study: "s1", patient: "a2" }); + const firstPage = log.events.findIndex((e) => e.startsWith("page:")); + const done = log.events.indexOf("counts-done:db1"); + assert.ok(done >= 0 && (firstPage < 0 || done < firstPage), log.events.join(", ")); + }); +}); + +// ---- P4: failures -------------------------------------------------------------------------------- + +describe("failures", () => { + async function noUnhandled(fn: () => Promise) { + const seen: unknown[] = []; + const on = (e: unknown) => { seen.push(e); }; + process.on("unhandledRejection", on); + try { + await fn(); + await sleep(120); + } finally { + process.off("unhandledRejection", on); + } + assert.deepEqual(seen.map(String), [], "no unhandled rejection"); + } + const one = (log: Log, o: Parameters[2]) => { + const r = standIn("db1", log, o); + return () => runRows(ctx({ A: cohort({ s1: 2 }) }, { s1: r }), "t", ["s1"], {}, [], [], 10, source(log)); + }; + + test("P4 a failing page rejects with its error (one database)", () => noUnhandled(async () => { + const boom = new Error("page went wrong"); + await assert.rejects(one(newLog(), { counts: [{ cohort: "A", study: "s1", n: 2, all: 2 }], pageFails: boom, countsWait: () => sleep(30) })(), (e) => e === boom); + })); + + test("P4 a failing count rejects with its error (one database)", () => noUnhandled(async () => { + const boom = new Error("counts went wrong"); + await assert.rejects(one(newLog(), { counts: [], page: pts("A", "s1", ["a1"]), countsFails: boom, countsFailAfter: 20 })(), (e) => e === boom); + })); + + test("P4 page and count both failing: rejects, and the second failure is not left unhandled", () => noUnhandled(async () => { + const page = new Error("page went wrong"), counts = new Error("counts went wrong"); + await assert.rejects(one(newLog(), { counts: [], pageFails: page, countsFails: counts, countsFailAfter: 30 })(), (e) => e === page || e === counts); + })); + + test("P4 a failing count in one of two databases rejects with its error", () => noUnhandled(async () => { + const log = newLog(); + const boom = new Error("db2 counts went wrong"); + const d1 = standIn("db1", log, { counts: [{ cohort: "A", study: "s1", n: 1, all: 1 }], page: pts("A", "s1", ["a1"]) }); + const d2 = standIn("db2", log, { counts: [], countsFails: boom, countsFailAfter: 10 }); + await assert.rejects(runRows(ctx({ A: cohort({ s1: 1, s2: 1 }) }, { s1: d1, s2: d2 }), "t", ["s1", "s2"], {}, [], [], 10, source(log)), (e) => e === boom); + })); +}); + +// ---- P5: summaries ------------------------------------------------------------------------------- + +describe("P5 summarize", () => { + const ASK: Ask[] = [{ column: "vaf", numeric: true }, { column: "cancerType", numeric: false }]; + const sums = (min: number | null, max: number | null, values: string[], truncated = false): Summary[] => + [{ column: "vaf", numeric: true, min, max }, { column: "cancerType", numeric: false, values, truncated }]; + const setup = (log: Log, db2Sums: boolean) => { + const d1 = standIn("db1", log, { counts: [ + { cohort: "A", study: "s1", n: 1, all: 4, sums: sums(0.2, 0.4, ["Colon"]) }, + { cohort: "B", study: "s1", n: 0, all: 2, sums: sums(null, null, [""]) }, + ], page: pts("A", "s1", ["a1"]) }); + const d2 = standIn("db2", log, { counts: [{ cohort: "A", study: "s2", n: 1, all: 3, ...(db2Sums ? { sums: sums(0.1, 0.3, ["Rectal", "Colon"]) } : {}) }], page: pts("A", "s2", ["b1"]) }); + return ctx({ A: cohort({ s1: 4, s2: 3 }), B: cohort({ s1: 2 }) }, { s1: d1, s2: d2 }); + }; + const norm = (s: Summary[] | undefined) => s?.map((x) => x.numeric ? x : { ...x, values: [...x.values].sort() }); + + test("every count carried sums: Rows.summaries is their merge over every part (the filters' n aside)", async () => { + const log = newLog(); + const res = await runRowsAny(setup(log, true), "t", ["s1", "s2"], { search: "x" }, [], [], 10, source(log), undefined, undefined, undefined, ASK); + assert.deepEqual(norm(res.summaries), norm(sums(0.1, 0.4, ["", "Colon", "Rectal"]))); + assert.equal(res.total, 2); + }); + + test("the counts are asked with the summarize argument and the summary columns among their reads", async () => { + const log = newLog(); + await runRowsAny(setup(log, true), "t", ["s1", "s2"], {}, [], [], 10, source(log), undefined, undefined, undefined, ASK); + assert.equal(log.countsAsked.length, 2, "one count per database"); + for (const c of log.countsAsked) { + assert.deepEqual(c.summarize, ASK, c.conn); + assert.ok(c.reads === "all" || (Array.isArray(c.reads) && ASK.every((a) => (c.reads as string[]).includes(a.column))), + c.conn + " reads " + JSON.stringify(c.reads)); + } + }); + + test("a count without sums (an older or stand-in backend): no summaries", async () => { + const log = newLog(); + const res = await runRowsAny(setup(log, false), "t", ["s1", "s2"], {}, [], [], 10, source(log), undefined, undefined, undefined, ASK); + assert.equal(res.summaries, undefined); + assert.equal(res.total, 2, "the rows themselves are unaffected"); + }); + + test("no summarize asked: no summaries, and the counts are not asked to summarise", async () => { + const log = newLog(); + const res = await runRows(setup(log, true), "t", ["s1", "s2"], {}, [], [], 10, source(log)); + assert.equal(res.summaries, undefined); + for (const c of log.countsAsked) assert.ok(c.summarize == null || (Array.isArray(c.summarize) && !c.summarize.length), JSON.stringify(c.summarize)); + const empty = await runRowsAny(setup(newLog(), true), "t", ["s1", "s2"], {}, [], [], 10, source(newLog()), undefined, undefined, undefined, []); + assert.equal(empty.summaries, undefined, "an empty summarize is none"); + }); + + test("values mode: no summaries", async () => { + const log = newLog(); + const res = await runRowsAny(setup(log, true), "t", ["s1", "s2"], {}, [], [], 10, source(log), { column: "cancerType", numeric: false }, undefined, undefined, ASK); + assert.equal(res.summaries, undefined); + assert.ok(res.values, "the values are returned"); + }); +});