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): hold an OS lock on a module while a command writes .tazel/
- Commit
4d8196e694ecd6b0a7652f1bbe0f3e8091bf72f1- Author
- Leitwolf11 ·
- Parents
0eba574719cd
Changes
CHANGELOG.md | 3 + docs/commands.md | 13 ++- src/Progmasoft.Tazel/Cli/Commands.cs | 53 +++++++++++-- src/Progmasoft.Tazel/Cli/Help.cs | 4 +- src/Progmasoft.Tazel/Project/StateLock.cs | 105 +++++++++++++++++++++++++ tests/Progmasoft.Tazel.Tests/StateLockTests.cs | 90 +++++++++++++++++++++ 6 files changed, 259 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23ef369..4c370a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,9 @@ - `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. +- Commands that write `.tazel/` (`build`, `test`, `coverage`, `run` until the program starts, `clean`, `fetch`, `vendor`, + `package`, `cache repair`) hold an OS lock on the module, `$TAZEL_HOME/Locks/state-<key>.lock`; a second one says + which process holds it and waits, and Ctrl+C stops the wait. The system releases the lock when a process ends. ## 0.5.0 - 2026-12-03 diff --git a/docs/commands.md b/docs/commands.md index 872263f..5743088 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -109,7 +109,18 @@ input that changed: that is how builds find what to run, not a fault. A broken o kept beside is gone or changed while every input is as recorded, which means something touched the file behind Tazel's back. A test result without its log and a compiled project file whose metadata does not read are broken too; each is an `error[E0508]`, and the command exits 1. `tazel cache repair` removes what is broken and the files writes -left half done, and the next build redoes them; it keeps stale records and outputs. Run it when no build runs. +left half done, and the next build redoes them; it keeps stale records and outputs. It takes the module's state lock, +so it waits for a build that is running. + +### The state lock + +Commands that write a module's `.tazel/` hold an OS lock on it: `build`, `test`, `coverage`, `run` (until the program +starts), `clean` (not `--dry-run`), `fetch`, `vendor`, `package` and `cache repair`. A second one on the same module +says which process holds the lock (`another tazel (pid 4242, tazel build, since ...) is writing .../.tazel; waiting for +it to finish`) and waits; Ctrl+C stops the wait. The lock is `$TAZEL_HOME/Locks/state-<key>.lock`, where `<key>` is the +first 16 hexadecimal digits of the SHA-256 of the module root's canonical path. It is an OS lock (`flock` on Unix, a +share mode on Windows), released by the system when the process ends, so a crashed Tazel never leaves it held. Reading +commands (`query`, `log`, `trace`, `cache validate`, `trash list`) take no lock. With `--remote` both read `MODULE.csx`. `validate` asks the remote cache for a key no action has: a 404 means it is reached and lets this machine in, an error or no answer exits 1. A `SigningKey` with a `PublicKey` must sign what the diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 600e43d..2c7558b 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -40,11 +40,11 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector CoverageCommand coverage => ThenCollectTrash(BuildAsync(coverage.Labels, coverage.Flags, BuildKind.Coverage, null, cancel)), RunCommand run => ThenCollectTrash(BuildAsync(run.Label is null ? [] : [run.Label], run.Flags, BuildKind.Run, run.Arguments, cancel)), QueryCommand query => QueryAsync(query), - FetchCommand fetch => ThenCollectTrash(FetchAsync(fetch)), + FetchCommand fetch => ThenCollectTrash(WithStateLockAsync("fetch", () => FetchAsync(fetch), cancel)), ModulesCommand modules => new ModulesCommands(reporter, workingDirectory, TazelVersion).RunAsync(modules, cancel), UpdateCommand update => new ModulesCommands(reporter, workingDirectory, TazelVersion).UpdateAsync(update, cancel), - VendorCommand => ThenCollectTrash(VendorAsync(cancel)), - PackageCommand package => PackageAsync(package), + VendorCommand => ThenCollectTrash(WithStateLockAsync("vendor", () => VendorAsync(cancel), cancel)), + PackageCommand package => WithStateLockAsync("package", () => PackageAsync(package), cancel), GitAddCommand => new GitCommands(reporter, workingDirectory).AddAsync(TazelVersion), NewCommand create => Task.FromResult(new NewInitCommands(reporter, workingDirectory).New(create.Name, create.Force)), InitCommand init => Task.FromResult(new NewInitCommands(reporter, workingDirectory).Init(init.Force)), @@ -56,7 +56,9 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector IdeCompdbCommand compdb => new IdeCommands(reporter, workingDirectory, TazelVersion).CompdbAsync(compdb), DaemonCommand daemon => DaemonAsync(daemon, cancel), CustomCommandLine custom => CustomAsync(custom, cancel), - CacheCheckCommand check => CacheCheckAsync(check, cancel), + CacheCheckCommand check => check.Repair + ? WithStateLockAsync("cache repair", () => CacheCheckAsync(check, cancel), cancel) + : CacheCheckAsync(check, cancel), ToolLaunchCommand tool => Task.FromResult(LaunchTool(tool)), IgnoreCommand ignore => Task.FromResult(new IgnoreCommands(reporter, workingDirectory).Run(ignore)), ToolWrapperCommand wrapper => Task.FromResult(CreateWrapper(wrapper)), @@ -97,7 +99,10 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector case DotnetWhatIsCommand whatIs: return WhatIs(whatIs.Term); case CleanCommand clean: - return Clean(clean.Expunge, clean.DryRun); + { + using var held = clean.DryRun ? null : LockState("clean", CancellationToken.None); + return Clean(clean.Expunge, clean.DryRun); + } case CacheKeygenCommand keygen: { var (publicKey, signingKey) = Cache.CacheKey.Generate(keygen.Algorithm); @@ -488,6 +493,35 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector CancellationToken cancel) { RefuseWithoutSandbox(); + var held = LockState(kind.ToString().ToLowerInvariant(), cancel); + try + { + return await LockedBuildAsync(labels, flags, kind, programArguments, () => { held?.Dispose(); held = null; }, cancel) + .ConfigureAwait(false); + } + finally + { + held?.Dispose(); + } + } + + /// <summary> + /// The module's state lock, held while a command writes <c>.tazel/</c>; null outside a module, where the command + /// fails on its own. + /// </summary> + private Project.StateLock? LockState(string command, CancellationToken cancel) => + ModuleFiles.RootOf(workingDirectory) is { } root ? Project.StateLock.Acquire(root, command, reporter.Status, cancel) : null; + + private async Task<int> WithStateLockAsync(string command, Func<Task<int>> work, CancellationToken cancel) + { + using var held = LockState(command, cancel); + return await work().ConfigureAwait(false); + } + + private async Task<int> LockedBuildAsync( + IReadOnlyList<string> labels, BuildFlags flags, BuildKind kind, IReadOnlyList<string>? programArguments, + Action release, CancellationToken cancel) + { if (flags.Locked || flags.Frozen) { var lockErrors = await ModulesCommands.CheckLockedAsync(workingDirectory, TazelVersion).ConfigureAwait(false); @@ -515,7 +549,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return kind switch { BuildKind.Test or BuildKind.Coverage => await FinishTestsAsync(built, kind, cancel).ConfigureAwait(false), - BuildKind.Run => built.Succeeded ? RunProgram(built, programArguments) : 1, + // The program is the user's, not a writer of .tazel/: another command may build while it runs. + BuildKind.Run => built.Succeeded ? RunAfter(release, built, programArguments) : 1, _ => FinishBuild(built, selected.Count), }; } @@ -649,6 +684,12 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return passed && reported ? 0 : 1; } + private static int RunAfter(Action release, Built built, IReadOnlyList<string>? programArguments) + { + release(); + return RunProgram(built, programArguments); + } + private static int RunProgram(Built built, IReadOnlyList<string>? programArguments) { var (target, products) = built.Planned[0]; diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 7dabf43..f77e18d 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -226,8 +226,8 @@ internal static class Help read. With --remote it reads MODULE.csx, asks the remote cache for a key no action has, and checks that the SigningKey signs what the PublicKey verifies. repair removes what is broken and what writes left half done, never a stale record or an output; with --remote, and a cache that takes writes, it stores again the results - of this machine's valid records, for its platform in debug, that the cache lacks or holds unsigned. Run - repair when no build runs. + of this machine's valid records, for its platform in debug, that the cache lacks or holds unsigned. repair + takes the module's state lock, so it waits for a build that is running. Prints a PublicKey and a SigningKey for Remote.From in MODULE.csx, each written as its algorithm and the key diff --git a/src/Progmasoft.Tazel/Project/StateLock.cs b/src/Progmasoft.Tazel/Project/StateLock.cs new file mode 100644 index 0000000..70c259b --- /dev/null +++ b/src/Progmasoft.Tazel/Project/StateLock.cs @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Globalization; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Progmasoft.Tazel.Dsl.Configuration; + +namespace Progmasoft.Tazel.Project; + +/// <summary> +/// The OS lock a command holds while it writes a module's <c>.tazel/</c>: builds, tests, runs (until the program +/// starts), <c>clean</c>, <c>fetch</c>, <c>vendor</c>, <c>package</c> and <c>cache repair</c>. A second such command on +/// the same module waits for the first, as Bazel's "Another command is running" does, instead of writing beside it. +/// </summary> +/// <remarks> +/// The lock is <c>$TAZEL_HOME/Locks/state-<key>.lock</c>, opened with no sharing: an OS lock (<c>flock</c> on +/// Unix, a share mode on Windows) that the system releases when the process ends, however it ends, so a crashed Tazel +/// never leaves a stale lock. It lives outside <c>.tazel/</c> so that <c>clean --expunge</c> can move <c>.tazel/</c> +/// while holding it. Beside it, <c>.info</c> says which process holds it, for the one that waits. +/// </remarks> +public sealed class StateLock : IDisposable +{ + private readonly FileStream _held; + private readonly string _info; + + private StateLock(FileStream held, string info) + { + _held = held; + _info = info; + } + + /// <summary>How long a waiting command sleeps between tries.</summary> + public static TimeSpan Poll { get; } = TimeSpan.FromMilliseconds(100); + + /// <summary> + /// Takes the lock of the module rooted at <paramref name="moduleRoot"/> for <paramref name="command"/>; while another + /// process holds it, says once through <paramref name="status"/> who holds it, and waits until it is free or + /// <paramref name="cancel"/> asks to stop. + /// </summary> + public static StateLock Acquire(string moduleRoot, string command, Action<string> status, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(moduleRoot); + ArgumentNullException.ThrowIfNull(status); + var locks = Path.Combine(TazelHome.Directory(), "Locks"); + Directory.CreateDirectory(locks); + var canonical = ConfigurationResolver.Canonical(moduleRoot); + var key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(canonical)))[..16]; + var path = Path.Combine(locks, $"state-{key}.lock"); + var info = Path.Combine(locks, $"state-{key}.info"); + var told = false; + while (true) + { + cancel.ThrowIfCancellationRequested(); + try + { + var held = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + File.WriteAllText(info, string.Create(CultureInfo.InvariantCulture, + $"pid {Environment.ProcessId}, tazel {command}, since {DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss} UTC\n")); + return new StateLock(held, info); + } + catch (IOException) when (!cancel.IsCancellationRequested) + { + if (!told) + { + told = true; + status($"another tazel ({Holder(info)}) is writing {Path.Combine(canonical, ModuleFiles.StateDirectory)}; " + + "waiting for it to finish"); + } + + cancel.WaitHandle.WaitOne(Poll); + } + } + } + + /// <summary>Releases the lock.</summary> + public void Dispose() + { + try + { + File.Delete(_info); + } + catch (IOException) + { + // Only the note of who held it; the lock itself is released below. + } + + _held.Dispose(); + } + + private static string Holder(string info) + { + try + { + return File.Exists(info) ? File.ReadAllText(info).Trim() : "it did not say which"; + } + catch (IOException) + { + return "it did not say which"; + } + } +} diff --git a/tests/Progmasoft.Tazel.Tests/StateLockTests.cs b/tests/Progmasoft.Tazel.Tests/StateLockTests.cs new file mode 100644 index 0000000..f5781d4 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/StateLockTests.cs @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl.Configuration; +using Progmasoft.Tazel.Project; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>The OS lock on a module's .tazel/; the tests set TAZEL_HOME, so one at a time.</summary> +[Collection(nameof(TazelHomeCollection))] +public sealed class StateLockTests : IDisposable +{ + private readonly string _was = Environment.GetEnvironmentVariable(TazelHome.Variable) ?? ""; + private readonly string _home = Path.Combine(Path.GetTempPath(), "tazel-lock-home-" + Guid.NewGuid().ToString("N")); + private readonly TemporaryModule _module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile); + + public StateLockTests() + { + Directory.CreateDirectory(_home); + Environment.SetEnvironmentVariable(TazelHome.Variable, _home); + } + + public void Dispose() + { + Environment.SetEnvironmentVariable(TazelHome.Variable, _was.Length == 0 ? null : _was); + _module.Dispose(); + Directory.Delete(_home, recursive: true); + } + + [Fact] + public async Task ASecondCommandSaysWhoHoldsTheLockAndWaitsForIt() + { + var said = new ConcurrentQueue<string>(); + var first = StateLock.Acquire(_module.Root, "build", _ => { }, TestContext.Current.CancellationToken); + var second = Task.Run(() => StateLock.Acquire(_module.Root, "test", said.Enqueue, TestContext.Current.CancellationToken), + TestContext.Current.CancellationToken); + + await Task.Delay(StateLock.Poll * 5, TestContext.Current.CancellationToken); + Assert.False(second.IsCompleted); + var message = Assert.Single(said); + Assert.Contains($"pid {Environment.ProcessId}, tazel build", message, StringComparison.Ordinal); + Assert.Contains("waiting for it to finish", message, StringComparison.Ordinal); + + first.Dispose(); + using var acquired = await second.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + Assert.Single(said); + } + + [Fact] + public void WaitingStopsWhenTheCommandIsCanceled() + { + using var first = StateLock.Acquire(_module.Root, "build", _ => { }, TestContext.Current.CancellationToken); + using var stop = new CancellationTokenSource(StateLock.Poll * 3); + Assert.ThrowsAny<OperationCanceledException>(() => StateLock.Acquire(_module.Root, "build", _ => { }, stop.Token)); + } + + [Fact] + public void OtherModulesDoNotWaitAndTheLockIsFreeAgainAfterRelease() + { + using var other = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile); + using (StateLock.Acquire(_module.Root, "build", _ => { }, TestContext.Current.CancellationToken)) + { + using var elsewhere = StateLock.Acquire(other.Root, "build", _ => throw new InvalidOperationException("waited"), + TestContext.Current.CancellationToken); + } + + using var again = StateLock.Acquire(_module.Root, "clean", _ => throw new InvalidOperationException("waited"), + TestContext.Current.CancellationToken); + Assert.Single(Directory.GetFiles(Path.Combine(_home, "Locks"), "state-*.info")); + } + + [Fact] + public async Task CleanExpungeMovesTheCacheWhileHoldingTheLock() + { + Directory.CreateDirectory(Path.Combine(_module.Root, ".tazel", "out")); + File.WriteAllText(Path.Combine(_module.Root, ".tazel", "out", "a.o"), "x"); + using var output = new StringWriter(); + var status = await Program.RunAsync(["--color", "never", "clean", "--expunge"], _module.Root, output, + TestContext.Current.CancellationToken); + Assert.True(status == 0, output.ToString()); + Assert.False(Directory.Exists(Path.Combine(_module.Root, ".tazel"))); + Assert.Empty(Directory.GetFiles(Path.Combine(_home, "Locks"), "state-*.info")); + } +}