Skip to content

Enhanced ninja-recompact workaround: snapshot+restore + broken-marker (follow-up to #2860) #2873

Closed

Description

@zackees

Background

PR #2860 (closes #2857) defused the recompact crash cascade by renaming .ninja_deps to .ninja_deps.bak before invoking ninja -t recompact, and touching the marker on failure so the maintenance step doesn't re-run every invocation. Root cause is upstream: ninja-build/ninja#2787 (heap-OOB read in DepsLog::Recompact() when Load() recovers from a corrupted log).

That PR is correct as a stop-gap, but it has a subtle downside that's worth fixing in a follow-up: the rename throws away ninja's accumulated header→TU dependency information once per 24 h, so the first build after each maintenance pass can produce an incorrect incremental rebuild (a header change won't trigger a recompile of any TU that wasn't otherwise dirty, because the deps log no longer knows that TU depends on that header). Self-heals on subsequent builds as .d files repopulate .ninja_deps, but it's a real correctness gap for one build window per day.

Compare to the pre-fix behavior, which is worth being honest about: recompact crashed mid-iteration, but it had already called Close() on the original log and was writing to .ninja_deps.recompact (a temp). The original .ninja_deps survived intact, and Load() "recovered" the truncated tail on the next ninja invocation. The pre-fix damage was visible (12 s of noise + 150 minidumps + phantom test failures), not silent (lost deps).

This issue proposes an enhanced workaround that suppresses the noise and keeps the deps log intact.

Proposed design

Three markers in build_dir:

Marker Purpose
.ninja_deps_maintenance 24 h cooldown timestamp (existing)
.ninja_deps_recompact_broken sentinel: once set, recompact is skipped on this build dir forever
.ninja_deps.bak snapshot of the original deps log; restored if recompact fails

Algorithm in perform_ninja_maintenance(build_dir):

  1. If .ninja_deps_recompact_broken exists -> return immediately. Recompact has been observed to fail on this host; it is an optimisation, not a correctness requirement, so we simply skip it.
  2. If .ninja_deps_maintenance was touched < 24 h ago -> return (existing cooldown).
  3. Snapshot: shutil.copy2(.ninja_deps, .ninja_deps.bak) if the deps log exists. This is the only behavioural difference vs PR fix(ci): defuse recompact crash cascade on Windows (#2857) #2860's "rename"; the original stays in place so recompact actually operates on it.
  4. Run ninja -t recompact (existing).
  5. Touch .ninja_deps_maintenance regardless of outcome (existing).
  6. On returncode == 0: delete .ninja_deps.bak, log success.
  7. On non-zero / exception:
    • Restore .ninja_deps.bak -> .ninja_deps (preserves all the deps records the corrupt-tail recovery saved).
    • Touch .ninja_deps_recompact_broken.
    • Log: Maintenance completed with warnings (non-fatal); disabling future recompact attempts on this build dir.

Behaviour comparison

Scenario Pre-fix PR #2860 Enhanced
Healthy host, healthy log recompact runs, optimises log, deps preserved rename costs deps records once/24h, recompact starts fresh and writes empty log recompact runs, optimises log, deps preserved (no behaviour change)
Windows host, corrupt log, 1st run 12 s crash, 150 minidumps, deps survive 0 s, no noise, deps lost 12 s crash, 150 minidumps, deps survive (restored from .bak), broken marker set
Windows host, corrupt log, 2nd+ run same 12 s cascade, every run 0 s, deps lost again at next 24h tick 0 s, broken marker -> skip entirely, deps untouched
Loss of incremental dep correctness never once per 24 h never (after first run)

Trade-off: one visible cascade per build dir lifetime (vs. once per 24 h or every run pre-fix). Acceptable cost given that current FastLED-on-Windows users have already seen many cascades, and we get zero data loss and zero recurrence.

Concrete diff sketch

def perform_ninja_maintenance(build_dir: Path) -> bool:
    marker_file = build_dir / ".ninja_deps_maintenance"
    broken_marker = build_dir / ".ninja_deps_recompact_broken"

    if broken_marker.exists():
        return True

    if marker_file.exists():
        try:
            if (time.time() - marker_file.stat().st_mtime) / 3600 < 24:
                return True
        except (OSError, IOError):
            pass

    deps_file = build_dir / ".ninja_deps"
    deps_bak = build_dir / ".ninja_deps.bak"
    snapshot_taken = False
    if deps_file.exists():
        try:
            if deps_bak.exists():
                deps_bak.unlink()
            shutil.copy2(str(deps_file), str(deps_bak))
            snapshot_taken = True
        except OSError:
            pass

    _ts_print("[MESON] Performing periodic Ninja dependency database maintenance...")

    returncode = -1
    try:
        repair_proc = RunningProcess(
            ["ninja", "-C", str(build_dir), "-t", "recompact"],
            timeout=60, auto_run=True, check=False,
            env=os.environ.copy(),
            output_formatter=TimestampFormatter(),
        )
        returncode = repair_proc.wait(echo=True)
    except KeyboardInterrupt as ki:
        handle_keyboard_interrupt(ki); raise
    except Exception as e:
        _ts_print(f"[MESON] Maintenance failed with exception: {e} (non-fatal)",
                  file=sys.stderr)

    try:
        marker_file.touch()
    except (OSError, IOError):
        pass

    if returncode == 0:
        if snapshot_taken:
            try: deps_bak.unlink()
            except OSError: pass
        _ts_print("[MESON] Dependency database maintenance completed successfully")
        return True

    # Restore the snapshot so subsequent builds keep their deps info.
    if snapshot_taken:
        try:
            if deps_file.exists():
                deps_file.unlink()
            deps_bak.rename(deps_file)
        except OSError:
            pass

    try:
        broken_marker.touch()
    except (OSError, IOError):
        pass

    _ts_print(
        "[MESON] Maintenance completed with warnings (non-fatal); "
        "disabling future recompact on this build dir.",
        file=sys.stderr,
    )
    return True

Tests to add / extend

Augment ci/tests/test_ninja_maintenance.py (added in PR #2860):

  • test_snapshot_restored_on_failure — write a deps log with known bytes; mock recompact to fail; assert .ninja_deps contents are identical to pre-call bytes.
  • test_broken_marker_skips_future_runs — set .ninja_deps_recompact_broken; assert RunningProcess is never called and the function returns True.
  • test_broken_marker_set_on_failure — mock recompact to fail once; assert .ninja_deps_recompact_broken is then present.
  • test_snapshot_discarded_on_success — mock recompact returns 0; assert .ninja_deps.bak does not remain on disk.
  • Keep the 24 h cooldown short-circuit test from PR fix(ci): defuse recompact crash cascade on Windows (#2857) #2860.

Out of scope

  • Periodic cleanup of accumulated ninja_crash_dump_*.dmp files. With the broken-marker short-circuit in place, the source is gated to one cascade per build dir lifetime, so disk bleed becomes a non-issue. If we want belt-and-suspenders, a separate housekeeping pass can prune build_dir/*.dmp older than 1 h — file as a follow-up if it's still noticeable in practice.
  • Sniffing .ninja_deps for the "valid header + partial trailing record" signature to preemptively skip recompact even on the first run. Possible but invasive — requires understanding ninja's on-disk format. Not worth it given the broken-marker approach already caps damage to one occurrence.

Acceptance

  • bash test --cpp on Windows hits the cascade at most once per build dir, then never again.
  • The .ninja_deps deps log is byte-identical before and after a failed-recompact run.
  • Subsequent bash test --cpp runs on the same build dir do not invoke ninja -t recompact.
  • Healthy hosts (Linux/Mac/Windows w/ uncorrupted log) see no behaviour change vs the pre-fix(ci): defuse recompact crash cascade on Windows (#2857) #2860 code path beyond the 24 h cooldown marker being touched on failure.

Refs:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions