Skip to content
Open
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"@libpg-query/parser": "^17.6.3",
"@opentelemetry/api": "^1.9.0",
"@pgsql/types": "^17.6.2",
"@query-doctor/core": "^0.12.0",
"@query-doctor/core": "^0.13.0",
"async-sema": "^3.1.1",
"capnweb": "^0.7.0",
"dedent": "^1.7.1",
Expand Down
72 changes: 72 additions & 0 deletions src/remote/query-optimizer-synthesis.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { expect, test } from "vitest";
import { PostgreSqlContainer } from "@testcontainers/postgresql";
import { dumpSchema, PostgresVersion, Statistics } from "@query-doctor/core";
import { ConnectionManager } from "../sync/connection-manager.ts";
import { Connectable } from "../sync/connectable.ts";
import { QueryOptimizer } from "./query-optimizer.ts";

// When the exported snapshot doesn't cover a table in the current schema — added
// on this branch since the snapshot was captured — setStatistics must pass the
// schema through to core's Statistics so the synthesizer sizes that table,
// instead of it falling to the flat default. This is the analyzer-side wiring;
// the synthesis logic itself is covered in @query-doctor/core.
//
// Requires @query-doctor/core >= 0.13.0 (the currentSchema parameter and the
// syntheticTables getter).
test(
"setStatistics sizes a table missing from the exported snapshot",
async () => {
const pg = await new PostgreSqlContainer("postgres:17")
.withCopyContentToContainer([
{
content: `
create table orders (id serial primary key);
create table refunds (id serial primary key, order_id int references orders(id));
insert into orders default values;
insert into refunds (order_id) values (1);
`,
target: "/docker-entrypoint-initdb.d/init.sql",
},
])
.start();

try {
const manager = ConnectionManager.forLocalDatabase();
const conn = Connectable.fromString(pg.getConnectionUri());
const optimizer = new QueryOptimizer(manager, conn);

const version = PostgresVersion.parse("17");
const connection = manager.getOrCreateConnection(conn);
const ownStats = await Statistics.dumpStats(connection, version);

// refunds is omitted from the snapshot (uncovered); orders is given a
// production-sized count so synthesis yields a large number rather than
// the single branch row.
const snapshot = ownStats
.filter((t) => t.tableName !== "refunds")
.map((t) => ({
...t,
reltuples: t.tableName === "orders" ? 1_000_000 : t.reltuples,
}));
const schema = await dumpSchema(connection);

await optimizer.setStatistics(
Statistics.statsModeFromExport(snapshot),
schema,
);

// refunds is reported as modeled/unverified and sized from the 1M-row
// snapshot (via its foreign key to orders), not its own one row.
expect(
optimizer.syntheticTables.some((t) => t.endsWith(".refunds")),
).toBe(true);
const refunds = optimizer.computedStats?.reltuples.find(
(r) => r.relname === "refunds",
);
expect(refunds?.reltuples).toBeGreaterThan(100_000);
} finally {
await pg.stop();
}
},
120_000,
);
15 changes: 14 additions & 1 deletion src/remote/query-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ export class QueryOptimizer extends EventEmitter<EventMap> {
return this.target?.statistics.ownMetadata;
}

/**
* Tables ("schema.table") sized by the synthesizer because the exported
* snapshot didn't cover them — their costs are modeled, not verified. Empty
* unless a schema was supplied in fromStatisticsExport mode.
*/
get syntheticTables(): string[] {
return this.target?.statistics.syntheticTables ?? [];
}

getExistingIndexes(): FullSchemaIndex[] {
return this.existingIndexes;
}
Expand Down Expand Up @@ -146,7 +155,11 @@ export class QueryOptimizer extends EventEmitter<EventMap> {
const version = PostgresVersion.parse("17");
const pg = this.manager.getOrCreateConnection(this.connectable);
const ownStats = await Statistics.dumpStats(pg, version);
const statistics = new Statistics(pg, version, ownStats, statsMode);
// Pass the current schema so tables the exported snapshot doesn't cover
// (added on this branch / since the snapshot was captured) are sized by the
// synthesizer instead of the flat default. No-op when statsMode isn't
// fromStatisticsExport.
const statistics = new Statistics(pg, version, ownStats, statsMode, schema);
this.existingIndexes = schema?.indexes ?? [];
const filteredIndexes = this.filterDisabledIndexes(this.existingIndexes);
const optimizer = new IndexOptimizer(pg, statistics, filteredIndexes, {
Expand Down
7 changes: 7 additions & 0 deletions src/reporters/reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ export interface ReportContext {
* A pure diff heuristic — independent of the baseline comparison.
*/
testPresenceVerdict?: TestPresenceVerdict;
/**
* Tables ("schema.table") in the analyzed schema the production snapshot
* doesn't cover, so their costs were modeled by the synthesizer rather than
* verified against real data. Empty when the snapshot covers the whole schema.
* Not yet rendered in the comment — plumbed for the surfacing that follows.
*/
modeledTables?: string[];
}

export interface IndexStatistic {
Expand Down
1 change: 1 addition & 0 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ export class Runner {
const reportContext: ReportContext = {
statisticsMode: this.remote.optimizer.statisticsMode,
computedStats: this.remote.optimizer.computedStats,
modeledTables: this.remote.optimizer.syntheticTables,
recommendations: filteredRecommendations,
queriesPastThreshold: filteredThresholdWarnings,
queryStats: Object.freeze({
Expand Down
Loading