Skip to content
Merged
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
23 changes: 17 additions & 6 deletions .github/actions/wf-driver/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,24 @@ runs:
- name: Install GCC 16 and WebKitGTK
shell: bash
run: |
# The hosted runner's Azure mirror can trickle large GCC packages until the job times out.
# Keep Ubuntu's suites and package verification, using its primary archive instead.
if [ -f /etc/apt/apt-mirrors.txt ]; then
sudo sed -i 's|azure\.archive\.ubuntu\.com|archive.ubuntu.com|g' /etc/apt/apt-mirrors.txt
# The hosted runner's Azure mirror can trickle large GCC packages until the job times out, and so can Ubuntu's
# primary archive. Keep Ubuntu's suites and package verification, start with the primary archive, bound the
# attempt and fall back to the runner's own mirror. Both attempts and the repair between them take at most
# 11 minutes, inside the 15 minutes of the shortest job that uses this action; an install takes under a minute.
mirrors=/etc/apt/apt-mirrors.txt
install() {
sudo timeout 60 apt-get update && sudo timeout 240 apt-get install -y --no-install-recommends -o Acquire::Retries=3 -o Acquire::http::Timeout=15 gcc-16 g++-16 libwebkitgtk-6.0-dev
}
if [ -f "$mirrors" ]; then
sudo cp "$mirrors" "$mirrors.hosted"
sudo sed -i 's|azure\.archive\.ubuntu\.com|archive.ubuntu.com|g' "$mirrors"
fi
if ! install; then
echo "::warning::The primary Ubuntu archive did not deliver the packages in time; using the runner's mirror"
if [ -f "$mirrors.hosted" ]; then sudo cp "$mirrors.hosted" "$mirrors"; fi
sudo timeout 60 dpkg --configure -a || echo "::warning::The interrupted installation could not be repaired in time"
install
fi
sudo apt-get update
sudo apt-get install -y --no-install-recommends -o Acquire::Retries=3 gcc-16 g++-16 libwebkitgtk-6.0-dev
echo "CC=gcc-16" >> "$GITHUB_ENV"
echo "CXX=g++-16" >> "$GITHUB_ENV"
- name: Build webfront-wf
Expand Down
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ these entries stays in the GitHub releases and the Git history.

### Fixed

- On Windows, `wf install`, `wf build` and `wf test` no longer fail with `rename: Access is denied` while another process, such as an antivirus scan, still reads the files just written: the developer store tries the rename again for up to 635 ms; `wf test` also empties the directory of an interrupted run (#542).
- Run the commit attribution regression checks with older Git versions by dropping the unsupported `git log --no-graph` option (#525).

- Build with `-DWEBFRONT_EMBED_CEF=ON` on Linux aarch64 instead of failing on `-m64`, and cross-compile CEF: WebFront pins CEF 156.0.28, whose package selects the archive and `PROJECT_ARCH` from the target (#523).
Expand Down
26 changes: 24 additions & 2 deletions include/webfront/system/DeveloperFiles.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include <stdexcept>
#include <string>
#include <system_error>
#include <thread>
#include <utility>

namespace webfront::developer {
Expand Down Expand Up @@ -59,6 +60,27 @@ inline std::pair<std::string, std::filesystem::path> createStaging(const std::fi
}
}

// Windows refuses to rename a file, or a directory that holds one, while another process has it open without sharing its
// deletion: an antivirus or an indexer reading what was just written. The refusal ends with that read, so the rename is
// tried again for a bounded time (635 ms) before it is reported. Elsewhere an open file never prevents a rename.
inline void renameSettled(const std::filesystem::path& from, const std::filesystem::path& to) {
#ifdef _WIN32
constexpr int accessDenied = 5, sharingViolation = 32;
for (std::chrono::milliseconds delay{5};; delay *= 2) {
std::error_code error;
std::filesystem::rename(from, to, error);
if (!error)
return;
const bool transient = error.category() == std::system_category() && (error.value() == accessDenied || error.value() == sharingViolation);
if (!transient || delay > std::chrono::milliseconds{320})
throw std::filesystem::filesystem_error("rename", from, to, error);
std::this_thread::sleep_for(delay);
}
#else
std::filesystem::rename(from, to);
#endif
}

// Moves the staged files over the target, restoring the previous content if that fails.
inline void replaceTarget(const std::filesystem::path& target, bool replace, const std::filesystem::path& source, const std::filesystem::path& backup) {
std::filesystem::create_directories(target.parent_path());
Expand All @@ -68,9 +90,9 @@ inline void replaceTarget(const std::filesystem::path& target, bool replace, con
if (exists && !replace)
throw std::runtime_error("Starter destination already exists");
if (exists)
std::filesystem::rename(target, backup);
renameSettled(target, backup);
try {
std::filesystem::rename(source, target);
renameSettled(source, target);
} catch (...) {
if (exists)
std::filesystem::rename(backup, target);
Expand Down
3 changes: 2 additions & 1 deletion include/webfront/system/DeveloperJournal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#pragma once

#include "WindowsCompat.hpp"
#include "DeveloperFiles.hpp"
#include "DeveloperPaths.hpp"

#include <algorithm>
Expand Down Expand Up @@ -224,7 +225,7 @@ inline void rollForward(const std::filesystem::path& root, const std::filesystem
const auto destination = projectPath(root, target);
if (std::filesystem::is_regular_file(staged)) {
createDirectoriesDurably(root, destination.parent_path());
std::filesystem::rename(staged, destination);
renameSettled(staged, destination);
}
directories.insert(destination.parent_path());
if (hook)
Expand Down
4 changes: 2 additions & 2 deletions include/webfront/system/DeveloperStore.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ class Store {
try {
for (std::size_t i = 0; i < group.size(); ++i) {
const auto owned = directory / (number + ".d") / std::to_string(i);
std::filesystem::rename(stagedSource(*group[i]), owned);
renameSettled(stagedSource(*group[i]), owned);
syncFile(owned);
}
syncDirectory(directory / (number + ".d"));
Expand Down Expand Up @@ -326,7 +326,7 @@ class Store {
throw std::runtime_error("Cannot write the publication journal");
}
syncFile(temporary);
std::filesystem::rename(temporary, directory / (number + ".journal"));
renameSettled(temporary, directory / (number + ".journal"));
syncDirectory(directory);
step("after-journal");
}
Expand Down
2 changes: 1 addition & 1 deletion js/developer/environment/bundles.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad",
"js/developer/environment/starter.mjs": "89ccab43be4455ed9598c54355b4bbe5adea1afd7a0ae5d755a14317e3ca39df",
"js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3",
"js/developer/environment/runtime.mjs": "5ce088084c84874e143e7e3f5e4d55d7151064f01c0137071343880dfa4acd4d",
"js/developer/environment/runtime.mjs": "2c9ef449c44ddbdcc327ffb126e61c3e8e8076edbe73a0dce99e3dc9bb42b5a9",
"js/developer/environment/automation.mjs": "79405c89ba7025c1774bc13c9b78d814a07592755dcde018c8659a8015c4b8ed",
"js/developer/environment/development.mjs": "168a2619c4d74544eed2b2ae1121e87c3afc776dc6140a3c7d1ba1d0d6168cd8",
"js/developer/environment/testing.mjs": "aeb584505fab5957b9c02e78536e12f7d7f3d12f8adb2e17f1a1a6e395e43f3c",
Expand Down
25 changes: 20 additions & 5 deletions js/developer/environment/runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ async function check(args, {bridge, signal, write = () => {}, createWorker = che
return syncNotice(project) + runResult('Type check', outcome, host.publications);
}

// Milliseconds before each new attempt to empty the directory of a finished run; the last attempt is not followed by a wait.
const cleanupRetryDelays = [20, 40, 80, 160, 320, undefined];

// wf test [--timeout <seconds>] [pattern]: the specs of "test.specs" under the Jasmine of the lock, in a frame of this page.
// context.onReport receives the structured report, also when the run fails. --timeout, never later than the deadline
// of the wf script that runs this command, covers the whole command: no step waits for the bridge past it, and Ctrl+C
Expand Down Expand Up @@ -255,12 +258,24 @@ async function test(args, {bridge, signal, write = () => {}, createFrame, onRepo
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', interrupt);
// The files of the run are not needed any more: an empty directory replaces them, for at most two seconds.
let cleanupTimer;
// The files of the run are not needed any more: an empty directory replaces them, for at most two seconds. The
// server may still be sending a file to a frame removed in the middle of its run, and Windows refuses to replace
// a directory with an open file: the publication is tried again once the server has had time to close it.
let cleanupTimer, retryTimer, expired = false;
const empty = async () => {
for (const delay of cleanupRetryDelays) {
try { return await publish(bridge, directory, new Map()); } catch { /* tried again below */ }
if (expired || delay === undefined) return;
await new Promise(resolve => { retryTimer = setTimeout(resolve, delay); });
}
};
try {
await Promise.race([publish(bridge, directory, new Map()).catch(() => {}),
new Promise(resolve => { cleanupTimer = setTimeout(resolve, 2000); })]);
} finally { clearTimeout(cleanupTimer); }
await Promise.race([empty(), new Promise(resolve => { cleanupTimer = setTimeout(resolve, 2000); })]);
} finally {
expired = true;
clearTimeout(cleanupTimer);
clearTimeout(retryTimer);
}
}
}

Expand Down
34 changes: 34 additions & 0 deletions test/developer/specs/testing-specs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,40 @@ describe('wf test', () => {
} finally { globalThis.setTimeout = originalSet; }
});

it('empties the test directory again when the first publications are refused', async () => {
// Windows refuses to replace a directory while the server still sends one of its files to a removed frame.
const originalSet = globalThis.setTimeout, originalClear = globalThis.clearTimeout;
const timers = new Set();
globalThis.setTimeout = (callback, milliseconds, ...args) => {
// Only the waits between two attempts are shortened: the two-second bound of the cleanup stays.
const id = originalSet(() => { timers.delete(id); callback(...args); }, milliseconds <= 320 ? 1 : milliseconds);
timers.add(id);
return id;
};
globalThis.clearTimeout = id => { timers.delete(id); originalClear(id); };
try {
for (const refusals of [2, 100]) {
const calls = [];
const bridge = {cppFunction: name => async () => {
const call = name.split('.').at(-1);
calls.push(call);
if (call === 'read') throw new Error('read failed');
if (call === 'commit' && calls.filter(made => made === 'commit').length <= refusals) throw new Error('Access is denied');
return 'transaction';
}};
await rejects(execute(['test'], {bridge}), /read failed/);
const count = call => calls.filter(made => made === call).length;
// A refused publication is abandoned before the next one; the attempts are bounded.
expect([count('commit'), count('abort')]).withContext(`${refusals} refusals`).toEqual(refusals === 2 ? [3, 2] : [6, 6]);
expect(timers.size).withContext(`${refusals} refusals: timers released`).toBe(0);
}
} finally {
globalThis.setTimeout = originalSet;
globalThis.clearTimeout = originalClear;
timers.forEach(originalClear);
}
});

it('a report is bounded: what the specs post is cut, not trusted', () => {
const many = Array.from({length: 300}, (_, index) => spec(`s${index}`, 'failed', {failures: Array.from({length: 20}, () => failure('m'.repeat(50000)))}));
const report = buildReport({type: 'done', overall: 'failed', specs: many, global: [], durationMs: Infinity, version: 'v'.repeat(100)});
Expand Down
9 changes: 6 additions & 3 deletions test/tools/AutomationClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,15 @@ def run(self, operation, arguments=None, state="succeeded"):
def close(self):
if self.child.poll() is None:
self.child.stdin.close()
# The agent ends on its own within about 9 s when a browser does not close: 5 s of grace, then up to 2 s to
# end its processes and 2 s to remove its profile. Wait longer than that, so a loaded machine is not a failure.
try:
self.child.wait(timeout=10)
except subprocess.TimeoutExpired:
self.child.wait(timeout=30)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
except subprocess.TimeoutExpired as error:
self.child.kill()
self.child.wait()
raise
details = self.log_path.read_text()[-2000:] if self.log_path and self.log_path.exists() else ""
raise TimeoutError(f"The agent did not exit after its input closed; native stderr: {details}") from error
self.reader.join(timeout=2)


Expand Down
101 changes: 101 additions & 0 deletions test/tools/FlakeReport.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Counts the CTest cases that failed in the recent runs of a workflow, per platform job.

Read-only: it lists runs and reads the logs of their failed jobs through the GitHub CLI (`gh`), which must be
authenticated. A case that fails on one platform of a run whose other platforms pass is the usual sign of an
intermittent failure; one that fails everywhere on a branch is more likely a regression of that branch. Every attempt
of a run is read: a job that failed and passed once run again is exactly an intermittent failure.

python3 test/tools/FlakeReport.py --limit 60
"""
import argparse
import collections
import json
import re
import subprocess
import sys
import time

# "644/687 Test #615: DeveloperBrowserIntegration-jasmine .....***Failed 18.97 sec", after the log's own prefix.
# A repeated case (`--repeat until-fail:5`) has no "644/687" before its first attempts.
FAILED_CASE = re.compile(r"(?:\d+/\d+ )?Test +#\d+: (?P<name>.+?) \.*\*\*\*(?P<kind>Failed|Timeout|Exception[^ ]*|Not Run)")


def failed_cases(log):
"""The (case, kind) pairs of a CTest log; cases that did not run because a dependency failed are left out."""
found = []
for line in log.splitlines():
match = FAILED_CASE.search(line)
if match and match["kind"] != "Not Run":
found.append((match["name"].strip(), match["kind"]))
return found


def gh(*arguments):
# GitHub answers a read with a 502 now and then: three tries, ten seconds apart.
for attempt in range(3):
result = subprocess.run(["gh", *arguments], capture_output=True, text=True, encoding="utf-8", errors="replace")
if result.returncode == 0 or "HTTP 50" not in result.stderr:
break
if attempt < 2:
time.sleep(10)
if result.returncode != 0:
raise RuntimeError(f"gh {' '.join(arguments)}: {result.stderr.strip()}")
return result.stdout


def attempts_to_read(run):
"""The attempts of a run that can hold a failed job: all the earlier ones, and the last one when it failed."""
last = run.get("attempt") or 1
return [attempt for attempt in range(1, last + 1) if attempt < last or run["conclusion"] == "failure"]


def failed_jobs(run, attempt):
path = f"repos/{{owner}}/{{repo}}/actions/runs/{run['databaseId']}/attempts/{attempt}/jobs?per_page=100"
return [job for job in json.loads(gh("api", path))["jobs"] if job["conclusion"] == "failure"]


def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--workflow", default="BuildAndTest.yml")
parser.add_argument("--limit", type=int, default=60, help="how many of the latest runs to read")
parser.add_argument("--branch", help="only the runs of this branch")
arguments = parser.parse_args()

listing = ["run", "list", "--workflow", arguments.workflow, "--limit", str(arguments.limit),
"--json", "databaseId,conclusion,headBranch,event,attempt"]
if arguments.branch:
listing += ["--branch", arguments.branch]
runs = json.loads(gh(*listing))
completed = [run for run in runs if run["conclusion"] in ("success", "failure")]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
cases = collections.defaultdict(list)
other = collections.Counter()
rerun = 0
for run in completed:
last = run.get("attempt") or 1
rerun += last > 1 and run["conclusion"] == "success"
for attempt in attempts_to_read(run):
where = f"{run['headBranch']}, run {run['databaseId']}" + (f", attempt {attempt} of {last}" if last > 1 else "")
for job in failed_jobs(run, attempt):
found = failed_cases(gh("run", "view", "--job", str(job["id"]), "--attempt", str(attempt), "--log"))
if not found:
steps = ", ".join(step["name"] for step in job.get("steps", []) if step["conclusion"] == "failure")
other[f"{job['name']}: {steps}"] += 1
for name, kind in found:
cases[name].append(f"{job['name']} {kind} ({where})")

failures = sum(1 for run in completed if run["conclusion"] == "failure")
print(f"{len(completed)} completed runs of {arguments.workflow}, {failures} failed, {rerun} passed once run again")
for name, occurrences in sorted(cases.items(), key=lambda item: (-len(item[1]), item[0])):
print(f"\n{len(occurrences):3d} {name}")
for occurrence in occurrences:
print(f" {occurrence}")
if other:
print("\nFailed jobs without a failed CTest case:")
for description, count in other.most_common():
print(f"{count:3d} {description}")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading