tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
feat(cli): keep a timeline of each build and print its critical path
- Commit
3d07f51997478121abcf41917f2a71cc6a32eea4- Author
- Leitwolf11 ·
- Parents
9fd337b72f79
Changes
CHANGELOG.md | 3 + docs/commands.md | 1 + src/Progmasoft.Tazel/Cli/CommandLine.cs | 4 +- src/Progmasoft.Tazel/Cli/CommandMakers.cs | 1 + src/Progmasoft.Tazel/Cli/CommandTypes.cs | 3 + src/Progmasoft.Tazel/Cli/Commands.cs | 11 +- src/Progmasoft.Tazel/Cli/Help.cs | 11 ++ src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 1 + src/Progmasoft.Tazel/Cli/TraceCommands.cs | 57 +++++++ src/Progmasoft.Tazel/Driver/BuildTimeline.cs | 195 ++++++++++++++++++++++++ src/Progmasoft.Tazel/Driver/Executor.cs | 18 ++- tests/Progmasoft.Tazel.Tests/BuildTraceTests.cs | 164 ++++++++++++++++++++ 12 files changed, 462 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea1b25e..23ef369 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,9 @@ - `tazel log why <label>`: every build records why each action ran (its first cause: changed, removed or new input with old and new digests, changed command, changed output, no record, or forced) in `.tazel/logs/why.json`, and the command prints the chain from the first changed source through each rebuild to the target's actions. +- `tazel trace [--output <file>]`: every build keeps the times of the actions that ran in `.tazel/logs/trace.json` + (Chrome Trace Event format, lanes for parallel actions, the actions each waited for); the command prints the critical + path with each action's time and its share of the wall time, and `--output` exports the timeline for Perfetto. ## 0.5.0 - 2026-12-03 diff --git a/docs/commands.md b/docs/commands.md index 24d1e7b..872263f 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -17,6 +17,7 @@ | `tazel git add` | stages the module's files with system `git`, respecting `.gitignore` | | `tazel log cache\|workspace\|what-ran\|what-failed\|what-up\|snoop\|daemon\|registries` | read-only inspection of cache, module root, recent runs, daemon status, and effective registries | | `tazel log why <label>` | why the target's actions ran in the last build: for each, the first cause (a changed, removed or newly read input with its old and new SHA-256 prefix, a changed command, an output changed behind the build's back, no earlier record, or `--no-cache`/`--recompile`) and the chain of rebuilds from that cause to the action; it reads `.tazel/logs/why.json`, which every build rewrites, and loads no `BUILD.csx` | +| `tazel trace [--output <file>]` | the critical path of the last build: the chain of actions, each waiting for the one before it, that decided its wall time, with each action's time and the path's share of the wall time; `--output` writes the timeline (Chrome Trace Event JSON, one row per lane of parallel actions) for Perfetto or `chrome://tracing`; every build keeps it in `.tazel/logs/trace.json` | | `tazel doctor` | checks local compilers, runtime, git, Linux KVM/MicroVM, and daemon status without requiring a workspace | | `tazel dump [--cadre-celeste=...] [-o text\|json]` | inspects the running .NET daemon and Cadre Celeste state without starting a daemon | | `tazel ide compdb [labels] [-o <file>]` | writes a deterministic `compile_commands.json` for C/C++/ObjC targets (default `//...`) | diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index cbbe653..ea16a31 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -20,7 +20,7 @@ internal static class CommandLine { /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = - ["build", "run", "test", "coverage", "query", "cquery", "aquery", "new", "init", "git", "log", "doctor", "dump", "ide", "modules", "update", "fetch", "vendor", "clean", "trash", "package", "custom", + ["build", "run", "test", "coverage", "query", "cquery", "aquery", "new", "init", "git", "log", "doctor", "dump", "ide", "modules", "update", "fetch", "vendor", "clean", "trash", "trace", "package", "custom", "cache", "explain", "version", "help", "license", "shell-completion", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool", "ignore"]; private static readonly string[] Building = ["build", "run", "test", "coverage", "cquery", "aquery", "ide"]; @@ -80,7 +80,7 @@ internal static class CommandLine new("memory", OptionKind.Value, ["true", "false"], "dump"), new("filter", OptionKind.Value, null, "dump"), new("label", OptionKind.Value, null, "dump"), - new("output", OptionKind.Value, null, "query", "cquery", "aquery", "license", "version", "dump", "ide"), + new("output", OptionKind.Value, null, "query", "cquery", "aquery", "license", "version", "dump", "ide", "trace"), ]; /// <summary>Reads <paramref name="arguments"/>.</summary> diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index d546396..617dea1 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -40,6 +40,7 @@ internal static class CommandMakers ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(output)), ["clean"] = (scanned, output) => Bare(scanned, new CleanCommand(output, scanned.Has("expunge"), scanned.Has("dry-run"))), ["trash"] = MakeTrash, + ["trace"] = (scanned, output) => Bare(scanned, new TraceCommand(output, scanned.Last("output"))), ["package"] = (scanned, output) => Bare(scanned, new PackageCommand(output, scanned.Has("list"), scanned.Has("allow-dirty"), scanned.Last("output-dir"))), ["custom"] = (scanned, output) => scanned.Positional.Count == 0 ? throw new CommandLineException("tazel custom needs the name of a command of tazel_custom.txt") diff --git a/src/Progmasoft.Tazel/Cli/CommandTypes.cs b/src/Progmasoft.Tazel/Cli/CommandTypes.cs index 95a0e04..f90fc95 100644 --- a/src/Progmasoft.Tazel/Cli/CommandTypes.cs +++ b/src/Progmasoft.Tazel/Cli/CommandTypes.cs @@ -209,6 +209,9 @@ internal sealed record GitAddCommand(OutputOptions Output) : Command(Output); internal sealed record TrashCommand(OutputOptions Output, string Action, string? Fingerprint, TimeSpan? OlderThan, bool DryRun) : Command(Output); +/// <summary><c>tazel trace [--output <file>]</c>: the critical path of the last build, and its timeline.</summary> +internal sealed record TraceCommand(OutputOptions Output, string? OutputFile) : Command(Output); + /// <summary><c>tazel log <action></c>: read-only inspection of workspace, cache, runs, daemon, and registries.</summary> internal sealed record LogCommand(OutputOptions Output, string Action, string? Argument = null) : Command(Output); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index d402a92..600e43d 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -50,6 +50,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector InitCommand init => Task.FromResult(new NewInitCommands(reporter, workingDirectory).Init(init.Force)), LogCommand log => Task.FromResult(new LogCommands(reporter, workingDirectory, TazelVersion).Run(log.Action, log.Argument)), TrashCommand trash => Task.FromResult(new TrashCommands(reporter).Run(trash)), + TraceCommand trace => Task.FromResult(new TraceCommands(reporter, workingDirectory).Run(trace)), DoctorCommand => new DoctorCommands(reporter, TazelVersion).RunAsync(cancel), DumpCommand dump => new DumpCommands(reporter).RunAsync(dump, cancel), IdeCompdbCommand compdb => new IdeCommands(reporter, workingDirectory, TazelVersion).CompdbAsync(compdb), @@ -578,9 +579,10 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector : null; var remoteActions = remoteCache is null ? null : RemoteActionsOf(remoteCache, cacheSettings!.Remote!.Settings, digests); var reasons = new RebuildReasonLog(); + var timeline = new BuildTimeline(); var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind is BuildKind.Test or BuildKind.Coverage, new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter, remoteActions, buildOptions.CachePolicy, - planner.Layout.Full($"{ModuleFiles.StateDirectory}/forced"), reasons); + planner.Layout.Full($"{ModuleFiles.StateDirectory}/forced"), reasons, timeline); bool succeeded; try { @@ -589,21 +591,22 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector finally { // What ran is worth explaining whether the build passed, failed or was stopped. - WriteReasons(planner.Layout.Full(ModuleFiles.StateDirectory), reasons); + WriteReasons(planner.Layout.Full(ModuleFiles.StateDirectory), reasons, timeline); } return new Built(buildOptions, planner, chooser, executor, succeeded, planned); } - private void WriteReasons(string state, RebuildReasonLog reasons) + private void WriteReasons(string state, RebuildReasonLog reasons, BuildTimeline timeline) { try { RebuildReasons.Write(state, reasons.All); + BuildTrace.Write(state, timeline.Spans()); } catch (Exception problem) when (problem is IOException or UnauthorizedAccessException) { - reporter.Warning($"tazel log why will not know this build: {problem.Message}"); + reporter.Warning($"tazel log why and tazel trace will not know this build: {problem.Message}"); } } diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 290f8df..7dabf43 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -368,6 +368,17 @@ internal static class Help Stages MODULE.csx, reachable BUILD.csx files, target sources/headers/data, configuration files, LOCK.sqlite3, .tazelignore and .gitignore using system git add -- <paths>, respecting .gitignore. """), + ["trace"] = new("tazel trace [--output <file>]: the critical path of the last build.", """ + tazel trace [--output <file>] + + Prints the critical path of the last build, run, test or coverage: the chain of actions, each waiting for the + one before it, that decided how long the build took, with each action's time and the share of the build's + wall time the path took. Actions that were current took no time and are left out, but an action that waited + for one of them waited for what that one waited for. + --output writes the timeline in the Chrome Trace Event format, which Perfetto (ui.perfetto.dev) and + chrome://tracing open; one row per lane of actions that ran side by side. Every build keeps it in + .tazel/logs/trace.json. + """), ["trash"] = new("tazel trash list|size|restore|empty: caches moved by tazel clean --expunge.", """ tazel trash list tazel trash size diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs index fb62348..428ac51 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -76,6 +76,7 @@ internal static class ShellCompletion ("vendor", "Copy dependencies into vendor/"), ("clean", "Remove build outputs"), ("trash", "List, measure, restore or empty caches moved by clean --expunge"), + ("trace", "Print the last build's critical path and export its timeline"), ("package", "Create a module archive"), ("custom", "Run a custom command from tazel_custom.txt"), ("cache", "Manage remote cache keys and validate or repair caches"), diff --git a/src/Progmasoft.Tazel/Cli/TraceCommands.cs b/src/Progmasoft.Tazel/Cli/TraceCommands.cs new file mode 100644 index 0000000..0c25aab --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/TraceCommands.cs @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Globalization; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary><c>tazel trace</c>: the critical path of the last build, and its timeline for Perfetto.</summary> +internal sealed class TraceCommands(Reporter reporter, string workingDirectory) +{ + public int Run(TraceCommand command) + { + var root = ModuleFiles.FindRoot(workingDirectory); + var state = Path.Combine(root, ModuleFiles.StateDirectory); + var spans = BuildTrace.Read(state); + if (spans is null) + { + reporter.Status("no build has been traced here yet; build first, then trace"); + return 0; + } + + if (command.OutputFile is { } output) + { + var target = Path.GetFullPath(Path.Combine(workingDirectory, output)); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(Path.Combine(state, BuildTrace.RelativePath), target, overwrite: true); + reporter.Success($"wrote the timeline to {target}; open it in ui.perfetto.dev or chrome://tracing"); + } + + if (spans.Count == 0) + { + reporter.Status("the last build ran no actions: everything was current"); + return 0; + } + + var path = BuildTrace.CriticalPath(spans); + var wall = spans.Max(span => span.End) - spans.Min(span => span.Start); + var onPath = path.Sum(span => span.Duration); + foreach (var span in path) + { + reporter.Plain($"{Milliseconds(span.Duration),10} {span.Description}{(span.Ok ? "" : " (failed)")}"); + } + + var share = wall == 0 ? 100 : onPath * 100 / wall; + reporter.Status($"critical path: {path.Count} of {spans.Count} actions, {Milliseconds(onPath)} of " + + $"{Milliseconds(wall)} wall time ({share.ToString(CultureInfo.InvariantCulture)}%)"); + return 0; + } + + private static string Milliseconds(long microseconds) => + (microseconds / 1000.0).ToString("0.0", CultureInfo.InvariantCulture) + " ms"; +} diff --git a/src/Progmasoft.Tazel/Driver/BuildTimeline.cs b/src/Progmasoft.Tazel/Driver/BuildTimeline.cs new file mode 100644 index 0000000..ff8df3b --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/BuildTimeline.cs @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>One action that ran in a build, as the trace keeps it.</summary> +/// <param name="Id">Its number in the trace, from 1.</param> +/// <param name="Description">What it did.</param> +/// <param name="Target">The label of its target, or null.</param> +/// <param name="Start">When it started, in microseconds from the start of the build.</param> +/// <param name="End">When it ended, in the same unit.</param> +/// <param name="Ok">Whether it succeeded.</param> +/// <param name="Lane">The row it is drawn on: lanes are given so that no two spans of a lane overlap.</param> +/// <param name="After">The ids of the actions of the trace it waited for, through any that were current.</param> +public sealed record TraceSpan(int Id, string Description, string? Target, long Start, long End, bool Ok, int Lane, IReadOnlyList<int> After) +{ + /// <summary>How long it ran, in microseconds.</summary> + public long Duration => End - Start; +} + +/// <summary> +/// The times of the actions that ran in a build, for <c>tazel trace</c>. Each build writes them to +/// <c>.tazel/logs/trace.json</c> in the Chrome Trace Event format, which Perfetto and <c>chrome://tracing</c> open. +/// </summary> +internal sealed class BuildTimeline +{ + private readonly Stopwatch _clock = Stopwatch.StartNew(); + private readonly ConcurrentQueue<(BuildAction Action, long Start, long End, bool Ok)> _ran = new(); + + /// <summary>Microseconds since the build started.</summary> + public long Now => _clock.ElapsedTicks * 1_000_000 / Stopwatch.Frequency; + + /// <summary>Records that <paramref name="action"/> ran from <paramref name="start"/> until now.</summary> + public void Add(BuildAction action, long start, bool ok) => _ran.Enqueue((action, start, Now, ok)); + + /// <summary>The spans, ordered by start, with their lanes and what each waited for.</summary> + public IReadOnlyList<TraceSpan> Spans() + { + var ran = _ran.OrderBy(entry => entry.Start).ThenBy(entry => entry.Action.Description, StringComparer.Ordinal).ToList(); + var ids = new Dictionary<BuildAction, int>(ReferenceEqualityComparer.Instance); + for (var i = 0; i < ran.Count; i++) + { + ids[ran[i].Action] = i + 1; + } + + var laneEnds = new List<long>(); + var spans = new List<TraceSpan>(ran.Count); + foreach (var (action, start, end, ok) in ran) + { + var lane = laneEnds.FindIndex(laneEnd => laneEnd <= start); + if (lane < 0) + { + lane = laneEnds.Count; + laneEnds.Add(end); + } + else + { + laneEnds[lane] = end; + } + + spans.Add(new TraceSpan(ids[action], action.Description, action.Target, start, end, ok, lane, After(action, ids))); + } + + return spans; + } + + // The traced actions this one waited for: its prerequisites, and through a prerequisite that was current, that one's. + private static List<int> After(BuildAction action, Dictionary<BuildAction, int> ids) + { + var found = new SortedSet<int>(); + var seen = new HashSet<BuildAction>(ReferenceEqualityComparer.Instance); + var pending = new Stack<BuildAction>(action.Prerequisites); + while (pending.TryPop(out var prerequisite)) + { + if (!seen.Add(prerequisite)) + { + continue; + } + + if (ids.TryGetValue(prerequisite, out var id)) + { + found.Add(id); + continue; + } + + foreach (var next in prerequisite.Prerequisites) + { + pending.Push(next); + } + } + + return [.. found]; + } +} + +/// <summary>Reads and writes <c>.tazel/logs/trace.json</c>, and finds the critical path in it.</summary> +public static class BuildTrace +{ + /// <summary>The file, below the module's <c>.tazel/</c>.</summary> + public static string RelativePath { get; } = "logs/trace.json"; + + /// <summary>Writes <paramref name="spans"/> as the last build's trace.</summary> + public static void Write(string stateDirectory, IReadOnlyList<TraceSpan> spans) + { + ArgumentNullException.ThrowIfNull(stateDirectory); + ArgumentNullException.ThrowIfNull(spans); + var file = Path.Combine(stateDirectory, RelativePath); + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + var document = new TraceDocument( + [.. spans.Select(span => new TraceEvent( + span.Description, span.Target ?? "action", "X", span.Start, span.Duration, 1, span.Lane + 1, + new TraceArgs(span.Id, span.Target, span.Ok, span.After)))], + "ms"); + var partial = file + ".partial"; + File.WriteAllText(partial, JsonSerializer.Serialize(document, BuildTraceJson.Default.TraceDocument)); + File.Move(partial, file, overwrite: true); + } + + /// <summary>The spans of the last build's trace, or null when there is none or it cannot be read.</summary> + public static IReadOnlyList<TraceSpan>? Read(string stateDirectory) + { + var file = Path.Combine(stateDirectory, RelativePath); + if (!File.Exists(file)) + { + return null; + } + + try + { + var document = JsonSerializer.Deserialize(File.ReadAllText(file), BuildTraceJson.Default.TraceDocument); + return document?.TraceEvents + .Where(item => item.Ph == "X" && item.Args is not null) + .Select(item => new TraceSpan(item.Args!.Id, item.Name, item.Args.Target, item.Ts, item.Ts + item.Dur, + item.Args.Ok, item.Tid - 1, item.Args.After ?? [])) + .ToList(); + } + catch (JsonException) + { + return null; + } + } + + /// <summary> + /// The critical path: from the span that ended last, back through the span it waited for that ended last, to one that + /// waited for none; returned first to last. + /// </summary> + public static IReadOnlyList<TraceSpan> CriticalPath(IReadOnlyList<TraceSpan> spans) + { + ArgumentNullException.ThrowIfNull(spans); + if (spans.Count == 0) + { + return []; + } + + var byId = spans.ToDictionary(span => span.Id); + var path = new List<TraceSpan>(); + var current = spans.MaxBy(span => span.End)!; + var seen = new HashSet<int>(); + while (seen.Add(current.Id)) + { + path.Add(current); + var before = current.After.Where(byId.ContainsKey).Select(id => byId[id]).MaxBy(span => span.End); + if (before is null) + { + break; + } + + current = before; + } + + path.Reverse(); + return path; + } +} + +internal sealed record TraceArgs(int Id, string? Target, bool Ok, IReadOnlyList<int>? After); + +internal sealed record TraceEvent(string Name, string Cat, string Ph, long Ts, long Dur, int Pid, int Tid, TraceArgs? Args); + +internal sealed record TraceDocument(IReadOnlyList<TraceEvent> TraceEvents, string DisplayTimeUnit); + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] +[JsonSerializable(typeof(TraceDocument))] +internal sealed partial class BuildTraceJson : JsonSerializerContext +{ +} diff --git a/src/Progmasoft.Tazel/Driver/Executor.cs b/src/Progmasoft.Tazel/Driver/Executor.cs index a8f5495..8907851 100644 --- a/src/Progmasoft.Tazel/Driver/Executor.cs +++ b/src/Progmasoft.Tazel/Driver/Executor.cs @@ -18,7 +18,7 @@ namespace Progmasoft.Tazel.Driver; /// </summary> internal sealed class Executor( int jobs, bool keepGoing, ActionCache cache, Reporter reporter, Cache.RemoteActions? remote = null, - CachePolicy policy = CachePolicy.Normal, string? scratch = null, RebuildReasonLog? reasons = null) + CachePolicy policy = CachePolicy.Normal, string? scratch = null, RebuildReasonLog? reasons = null, BuildTimeline? timeline = null) { private readonly System.Collections.Concurrent.ConcurrentDictionary<BuildAction, bool> _made = new(); private int _done; @@ -108,6 +108,22 @@ internal sealed class Executor( } reasons?.Add(why); + var started = timeline?.Now ?? 0; + var ok = false; + try + { + ok = await RunStaleAsync(action, total, stop, forced).ConfigureAwait(false); + return ok; + } + finally + { + timeline?.Add(action, started, ok); + } + } + + /// <summary>Runs <paramref name="action"/>, found not current, or takes its outputs from the remote cache.</summary> + private async Task<bool> RunStaleAsync(BuildAction action, int total, CancellationTokenSource stop, bool forced) + { foreach (var output in action.Outputs) { var full = action.Full(output); diff --git a/tests/Progmasoft.Tazel.Tests/BuildTraceTests.cs b/tests/Progmasoft.Tazel.Tests/BuildTraceTests.cs new file mode 100644 index 0000000..f2cf6ae --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/BuildTraceTests.cs @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Output; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>The timeline every build keeps, and the critical path <c>tazel trace</c> finds in it.</summary> +public sealed class BuildTraceTests +{ + private static BuildAction Sleep(string root, string name, string seconds, params BuildAction[] after) + { + var action = new BuildAction + { + Description = $"Running //:{name}", + Target = $"//:{name}", + Command = ["sh", "-c", $"sleep {seconds} && echo {name} > {name}.out"], + Directory = root, + Inputs = [], + Outputs = [$"{name}.out"], + }; + action.Prerequisites.AddRange(after); + return action; + } + + [Fact] + public async Task TheTimelineFollowsTheSlowBranchAndKeepsParallelActionsOnSeparateLanes() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the commands are sh"); + using var module = new TemporaryModule(); + // slow and quick run side by side; last waits for both, so the path is slow -> last. + var slow = Sleep(module.Root, "slow", "0.4"); + var quick = Sleep(module.Root, "quick", "0.05"); + var last = Sleep(module.Root, "last", "0.05", slow, quick); + var timeline = new BuildTimeline(); + using var reporter = new Reporter(MessageFormat.Jsonl, new StringWriter(), When.Never, true, When.Never); + var executor = new Executor(2, false, new ActionCache(new Digests()), reporter, null, CachePolicy.Normal, null, null, timeline); + Assert.True(await executor.RunAsync([last], TestContext.Current.CancellationToken)); + + var spans = timeline.Spans(); + Assert.Equal(3, spans.Count); + var bySlow = spans.Single(span => span.Target == "//:slow"); + var byQuick = spans.Single(span => span.Target == "//:quick"); + var byLast = spans.Single(span => span.Target == "//:last"); + Assert.NotEqual(bySlow.Lane, byQuick.Lane); + Assert.Equal([bySlow.Id, byQuick.Id], byLast.After.Order()); + Assert.True(byLast.Start >= bySlow.End); + + var path = BuildTrace.CriticalPath(spans); + Assert.Equal(["//:slow", "//:last"], path.Select(span => span.Target)); + } + + [Fact] + public async Task ACurrentActionPassesOnWhatItWaitedFor() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the commands are sh"); + using var module = new TemporaryModule(); + // first -> middle -> last; once built, middle alone is kept current while first and last rerun. + BuildAction First() => Sleep(module.Root, "first", "0"); + var timeline = new BuildTimeline(); + using var reporter = new Reporter(MessageFormat.Jsonl, new StringWriter(), When.Never, true, When.Never); + var cache = new ActionCache(new Digests()); + var first = First(); + var middle = Sleep(module.Root, "middle", "0", first); + var last = Sleep(module.Root, "last", "0", middle); + Assert.True(await new Executor(1, false, cache, reporter).RunAsync([last], TestContext.Current.CancellationToken)); + + File.Delete(Path.Combine(module.Root, "first.out")); + File.Delete(Path.Combine(module.Root, "last.out")); + var executor = new Executor(1, false, new ActionCache(new Digests()), reporter, null, CachePolicy.Normal, null, null, timeline); + Assert.True(await executor.RunAsync([last], TestContext.Current.CancellationToken)); + + var spans = timeline.Spans(); + Assert.Equal(["//:first", "//:last"], spans.Select(span => span.Target)); + Assert.Equal([spans[0].Id], spans[1].After); + } + + [Fact] + public void TheTraceFileIsChromeTraceEventsAndReadsBack() + { + using var module = new TemporaryModule(); + var state = Path.Combine(module.Root, ".tazel"); + Assert.Null(BuildTrace.Read(state)); + TraceSpan[] spans = + [ + new(1, "Compiling //:a a.c", "//:a", 0, 1500, true, 0, []), + new(2, "Linking //:a", "//:a", 1500, 2000, false, 0, [1]), + ]; + BuildTrace.Write(state, spans); + + using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(state, BuildTrace.RelativePath))); + var events = document.RootElement.GetProperty("traceEvents"); + Assert.Equal(2, events.GetArrayLength()); + var link = events[1]; + Assert.Equal("X", link.GetProperty("ph").GetString()); + Assert.Equal(1500, link.GetProperty("ts").GetInt64()); + Assert.Equal(500, link.GetProperty("dur").GetInt64()); + Assert.Equal(1, link.GetProperty("tid").GetInt32()); + + var read = BuildTrace.Read(state)!; + Assert.Equal(spans, read, (x, y) => x.Id == y.Id && x.Start == y.Start && x.End == y.End && x.Ok == y.Ok && + x.Lane == y.Lane && x.After.SequenceEqual(y.After) && x.Description == y.Description); + Assert.Equal([1, 2], BuildTrace.CriticalPath(read).Select(span => span.Id)); + } + + [Fact] + public void TheCriticalPathOfNothingIsEmptyAndACycleEnds() + { + Assert.Empty(BuildTrace.CriticalPath([])); + TraceSpan[] looped = [new(1, "a", null, 0, 10, true, 0, [2]), new(2, "b", null, 0, 5, true, 1, [1])]; + Assert.Equal([2, 1], BuildTrace.CriticalPath(looped).Select(span => span.Id)); + } + + [Fact] + public void TraceTakesOnlyItsOutputOption() + { + var command = Assert.IsType<TraceCommand>(CommandLine.Parse(["trace", "--output", "build.json"])); + Assert.Equal("build.json", command.OutputFile); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["trace", "now"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["build", "--output", "x.json"])); + } + + [Fact] + public async Task TazelTracePrintsThePathAndExportsTheTimeline() + { + Assert.SkipWhen(Host.Which("cc") is null && Host.Which("gcc") is null && Host.Which("clang") is null, "no C compiler"); + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + CC.StaticLibrary("math", new() { Sources = ["math.c"], Headers = ["math.h"] }); + CC.Executable("app", new() { Sources = ["main.c"], Depends = ["//:math"] }); + """) + .Write("math.h", "int add(int a, int b);\n") + .Write("math.c", "#include \"math.h\"\nint add(int a, int b) { return a + b; }\n") + .Write("main.c", "#include \"math.h\"\nint main(void) { return add(1, 1) - 2; }\n"); + + var (status, output) = await module.TazelAsync(".", ["--color", "never", "trace"]); + Assert.Equal(0, status); + Assert.Contains("no build has been traced", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", ["--color", "never", "build", "//:app"]); + Assert.True(status == 0, output); + (status, output) = await module.TazelAsync(".", ["--color", "never", "trace", "--output", "out/trace.json"]); + Assert.Equal(0, status); + Assert.Contains("Linking //:app", output, StringComparison.Ordinal); + Assert.Contains("critical path:", output, StringComparison.Ordinal); + using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(module.Root, "out", "trace.json"))); + Assert.True(document.RootElement.GetProperty("traceEvents").GetArrayLength() >= 3); + + (status, output) = await module.TazelAsync(".", ["--color", "never", "build", "//:app"]); + Assert.True(status == 0, output); + (status, output) = await module.TazelAsync(".", ["--color", "never", "trace"]); + Assert.Contains("ran no actions", output, StringComparison.Ordinal); + } +}