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
8 changes: 6 additions & 2 deletions src/TaskRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ export class TaskRunner<TContext> {

if (step.dependencies) {
for (const dep of step.dependencies) {
const depId = getUniqueId(dep);
const depName = typeof dep === "string" ? dep : dep.step;
const depId = getUniqueId(depName);
edgeLines.add(` ${depId} --> ${stepId}`);
}
}
Expand Down Expand Up @@ -180,7 +181,10 @@ export class TaskRunner<TContext> {
const taskGraph: TaskGraph = {
tasks: steps.map((step) => ({
id: step.name,
dependencies: step.dependencies ?? [],
dependencies:
step.dependencies?.map((dep) =>
typeof dep === "string" ? dep : dep.step
) ?? [],
})),
};

Expand Down
48 changes: 32 additions & 16 deletions src/TaskStateManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TaskStep } from "./TaskStep.js";
import { TaskRunCondition, TaskStep } from "./TaskStep.js";
import { TaskResult } from "./TaskResult.js";
import { EventBus } from "./EventBus.js";

Expand All @@ -12,7 +12,7 @@
private readonly running = new Set<string>();

// Optimization structures
private readonly dependencyGraph = new Map<string, TaskStep<TContext>[]>();
private readonly dependencyGraph = new Map<string, { step: TaskStep<TContext>; condition: TaskRunCondition }[]>();
private readonly dependencyCounts = new Map<string, number>();
private readyQueue: TaskStep<TContext>[] = [];
private readonly taskDefinitions = new Map<string, TaskStep<TContext>>();
Expand All @@ -23,7 +23,7 @@
* Initializes the state with the given steps.
* @param steps The steps to execute.
*/
initialize(steps: TaskStep<TContext>[]): void {

Check failure on line 26 in src/TaskStateManager.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=thalesraymond_task-runner&issues=AZ105oZn0UMIDiWzn-ZI&open=AZ105oZn0UMIDiWzn-ZI&pullRequest=257
this.pendingSteps = new Set(steps);
this.results.clear();
this.running.clear();
Expand All @@ -42,12 +42,15 @@
this.readyQueue.push(step);
} else {
for (const dep of deps) {
let dependents = this.dependencyGraph.get(dep);
const depName = typeof dep === "string" ? dep : dep.step;
const condition = typeof dep === "string" ? "success" : (dep.runCondition ?? "success");

let dependents = this.dependencyGraph.get(depName);
if (dependents === undefined) {
dependents = [];
this.dependencyGraph.set(dep, dependents);
this.dependencyGraph.set(depName, dependents);
}
dependents.push(step);
dependents.push({ step, condition });
}
}
}
Expand Down Expand Up @@ -182,15 +185,22 @@
if (!dependents) return;

for (const dependent of dependents) {
const currentCount = this.dependencyCounts.get(dependent.name)!;
const newCount = currentCount - 1;
this.dependencyCounts.set(dependent.name, newCount);

if (newCount === 0) {
// Task is ready. Ensure it's still pending.
if (this.pendingSteps.has(dependent)) {
this.readyQueue.push(dependent);
}
this.decrementDependencyCount(dependent.step);
}
}

/**
* Decrements the dependency count for a task and queues it if ready.
*/
private decrementDependencyCount(dependent: TaskStep<TContext>): void {
const currentCount = this.dependencyCounts.get(dependent.name)!;
const newCount = currentCount - 1;
this.dependencyCounts.set(dependent.name, newCount);

if (newCount === 0) {
// Task is ready. Ensure it's still pending.
if (this.pendingSteps.has(dependent)) {
this.readyQueue.push(dependent);
}
}
}
Expand All @@ -216,13 +226,19 @@
const depError = currentResult?.error ? `: ${currentResult.error}` : "";

for (const dependent of dependents) {
// If the dependent runs 'always' and the parent task *actually failed* (not skipped), we can unblock it
if (dependent.condition === "always" && currentResult?.status === "failure") {
this.decrementDependencyCount(dependent.step);
continue;
}
Comment on lines +229 to +233
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current logic for always dependencies only considers the failure status to unblock the dependent task. This means if a parent task is cancelled, any always dependent task will be incorrectly skipped instead of being executed for cleanup.

According to the feature's goal of ensuring cleanup tasks run, always should trigger on any non-successful completion of the parent task, except when the parent was skipped.

I suggest modifying the condition to unblock always dependents for any terminal status that isn't skipped, which would correctly include both failure and cancelled.

Suggested change
// If the dependent runs 'always' and the parent task *actually failed* (not skipped), we can unblock it
if (dependent.condition === "always" && currentResult?.status === "failure") {
this.decrementDependencyCount(dependent.step);
continue;
}
// If the dependent runs 'always' and the parent task *actually ran* (i.e., was not skipped), we can unblock it
if (dependent.condition === "always" && currentResult && currentResult.status !== "skipped") {
this.decrementDependencyCount(dependent.step);
continue;
}


const result: TaskResult = {
status: "skipped",
message: `Skipped because dependency '${currentName}' failed${depError}`,
};

if (this.internalMarkSkipped(dependent, result)) {
queue.push(dependent.name);
if (this.internalMarkSkipped(dependent.step, result)) {
queue.push(dependent.step.name);
}
}
}
Expand Down
9 changes: 8 additions & 1 deletion src/TaskStep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import { TaskResult } from "./TaskResult.js";
import { TaskRetryConfig } from "./contracts/TaskRetryConfig.js";
import { TaskLoopConfig } from "./contracts/TaskLoopConfig.js";

export type TaskRunCondition = "success" | "always";

export interface TaskDependencyConfig {
step: string;
runCondition?: TaskRunCondition;
}

/**
* Represents a single, executable step within a workflow.
* @template TContext The shape of the shared context object.
Expand All @@ -10,7 +17,7 @@ export interface TaskStep<TContext> {
/** A unique identifier for this task. */
name: string;
/** An optional list of task names that must complete successfully before this step can run. */
dependencies?: string[];
dependencies?: (string | TaskDependencyConfig)[];
/** Optional retry configuration for the task. */
retry?: TaskRetryConfig;
/** Optional loop configuration for the task. */
Expand Down
29 changes: 29 additions & 0 deletions tests/TaskRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,4 +267,33 @@ describe("TaskRunner", () => {
const results = await runner.execute(steps);
expect(results.get("A")?.message).toBe("Executed by custom strategy");
});

describe("teardown scenarios", () => {
it("should execute a cleanup task even if the preceding task fails, using 'always' runCondition", async () => {
const runner = new TaskRunner<Record<string, unknown>>({});

const setup: TaskStep<Record<string, unknown>> = {
name: "Setup",
run: async () => ({ status: "success" }),
};

const work: TaskStep<Record<string, unknown>> = {
name: "Work",
dependencies: ["Setup"],
run: async () => ({ status: "failure", error: "Something broke" }),
};

const teardown: TaskStep<Record<string, unknown>> = {
name: "Teardown",
dependencies: [{ step: "Work", runCondition: "always" }],
run: async () => ({ status: "success" }),
};

const results = await runner.execute([setup, work, teardown]);

expect(results.get("Setup")?.status).toBe("success");
expect(results.get("Work")?.status).toBe("failure");
expect(results.get("Teardown")?.status).toBe("success"); // Teardown ran despite Work failing!
});
});
});
14 changes: 14 additions & 0 deletions tests/TaskRunnerMermaid.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ describe("TaskRunner Mermaid Graph", () => {
expect(lines).toContain(" B[\"B\"]");
});

it("should generate a graph for a sequence of tasks with mixed dependencies", () => {
const steps: TaskStep<void>[] = [
{ name: "A", run: async () => ({ status: "success" }) },
{ name: "B", dependencies: [{ step: "A", runCondition: "always" }], run: async () => ({ status: "success" }) },
{ name: "C", dependencies: ["B"], run: async () => ({ status: "success" }) },
];
const graph = TaskRunner.getMermaidGraph(steps);
expect(graph).toContain("A[\"A\"]");
expect(graph).toContain("B[\"B\"]");
expect(graph).toContain("C[\"C\"]");
expect(graph).toContain("A --> B");
expect(graph).toContain("B --> C");
});

it("should generate a graph with dependencies", () => {
const steps: TaskStep<unknown>[] = [
{ name: "A", run: async () => ({ status: "success" }) },
Expand Down
64 changes: 64 additions & 0 deletions tests/TaskStateManager_coverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,68 @@ describe("TaskStateManager Coverage", () => {

expect(stateManager.getResults().get("B")?.status).toBe("cancelled");
});
it("should push 'always' dependent to readyQueue when dependency fails", () => {
const eventBus = new EventBus<void>();
const stateManager = new TaskStateManager<void>(eventBus);

const stepA: TaskStep<void> = { name: "A", run: async () => ({ status: "failure" }) };
const stepB: TaskStep<void> = { name: "B", dependencies: [{ step: "A", runCondition: "always" }], run: async () => ({ status: "success" }) };

stateManager.initialize([stepA, stepB]);

const readyA = stateManager.processDependencies();
expect(readyA).toHaveLength(1);
expect(readyA[0].name).toBe("A");

stateManager.markRunning(readyA[0]);
stateManager.markCompleted(readyA[0], { status: "failure", error: "failed A" });

// B should be queued because of 'always' condition despite A failing
const readyB = stateManager.processDependencies();
expect(readyB).toHaveLength(1);
expect(readyB[0].name).toBe("B");
});

it("should skip 'always' dependent if dependency is skipped", () => {
const eventBus = new EventBus<void>();
const stateManager = new TaskStateManager<void>(eventBus);

const stepX: TaskStep<void> = { name: "X", run: async () => ({ status: "failure" }) };
const stepA: TaskStep<void> = { name: "A", dependencies: ["X"], run: async () => ({ status: "success" }) };
const stepB: TaskStep<void> = { name: "B", dependencies: [{ step: "A", runCondition: "always" }], run: async () => ({ status: "success" }) };

stateManager.initialize([stepX, stepA, stepB]);

const readyX = stateManager.processDependencies();
expect(readyX).toHaveLength(1);

stateManager.markRunning(readyX[0]);
stateManager.markCompleted(readyX[0], { status: "failure" }); // X fails -> A skips

// processDependencies should be empty because A is skipped, and B is skipped too
const readyB = stateManager.processDependencies();
expect(readyB).toHaveLength(0);

expect(stateManager.getResults().get("A")?.status).toBe("skipped");
expect(stateManager.getResults().get("B")?.status).toBe("skipped");
});

it("should handle default runCondition when TaskDependencyConfig omits it", () => {
const eventBus = new EventBus<void>();
const stateManager = new TaskStateManager<void>(eventBus);

const stepA: TaskStep<void> = { name: "A", run: async () => ({ status: "failure" }) };
const stepB: TaskStep<void> = { name: "B", dependencies: [{ step: "A" }], run: async () => ({ status: "success" }) };

stateManager.initialize([stepA, stepB]);

const readyA = stateManager.processDependencies();
stateManager.markRunning(readyA[0]);
stateManager.markCompleted(readyA[0], { status: "failure" });

// B should be skipped because it defaults to 'success'
const readyB = stateManager.processDependencies();
expect(readyB).toHaveLength(0);
expect(stateManager.getResults().get("B")?.status).toBe("skipped");
});
});
Loading