From 5dfaed353279fd13b83a6abae07f8bfd246e519a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:50:48 +0100 Subject: [PATCH 01/14] Fix phase timing corruption and extend flaky test diagnostics (#542) --- docs/CHANGELOG.md | 2 ++ docs/PROJECT_STATUS.md | 6 ++++++ docs/TEST_PERFORMANCE.md | 26 ++++++++++++++++++++++++++ js/developer/tools/WebFrontAgent.cpp | 7 +++++++ test/driver/RequestLog.hpp | 24 ++++++++++++++++++++++++ test/driver/WfDriver.hpp | 2 ++ test/tools/ProfileTests.py | 9 ++++++++- test/tools/TestProfileTests.py | 20 ++++++++++++++++++++ test/unit/WfDriverTests.cpp | 25 +++++++++++++++++++++++++ test/web/AutomationConsumer.cpp | 1 + test/web/CMakeLists.txt | 2 ++ test/web/DeveloperTest.cpp | 13 ++++++++++--- test/web/developer-specs.mjs | 8 +++++++- 13 files changed, 140 insertions(+), 5 deletions(-) create mode 100644 test/driver/RequestLog.hpp diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 75d13cf5..87068f48 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -28,6 +28,8 @@ these entries stays in the GitHub releases and the Git history. ### Fixed +- Serialize the developer session's phase logs and keep CI timing analysis running if a duration is malformed: report and omit that timing while retaining the other phases and test results (#542). + - Restore the terminal prompt with exit code 1 when `wf dev` starts without a project or a selectable entry; compilation errors still keep watching for edits. Environment 0.9.2 (#560). - Read all six developer integration reports in CTest after a part fails, and keep the successful parts' dependent tests runnable, also when the session's native deadline ends it (#556). - 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). diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 203e18e8..9128e2ed 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -77,6 +77,12 @@ resource limits and complete-suite repetition. Sessions retain individual CTest independent driver processes use OS-assigned loopback ports. Manual transport measurements remain separate from the short native transport contract tests. +Intermittent CI failures in session resource loading, workspace reloading and native browser lifecycle tests remain +under investigation in [#542](https://github.com/ambroise-leclerc/WebFront/issues/542); the Windows early-close COM +lifetime failure is tracked separately in [#564](https://github.com/ambroise-leclerc/WebFront/issues/564). +The [diagnostic workflow](TEST_PERFORMANCE.md#investigating-intermittent-failures) preserves failed attempts and HTTP +transcripts; successful local repetitions do not establish that these platform-specific defects are fixed. + [Local-model qualification](validation/automation-models-2026-10-29.md) records five installed models driving the real MCP window through an external LM Studio measurement adapter. It distinguishes final source correctness (30/30 host-verified tasks) from completed verification observed by the model diff --git a/docs/TEST_PERFORMANCE.md b/docs/TEST_PERFORMANCE.md index 1f301626..8289b81b 100644 --- a/docs/TEST_PERFORMANCE.md +++ b/docs/TEST_PERFORMANCE.md @@ -174,6 +174,11 @@ runner raises the CTest output cap to 2 MiB per case so JUnit retains these deta phase/spec durations. WASM compilation/initialization, command preparation, publication, navigation and execution can be located by the enclosing command and spec; these spans include waits and bridge traffic, not just CPU time. +Malformed `durationMs` values (for example two numbers interleaved by concurrent output) are reported on stderr and +omitted from the phase ranking. Other phases and the CTest result remain available; no numeric prefix is used as an +invented duration. This tolerance applies only to optional phase timings, not to malformed JUnit or dependency graphs. +The developer session serializes progress and result lines from its independent server threads. + The esbuild helper used by developer specs initializes its WASM compiler in a Worker, matching the developer environment and avoiding off-screen frame timer throttling. Its rebuild spec changes an imported file, checks a syntax error and checks recovery. @@ -203,6 +208,27 @@ statistics. Qualification dispatches `BuildAndTest.yml` with `repeat_desktop_tes passes plus GCC/Clang CEF and sanitizers. First-pass fixtures/profiles are fresh; later passes reset them too but may benefit from OS/filesystem and compiler caches. They are not measurements of a physically cold OS page cache. +## Investigating intermittent failures + +Read the failures of recent workflow runs, including earlier attempts of a run that later passed: + +```sh +python3 test/tools/FlakeReport.py --limit 60 +``` + +This read-only tool requires authenticated `gh`. Correlate the case, platform and revision before treating a failure as +intermittent. Repeat the complete fixture graph with `RunTestSuite.cmake` as above; repeating an individual stateful +command does not reset its inputs. Do not add automatic CI retries. + +The developer integration executable, `webfront-wf`, the browser suite driver and the automation consumer log HTTP +requests, response statuses and streaming failures to stderr. The agent does so only in a browser test build. +These logs retain warnings and errors and filter out ordinary bridge traffic to keep resource diagnostics within CTest's output cap; service +tokens and request queries retain the HTTP server's redaction. JSON/MCP stdout stays separate. +For grouped sessions, read `DeveloperBrowserSession` or the corresponding `*Session` transcript in the uploaded +`Testing/Temporary/LastTest-.log` even when that aggregate case passes: the individual report reader may fail later. +The workspace reloading assertion also reports the preview URL, document readiness, displayed root, tab status and +`wf dev` output. A 200 response alone does not prove that a frame executed its script. + ## Recording a run Write profiles, resource samples, JUnit reports and dependency graphs under the build directory. diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 5980aed0..e0be9287 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -10,6 +10,10 @@ #include #include +#ifdef WEBFRONT_TEST_REQUEST_LOG + #include "../../../test/driver/RequestLog.hpp" +#endif + #include #include @@ -789,6 +793,9 @@ int main(int argc, char** argv) { // Dispatch CEF renderer processes before parsing flags or creating a // profile. webfront::detail::ensureFrontendInitialized(); +#ifdef WEBFRONT_TEST_REQUEST_LOG + [[maybe_unused]] const auto requestLog = webfront::testdriver::logRequests(); +#endif const auto options = parse(argc, argv); Interrupt interrupt; Profile profile; diff --git a/test/driver/RequestLog.hpp b/test/driver/RequestLog.hpp new file mode 100644 index 00000000..4dd306f9 --- /dev/null +++ b/test/driver/RequestLog.hpp @@ -0,0 +1,24 @@ +// HTTP diagnostics for native test processes. Keep bridge traffic out of the transcript so CTest's output cap +// does not discard the resource requests we need when a session frame fails to load (#542). +#pragma once + +#include + +#include +#include +#include + +namespace webfront::testdriver { +inline auto logRequests() { + log::setLogLevel(log::Info); + return log::addSinks([](std::string_view line) { + if (line.find("[I]") == std::string_view::npos || line.find("Received request ") != std::string_view::npos + || line.find("responding http ") != std::string_view::npos || line.find("HTTP asset request ") != std::string_view::npos + || line.find("ended its response early") != std::string_view::npos || line.find("Route ") != std::string_view::npos) { + static std::mutex output; + const std::scoped_lock lock{output}; + std::clog << line << '\n'; + } + }); +} +} // namespace webfront::testdriver diff --git a/test/driver/WfDriver.hpp b/test/driver/WfDriver.hpp index 2217f78c..8505970d 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -8,6 +8,7 @@ #include "../unit/TemporaryDirectory.hpp" #include "DriverSuite.hpp" +#include "RequestLog.hpp" #include "TestFrontend.hpp" #include #include @@ -623,6 +624,7 @@ int main(int argc, char** argv, std::string_view program, Setup&& setup = {}) { try { // CEF child processes must dispatch before interpreting application arguments or creating files. webfront::detail::ensureFrontendInitialized(); + [[maybe_unused]] const auto requestLog = logRequests(); #if defined(WEBFRONT_EMBED_CEF) && defined(__linux__) std::optional temporaryProfile; if constexpr (std::is_same_v) { diff --git a/test/tools/ProfileTests.py b/test/tools/ProfileTests.py index 51d25841..97f07802 100644 --- a/test/tools/ProfileTests.py +++ b/test/tools/ProfileTests.py @@ -1,9 +1,11 @@ """Combine CTest's JSON dependency/lock graph and JUnit timings without summing parallel wall times.""" import argparse import json +import math from pathlib import Path import statistics import re +import sys import xml.etree.ElementTree as ET @@ -84,7 +86,7 @@ def write_report(result, output): output.with_suffix('.dot').write_text('\n'.join(dot + ['}']) + '\n', encoding='utf-8') -PHASE = re.compile(r'(?:wf spec: |Developer integration: )?(?:[\d.]+ms )?end (.*?)(?: status=\S+)? durationMs=([\d.]+)') +PHASE = re.compile(r'(?:wf spec: |Developer integration: )?(?:[\d.]+ms )?end (.*?)(?: status=\S+)? durationMs=(\S*)') def phase_durations(transcripts): @@ -94,6 +96,11 @@ def phase_durations(transcripts): for line in transcript.splitlines(): match = PHASE.search(line) if match: + # Parallel native/browser output can interleave. Do not turn a corrupt timing into a failed CI job, + # or silently accept its numeric prefix and publish a fabricated measurement. + if not re.fullmatch(r'\d+(?:\.\d+)?', match[2]) or not math.isfinite(float(match[2])): + print(f'Ignoring malformed phase duration in pass {index}: {line}', file=sys.stderr) + continue phases.append((float(match[2]), f'pass {index}: {match[1]}')) return phases diff --git a/test/tools/TestProfileTests.py b/test/tools/TestProfileTests.py index 586a7b07..a1939954 100644 --- a/test/tools/TestProfileTests.py +++ b/test/tools/TestProfileTests.py @@ -1,4 +1,6 @@ from pathlib import Path +from contextlib import redirect_stderr +import io import tempfile import unittest from ProfileTests import analyze, write_report @@ -56,6 +58,24 @@ def test_ninja_durations_rank_compile_and_link_jobs(self): log.write_text('# ninja log v5\n0\t2000\t0\ta.cpp.o\t123\n500\t1500\t0\tapp\t234\n') self.assertEqual(compile_profile(log), [(2, 'a.cpp.o'), (1, 'app')]) + def test_malformed_phase_durations_are_reported_without_losing_other_phases(self): + from ProfileTests import phase_durations + lines = ('end valid durationMs=1.250\n' + 'Developer integration: Developer integration: 20868.300ms end command embed ui/main.tsx --output ' + 'durationMs=4723.50020276.900ms begin command run unawaited\n' + 'end truncated durationMs=\n' + 'end invalid durationMs=nan\n' + 'end suffix durationMs=12.500garbled\n' + 'end negative durationMs=-3\n' + 'end overflow durationMs=' + '9' * 400 + '\n' + 'end next status=passed durationMs=2.000\n') + diagnostics = io.StringIO() + with redirect_stderr(diagnostics): + self.assertEqual(phase_durations([lines]), + [(1.25, 'pass 1: valid'), (2, 'pass 1: next')]) + self.assertIn('4723.50020276.900', diagnostics.getvalue()) + self.assertEqual(diagnostics.getvalue().count('Ignoring malformed phase duration'), 6) + if __name__ == '__main__': unittest.main() diff --git a/test/unit/WfDriverTests.cpp b/test/unit/WfDriverTests.cpp index db47506a..a0d91b2b 100644 --- a/test/unit/WfDriverTests.cpp +++ b/test/unit/WfDriverTests.cpp @@ -1,6 +1,8 @@ #include "../driver/WfDriver.hpp" #include +#include + namespace { struct DriverUI { std::vector* scripts; @@ -18,6 +20,29 @@ webfront::testdriver::Options parseDriver(std::initializer_list ext } } // namespace +SCENARIO("Browser test diagnostics retain HTTP failures without filling the transcript with bridge traffic") { + std::ostringstream output; + auto* previous = std::clog.rdbuf(output.rdbuf()); + const auto sink = webfront::testdriver::logRequests(); + webfront::log::info("Received request GET on /scripts.js"); + webfront::log::info(" responding http 404"); + webfront::log::info("onMessage(binary): bridge traffic"); + webfront::log::warn("HTTP asset request failed: denied"); + webfront::log::warn("File response ended its response early: short read"); + webfront::log::warn("WebSocket disconnected unexpectedly"); + webfront::log::removeSinks(sink); + std::clog.rdbuf(previous); + webfront::log::setLogLevel(webfront::log::Disabled); + THEN("the resource, status and failures remain, but ordinary bridge messages do not") { + CHECK(output.str().find("GET on /scripts.js") != std::string::npos); + CHECK(output.str().find("responding http 404") != std::string::npos); + CHECK(output.str().find("request failed: denied") != std::string::npos); + CHECK(output.str().find("response early: short read") != std::string::npos); + CHECK(output.str().find("WebSocket disconnected unexpectedly") != std::string::npos); + CHECK(output.str().find("bridge traffic") == std::string::npos); + } +} + SCENARIO("The driver deadline closes both connected and late browsers without losing the request") { std::vector scripts; webfront::testdriver::DriverBrowser browser; diff --git a/test/web/AutomationConsumer.cpp b/test/web/AutomationConsumer.cpp index d60527d9..206a0cb3 100644 --- a/test/web/AutomationConsumer.cpp +++ b/test/web/AutomationConsumer.cpp @@ -23,6 +23,7 @@ int main(int argc, char** argv) { using Frontend = WEBFRONT_DRIVER_FRONTEND; try { webfront::detail::ensureFrontendInitialized(); + [[maybe_unused]] const auto requestLog = webfront::testdriver::logRequests(); #if defined(WEBFRONT_EMBED_CEF) && defined(__linux__) std::optional temporaryProfile; if constexpr (std::is_same_v) { diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 8a77dda6..db397800 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -88,6 +88,8 @@ set(_self_project "${CMAKE_CURRENT_BINARY_DIR}/self-build-project") set(_registry "${_self_project}/build-registry") set(_fixtures "${CMAKE_CURRENT_BINARY_DIR}/developer-fixtures") if(_browser_tests_available AND TARGET webfront-agent) + # Only the test build logs HTTP to stderr; stdout remains the JSON/MCP protocol. + target_compile_definitions(webfront-agent PRIVATE WEBFRONT_TEST_REQUEST_LOG=1) webfront_optional_window_test_runner(_window_test_prefix _automation_windows_available) add_dependencies(webtest webfront-agent) find_package(Python3 COMPONENTS Interpreter QUIET) diff --git a/test/web/DeveloperTest.cpp b/test/web/DeveloperTest.cpp index 856af25e..12f32686 100644 --- a/test/web/DeveloperTest.cpp +++ b/test/web/DeveloperTest.cpp @@ -1,5 +1,6 @@ #include "../../examples/life/Life.hpp" #include "../driver/DriverSuite.hpp" +#include "../driver/RequestLog.hpp" #include "../unit/TemporaryDirectory.hpp" #include #include @@ -17,6 +18,9 @@ #include namespace { +// The parts have independent server threads. A phase marker must not splice its duration into another part's line. +std::mutex transcript; + std::string readFixtureText(const std::filesystem::path& path) { const auto size = std::filesystem::file_size(path); if (size > 16 * 1024 * 1024) @@ -85,10 +89,14 @@ void registerCallbacks(App& app, const std::filesystem::path& project, std::atom return result->json; }); app.cppFunction("test.progress", [](std::string message) { + const std::scoped_lock lock{transcript}; std::cout << "Developer integration: " << message << std::endl; }); app.cppFunction("test.report", [&passed, reported = std::move(reported)](bool success, std::string message) { - std::cout << message << std::endl; + { + const std::scoped_lock lock{transcript}; + std::cout << message << std::endl; + } passed.store(success); if (reported) reported(std::move(message)); @@ -589,8 +597,7 @@ int main(int argc, char** argv) { 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); + [[maybe_unused]] const auto requestLog = webfront::testdriver::logRequests(); if (argc != 3 && argc != 4) throw std::invalid_argument("Expected fixture directory, header output directory and optional --session, --public or --part="); if (argc == 4 && std::string_view(argv[3]) == "--session") diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index c6185c9d..e1feedaa 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -1040,7 +1040,13 @@ try { await until(() => /Preview ready/.test(devOutput) && shows('layout-one')(), 'wf dev did not start'); await writeFile('layout/value.ts', "export const value: string = 'layout-two';\n"); await poll(); - await until(shows('layout-two'), 'wf dev must reload the full-window interface'); + try { + await until(shows('layout-two'), 'wf dev must reload the full-window interface'); + } catch (error) { + throw new Error(`${error.message}; preview=${pagePreview.contentWindow.location.href}; ` + + `readyState=${pagePreview.contentDocument?.readyState}; root=${pagePreview.contentDocument?.getElementById('root')?.textContent}; ` + + `status=${button.dataset.status}; wf dev output:\n${devOutput}`); + } assert(again.state() === 'interface' && again.fills('#preview'), 'A reload must leave the terminal collapsed'); await until(() => button.dataset.status === 'ready', `The tab must show that wf dev watches: ${button.dataset.status}`); assert(/wf dev is watching/.test(button.getAttribute('aria-label')), 'The tab must name the state of wf dev'); From 846670cd6dc9f22d9b86896ca043a7305416cfa7 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:45:47 +0100 Subject: [PATCH 02/14] Keep driver frames visible and bound Linux loop wakeups (#542) --- .github/workflows/BuildAndTest.yml | 8 +- docs/FRONTENDS.md | 2 +- docs/TEST_PERFORMANCE.md | 5 ++ include/webfront/frontend/UILoop.hpp | 114 +++++++++++++++++++-------- test/cmake/DriverSessions.cmake | 2 +- test/driver/WfDriver.hpp | 23 ++++-- test/sanitizers/tsan.supp | 7 +- test/unit/UIExecutorTests.cpp | 24 ++++++ test/web/developer-specs.mjs | 8 +- 9 files changed, 148 insertions(+), 45 deletions(-) diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 909eb1ce..a648aca7 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -296,7 +296,8 @@ jobs: if: github.event_name != 'workflow_dispatch' || inputs.repeat_desktop_tests permissions: contents: read - timeout-minutes: 25 + # The explicit three-pass qualification also enables MSVC /analyze; a cold build can consume 21 minutes alone. + timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests && 60 || 25 }} strategy: fail-fast: false matrix: @@ -490,6 +491,11 @@ jobs: run: >- ctest --test-dir build-sanitizers --output-on-failure --no-tests=error --parallel 4 --output-junit "${{ github.workspace }}/build-sanitizers/test-results.xml" + - name: Stress interface loop shutdown under ThreadSanitizer + if: matrix.sanitizer == 'thread' && github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests + run: >- + ctest --test-dir build-sanitizers --output-on-failure --no-tests=error + -R 'Scenario: The system browser can run an interface-thread loop' --repeat until-fail:100 - name: Compare generated gzip streams against zlib timeout-minutes: 5 if: matrix.sanitizer == 'address-undefined' diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index e9ef7259..35fdfbcd 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -237,7 +237,7 @@ frontends without a loop). An operation that started is never interrupted, and ` | WebView2 | window message `WM_APP + 0x4C3` | | WebKitGTK | `g_idle_add_full` on the default context | | CEF | `CefPostTask(TID_UI, ...)` | -| `BrowserWithUILoopFrontend` | message-only window (Windows), run loop source (macOS), GLib idle (Linux) | +| `BrowserWithUILoopFrontend` | message-only window (Windows), run loop source (macOS), GLib eventfd watch (Linux, GLib 2.36+) | The plain `DefaultBrowserFrontend` runs no loop and has no executor. `BrowserWithUILoopFrontend` launches the page in the system browser and runs the minimal loop on the calling thread until `BrowserWithUILoopFrontend::requestStop()` (any thread); the server diff --git a/docs/TEST_PERFORMANCE.md b/docs/TEST_PERFORMANCE.md index 8289b81b..d7af582f 100644 --- a/docs/TEST_PERFORMANCE.md +++ b/docs/TEST_PERFORMANCE.md @@ -35,6 +35,11 @@ Each new realm owns its bridge connection, imports, timers, Workers, listeners a those resources. Local/session storage and enumerated IndexedDB databases are reset before the next command. The native project Store survives intentionally. Pinned and rebuilt environments retain different profiles and URLs/ports. The normal suite resets both; never point the two revisions at a shared persistent profile. +Driver session frames fill the native window while their command runs. A case verifies its viewport and receives a +rendering frame before starting work; off-screen frames can have their scripts, messages and Workers suspended by the +engine. Like the developer session, each driver session reserves four CTest processors, so another browser test does +not cover its window while it waits for rendering. + Filter the familiar CTest names with `ctest --test-dir build -R WfDriverTestFails --output-on-failure`. CTest includes the session fixture and its prerequisite project setup. For a truly isolated process per case, configure `-DWEBFRONT_TEST_SESSIONS=OFF` and use the same filter. A case that blocks consumes its session's remaining budget and the later cases then report "No result for the suite case": rerun with sessions off to find the cause. Repetition must repeat the complete fixture graph, rather than diff --git a/include/webfront/frontend/UILoop.hpp b/include/webfront/frontend/UILoop.hpp index abc49294..31742ad6 100644 --- a/include/webfront/frontend/UILoop.hpp +++ b/include/webfront/frontend/UILoop.hpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -25,7 +26,10 @@ #include #include #elif defined(__linux__) + #include #include + #include + #include #endif namespace webfront::frontend { @@ -354,18 +358,45 @@ inline void run(UIExecutorHost& host, UILoopStop& stop) { #elif defined(__linux__) +// One kernel counter per loop. Waking from another thread allocates no GLib source and cannot leave a callback +// referring to this session in the default context after run() returns. A full counter is already readable. +class WakeEvent { + int descriptor; + +public: + WakeEvent() : descriptor(::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC)) { + if (descriptor < 0) + throw std::runtime_error("UI loop: cannot create the wake event"); + } + WakeEvent(const WakeEvent&) = delete; + ~WakeEvent() { + ::close(descriptor); + } + int handle() const noexcept { + return descriptor; + } + void signal() const noexcept { + const std::uint64_t one = 1; + while (::write(descriptor, &one, sizeof(one)) < 0 && errno == EINTR) { } + } + std::uint64_t consume() const noexcept { + std::uint64_t count = 0; + while (::read(descriptor, &count, sizeof(count)) < 0 && errno == EINTR) { } + return count; + } +}; + // GLib is loaded at run time, like the WebKitGTK adapter loads its toolkit. class GLib { public: - using Object = void*; - Object (*contextDefault)() = nullptr; - Object (*loopNew)(Object, int) = nullptr; - void (*loopRun)(Object) = nullptr; - void (*loopQuit)(Object) = nullptr; - void (*loopUnref)(Object) = nullptr; - Object (*loopRef)(Object) = nullptr; - unsigned (*idleAddFull)(int, int (*)(void*), void*, void (*)(void*)) = nullptr; - void (*contextWakeup)(Object) = nullptr; + using Object = void*; + Object (*contextDefault)() = nullptr; + Object (*loopNew)(Object, int) = nullptr; + void (*loopRun)(Object) = nullptr; + void (*loopQuit)(Object) = nullptr; + void (*loopUnref)(Object) = nullptr; + unsigned (*fdAddFull)(int, int, unsigned, int (*)(int, unsigned, void*), void*, void (*)(void*)) = nullptr; + int (*sourceRemove)(unsigned) = nullptr; static const GLib& get() { static const GLib instance; @@ -388,9 +419,8 @@ class GLib { bind(module, loopRun, "g_main_loop_run"); bind(module, loopQuit, "g_main_loop_quit"); bind(module, loopUnref, "g_main_loop_unref"); - bind(module, loopRef, "g_main_loop_ref"); - bind(module, idleAddFull, "g_idle_add_full"); - bind(module, contextWakeup, "g_main_context_wakeup"); + bind(module, fdAddFull, "g_unix_fd_add_full"); + bind(module, sourceRemove, "g_source_remove"); } }; @@ -400,33 +430,55 @@ inline void run(UIExecutorHost& host, UILoopStop& stop) { if (!loop) throw std::runtime_error("UI loop: cannot create the GLib main loop"); struct Unref { - const GLib& glib; + const GLib& glib; GLib::Object loop; ~Unref() { glib.loopUnref(loop); } } unref{glib, loop}; + struct Dispatch { + const GLib& glib; + GLib::Object loop; + UIExecutorHost& host; + UILoopStop& stop; + WakeEvent wake; + } dispatch{glib, loop, host, stop, {}}; + // The watch is created, invoked and removed on the interface thread. Producers only signal the eventfd; + // the C++ host/stop locks publish the queued work, including when GLib itself is not instrumented by TSan. constexpr int defaultIdle = 200; // G_PRIORITY_DEFAULT_IDLE - host.attach([&glib, &host] { - glib.idleAddFull( - defaultIdle, - +[](void* data) -> int { - static_cast(data)->drain(); - return 0; // G_SOURCE_REMOVE - }, - &host, - nullptr); + const auto source = glib.fdAddFull( + defaultIdle, + dispatch.wake.handle(), + 1 /* G_IO_IN */, + +[](int, unsigned, void* data) -> int { + auto& state = *static_cast(data); + state.wake.consume(); + if (state.stop.requestedStop()) + state.glib.loopQuit(state.loop); + else + state.host.drain(); + return 1; // G_SOURCE_CONTINUE + }, + &dispatch, + nullptr); + if (!source) + throw std::runtime_error("UI loop: cannot watch the wake event"); + struct Remove { + const GLib& glib; + unsigned source; + ~Remove() { + glib.sourceRemove(source); + } + } remove{glib, source}; + host.attach([&dispatch] { + dispatch.wake.signal(); }); CloseGuard guard{host, stop}; - // Quitting from an idle callback happens inside the loop: a request before g_main_loop_run is not lost. Each pending - // source owns a reference to the loop (released when the source is destroyed, run or not), so one that is still queued - // when run() returns, from a second request during the exit, never reaches a freed loop. - static const auto quitLoop = +[](void* data) -> int { - GLib::get().loopQuit(data); - return 0; - }; - static const auto releaseLoop = +[](void* data) { GLib::get().loopUnref(data); }; - if (stop.arm([&glib, loop] { glib.idleAddFull(defaultIdle, quitLoop, glib.loopRef(loop), releaseLoop); })) + // CloseGuard waits for producers before removing the watch and closing the descriptor. A stop already pending + // at arm() needs no loop turn; a later one leaves the descriptor readable until the loop observes it. + if (stop.arm([&dispatch] { + dispatch.wake.signal(); + })) return; glib.loopRun(loop); } diff --git a/test/cmake/DriverSessions.cmake b/test/cmake/DriverSessions.cmake index d8f1dd80..10e63939 100644 --- a/test/cmake/DriverSessions.cmake +++ b/test/cmake/DriverSessions.cmake @@ -59,5 +59,5 @@ function(webfront_add_driver_suite group) set(lock self-build-project) endif() set_tests_properties(${group} PROPERTIES FIXTURES_REQUIRED "${ARG_REQUIRES}" FIXTURES_SETUP ${group} - RESOURCE_LOCK "${lock}") + RESOURCE_LOCK "${lock}" PROCESSORS 4) endfunction() diff --git a/test/driver/WfDriver.hpp b/test/driver/WfDriver.hpp index 8505970d..9077d838 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -206,6 +206,11 @@ inline Sources& sources() { // Real HTTP page: WebFront.js derives its WebSocket URL from location.host (srcdoc has no host). inline constexpr std::string_view suitePage = R"HTML(