Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion app/lab/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,38 @@ interface Opts { signal?: AbortSignal }
function post(path: string, body: unknown, signal?: AbortSignal): Promise<Response> {
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<string, Promise<Response>>();
function postShared(path: string, body: unknown, signal?: AbortSignal): Promise<Response> {
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<Response>((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<Response> =>
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 = {}) =>
Expand Down
2 changes: 1 addition & 1 deletion app/portal/PortalTabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 */ });
Expand Down
4 changes: 3 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
33 changes: 33 additions & 0 deletions docs/PERFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
18 changes: 10 additions & 8 deletions lib/federation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
/**
Expand Down Expand Up @@ -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 }
/**
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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<ChRow[]>;
/** 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<RowCounts[]>;
rowsCounts(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], summarize?: SummaryAsk[]): Promise<RowCounts[]>;
rowsValues(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], column: string): Promise<ChRow[]>;
rowsRank(label: string, source: (db: string, materialized: boolean) => RowSource, q: TableQuery, defaults: string[], study: string, patient: string): Promise<number | null>;
/** one patient's timeline events and samples — see PatientLevelResolver.patientTimeline */
Expand Down Expand Up @@ -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<RowCounts[]> {
const r = await this.runPatientRows<ChRow>(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<RowCounts[]> {
const r = await this.runPatientRows<ChRow>(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<ChRow[]> {
Expand Down
4 changes: 3 additions & 1 deletion lib/hotspots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, '') != ''";
Expand Down
58 changes: 55 additions & 3 deletions lib/table-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`s<i>lo`/`s<i>hi`, or `s<i>v`: 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<string, unknown>): 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 };
}

/**
Expand Down
Loading
Loading