From 130e56aeeffa9173d31ca00c127e766e6f1f7867 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:54:02 +0100 Subject: [PATCH 1/6] Retry the renames of the developer store on Windows and steady three intermittent tests (#542) A publication failed with "rename: Access is denied" when another process still read the files just written, and wf test left the files of an interrupted run behind while the server was closing them. The store now tries a refused rename again for up to 635 ms, and wf test tries again to empty the directory of its run. The Python tool tests get 60 seconds instead of 15, TestMeasurement waits for a sample with resident memory, and test/tools/FlakeReport.py counts the CTest cases that failed in the recent runs of a workflow. --- docs/CHANGELOG.md | 1 + include/webfront/system/DeveloperFiles.hpp | 26 ++++++- include/webfront/system/DeveloperJournal.hpp | 3 +- include/webfront/system/DeveloperStore.hpp | 4 +- js/developer/environment/bundles.json | 2 +- js/developer/environment/runtime.mjs | 25 ++++-- test/developer/specs/testing-specs.mjs | 34 ++++++++ test/tools/FlakeReport.py | 81 ++++++++++++++++++++ test/tools/TestFlakeReport.py | 25 ++++++ test/tools/TestMeasurement.py | 5 +- test/unit/CMakeLists.txt | 5 +- test/unit/DeveloperTests.cpp | 26 +++++++ 12 files changed, 222 insertions(+), 15 deletions(-) create mode 100644 test/tools/FlakeReport.py create mode 100644 test/tools/TestFlakeReport.py diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 2db31faa..1b4eb45d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -16,6 +16,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). - 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). ## [0.9.0] - 2026-11-10 diff --git a/include/webfront/system/DeveloperFiles.hpp b/include/webfront/system/DeveloperFiles.hpp index c8ca64ce..771a0752 100644 --- a/include/webfront/system/DeveloperFiles.hpp +++ b/include/webfront/system/DeveloperFiles.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include namespace webfront::developer { @@ -59,6 +60,27 @@ inline std::pair 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()); @@ -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); diff --git a/include/webfront/system/DeveloperJournal.hpp b/include/webfront/system/DeveloperJournal.hpp index a4626886..b00b9749 100644 --- a/include/webfront/system/DeveloperJournal.hpp +++ b/include/webfront/system/DeveloperJournal.hpp @@ -2,6 +2,7 @@ #pragma once #include "WindowsCompat.hpp" +#include "DeveloperFiles.hpp" #include "DeveloperPaths.hpp" #include @@ -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) diff --git a/include/webfront/system/DeveloperStore.hpp b/include/webfront/system/DeveloperStore.hpp index 16d28c15..5890218e 100644 --- a/include/webfront/system/DeveloperStore.hpp +++ b/include/webfront/system/DeveloperStore.hpp @@ -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")); @@ -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"); } diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index e5f54510..33784f4e 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -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", diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index 54e0171a..f273e218 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -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 ] [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 @@ -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); + } } } diff --git a/test/developer/specs/testing-specs.mjs b/test/developer/specs/testing-specs.mjs index 9c5bad72..2747ca63 100644 --- a/test/developer/specs/testing-specs.mjs +++ b/test/developer/specs/testing-specs.mjs @@ -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)}); diff --git a/test/tools/FlakeReport.py b/test/tools/FlakeReport.py new file mode 100644 index 00000000..81389d61 --- /dev/null +++ b/test/tools/FlakeReport.py @@ -0,0 +1,81 @@ +#!/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. + + python3 test/tools/FlakeReport.py --limit 60 +""" +import argparse +import collections +import json +import re +import subprocess +import sys + +# "644/687 Test #615: DeveloperBrowserIntegration-jasmine .....***Failed 18.97 sec", after the log's own prefix. +FAILED_CASE = re.compile(r"\d+/\d+ Test +#\d+: (?P.+?) \.*\*\*\*(?PFailed|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): + result = subprocess.run(["gh", *arguments], capture_output=True, text=True, encoding="utf-8", errors="replace") + if result.returncode != 0: + raise RuntimeError(f"gh {' '.join(arguments)}: {result.stderr.strip()}") + return result.stdout + + +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"] + if arguments.branch: + listing += ["--branch", arguments.branch] + runs = json.loads(gh(*listing)) + completed = [run for run in runs if run["conclusion"] in ("success", "failure")] + cases = collections.defaultdict(list) + other = collections.Counter() + for run in completed: + if run["conclusion"] != "failure": + continue + jobs = json.loads(gh("run", "view", str(run["databaseId"]), "--json", "jobs"))["jobs"] + for job in jobs: + if job["conclusion"] != "failure": + continue + found = failed_cases(gh("run", "view", "--job", str(job["databaseId"]), "--log-failed")) + if not found: + steps = ", ".join(step["name"] for step in job["steps"] if step["conclusion"] == "failure") + other[f"{job['name']}: {steps}"] += 1 + for name, kind in found: + cases[name].append(f"{job['name']} {kind} ({run['headBranch']}, run {run['databaseId']})") + + failures = sum(1 for run in completed if run["conclusion"] == "failure") + print(f"{len(completed)} completed runs of {arguments.workflow}, {failures} failed") + 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()) diff --git a/test/tools/TestFlakeReport.py b/test/tools/TestFlakeReport.py new file mode 100644 index 00000000..81068cce --- /dev/null +++ b/test/tools/TestFlakeReport.py @@ -0,0 +1,25 @@ +import unittest +from FlakeReport import failed_cases + + +class FlakeReportTests(unittest.TestCase): + def test_failed_cases_of_a_ctest_log(self): + log = '\n'.join([ + 'desktop\tTest\t2026-11-11T07:40:00Z 643/687 Test #614: DeveloperBrowserIntegration-typescript ..... Passed 23.76 sec', + 'desktop\tTest\t2026-11-11T07:40:01Z 644/687 Test #615: DeveloperBrowserIntegration-jasmine ........***Failed 18.97 sec', + 'desktop\tTest\t2026-11-11T07:40:02Z 64/687 Test #652: JourneyOfflineMissing ......................***Not Run 0.00 sec', + 'desktop\tTest\t2026-11-11T07:40:03Z 503/505 Test #543: TestResourceMeasurement ....................***Timeout 15.34 sec', + 'desktop\tTest\t2026-11-11T07:40:04Z 49/650 Test #160: Scenario: A window that ignores the close request ...***Failed 16.65 sec', + 'desktop\tTest\t2026-11-11T07:40:05Z \t615 - DeveloperBrowserIntegration-jasmine (Failed) web-integration', + ]) + self.assertEqual(failed_cases(log), [ + ('DeveloperBrowserIntegration-jasmine', 'Failed'), + ('TestResourceMeasurement', 'Timeout'), + ('Scenario: A window that ignores the close request', 'Failed')]) + + def test_a_log_without_ctest_has_no_case(self): + self.assertEqual(failed_cases('ninja: build stopped: subcommand failed.\n'), []) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/tools/TestMeasurement.py b/test/tools/TestMeasurement.py index d73f06ba..26817c18 100644 --- a/test/tools/TestMeasurement.py +++ b/test/tools/TestMeasurement.py @@ -13,7 +13,8 @@ def test_resources_and_failed_command_status_are_retained(self): with tempfile.TemporaryDirectory() as directory: output = Path(directory) / 'resources.json' sampled = Path(directory) / 'sampled' - # Keep the child alive until a real sample includes it, even on a loaded runner. + # Keep the child alive until a real sample includes it with resident memory, even on a loaded runner: a + # process caught while it starts is listed with none yet. child = """import pathlib, sys, time marker = pathlib.Path(sys.argv[1]) deadline = time.monotonic() + 30 @@ -23,7 +24,7 @@ def test_resources_and_failed_command_status_are_retained(self): """ def record_sample(root): processes = snapshot(root) - if root in processes: + if processes.get(root, (0, 0, 0))[1] > 0: sampled.touch() return processes with patch('MeasureCommand.snapshot', side_effect=record_sample): diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 236f5564..129625c0 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -391,9 +391,10 @@ find_package(Python3 QUIET COMPONENTS Interpreter) if(Python3_Interpreter_FOUND) add_test(NAME TestPerformanceProfile COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/tools/TestProfileTests.py") add_test(NAME FuzzerConcurrency COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/fuzz/TestRunFuzzers.py") - set_tests_properties(TestPerformanceProfile FuzzerConcurrency PROPERTIES TIMEOUT 15 LABELS fast) + set_tests_properties(TestPerformanceProfile FuzzerConcurrency PROPERTIES TIMEOUT 60 LABELS fast) endif() if(Python3_Interpreter_FOUND) add_test(NAME TestResourceMeasurement COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/tools/TestMeasurement.py") - set_tests_properties(TestResourceMeasurement PROPERTIES TIMEOUT 15 LABELS fast) + add_test(NAME TestFlakeReport COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/tools/TestFlakeReport.py") + set_tests_properties(TestResourceMeasurement TestFlakeReport PROPERTIES TIMEOUT 60 LABELS fast) endif() diff --git a/test/unit/DeveloperTests.cpp b/test/unit/DeveloperTests.cpp index 880adece..52c84c6e 100644 --- a/test/unit/DeveloperTests.cpp +++ b/test/unit/DeveloperTests.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include using namespace webfront; @@ -58,6 +59,31 @@ SCENARIO("Developer publication preserves the installed files until commit") { } } +SCENARIO("A publication waits for a file that another reader is about to release") { + TemporaryDirectory project; + developer::Store store{project.path()}; + GIVEN("a published directory with a file held open, as a scan of what was just written holds it on Windows") { + auto first = store.begin("packages/library", true); + store.write(first, "index.js", 0, bytes("old")); + store.commit(first); + std::ifstream held(project.path() / "packages/library/index.js", std::ios::binary); + REQUIRE(held.is_open()); + auto released = std::async(std::launch::async, [&held] { + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + held.close(); + }); + WHEN("the directory is replaced before the reader closes the file") { + auto second = store.begin("packages/library", true); + store.write(second, "index.js", 0, bytes("new")); + store.commit(second); + THEN("the publication is completed once the file is released") { + REQUIRE(read(store, "packages/library/index.js") == "new"); + } + } + released.get(); + } +} + SCENARIO("Developer writes are bounded and paths stay inside the explicit project") { TemporaryDirectory project; developer::Store store{project.path()}; From ed819c9f6455e263cee5443ca71181f75e43bf57 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:13:30 +0100 Subject: [PATCH 2/6] Wait for the agent's own exit bound in the automation client and bound the apt install of the wf driver (#542) The agent ends on its own within about 9 s when a browser does not close; the test client waited 10 s and lost the agent's log. It now waits 30 s and reports the log. The wf driver action bounds apt-get on the primary archive and falls back to the runner's mirror. --- .github/actions/wf-driver/action.yml | 22 ++++++++++++++++------ test/tools/AutomationClient.py | 9 ++++++--- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/.github/actions/wf-driver/action.yml b/.github/actions/wf-driver/action.yml index 438cd55e..72a43516 100644 --- a/.github/actions/wf-driver/action.yml +++ b/.github/actions/wf-driver/action.yml @@ -13,13 +13,23 @@ 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. + mirrors=/etc/apt/apt-mirrors.txt + install() { + sudo timeout 120 apt-get update && sudo timeout 300 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 dpkg --configure -a + 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 diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index cc961cb9..b595a316 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -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) + 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) From 4f8fbed3638408354f04dfaca3a7ef593477d6f0 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:52:30 +0100 Subject: [PATCH 3/6] Read every attempt in the flake report, log the requests of the developer integration and keep the apt fallback inside the job limit (#542) A run that passed once run again hid its failed attempt from the report. The developer integration prints each request and its status, shown by CTest when a case fails, to tell why a page resource did not load. The two apt attempts and the repair between them take at most 11 minutes. --- .github/actions/wf-driver/action.yml | 7 +++-- test/tools/FlakeReport.py | 45 ++++++++++++++++++---------- test/tools/TestFlakeReport.py | 13 ++++++-- test/web/CMakeLists.txt | 3 +- test/web/DeveloperTest.cpp | 4 +++ 5 files changed, 50 insertions(+), 22 deletions(-) diff --git a/.github/actions/wf-driver/action.yml b/.github/actions/wf-driver/action.yml index 72a43516..d39fe7ec 100644 --- a/.github/actions/wf-driver/action.yml +++ b/.github/actions/wf-driver/action.yml @@ -15,10 +15,11 @@ runs: run: | # 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. + # 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 120 apt-get update && sudo timeout 300 apt-get install -y --no-install-recommends -o Acquire::Retries=3 -o Acquire::http::Timeout=15 gcc-16 g++-16 libwebkitgtk-6.0-dev + 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" @@ -27,7 +28,7 @@ runs: 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 dpkg --configure -a + sudo timeout 60 dpkg --configure -a || echo "::warning::The interrupted installation could not be repaired in time" install fi echo "CC=gcc-16" >> "$GITHUB_ENV" diff --git a/test/tools/FlakeReport.py b/test/tools/FlakeReport.py index 81389d61..52c91d44 100644 --- a/test/tools/FlakeReport.py +++ b/test/tools/FlakeReport.py @@ -3,7 +3,8 @@ 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. +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 """ @@ -15,7 +16,8 @@ import sys # "644/687 Test #615: DeveloperBrowserIntegration-jasmine .....***Failed 18.97 sec", after the log's own prefix. -FAILED_CASE = re.compile(r"\d+/\d+ Test +#\d+: (?P.+?) \.*\*\*\*(?PFailed|Timeout|Exception[^ ]*|Not Run)") +# 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.+?) \.*\*\*\*(?PFailed|Timeout|Exception[^ ]*|Not Run)") def failed_cases(log): @@ -35,6 +37,17 @@ def gh(*arguments): 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") @@ -43,29 +56,29 @@ def main(): arguments = parser.parse_args() listing = ["run", "list", "--workflow", arguments.workflow, "--limit", str(arguments.limit), - "--json", "databaseId,conclusion,headBranch,event"] + "--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")] cases = collections.defaultdict(list) other = collections.Counter() + rerun = 0 for run in completed: - if run["conclusion"] != "failure": - continue - jobs = json.loads(gh("run", "view", str(run["databaseId"]), "--json", "jobs"))["jobs"] - for job in jobs: - if job["conclusion"] != "failure": - continue - found = failed_cases(gh("run", "view", "--job", str(job["databaseId"]), "--log-failed")) - if not found: - steps = ", ".join(step["name"] for step in job["steps"] if step["conclusion"] == "failure") - other[f"{job['name']}: {steps}"] += 1 - for name, kind in found: - cases[name].append(f"{job['name']} {kind} ({run['headBranch']}, run {run['databaseId']})") + 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"]), "--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") + 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: diff --git a/test/tools/TestFlakeReport.py b/test/tools/TestFlakeReport.py index 81068cce..598c2a48 100644 --- a/test/tools/TestFlakeReport.py +++ b/test/tools/TestFlakeReport.py @@ -1,5 +1,5 @@ import unittest -from FlakeReport import failed_cases +from FlakeReport import attempts_to_read, failed_cases class FlakeReportTests(unittest.TestCase): @@ -11,11 +11,20 @@ def test_failed_cases_of_a_ctest_log(self): 'desktop\tTest\t2026-11-11T07:40:03Z 503/505 Test #543: TestResourceMeasurement ....................***Timeout 15.34 sec', 'desktop\tTest\t2026-11-11T07:40:04Z 49/650 Test #160: Scenario: A window that ignores the close request ...***Failed 16.65 sec', 'desktop\tTest\t2026-11-11T07:40:05Z \t615 - DeveloperBrowserIntegration-jasmine (Failed) web-integration', + 'desktop Test 2026-11-11T07:40:06Z Test #612: WebKitGTKAdapter-choose-file ..........***Failed 2.10 sec', ]) self.assertEqual(failed_cases(log), [ ('DeveloperBrowserIntegration-jasmine', 'Failed'), ('TestResourceMeasurement', 'Timeout'), - ('Scenario: A window that ignores the close request', 'Failed')]) + ('Scenario: A window that ignores the close request', 'Failed'), + ('WebKitGTKAdapter-choose-file', 'Failed')]) + + def test_the_failed_attempts_of_a_run_that_passed_once_run_again_are_read(self): + self.assertEqual(attempts_to_read({"conclusion": "success", "attempt": 3}), [1, 2]) + self.assertEqual(attempts_to_read({"conclusion": "failure", "attempt": 2}), [1, 2]) + self.assertEqual(attempts_to_read({"conclusion": "failure", "attempt": 1}), [1]) + self.assertEqual(attempts_to_read({"conclusion": "success", "attempt": 1}), []) + self.assertEqual(attempts_to_read({"conclusion": "failure"}), [1]) def test_a_log_without_ctest_has_no_case(self): self.assertEqual(failed_cases('ninja: build stopped: subcommand failed.\n'), []) diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index a73358be..06004ac7 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -106,8 +106,9 @@ if(_browser_tests_available AND TARGET webfront-agent) --environment "${_fixtures}/environment.tgz" --provision "${_fixtures}/provision.json" --registry "${_registry}" --fixture "${PROJECT_SOURCE_DIR}/test/fixtures/automation-project" --work "${CMAKE_CURRENT_BINARY_DIR}/automation-${_scenario}") + # The session scenario closes several agents, each of which may use its own bound of about 9 s to exit. set_tests_properties(${_case} PROPERTIES FIXTURES_REQUIRED DeveloperFixtures - LABELS web-integration TIMEOUT 120) + LABELS web-integration TIMEOUT 180) webfront_use_own_profile(${_case} "automation-${_scenario}") if(NOT _scenario STREQUAL "session") # One deliberately spinning renderer at a time, without serializing unrelated browser tests. diff --git a/test/web/DeveloperTest.cpp b/test/web/DeveloperTest.cpp index 345f4b49..55e12800 100644 --- a/test/web/DeveloperTest.cpp +++ b/test/web/DeveloperTest.cpp @@ -252,6 +252,10 @@ int main(int argc, char** argv) { try { // CEF child processes must dispatch before interpreting application arguments or creating files. webfront::detail::ensureFrontendInitialized(); + // CTest shows the output of a failed case only: it then names every request and the status it was answered, + // which is what tells a resource the page could not load from one the server refused (#542). + webfront::log::setLogLevel(webfront::log::Info); + [[maybe_unused]] const auto requestLog = webfront::log::addSinks(webfront::log::clogSink); if (argc != 3 && argc != 4) throw std::invalid_argument("Expected fixture directory, header output directory and optional --public or --part="); const Mode mode = parseMode(argc == 4 ? std::string_view(argv[3]) : std::string_view{}); From d85f76c9b844599757eed8fbd1a2e93183cf65ed Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:55:30 +0100 Subject: [PATCH 4/6] Try a GitHub read again when it answers a 502 in the flake report (#542) --- test/tools/FlakeReport.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/test/tools/FlakeReport.py b/test/tools/FlakeReport.py index 52c91d44..bc3c139b 100644 --- a/test/tools/FlakeReport.py +++ b/test/tools/FlakeReport.py @@ -14,6 +14,7 @@ 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. @@ -31,7 +32,13 @@ def failed_cases(log): def gh(*arguments): - result = subprocess.run(["gh", *arguments], capture_output=True, text=True, encoding="utf-8", errors="replace") + # 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 From c88d66d0a4254c9f319bec6b7b312937d8ae27cd Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:08:06 +0100 Subject: [PATCH 5/6] Accept a pending removal while waiting for the endpoint to be withdrawn (#542) On Windows std::filesystem::exists throws Access is denied for a file being removed, which failed the discovery scenario instead of letting it wait. --- test/unit/AutomationDiscoveryTests.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/unit/AutomationDiscoveryTests.cpp b/test/unit/AutomationDiscoveryTests.cpp index 4aa901e9..866ae70e 100644 --- a/test/unit/AutomationDiscoveryTests.cpp +++ b/test/unit/AutomationDiscoveryTests.cpp @@ -409,7 +409,11 @@ SCENARIO("A window that ignores the deadline's close request is declared unrespo automation->controller()->close("Developer window disconnected"); THEN("the record and the endpoint are withdrawn at once, and closing the automation confirms the window is gone") { REQUIRE(eventually([&] { return discovery::list(sessions).empty(); })); - REQUIRE(eventually([&] { return !std::filesystem::exists(automation->endpoint() / "endpoint.json"); })); + // Windows refuses to look at a file whose removal is pending: that is the withdrawal under way, not a failure. + REQUIRE(eventually([&] { + std::error_code pending; + return !std::filesystem::exists(automation->endpoint() / "endpoint.json", pending); + })); automation->close(); std::this_thread::sleep_for(std::chrono::milliseconds{100}); REQUIRE(unresponsive.load() == 0); From 807cae8d3424eadecbb191bce5cca937b6234284 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:41:56 +0100 Subject: [PATCH 6/6] Read workflow logs from the requested run attempt (#542) --- test/tools/FlakeReport.py | 2 +- test/tools/TestFlakeReport.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/test/tools/FlakeReport.py b/test/tools/FlakeReport.py index bc3c139b..85e51319 100644 --- a/test/tools/FlakeReport.py +++ b/test/tools/FlakeReport.py @@ -77,7 +77,7 @@ def main(): 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"]), "--log")) + 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 diff --git a/test/tools/TestFlakeReport.py b/test/tools/TestFlakeReport.py index 598c2a48..40efcf73 100644 --- a/test/tools/TestFlakeReport.py +++ b/test/tools/TestFlakeReport.py @@ -1,5 +1,9 @@ +import contextlib +import io +import json import unittest -from FlakeReport import attempts_to_read, failed_cases +from unittest.mock import patch +from FlakeReport import attempts_to_read, failed_cases, main class FlakeReportTests(unittest.TestCase): @@ -29,6 +33,32 @@ def test_the_failed_attempts_of_a_run_that_passed_once_run_again_are_read(self): def test_a_log_without_ctest_has_no_case(self): self.assertEqual(failed_cases('ninja: build stopped: subcommand failed.\n'), []) + def test_logs_of_failed_attempts_are_read_even_after_a_successful_rerun(self): + run = {"databaseId": 123, "conclusion": "success", "headBranch": "develop", "attempt": 3} + + def github(*arguments): + if arguments[:2] == ('run', 'list'): + return json.dumps([run]) + if arguments[0] == 'api': + return json.dumps({"jobs": [{"id": 456, "name": "Windows", "conclusion": "failure", "steps": []}]}) + if arguments[:2] == ('run', 'view'): + # Without --attempt, gh returns the latest attempt's successful log, even for an older job ID. + if '--attempt' not in arguments: + return 'Test #1: IntermittentCase ........ Passed 1.00 sec' + return 'Test #1: IntermittentCase ........***Failed 1.00 sec' + self.fail(f'Unexpected GitHub command: {arguments}') + + output = io.StringIO() + with patch('FlakeReport.gh', side_effect=github) as github_call, \ + patch('sys.argv', ['FlakeReport.py']), contextlib.redirect_stdout(output): + self.assertEqual(main(), 0) + + for attempt in (1, 2): + github_call.assert_any_call('run', 'view', '--job', '456', '--attempt', str(attempt), '--log') + self.assertIn(f'Windows Failed (develop, run 123, attempt {attempt} of 3)', output.getvalue()) + self.assertIn(' 2 IntermittentCase', output.getvalue()) + self.assertNotIn('Failed jobs without a failed CTest case', output.getvalue()) + if __name__ == '__main__': unittest.main()