Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
"application": "scout-beta",
"pipelineRevisionId": "scout-beta/1",
"configurationRevision": "scout-beta/1",
"configuration": { "scout.reportLakeSchemaEpoch": "2" },
"configuration": { "scout.reportLakeSchemaEpoch": "3" },
"automatic": true
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"application": "scout-prod",
"pipelineRevisionId": "scout-prod/1",
"configurationRevision": "scout-prod/1",
"configuration": { "scout.reportLakeSchemaEpoch": "2" },
"configuration": { "scout.reportLakeSchemaEpoch": "3" },
"automatic": true,
"promotionSourceEnvironmentId": "scout-for-lol/beta"
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"id": "scout-beta/2",
"content": { "scout.reportLakeSchemaEpoch": "2" },
"id": "scout-beta/3",
"content": { "scout.reportLakeSchemaEpoch": "3" },
"forwardOnly": ["/helm/parameters/scout.reportLakeSchemaEpoch"]
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"id": "scout-prod/2",
"content": { "scout.reportLakeSchemaEpoch": "2" },
"id": "scout-prod/3",
"content": { "scout.reportLakeSchemaEpoch": "3" },
"forwardOnly": ["/helm/parameters/scout.reportLakeSchemaEpoch"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ That is deliberate. Reads name their columns, so
a build published before a column existed fails any read that names it until
the schema fingerprint's rebuild publishes. Leaving the loadout out of ordinary
reads keeps reports working through that window
([lake.ts](https://github.com/shepherdjerred/monorepo/blob/main/packages/scout-for-lol/packages/backend/src/reports/duckdb/lake.ts)).
([reports/duckdb/lake](https://github.com/shepherdjerred/monorepo/tree/main/packages/scout-for-lol/packages/backend/src/reports/duckdb/lake)).

### Bots and unidentified players

Expand Down Expand Up @@ -477,6 +477,46 @@ for rebuild. Legacy flat files are still validated individually. Skips count in
Growth in that counter is the early warning that Riot's payloads drifted from
the Zod schemas.

### Derived tables: lane results

Most lake tables flatten one raw document. `lane_results` is derived instead:
one row per laner per tracked match, pairing each laner with the same-role
opponent and stating the gold, creep score and experience difference at 15:00
([report-lake](https://github.com/shepherdjerred/monorepo/tree/main/packages/scout-for-lol/packages/backend/src/report-lake)).
A lane rate across a friend group would otherwise read every frame of every
game on each request, and consumer reads share two DuckDB slots per process.

The table reuses the match page's own pairing, `buildRoleMatchups`, over the
same checkpoint: the first frame stamped at or after 15:00 and before 16:00.
Riot stamps each minute's frame just past the minute (about 900303 ms for
15:00), so "the last frame at or before 15:00" would read the 14:00 frame. A
game shorter than fifteen minutes, or one missing that frame, has no
checkpoint, and its rows carry `NULL` differences rather than a nearby frame.
A match with no timeline keeps its rows too, with `has_timeline` false, so a
lane figure can state how many of its games could be measured.

A checkpoint frame can also omit a participant: Riot's timeline states frames
as an open record, and nothing between Riot and the lake guarantees ten
entries. That is boundary data, not a broken internal contract, so it is a
stated state rather than an error. The match's rows carry
`checkpoint_complete` false with `NULL` differences, the match page shows no
lane result for it, and a metric counts such matches. Failing instead would
let one Riot timeline stop every fold and rebuild in a stage.

Nothing is staged for the table. A fold re-derives every match that its staged
match or timeline rows name, and a rebuild derives every match. Timelines
arrive separately from matches, so a match is often derived first without its
timeline and again once it lands. Readers keep the newest derivation per laner
(`derived_at`), which makes a lake built by many folds read the same rows as
one rebuild
([compactor.ts](https://github.com/shepherdjerred/monorepo/blob/main/packages/scout-for-lol/packages/backend/src/report-lake/compactor.ts)).

Adding the table changed the schema fingerprint, so it is migrated like a
column: the declared predecessor is the lake without `lane_results`, and the
next scheduled fold rebuilds it. Until a stage has published that rebuild,
`buildLaneResultsSource` answers "unavailable" rather than "no lane games"
([reports/duckdb/lake](https://github.com/shepherdjerred/monorepo/tree/main/packages/scout-for-lol/packages/backend/src/reports/duckdb/lake)).

Both tiers publish the same way: builds are immutable, and a `CURRENT` file
is atomically renamed to point at the new build
([paths.ts](https://github.com/shepherdjerred/monorepo/blob/main/packages/scout-for-lol/packages/backend/src/report-lake/paths.ts)).
Expand Down
4 changes: 2 additions & 2 deletions packages/ops-model/catalog-document.json
Original file line number Diff line number Diff line change
Expand Up @@ -2860,7 +2860,7 @@
"approvalPolicy": "none",
"automatic": true,
"recipeRevisionId": "scout-beta/4",
"configurationRevisionId": "scout-beta/2"
"configurationRevisionId": "scout-beta/3"
},
{
"id": "scout-for-lol/prod",
Expand All @@ -2869,7 +2869,7 @@
"automatic": true,
"promotionSourceEnvironmentId": "scout-for-lol/beta",
"recipeRevisionId": "scout-prod/3",
"configurationRevisionId": "scout-prod/2"
"configurationRevisionId": "scout-prod/3"
},
{
"id": "birmel/prod",
Expand Down
42 changes: 32 additions & 10 deletions packages/scout-for-lol/packages/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -435,23 +435,45 @@ wire-only compatibility fields. Folds and rebuilds reject an incompatible
published fingerprint before creating a candidate build; schema changes require
an explicit migration rather than mixing old and new Parquet columns.

A migration is one declared predecessor, never a bridge. No migration is in
flight: the build accepts only its own fingerprint. A migration declares the
one older fingerprint it accepts, and while it is in flight:
A migration is one declared predecessor, never a bridge. The current one adds
the derived `lane_results` table (schema epoch 3):

- `LAKE_PREDECESSOR_SCHEMA_FINGERPRINT` (`report-lake/schema.ts`) names the
one older schema this build accepts. A test pins it to the current schema
minus `lane_results`.
- A fold that finds that schema published runs a full rebuild instead, so no
fold mixes layouts. The rebuild accepts the predecessor as the build it
replaces, and any other fingerprint still throws.
- Only the scheduled lake job runs that rebuild, under its heartbeats. The
boot fold and initial-history publishing skip their inline fold while the
migration is pending. Otherwise the single application pod, which uses a
Recreate rollout, would stay unready for the whole rebuild.
- No read names the new columns, so Reports, ScoutQL, Dares and raw-document
analysis keep reading the predecessor build and staging while the rebuild
runs, and the lake stays available.
migration is pending (`reportLakeMigrationPending`). Otherwise the single
application pod, which uses a Recreate rollout, would stay unready for the
whole rebuild.
- Until a stage publishes the rebuild, `buildLaneResultsSource`
(`reports/duckdb/lake/lane-results-source.ts`) answers `unavailable` for a build that is not at
the current fingerprint, and readers show that as "not yet available", not
as no lane games. No other read changes, so the lake stays available.
- After Beta and Prod each publish a build at the current fingerprint, one
follow-up deletes the predecessor and the gate together. The columns then
become ordinary reads and ScoutQL catalog columns.
follow-up deletes the predecessor and the gate together.

`lane_results` holds one row per laner per tracked match that
`buildRoleMatchups` can pair: the laner and same-role opponent (PUUID,
participant id, champion), team, role, win, queue and game time, whether the
lake holds the match's timeline, and the gold, creep score and experience
difference against the opponent at the 15:00 checkpoint. The checkpoint is the
first frame stamped at or after 15:00 and before 16:00; with none (a shorter
game, a missing frame, no timeline) the differences are `NULL` and
`checkpoint_complete` is `NULL`. A checkpoint frame that omits a participant
(Riot's `participantFrames` is an open record) gives `checkpoint_complete =
false` and `NULL` differences for the whole match; `buildRoleMatchups`
(`reports/lanes/role-matchups.ts`) states the same `incomplete` checkpoint to
the match page instead of failing. "Ahead at 15" means a gold difference
strictly greater than zero. Nothing is staged for it: a fold re-derives the
matches its staged match or timeline rows name (`report-lake/lane-results/`), a
rebuild derives all of them, and reads keep the newest derivation per laner.
Each build manifest records `laneResultRows` and
`laneResultIncompleteCheckpoints`, and
`report_lake_lane_checkpoint_incomplete_total` counts incomplete checkpoints.

Every participant has a `matches` row. `puuid` is non-null exactly when the row
names a player; a bot or an unresolved player has a `NULL` `puuid` and its
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { ExtendedPrismaClient } from "#src/database/index.ts";
import { initialHistoryImportPhasesTotal } from "#src/metrics/initial-history-import.ts";
import { runReportLakeFold } from "#src/report-lake/compactor.ts";
import {
reportLakeMigrationPending,
runReportLakeFold,
} from "#src/report-lake/compactor.ts";

export async function publishReadyImports(
db: ExtendedPrismaClient,
Expand Down Expand Up @@ -28,6 +31,10 @@ export async function publishReadyImports(

const ready = jobs.filter((job) => trackedPuuids.has(job.puuid));
if (ready.length === 0) return;
// While the schema migration is pending only the scheduled rebuild
// publishes the accounts snapshot that guild queries join, so these jobs stay
// in the publish phase until it has run (see reportLakeMigrationPending).
if (await reportLakeMigrationPending()) return;
await runReportLakeFold({ prisma: db });

const completions = await Promise.all(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ vi.doMock("#src/report-store/live-ingest.ts", () => ({
recordMatchForReportStore,
}));
vi.doMock("#src/report-lake/compactor.ts", () => ({
reportLakeMigrationPending: () => Promise.resolve(false),
runReportLakeFold,
}));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {
readPlayerChampionPool,
readPlayerMatchHistory,
} from "#src/reports/duckdb/lake-reads.ts";
import { STANDARD_COMMUNITY_QUEUES } from "#src/trpc/router/consumer/standard-rift.ts";
import { STANDARD_COMMUNITY_QUEUES } from "#src/reports/lanes/standard-rift.ts";
import type { CommunityPlayer } from "#src/trpc/router/consumer/community-insights.ts";
import type { z } from "zod";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
type LaneDeltaFrame,
} from "#src/reports/duckdb/consumer/profile-lake-reads.ts";
import { withDuckDBConnection } from "#src/reports/duckdb/instance.ts";
import { buildRoleMatchups } from "#src/trpc/router/consumer/consumer-match-role-matchups.ts";
import { buildRoleMatchups } from "#src/reports/lanes/role-matchups.ts";
import {
crawlRecord,
memoryCrawlSegmentSource,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ export const reportLakeCompactionSkippedTotal = new Counter({
registers: [registry],
});

/**
* Matches derived into `lane_results` whose 15:00 checkpoint frame omits a
* participant, so they carry no lane result (`checkpoint_complete = false`).
* Riot boundary data; growth means timelines with partial frames are arriving.
*/
export const reportLakeLaneCheckpointIncompleteTotal = new Counter({
name: "report_lake_lane_checkpoint_incomplete_total",
help: "Matches derived into lane_results with an incomplete 15:00 checkpoint frame, by tier.",
labelNames: ["tier"] as const,
registers: [registry],
});

export const reportLakeStagingWritesTotal = new Counter({
name: "report_lake_staging_writes_total",
help: "Ingest-time staging file writes by table and status.",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from "node:path";
import {
reportLakeCompactionRowsTotal,
reportLakeLaneCheckpointIncompleteTotal,
reportLakeLastPublishTimestamp,
} from "#src/metrics/reports/report-lake.ts";
import { lakeSchemaFingerprint } from "#src/report-lake/schema.ts";
Expand All @@ -24,6 +25,10 @@ export type CompactionSummary = {
timelineEventParticipantRows: number;
timelineParticipantFrameRows: number;
timelineCoverageRows: number;
/** Rows derived into `lane_results` (a fold's re-derivations, or all). */
laneResultRows: number;
/** Derived matches whose 15:00 frame omits a participant. */
laneResultIncompleteCheckpoints: number;
skippedMatches: number;
skippedPrematches: number;
skippedCompetitionRankHistory: number;
Expand Down Expand Up @@ -67,6 +72,7 @@ export function publishCompactionMetrics(
["timeline_event_participants", summary.timelineEventParticipantRows],
["timeline_participant_frames", summary.timelineParticipantFrameRows],
["timeline_coverage", summary.timelineCoverageRows],
["lane_results", summary.laneResultRows],
] as const) {
reportLakeCompactionRowsTotal.inc({ table, tier: summary.tier }, rows);
}
Expand All @@ -76,5 +82,9 @@ export function publishCompactionMetrics(
summary.crawl.rows[table],
);
}
reportLakeLaneCheckpointIncompleteTotal.inc(
{ tier: summary.tier },
summary.laneResultIncompleteCheckpoints,
);
reportLakeLastPublishTimestamp.set({ tier: summary.tier }, Date.now() / 1000);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import {
type CompactionSummary as PublishedCompactionSummary,
} from "#src/report-lake/compaction-publish.ts";
type CompactionSummary = PublishedCompactionSummary;
import { lakeSchemaFingerprint } from "#src/report-lake/schema.ts";
import {
LAKE_PREDECESSOR_SCHEMA_FINGERPRINT,
lakeSchemaStatus,
} from "#src/report-lake/schema.ts";
import {
buildDirPath,
ensureLakeScaffold,
Expand Down Expand Up @@ -47,10 +50,17 @@ import {
runCrawlErasureStep,
} from "#src/report-lake/crawl/crawl-erasure-step.ts";
import { createConfiguredRawErasureObjects } from "#src/report-lake/crawl/crawl-raw-erasure-store.ts";
import {
buildDirLaneResultInputs,
stagedLaneResultScope,
writeLaneResultsParquet,
} from "#src/report-lake/lane-results/derive-lane-results.ts";

const logger = createLogger("report-lake-compactor");

const GC_KEEP_BUILDS = 2;
/** The same budget a fold gives each staged table's Parquet COPY. */
const LANE_RESULTS_FOLD_TIMEOUT_MS = 30 * 60 * 1000;

let compactionTail: Promise<unknown> = Promise.resolve();

Expand All @@ -66,6 +76,26 @@ async function withCompactionLock<T>(fn: () => Promise<T>): Promise<T> {
}
}

/**
* Whether the published build has the declared predecessor schema, so the
* next fold is the migration's full rebuild.
*
* Callers that fold inline, where a rebuild would hold something else up,
* check this and leave the migration to the scheduled lake job: the boot fold
* would keep the single application pod unready for the whole rebuild, and an
* import would wait on it. Readers serve the published build and staging
* meanwhile, so skipping the inline fold loses nothing.
*/
export async function reportLakeMigrationPending(
lakeDir: string = resolveLakeDir(),
): Promise<boolean> {
const currentDir = await readCurrentBuildDir(lakeDir);
return (
currentDir !== undefined &&
lakeSchemaStatus(await readBuildFingerprint(currentDir)) === "predecessor"
);
}

/**
* Tier 1 — fold: hardlink the current build, add staged rows as fold
* parquet files, fold the crawl inbox into the crawl tables, refresh the
Expand All @@ -92,10 +122,19 @@ export async function runReportLakeFold(
}

// A fold hardlinks the published build's parquet and appends fold files
// written at the same physical column set. Reject incompatible builds
// before creating mixed-schema Parquet.
// written at the same physical column set. The one declared predecessor
// schema is migrated by a full rebuild instead, which never mixes the two
// layouts; any other incompatible build is rejected before creating
// mixed-schema Parquet.
const publishedFingerprint = await readBuildFingerprint(currentDir);
if (publishedFingerprint !== lakeSchemaFingerprint()) {
const status = lakeSchemaStatus(publishedFingerprint);
if (status === "predecessor") {
logger.info(
`Published build has the predecessor schema (${LAKE_PREDECESSOR_SCHEMA_FINGERPRINT}); migrating via full rebuild`,
);
return await rebuildReportLake(prisma, lakeDir, startedAt, options);
}
if (status === "unknown") {
throw new Error(
`Published report lake has an unknown schema (${publishedFingerprint ?? "unrecorded"}); refusing to fold before its physical layout is established`,
);
Expand Down Expand Up @@ -211,6 +250,21 @@ export async function runReportLakeFold(
staged: stagedTimelineCoverage,
abortSignal: options.abortSignal,
});
// Re-derive every match a staged match or timeline row names, so a
// timeline folded after its match replaces the timeline-less rows.
const laneResults = await writeLaneResultsParquet({
buildDir,
inputs: await buildDirLaneResultInputs(buildDir),
scope: stagedLaneResultScope([
stagedMatches,
stagedTimelineParticipantFrames,
stagedTimelineCoverage,
]),
derivedAt: new Date(),
foldBuildId: buildId,
timeoutMs: LANE_RESULTS_FOLD_TIMEOUT_MS,
abortSignal: options.abortSignal,
});
options.onProgress?.({ phase: "folding-crawl" });
const crawlFold = await foldCrawlInbox({
lakeDir,
Expand Down Expand Up @@ -249,6 +303,9 @@ export async function runReportLakeFold(
timelineEventParticipantRows: stagedTimelineEventParticipants.rows,
timelineParticipantFrameRows: stagedTimelineParticipantFrames.rows,
timelineCoverageRows: stagedTimelineCoverage.rows,
laneResultRows: laneResults.rows,
laneResultIncompleteCheckpoints:
laneResults.incompleteCheckpointMatches,
skippedMatches: stagedMatches.skipped,
skippedPrematches: stagedPrematches.skipped,
skippedCompetitionRankHistory: stagedRankHistory.skipped,
Expand Down
Loading