From 354c4c97b7fbbab0299fc7101d41317b57598e47 Mon Sep 17 00:00:00 2001 From: Rafal Hawrylak Date: Thu, 26 Nov 2026 15:35:04 +0000 Subject: [PATCH 1/2] fix(cli): index actions by exact target in prune and run When two compiled actions shared the same readable target string, prune and runCommand indexed internal sets and maps by targetAsReadableString instead of targetStringifier. Unqualified --actions missed short-name ambiguity, --include-deps dropped overwritten dependencies, --tags leaked untagged colliding actions and console output mislabeled action types across ticks. prune and runCommand now index actions and walk dependency targets by targetStringifier while matching --actions and '*' wildcard patterns directly against compiled actions. --- cli/api/commands/prune.ts | 177 ++++++++++------ cli/api/commands/prune_test.ts | 366 +++++++++++++++++++++++++++++++++ cli/commands/run_command.ts | 55 ++--- cli/index_compile_test.ts | 10 + cli/tests/run_command_test.ts | 86 +++++++- core/utils.ts | 4 +- 6 files changed, 606 insertions(+), 92 deletions(-) diff --git a/cli/api/commands/prune.ts b/cli/api/commands/prune.ts index 682f227f8..9cc7b637f 100644 --- a/cli/api/commands/prune.ts +++ b/cli/api/commands/prune.ts @@ -1,98 +1,146 @@ -import { targetAsReadableString } from "df/core/targets"; +import { targetAsReadableString, targetStringifier } from "df/core/targets"; import * as utils from "df/core/utils"; import { dataform } from "df/protos/ts"; type CompileAction = dataform.ITable | dataform.IOperation | dataform.IAssertion | dataform.IPropertyGraph; +function targetKey(target?: dataform.ITarget | null): string | undefined { + return target ? targetStringifier.stringify(target) : undefined; +} + export function prune( compiledGraph: dataform.ICompiledGraph, runConfig: dataform.IRunConfig, ): dataform.ICompiledGraph { - compiledGraph.tables.forEach(utils.setOrValidateTableEnumType); - const includedActionNames = computeIncludedActionNames(compiledGraph, runConfig); + (compiledGraph.tables || []).forEach(utils.setOrValidateTableEnumType); + const includedActionKeys = computeIncludedActionKeys(compiledGraph, runConfig); + const isIncluded = (target?: dataform.ITarget | null) => { + const key = targetKey(target); + return key !== undefined && includedActionKeys.has(key); + }; return { ...compiledGraph, - tables: compiledGraph.tables.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), - assertions: compiledGraph.assertions.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), - operations: compiledGraph.operations.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), - propertyGraphs: compiledGraph.propertyGraphs?.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), + tables: (compiledGraph.tables || []).filter((action) => isIncluded(action.target)), + assertions: (compiledGraph.assertions || []).filter((action) => isIncluded(action.target)), + operations: (compiledGraph.operations || []).filter((action) => isIncluded(action.target)), + propertyGraphs: compiledGraph.propertyGraphs?.filter((action) => isIncluded(action.target)), // `targets` is declarative output only (nothing downstream reads it), but // `compile` prints it, so it has to agree with the filtered action lists. - targets: compiledGraph.targets?.filter((target) => - includedActionNames.has(targetAsReadableString(target)), - ), + targets: compiledGraph.targets?.filter((target) => isIncluded(target)), }; } -function computeIncludedActionNames( +function matchActionSelectors(patterns: string[], allActions: CompileAction[]): string[] { + const matchedActionKeys: string[] = []; + patterns.forEach((pattern) => { + if (pattern.includes("*")) { + // Wildcard selector: patterns containing "." match the full readable target string; + // otherwise they match the unqualified action name, with no ambiguity error. + const regExp = utils.globToRegExp(pattern); + const matchFullTarget = pattern.includes("."); + allActions.forEach((action) => { + if (!action.target) { + return; + } + const candidate = matchFullTarget + ? targetAsReadableString(action.target) + : action.target.name; + if (candidate !== undefined && regExp.test(candidate)) { + matchedActionKeys.push(targetStringifier.stringify(action.target)); + } + }); + } else if (pattern.includes(".")) { + allActions.forEach((action) => { + if (action.target && targetAsReadableString(action.target) === pattern) { + matchedActionKeys.push(targetStringifier.stringify(action.target)); + } + }); + } else { + const matchingActions = allActions.filter((action) => action.target?.name === pattern); + if (matchingActions.length === 0) { + return; + } + if (matchingActions.length > 1) { + throw new Error( + utils.ambiguousActionNameMsg( + pattern, + matchingActions.map((action) => targetAsReadableString(action.target)), + ), + ); + } + matchedActionKeys.push(targetStringifier.stringify(matchingActions[0].target)); + } + }); + return matchedActionKeys; +} + +function computeIncludedActionKeys( compiledGraph: dataform.ICompiledGraph, runConfig: dataform.IRunConfig, ): Set { // Union all tables, operations, assertions, property graphs. const allActions: CompileAction[] = [].concat( - compiledGraph.tables, - compiledGraph.operations, - compiledGraph.assertions, - compiledGraph.propertyGraphs, + compiledGraph.tables || [], + compiledGraph.operations || [], + compiledGraph.assertions || [], + compiledGraph.propertyGraphs || [], ); - const allActionNames = new Set( - allActions.map((action) => targetAsReadableString(action.target)), - ); - const allActionsByName = new Map( - allActions.map((action) => [targetAsReadableString(action.target), action]), - ); + const allActionKeys = new Set(); + const allActionsByKey = new Map(); + allActions.forEach((action) => { + const key = targetKey(action?.target); + if (key !== undefined) { + allActionKeys.add(key); + allActionsByKey.set(key, action); + } + }); const hasActionSelector = runConfig.actions?.length > 0; const hasTagSelector = runConfig.tags?.length > 0; // If no selectors, return all actions. if (!hasActionSelector && !hasTagSelector) { - return allActionNames; + return allActionKeys; } - const includedActionNames = new Set(); + const includedActionKeys = new Set(); // Add all actions included by action filters. if (hasActionSelector) { - utils - .matchPatterns(runConfig.actions, [...allActionNames]) - .forEach((actionName) => includedActionNames.add(actionName)); + matchActionSelectors(runConfig.actions, allActions).forEach((actionKey) => + includedActionKeys.add(actionKey), + ); } // Determine actions selected with --tag option and update applicable actions if (hasTagSelector) { allActions .filter((action) => action.tags?.some((tag) => runConfig.tags.includes(tag))) - .forEach((action) => includedActionNames.add(targetAsReadableString(action.target))); + .forEach((action) => { + const key = targetKey(action.target); + if (key !== undefined) { + includedActionKeys.add(key); + } + }); } // Compute all transitive dependencies. if (runConfig.includeDependencies) { - const queue = [...includedActionNames]; + const queue = [...includedActionKeys]; while (queue.length > 0) { - const actionName = queue.pop(); - const action = allActionsByName.get(actionName); - const matchingDependencyNames = - action.dependencyTargets?.length > 0 - ? utils.matchPatterns( - action.dependencyTargets.map((dependency) => targetAsReadableString(dependency)), - [...allActionNames], - ) - : []; - matchingDependencyNames.forEach((dependencyName) => { - if (!includedActionNames.has(dependencyName)) { - queue.push(dependencyName); - includedActionNames.add(dependencyName); + const actionKey = queue.pop(); + const action = allActionsByKey.get(actionKey); + (action?.dependencyTargets || []).forEach((dependency) => { + const dependencyKey = targetKey(dependency); + if ( + dependencyKey !== undefined && + allActionKeys.has(dependencyKey) && + !includedActionKeys.has(dependencyKey) + ) { + queue.push(dependencyKey); + includedActionKeys.add(dependencyKey); } }); } @@ -100,28 +148,23 @@ function computeIncludedActionNames( // Compute all transitive dependents. if (runConfig.includeDependents) { - const queue = [...includedActionNames]; + const queue = [...includedActionKeys]; while (queue.length > 0) { - const actionName = queue.pop(); - const matchingDependentNames = allActions - .filter( - (compileAction) => - utils.matchPatterns( - [actionName], - compileAction.dependencyTargets?.map((dependency) => - targetAsReadableString(dependency), - ) || [], - ).length >= 1, - ) - .map((compileAction) => targetAsReadableString(compileAction.target)); - matchingDependentNames.forEach((dependentName) => { - if (!includedActionNames.has(dependentName)) { - queue.push(dependentName); - includedActionNames.add(dependentName); + const actionKey = queue.pop(); + allActions.forEach((compileAction) => { + const dependsOnAction = compileAction.dependencyTargets?.some( + (dependency) => targetKey(dependency) === actionKey, + ); + if (dependsOnAction) { + const dependentKey = targetKey(compileAction.target); + if (dependentKey !== undefined && !includedActionKeys.has(dependentKey)) { + queue.push(dependentKey); + includedActionKeys.add(dependentKey); + } } }); } } - return includedActionNames; + return includedActionKeys; } diff --git a/cli/api/commands/prune_test.ts b/cli/api/commands/prune_test.ts index 87d9f6e7b..c4f54985d 100644 --- a/cli/api/commands/prune_test.ts +++ b/cli/api/commands/prune_test.ts @@ -167,4 +167,370 @@ suite("prune", () => { }), ); }); + + test("--actions= matches property graphs and keeps targets in sync", () => { + const compiledGraph: dataform.ICompiledGraph = { + tables: [TABLE_ACTION], + operations: [], + assertions: [], + propertyGraphs: [GRAPH_ACTION, TAGGED_GRAPH_ACTION], + targets: [TABLE_TARGET, GRAPH_TARGET, TAGGED_GRAPH_TARGET], + }; + expect(asPlainObject(prune(compiledGraph, { actions: ["*Graph"] }))).deep.equals( + asPlainObject({ + tables: [], + operations: [], + assertions: [], + propertyGraphs: [GRAPH_ACTION, TAGGED_GRAPH_ACTION], + targets: [GRAPH_TARGET, TAGGED_GRAPH_TARGET], + }), + ); + }); + + suite("targets colliding under targetAsReadableString", () => { + const DEP_TABLE_TARGET: dataform.ITarget = { database: "proj", schema: "b", name: "dep_table" }; + const DEP_ASSERT_TARGET: dataform.ITarget = { + database: "proj", + schema: "b", + name: "dep_assert", + }; + const COLLIDING_TABLE_TARGET: dataform.ITarget = { database: "proj", schema: "b", name: "c" }; + const COLLIDING_ASSERT_TARGET: dataform.ITarget = { schema: "proj", name: "b.c" }; + const AFTER_TABLE_TARGET: dataform.ITarget = { + database: "proj", + schema: "b", + name: "after_table", + }; + const AFTER_ASSERT_TARGET: dataform.ITarget = { + database: "proj", + schema: "b", + name: "after_assert", + }; + + const DEP_TABLE: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: DEP_TABLE_TARGET, + canonicalTarget: DEP_TABLE_TARGET, + query: "select 1", + dependencyTargets: [], + }; + const DEP_ASSERT: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: DEP_ASSERT_TARGET, + canonicalTarget: DEP_ASSERT_TARGET, + query: "select 2", + dependencyTargets: [], + }; + const COLLIDING_TABLE: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: COLLIDING_TABLE_TARGET, + canonicalTarget: COLLIDING_TABLE_TARGET, + query: "select 3", + tags: ["tag_tbl"], + dependencyTargets: [DEP_TABLE_TARGET], + }; + const COLLIDING_ASSERT: dataform.IAssertion = { + target: COLLIDING_ASSERT_TARGET, + canonicalTarget: COLLIDING_ASSERT_TARGET, + query: "select 4", + tags: ["tag_ass"], + dependencyTargets: [DEP_ASSERT_TARGET], + }; + const AFTER_TABLE: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: AFTER_TABLE_TARGET, + canonicalTarget: AFTER_TABLE_TARGET, + query: "select 5", + dependencyTargets: [COLLIDING_TABLE_TARGET], + }; + const AFTER_ASSERT: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: AFTER_ASSERT_TARGET, + canonicalTarget: AFTER_ASSERT_TARGET, + query: "select 6", + dependencyTargets: [COLLIDING_ASSERT_TARGET], + }; + + function makeCollidingGraph(): dataform.ICompiledGraph { + return { + tables: [DEP_TABLE, DEP_ASSERT, COLLIDING_TABLE, AFTER_TABLE, AFTER_ASSERT], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + DEP_TABLE_TARGET, + DEP_ASSERT_TARGET, + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + AFTER_TABLE_TARGET, + AFTER_ASSERT_TARGET, + ], + }; + } + + test("unqualified --actions throws ambiguous error when another action shares its short name", () => { + const otherC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { schema: "proj.b", name: "c" }, + canonicalTarget: { schema: "proj.b", name: "c" }, + query: "select 7", + dependencyTargets: [], + }; + const graph: dataform.ICompiledGraph = { + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target], + }; + expect(() => prune(graph, { actions: ["c"] })).to.throw( + "Ambiguous Action name: c. Did you mean one of: proj.b.c, proj.b.c.", + ); + }); + + test("dotted --actions selects all matching actions and walks all of their dependencies", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["proj.b.c"], + includeDependencies: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [DEP_TABLE, DEP_ASSERT, COLLIDING_TABLE], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + DEP_TABLE_TARGET, + DEP_ASSERT_TARGET, + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + ], + }), + ); + }); + + test("dotted --actions with includeDependents walks dependents of all matching actions", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["proj.b.c"], + includeDependents: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, AFTER_TABLE, AFTER_ASSERT], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + AFTER_TABLE_TARGET, + AFTER_ASSERT_TARGET, + ], + }), + ); + }); + + test("--tags selects only the tagged colliding action and walks only its dependencies", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + tags: ["tag_tbl"], + includeDependencies: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [DEP_TABLE, COLLIDING_TABLE], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [DEP_TABLE_TARGET, COLLIDING_TABLE_TARGET], + }), + ); + }); + + test("--tags with includeDependents walks only dependents of the tagged colliding action", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + tags: ["tag_tbl"], + includeDependents: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, AFTER_TABLE], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, AFTER_TABLE_TARGET], + }), + ); + }); + + test("unqualified wildcard matches actual target.name without ambiguity and skips dotted names", () => { + const otherC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { schema: "proj.b", name: "c" }, + canonicalTarget: { schema: "proj.b", name: "c" }, + query: "select 7", + dependencyTargets: [], + }; + const graph: dataform.ICompiledGraph = { + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target, COLLIDING_ASSERT_TARGET], + }; + + // "c*" matches target.name === "c" on both tables without throwing ambiguity, and does not + // match COLLIDING_ASSERT whose target.name is "b.c" (even though its readable string ends in ".c"). + expect(asPlainObject(prune(graph, { actions: ["c*"] }))).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target], + }), + ); + + // "*c" matches all three because "c" and "b.c" both end in "c". + expect(asPlainObject(prune(graph, { actions: ["*c"] }))).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target, COLLIDING_ASSERT_TARGET], + }), + ); + }); + + test("qualified wildcard selects all colliding targets and walks all of their dependencies and dependents", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["*.b.c"], + includeDependencies: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [DEP_TABLE, DEP_ASSERT, COLLIDING_TABLE], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + DEP_TABLE_TARGET, + DEP_ASSERT_TARGET, + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + ], + }), + ); + + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["proj.**c"], + includeDependents: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, AFTER_TABLE, AFTER_ASSERT], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + AFTER_TABLE_TARGET, + AFTER_ASSERT_TARGET, + ], + }), + ); + }); + + test("overlapping wildcard, exact and tag selectors do not duplicate actions or targets", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["*", "proj.b.c", "*table"], + tags: ["tag_tbl", "tag_ass"], + }), + ), + ).deep.equals(asPlainObject(makeCollidingGraph())); + }); + + test("literal '*' in a target name does not wildcard-expand during dependency or dependent walks", () => { + const starTarget: dataform.ITarget = { schema: "s", name: "op*" }; + const unrelatedTarget: dataform.ITarget = { schema: "s", name: "op_unrelated" }; + const consumerTarget: dataform.ITarget = { schema: "s", name: "consumer" }; + const starOp: dataform.IOperation = { + target: starTarget, + canonicalTarget: starTarget, + queries: ["select 1"], + dependencyTargets: [], + }; + const unrelatedOp: dataform.IOperation = { + target: unrelatedTarget, + canonicalTarget: unrelatedTarget, + queries: ["select 2"], + dependencyTargets: [], + }; + const consumerOp: dataform.IOperation = { + target: consumerTarget, + canonicalTarget: consumerTarget, + queries: ["select 3"], + dependencyTargets: [starTarget], + }; + const graph: dataform.ICompiledGraph = { + tables: [], + operations: [starOp, unrelatedOp, consumerOp], + assertions: [], + propertyGraphs: [], + targets: [starTarget, unrelatedTarget, consumerTarget], + }; + + expect( + asPlainObject(prune(graph, { actions: ["consumer"], includeDependencies: true })), + ).deep.equals( + asPlainObject({ + tables: [], + operations: [starOp, consumerOp], + assertions: [], + propertyGraphs: [], + targets: [starTarget, consumerTarget], + }), + ); + + expect( + asPlainObject(prune(graph, { actions: ["op_unrelated"], includeDependents: true })), + ).deep.equals( + asPlainObject({ + tables: [], + operations: [unrelatedOp], + assertions: [], + propertyGraphs: [], + targets: [unrelatedTarget], + }), + ); + }); + }); }); diff --git a/cli/commands/run_command.ts b/cli/commands/run_command.ts index bb43921c6..30d3a4878 100644 --- a/cli/commands/run_command.ts +++ b/cli/commands/run_command.ts @@ -108,6 +108,32 @@ function createLineageEmitter( }); } +export function createExecutedGraphPrinter( + actionsByTarget: ReadonlyMap, + dryRun?: boolean, +): (executedGraph: dataform.IRunResult) => void { + const alreadyPrintedActions = new Set(); + return (executedGraph: dataform.IRunResult) => { + for (const executedAction of executedGraph.actions || []) { + if ( + executedAction.status === dataform.ActionResult.ExecutionStatus.RUNNING || + !executedAction.target + ) { + continue; + } + const targetKey = targetStringifier.stringify(executedAction.target); + if (alreadyPrintedActions.has(targetKey)) { + continue; + } + const executionAction = actionsByTarget.get(targetKey); + if (executionAction) { + printExecutedAction(executedAction, executionAction, dryRun); + } + alreadyPrintedActions.add(targetKey); + } + }; +} + export const runCommand: ICommand = { format: `run [${projectDirOption.name}]`, description: "Run the dataform project.", @@ -236,12 +262,14 @@ export const runCommand: ICommand = { bigqueryOptions = { ...bigqueryOptions, labels: argv.jobLabels }; } - const actionsByName = new Map(); + const actionsByTarget = new Map(); executionGraph.actions.forEach((action) => { - actionsByName.set(targetAsReadableString(action.target), action); + if (action.target) { + actionsByTarget.set(targetStringifier.stringify(action.target), action); + } }); - if (actionsByName.size === 0) { + if (actionsByTarget.size === 0) { if (argv.json) { print( prettyJsonStringify({ @@ -280,26 +308,7 @@ export const runCommand: ICommand = { // The first Ctrl+C cancels the run gracefully; a second one exits immediately. setSignalHandler("SIGINT", () => runner.cancel()); - const alreadyPrintedActions = new Set(); - - const printExecutedGraph = (executedGraph: dataform.IRunResult) => { - executedGraph.actions - .filter( - (actionResult) => actionResult.status !== dataform.ActionResult.ExecutionStatus.RUNNING, - ) - .filter( - (executedAction) => - !alreadyPrintedActions.has(targetAsReadableString(executedAction.target)), - ) - .forEach((executedAction) => { - printExecutedAction( - executedAction, - actionsByName.get(targetAsReadableString(executedAction.target)), - argv.dryRun, - ); - alreadyPrintedActions.add(targetAsReadableString(executedAction.target)); - }); - }; + const printExecutedGraph = createExecutedGraphPrinter(actionsByTarget, argv.dryRun); if (!argv.json) { runner.onChange(printExecutedGraph); diff --git a/cli/index_compile_test.ts b/cli/index_compile_test.ts index 18d8910ee..7ff8d066f 100644 --- a/cli/index_compile_test.ts +++ b/cli/index_compile_test.ts @@ -703,6 +703,16 @@ SELECT 1 as id const result = await runCli("compile", [projectDir, "--output-actions", "*stream", "--json"]); expect(result.exitCode, result.stderr).equals(0); expect(tableNames(result.stdout)).deep.equals(["downstream", "midstream", "upstream"]); + + const withDepsResult = await runCli("compile", [ + projectDir, + "--output-actions", + "*.mid*", + "--output-include-deps", + "--json", + ]); + expect(withDepsResult.exitCode, withDepsResult.stderr).equals(0); + expect(tableNames(withDepsResult.stdout)).deep.equals(["midstream", "upstream"]); }); test("--output-actions --output-include-deps pulls in upstream dependencies", async () => { diff --git a/cli/tests/run_command_test.ts b/cli/tests/run_command_test.ts index 0a1f8c4b1..5515c3600 100644 --- a/cli/tests/run_command_test.ts +++ b/cli/tests/run_command_test.ts @@ -1,6 +1,10 @@ import { expect } from "chai"; -import { warnAboutOverrideProtectedFullRefresh } from "df/cli/commands/run_command"; +import { + createExecutedGraphPrinter, + warnAboutOverrideProtectedFullRefresh, +} from "df/cli/commands/run_command"; +import { targetStringifier } from "df/core/targets"; import { dataform } from "df/protos/ts"; import { suite, test } from "df/testing"; @@ -279,3 +283,83 @@ suite("warnAboutOverrideProtectedFullRefresh", ({ beforeEach, afterEach }) => { expect(stderrOutput).deep.equals([]); }); }); + +function stripAnsi(text: string): string { + return text.replace(/\x1b\[[0-9;]*m/g, ""); +} + +function captureStreams(fn: () => void): { stdout: string; stderr: string } { + const stdoutChunks: string[] = []; + const stderrChunks: string[] = []; + const origStdoutWrite = process.stdout.write.bind(process.stdout); + const origStderrWrite = process.stderr.write.bind(process.stderr); + process.stdout.write = ((chunk: string | Uint8Array) => { + stdoutChunks.push(String(chunk)); + return true; + }) as typeof process.stdout.write; + process.stderr.write = ((chunk: string | Uint8Array) => { + stderrChunks.push(String(chunk)); + return true; + }) as typeof process.stderr.write; + try { + fn(); + } finally { + process.stdout.write = origStdoutWrite; + process.stderr.write = origStderrWrite; + } + return { + stdout: stripAnsi(stdoutChunks.join("")), + stderr: stripAnsi(stderrChunks.join("")), + }; +} + +suite("createExecutedGraphPrinter", () => { + test("prints colliding readable targets with their own action types across separate ticks", () => { + const viewTarget: dataform.ITarget = { database: "proj", schema: "b", name: "c" }; + const assertionTarget: dataform.ITarget = { schema: "proj", name: "b.c" }; + + const viewAction: dataform.IExecutionAction = { + type: "table", + tableType: "view", + target: viewTarget, + tasks: [{ type: "statement", statement: "SELECT 1" }], + }; + const assertionAction: dataform.IExecutionAction = { + type: "assertion", + target: assertionTarget, + tasks: [{ type: "assertion", statement: "SELECT 2" }], + }; + + const actionsByTarget = new Map([ + [targetStringifier.stringify(viewTarget), viewAction], + [targetStringifier.stringify(assertionTarget), assertionAction], + ]); + const printExecutedGraph = createExecutedGraphPrinter(actionsByTarget, true); + + const viewCompleted: dataform.IActionResult = { + target: viewTarget, + status: dataform.ActionResult.ExecutionStatus.SUCCESSFUL, + tasks: [{ status: dataform.TaskResult.ExecutionStatus.SUCCESSFUL }], + }; + const assertionRunning: dataform.IActionResult = { + target: assertionTarget, + status: dataform.ActionResult.ExecutionStatus.RUNNING, + tasks: [], + }; + const assertionCompleted: dataform.IActionResult = { + target: assertionTarget, + status: dataform.ActionResult.ExecutionStatus.SUCCESSFUL, + tasks: [{ status: dataform.TaskResult.ExecutionStatus.SUCCESSFUL }], + }; + + const tick1 = captureStreams(() => { + printExecutedGraph({ actions: [viewCompleted, assertionRunning] }); + }); + expect(tick1.stdout.trim()).to.equal("Table dry run success: b.c [view]"); + + const tick2 = captureStreams(() => { + printExecutedGraph({ actions: [viewCompleted, assertionCompleted] }); + }); + expect(tick2.stdout.trim()).to.equal("Assertion dry run success: proj.b.c"); + }); +}); diff --git a/core/utils.ts b/core/utils.ts index a7b22c1f5..6d34dfb14 100644 --- a/core/utils.ts +++ b/core/utils.ts @@ -41,11 +41,13 @@ export const nativeRequire = // above has already consumed every "*", so none can reach here. ("]" and "\" carry // backslashes for the character class's own syntax; "-" and "/" are not metacharacters // outside a class and so need no escaping.) -function globToRegExp(pattern: string): RegExp { +/** @internal */ +export function globToRegExp(pattern: string): RegExp { const escapeLiteral = (literal: string) => literal.replace(/[.+?^${}()|[\]\\]/g, "\\$&"); return new RegExp(`^${pattern.replace(/\*+/g, "*").split("*").map(escapeLiteral).join(".*")}$`); } +/** @internal */ export function matchPatterns(patterns: string[], values: string[]) { const fullyQualifiedActions: string[] = []; patterns.forEach((pattern) => { From aec510ee7e6f6e15975d7d6042eac704f0f218e6 Mon Sep 17 00:00:00 2001 From: Rafal Hawrylak Date: Fri, 27 Nov 2026 14:29:26 +0000 Subject: [PATCH 2/2] fix(cli): precompute prune dependency maps and share selector matcher --- cli/api/commands/prune.ts | 152 +++++++++++++++------------------ cli/api/commands/prune_test.ts | 31 ++++++- cli/commands/run_command.ts | 5 +- core/utils.ts | 74 +++++++++++----- 4 files changed, 151 insertions(+), 111 deletions(-) diff --git a/cli/api/commands/prune.ts b/cli/api/commands/prune.ts index 9cc7b637f..549873f53 100644 --- a/cli/api/commands/prune.ts +++ b/cli/api/commands/prune.ts @@ -9,76 +9,45 @@ function targetKey(target?: dataform.ITarget | null): string | undefined { return target ? targetStringifier.stringify(target) : undefined; } +function formatTargetParts(target: dataform.ITarget): string { + const parts = [ + target.database ? `database: "${target.database}"` : undefined, + target.schema ? `schema: "${target.schema}"` : undefined, + target.name ? `name: "${target.name}"` : undefined, + ].filter(Boolean); + return `{ ${parts.join(", ")} }`; +} + export function prune( compiledGraph: dataform.ICompiledGraph, runConfig: dataform.IRunConfig, ): dataform.ICompiledGraph { (compiledGraph.tables || []).forEach(utils.setOrValidateTableEnumType); - const includedActionKeys = computeIncludedActionKeys(compiledGraph, runConfig); - const isIncluded = (target?: dataform.ITarget | null) => { + const { includedActionKeys, keyByAction } = computeIncludedActionKeys(compiledGraph, runConfig); + const isActionIncluded = (action: CompileAction) => { + const key = keyByAction.get(action); + return key !== undefined && includedActionKeys.has(key); + }; + const isTargetIncluded = (target?: dataform.ITarget | null) => { const key = targetKey(target); return key !== undefined && includedActionKeys.has(key); }; return { ...compiledGraph, - tables: (compiledGraph.tables || []).filter((action) => isIncluded(action.target)), - assertions: (compiledGraph.assertions || []).filter((action) => isIncluded(action.target)), - operations: (compiledGraph.operations || []).filter((action) => isIncluded(action.target)), - propertyGraphs: compiledGraph.propertyGraphs?.filter((action) => isIncluded(action.target)), + tables: (compiledGraph.tables || []).filter(isActionIncluded), + assertions: (compiledGraph.assertions || []).filter(isActionIncluded), + operations: (compiledGraph.operations || []).filter(isActionIncluded), + propertyGraphs: compiledGraph.propertyGraphs?.filter(isActionIncluded), // `targets` is declarative output only (nothing downstream reads it), but // `compile` prints it, so it has to agree with the filtered action lists. - targets: compiledGraph.targets?.filter((target) => isIncluded(target)), + targets: compiledGraph.targets?.filter(isTargetIncluded), }; } -function matchActionSelectors(patterns: string[], allActions: CompileAction[]): string[] { - const matchedActionKeys: string[] = []; - patterns.forEach((pattern) => { - if (pattern.includes("*")) { - // Wildcard selector: patterns containing "." match the full readable target string; - // otherwise they match the unqualified action name, with no ambiguity error. - const regExp = utils.globToRegExp(pattern); - const matchFullTarget = pattern.includes("."); - allActions.forEach((action) => { - if (!action.target) { - return; - } - const candidate = matchFullTarget - ? targetAsReadableString(action.target) - : action.target.name; - if (candidate !== undefined && regExp.test(candidate)) { - matchedActionKeys.push(targetStringifier.stringify(action.target)); - } - }); - } else if (pattern.includes(".")) { - allActions.forEach((action) => { - if (action.target && targetAsReadableString(action.target) === pattern) { - matchedActionKeys.push(targetStringifier.stringify(action.target)); - } - }); - } else { - const matchingActions = allActions.filter((action) => action.target?.name === pattern); - if (matchingActions.length === 0) { - return; - } - if (matchingActions.length > 1) { - throw new Error( - utils.ambiguousActionNameMsg( - pattern, - matchingActions.map((action) => targetAsReadableString(action.target)), - ), - ); - } - matchedActionKeys.push(targetStringifier.stringify(matchingActions[0].target)); - } - }); - return matchedActionKeys; -} - function computeIncludedActionKeys( compiledGraph: dataform.ICompiledGraph, runConfig: dataform.IRunConfig, -): Set { +): { includedActionKeys: Set; keyByAction: Map } { // Union all tables, operations, assertions, property graphs. const allActions: CompileAction[] = [].concat( compiledGraph.tables || [], @@ -88,12 +57,14 @@ function computeIncludedActionKeys( ); const allActionKeys = new Set(); - const allActionsByKey = new Map(); + const keyByAction = new Map(); + const keyedActions: Array<{ action: CompileAction; key: string }> = []; allActions.forEach((action) => { const key = targetKey(action?.target); if (key !== undefined) { allActionKeys.add(key); - allActionsByKey.set(key, action); + keyByAction.set(action, key); + keyedActions.push({ action, key }); } }); @@ -102,28 +73,55 @@ function computeIncludedActionKeys( // If no selectors, return all actions. if (!hasActionSelector && !hasTagSelector) { - return allActionKeys; + return { includedActionKeys: allActionKeys, keyByAction }; } const includedActionKeys = new Set(); // Add all actions included by action filters. if (hasActionSelector) { - matchActionSelectors(runConfig.actions, allActions).forEach((actionKey) => - includedActionKeys.add(actionKey), - ); + const candidates: utils.IMatchCandidate[] = keyedActions.map(({ action, key }) => { + const fullName = targetAsReadableString(action.target); + return { + fullName, + shortName: action.target.name, + key, + disambiguatedName: `${fullName} (${formatTargetParts(action.target)})`, + }; + }); + utils + .matchCandidatePatterns(runConfig.actions, candidates) + .forEach((actionKey) => includedActionKeys.add(actionKey)); } // Determine actions selected with --tag option and update applicable actions if (hasTagSelector) { - allActions - .filter((action) => action.tags?.some((tag) => runConfig.tags.includes(tag))) - .forEach((action) => { - const key = targetKey(action.target); - if (key !== undefined) { - includedActionKeys.add(key); + keyedActions.forEach(({ action, key }) => { + if (action.tags?.some((tag) => runConfig.tags.includes(tag))) { + includedActionKeys.add(key); + } + }); + } + + const dependencyKeysByActionKey = new Map(); + const dependentKeysByActionKey = new Map(); + if (runConfig.includeDependencies || runConfig.includeDependents) { + keyedActions.forEach(({ action, key }) => { + const dependencyKeys: string[] = []; + (action.dependencyTargets || []).forEach((dependency) => { + const dependencyKey = targetKey(dependency); + if (dependencyKey !== undefined && allActionKeys.has(dependencyKey)) { + dependencyKeys.push(dependencyKey); + let dependents = dependentKeysByActionKey.get(dependencyKey); + if (!dependents) { + dependents = []; + dependentKeysByActionKey.set(dependencyKey, dependents); + } + dependents.push(key); } }); + dependencyKeysByActionKey.set(key, dependencyKeys); + }); } // Compute all transitive dependencies. @@ -131,14 +129,8 @@ function computeIncludedActionKeys( const queue = [...includedActionKeys]; while (queue.length > 0) { const actionKey = queue.pop(); - const action = allActionsByKey.get(actionKey); - (action?.dependencyTargets || []).forEach((dependency) => { - const dependencyKey = targetKey(dependency); - if ( - dependencyKey !== undefined && - allActionKeys.has(dependencyKey) && - !includedActionKeys.has(dependencyKey) - ) { + (dependencyKeysByActionKey.get(actionKey) || []).forEach((dependencyKey) => { + if (!includedActionKeys.has(dependencyKey)) { queue.push(dependencyKey); includedActionKeys.add(dependencyKey); } @@ -151,20 +143,14 @@ function computeIncludedActionKeys( const queue = [...includedActionKeys]; while (queue.length > 0) { const actionKey = queue.pop(); - allActions.forEach((compileAction) => { - const dependsOnAction = compileAction.dependencyTargets?.some( - (dependency) => targetKey(dependency) === actionKey, - ); - if (dependsOnAction) { - const dependentKey = targetKey(compileAction.target); - if (dependentKey !== undefined && !includedActionKeys.has(dependentKey)) { - queue.push(dependentKey); - includedActionKeys.add(dependentKey); - } + (dependentKeysByActionKey.get(actionKey) || []).forEach((dependentKey) => { + if (!includedActionKeys.has(dependentKey)) { + queue.push(dependentKey); + includedActionKeys.add(dependentKey); } }); } } - return includedActionKeys; + return { includedActionKeys, keyByAction }; } diff --git a/cli/api/commands/prune_test.ts b/cli/api/commands/prune_test.ts index c4f54985d..589643e72 100644 --- a/cli/api/commands/prune_test.ts +++ b/cli/api/commands/prune_test.ts @@ -290,7 +290,36 @@ suite("prune", () => { targets: [COLLIDING_TABLE_TARGET, otherC.target], }; expect(() => prune(graph, { actions: ["c"] })).to.throw( - "Ambiguous Action name: c. Did you mean one of: proj.b.c, proj.b.c.", + 'Ambiguous Action name: c. Did you mean one of: proj.b.c ({ database: "proj", schema: "b", name: "c" }), proj.b.c ({ schema: "proj.b", name: "c" }).', + ); + }); + + test("unqualified --actions keeps plain readable names when candidates do not collide", () => { + const firstC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { database: "proj", schema: "s1", name: "c" }, + canonicalTarget: { database: "proj", schema: "s1", name: "c" }, + query: "select 1", + dependencyTargets: [], + }; + const secondC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { database: "proj", schema: "s2", name: "c" }, + canonicalTarget: { database: "proj", schema: "s2", name: "c" }, + query: "select 2", + dependencyTargets: [], + }; + const graph: dataform.ICompiledGraph = { + tables: [firstC, secondC], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [firstC.target, secondC.target], + }; + expect(() => prune(graph, { actions: ["c"] })).to.throw( + "Ambiguous Action name: c. Did you mean one of: proj.s1.c, proj.s2.c.", ); }); diff --git a/cli/commands/run_command.ts b/cli/commands/run_command.ts index 30d3a4878..cfef5fb36 100644 --- a/cli/commands/run_command.ts +++ b/cli/commands/run_command.ts @@ -125,10 +125,7 @@ export function createExecutedGraphPrinter( if (alreadyPrintedActions.has(targetKey)) { continue; } - const executionAction = actionsByTarget.get(targetKey); - if (executionAction) { - printExecutedAction(executedAction, executionAction, dryRun); - } + printExecutedAction(executedAction, actionsByTarget.get(targetKey), dryRun); alreadyPrintedActions.add(targetKey); } }; diff --git a/core/utils.ts b/core/utils.ts index 6d34dfb14..9fb961e89 100644 --- a/core/utils.ts +++ b/core/utils.ts @@ -41,46 +41,74 @@ export const nativeRequire = // above has already consumed every "*", so none can reach here. ("]" and "\" carry // backslashes for the character class's own syntax; "-" and "/" are not metacharacters // outside a class and so need no escaping.) -/** @internal */ -export function globToRegExp(pattern: string): RegExp { +function globToRegExp(pattern: string): RegExp { const escapeLiteral = (literal: string) => literal.replace(/[.+?^${}()|[\]\\]/g, "\\$&"); return new RegExp(`^${pattern.replace(/\*+/g, "*").split("*").map(escapeLiteral).join(".*")}$`); } /** @internal */ -export function matchPatterns(patterns: string[], values: string[]) { - const fullyQualifiedActions: string[] = []; +export interface IMatchCandidate { + fullName: string; + shortName?: string; + key: string; + disambiguatedName?: string; +} + +/** @internal */ +export function matchCandidatePatterns( + patterns: string[], + candidates: IMatchCandidate[], +): string[] { + const matchedKeys: string[] = []; patterns.forEach((pattern) => { if (pattern.includes("*")) { - // Wildcard selector. A pattern that contains "." matches against the - // fully-qualified action name; otherwise it matches against the unqualified - // name (last segment), mirroring the exact-match branches below. Wildcards - // are expected to select many actions, so no ambiguity error applies here. + // Wildcard selector: patterns containing "." match the full readable target string; + // otherwise they match the unqualified action name, with no ambiguity error. const regExp = globToRegExp(pattern); - const scope = pattern.includes(".") - ? values - : values.map((value) => value.split(".").slice(-1)[0]); - values.forEach((value, i) => { - if (regExp.test(scope[i])) { - fullyQualifiedActions.push(value); + const matchFullTarget = pattern.includes("."); + candidates.forEach((candidate) => { + const value = matchFullTarget ? candidate.fullName : candidate.shortName; + if (value !== undefined && regExp.test(value)) { + matchedKeys.push(candidate.key); } }); } else if (pattern.includes(".")) { - if (values.includes(pattern)) { - fullyQualifiedActions.push(pattern); - } + // Dotted selectors are already fully qualified in CLI syntax, so when distinct targets + // render to the same dotted string, all matching targets are selected. + candidates.forEach((candidate) => { + if (candidate.fullName === pattern) { + matchedKeys.push(candidate.key); + } + }); } else { - const matchingActions = values.filter((value) => pattern === value.split(".").slice(-1)[0]); - if (matchingActions.length === 0) { + const matching = candidates.filter((candidate) => candidate.shortName === pattern); + if (matching.length === 0) { return; } - if (matchingActions.length > 1) { - throw new Error(ambiguousActionNameMsg(pattern, matchingActions)); + if (matching.length > 1) { + const fullNames = matching.map((candidate) => candidate.fullName); + const displayNames = + new Set(fullNames).size < fullNames.length + ? matching.map((candidate) => candidate.disambiguatedName || candidate.fullName) + : fullNames; + throw new Error(ambiguousActionNameMsg(pattern, displayNames)); } - fullyQualifiedActions.push(matchingActions[0]); + matchedKeys.push(matching[0].key); } }); - return fullyQualifiedActions; + return matchedKeys; +} + +/** @internal */ +export function matchPatterns(patterns: string[], values: string[]) { + return matchCandidatePatterns( + patterns, + values.map((value) => ({ + fullName: value, + shortName: value.split(".").slice(-1)[0], + key: value, + })), + ); } export function getCallerFile(rootDir: string) {