diff --git a/.github/workflows/v3-package-validation.yml b/.github/workflows/v3-package-validation.yml index 6b3f3c3bc..dd4b1bce0 100644 --- a/.github/workflows/v3-package-validation.yml +++ b/.github/workflows/v3-package-validation.yml @@ -149,7 +149,7 @@ jobs: if-no-files-found: error freebsd: runs-on: ubuntu-24.04 - timeout-minutes: 180 + timeout-minutes: 240 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: freebsd_instance diff --git a/.github/workflows/v3-release-acceptance.yml b/.github/workflows/v3-release-acceptance.yml index e2fc38dd3..a54cf6c0b 100644 --- a/.github/workflows/v3-release-acceptance.yml +++ b/.github/workflows/v3-release-acceptance.yml @@ -177,8 +177,13 @@ jobs: uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: platform-Darwin-failure-evidence + # Documents only: the whole platform tree (build lanes included) + # measured 8.85 GB on this runner in run 47064150035. path: |- - ${{ runner.temp }}/platform + ${{ runner.temp }}/platform/*.json + ${{ runner.temp }}/platform/**/*.json + ${{ runner.temp }}/platform/**/*.log + ${{ runner.temp }}/platform/**/*.trs ${{ runner.temp }}/v3-toolchain ${{ runner.temp }}/prerequisites/preparation.json ${{ runner.temp }}/prerequisites/*.log @@ -254,8 +259,13 @@ jobs: uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: platform-Windows-failure-evidence + # Documents only: the whole platform tree measured 4.6 GB on this + # runner in run 47064150035 and grows with the build lanes. path: |- - ${{ runner.temp }}/platform + ${{ runner.temp }}/platform/*.json + ${{ runner.temp }}/platform/**/*.json + ${{ runner.temp }}/platform/**/*.log + ${{ runner.temp }}/platform/**/*.trs ${{ runner.temp }}/prerequisites/preparation.json ${{ runner.temp }}/prerequisites/*.log ${{ runner.temp }}/prerequisites-ci.log @@ -269,7 +279,7 @@ jobs: freebsd: runs-on: ubuntu-24.04 needs: prepare - timeout-minutes: 180 + timeout-minutes: 300 outputs: artifact_id: ${{ steps.proof.outputs.artifact-id }} artifact_digest: ${{ steps.proof.outputs.artifact-digest }} @@ -299,7 +309,37 @@ jobs: set -eu export RUNNER_TEMP=/tmp/v3-release-${{ github.run_id }}-${{ github.run_attempt }} mkdir -p "$RUNNER_TEMP/platform-evidence" - trap 'cp -R "$RUNNER_TEMP/platform" "$RUNNER_TEMP/platform-evidence/" 2>/dev/null || true; cp -R "$RUNNER_TEMP/prerequisites" "$RUNNER_TEMP/platform-evidence/" 2>/dev/null || true; cp -R "$RUNNER_TEMP/platform-evidence" ./platform-evidence' EXIT + copy_bounded_evidence() { + # Failure evidence is receipts, logs and finished bundles only: + # the previous whole-tree copies exhausted the runner disk in run + # 47189408281 (the two -O0 -g build lanes alone measure 8.25 GB, + # and retention, tar, trap copy and scp each duplicated them). + python3 - "$RUNNER_TEMP/platform" "$RUNNER_TEMP/platform-evidence/platform" <<'COPY_PY' + import shutil, sys + from pathlib import Path + source, target = Path(sys.argv[1]), Path(sys.argv[2]) + if not source.is_dir(): + sys.exit(0) + for path in sorted(source.rglob("*")): + if path.is_file() and path.suffix in (".json", ".log", ".trs", ".gz"): + relative = path.relative_to(source) + (target / relative).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target / relative) + COPY_PY + python3 - "$RUNNER_TEMP/prerequisites" "$RUNNER_TEMP/platform-evidence/prerequisites" <<'COPY_PY' + import shutil, sys + from pathlib import Path + source, target = Path(sys.argv[1]), Path(sys.argv[2]) + if not source.is_dir(): + sys.exit(0) + target.mkdir(parents=True, exist_ok=True) + for pattern in ("*.json", "*.log"): + for path in sorted(source.glob(pattern)): + if path.is_file(): + shutil.copy2(path, target / path.name) + COPY_PY + } + trap 'status=$?; trap - EXIT; copy_bounded_evidence 2>/dev/null || true; cp -R "$RUNNER_TEMP/platform-evidence" ./platform-evidence; exit "$status"' EXIT # Guest root must trust only the host checkout, including in Python's Git children. export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=safe.directory GIT_CONFIG_VALUE_0="$PWD" git_log="$RUNNER_TEMP/platform-evidence/git-provenance.log" @@ -332,6 +372,12 @@ jobs: fi test "$(node --version)" = v24.15.0 python3 -c 'import subprocess; subprocess.run(["git","--version"],check=True)' + # The native peer-policy runtime test binds 127.0.0.2 as its + # admin source address; FreeBSD only configures 127.0.0.1 on + # lo0 by default, so the alias must exist before make check. + if ifconfig lo0 >/dev/null 2>&1; then + ifconfig lo0 alias 127.0.0.2 2>/dev/null || ifconfig lo0 | grep -q '127\.0\.0\.2' + fi python3 scripts/ci-freebsd-toolchain.py --output "$RUNNER_TEMP/platform-evidence/toolchain" . "$RUNNER_TEMP/platform-evidence/toolchain/toolchain.env" python3 scripts/prepare-v3-package-ci.py --output "$RUNNER_TEMP/prerequisites" --make gmake diff --git a/ChangeLog b/ChangeLog index 766cdb7ee..271cf43f0 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,4 +1,168 @@ Version 3.0.0 - 2026-10-10 + Anchor the selected-archive freshness check to the run-level + original creation time instead of the attempt-scoped + run_started_at (verified against both attempts of run + 47593684692), because a --failed rerun legitimately re-consumes + the digest-pinned attempt-1 artifact and the attempt comparison + rejected every rerun at the download step; the artifact ID, run, + head-SHA and digest pins are unchanged and the acceptance still + rejects anything created before the run itself. + Clear the round-5 Windows residue (230/235): the behavior-parity + receipt audit resolves the platform executable suffix so a + Windows supporting-test record can match the file CreateProcess + actually executed (mingw '-o name' links produce name.exe), and + the cookie witness records and byte-binds that same file; the + fuzz runner writes sources.list through write_bytes because a + native Windows python3 turns a text-mode stdout redirect into + CRLF and left \r on every recorded source path, the compile.sh + translation uppercases the msys drive letter, translates the + -I-prefix flag form, and leaves arguments that already carry a + native drive path untouched, the reproduce.sh corpus assertion + resolves the bash-side msys paths through the same cygpath the + runner used, and the corpus symlink negative test skips with + reason where symlink creation is unavailable. + Clear the round-4 Windows residue (227/235): the WebSocket output + phase of the memory test re-saturates its parked watermark + before asserting admission stopped (the same idle-window loopback + absorption the HTTP phase hit), the cookie execution bind reads + the produced name.exe, the fuzz runner compares compile.sh under + the msys-to-native path translation its own compile.jsonl + receipts already carry, the last POSIX-script gate-runner + fixture skips with reason on Windows, the wrapper compiler + fixture replaces the Windows-absent os.execvp, the static + archive probe carries the platform .exe suffix, the PE-walker + rejection matches the audit error by type name (separate module + loads create distinct classes), and the SDK directory membership + compares file names because the msys2 interpreter preserves + input separator style in str(Path). + Port the first full Windows native make-check exposure (run + 47289018867, 213/235) and the FreeBSD websocket e2e exposure + (232/235): the four operator-new-driven suites (hpack_primitives, + qpack_field_section, server_routes_families, + task_resume_signal_lifetime) link the raw v3core archive + statically because a Windows DLL binds its own allocations to the + runtime DLL and the executable's override never reaches them + (stage-5 linkage rule); io_operation's cross-thread drain is + bounded by wall clock and drains apply's posted resume after the + applier join (Win32 Sleep granularity); native_protocol_memory + re-saturates the outbox before asserting admission stopped + (Windows loopback absorbs more than the shrunken send buffers); + forms_multipart_files anchors its mkdtemp template at + temp_directory_path instead of the Windows-nonexistent /tmp; + the quic interop symlink fixtures skip with reason where + unprivileged symlink creation is refused. + Spawn the websocket e2e fixture through the real .libs binary with + the build's DLL directories on PATH on Windows (a native + CreateProcess cannot execute the libtool wrapper, so the fixture + died in the loader before READY), surface the fixture's exit + code and stderr when READY never arrives, and restart + connections the server closed before its handshake completed in + the churn loops (the deliberately short 100ms header deadline + expired once on the loaded FreeBSD VM); all documented in + test/PORTABILITY.md. + Port the eleven Windows script-test failures to their mechanisms: + unqualified bash resolves to the System32 WSL stub (three + runners), configure injects flags into CXX so the compile driver + is shlex-split, os.killpg is guarded where absent (both gate + runners), tar members parse as PurePosixPath so /outside stays + absolute on Windows, provenance linkage containment is lexical + over the translated namespace instead of resolving the virtual + prefix under the current drive, compile-artifact identity and + the SDK query selection compare normalized separator forms, the + cookie test fixture writes bytes instead of translated text, + and the Linux-only sampler and POSIX-script fixtures skip with + reason on Windows. + Split the websocket test rig's socket includes per platform: the + unconditional in websocket_engine_helpers.hpp was + the native make-check tree's first Windows compile exposure once + the stage-18 receipt repairs let the acceptance lane reach it + (run 47189408281); the rig's only direct socket use is the + shared SO_SNDBUF shrink helper (Winsock takes char* option + values), and the upgrade test's single-syscall mirror writes + now route through pollsys::write_some like every other rig + consumer. + Retain only the verifiable platform evidence documents: the whole- + tree retention duplicated the two -O0 -g build lanes (8.249 GB + on FreeBSD) into the bundle, then again into the tarball, the + EXIT-trap copy and the recovery scp, exhausting the runner disk + after every installed and native check had passed (runs + 47064150035, 47189408281); the retained set is now the *.json + receipts, *.log/*.trs test records, receipt-referenced files + and selected tools, with the byte budget sized to that shape + (4 GiB, ~4x the ~1 GiB it measures) so three producer bundles + also fit the shared gate runner. + Bind the acceptance failure-evidence transport to the same + documents: the FreeBSD EXIT trap and the recovery scp copied + whole trees (15.8 GB artifact on the disk-fatal run), and the + Windows/Darwin failure-evidence uploads took the whole platform + directory (4.6 and 8.9 GB); receipts, logs, test records and + the finished bundle tar travel, the build lanes and provider + sources stay on the failed runner. + FreeBSD acceptance tree (two -O0 -g lanes with llvm19 debug + info, 8.249 GB across 6,220 files) outgrew the 2026-10-15 + 8 GiB bound after passing every installed and native check, + and the single bound message named neither budget; the file + count stays bounded, the byte budget now documents the + measured producer, and each bound names itself and its value + when exceeded. + Retain installed-package inspector stdout by digest in the command + records: PE/COFF objdump -p and nm output reach tens of + megabytes per binary with -g debug sections, which inflated the + Windows installed receipts (audit.json 288-712 MB, suites.json + up to 341 MB) past the 64 MiB receipt bound at package + validation, the first lane to reach it; the resolved import + graphs and the verbatim archive member symbols keep the + evidence, so the duplicated raw stdout keeps only its digest + and byte count. + Bind native listeners with SO_EXCLUSIVEADDRUSE on Winsock instead + of SO_REUSEADDR, which on Windows forcibly shares a live + listener's port: the installed-consumer rollback scenarios + observed the obstacle bind succeed and the partial-bind + rollback contract fail ("partial H2 bind was retained"); the + exclusive option keeps the POSIX restart property (a closed + listening socket carries no TIME_WAIT) while refusing every + bind onto a live listener. + Enlarge the mid-send truncation fixture past any stdio readahead: + the reopen_file cursor's FILE* buffers st_blksize bytes ahead + (32 KiB on FreeBSD UFS), so a 40 KiB payload was fully staged + before the on-disk truncate and the send legally completed; + 2 MiB owed after the parked chunk forces the shrink to + surface on every filesystem. + Rewrite the file-source test asset with checked direct syscalls + and a visible-size verification: a silently failed ofstream + open left the asset intact, so the truncated mid-send suites + legally succeeded on the original content (FreeBSD, three + runs) instead of proving the short-body protocol error. + Link the Windows network libraries into the raw static v3core + archive consumers: the QUIC interop programs bypass libtool + dependency propagation, so -lws2_32 -lmswsock -lbcrypt must + ride the LDADD after the archive on Windows. + Link the QUIC interop provider test programs with a per-host + dynamic-loader flag: empty on Windows, -ldl elsewhere. + Bound the pre-filled pipe rig payload to the kernel pipe capacity + (4096 bytes) after an 8192-byte payload hung twice on + FreeBSD, and drive the truncated-file send test to + completion with a bounded wake-and-pull loop. + Poll the QUIC interop endpoint and UDP fixture through the shared + cross-platform host helper on Windows. + Open the QUIC interop test keylog with Windows-compatible flags + instead of O_NOFOLLOW/O_CLOEXEC/fchmod. + Complete the first FreeBSD native make-check exposure: portable + process-memory measurement, GNU-make gate selection, the + loopback admin alias, per-test hang bounds and job budget. + Link the installed public TLS and HTTP/2 audit clients to Winsock on + Windows and name their executables with the platform suffix. + Resolve the Windows version-information system import in installed + package dependency audits. + Keep the HTTP/1 connection watchdog armed at a pending server drain + deadline so a stalled close handoff cannot outlive the drain budget. + Tolerate a concurrently closed borrowed registration in the Windows + reference host poll helper instead of failing the whole WSAPoll set. + Register each native executable once in Automake test evidence inventories. + Run Windows allocation-failure injection against the installed static + library and require ordinary readiness cases in both linkage lanes. + Keep PSK cancellation lookup held until owner release and avoid artificial + per-fragment scheduling delays in the TLS test transport. Avoid Windows DLL shutdown hangs by retaining the default timer service during process termination while preserving ordinary timer cleanup. Report the saved Winsock error code when host WSAPoll fails. diff --git a/configure.ac b/configure.ac index a88f8a7df..922c5c291 100644 --- a/configure.ac +++ b/configure.ac @@ -187,6 +187,20 @@ For native Windows binaries, use the MinGW64 shell instead. ;; esac +# Static OpenSSL on POSIX platforms requires the dynamic-loader library at +# link time; Windows resolves its loader through the system runtime and +# provides no libdl. +AS_IF([test "x$is_windows" = xyes], [V3_TLS_DL_LIBS=""], [V3_TLS_DL_LIBS="-ldl"]) +AC_SUBST([V3_TLS_DL_LIBS]) + +# Programs that link the raw static v3core archive bypass libtool's +# dependency propagation, and the global LDFLAGS carrying NETWORK_LIBS +# precede the objects on automake link lines, so the Windows network +# libraries must ride the program LDADD explicitly, after the archive. +# POSIX libc resolves socket symbols implicitly. +AS_IF([test "x$is_windows" = xyes], [V3_NETWORK_LIBS="$NETWORK_LIBS"], [V3_NETWORK_LIBS=""]) +AC_SUBST([V3_NETWORK_LIBS]) + # Checks for header files. AC_CHECK_HEADER([stdint.h],[],[AC_MSG_ERROR("stdint.h not found")]) AC_CHECK_HEADER([inttypes.h],[],[AC_MSG_ERROR("inttypes.h not found")]) diff --git a/docs/external-loop-contract.md b/docs/external-loop-contract.md index c2877ded7..f193e039b 100644 --- a/docs/external-loop-contract.md +++ b/docs/external-loop-contract.md @@ -121,6 +121,15 @@ the resulting protocol/transport outcome. Duplicate or spurious notifications, including events with all flags false, are permitted and do not imply additional completions. Empty batches are permitted for timers and pending library work. +A registration borrowed by a snapshot can be closed by library work at any +moment, because retaining a snapshot never extends a handle lifetime. A POSIX +host observes this as a per-entry `POLLNVAL` readiness (translated to `error` +and ignored as stale). Windows `WSAPoll` instead rejects the entire call with +`WSAENOTSOCK`; a host must treat that failure like an empty batch — dispatch, +acquire a fresh snapshot, and wait again — rather than stopping, because the +closed registration is absent from every later snapshot. The reference +`examples/host_poll.hpp` helper implements this tolerance. + Obtain an initial snapshot before waiting. After **every successful dispatch**, obtain and reconcile a fresh snapshot before waiting again. A failed dispatch may have consumed part of a batch unless the documented rejection rule says diff --git a/examples/host_poll.hpp b/examples/host_poll.hpp index b864968d6..c30fbafaf 100644 --- a/examples/host_poll.hpp +++ b/examples/host_poll.hpp @@ -102,6 +102,13 @@ inline std::vector wait( const auto ready = ::WSAPoll(fds.data(), static_cast(fds.size()), timeout(deadline)); if (ready < 0) { const int error = ::WSAGetLastError(); + // Snapshot handles are borrowed: the library may close one between + // snapshot acquisition and this call. POSIX poll reports that + // per entry as POLLNVAL; WSAPoll rejects the whole set with + // WSAENOTSOCK. An empty batch keeps the contract's spurious- + // notification allowance: the caller dispatches, re-acquires + // interests, and the closed registration is already gone. + if (error == WSAENOTSOCK) return {}; if (error != WSAEINTR) throw std::runtime_error("WSAPoll failed (WSA error " + std::to_string(error) + ")"); } #else diff --git a/scripts/audit-v3-installed-package.py b/scripts/audit-v3-installed-package.py index 260536f17..c90e3004b 100644 --- a/scripts/audit-v3-installed-package.py +++ b/scripts/audit-v3-installed-package.py @@ -139,7 +139,8 @@ def parse_otool(output, artifact): WINDOWS_SYSTEM = {'kernel32.dll', 'kernelbase.dll', 'ntdll.dll', 'msvcrt.dll', 'ucrtbase.dll', 'ws2_32.dll', 'advapi32.dll', 'bcrypt.dll', 'bcryptprimitives.dll', 'crypt32.dll', 'secur32.dll', 'user32.dll', 'iphlpapi.dll', 'winmm.dll', 'ole32.dll', 'shell32.dll', - 'userenv.dll', 'ncrypt.dll', 'gdi32.dll', 'shlwapi.dll', 'comdlg32.dll'} + 'userenv.dll', 'ncrypt.dll', 'gdi32.dll', 'shlwapi.dll', 'comdlg32.dll', + 'version.dll'} def windows_system(name): @@ -184,7 +185,10 @@ def platform_inspector(path): if platform.system() == 'Windows': if runtime(path) and windows_system(Path(path).name): return [] - return [(name, resolve_pe(name)) for name in parse_pe(run(['objdump', '-p', path]))] + # PE/COFF inspector stdout reaches tens of megabytes per binary with + # -g debug sections; the resolved import table below retains the + # evidence gates need, so the command record keeps only its digest. + return [(name, resolve_pe(name)) for name in parse_pe(run(['objdump', '-p', path], retain_output=False))] if platform.system() == 'Darwin': names = parse_otool(run(['otool', '-L', path]), path) resolved = [] @@ -401,7 +405,10 @@ def audit(prefix, build, consumer, tls, mode, provider_prefix, compiler='c++'): violations += graph_violations(native, mode, tls, 'native', policy, provider_prefix) symbols = {} for artifact, surface in [(p, 'aggregate') for p in archives] + [(native_archive, 'native')]: - output = run(['nm', str(artifact)]) + # The verbatim member symbols are retained in archive_symbols below; + # the command record keeps only its digest so the receipt respects + # the read_json size bound (COFF symbol tables are tens of MB). + output = run(['nm', str(artifact)], retain_output=False) if not output.strip(): raise AuditError('empty archive inspection: ' + str(artifact)) symbols[str(artifact)] = output diff --git a/scripts/check-v3-public-http2.py b/scripts/check-v3-public-http2.py index 2a186e258..38af737e3 100755 --- a/scripts/check-v3-public-http2.py +++ b/scripts/check-v3-public-http2.py @@ -146,8 +146,15 @@ def run(args): flags = ['--libs'] + (['--static'] if linkage == 'static' else []) libraries = shlex.split(command(['pkg-config'] + flags + ['libhttpserver'], consumer, env)) if linkage == 'static': libraries = [str(prefix / 'lib/libhttpserver.a') if f == '-lhttpserver' else f for f in libraries] - libraries += ['-pthread', '-Wl,-rpath,' + str(prefix / 'lib'), '-Wl,-rpath,' + str(provider / 'lib')] + shlex.split(args.sanitize) - executable = consumer / linkage + # Winsock is a system library on Windows and lives in libc on the + # POSIX targets, whose runtime search needs the explicit rpath. + if os.name == 'nt': + libraries += ['-lws2_32', '-lmswsock', '-lbcrypt'] + else: + libraries += ['-pthread', '-Wl,-rpath,' + str(prefix / 'lib'), '-Wl,-rpath,' + str(provider / 'lib')] + libraries += shlex.split(args.sanitize) + suffix = '.exe' if os.name == 'nt' else '' + executable = consumer / (linkage + suffix) provenance = compile_probe(args.compiler, [consumer / 'http2_consumer.cpp'], cflags + shlex.split(args.sanitize), libraries, executable, command, env, source, build, prefix, False) validate_public(True, provenance['dependencies'], prefix, source, build) @@ -155,7 +162,7 @@ def run(args): violations = audit.graph_violations(graph, 'strict', args.tls, 'aggregate', audit.load_policy(), provider) require(not violations, 'dependency audit: ' + repr(violations)) if args.tls == 'yes': - example = consumer / (linkage + '-example') + example = consumer / (linkage + '-example' + suffix) example_compile = compile_probe(args.compiler, [consumer / 'http2.cpp'], cflags + shlex.split(args.sanitize), libraries, example, command, env, source, build, prefix, False) example_graph = audit.dependency_graph([str(example)]); check_linkage(example_graph, linkage, prefix) diff --git a/scripts/check-v3-public-tls.py b/scripts/check-v3-public-tls.py index b356db3dc..1dd0d8d21 100755 --- a/scripts/check-v3-public-tls.py +++ b/scripts/check-v3-public-tls.py @@ -330,17 +330,21 @@ def run(args): if identity == 'client-valid': chain += (fixtures / 'client-intermediate.pem').read_bytes() (fixtures / (identity + '-chain.pem')).write_bytes(chain) - independent = consumer / 'independent-client' + independent = consumer / ('independent-client' + ('.exe' if os.name == 'nt' else '')) + # tls_client.cpp dials raw sockets: Winsock is a system library on + # Windows and lives in libc on the POSIX targets. + independent_system = ['-lws2_32'] if os.name == 'nt' else [] command_log([args.compiler, '-std=c++20', '-I' + str(args.provider_prefix / 'include'), consumer / 'tls_client.cpp', '-L' + str(args.provider_prefix / 'lib'), - '-Wl,-rpath,' + str(args.provider_prefix / 'lib'), '-lssl', '-lcrypto', '-o', independent], consumer, env) + '-Wl,-rpath,' + str(args.provider_prefix / 'lib'), '-lssl', '-lcrypto'] + + independent_system + ['-o', independent], consumer, env) receipt['independent_client'] = dict(executable=str(independent), sha256=hashlib.sha256(independent.read_bytes()).hexdigest(), dependencies=audit.dependency_graph([str(independent)])) check('libhttpserver' not in json.dumps(receipt['independent_client']['dependencies']), 'client links server library') command_log([independent, 'fixtures', fixtures], consumer, env, timeout=10) (fixtures / 'malformed.pem').write_text('malformed certificate') (fixtures / 'malformed-key.pem').write_text('malformed private key') - command_log([args.provider_prefix / 'bin/openssl', 'pkey', '-in', fixtures / 'acme-key.pem', '-aes-256-cbc', '-passout', 'pass:task194-test-only', '-out', fixtures / 'encrypted-key.pem'], consumer, env) + command_log([args.provider_prefix / 'bin' / ('openssl.exe' if os.name == 'nt' else 'openssl'), 'pkey', '-in', fixtures / 'acme-key.pem', '-aes-256-cbc', '-passout', 'pass:task194-test-only', '-out', fixtures / 'encrypted-key.pem'], consumer, env) (fixtures / 'extra.pem').write_bytes((fixtures / 'acme.pem').read_bytes() * 2) for name in ('mismatch-key', 'past-expiry', 'late-expiry'): shutil.copyfile(fixtures / 'acme.pem', fixtures / (name + '.pem')) diff --git a/scripts/lib/compiler_sdk.py b/scripts/lib/compiler_sdk.py index 6fdd77161..86d3c0b77 100644 --- a/scripts/lib/compiler_sdk.py +++ b/scripts/lib/compiler_sdk.py @@ -108,8 +108,14 @@ def verify(context, compiler): require(query['argv'] == context['compiler_argv'] + ['-###', '-x', 'c++', '-c', os.devnull, '-o', os.devnull], 'different SDK query command') sdk, metadata, driver, target = _selected(query) - require((str(sdk), str(metadata), str(driver), target) == - (context['sdk'], context['metadata']['path'], context['driver']['path'], context['target']), 'changed SDK query selection') + # The driver echoes its own separator style; compare normalized paths so a + # backslash query selection matches forward-slash retained records (msys2 + # python preserves unix separators in str(Path)). + def same_path(left, right): + return os.path.normpath(str(left)) == os.path.normpath(str(right)) + require(same_path(sdk, context['sdk']) and same_path(metadata, context['metadata']['path']) + and same_path(driver, context['driver']['path']) and target == context['target'], + 'changed SDK query selection') for record in [context['metadata'], context['driver'], *context['compiler_inputs'].values()]: verify_artifact(record) data = bytes.fromhex(context['metadata_hex']) diff --git a/scripts/lib/package_integration.py b/scripts/lib/package_integration.py index f2462e87f..71ca28df4 100644 --- a/scripts/lib/package_integration.py +++ b/scripts/lib/package_integration.py @@ -38,6 +38,11 @@ def run_suites(inventory, host, mode, linkage, directory, prefix, source, build, receipt = dict(name=name, tls=mode, linkage=linkage, execution=definition.get('execution', 'installed-library')) try: flags = cflags + ['-DHTTPSERVER_COMPILATION', '-I' + str(source / 'src'), '-I' + str(source / 'test')] + if host == 'Windows' and linkage == 'shared' and definition.get('windows_static_cases'): + # An executable's operator new cannot interpose PE DLL imports. + # The installed static lane retains every fault-injection case. + flags += ['-DLHS_TEST_DLL_LINKAGE'] + receipt['windows_static_cases'] = definition['windows_static_cases'] for macro, value in (('TLS_TEST_DIR', source / 'test'), ('PARITY_TRANSCRIPT_DIR', source / 'test/parity/transcripts'), ('PARITY_DATA_ROOT', source / 'test'), ('HTTP2_CORPUS_DIR', source / 'test/conformance/http2')): flags += ['-D' + macro + '="' + value.as_posix() + '"'] @@ -61,9 +66,7 @@ def run_suites(inventory, host, mode, linkage, directory, prefix, source, build, started = time.monotonic() output = command([str(executable)], source / 'test', env, timeout=180, allow_failure=True) receipt.update(matrix.suite_result(output, command.records[-1]['exit'])) - missing = set(definition.get('required_cases', [])) - set(receipt['case_names']) - if missing: - raise ValueError('required suite cases absent: ' + ', '.join(sorted(missing))) + matrix.check_suite_cases(definition, host, linkage, receipt['case_names']) receipt.update(duration=time.monotonic() - started, log=command.records[-1]['log']) if name in ('tls_io_loopback', 'native_http1_tls_parity'): matrix.check_tls_witnesses(output, inventory['platforms'][host]) diff --git a/scripts/lib/package_matrix.py b/scripts/lib/package_matrix.py index 3a86b8508..82c80b07e 100644 --- a/scripts/lib/package_matrix.py +++ b/scripts/lib/package_matrix.py @@ -150,6 +150,18 @@ def suites(inventory, platform, tls): return {name: inventory['suites'][name] for name in names} +def check_suite_cases(definition, host, linkage, observed): + required = set(definition.get('required_cases', [])) + windows_static = set(definition.get('windows_static_cases', [])) + if not windows_static <= required: + raise ValueError('Windows static cases must also be required suite cases') + if host == 'Windows' and linkage == 'shared': + required -= windows_static + missing = required - set(observed) + if missing: + raise ValueError('required suite cases absent: ' + ', '.join(sorted(missing))) + + def suite_result(output, status): output = output.replace('\r\n', '\n') tests = re.findall(r'^(\d+) tests executed$', output, re.M) @@ -169,7 +181,11 @@ def suite_result(output, status): def check_linkage(graph, linkage, prefix): libraries = [Path(node['id']) for node in graph['nodes'] if re.match(r'libhttpserver(?:[.-])', Path(node['id']).name.lower())] - if linkage == 'shared' and (not libraries or any(not p.is_relative_to(prefix.resolve()) for p in libraries)): + # Both the node ids and the prefix arrive through the same provenance + # translation (a comparison-only namespace for foreign-platform paths), so + # containment is decided lexically; resolving the translated prefix would + # anchor it under the current drive on Windows and break every comparison. + if linkage == 'shared' and (not libraries or any(not p.is_relative_to(prefix) for p in libraries)): raise ValueError('shared integration did not resolve installed library') if linkage == 'static' and libraries: raise ValueError('static integration loaded a shared/import library') diff --git a/scripts/lib/release_checks.py b/scripts/lib/release_checks.py index 2a77d88bf..054f06298 100644 --- a/scripts/lib/release_checks.py +++ b/scripts/lib/release_checks.py @@ -4,7 +4,7 @@ import importlib.util import json import math -from pathlib import Path +from pathlib import Path, PurePosixPath import re import tarfile @@ -75,7 +75,11 @@ def verify_library_files(build, prefix): def extract_archive(archive, directory): with tarfile.open(archive) as stream: members = stream.getmembers() - names = [Path(m.name) for m in members] + # Archive member names are tar (POSIX) paths; parsing them as the host + # Path makes "/outside" non-absolute on Windows (no drive) and lets the + # traversal guard miss it, so parse with PurePosixPath like + # scripts/lib/release_ci.py does. + names = [PurePosixPath(m.name) for m in members] need(names and len(members) < 20000 and sum(m.size for m in members) < 512 * 1024 * 1024, 'archive exceeds release extraction bounds') need(all(not p.is_absolute() and '..' not in p.parts and '\\' not in m.name diff --git a/scripts/lib/release_ci.py b/scripts/lib/release_ci.py index 3ac3f4406..89d4dbc4b 100644 --- a/scripts/lib/release_ci.py +++ b/scripts/lib/release_ci.py @@ -94,12 +94,15 @@ def validate_request(root, commit, version): subprocess.run([bash, str(root / 'scripts/validate-version.sh'), version], cwd=root, check=True) -def verify_download(archive, metadata, run, expected, expected_digest, destination): +def verify_download(archive, metadata, run, run_created, expected, expected_digest, destination): require(str(metadata['id']) == expected['artifact_id'] and metadata['expired'] is False, 'wrong/expired artifact ID') require(str(metadata['workflow_run']['id']) == expected['run_id'] and metadata['workflow_run']['head_sha'] == expected['workflow_head'], 'artifact from another workflow source/run') require(str(run['id']) == expected['run_id'] and str(run['run_attempt']) == expected['run_attempt'] and run['repository']['full_name'] == expected['repository'] and run['head_sha'] == expected['workflow_head'], 'wrong repository/source/run attempt') - require(datetime.fromisoformat(metadata['created_at']) >= datetime.fromisoformat(run['run_started_at']), 'artifact belongs to an earlier run attempt') + # The attempt endpoint's timestamps are attempt-scoped, so a --failed + # rerun legitimately re-consumes the digest-pinned attempt-1 artifact; + # the freshness anchor is the run-level original creation time. + require(datetime.fromisoformat(metadata['created_at']) >= datetime.fromisoformat(run_created), 'artifact belongs to an earlier run') from release_artifact import sha256 digest = 'sha256:' + sha256(archive) require(digest == expected_digest == metadata['digest'], 'downloaded artifact digest mismatch') diff --git a/scripts/lib/release_package_provenance.py b/scripts/lib/release_package_provenance.py index 11ba91a4c..bcf2b2b25 100644 --- a/scripts/lib/release_package_provenance.py +++ b/scripts/lib/release_package_provenance.py @@ -28,11 +28,17 @@ def validate_compile(compiled, linkage, identity, artifacts, commands): public_units = ('examples/', 'test/installed/', 'test/examples/') members = {digest for name, digest in identity['archive']['members'].items() if name.startswith(public_units)} + # Identity is decided on normalized forms: on Windows the recorded keys and + # a freshly resolved path can carry different separator styles (msys2 + # python preserves unix separators), so exact string membership misses. + lookup = {os.path.normcase(os.path.normpath(key)): key for key in artifacts} + def bound(path, digest=None): path = str(Path(path).resolve()) - require(path in artifacts, 'unbound compile artifact: ' + path) - verify_artifact(artifacts[path]) - require(digest is None or artifacts[path]['sha256'] == digest, 'compile digest differs: ' + path) + key = lookup.get(os.path.normcase(os.path.normpath(path))) + require(key is not None, 'unbound compile artifact: ' + path) + verify_artifact(artifacts[key]) + require(digest is None or artifacts[key]['sha256'] == digest, 'compile digest differs: ' + path) for path, digest in sources.items(): require(digest in members, 'source outside supplied archive') diff --git a/scripts/lib/release_platform.py b/scripts/lib/release_platform.py index 6b44e1c1b..488d83006 100644 --- a/scripts/lib/release_platform.py +++ b/scripts/lib/release_platform.py @@ -11,7 +11,17 @@ PLATFORMS = ('FreeBSD', 'Darwin', 'Windows') MAX_FILES = 20000 -MAX_BYTES = 8 * 1024 * 1024 * 1024 +# The retained tree is the evidence documents (*.json receipts, *.log/*.trs +# test records) plus the selected tools and receipt-referenced files; the +# -O0 -g build lanes stay out (run-v3-release-ci.py collects the set). +# Runs 47064150035/47189408281 measured the whole-tree shape this replaced: +# 8.249 GB / 6,220 files on FreeBSD (two lanes with llvm19 debug info), +# which exhausted the runner disk once retention, tar, trap copy and scp +# each duplicated it, and a 16 GiB-bound bundle cannot fit the shared gate +# runner three times. The document/tool/referenced shape measures ~1 GiB +# per producer (darwin's full-tree bundle tarred to 0.9 GB compressed); +# keep 4x headroom above it. +MAX_BYTES = 4 * 1024 * 1024 * 1024 def read_document(path): @@ -53,7 +63,8 @@ def retain(destination, platform, receipt, paths): for path in sorted(paths): logical = str(path) value = record(path); total += value['bytes'] - require(len(catalog) < MAX_FILES and total <= MAX_BYTES, 'platform evidence exceeds bounds') + require(len(catalog) < MAX_FILES, 'platform evidence exceeds the file-count bound: ' + str(MAX_FILES)) + require(total <= MAX_BYTES, 'platform evidence exceeds the byte bound: ' + str(total)) name = 'bytes/' + value['sha256'] target = destination / name if not target.exists(): shutil.copyfile(path, target) @@ -153,7 +164,7 @@ def package_origin(root, origin, read_json, read_text, expected, platform, read_ receipt = suites[name] observed = matrix.suite_result(read_text(receipt['log']), 0) require(all(receipt.get(k) == v for k, v in observed.items()), 'stale platform suite summary') - require(set(definition.get('required_cases', [])) <= set(observed['case_names']), 'pruned platform suite') + matrix.check_suite_cases(definition, platform, linkage, observed['case_names']) return result diff --git a/scripts/lib/resource_limits_probe_test.py b/scripts/lib/resource_limits_probe_test.py index d707b75ed..0cf9e43c5 100644 --- a/scripts/lib/resource_limits_probe_test.py +++ b/scripts/lib/resource_limits_probe_test.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 """Task-local plateau receipt checks; no network dependencies required.""" +import os import unittest from pathlib import Path from unittest.mock import patch @@ -17,6 +18,7 @@ def test_current_memory_growth_is_rejected(self): def test_bounded_idle_window_is_accepted(self): validate_window({'cpu_seconds': .1, 'wall_seconds': 1, 'rss_before': 1048576, 'rss_after': 1048576}) +@unittest.skipIf(not hasattr(os, 'sysconf'), 'the probe samples /proc and os.sysconf, which do not exist off Linux') class Sampler(unittest.TestCase): def read_pair(self, raw, precise): fields = ['S'] + ['0'] * 10 + ['17', '23'] + ['0'] * 10 diff --git a/scripts/run-v3-behavior-parity.py b/scripts/run-v3-behavior-parity.py index 0acb1f4f4..5ecb37dd3 100644 --- a/scripts/run-v3-behavior-parity.py +++ b/scripts/run-v3-behavior-parity.py @@ -363,7 +363,11 @@ def matching_execution(command, suite, log): if not isinstance(proof, dict) or not cwd.is_absolute() or not argv or proof.get('suite') != suite: return False binary = (cwd / argv[-1]).resolve() - if binary.name != suite or not binary.is_file(): + # CreateProcess resolves an extensionless command to .exe, and a + # mingw '-o name' link produces exactly that file; POSIX keeps the + # extensionless name. + names = (suite, suite + '.exe') if os.name == 'nt' else (suite,) + if binary.name not in names or not binary.is_file(): return False if len(argv) != 1: # The sole supported launcher is the explicitly recorded peer_policy affinity. diff --git a/scripts/run-v3-http3-full-gates.py b/scripts/run-v3-http3-full-gates.py index 3d9fb1fb4..05e635ef7 100644 --- a/scripts/run-v3-http3-full-gates.py +++ b/scripts/run-v3-http3-full-gates.py @@ -20,6 +20,9 @@ ROOT = Path(__file__).resolve().parents[1] INVENTORY = ROOT / 'test/conformance/http3/full-gates.json' +# Generated Makefiles need GNU make; FreeBSD's default `make` is BSD +# make, so prefer gmake where it exists and fall back to `make`. +MAKE = shutil.which('gmake') or 'make' OFF_SUITES = '''http3_frame http3_settings http3_connection http3_headers http3_exchange http3_streaming http3_cancellation http3_qpack http3_qpack_scheduling http3_drain http3_fuzz_replay qpack_primitives qpack_field_section qpack_dynamic_table @@ -166,11 +169,19 @@ def run_process(command, cwd, output, timeout, limit=MAX_ARTIFACT): row['failure'] = str(error) finally: if process and process.poll() is None: - os.killpg(process.pid, signal.SIGTERM) + # os.killpg does not exist on Windows (no process groups); the + # direct child is all this runner spawns, so terminate/kill it. + if hasattr(os, 'killpg'): + os.killpg(process.pid, signal.SIGTERM) + else: + process.terminate() try: process.wait(timeout=5) except subprocess.TimeoutExpired: - os.killpg(process.pid, signal.SIGKILL) + if hasattr(os, 'killpg'): + os.killpg(process.pid, signal.SIGKILL) + else: + process.kill() process.wait(timeout=5) row['returncode'] = process.returncode row['duration_seconds'] = round(time.monotonic() - start, 3) @@ -374,10 +385,10 @@ def build_configuration(build, tls, sanitized): def native_stage(build, suites, directory, fixtures=False): directory.mkdir(mode=0o700) - commands = [checked(['make', '-j4', '-C', build / 'src'], ROOT, directory / 'build')] + commands = [checked([MAKE, '-j4', '-C', build / 'src'], ROOT, directory / 'build')] targets = suites + (['http3_udp_fixture', 'http3_semantic_parity_fixture', 'quic_interop_endpoint'] if fixtures else []) selection = [name + '=' + ' '.join(targets) for name in ('TESTS', 'check_PROGRAMS', 'noinst_PROGRAMS')] - commands.append(checked(['make', '-j4', '-C', build / 'test', *selection, *targets], ROOT, directory / 'test-build')) + commands.append(checked([MAKE, '-j4', '-C', build / 'test', *selection, *targets], ROOT, directory / 'test-build')) results = run_native_suites(build, suites, directory / 'tests') results['commands'] = commands tls = '#define NATIVE_V3_TLS' in (build / 'config.h').read_text() diff --git a/scripts/run-v3-protocol-fuzz.sh b/scripts/run-v3-protocol-fuzz.sh index 07b52554f..3796744b3 100755 --- a/scripts/run-v3-protocol-fuzz.sh +++ b/scripts/run-v3-protocol-fuzz.sh @@ -175,7 +175,9 @@ PYTHON if [ "$target" = http3_engine ] || [ "$target" = qpack ] || [ "$target" = http2_engine ] || [ "$target" = quic_state ] || [ "$target" = quic_recovery ] || [ "$target" = quic_tls_callbacks ]; then # Compile configured native project sources with the same instrumentation; # linking an ordinary library would leave the engine uninstrumented. - python3 - "$root/src/Makefile.am" "$target" > "$build/$target/sources.list" <<'PYTHON' + # write_bytes: a native Windows python3 translates a text-mode stdout + # redirect to CRLF, which would leave \r on every recorded path. + python3 - "$root/src/Makefile.am" "$target" "$build/$target/sources.list" <<'PYTHON' import pathlib, re, sys names = ['v3core'] if sys.argv[2] == 'quic_tls_callbacks': @@ -190,7 +192,7 @@ for line in pathlib.Path(sys.argv[1]).read_text().splitlines(): found.append(source) if not found: raise SystemExit('missing native instrumentation sources') -print('\n'.join(dict.fromkeys(found))) +pathlib.Path(sys.argv[3]).write_bytes('\n'.join(dict.fromkeys(found)).encode() + b'\n') PYTHON while IFS= read -r source; do sources+=("$root/src/$source"); done < "$build/$target/sources.list" fi diff --git a/scripts/run-v3-quic-interop.py b/scripts/run-v3-quic-interop.py index a1929a4bb..e6375700a 100644 --- a/scripts/run-v3-quic-interop.py +++ b/scripts/run-v3-quic-interop.py @@ -280,11 +280,19 @@ def run_bounded(command, cwd, stdout, stderr, timeout): try: return process.wait(timeout=timeout) except subprocess.TimeoutExpired: - os.killpg(process.pid, signal.SIGTERM) + # os.killpg does not exist on Windows (no process groups); the + # direct child is all this runner spawns, so terminate/kill it. + if hasattr(os, 'killpg'): + os.killpg(process.pid, signal.SIGTERM) + else: + process.terminate() try: process.wait(timeout=10) except subprocess.TimeoutExpired: - os.killpg(process.pid, signal.SIGKILL) + if hasattr(os, 'killpg'): + os.killpg(process.pid, signal.SIGKILL) + else: + process.kill() process.wait(timeout=10) raise RuntimeError("upstream runner deadline exceeded") diff --git a/scripts/run-v3-release-ci.py b/scripts/run-v3-release-ci.py index 8516adc08..a847c0fa5 100755 --- a/scripts/run-v3-release-ci.py +++ b/scripts/run-v3-release-ci.py @@ -91,7 +91,15 @@ def platform_proof(args): origin['native'][mode] = dict(build=str(build), tests=tests) native = checks.automake_result(build, platform.system()) result = checks.counts(result['tests'] + native['tests'], result['checks'] + native['checks']) - files = [p for p in args.output.rglob('*') if p.is_file() and '__pycache__' not in p.parts] + # Retain the verifiable evidence documents, not the multi-gigabyte -O0 -g + # build lanes: every catalog read in release_platform.py is a *.json + # receipt, a *.log/*.trs test record, or an explicitly referenced file + # (referenced_files below walks every receipt). Copying whole lanes (the + # 8.25 GB FreeBSD tree of run 47064150035) exhausted the runner disk + # again in run 47189408281 once retention, tar, trap copy and scp each + # duplicated it. + files = [p for p in args.output.rglob('*') if p.is_file() + and '__pycache__' not in p.parts and p.suffix in ('.json', '.log', '.trs')] # Preserve explicit tools/provider inputs referenced outside the platform tree. files += [args.provider_prefix / 'include/openssl/opensslv.h', args.archive] for receipt_path in package.rglob('*.json'): @@ -146,11 +154,12 @@ def download(args): endpoint='repos/'+expected['repository']+'/actions/artifacts/'+args.artifact_id metadata=json.loads(subprocess.check_output(['gh','api',endpoint],text=True)) run=json.loads(subprocess.check_output(['gh','api','repos/'+expected['repository']+'/actions/runs/'+expected['run_id']+'/attempts/'+expected['run_attempt']],text=True)) + run_origin=json.loads(subprocess.check_output(['gh','api','repos/'+expected['repository']+'/actions/runs/'+expected['run_id']],text=True)) archive=args.output.parent/('artifact-'+args.artifact_id+'.zip') with archive.open('xb') as output: subprocess.run(['gh','api',endpoint+'/zip'],stdout=output,check=True) digest=args.digest if args.digest.startswith('sha256:') else 'sha256:'+args.digest - verify_download(archive,metadata,run,expected,digest,args.output) + verify_download(archive,metadata,run,run_origin['created_at'],expected,digest,args.output) def main(): diff --git a/scripts/test-v3-ci-workflows.py b/scripts/test-v3-ci-workflows.py index 158603856..8e44db298 100755 --- a/scripts/test-v3-ci-workflows.py +++ b/scripts/test-v3-ci-workflows.py @@ -353,6 +353,42 @@ def test_successful_evidence_recovery_retains_payload_layout_and_copyback(self): self.assertEqual((evidence / 'platform/FreeBSD.tar.gz').read_bytes(), b'platform proof') self.assertFalse((evidence / folder).exists()) + def test_acceptance_trap_bounds_evidence_to_documents_and_finished_bundles(self): + # Run 47189408281 exhausted the runner disk: even with bounded + # retention, the trap copied (and the recovery scp'd) the whole + # two-lane build trees and the provider sources. + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + runner = root / 'runner' + lane = runner / 'platform/matrix/tls-no/build/test' + lane.mkdir(parents=True) + (lane / 'websocket_drain_test.o').write_bytes(b'build-lane intermediate') + (lane / 'websocket_drain_test.trs').write_text(':test-result: PASS\n') + (lane / 'test-suite.log').write_text('# TOTAL: 1\n') + (runner / 'platform/matrix/tls-no/summary.json').write_text('{"status": "passed"}\n') + (runner / 'platform/artifact-identity.json').write_text('{}\n') + (runner / 'platform/FreeBSD.tar.gz').write_bytes(b'finished bundle') + prerequisites = runner / 'prerequisites/openssl-3.5.9' + prerequisites.mkdir(parents=True) + (prerequisites / 'Configure').write_text('provider source tree') + (runner / 'prerequisites/preparation.json').write_text('{}\n') + (runner / 'prerequisites/prepare-00.log').write_bytes(b'provider build log\n') + run, _ = self.guest_run(self.workflows[1], runner) + preamble = run.split('# Guest root', 1)[0] + result = subprocess.run(['sh', '-eu', '-c', preamble + '\nexit 1'], cwd=root, + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + evidence = root / 'platform-evidence' + for kept in ('platform/FreeBSD.tar.gz', 'platform/artifact-identity.json', + 'platform/matrix/tls-no/summary.json', + 'platform/matrix/tls-no/build/test/test-suite.log', + 'platform/matrix/tls-no/build/test/websocket_drain_test.trs', + 'prerequisites/preparation.json', 'prerequisites/prepare-00.log'): + self.assertTrue((evidence / kept).is_file(), 'missing bounded evidence: ' + kept) + for dropped in ('platform/matrix/tls-no/build/test/websocket_drain_test.o', + 'prerequisites/openssl-3.5.9/Configure'): + self.assertFalse((evidence / dropped).exists(), 'build-lane bulk leaked into evidence: ' + dropped) + def test_early_inspection_receipt_survives_package_and_archive_failure_recovery(self): spec = importlib.util.spec_from_file_location('installed_failure_fixture', ROOT / 'scripts/test-v3-installed-consumer.py') fixture = importlib.util.module_from_spec(spec) diff --git a/scripts/test-v3-installed-consumer.py b/scripts/test-v3-installed-consumer.py index 977611e8d..2f4aceb76 100644 --- a/scripts/test-v3-installed-consumer.py +++ b/scripts/test-v3-installed-consumer.py @@ -1580,5 +1580,32 @@ def test_nonzero_shutdown_is_failure(self): self.assertEqual(8, json.loads(receipt.read_text())['exit']) +class SuiteCaseCoverageTest(unittest.TestCase): + def setUp(self): + self.definition = dict(required_cases=['ordinary', 'allocation_failure'], + windows_static_cases=['allocation_failure']) + + def test_windows_dll_requires_all_ordinary_cases(self): + matrix.check_suite_cases(self.definition, 'Windows', 'shared', ['ordinary']) + with self.assertRaisesRegex(ValueError, 'ordinary'): + matrix.check_suite_cases(self.definition, 'Windows', 'shared', []) + + def test_static_proof_requires_all_allocation_failure_cases(self): + for host in ('Windows', 'Linux', 'Darwin', 'FreeBSD'): + with self.subTest(host=host), self.assertRaisesRegex(ValueError, 'allocation_failure'): + matrix.check_suite_cases(self.definition, host, 'static', ['ordinary']) + matrix.check_suite_cases(self.definition, host, 'static', ['ordinary', 'allocation_failure']) + + def test_other_shared_platforms_retain_allocation_failure_coverage(self): + for host in ('Linux', 'Darwin', 'FreeBSD'): + with self.subTest(host=host), self.assertRaisesRegex(ValueError, 'allocation_failure'): + matrix.check_suite_cases(self.definition, host, 'shared', ['ordinary']) + + def test_windows_static_cases_must_also_be_required(self): + self.definition['required_cases'] = ['ordinary'] + with self.assertRaisesRegex(ValueError, 'static.*required'): + matrix.check_suite_cases(self.definition, 'Windows', 'static', ['ordinary']) + + if __name__ == '__main__': unittest.main() diff --git a/scripts/test-v3-installed-package.py b/scripts/test-v3-installed-package.py index 6543a2763..b37da474a 100644 --- a/scripts/test-v3-installed-package.py +++ b/scripts/test-v3-installed-package.py @@ -369,8 +369,15 @@ def enumerate_alias(prefix): self.assertEqual([record['argv'] for record in inspected], [['nm', str(selected[0])], ['nm', str(native)]]) self.assertFalse(selected[0].samefile(native)) - self.assertEqual(inspected[1]['stdout'], 'used.o:\n U _fixture_runtime\n') - self.assertEqual(inspected[0]['stdout'], 'unused.o:\n U _MHD_start_daemon\n') + # The command record keeps only its digest; archive_symbols retains + # the verbatim member symbols for each inspected archive. + for record, expected in ((inspected[1], 'used.o:\n U _fixture_runtime\n'), + (inspected[0], 'unused.o:\n U _MHD_start_daemon\n')): + self.assertNotIn('stdout', record) + self.assertEqual(record['stdout_sha256'], hashlib.sha256(expected.encode()).hexdigest()) + self.assertEqual(record['stdout_bytes'], len(expected.encode())) + self.assertEqual(receipt['archive_symbols'][str(selected[0])], 'unused.o:\n U _MHD_start_daemon\n') + self.assertEqual(receipt['archive_symbols'][str(native)], 'used.o:\n U _fixture_runtime\n') self.assertEqual(receipt['violations'], ['legacy archive symbol: MHD_start_daemon']) def test_no_policy_mode_accepts_legacy_closure(self): diff --git a/scripts/test-v3-packaged-adapters.py b/scripts/test-v3-packaged-adapters.py index 4e532526b..45f55e157 100755 --- a/scripts/test-v3-packaged-adapters.py +++ b/scripts/test-v3-packaged-adapters.py @@ -32,7 +32,9 @@ def setUp(self): self.root = Path(self.temp.name).resolve() self.source = self.root / 'source' self.source.mkdir() - (self.source / 'unit.cpp').write_text('public source\n') + # Bytes, not text: write_text would translate the newline on Windows + # and the archived member digest would diverge from the recorded one. + (self.source / 'unit.cpp').write_bytes(b'public source\n') self.archive = self.root / 'source.tar.gz' with tarfile.open(self.archive, 'w:gz') as archive: archive.add(self.source, arcname='libhttpserver-3.0.0') @@ -401,7 +403,10 @@ def test_local_clang_darwin_driver_dry_run_selects_exact_controlled_sdk(self): self.assertIsNotNone(context, 'real Clang Darwin driver dry run must produce one selected context') self.assertEqual(compiler_sdk.verify(context, compiler), str(metadata)) self.assertEqual(context['metadata_hex'], metadata.read_bytes().hex()) - self.assertEqual(list(sdk.iterdir()), [metadata]) + # str(Path) preserves the input separator style on the msys2 + # interpreter, so WindowsPath equality across styles is False; + # the SDK directory must hold exactly the metadata file name. + self.assertEqual([entry.name for entry in sdk.iterdir()], [metadata.name]) def test_sdk_context_is_rechecked_in_actual_compile_working_directory(self): import compiler_sdk @@ -709,6 +714,7 @@ def test_h3_lifecycle_keeps_its_lazy_h2_client_binding(self): self.assertNotIn('H2Client', inspect.getclosurevars(runner.scenarios).unbound, 'aggregate/semantic HTTP2 witnesses cannot execute with an unbound client') + @unittest.skipIf(os.name == 'nt', 'the probe fixture is a POSIX shebang script; Windows TLS lanes drive PE probe executables') def test_tls_configuration_commands_do_not_overwrite_profile_logs(self): import os from package_commands import Commands @@ -764,7 +770,20 @@ def test_tls_negative_controls_require_decoded_rejection_and_exact_client(self): def test_runtime_inspection_rejects_unrelated_executable_as_shared_consumer(self): from release_package_provenance import validate_runtime identity = dict(source=str(Path(__file__).parent.parent), prefix=str(self.root / 'prefix'), tls='no') - with self.assertRaises(ValueError): validate_runtime(sys.executable, 'shared', identity) + if os.name == 'nt': + # The PE walker rejects the unrelated executable first (its own + # runtime DLLs do not resolve from an arbitrary directory); the + # shared-consumer linkage check only runs on ELF/Mach-O hosts. + with self.assertRaises(Exception) as rejected: + validate_runtime(sys.executable, 'shared', identity) + # validate_runtime loads its own audit module instance, so the + # raised AuditError class object differs from a locally imported + # one; match on the type name. + self.assertTrue(isinstance(rejected.exception, ValueError) + or type(rejected.exception).__name__ == 'AuditError', + repr(rejected.exception)) + else: + with self.assertRaises(ValueError): validate_runtime(sys.executable, 'shared', identity) def test_installed_h1_gate_is_public_and_dependency_free_to_import(self): runner_path = Path(__file__).parent / 'check-v3-public-http1.py' @@ -818,7 +837,8 @@ def test_static_archive_fixture_uses_selected_quoted_compiler(self): marker = self.root / 'compiler-commands.jsonl' wrapper.write_text('import json, os, sys\n' 'with open(' + repr(str(marker)) + ', "a") as stream: stream.write(json.dumps(sys.argv[1:]) + "\\n")\n' - 'argv = ' + repr(compiler) + '\nos.execvp(argv[0], argv + sys.argv[1:])\n') + 'argv = ' + repr(compiler) + '\n' + 'import subprocess\nraise SystemExit(subprocess.call(argv + sys.argv[1:]))\n') result = subprocess.run([sys.executable, str(Path(__file__).resolve()), 'AdapterContracts.test_unused_selected_static_archive_cannot_supply_link_identity'], env=dict(os.environ, CXX=shlex.join([sys.executable, str(wrapper)])), @@ -855,11 +875,12 @@ def test_unused_selected_static_archive_cannot_supply_link_identity(self): from package_commands import Commands from package_integration import compile_probe command = Commands(directory) + probe = directory / ('static.exe' if os.name == 'nt' else 'static') compiled = compile_probe(identity['compiler'], [unit], ['-I' + str(Path(identity['prefix']) / 'include')], - libraries, directory / 'static', command, os.environ, self.source, + libraries, probe, command, os.environ, self.source, Path(identity['build']), Path(identity['prefix']), False) commands = command.records - self.assertEqual(subprocess.run([str(directory / 'static')]).returncode, 2) + self.assertEqual(subprocess.run([str(probe)]).returncode, 2) identity['archive']['members']['test/installed/consumer.cpp'] = compiled['sources'][str(unit)] identity['package'] = {p: bench.artifact(p)['sha256'] for p in identity['package']} artifacts = {str(p): bench.artifact(p) for p in directory.iterdir() if p.is_file()} @@ -874,8 +895,8 @@ def test_unused_selected_static_archive_cannot_supply_link_identity(self): # The same real consumer succeeds when the selected archive contributes. commands[1]['argv'].remove(libraries[0]) subprocess.run(commands[1]['argv'], check=True, capture_output=True) - self.assertEqual(subprocess.run([str(directory / 'static')]).returncode, 1) - compiled['artifact_sha256'] = bench.artifact(directory / 'static')['sha256'] + self.assertEqual(subprocess.run([str(probe)]).returncode, 1) + compiled['artifact_sha256'] = bench.artifact(probe)['sha256'] artifacts = {str(p): bench.artifact(p) for p in directory.iterdir() if p.is_file()} if sdk: artifacts.update({path: bench.artifact(path) for path in compiler_sdk.artifact_paths(sdk)}) diff --git a/scripts/test-v3-platform-ci.py b/scripts/test-v3-platform-ci.py index 27f7b3805..b4f73c039 100755 --- a/scripts/test-v3-platform-ci.py +++ b/scripts/test-v3-platform-ci.py @@ -73,6 +73,7 @@ def test_verified_source_contains_all_runtime_build_inputs(self): self.assertEqual((source / part / 'input').read_bytes(), b'x') self.assertFalse((source / 'clang').exists()) + @unittest.skipIf(os.name == 'nt', 'the FreeBSD compiler wrapper and its fixture compiler are POSIX executable scripts') def test_compiler_wrapper_keeps_headers_and_runtime_through_clean_environment(self): selector = self.selector() with tempfile.TemporaryDirectory() as directory: @@ -296,6 +297,28 @@ def test_archive_retains_compound_compilers_and_spaced_make_exact_bytes(self): self.assertEqual(catalog.path(str(path)).read_bytes(), path.read_bytes()) self.assertEqual(catalog.path(str(path.resolve())).read_bytes(), path.read_bytes()) + @unittest.skipIf(os.name == 'nt', 'retention fixture uses POSIX executable aliases') + def test_archive_retention_excludes_build_lane_intermediates(self): + # Runs 47064150035/47189408281 measured the whole-tree retention at + # 8.25 GB (two -O0 -g lanes) and it exhausted the runner disk; the + # retained set is the evidence documents, receipt-referenced files + # and selected tools only. + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.native_checks(root, selected_tools=True, retain_tools=True) + sys.path.insert(0, str(ROOT / 'scripts/lib')) + from release_platform import Catalog + catalog = Catalog(root / 'output/bundle/FreeBSD') + for document in (root / 'output/commands.json', root / 'output/matrix/child.json'): + with self.subTest(document=document): + self.assertTrue(catalog.path(str(document)).is_file()) + for intermediate in (root / 'output/matrix/tls-no/build/test/native_linkage', + root / 'output/matrix/tls-no/build/test/Makefile'): + with self.subTest(intermediate=intermediate): + self.assertTrue(intermediate.is_file()) + with self.assertRaisesRegex(ValueError, 'missing catalog entry'): + catalog.path(str(intermediate)) + @unittest.skipIf(os.name == 'nt', 'FreeBSD audit fixtures require POSIX scripts and GNU make') def test_explicit_sdk_reaches_both_later_make_checks(self): for inherited in (None, '/unselected/sdk'): diff --git a/specs/tasks/FEATURE-ci-v3-runtime-green.md b/specs/tasks/FEATURE-ci-v3-runtime-green.md index 3117565eb..4b3db538d 100644 --- a/specs/tasks/FEATURE-ci-v3-runtime-green.md +++ b/specs/tasks/FEATURE-ci-v3-runtime-green.md @@ -1,6 +1,6 @@ # FEATURE-ci-v3-runtime-green -Status: Stages 1 and 3 implemented with focused proof; complete CI and remaining supported runtime repairs are pending. Groundwork validation is explicitly prohibited until FULL CI IS GREEN. +Status: Stages 1, 3, 4, 5 and 6 implemented with focused proof; complete CI and remaining supported runtime repairs are pending. Groundwork validation is explicitly prohibited until FULL CI IS GREEN. Base: `v3` at `8f3083977f49706e66cefbb3ee8b6f6685469719`. Working branch: `task/FEATURE-ci-v3-runtime-green`. User requested integration into `v3` before full CI completion; retain incomplete verification explicitly. Plan: primary checkout `.groundwork-plans/FEATURE-ci-v3-runtime-green-plan.md`. @@ -70,3 +70,224 @@ Integrate the focused repairs and ChangeLog update now. Full CI remains incomple Groundwork validation has not run and stays deferred until full CI is green. This integration does not mark the overall CI repair complete or reopen closed diagnostic batches. Draft PR #382 carries the original working-branch runs. + +## Stage 4: PSK test fixture scheduling (2026-10-27) + +- [x] Read the completed, previously authorized diagnostic receipts; keep their budgets closed. +- [x] Preserve the native Darwin RED: 14 tests/313 checks, three failures; held TLS1.3 cancellation callback already returned, and certificate-default TLS1.3 handshake timed out. +- [x] Release the held cancellation lookup explicitly after assertions and close; bound the callback wait to five seconds for failure cleanup. +- [x] Drain ready fragmented transport work and yield while waiting for provider work, preserving the original fragments and every deadline/assertion. +- [x] Reproduce the real certificate fixture timeout under coarse scheduling, then pass the same regression and all 14 PSK tests/313 checks. +- [x] Pass changed-file cpplint and diff checks. +- [ ] Native current-source CI, including Darwin selected archive acceptance. +- [ ] Resolve the remaining Windows external-loop failure from supported evidence. +- [ ] Close the FreeBSD selected-archive timeout gate with actual evidence. + +Evidence and commands: primary checkout `.debug/v3-ci-native-repairs-PJFEkn/journal.md`. +Current c1 installed matrix passed Linux, Darwin, FreeBSD; Windows failed. Native/fuzz, CodeQL and Verify Build passed. Source-equivalent selected archive remains failed; no current-source green claim. + +The diagnostic Windows four-test program failed one of 52 checks in 0.741 seconds with WSAPoll error10038 before stop was requested. Two bounded new socket-only probes on local Windows11 returned POLLNVAL successfully; they do not establish the Server2022 failure cause. No poll error suppression or guessed production fix was applied. Previous capture budgets remain closed. + +Fixture root cause: the cancellation rescue unconditionally released after250ms, before the owner could assert cancellation under slower scheduling. The transport also slept after every41/73-byte fragment, charging scheduler delays to real handshake deadlines. A minimal real TLS1.3 certificate fixture with1ms sleeps delayed to15ms failed at2089ms/outcome8(timeout); draining progress first passed at625ms. An intermediate full coarse-scheduling check still failed two held/capacity assertions because idle sleeps could expire the400ms pre-lookup deadline. Yielding while idle preserved that deadline and passed all313 checks in1.029seconds, with zero skips. The100ms owner-responsiveness assertion, cancellation/timeout/capacity/late-result assertions, bounded drains and all protocol settings remain unchanged. Only test source changed; production TLS is unchanged. + +Setup evidence is retained honestly: system OpenSSL was rejected before selecting the existing3.5.9 provider; the first suite launch used build-root cwd instead of test cwd and failed fixture path lookup. Correcting cwd, as required by the generated relative TLS_TEST_DIR, produced the meaningful behavioral check. Neither setup failure justifies a source workaround. No broad baseline or Groundwork validation was run. + +## Stage 5: Windows allocator fault-injection fixture linkage + +- [x] Identify the current PR383 failed program from one bounded selected artifact assessment (3,891,726 range bytes; no full ZIP or original execution). +- [x] Prove that executable operator-new replacement does not affect Windows DLL allocation, and that static linkage delivers the intended fault. +- [x] Keep all 22 ordinary readiness cases against the installed Windows DLL; require all 27 cases, including the five unchanged allocation-failure cases, against the installed static archive. +- [x] Make the required case names explicit in the inventory and reject every missing static fault case. Other platforms retain their original fault coverage. +- [x] Pass native Windows focused DLL22/438 and static27/486 gates, Linux28/497, 28 package coverage/matrix checks, changed-file lint and diff checks. +- [ ] Full exact-source CI with the corrected installed linkage profiles. + +Current PR383 package job122630892885 passed native62 in4.812276s and external4 in0.572681s, then failed external_readiness_adapter27/486 with13 failures, all inside five allocation-failure cases. The assertion expecting bad_alloc was false and regular work completed. The PSK change cannot affect these allocation boundaries; this repair is within the accepted overall CI goal. Member CRC/SHA are verified; the full212MB ZIP digest is metadata-only. Assessment is closed. + +A tiny native PE fixture reproduces the cause: executable allocation throws under its replacement operator new, DLL-owned allocation does not (exit1/0.362s). Linking the same owner object into the executable makes both throw (exit0/0.309s). Microsoft documents per-module DLL import binding: https://learn.microsoft.com/en-us/cpp/build/linking-an-executable-to-a-dll?view=msvc-170 . The chosen correction scopes allocation injection to linkage where it can actually reach the owner. Artificially throwing in the caller would not exercise the backend; a new production allocator hook or loader patch is unnecessary. + +Only Windows shared compilation selects LHS_TEST_DLL_LINKAGE; this omits allocator replacement and the five fault registrations from that executable. All five original assertion bodies remain unchanged and mandatory in the installed static lane. The inventory names all27 ordinary/static cases, and the receipt validator requires the22 DLL cases or all27 static cases. No test skip or failed/empty receipt is accepted. Every original C++ assertion line is preserved. The other platforms keep all five fault cases in both linkage lanes. + +Fresh current-source focused Windows backend DLL (16 owning translation units) passed22/438 in0.899s; matching static executable passed27/486 in1.237s, both zero skips and retired. Linux passes28/497 including its descriptor-zero case. Removing any one of the five fault names from the static receipt is rejected. Python coverage/matrix tests pass28 cases. Native setup initially missed net_address.cpp at link; adding that existing owning translation unit corrected the test build without a production workaround. Context is qualified local Windows11/cached LLVM23.1.4/GCC15.2 headers and retained runtime DLLs, not Server2022/MSYS2 CI. Evidence: primary `.debug/v3-ci-native-repairs-PJFEkn/allocator-linkage/`. + +## Approved Windows capture closure + +User approved exact430fa17e publication and ONE1/60 Windows original external-loop capture. Run40635371672 completed once:4tests/52checks/zero skips, exit0 in0.4701966s, retirement confirmed, stderr empty. Budget is CLOSED; no retry or remaining-time authority. This establishes nonreproduction in that context, not a fix or independence of the earlier WSAPoll10038 failure. The diagnostic branch remains NEVER MERGE. Only a proven repair may change production behavior. + +Stage5 receipt-import closure: source review found the selected-archive importer independently required all cases in each linkage. A new real receipt-bundle regression was RED with `valid DLL/static split rejected: pruned platform suite`. Reusing the same coverage validator fixes this producer/consumer mismatch while still rejecting missing static fault cases. All14 platform-bundle tests and changed Python syntax/diff checks pass. This is part of the same proven setup repair; native binaries are unchanged, so their focused evidence is carried without repetition. Current-source CI remains pending. + +## Stage 6: unique native Automake inventory + +- [x] Preserve Darwin archive failure `duplicate/empty native suite inventory` after its native commands completed. +- [x] Reproduce the exact producer inventory command against a real configured Makefile: TLSyes271 entries/266 unique, five duplicated executables. +- [x] Remove only four redundant TESTS additions; keep each executable in check_PROGRAMS, which already feeds TESTS recursively. +- [x] Regenerate actual Automake/configured Makefiles and verify unique inventories in both TLS modes: yes266/266, no235/235. All five affected executables remain registered exactly once. +- [ ] Full current-source archive evidence with this registration correction. + +The duplicated names are http_cookie, consumer_v3_cookie, consumer_v3_cookie_wire, protocol_limits and protocol_compression. TESTS already equals $(check_PROGRAMS); the extra TESTS += lines counted them twice. The strict receipt duplicate rejection is unchanged. No executable, assertion, script test, protocol setting or failure deadline was removed. This four-line configuration repair is proved by the actual producer command, not a source-text mirror test or a broad baseline rerun. + +Evidence: primary `.debug/v3-ci-native-repairs-PJFEkn/native-inventory/`. Autoreconf succeeded with existing AC_OUTPUT/.PHONY warnings. Initial config.status invocation used the source directory instead of its configured build directory and failed before any native execution; rechecking/regenerating in the correct build directory fixed setup. No unrelated source or generated tracked file changed. + +Current9c92 Windows package job122646921257 fails earlier at the public shared external consumer: exit6, captured stderr WSAPoll error10038. The selected820-byte process receipt was verified within a closed2,581,790-byte range assessment; no full artifact or original program ran. It contains no failed-call slot/state values. The earlier approved external4 capture remains CLOSED/PASS4/52/nonreproduction, and does not authorize running the distinct public consumer. No guessed polling or shutdown suppression was applied. A fresh consumer-specific bounded capture proposal is needed if further native diagnosis is required. + +## Stage 7: Windows WSAPoll borrowed-closure tolerance and HTTP/1 drain-deadline watchdog (2026-10-30) + +- [x] Correlate all retained Windows failures (external four-test suite twice, public shared consumer exit6) with the approved DIAG capture: the host loop dies on "WSAPoll failed (WSA error 10038)" while dispatch never failed and stopping was false. +- [x] Root-cause by contract analysis, not a new capture: `interest_snapshot` handles are borrowed and "retaining a snapshot does not extend any handle lifetime"; the library closes registrations under its registry mutex and never republishes dead records, so WSAENOTSOCK can only mean a snapshot handle closed between snapshot and WSAPoll entry (handle-value reuse makes it WSAENOTSOCK on busy runners and POLLNVAL on idle probes, reconciling the closed local probes). +- [x] Repair `examples/host_poll.hpp`: WSAENOTSOCK returns an empty batch (the contract's spurious-notification allowance); every reference caller re-acquires interests after each dispatch, and dead records are pruned from the next snapshot, so the loop provably progresses. All other WSAPoll failures still throw; POSIX POLLNVAL handling is unchanged. Document the host obligation in `docs/external-loop-contract.md`. +- [x] Root-cause the 2026-10-28 macOS/Darwin external4 drain stall (idle keep-alive connection never closed after `begin_drain`; host silent for the full 10s budget; remaining 1): `watchdog_terminal_locked()` treated the quiesce close mark as terminal, but HTTP/1 enforces the server drain deadline only through the watchdog (`enforce_timeout` is the sole HTTP/1 `scope_.expire_if_due` caller), so a stalled close handoff had no deadline enforcement left. +- [x] Repair: the close mark no longer retires the watchdog while a server drain deadline is pending; the deadline joins `plan_watchdog_locked` candidates through the existing `add_protocol_deadlines_locked` entry and fires through the unchanged global-expiry path. Deadline-less closes (request_close, response-Connection: close) stay terminal as before. +- [x] RED/GREEN regression `quiesce_with_drain_deadline_keeps_watchdog_armed` (unstarted engine, deterministic plan sample; deadline-less case pins unchanged terminal behavior) plus behavioral `quiesce_with_drain_deadline_still_closes_promptly`. RED verified against unfixed source, GREEN against the repair, five consecutive clean runs. +- [x] Linux focused gates: connection_engine 42/0 (x5), external_http1_e2e 4/0, websocket_drain 3/0, http1_websocket_upgrade 17/0, native_http1_e2e 62/0, external_readiness_adapter 28/0, examples/external_event_loop builds and serves; changed-file cpplint and `git diff --check` pass. +- [ ] Full exact-source CI on the working branch (mingw64/macOS/FreeBSD lanes remain nonlocal and deferred to CI). + +## Stage 8: FreeBSD job timeout (2026-10-30) + +- [x] Evidence: the 2026-10-26 acceptance FreeBSD job completed its native proof at 2h59m45s (57 seconds under the 180-minute job timeout); the 2026-10-28 package-validation FreeBSD job was cancelled by the 180-minute timeout at 3h3m mid-run. The workload (libc++ 20.1.8 runtime build + provider + both TLS lanes on a 2-CPU VM) legitimately straddles the limit. +- [x] Raise only the freebsd job `timeout-minutes` from 180 to 240 in both `v3-package-validation.yml` and `v3-release-acceptance.yml`; every other job keeps its existing timeout. `test-v3-package-workflow.py` (4/4) and `test-v3-ci-workflows.py` (31/31) pass. +- [ ] Full FreeBSD CI evidence with the corrected budget. + +The 2026-10-26 FreeBSD tls-yes `check-v3-public-http2.py` shared-external failure ("no retired connection generation captured", one occurrence) is retained as an open flake: the consumer's `stale` check depends on the single-point `snapshot` having captured the soon-to-retire H2 connection's published registration, and the saved pair in that run was still live at `stale` time. No consumer change is made without a recurrence; the 2026-10-30 runs will decide. + +Full local `make check -j1` (TLS=no, g++ 15.2, WSL2): 232/235 pass, 2 platform skips (iocp/kqueue), 1 FAIL `quic_flow_control` (12 checks expecting ceiling-rejection throws). Byte-identical failures with stage 7 reverted and at b71192c9, so pre-existing and unrelated to this repair; CI builds this test with clang where it passes. Recorded as a local g++ environment observation, not a regression. + +## Stage 9: Windows audit client closure (2026-10-30) + +- [x] The 2026-10-30 mingw64 package run (job c8dc2d64) passed every external/installed suite in both linkages for the first time (stage 7 repair holding) and advanced to `check-v3-public-tls.py`, which failed walking the Python TLS client: `AuditError: unresolved PE import: version.dll` from `_ssl.pyd` -> `libpython3.14.dll` (its import table lists VERSION.dll; api-ms-win-* names already match the existing pattern rule). +- [x] Verified against the real MSYS2 mingw64 packages (python 3.14.9-1, openssl 3.6.5-1, libgcc 16.2.0-6, winpthreads, libstdc++): after adding `version.dll` to `WINDOWS_SYSTEM`, the full `_ssl` client closure resolves -- remaining names are WINDOWS_SYSTEM entries or MSYS2 runtime DLLs that the same run's own recorded suite graphs already resolve through `V3_PACKAGE_DLL_DIRS`. The mingw-built integration closures (from the run's suites.json) import only allowlisted system DLLs. +- [x] One-line allowlist addition in `scripts/audit-v3-installed-package.py`; `version.dll` is a documented System32 component (version-information APIs). `test-v3-installed-package.py` 60/60; `test-v3-installed-consumer.py` 97/97 (one unrelated compile-timing flake on the first local run, clean on rerun). +- [ ] Full mingw64 CI evidence past the client audit. + +## Stage 10: Windows public audit client linkage (2026-10-30) + +- [x] Evidence: the 2026-10-30 mingw64 package job (124062430922) and the Windows acceptance job (124062636691) both advanced past every earlier gate (installed suites, traffic cells, compiled operations and the Python TLS client audit of stage 9) and failed at the same place: linking the independent TLS client in `check-v3-public-tls.py`, with `undefined reference to __imp_WSAStartup/__imp_socket/__imp_htons/__imp_htonl/__imp_connect/__imp_closesocket` (tls_client.cpp already carries its own `_WIN32` Winsock path; only the link line lacked the system library). +- [x] Repair in `scripts/check-v3-public-tls.py`: the independent client is named with the platform `.exe` suffix and linked with `-lws2_32` on `os.name == 'nt'` (POSIX targets unchanged), and the provider `openssl` tool is invoked with its explicit `.exe` name on Windows, matching `run-v3-release-ci.py`. +- [x] Same-class parity repair in `scripts/check-v3-public-http2.py` (preemptive, code-audit driven, not yet exercised on Windows): consumers and examples get the `.exe` suffix and the `ws2_32/mswsock/bcrypt` system libraries replace the POSIX-only `-pthread`/`-rpath` line, matching the `check-v3-installed-consumer.py`/`check-v3-public-tls.py` convention; runtime DLL resolution stays on the `runtime_environment` PATH/V3_PACKAGE_DLL_DIRS mechanism. Local gates: `test-v3-public-http2.py` 6/6, `py_compile` on both scripts. +- [ ] Full mingw64/Windows CI evidence past the public TLS client link. + +## Stage 11: first FreeBSD native make-check exposure (2026-10-30) + +- [x] Evidence (5.1GB failure artifact 12993618134, run 41055662147, analyzed in full): the FreeBSD acceptance lane passed the entire installed matrix (both TLS lanes incl. public-tls and public-http2) in ~18 minutes, then reached `gmake check` for the first time ever (every earlier acceptance run died earlier: the Oct-26 runs at the http2 stale flake/copyback, the Oct-28 runs at the 180-min timeout). The first `make check` ran the full 7200s command deadline and was killed with only `response_sources` still unfinished: test 24 `threaded_pipe_sends_single_winner` started and never printed a result. Four real test failures were also recorded: `response_definition` (checks 846/847, `file_send_truncated_mid_send_fails`, completed in 2.58ms with `done==0`), `native_protocol_memory` ("process memory measurement unavailable" — no FreeBSD branch), `consumer_v3_peer_policy_runtime` (line 86 = bind/connect of the 127.0.0.2 admin source: FreeBSD has no 127/8 loopback alias by default), and `integ/http3_full_gate_runner_test.py` (`make -j4` in the gate runner is BSD make on FreeBSD; needs gmake). +- [x] Repairs with proven causes: `native_protocol_memory_test.cpp` gains FreeBSD (kinfo_proc sysctl) and Windows (GetProcessMemoryInfo) resident-memory branches — the Windows acceptance make check needs the same branch; `run-v3-http3-full-gates.py` selects gmake when present (GNU-make Makefiles, BSD default make); the freebsd acceptance VM run script adds-or-verifies the `lo0` 127.0.0.2 alias (no-op where `ifconfig lo0` is absent, e.g. the Linux workflow tests). +- [x] Hang bound: `test/timeout-wrapper.sh` (EXTRA_DIST, `LOG_COMPILER`) wraps every native test with `timeout -k 60 600` where timeout(1) exists, so a recurrence cannot consume a whole CI make-check budget; hosts without timeout (macOS default) run exactly as before. +- [x] Budget: freebsd acceptance `timeout-minutes` 240 → 300 (observed: ~95 min prepare with the pinned-Node source build + ~18 min matrix + make check ×2 + evidence recovery). +- [x] Local gates: fresh worktree configure/build; `native_protocol_memory` passes under the new LOG_COMPILER wrapper; `test-v3-ci-workflows.py` 31/31, `test-v3-platform-ci.py` 20/20, `test-v3-http3-full-gates.py` 1/1; changed-file cpplint and YAML parse pass. +- [ ] Open flakes (no repair without a recurrence, per the standing http2-stale precedent): `response_sources` test 24 hang (one occurrence; the claim/close guard is a single atomic CAS and `pull_handle`'s fread cannot block on a pipe whose write end is closed — mechanism unexplained) and `response_definition` checks 846/847 (coroutine did not complete after the mid-send truncation). Both pass on Linux/macOS; the next FreeBSD run with bounded hangs decides. +- [ ] Full FreeBSD acceptance CI evidence. + +## Stage 12: Windows TLS-on interop keylog portability (2026-10-30) + +- [x] Evidence (mingw64 job 124232738670, Windows acceptance job 124233097485, both at b080f744): with stage 10 in place the mingw64 package lane printed `PASS installed consumer native TLS=no` — the entire installed tls-no matrix including public-tls and public-http2 passed on Windows for the first time. The tls-yes lane then failed building `libquic_interop_provider_a`: `src/detail/tls_session.cpp:127/129` use `O_NOFOLLOW`, `O_CLOEXEC` and `fchmod`, none of which exist on Windows. +- [x] Repair: `open_keylog()` gains a `_WIN32` branch using `_O_NOINHERIT` (the close-on-exec analog) and dropping `fchmod` (the creating open already owns the file); the POSIX branch is unchanged. This is the only site in `src/` using those identifiers (`quic_tls_session.cpp` is clean). POSIX-branch syntax check with the interop define passes locally; cpplint clean. +- [ ] Full Windows tls-yes CI evidence past the interop provider build (SNI/rotation scenarios and the tls-yes public audits remain first-exposure). + +## Stage 13: Windows QUIC fixture polls (2026-10-30) + +- [x] Evidence (mingw64 job at db7cefec, 41112829610): with the stage-12 keylog fix the tls-yes `make -j2` advanced past `libquic_interop_provider_a` and failed at the next noinst program: `test/integ/quic_interop_endpoint.cpp:3: 'poll.h' file not found`. +- [x] Repair: the interop endpoint's hand-rolled poll loop now goes through the shared `examples/host_poll.hpp` helper (WSAPoll on Windows, the same contract every external-loop consumer uses), preserving the connection-deadline folding and the one-second park bound; `chmod` of the log directory is POSIX-only. `test/integ/http3_udp_fixture.cpp` — the next `poll.h` includer in the same build set — takes a `_WIN32` branch on the same helper while its POSIX stdin-poll path stays byte-identical (the stdin command channel is driven only by the POSIX parity lanes). +- [x] Local gates: both files pass cpplint and `g++ -std=c++20 -fsyntax-only` with the full build flags; `integ/http3_full_gate_runner_test.py` 27/27 (it drives the gate runner that builds and runs these fixtures). +- [ ] Full Windows tls-yes CI evidence past the QUIC fixtures. + +## Stage 14: Windows parity pipe rig restoration (2026-11-30) + +- [x] Evidence (runs 41120424056/41120424110 at 5b2db29a): mingw64 package tls-yes `make -j2` and the Windows acceptance installed matrix fail at `behavior_profiles.hpp:141` (`no member named 'filled_pipe'`) compiling `integ/http3_udp_fixture.o` and `integ/http2_tls_fixture.o`; darwin acceptance tls-no make check failed `integ/native_websocket_e2e.sh` (1/235; the db7cefec run failed a different test — `consumer_v3_cookie_wire` — which passed at 20:04) and freebsd failed `response_sources` plus one more FAIL beyond the 3000-byte tail window (# FAIL: 2). All artifacts of the 2026-10-30 runs are expired (14-day retention); evidence retained at `.debug/v3-ci-green-VSvXxx/runtime-green-stage14/` (journal, raw failed logs). +- [x] Local darwin reproduction: fresh scratch worktree full build; `native_websocket_e2e.sh` passes standalone (exit 0, fixture binds port 0 and reports `get_bound_port(0)` — no fixed-port mechanism). Recorded as an open flake under the standing no-repair-without-recurrence rule; a different test failed in the prior run, so this is not a recurrence of one defect. Fresh `test-suite.log` evidence to be captured from the next acceptance run within artifact retention. +- [x] Root cause: `test/unit/response_source_rig.hpp` declared `filled_pipe` only under `#ifndef _WIN32` (POSIX `::pipe`; the gap was documented as tracked in test/PORTABILITY.md), while `behavior_profiles.hpp:141` and `native_http1_parity_test.cpp:152` use it unconditionally. The tls-no Windows matrix passed at b080f744, so exposure is exactly the TLS-gated set reached by the tls-yes full-tree `make` (`check-v3-installed-consumer.py` line 78). The live parity drivers (`behavior_parity_h2.py:80`, `behavior_parity_h3.py:76`, called from `run-v3-release-gates.py`) drive the `file_resp` profile at runtime, so `/pipe` must WORK on Windows, not merely compile. Production owned_pipe reads via `std::fread` (`src/response_sources.cpp:214`) — portable. +- [x] Repair implements the restoration plan already recorded in test/PORTABILITY.md: platform shims in the rig — Windows `_pipe(fds, max(4096, payload+1), _O_BINARY)`/`_write`/`_close`/`_fdopen(..., "rb")` from ``/``, POSIX `::pipe`/`::write`/`::close`/`::fdopen(fd, "rb")` — with a single unguarded class body; `behavior_profiles.hpp` and `native_http1_parity_test.cpp` unchanged. The Windows pipe buffer is sized to the payload because the constructor writes the entire payload before any reader exists (a `_pipe` write beyond the buffer would block forever). +- [x] Local gates: `response_sources`, `response_definition`, `native_http1_parity` pass in a fresh scratch-worktree build (macOS arm64); both previously failing TUs (`http3_udp_fixture.cpp`, `http2_tls_fixture.cpp`) syntax-check clean with the fixture CPPFLAGS against the edited rig; cpplint and `git diff --check` clean. The `_WIN32` branch was not compiled locally (no mingw toolchain on this host); recorded honestly, CI compiles it. +- [x] Audit the remaining TLS-gated Windows first-exposure compile set (stage-14 journal): exactly two more unguarded mingw64 blockers, both repaired on the same push. `test/integ/http2_tls_fixture.cpp` (zero `_WIN32` guards; missed the stage-13 treatment its sibling received) ported onto the production `detail::pollsys` primitives — native_socket_t/poll_slot/k_readable/k_writable/poll_call/read_some/write_some/accept_one/set_nonblocking/close_socket/ensure_winsock — with identical status mapping (`recv==0`/`EPIPE`/`ECONNRESET` → drop; `EAGAIN` → continue; `EINTR` now retried inside the pollsys calls, equivalent) and the stdin command channel POSIX-only per the stage-13 precedent (it is driven only by `run-v3-release-gates.py` parity lanes, which no CI lane invokes). `test/support/quic_interop_files.cpp` (+ header, also in the unconditional tls-no `quic_interop_files` check program) gains Windows branches: validated root path + `GetFileAttributes` REPARSE_POINT refusal (the O_NOFOLLOW analog) replacing the O_DIRECTORY dir fd and `openat`, `_open(_O_RDONLY|_O_BINARY|_O_NOINHERIT)` per file, and a sequential single-thread `_lseeki64`/`_read`/restore `pread` emulation; POSIX branches byte-identical. The audit also determined `test/parity/v2_fixture.cpp` is compiled by NO make target (only its header is in noinst_HEADERS), so its `::pipe` is not an exposure, and all other TLS-gated sources (25+ programs, src TLS library, parity/support headers) scanned clean. +- [x] Local gates (audit repairs): both ported files syntax-check clean on POSIX with the fixture/support CPPFLAGS; the tls-no `quic_interop_files` program rebuilds and passes (exit 0) against the ported source; cpplint clean on all four changed files; `git diff --check` clean. The `_WIN32` branches were not compiled locally (no mingw toolchain); recorded honestly, CI compiles them. +- [ ] Full mingw64/Windows tls-yes CI evidence past the fixtures. +- [ ] Fresh darwin/freebsd acceptance evidence for the open flakes. + +## Stage 15: dynamic-loader link flag and FreeBSD make-check repairs (2026-12-01) + +- [x] Evidence (run 46508507388 acceptance + run 46508507514 package, both at c3b235a8): mingw64 and windows failed linking `quic_interop_endpoint.exe` with `cannot find -ldl` (the next first-exposure blocker after stage 13/14); freebsd tls-no `make check` failed exactly two tests — `response_sources` exit 124 (the stage-11 wrapper's `timeout -k 60 600` kill) hung at test 24 `threaded_pipe_sends_single_winner` again, and `response_definition` `file_send_truncated_mid_send_fails` checks 846/847 (`done==0` after the wake round). darwin and every other workflow were green. Full `test-suite.log` retrieved from artifact 15434253566 (`platform-FreeBSD-failure-evidence`, 5.1 GB) into external evidence storage. +- [x] `response_sources` hang mechanism: the rig constructor writes the whole payload through a blocking fd before any reader exists, so the payload must fit the kernel pipe capacity. FreeBSD's default is 8 KiB and test 24 was the only pipe payload at that boundary (8192; every other pipe payload ≤ 4096: 3000/128 passed on the same VM). 2/2 occurrences (2026-10-30 and 2026-11-30) satisfy the standing no-repair-without-recurrence rule. Repair: payload 4096 (2x margin; the race semantics need only an identical body across the four threads) and the rig documents the POSIX payload bound beside the stage-14 Windows sizing note. +- [x] `response_definition` checks 846/847: every library path (`pull_file` on any read outcome, executor posting, spawn delivery) reaches the spawn callback within one drain-and-pump round, verified against the LLVM 20 libc++ filebuf internals (≤ 4092-byte refills, eofbit set on partial serves) and a local probe that reproduced the macOS stale-tail-plus-eof behavior. The observed `done==0` needs the repair to be a robustifier, not a claimed mechanism: a bounded wake-and-pull drive (checked first drain unchanged, 8 rounds) tolerates a one-pull-later truncation surfacing or one extra executor round; a permanent stall still fails both assertions with the same evidence. The next FreeBSD run decides. +- [x] Windows `-ldl`: `configure.ac` derives `V3_TLS_DL_LIBS` from the existing `is_windows` host classification (empty on mingw/msys/cygwin, `-ldl` elsewhere) and `quic_interop_tls_LDADD` (inherited by `quic_interop_endpoint`) uses the substitution. POSIX branch verified in a fresh scratch worktree (`V3_TLS_DL_LIBS = -ldl` in the generated test/Makefile); the mingw64 empty branch was not compiled locally (no mingw toolchain), recorded honestly, CI compiles it. +- [x] Local gates (macOS arm64 scratch worktree at f821d40a): bootstrap, configure (no doxygen flag), `response_sources` 30/304 checks green ×3, `response_definition` 32/311 checks green ×3, `native_http1_parity` green; cpplint clean on all three touched files; `git diff --check` clean; `test-v3-http3-full-gates.py` 1/1; ChangeLog entries added. Script tests on this host: `test-v3-ci-workflows.py` 30/31 and `test-v3-platform-ci.py` 11/20 — the failures are environmental (Apple BSD make lacks `--eval`, system python lacks `hashlib.file_digest`, a fixture git invocation) and the same single workflows failure reproduces at c3b235a8 in a throwaway worktree, so pre-existing; the Linux CI lane runs these green. +- [ ] Full exact-source CI on the working branch (mingw64 tls-yes build, Windows acceptance, FreeBSD make check past both repairs). + +## Stage 16: Windows raw-archive Winsock linkage and the FreeBSD truncation fixture (2026-12-02) + +- [x] Evidence (runs 46731744600 package + 46731744909 acceptance, both at the b3ae3e95 merge preview 7819ff62): mingw64 tls-yes `make -j2` and the Windows acceptance in-tree build both fail linking `quic_interop_endpoint.exe` — undefined `__imp_inet_ntop/getsockopt/WSAIoctl/WSASocketW/WSARecvFrom/WSASendTo/WSARecv/WSASend/setsockopt/getpeername` from `io_iocp_backend.o` and `net/address.cpp` inside the raw `src/.libs/libhttpserver_v3core.a`. darwin acceptance and macos package never ran: GitHub-hosted runner-acquisition failures ("not acquired by Runner of type hosted", macOS arm64 capacity) — infrastructure, not code. FreeBSD tls-no `make check` failed 1/235 (`response_definition`, `file_send_truncated_mid_send_fails`, checks at lines 858/860, done==1 but outcome not protocol_error and `end_calls()==1`). +- [x] Windows root cause: `quic_interop_tls_LDADD` is the only link line that takes the raw static v3core archive, bypassing libtool dependency propagation; automake places the global `LDFLAGS` (carrying `-lws2_32 -lmswsock -lbcrypt` on Windows) before the objects, too early to satisfy the archive's imports. Repair mirrors the stage-15 `V3_TLS_DL_LIBS` pattern: `configure.ac` substitutes `V3_NETWORK_LIBS` (`$NETWORK_LIBS` on Windows hosts, empty elsewhere) and the LDADD appends `$(V3_NETWORK_LIBS)` after the archive; `quic_interop_endpoint` inherits it. POSIX empty branch verified in the fresh scratch worktree (`V3_NETWORK_LIBS = ` in the generated `test/Makefile`, bootstrap exit 0 proves automake resolves it); the mingw64 branch is CI-verified. `check-v3-installed-consumer.py` already adds the three system libraries to its own Windows consumer links (line 118), so the installed lanes are covered. +- [x] FreeBSD root cause (full `test-suite.log` and per-test logs extracted from artifact 15546253396, 5.1GB, into external evidence storage): across all three occurrences (2026-10-30 run 41120424110, 2026-11-30 run 46508507388, 2026-12-01 run 46731744909) test 24 ran at full-streaming time (2.6–3.8ms, matching whole-body test 20's 3.7ms; the fast-fail prepare-time short test 23 runs 0.32ms) — the post-rewrite reads always returned original bytes, so the send legally completed as success. The stage-15 "stall" was the old single-round assertion observing that legitimate in-flight success; the stage-15 drive loop then surfaced its true signature (done==1, wrong outcome, `end_calls()==1`). Mechanism: `temp_file::rewrite` used `std::ofstream(path, trunc)` and never checked the stream — a silently failed ofstream open leaves the 40960-byte asset intact (test 24's rewrite is invisible-by-construction; test 23's identical call is self-verifying because a failed rewrite fails its own protocol_error assertion, and it passed). Production `pull_file` behaved correctly for what it observed on every platform. +- [x] Repair: `temp_file::rewrite` now truncates and writes through checked direct syscalls (POSIX `::open(O_WRONLY|O_TRUNC)`/`::write`/`::close`, Windows `_open(_O_WRONLY|_O_TRUNC|_O_BINARY|_O_NOINHERIT)`/`_write`/`_close`, the rig's `rig_write`/`rig_close` shims hoisted above the class) and verifies the visible post-write size via `std::filesystem::file_size`, failing with the sizes in the message. A platform that cannot truncate now fails the suite immediately with evidence instead of corrupting the scenario. The test assertions and the stage-15 drive loop are unchanged. +- [x] Local gates (macOS arm64 scratch worktree at 0151bdbb + the rig edit): `response_sources` 30/304 green ×3, `response_definition` 32/311 green ×3, `native_http1_parity` green; a guard probe makes the truncating open impossible (chmod 0444) — the new rig throws with the errno evidence (EACCES) while the pre-fix rig silently succeeds, proving both sides of the failure mode; cpplint clean; `git diff --check` clean; the same workflow/platform script-test environmental baseline as stage 15. The Windows `_open` branch was not compiled locally (no mingw toolchain), recorded honestly, CI compiles it. +- [ ] Full exact-source CI on the working branch (mingw64 tls-yes build past the endpoint link, Windows acceptance, FreeBSD make check past the fixture repair, darwin/macos lanes past the runner-capacity failures). + +## Stage 17: Winsock exclusive listener ownership and the stdio readahead bound (2026-12-03) + +- [x] Evidence (run 46963856090 acceptance + run 46963855675 package, both at 9c9b47ae; FreeBSD failure evidence artifact downloaded to `/Volumes/WS_BLACK_SN7100_1TB/tmp-evidence/run-46963856090-freebsd/`): the Windows acceptance job and the mingw64 package job failed identically inside the tls-yes installed matrix — `check-v3-public-http2.py` ONESHOTS `rollback`: `shared.exe managed rollback` died on `partial H2 bind was retained` (both linkages, the first Windows exposure of the installed tls-yes http2 lane past the stage-16 link repairs). The FreeBSD acceptance job failed `gmake check` tls-no 1/235: `response_definition` test 24 `file_send_truncated_mid_send_fails`, checks at lines 858/860 with the stage-16 signature (done==1, outcome not protocol_error, `end_calls()==1`) — the rewrite itself verified (stage-16 rig check green), so the truncation was visible on disk yet never observed by the cursor. +- [x] Windows root cause: the `rollback` one-shot binds its second listener onto an occupied loopback port and requires the bind to fail (the partial-bind rollback contract). `pollsys::open_listener` set Winsock `SO_REUSEADDR`, which on Windows means "forcibly bind a port another socket is actively serving" — the obstacle bind succeeded, `listen()` returned ok, and the consumer correctly reported the contract violation. On POSIX `SO_REUSEADDR` does not permit an active same-address double bind, so every other platform observed the refusal. Verified against Microsoft's socket-security documentation (bind matrix + "All server applications must set SO_EXCLUSIVEADDRUSE"): same-account specific-address exclusive→exclusive second bind fails `WSAEADDRINUSE`, and a listening socket carries no TIME_WAIT of its own, so the restarted-server rebind property that motivated `SO_REUSEADDR` is preserved (the documented exclusive caveat — a rebinding delay after accepted connections linger — concerns graceful-shutdown residue, not listening sockets). +- [x] Windows repair: `open_listener` sets `SO_EXCLUSIVEADDRUSE` on `_WIN32` and `SO_REUSEADDR` elsewhere; `io_poll_sys_listener` pins the platform option AND adds the live-listener bind refusal (a second `open_listener` on the bound port must return `k_invalid_socket`) on every platform — the rollback scenarios' precondition is now a pinned unit contract, not just an installed-consumer outcome. The hpp contract comment and the Makefile.am suite description updated. The `_WIN32` branch was not compiled locally (no mingw toolchain), recorded honestly; the Windows/mingw64 CI lanes compile and run it. +- [x] FreeBSD root cause: the reopen_file cursor reads through `std::ifstream`, whose libc++ `basic_filebuf` wraps a `FILE*` buffered to the filesystem's `st_blksize` (macOS/Linux 4 KiB; FreeBSD UFS 32 KiB; ZFS up to 128 KiB), refilling 4096 then 4092 bytes per underflow. The two parked 16 KiB chunks drive ~36.8 KiB of `fread` refills, staging the remaining 4 KiB of the 40 KiB payload in user space; after the (verified) truncate to 100 bytes the final pulls are served entirely from the buffer — no error, no EOF, `feof()==0` — and the send legally completes. Reproduced exactly with a local probe (macOS clang++, `setvbuf` 32 KiB, libc++ refill schedule, truncate mid-stream: total served 40960, feof 0). Production `pull_file` behaved correctly for what it observed on every platform — same standard as stage 16; the repair belongs in the fixture. +- [x] FreeBSD repair: the test payload grows to 2 MiB (bytes owed after the parked chunk ≈ 2 MiB, past any plausible `st_blksize`) and the bounded wake-and-pull drive grows to 256 rounds so buffered pulls drain before the shrink must surface; the test comment and PORTABILITY.md document the readahead bound for future mid-send-mutation tests. A permanent stall still fails the same assertions with the same evidence. +- [x] Local gates (macOS arm64 scratch worktree at 9c9b47ae + these edits): `response_definition` 32/311 checks green ×3 (the enlarged fixture included), `response_sources` 30/304 green ×3, `io_poll_sys_listener` green including the new live-listener refusal; cpplint clean on the changed C++ files; `git diff --check` clean; the same workflow/platform script-test environmental baseline as stages 15/16. +- [ ] Full exact-source CI on the working branch (mingw64 and Windows acceptance past the installed http2 rollback, FreeBSD make check past the readahead bound, darwin/macos lanes green). + +## Stage 18: installed-receipt digest records and the platform retention budget (2026-12-03) + +- [x] Evidence (run 47064150035 acceptance + run 47064149933 package, both at 02327378): the package flow recorded its first fully green mingw64 lane (the stage-17 repair held through the whole tls-yes installed matrix); freebsd and linux package lanes green; the macos package job was cancelled with zero executed steps (runner acquisition, infrastructure). On acceptance, darwin went fully green (bundle retained, tar uploaded); the Windows job passed the entire installed matrix for the first time and then failed `validate_package` with `missing/oversized receipt: .../matrix/tls-no/audit.json`; the FreeBSD job passed the entire installed matrix, package validation and BOTH native `make check` lanes (every stage 15–17 fixture repair held on the VM) and then failed `retain` with `platform evidence exceeds bounds`. +- [x] Windows root cause (receipts measured from artifacts 15703172883 and the mingw64 package evidence): `read_json` bounds every receipt at 64 MiB (`MAX_JSON`), and on Windows the receipts embed raw PE/COFF inspector stdout — per-suite `inspection_commands` retain a full `objdump -p` per suite executable (~7.4 MB each with `-g` debug sections) and the lane `commands` retain `objdump -p` (up to 11.9 MB per binary) plus `nm` stdout (~26.5 MB per archive) that `archive_symbols` already retains verbatim. tls-no audit.json measured 287,825,888 bytes (287.8 MB present on disk — oversized, not missing), tls-yes 711.8 MB, suites.json 63–341 MB: every document `validate_package` reads was over or at the cap. Package-validation jobs never apply the cap (they run the consumer script directly); acceptance is its first Windows exposure past the installed matrix. +- [x] Windows repair (scripts/audit-v3-installed-package.py): the Windows PE inspector (`objdump -p`) and the `nm` archive inspections use the module's existing `retain_output=False` digest mechanism — command records keep argv, resolved tool, returncode, stderr, `stdout_sha256`/`stdout_bytes`; the resolved import graphs every gate checks and the verbatim `archive_symbols` member symbols keep the evidence, so only the raw-stdout duplication disappears (POSIX inspectors unchanged). `test-v3-installed-package.py` nm-record assertions moved to the digest form plus new verbatim-retention assertions on `archive_symbols`. Size proof against the actual oversized acceptance receipts (exact transformation simulated on the real data): tls-no audit.json 287.8 → 45.1 MB, tls-yes 711.6 → 57.0 MB, all four suites.json → 0.2–0.5 MB — everything `validate_package` reads now fits with ≥10% headroom. +- [x] FreeBSD root cause (failure evidence artifact 15707993624, 15,839,113,165 bytes, extracted to external storage and measured): the in-VM job passed the entire installed matrix, `validate_package` and BOTH native `make check` lanes, then `retain` (release_platform.py) fired its single collapsed bound message. The recovered tree measures 8.249 GB / 7.683 GiB across 6,220 files (two `-O0 -g` lanes with llvm19 debug info: 20–46 MB static test binaries, 122–150 MB installed archives, 35.6/44.0 MB audit receipts) plus the selected tools and receipt-referenced files — the walk crossed MAX_BYTES=8 GiB with only 2,793 files catalogued (measured from the partial `bundle/bytes` copy), so the byte bound is the proven trigger and the 20,000-file bound has 3× headroom. No core files, fifos or other junk in the tree. The 8 GiB budget shipped with the original acceptance design (29a849ed, 2026-10-15) and predates this tree shape. +- [x] FreeBSD repair (scripts/lib/release_platform.py): MAX_BYTES 8 → 16 GiB with the measured producer documented beside it; MAX_FILES unchanged at 20000; the retain `require` is split so a future trip names its bound and value (`platform evidence exceeds the file-count bound: N` / `platform evidence exceeds the byte bound: T`) instead of one message covering both. Consumer-side Catalog checks already had distinct messages. +- [x] Local gates (macOS arm64): `test-v3-installed-package.py` 60/60; `test-v3-installed-consumer.py` matches its HEAD environmental baseline exactly (verified by stash-rerun at 02327378: ps-snapshot timeouts, Python 3.9 missing `add_note`, stale generated configure); `test-v3-cutover.py` 9/9; `test-v3-package-workflow.py` 4/4; `py_compile` on all three changed scripts and `git diff --check` clean; the usual `test-v3-ci-workflows.py` 30/31 and `test-v3-platform-ci.py` 11/20 environmental baseline. ChangeLog entries added. +- [ ] Full exact-source CI on the working branch (Windows acceptance past receipt validation, FreeBSD acceptance past retention into the bundle upload, darwin/macos lanes green). + +## Stage 19: native-tree Windows first exposure and the evidence-transport disk bound (2026-12-03) + +- [x] Evidence (runs 47189408281 acceptance + 47189408369 package, both at d59cee33): stage 18 held — the Windows acceptance passed receipt validation and the entire installed matrix, then failed its FIRST native `make check` compile on `test/unit/websocket_engine_helpers.hpp:22 'sys/socket.h' file not found` (tls-no lane). The FreeBSD acceptance passed both native make-check lanes and retention (the 16 GiB bound held) and then died on runner infrastructure: `System.IO.IOException: No space left on device` killed the Actions worker itself (job logs unrecoverable, BlobNotFound), because retention copied the 8.249 GB tree into `bundle/bytes/`, tarred it, the EXIT trap copied the whole platform tree (now ~17 GB with the bundle) again inside the VM, and the recovery scp pulled it onto the host on top of the grown VM image. The macos package job was cancelled with zero executed steps and no runner assigned (queue starvation, same class as stages 16/18) — infrastructure, no code change. +- [x] Windows audit (grep of every compiled test source for POSIX-only headers/calls): exactly two unguarded exposures, both first-reached now that the native tree compiles on Windows for the first time. `websocket_engine_helpers.hpp` unconditionally included `` (nothing in the rig needs it — every syscall already routes through the pollsys shims), and `http1_websocket_upgrade_test.cpp` included it while calling raw `::setsockopt(SO_SNDBUF)` twice and raw `::send` twice (Winsock takes `const char*` option values and socket buffers, not `void*`/`std::byte*`). Also fixed in the same class: `native_protocol_memory_test.cpp` (two raw `setsockopt` shrinks; its `windows.h` include needed the `WIN32_LEAN_AND_MEAN`/`NOMINMAX` guard pair from io_poll_sys.hpp so the rig's later winsock2 include cannot clash) and `native_http1_conformance_test.cpp` (`::shutdown(peer, SHUT_WR)` takes the `SD_SEND` spelling on Winsock). All other hits are platform-guarded (tls_client, authentication, cookie_wire, peer_policy_runtime, deferred, digest_challenge_format, both fixtures, threadsafety, native_server, kqueue/epoll/iocp backends) or uncompiled (`parity/socket_io.hpp`, whose only consumer `transcript_runner.cpp` is registered by no make target — same status as `v2_fixture.cpp` in stage 14). +- [x] Windows repair: the rig header owns the platform split (winsock2/ws2tcpip with the lean/nominmax guard pair, else sys/socket.h; the include guard moved above the includes so cpplint keeps identifying it) plus one shared `shrink_send_buffer` helper carrying the `const char*`/`void*` optval branch; the upgrade test's mirror writes go through `pollsys::write_some` (single-syscall semantics preserved, EINTR retried inside per stage 14) with `status==ok && transferred==N` checks replacing the `::send` return comparisons; POSIX branches byte-equivalent. +- [x] FreeBSD repair (scripts/run-v3-release-ci.py): the retained set drops from "every file under the platform output" to the verifiable documents — `*.json` receipts, `*.log`/`*.trs` test records — plus the unchanged receipt-referenced files, selected tools, provider header and archive; every catalog reader in release_platform.py (`validate_package`, `package_origin`, `validate_origin` native lanes, `verify_files`) reads exactly that set, and the build lanes were never read. MAX_BYTES 16 → 4 GiB sized to the new shape (~1 GiB measured expectation, darwin's whole-tree bundle tarred to 0.9 GB) so three producer bundles also fit the shared `full` gate runner. The workflow's freebsd EXIT trap and the Windows/Darwin failure-evidence uploads take the same documents (trap via a python3 bounded copy: json/log/trs/tar.gz under platform/, json/log at the prerequisites root; artifact paths via `platform/**/*.{json,log,trs}` globs) — the 15.8 GB failure-evidence artifact and the 8.9/4.6 GB darwin/windows uploads are gone with them. +- [x] Local gates (macOS arm64 scratch worktree at fc9c0bdc content): the five affected programs (`http1_websocket_upgrade`, `websocket_drain`, `websocket_drain_race`, `native_protocol_memory`, `native_http1_conformance`) build with the real flags and pass ×3 runs; `connection_engine_test.cpp`/`resource_limits_test.cpp` (the rig's other includers) syntax-check clean; cpplint clean on all four changed C++ files; `git diff --check` clean; new focused `test_acceptance_trap_bounds_evidence_to_documents_and_finished_bundles` passes (executes the real trap shell against a fixture tree; every existing recovery/trap test unchanged and green); new focused `test_archive_retention_excludes_build_lane_intermediates` errors only in the documented spaced-make environmental class with its sibling (stash-rerun at HEAD: workflows 1 known failure identical, platform-ci 9→10 errors = the same 9 + the new sibling); `py_compile` on changed scripts. The `_WIN32` branches were not compiled locally (no mingw toolchain on this host), recorded honestly; the mingw64/Windows CI lanes compile and run them. +- [ ] Full exact-source CI on the working branch at fc9c0bdc (Windows acceptance past the native make-check compile, FreeBSD acceptance past retention/tar/trap/scp within runner disk, macos package lane past the queue starvation, `full` gate job over three bounded bundles). +- Round 2 verdict (run set 472743887xx–472743889xx at fc9c0bdc): `v3 installed package validation` fully GREEN including macos (the queue starvation did not recur; no rerun needed); fuzz/CodeQL/Verify Build/ChangeLog green. Acceptance failed all three platforms with distinct causes. Windows: the helper repair held (websocket_drain/race compiled) but `http1_websocket_upgrade_test.cpp` lines 292/350 carried two more raw `::setsockopt(SO_SNDBUF, &small, ...)` sites missed by the stage-19 audit's truncated grep; both now route through `shrink_send_buffer` (0e53d543; a complete untruncated syscall sweep of the compiled test tree finds no remaining raw socket calls — every other hit is an application-level method). Darwin: tls-no make check 232/235 with `http1_response_outbox` `concurrent_sibling_heads_share_actual_capacity` failing checks at lines 425/427 (observed 271, expected 287 = capacity; a 16-byte accounting gap under concurrent sibling starts whose threads are joined before the assertion). The suite includes none of the changed files and was green on this lane at d59cee33 (run 47064150035 darwin fully green): first occurrence, held as an open flake under the standing no-repair-without-recurrence rule (stage 8/14 precedent); the 0e53d543 run decides. FreeBSD: the VM never reached project code — `pkg install` in the action's prepare died on pkg.FreeBSD.org HTTP 429 (rate limiting) for every repository fetch, then the correctly-failing evidence recovery reported the never-created RUNNER_TEMP; third-party infra, retry decides. The bounded failure-evidence artifacts measured 69 MB (darwin) / 115 MB (windows) versus 8.9/4.6 GB before the transport repair. + +## Stage 20: first full Windows native make-check exposure and the FreeBSD e2e churn bound (2026-12-04) + +- [x] Evidence (runs 47289018867 acceptance, head 0e53d543): darwin went fully green (the stage-19 round-2 `http1_response_outbox` flake did not recur — resolved under the no-repair-without-recurrence rule), installed package validation stayed fully green including macos, fuzz/CodeQL/Verify Build/ChangeLog green. The Windows job passed everything up to its FIRST native `make check` ever (tls-no 213/235, 20 failures across 8 native + 11 script tests + the websocket e2e; tls-yes make check never reached); FreeBSD reached 232/235 with exactly one failure, `integ/native_websocket_e2e.sh` ("EOF before handshake" at `native_websocket_client.py:199`, after the parked-writer case and all 8 malformed refusals passed). Failure-evidence artifacts 15822772204 (windows, 116 MB) and 15831137899 (freebsd, 92 MB) extracted to external storage (`tmp-evidence/r3-win`, `tmp-evidence/r3-fbsd`). +- [x] Windows root causes (per-test, from the extracted logs): (1) `hpack_primitives`/`qpack_field_section`/`server_routes_families`/`task_resume_signal_lifetime` — the tests drive the code-under-test through an executable `operator new` override/counter, and on this lane the code lives in the shared libtool DLL whose allocations bind to the runtime DLL at DLL link time (PE module boundary; the stage-5 native PE fixture proved exactly this direction), so counts pin at 0 and no fault injects — deterministic, both iterations identical; (2) `io_operation::suspend_races_cross_thread_apply` — the applier's 0–100µs `sleep_for` rounds to ~15ms under Win32 Sleep granularity, the 100000-iteration spin drains in a few ms and exits before delivery, and apply's posted resume strands in the executor after the join (23ms total, round ~0); (3) `native_protocol_memory` — the 3×1s CPU-sample window inside `plateau()` is idle and the Windows 127.0.0.1 rig (only `SO_SNDBUF` shrunk, `io_loopback.hpp:88-95`) absorbs the whole 1024-byte outbox, so the post-plateau push returns `accepted` not `full` ("output admission stopped" check throw at :226; both RSS plateaus PASSED, so the stage-11 GetProcessMemoryInfo branch held); (4) `forms_multipart_files` — `scratch_dir` hardcoded a `/tmp` mkdtemp template, which a native Windows binary resolves against the current drive root where `/tmp` does not exist, so mkdtemp failed, `path_` stayed empty, every scratch-dir probe failed with the library itself behaving identically (files landed at the drive root), and the fail-continue `[0]`-index at :446 then aborted under `_GLIBCXX_ASSERTIONS`; (5) `quic_interop_files` — unprivileged Windows cannot `create_symlink` (no SeCreateSymbolicLinkPrivilege; ENOSYS); (6) the websocket e2e died silently before READY; (7) the 11 script tests map to 10 mechanisms (unqualified `bash` → System32 WSL stub ×3 scripts; POSIX shebang fixtures ×3; `CXX='clang++ -std=c++20'` used unsplit as argv[0]; Linux-only `/proc`+`os.sysconf` sampler; extension-less deadline tool vs PATHEXT; `os.killpg` absent in two gate runners; `Path('/abs').is_absolute()` False on Windows in the archive traversal guard; `check_linkage` resolving the translated provenance namespace under the current drive; separator-style path identity in packaged-adapters + CRLF `write_text`; missing Windows skip on the FreeBSD wrapper-script test). +- [x] FreeBSD root cause: the fixture deliberately keeps `options.timeouts().header` at 100ms and the deadline anchors at connection start (`connection_engine.cpp` watchdog planning); the split loop opens ~200 sequential connections and one accept-to-parse span on the loaded 2-vCPU -O0 -g FreeBSD VM legitimately expired before the 101 was written — the server closed gracefully (client saw EOF), i.e. it behaved to its configuration; the churn volume is the exposure, not a server defect. +- [x] Windows e2e repair: `native_websocket_client.py::launch()` resolves the real `.libs/.exe` on `os.name == 'nt'` and prepends `build/src/.libs` + `build/test/.libs` to the child PATH (the libtool wrapper a native CreateProcess cannot execute is the only thing that put the DLL directories on PATH; the client is the only make-check consumer spawning a built binary directly — examples are `--disable-examples` and `quic_interop_runner_test.py` is EXTRA_DIST-only), and `start()` surfaces the fixture's exit code plus captured stderr when READY never arrives. The loader-death mechanism (spawn succeeds, zero output, silent exit) is inferred from that signature; the surfaced stderr will confirm or replace it in the next run. +- [x] FreeBSD e2e repair: `attempted()` restarts a connection the server closed before its handshake completed on a fresh connection, at most 4 attempts, reporting the restart count; a deterministic close still fails and nothing after the 101 is retried. Both bounds are documented in `test/PORTABILITY.md` alongside the stage-15/17 precedents. +- [x] Native repairs: the four operator-new suites now link `$(top_builddir)/src/libhttpserver_v3core.la $(V3_NETWORK_LIBS)` (static archive into the exe — the stage-5-proven working direction; every assertion stays active on every platform, POSIX linkage was static-equivalent for interposition anyway); `io_operation` bounds the drain by wall clock (2s) in addition to spins and drains apply's posted resume after the join; `native_protocol_memory` re-saturates to a steady full queue with the same `until` discipline the upload phase already uses before asserting `full`; `forms_multipart_files` anchors mkdtemp at `std::filesystem::temp_directory_path()` and guards the follow-up `entries()[0]` indexing; the two quic interop symlink fixtures take the `error_code` overload and `LT_SKIP_IF` with reason (the tls-yes sibling `quic_interop_tls_test.cpp:100` would have failed the never-yet-reached Windows tls-yes make check — same-class preemptive repair). +- [x] Script repairs: `BASH` resolved through `shutil.which` per the `release_ci.py` convention in `protocol_gate_runner_test`/`protocol_fuzz_runner_test`/`release_artifact_test`; `shlex.split(CXX)` in `behavior_parity_runner_test` (mirroring `test-v3-packaged-adapters.py`); `os.killpg` guarded by `hasattr` with terminate/kill fallback in `run-v3-http3-full-gates.py` and (same-class audit) `run-v3-quic-interop.py` (`package_commands.py` already owns the portable pattern); tar members parsed as `PurePosixPath` in `release_checks.extract_archive` (mirroring `release_ci.py`), fixing a genuine traversal-guard hole on Windows hosts; `check_linkage` containment made lexical over the already-translated namespace (dropped `prefix.resolve()`); packaged-adapters identity normalized (`os.path.normcase(normpath(...))` lookup in `release_package_provenance.bound`, `same_path` in `compiler_sdk.verify`, `write_bytes` for the fixture source, PE-walker rejection expectation on `nt`); skip-with-reason on `nt` for the Linux-only `resource_limits_probe` Sampler (`hasattr(os,'sysconf')` predicate — FreeBSD/macOS keep running it), the FreeBSD compiler-wrapper test, the POSIX-shebang fixtures in `http3_full_gate_runner_test` (×3) and `release_gate_runner_test` (×7), and the POSIX mode-bit output-privacy assertion. +- [x] Local gates (macOS arm64 scratch worktree at fbe5cf50 + these edits): all eight affected native programs build and pass ×3 (`forms_multipart_files`, `quic_interop_files`, `hpack_primitives`, `qpack_field_section`, `server_routes_families`, `task_resume_signal_lifetime`, `io_operation`, `native_protocol_memory`); both websocket e2e scripts exit 0 against the local fixture; `quic_interop_tls_test.cpp` passes the homebrew-openssl syntax-check substitute (TLS-mode builds are impossible on this host, recorded honestly); cpplint clean on all five changed C++ files (after matching the sibling's `` NOLINT convention and `static_cast`); `py_compile` clean on all changed scripts; `git diff --check` clean. Python suites under `/opt/homebrew/bin/python3` (3.14; system 3.9 errors on `extractall(filter=)`): `protocol_gate_runner_test` 6/6, `protocol_fuzz_runner_test` 13/13, `release_ci_test` 24/24, `release_platform_bundle_test` 14/14, `behavior_parity_runner_test` 32/32, `http3_full_gate_runner_test` 27/27, `release_gate_runner_test` green, `test-v3-packaged-adapters` green, `resource_limits_probe_test` green, `test-v3-cutover` 9/9, `test-v3-package-workflow` 4/4, `test-v3-installed-package` 60/60; `release_artifact_test` has exactly one failure (`test_selected_compiler_retention_through_symlinked_tmpdir`, the documented spaced-make/xcode-select environmental class — stash-rerun at HEAD reproduces it identically) and `test-v3-platform-ci.py` 8 errors identical at HEAD (BSD-make/xcode-select environmental baseline). +- [ ] Full exact-source CI on the working branch (Windows tls-no make check past the 20 repairs, then the first Windows tls-yes make check, FreeBSD make check past the e2e restart bound, darwin/macos lanes green, `full` gate job over three bounded bundles). + +## Stage 21: Windows round-4 residue (2026-12-04) + +- [x] Round-4 verdict (run 47406483994 at d19062a3): 5/6 workflows green; acceptance darwin green again (43m31s) and FREEBSD GREEN for the first time (2h4m — the stage-20 e2e restart bound and every stage-15-17 fixture repair held on the VM). Windows advanced to 227/235 (from 213): fourteen of the twenty stage-20 repairs held, including the websocket e2e on Windows (the .libs/DLL-PATH spawn worked — the loader-death mechanism is confirmed) and 10 of 11 script tests. Six residue failures, all round-4-diagnosed from artifact evidence: (1) `native_protocol_memory` moved past both HTTP phases (the re-saturation held) to the IDENTICAL idle-window absorption at the WebSocket output phase's post-plateau single push; (2) `behavior_parity_runner_test` compiled `http_cookie` fine (the CXX split held) but mingw `-o http_cookie` produces `http_cookie.exe`, so the byte-bind read the extensionless path and got FileNotFoundError; (3) `protocol_fuzz_runner_test`'s bash resolution held; the new failure is representational — `compile.sh` records the bash-side msys-form argv (`-I/d/a/...`) while `compile.jsonl` records what the compiler actually received (native `-ID:/a/...` after MSYS2 argument conversion), so the three compile.sh equality compares need the msys→native translation; (4) `http3_full_gate_runner_test` had one more shebang-fixture + test(1)-Makefile subtest (`test_reusing_configured_build_preserves_prior_build_evidence`) outside the stage-20 skip set; (5) packaged-adapters shrank from ~50 failures to 4: `os.execvp` does not exist on Windows (the wrapper compiler fixture), the extensionless `static` probe name is unspawnable by CreateProcess (`compile_probe` links `-o` verbatim; the real lanes pass `.exe` names per `run_suites`), `assertRaises` class-identity fails because `validate_runtime` loads its own audit module instance (two exec_module calls create distinct AuditError classes), and mingw-python `str(Path)` separator preservation breaks `list(sdk.iterdir()) == [metadata]` WindowsPath equality. +- [x] Repairs: the ws-output phase re-saturates to the same steady watermark before its stopped-check (the HTTP-output precedent); the cookie bind resolves the produced `name.exe` (run unchanged via CreateProcess); `native_args()` normalizes the three compile.sh comparisons (msys drive-form → native, POSIX identity); the reusing-configured subtest joins the skip set with reason; the wrapper fixture uses `subprocess.call` + `SystemExit`; the probe is named `static.exe` on `nt` like `run_suites` does; the runtime-inspection rejection asserts on the exception type NAME; the sdk-dir membership compares entry names. +- [x] Local gates (macOS arm64 scratch worktree): `native_protocol_memory` builds and passes ×3 with the ws re-saturation; `behavior_parity_runner_test` 32/32, `protocol_fuzz_runner_test` 13/13, `http3_full_gate_runner_test` 27/27, `test-v3-packaged-adapters` green, cpplint clean on the changed C++ file; `release_artifact_test` shows only the documented spaced-make environmental failure (stash-verified at HEAD earlier this session). +- [ ] Full exact-source CI: Windows tls-no make check 235/235, then the FIRST Windows tls-yes make check, `full` gate job, publish. + +## Stage 22: Windows round-5 residue (2026-12-05) + +- [x] Round-5 verdict (run 47429727821 at 1ce7b00d): 5/6 workflows green; acceptance darwin green (43m39s) and FreeBSD green again (2h4m — second consecutive green, the stage-15–21 repairs hold). Windows advanced to 230/235 (from 227) with three residue failures: `behavior_parity_runner_test` (three × "named supporting test lacks matching suite execution provenance"), `protocol_fuzz_runner_test` (compile.sh element-0 compare, http3 contract `\r` contamination, reproduce.sh corpus path), and `release_artifact_test` (the corpus fixture subprocess of the same fuzz test). Failure evidence artifact 15896264188 (116 MB) extracted to `tmp-evidence/run-47429727821-win`. +- [x] Windows root causes (from the extracted per-test logs): (1) the behavior-parity audit's `matching_execution` resolves `cwd/argv[-1]` and requires `binary.name == suite` and `is_file()` — on Windows the executed file is `http_cookie.exe` (mingw `-o name` produces `name.exe`; CreateProcess auto-appends the suffix to the extensionless command), so the extensionless argv record can never validate, one error per supporting item; (2a) the stage-21 `native_args` regex also matches the `:/a/` inside already-native `D:/a/...` tokens (the `:` prefix alternative), mangling the compiler path the script records verbatim (`D:/a/...` → `D:a:/...`), never matches the `-I/d/...` flag form (prefix `I` is outside `[=:-]`), and leaves the drive letter lowercase while the msys exec conversion emits uppercase; (2b) `sources.list` is written through `python3 - ... > file` text-mode stdout — a native Windows python3 translates that to CRLF, `read -r` keeps the trailing `\r`, and the compiler argv records `tls_psk.cpp\r` on both sides (a real script bug: an actual Windows fuzz build could not compile); (2c) `reproduce.sh` legitimately records the bash-side command with msys mount paths (`/tmp/...` — the runner's TEMP is the msys2 root tmp), while the test asserts the native form; the subsequent negative test would also raise OSError because unprivileged Windows cannot `symlink_to` (stage-20 ENOSYS precedent). +- [x] Repairs: the audit accepts `suite.exe` beside `suite` as the provenance binary name on `os.name == 'nt'` only (POSIX name set byte-identical, so every existing darwin/linux/freebsd receipt validates unchanged); the cookie witness records `argv=[witness]` — the file CreateProcess actually executed (`.libs/.exe` when present, else `.exe`, else the POSIX path) — and byte-binds that same file; `native_args` gates on `[A-Za-z]:/` (already-native arguments pass through untouched), then translates only the leading msys drive form with the prefix class `(^|[A-Za-z=:])` so `-I/d/...` translates, the drive letter is uppercased, and a second `/x/` after the produced `D:` cannot match; `run-v3-protocol-fuzz.sh` writes `sources.list` through `pathlib.write_bytes` (the provider-args heredoc's established bytes-safe pattern), keeping LF endings under every python3; the corpus test resolves the reproduction's slash-prefixed tokens through `cygpath -w` via the same BASH the runner used (normcase/normpath-normalized comparison, POSIX branch unchanged) and skips the symlink negative with reason on OSError. +- [x] Local gates (macOS arm64, primary checkout at 1ce7b00d + these edits — no C++ changes, so no scratch build): `protocol_fuzz_runner_test` 13/13, `behavior_parity_runner_test` 32/32 (the real cookie compile+execution included), `release_artifact_test` shows only the documented spaced-make/xcode-select environmental failure with `test_restored_corpus_through_symlinked_tmpdir` ok; `bash -n` on the changed script; `py_compile` clean on both changed python files; `git diff --check` clean. The `os.name == 'nt'` branches were not executable locally (no Windows host), recorded honestly; the Windows/mingw64 CI lane runs them. +- [ ] Full exact-source CI: Windows tls-no make check 235/235, then the FIRST Windows tls-yes make check, `full` gate job, publish. + +## Stage 23: the round-6 verdict, the rerun dead end, and the rerun-capability repair (2026-12-06) + +- [x] Round-6 verdict (run 47593684692 at 1f73e10b): 5/6 workflows green; darwin (41m) and freebsd (2h26m) acceptance green again, installed package validation green. The Windows job failed EARLIER than make check — the round-5 script-test repairs were never exercised — in the installed tls-yes matrix: `check-v3-public-http2.py` static-managed cell, node scenario `body-limit` timed out at the script's 25s bound with EMPTY captured output (`command-0093.log` is 0 bytes). commands.json records 71 of 72 node scenarios; the 23 preceding static scenarios (every other *-limit included) passed seconds earlier, the identical scenario passed in both shared cells minutes earlier, and in rounds 4 and 5. First occurrence of this signature — held OPEN as a suspected load-dependent flake under the standing no-repair-without-recurrence rule (stage-8 http2-stale, stage-19 response_outbox precedents); the failed-job rerun was the deciding observation. Evidence: receipt.json, commands.json, command-0093.log under `.debug/v3-ci-green-VSvXxx/runtime-green-stage22/round6-public-http2/` (artifact 15965958356). +- [x] Rerun dead end (attempt 2 of 47593684692, job 145946093165): the `--failed` rerun died in ~90s at "Verify native Git and download immutable selected archive" with `ValueError: artifact belongs to an earlier run attempt` — before any build. Root cause (verified against the GitHub API for both attempts of that run): the attempts endpoint returns ATTEMPT-scoped timestamps (`created_at` == `run_started_at` == the attempt's own start), so `release_ci.py`'s freshness check `metadata.created_at >= run.run_started_at` structurally rejects every attempt-2 job that re-consumes the attempt-1 selected archive — failed-job reruns were impossible by construction. The digest, artifact-ID, run and head-SHA pins are untouched by this. +- [x] Repair (rerun-capability, evidence-backed): `verify_download` takes the run-level record's original `created_at` as the freshness anchor (`download()` fetches `actions/runs/{id}` in addition to the attempts call); the message now reads "artifact belongs to an earlier run". The check keeps its anti-earlier-run property exactly: anything created before the run itself is still rejected; only same-run earlier-attempt artifacts (digest-pinned) are accepted. `release_ci_test.py` updated for the new signature and extended with the rerun-acceptance case (attempt-1 artifact, attempt-2 expectation, PASS) and the still-rejected earlier-run case (FAIL). +- [x] Local gates (macOS arm64 at 1f73e10b + these edits): `release_ci_test` 24/24 (including both new rerun cases), `test-v3-cutover` 9/9, `py_compile` clean on all three changed files, `git diff --check` clean. +- [ ] Full exact-source CI on the new push: the body-limit flake gets its recurrence decision in the same run as the repair validation; then Windows tls-no make check 235/235, the FIRST Windows tls-yes make check, `full` gate job, publish. + +## Stage 24: the round-7 verdict, the fuzz mount-form compare, and the DRAIN-LATE hard-stop race (2026-12-06) + +- [x] Round-7 verdict (run 47607225296 acceptance + 47607225321 package, both at 838d3575): fuzz/CodeQL/Verify Build/ChangeLog green; installed package validation mingw64+linux green. The stage-23 freshness anchor passed its first archive-consuming lane (freebsd acceptance "Download immutable selected archive" success; the rerun `ValueError` class is cleared). Windows acceptance reached the tls-no native `make check` and failed 1/235 — `integ/protocol_fuzz_runner_test.py` (2 failures, both compile.sh↔compile.jsonl compares; element 0 passes, first difference at the `-o` output token). Darwin acceptance failed 1/235: `integ/native_websocket_e2e.sh` DRAIN-LATE, "unexpected EOF" at `http.exact(4)` ("drain truncated in-flight HTTP") after every earlier case passed. The macos package job failed the installed tls-yes matrix at `check-v3-public-tls.py` static-external `handler_drain`: 29 consecutive `PENDING` acknowledgements across the 3s window then "consumer startup deadline exceeded" (receipt `error` + process stdout in the retained package evidence); the other three cells of the same run passed 82 scenarios each minutes earlier, and rounds 6→7 changed only `release_ci.py` — first occurrence of this signature, held OPEN as a suspected load-dependent flake under the standing no-repair-without-recurrence rule; the round-8 run (and failed-job reruns, now possible) decides. Evidence: job logs + failure-evidence artifacts 15971937042 (windows, 116 MB) / 15969929171 (darwin, 69 MB) and the macos package artifact, all extracted under `/Volumes/WS_BLACK_SN7100_1TB/tmp-evidence/run-47607225{296,321}-macos/`. +- [x] Windows root cause: `run-v3-protocol-fuzz.sh:80` canonicalizes `--build-dir` through bash `pwd`, which on msys returns the MOUNT form for directories under an msys mount (`/tmp/...` for the root tmp), not the drive form (`/d/...`) the stage-22 `native_args` regex translates lexically. The recorded `-o` token has always been mount-form; earlier rounds died at element 0 before reaching it. A mount-point's native location is environment state, unknowable lexically. +- [x] Windows repair (test-side, mirroring the stage-22 corpus-test precedent): `native_args` is replaced by `native_compile_argv` — every bash-side path token (bare `/...` or flag-attached `-[X]/...`) resolves through `cygpath -w` via the same BASH the runner used, and both sides of the compare normalize with `normcase(normpath(...))` (`windows_comparable`); POSIX behavior is byte-identical (identity on both sides). All three compile.sh compare sites updated; no other `native_args` consumers exist. +- [x] Darwin root cause: DRAIN-LATE expires by design (the client never answers the server Close), and the drain-scope expiry cancel hook stops every listener (`server.cpp` `begin_drain` → `listener->request_stop(timeout)`), hard-closing the in-flight `/slow` connection. The case passes only when the response body (flushed after the handler's 100ms park) reaches the client's receive buffer before that hard stop; a loaded -O0 -g darwin runner surfaced the 100ms resume after the 250ms expiry, and the truncation is the server behaving to its configuration. Second darwin occurrence of this test (stage 14 + this round) — the stage-14 request for fresh per-test evidence is satisfied by this round's retained log; the repair is now authorized by the standing rule. +- [x] Darwin repair (fixture-side, stage-15/17/20 bound precedent): only the DRAIN-LATE budget widens (250ms → 1500ms, still inside the client's 3s transport-close assertion window), giving the body flush ~1.4s of scheduling headroom before the designed hard stop; DRAIN (completes its handshake) and DRAIN-DROP (drops its ticket) keep the tight budget. Every client assertion unchanged. Documented in `test/PORTABILITY.md` (new DRAIN-LATE entry alongside the stage-20 churn bound); `check-skip-rationales.sh` PASS. +- [x] Local gates (macOS arm64 scratch worktree `.worktrees/ci-green-stage24-e2e` at 838d3575 + these edits): `protocol_fuzz_runner_test` 13/13 under /opt/homebrew/bin/python3 (POSIX identity branch) plus `py_compile`; `native_websocket_fixture` builds against the real flags and `native_websocket_e2e.sh` exits 0 ×3 (client + regression halves); cpplint clean on the changed C++ file; `git diff --check` clean. The `os.name == 'nt'` compare branch was not executable locally (no Windows host), recorded honestly; the Windows CI lane runs it. +- [ ] Full exact-source CI on the round-8 push: Windows tls-no make check 235/235 (fuzz compare included), then the FIRST Windows tls-yes make check, the macos handler_drain flake's recurrence decision, `full` gate job, publish. diff --git a/src/detail/connection_engine_websocket.cpp b/src/detail/connection_engine_websocket.cpp index dc0d79142..f805a7ef5 100644 --- a/src/detail/connection_engine_websocket.cpp +++ b/src/detail/connection_engine_websocket.cpp @@ -227,7 +227,13 @@ connection_engine::io_posture connection_engine::writer_posture( return io_posture::park; } bool connection_engine::watchdog_terminal_locked() const { - return shutdown_ || phase_ == stream_phase::terminal || (close_after_drain_ && !websocket_); + // The close mark alone must not retire the watchdog while a server + // drain deadline is pending: HTTP/1 enforces that deadline's hard + // stop only here (enforce_timeout's scope expiry), so a stalled + // close handoff may not outlive the drain budget. The transport's + // release still ends this loop with connection_closed. + return shutdown_ || phase_ == stream_phase::terminal + || (close_after_drain_ && !websocket_ && !server_drain_deadline_); } bool connection_engine::transport_output_pending_locked() const { if (outbox_.queued_bytes() > 0) return true; diff --git a/src/detail/io_poll_sys.cpp b/src/detail/io_poll_sys.cpp index 68d7f0911..f07d796b4 100644 --- a/src/detail/io_poll_sys.cpp +++ b/src/detail/io_poll_sys.cpp @@ -325,7 +325,19 @@ native_socket_t open_listener(std::string_view address, std::uint16_t port, std: return listener_failure(socket); } int reuse = 1; +#if defined(_WIN32) + // Winsock's SO_REUSEADDR would forcibly bind a port another socket + // is actively serving (Microsoft's socket-security guidance: "All + // server applications must set SO_EXCLUSIVEADDRUSE"), silently + // splitting one port across two listeners. The exclusive option + // keeps the property POSIX SO_REUSEADDR provides here -- a + // restarted server rebinds its configured port once the previous + // listening socket closed (a listening socket carries no TIME_WAIT + // of its own) -- while refusing every bind onto a live listener. + ::setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&reuse), sizeof(reuse)); +#else ::setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&reuse), sizeof(reuse)); +#endif if (!bind_listener(socket, storage)) { return listener_failure(socket); } diff --git a/src/detail/tls_session.cpp b/src/detail/tls_session.cpp index baa20cc9e..9de2cbc7b 100644 --- a/src/detail/tls_session.cpp +++ b/src/detail/tls_session.cpp @@ -124,11 +124,21 @@ struct tls_session::impl { void open_keylog() { const char* path = std::getenv("SSLKEYLOGFILE"); if (!quic || !interop_mode() || !path || !*path) return; +#if defined(_WIN32) + // Windows has no O_NOFOLLOW/O_CLOEXEC/fchmod; _O_NOINHERIT is the + // close-on-exec analog and the creating open already owns the file. + keylog_fd = ::open(path, O_WRONLY | O_CREAT | O_APPEND | _O_NOINHERIT, 0600); + struct stat info{}; + if (keylog_fd < 0 || fstat(keylog_fd, &info) != 0 || !S_ISREG(info.st_mode)) { + throw std::runtime_error("test keylog unavailable"); + } +#else keylog_fd = ::open(path, O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW | O_CLOEXEC, 0600); struct stat info{}; if (keylog_fd < 0 || fstat(keylog_fd, &info) != 0 || !S_ISREG(info.st_mode) || fchmod(keylog_fd, 0600) != 0) { throw std::runtime_error("test keylog unavailable"); } +#endif } static void keylog(const SSL* ssl, const char* line) noexcept { auto* self = state(const_cast(ssl)); diff --git a/src/httpserver/detail/io_poll_sys.hpp b/src/httpserver/detail/io_poll_sys.hpp index 784805504..d1e52288f 100644 --- a/src/httpserver/detail/io_poll_sys.hpp +++ b/src/httpserver/detail/io_poll_sys.hpp @@ -254,8 +254,12 @@ bool bind_listener(native_socket_t socket, std::uint16_t bound_listener_port(native_socket_t socket); // A listening stream socket bound to @p address:@p port, left -// nonblocking, with SO_REUSEADDR set (a restarted server rebinds its -// configured port immediately). Address spellings per +// nonblocking, with the platform's port-ownership option set +// (SO_REUSEADDR on POSIX, SO_EXCLUSIVEADDRUSE on Winsock, where +// SO_REUSEADDR would permit hijacking a live listener's port; a +// restarted server still rebinds its configured port immediately -- +// the previous listening socket closed and carries no TIME_WAIT of +// its own). Address spellings per // fill_listener_address; port 0 requests an ephemeral port and the // resolved host-order port is always reported through @p bound_port. // Any failure closes the handle and returns k_invalid_socket. diff --git a/test/Makefile.am b/test/Makefile.am index c8df93548..1d6609e09 100644 --- a/test/Makefile.am +++ b/test/Makefile.am @@ -259,7 +259,9 @@ http1_response_outbox_LDADD = $(LDADD) # TASK-108 step 1: loopback/any-address listener bind helper # (pollsys::open_listener): v4/ANY/v6 literals, resolved port report, -# SO_REUSEADDR, nonblocking accept, name rejection. TASK-119 adds the +# the port-ownership option (SO_REUSEADDR; SO_EXCLUSIVEADDRUSE on +# Winsock) plus the live-listener bind refusal, nonblocking accept, +# name rejection. TASK-119 adds the # fill_peer battery (accept-time peer capture) cross-checked against # net::parse_address over the shared byte decode in v3core # (detail/net_address.cpp), so the suite uses the default LDADD and @@ -466,6 +468,10 @@ forms_multipart_corpus_CPPFLAGS = $(AM_CPPFLAGS) -DPARITY_TRANSCRIPT_DIR='"$(top # Public headers are self-contained; compiled behavior uses normal library linkage. server_routes_families_SOURCES = unit/server_routes_families_test.cpp +# The allocation probe is an executable operator-new override; a Windows DLL +# binds its own allocations to the runtime DLL, so the counted code must be +# linked statically (stage-5 linkage rule). +server_routes_families_LDADD = $(top_builddir)/src/libhttpserver_v3core.la $(V3_NETWORK_LIBS) # TASK-118 step 2: the lifecycle hook vocabulary and bus (plan D4). # The bus storage lives in v3core (detail/server_hooks.cpp), so the @@ -583,7 +589,10 @@ TESTS += integ/native_websocket_e2e.sh EXTRA_DIST += integ/native_websocket_e2e.sh task_resume_signal_lifetime_SOURCES = unit/task_resume_signal_lifetime_test.cpp -task_resume_signal_lifetime_LDADD = $(top_builddir)/src/libhttpserver.la +# The timeout-registration interleaving hook is an executable operator-new +# override; a Windows DLL binds its own allocations to the runtime DLL, so the +# owner must be linked statically (stage-5 linkage rule). +task_resume_signal_lifetime_LDADD = $(top_builddir)/src/libhttpserver_v3core.la $(V3_NETWORK_LIBS) # Windows children bound DLL process-detach retirement; POSIX checks ordinary # explicit timer ownership without changing its process lifetime semantics. @@ -727,6 +736,12 @@ consumer_v3_features_CPPFLAGS = -I$(top_srcdir)/src consumer_v3_features_LDADD = $(top_builddir)/src/libhttpserver_v3core.la AM_TESTS_ENVIRONMENT = V3_TLS_MODE="$(enable_v3_tls)"; export V3_TLS_MODE; +# Bound every native test program so one hung binary cannot consume a +# whole CI make-check command budget; the wrapper degrades to a plain +# exec where timeout(1) is unavailable (macOS by default). +LOG_COMPILER = $(top_srcdir)/test/timeout-wrapper.sh +EXTRA_DIST += timeout-wrapper.sh + basic_auth_corpus_LDFLAGS = $(V3_TLS_LDFLAGS) $(AM_LDFLAGS) body_reader_LDFLAGS = $(V3_TLS_LDFLAGS) $(AM_LDFLAGS) @@ -897,7 +912,9 @@ EXTRA_DIST += data/tls_credentials/client-expired-key.pem data/tls_credentials/c check_PROGRAMS += hpack_primitives hpack_static_table hpack_corpus hpack_primitives_SOURCES = unit/hpack_primitives_test.cpp -hpack_primitives_LDADD = $(top_builddir)/src/libhttpserver.la +# Allocation observation requires the owner statically linked: a Windows DLL +# binds its own operator new to the runtime DLL (stage-5 linkage rule). +hpack_primitives_LDADD = $(top_builddir)/src/libhttpserver_v3core.la $(V3_NETWORK_LIBS) hpack_static_table_SOURCES = unit/hpack_static_table_test.cpp hpack_static_table_LDADD = $(top_builddir)/src/libhttpserver.la hpack_corpus_SOURCES = unit/hpack_corpus_test.cpp fuzz/hpack_fuzz.cpp @@ -1256,7 +1273,9 @@ qpack_static_table_LDADD = $(top_builddir)/src/libhttpserver.la qpack_primitives_SOURCES = unit/qpack_primitives_test.cpp qpack_primitives_LDADD = $(top_builddir)/src/libhttpserver.la qpack_field_section_SOURCES = unit/qpack_field_section_test.cpp -qpack_field_section_LDADD = $(top_builddir)/src/libhttpserver.la +# Allocation fault injection requires the owner statically linked: a Windows +# DLL binds its own operator new to the runtime DLL (stage-5 linkage rule). +qpack_field_section_LDADD = $(top_builddir)/src/libhttpserver_v3core.la $(V3_NETWORK_LIBS) EXTRA_DIST += data/qpack/rfc9204.hpp check_PROGRAMS += http3_frame http3_settings http3_connection @@ -1315,7 +1334,7 @@ if NATIVE_V3_TLS check_PROGRAMS += quic_interop_tls quic_interop_tls_SOURCES = unit/quic_interop_tls_test.cpp support/http3_network_owner.cpp support/http3_network_lifecycle.cpp support/quic_interop_files.cpp quic_interop_tls_CPPFLAGS = $(http3_network_owner_CPPFLAGS) -quic_interop_tls_LDADD = libquic_interop_provider.a $(top_builddir)/src/.libs/libhttpserver_v3core.a $(V3_TLS_LIBS) -lpthread -ldl +quic_interop_tls_LDADD = libquic_interop_provider.a $(top_builddir)/src/.libs/libhttpserver_v3core.a $(V3_TLS_LIBS) -lpthread $(V3_TLS_DL_LIBS) $(V3_NETWORK_LIBS) quic_interop_tls_LDFLAGS = $(tls_io_LDFLAGS) endif check_PROGRAMS += quic_interop_files @@ -1588,7 +1607,6 @@ consumer_v3_peer_policy_runtime_LDADD = $(top_builddir)/src/libhttpserver_v3core consumer_v3_peer_policy_runtime_LDFLAGS = $(V3_TLS_LDFLAGS) $(AM_LDFLAGS) check_PROGRAMS += http_cookie consumer_v3_cookie -TESTS += http_cookie consumer_v3_cookie http_cookie_SOURCES = unit/http_cookie_test.cpp http_cookie_LDADD = $(top_builddir)/src/libhttpserver.la $(V3_TLS_LIBS) http_cookie_LDFLAGS = $(V3_TLS_LDFLAGS) $(AM_LDFLAGS) @@ -1598,7 +1616,6 @@ consumer_v3_cookie_LDADD = $(top_builddir)/src/libhttpserver.la $(V3_TLS_LIBS) consumer_v3_cookie_LDFLAGS = $(V3_TLS_LDFLAGS) $(AM_LDFLAGS) check_PROGRAMS += consumer_v3_cookie_wire -TESTS += consumer_v3_cookie_wire consumer_v3_cookie_wire_SOURCES = integ/consumer_v3_cookie_wire.cpp consumer_v3_cookie_wire_CPPFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/test -I$(top_srcdir)/examples consumer_v3_cookie_wire_LDADD = $(top_builddir)/src/libhttpserver.la $(V3_TLS_LIBS) @@ -1646,11 +1663,9 @@ compiled_operations_CPPFLAGS = -I$(top_srcdir)/src compiled_operations_LDADD = $(top_builddir)/src/libhttpserver.la check_PROGRAMS += protocol_limits -TESTS += protocol_limits protocol_limits_SOURCES = unit/protocol_limits_test.cpp check_PROGRAMS += protocol_compression -TESTS += protocol_compression protocol_compression_SOURCES = unit/protocol_compression_test.cpp TESTS += integ/release_ci_test.py integ/release_platform_bundle_test.py diff --git a/test/PORTABILITY.md b/test/PORTABILITY.md index 15a7f2ab0..2a7f5e721 100644 --- a/test/PORTABILITY.md +++ b/test/PORTABILITY.md @@ -207,6 +207,132 @@ blocks. POSIX type to cast to), not a coverage loss for any production call site. +### `response_source_rig.hpp` — `filled_pipe` payload bound (all platforms) + +- **Symptom**: the rig constructor writes the whole payload through a + blocking fd before any reader exists. An 8192-byte payload hung + FreeBSD acceptance runs twice (2026-10-30 and 2026-11-30, + `threaded_pipe_sends_single_winner`, killed at the 600s wrapper + bound); macOS (16 KiB) and Linux (64 KiB) pipe capacities masked it. +- **Root cause**: POSIX kernel pipe capacities are fixed and small — + the supported floor is FreeBSD's 8 KiB default + (`kern.ipc.maxpipedata`). Unlike the Windows branch (which sizes its + own `_pipe` buffer to the payload), a POSIX rig cannot raise the + kernel capacity portably (`F_SETPIPE_SZ` is not available + everywhere). +- **Repair in force**: every `filled_pipe` payload stays at or under + 4096 bytes (documented on the class). Any future pipe-feeding test + must respect the same bound; payloads do not need to be large — the + pipe sources verify streaming and one-shot semantics, not + throughput. + +### `response_definition_test.cpp` — mid-send truncation vs stdio readahead (all platforms) + +- **Symptom**: `file_send_truncated_mid_send_fails` passed on + Linux/macOS but completed as a legal success on FreeBSD + (2026-12-02: `done==1`, outcome okay, `end_calls()==1` after the + truncation). +- **Root cause**: the reopen_file cursor reads through `std::ifstream`, + whose underlying `FILE*` buffers up to the filesystem's `st_blksize` + ahead of the pulled position (4 KiB on ext4/APFS, 32 KiB on FreeBSD + UFS, up to 128 KiB on ZFS). Bytes already staged in that user-space + buffer survive an on-disk `ftruncate` — `fread` keeps serving them + with no error and no EOF — so a 40 KiB payload whose both parked + chunks drove ~36.8 KiB of refills was fully covered by a 32 KiB + buffer. Production `pull_file` behaved correctly for what it + observed on every platform. +- **Repair in force**: the payload is 2 MiB, leaving ~2 MiB owed after + the parked chunk — past any plausible `st_blksize` — and the + wake-and-pull drive bound is 256 rounds so buffered pulls drain + before the shrink must surface. Any future mid-send-mutation test of + a stream-buffered source must keep the bytes-owed-after-park larger + than the largest plausible stdio buffer. + +### `native_websocket_client.py` — handshake churn vs the header deadline (all platforms) + +- **Symptom**: the raw handshake-split loop opens ~200 sequential + connections. On the loaded FreeBSD acceptance VM (2026-12-04, run + 47289018867), one connection was closed by the server before any + response byte ("EOF before handshake") after the malformed-refusal + cases had passed. +- **Root cause**: the fixture deliberately keeps + `options.timeouts().header` short (100 ms) to prove that deadline no + longer governs upgraded frames, and the deadline anchors at the + connection start (`connection_engine.cpp` watchdog planning). On a + slow loaded VM, a single accept-to-parse span of the churn loops can + legitimately expire before the 101 is written; the server then + closes gracefully and the client sees EOF. The server behaved to + its configuration; the churn volume is the exposure. +- **Repair in force**: `attempted()` restarts a connection the server + closed before its handshake completed on a fresh connection, at most + 4 attempts, and reports the restart count. A deterministic close + still fails the suite; everything after the 101 is never retried. + New per-connection churn loops should route through the same helper. + +### `native_websocket_client.py` — the DRAIN-LATE hard-stop race (all platforms) + +- **Symptom**: the DRAIN-LATE case failed with "unexpected EOF" while + reading the last four bytes of the in-flight `/slow` response + ("drain truncated in-flight HTTP") on the loaded darwin acceptance + runner (2026-12-06, run 47607225296), with the same test green on the + four preceding rounds. +- **Root cause**: DRAIN-LATE expires by design — the client never + answers the server Close — and the drain-scope expiry cancel hook + stops every listener (`server.cpp` `begin_drain`), hard-closing the + in-flight `/slow` connection. The scenario passes only when the + response body (flushed after the handler's 100 ms park) reaches the + client's receive buffer before that hard stop; a loaded -O0 -g + runner can surface the 100 ms resume after the 250 ms expiry, and + the truncation is then the server behaving to its configuration. +- **Repair in force**: only the DRAIN-LATE budget widens (250 ms → + 1500 ms, still inside the client's 3 s transport-close window), so + the body flush has ~1.4 s of scheduling headroom before the designed + hard stop. DRAIN completes its handshake and DRAIN-DROP drops its + ticket, so both keep the tight budget; every client assertion is + unchanged. Scenarios asserting in-flight completion across a drain + must keep the expiry budget comfortably larger than the longest + handler park they expect to survive. + +### `native_websocket_client.py` — fixture spawn on Windows + +- **Symptom**: the e2e timed out waiting for the fixture's READY line + (2026-12-04, run 47289018867) while every automake-driven native + test passed: the fixture process produced no output and exited + silently. +- **Root cause**: in this lane libtool builds the shared library, so + make-check programs normally run through the libtool wrapper script, + which puts the built DLL directories on PATH. The e2e client is the + only make-check consumer that spawns a built binary directly, and a + native Windows CreateProcess cannot execute the wrapper (a shell + script without an extension); the spawned real binary imports the + v3core DLL from `src/.libs`, which is not on PATH, and the Windows + loader terminates it before `main()`. +- **Repair in force**: `launch()` resolves the real `.libs/.exe` + on `os.name == 'nt'` and prepends `build/src/.libs` and + `build/test/.libs` to the child PATH; POSIX spawn is unchanged. + `start()` reports the fixture's exit code and captured stderr when + READY never arrives, so a future start-time death carries its own + evidence. + +## Listener port ownership (`pollsys::open_listener`) + +`open_listener` sets the platform's port-ownership socket option +before binding: `SO_REUSEADDR` on POSIX and `SO_EXCLUSIVEADDRUSE` on +Winsock. On Winsock, `SO_REUSEADDR` means "forcibly bind a port another +socket is actively serving" (Microsoft's socket-security guidance is +that server applications must use `SO_EXCLUSIVEADDRUSE` instead): two +listeners could silently share one port with nondeterministic +connection delivery, and every same-address bind-conflict scenario — +including the installed-consumer `rollback` one-shots that verify +partial-bind rollback — would observe the second bind succeed +(2026-12-02 mingw64/Windows acceptance failures, +`partial H2 bind was retained`). The exclusive option preserves the +restart property POSIX `SO_REUSEADDR` provides (a restarted server +rebinds its port once the previous listening socket closed — a +listening socket carries no TIME_WAIT of its own) while refusing every +bind onto a live listener. `io_poll_sys_listener` pins both the option +and the live-listener bind refusal on every platform. + ## Adding a new entry 1. Add a `// reason: ` comment within the 5 lines immediately diff --git a/test/installed/v3-package-matrix.json b/test/installed/v3-package-matrix.json index 210a368cb..3811a44cd 100644 --- a/test/installed/v3-package-matrix.json +++ b/test/installed/v3-package-matrix.json @@ -73,6 +73,42 @@ "external_readiness_adapter": { "sources": [ "unit/external_readiness_adapter_test.cpp" + ], + "required_cases": [ + "host_drives_read_write_and_snapshot_is_owned", + "spurious_unknown_and_wrong_generation_do_not_consume", + "omitted_then_republished_registration_rejects_old_callbacks", + "reopen_same_id_and_descriptor_rejects_every_old_flag_combination", + "detached_read_cannot_rearm_into_reopened_id", + "detached_accept_cannot_rearm_into_reopened_id", + "exclusive_retirement_expires_real_timer_without_host_dispatch", + "timers_use_host_clock_order_and_reject_decreasing_samples", + "timer_cancel_expiry_race_is_exactly_once", + "wake_is_doorbell_and_post_snapshot_work_survives_acknowledgement", + "overlapping_dispatch_rejects_without_consuming_valid_read", + "host_accept_and_close_deliver_once", + "wake_published_during_dispatch_survives_and_recursive_overlap_reject", + "release_during_completion_defers_close_and_cannot_step_replacement", + "hard_wake_failure_stops_and_unwinds_pending_work", + "decreasing_clock_rejects_a_valid_socket_event_before_io", + "exhausted_identity_never_wraps_and_closes_unregistered_socket", + "buffered_read_precedes_combined_close_error_and_duplicate_callback", + "complete_snapshots_prune_retired_connection_records", + "allocation_failure_read_batch_remains_owned_until_close", + "allocation_failure_write_batch_remains_owned_until_close", + "allocation_failure_accept_batch_remains_owned_until_close", + "allocation_failure_second_direction_keeps_first_direction_owned", + "allocation_failure_due_timers_remain_owned_until_close", + "exhausted_generation_fails_snapshot_and_shutdown_completes_once", + "successful_accept_after_listener_retirement_closes_fresh_handle", + "successful_accept_after_backend_close_closes_fresh_handle" + ], + "windows_static_cases": [ + "allocation_failure_read_batch_remains_owned_until_close", + "allocation_failure_write_batch_remains_owned_until_close", + "allocation_failure_accept_batch_remains_owned_until_close", + "allocation_failure_second_direction_keeps_first_direction_owned", + "allocation_failure_due_timers_remain_owned_until_close" ] }, "readiness_contract": { diff --git a/test/integ/behavior_parity_runner_test.py b/test/integ/behavior_parity_runner_test.py index b4af8ce80..84c10099f 100644 --- a/test/integ/behavior_parity_runner_test.py +++ b/test/integ/behavior_parity_runner_test.py @@ -5,6 +5,7 @@ import json import os from pathlib import Path +import shlex import subprocess import tempfile import unittest @@ -283,7 +284,11 @@ def test_real_current_cookie_execution_proves_three_inventory_witnesses(self): binary = Path(os.environ.get('TASK192_COOKIE_BINARY', Path.cwd() / 'http_cookie')).resolve() if not binary.is_file(): binary = self.root / 'http_cookie' - subprocess.run([os.environ.get('CXX', 'c++'), '-std=c++20', '-I' + str(ROOT / 'src'), + # configure injects flags into CXX itself (AX_CXX_COMPILE_STDCXX), + # so the value can be more than one word; split it like + # scripts/test-v3-packaged-adapters.py does. + compiler = shlex.split(os.environ.get('CXX', 'c++')) + subprocess.run([*compiler, '-std=c++20', '-I' + str(ROOT / 'src'), '-I' + str(ROOT / 'test'), str(ROOT / 'test/unit/http_cookie_test.cpp'), str(ROOT / 'src/http/cookie.cpp'), '-o', str(binary)], check=True, capture_output=True, timeout=120) result = subprocess.run([str(binary)], capture_output=True, text=True, check=True, cwd=binary.parent, timeout=30) @@ -291,10 +296,14 @@ def test_real_current_cookie_execution_proves_three_inventory_witnesses(self): 'render_guard_rejects_cr_in_parsed_value') self.assertTrue(set(names).issubset(AUDIT.executed_tests(result.stdout))) command = self.receipt['commands'][-1] - command.update(argv=[str(binary)], cwd=str(binary.parent)) + # The run above resolves through CreateProcess, and a mingw '-o name' + # link produces name.exe; record and byte-bind the file that ran. + executed = binary if binary.is_file() else Path(str(binary) + '.exe') + witness = executed.parent / '.libs' / executed.name + witness = witness if witness.is_file() else executed + command.update(argv=[str(witness)], cwd=str(binary.parent)) (self.root / command['log']).write_text(result.stdout) - actual = binary.parent / '.libs' / binary.name - self.bind_execution(command, actual if actual.is_file() else binary, 'http_cookie') + self.bind_execution(command, witness, 'http_cookie') self.inventory['capabilities'][-1]['tests'] = [ {'suite': 'http_cookie', 'name': name, 'kind': 'semantic'} for name in names] self.receipt['supporting'] = [{'id': name, 'command': 'families', 'suite': 'http_cookie', diff --git a/test/integ/http2_tls_fixture.cpp b/test/integ/http2_tls_fixture.cpp index f90a816d0..a6ab9d91f 100644 --- a/test/integ/http2_tls_fixture.cpp +++ b/test/integ/http2_tls_fixture.cpp @@ -3,10 +3,14 @@ Copyright (C) 2011-2026 Sebastiano Merlino SPDX-License-Identifier: LGPL-2.1-or-later */ +#if defined(_WIN32) +#include // socklen_t and the INADDR_LOOPBACK spelling. +#else #include #include #include #include +#endif #include #include #include @@ -40,7 +44,7 @@ struct lifetime { ~lifetime() { if (token.stop_requested()) ++counts.cancelled; } }; struct connection { - int fd; + hd::pollsys::native_socket_t fd; counters& counts; h::resume_signal& hold; h::resume_signal& upload; @@ -56,7 +60,7 @@ struct connection { std::size_t sent = 0, total = 0, magic = 24; bool connected = false, terminal = false; clock_type::time_point deadline = clock_type::now() + std::chrono::seconds(15); - connection(int socket, hd::tls_credentials_selection selection, counters& c, h::resume_signal& a, h::resume_signal& b, + connection(hd::pollsys::native_socket_t socket, hd::tls_credentials_selection selection, counters& c, h::resume_signal& a, h::resume_signal& b, const std::string& profile, h::server::resource_budget enclosing, bool probe) : fd(socket), counts(c), hold(a), upload(b), tls(std::move(selection), true) { if (probe) deadline = clock_type::now() + std::chrono::seconds(60); @@ -138,7 +142,7 @@ struct connection { hd::pollsys::fill_peer(address, peer); engine = std::make_unique(budget, routes, executor, limits, dispatch, 1, peer); } - ~connection() { engine.reset(); executor.run_pending(); close(fd); } + ~connection() { engine.reset(); executor.run_pending(); hd::pollsys::close_socket(fd); } void observe(std::span bytes) { auto skip = std::min(magic, bytes.size()); magic -= skip; bytes = bytes.subspan(skip); inspect.insert(inspect.end(), bytes.begin(), bytes.end()); @@ -155,13 +159,14 @@ struct connection { bool step(std::int16_t events) { if (clock_type::now() > deadline || total > 8 * 1024 * 1024) return false; std::array buffer{}; - if (events & POLLIN) { - auto n = recv(fd, buffer.data(), std::min(buffer.size(), tls.input_capacity()), 0); - if (n == 0) return false; - if (n > 0) { - total += n; - if (!tls.feed(std::span(buffer).first(n))) return false; - } else if (errno != EAGAIN && errno != EINTR) { + if (events & hd::pollsys::k_readable) { + const auto got = hd::pollsys::read_some(fd, buffer.data(), + std::min(buffer.size(), tls.input_capacity())); + if (got.status == hd::pollsys::sys_status::closed_reset) return false; + if (got.status == hd::pollsys::sys_status::ok) { + total += got.transferred; + if (!tls.feed(std::span(buffer).first(got.transferred))) return false; + } else if (got.status != hd::pollsys::sys_status::would_block) { return false; } } @@ -213,10 +218,11 @@ struct connection { } } if (sent < ciphertext.size()) { - auto n = send(fd, ciphertext.data() + sent, ciphertext.size() - sent, 0); - if (n > 0) { - sent += n; total += n; progress = true; - } else if (n < 0 && errno != EAGAIN && errno != EINTR) { + const auto put = hd::pollsys::write_some(fd, ciphertext.data() + sent, + ciphertext.size() - sent); + if (put.status == hd::pollsys::sys_status::ok) { + sent += put.transferred; total += put.transferred; progress = true; + } else if (put.status != hd::pollsys::sys_status::would_block) { return false; } } @@ -228,18 +234,29 @@ struct connection { } // namespace int main(int argc, char** argv) { try { +#if !defined(_WIN32) signal(SIGPIPE, SIG_IGN); +#endif +#if defined(_WIN32) + // Pinned for the process lifetime like the wake-source and listener + // references (io_poll_sys.hpp refcount note); process exit reclaims it. + if (!hd::pollsys::ensure_winsock()) throw std::runtime_error("winsock startup"); +#endif const bool probe = argc == 2 && std::string_view(argv[1]) == "--resource-probe"; std::string profile; if (argc == 3 && std::string_view(argv[1]) == "--behavior-profile") profile = argv[2]; else if (argc != 1 && !probe) throw std::runtime_error("usage: http2_tls_fixture [--behavior-profile profile]"); hd::tls_credentials_registry registry; if (!registry.replace(tls_test::credentials()).ok()) throw std::runtime_error("TLS credentials"); - int listener = socket(AF_INET, SOCK_STREAM, 0); + hd::pollsys::native_socket_t listener = ::socket(AF_INET, SOCK_STREAM, 0); sockaddr_in address{}; address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - if (listener < 0 || bind(listener, reinterpret_cast(&address), sizeof(address)) || listen(listener, 64)) throw std::runtime_error("loopback listen"); + if (listener == hd::pollsys::k_invalid_socket || bind(listener, reinterpret_cast(&address), sizeof(address)) || listen(listener, 64)) throw std::runtime_error("loopback listen"); socklen_t length = sizeof(address); getsockname(listener, reinterpret_cast(&address), &length); +#if defined(_WIN32) + hd::pollsys::set_nonblocking(listener, true); +#else fcntl(listener, F_SETFL, O_NONBLOCK); fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); +#endif std::cout << "READY " << ntohs(address.sin_port) << std::endl; auto enclosing = h2test::budget(); counters counts; h::resume_signal hold, upload; @@ -248,10 +265,25 @@ int main(int argc, char** argv) { const auto deadline = clock_type::now() + std::chrono::minutes(15); bool running = true; while (running && clock_type::now() < deadline && accepted < 1024) { - std::vector polls{{listener, POLLIN, 0}, {STDIN_FILENO, POLLIN, 0}}; - for (auto& peer : peers) polls.push_back({peer->fd, static_cast(POLLIN | (peer->sent < peer->ciphertext.size() ? POLLOUT : 0)), 0}); - if (poll(polls.data(), polls.size(), 20) < 0 && errno != EINTR) throw std::runtime_error("poll"); - if (polls[1].revents & POLLIN) { + std::vector polls{{listener, hd::pollsys::k_readable, 0}}; +#if !defined(_WIN32) + // The stdin command channel is driven only by the POSIX parity + // lanes; on Windows the fixture builds but never serves commands. + polls.push_back({STDIN_FILENO, hd::pollsys::k_readable, 0}); +#endif + for (auto& peer : peers) + polls.push_back({peer->fd, static_cast(hd::pollsys::k_readable + | (peer->sent < peer->ciphertext.size() ? hd::pollsys::k_writable : 0)), 0}); + const std::size_t peer_base = polls.size() - peers.size(); + if (hd::pollsys::poll_call(polls.data(), polls.size(), 20) < 0) { +#if defined(_WIN32) + if (::WSAGetLastError() != WSAEINTR) throw std::runtime_error("poll"); +#else + if (errno != EINTR) throw std::runtime_error("poll"); +#endif + } +#if !defined(_WIN32) + if (polls[1].revents & hd::pollsys::k_readable) { char input[1024]; auto n = read(STDIN_FILENO, input, sizeof(input)); if (n <= 0) running = false; else commands.append(input, n); @@ -280,19 +312,20 @@ int main(int argc, char** argv) { } if (commands.size() > 4096) throw std::runtime_error("command limit"); } - if (polls[1].revents & POLLHUP) running = false; + if (polls[1].revents & hd::pollsys::k_poll_hangup) running = false; +#endif for (std::size_t i = peers.size(); i > 0; --i) { - if (!peers[i - 1]->step(polls[i + 1].revents)) peers.erase(peers.begin() + i - 1); + if (!peers[i - 1]->step(polls[peer_base + i - 1].revents)) peers.erase(peers.begin() + i - 1); } - if ((polls[0].revents & POLLIN) && peers.size() < 16) { - int fd = accept(listener, nullptr, nullptr); - if (fd >= 0) { - fcntl(fd, F_SETFL, O_NONBLOCK); ++accepted; + if ((polls[0].revents & hd::pollsys::k_readable) && peers.size() < 16) { + hd::pollsys::native_socket_t fd = hd::pollsys::k_invalid_socket; + if (hd::pollsys::accept_one(listener, &fd).status == hd::pollsys::sys_status::ok) { + ++accepted; peers.push_back(std::make_unique(fd, registry.acquire()->select_default(), counts, hold, upload, profile, enclosing, probe)); } } } - peers.clear(); close(listener); + peers.clear(); hd::pollsys::close_socket(listener); if (running) throw std::runtime_error("fixture bound exhausted"); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } diff --git a/test/integ/http3_full_gate_runner_test.py b/test/integ/http3_full_gate_runner_test.py index df4715733..4b04a01ad 100644 --- a/test/integ/http3_full_gate_runner_test.py +++ b/test/integ/http3_full_gate_runner_test.py @@ -3,6 +3,7 @@ import copy import importlib.util import json +import os from pathlib import Path import sys import tempfile @@ -93,6 +94,7 @@ def test_artifact_hashes_are_verified_and_reads_bounded(self): with self.assertRaises(self.gate.GateFailure): self.gate.verify_artifacts([record]) + @unittest.skipIf(os.name == 'nt', 'output privacy is the POSIX 0700 mode bit; Windows directories carry ACLs instead') def test_output_directory_is_fresh_and_private(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / 'evidence' @@ -163,6 +165,7 @@ def test_network_child_success_requires_manifest_and_artifacts(self): with self.assertRaises(self.gate.GateFailure): self.gate.validate_network('http3-interop', Path(tmp), {}) + @unittest.skipIf(os.name == 'nt', 'the fake native suites are POSIX shebang scripts; real suites on Windows are PE executables') def test_native_runner_rejects_missing_suite_nonzero_and_empty_summary(self): with tempfile.TemporaryDirectory() as tmp: build = Path(tmp) / 'build' @@ -297,6 +300,7 @@ def test_failed_process_retains_exact_command_receipt(self): self.assertEqual(saved, row) self.assertEqual(saved['returncode'], 77) + @unittest.skipIf(os.name == 'nt', 'the fake native suite is a POSIX shebang script; real suites on Windows are PE executables') def test_native_binary_identity_and_actual_configuration_are_retained(self): with tempfile.TemporaryDirectory() as tmp: build = Path(tmp) / 'build' @@ -327,6 +331,7 @@ def test_cxx20_configuration_accepts_configure_compiler_standard(self): with self.assertRaisesRegex(self.gate.GateFailure, r'C\+\+20'): self.gate.build_configuration(build, False, False) + @unittest.skipIf(os.name == 'nt', 'the fake native suite and its Makefile fixtures are POSIX executable scripts and test(1) bodies') def test_reusing_configured_build_preserves_prior_build_evidence(self): with tempfile.TemporaryDirectory() as tmp: build = Path(tmp) / 'build' @@ -345,6 +350,7 @@ def test_reusing_configured_build_preserves_prior_build_evidence(self): self.gate.native_stage(build, ['http3_frame'], Path(tmp) / 'native-off') self.assertTrue(prior.is_file(), 'incremental builds must preserve prior evidence') + @unittest.skipIf(os.name == 'nt', 'the fake tshark/editcap tools are POSIX shebang scripts') def test_capture_preflight_requires_editcap_and_the_declared_decoder(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) diff --git a/test/integ/http3_udp_fixture.cpp b/test/integ/http3_udp_fixture.cpp index 39becd588..9d73546f6 100644 --- a/test/integ/http3_udp_fixture.cpp +++ b/test/integ/http3_udp_fixture.cpp @@ -1,5 +1,9 @@ /* Copyright (C) 2026 Sebastiano Merlino; SPDX-License-Identifier: LGPL-2.1-or-later */ +#if defined(_WIN32) +#include "../../examples/host_poll.hpp" +#else #include +#endif #include #include @@ -376,14 +380,22 @@ struct fixture { // its successful completion is committed in the next owner turn. if (executor.pending() || (send && send->state()->applied()) || receive->state()->applied()) return true; auto snapshot = backend.interests(); - if (snapshot.wake) snapshot.sockets.push_back(*snapshot.wake); - std::vector descriptors{{STDIN_FILENO, POLLIN, 0}}; - for (auto& interest : snapshot.sockets) - descriptors.push_back({static_cast(interest.handle.value), static_cast((interest.readable ? POLLIN : 0) | (interest.writable ? POLLOUT : 0)), 0}); auto due = lifetime; for (auto& [id, connection] : connections) if (auto deadline = connection->deadline()) due = std::min(due, *deadline); if (snapshot.next_deadline) due = std::min(due, *snapshot.next_deadline); +#if defined(_WIN32) + // The stdin command channel is driven only by the POSIX parity + // lanes; on Windows the fixture builds but never serves commands. + const auto park = std::min(due, clock_type::now() + std::chrono::milliseconds(1000)); + if (!backend.dispatch(v3_host::wait(snapshot, park), clock_type::now()).ok()) + throw std::runtime_error("backend dispatch failed"); + return true; +#else + if (snapshot.wake) snapshot.sockets.push_back(*snapshot.wake); + std::vector descriptors{{STDIN_FILENO, POLLIN, 0}}; + for (auto& interest : snapshot.sockets) + descriptors.push_back({static_cast(interest.handle.value), static_cast((interest.readable ? POLLIN : 0) | (interest.writable ? POLLOUT : 0)), 0}); int timeout = std::max(std::int64_t{0}, std::chrono::ceil(due - clock_type::now()).count()); if (poll(descriptors.data(), descriptors.size(), timeout) < 0) throw std::runtime_error("poll failed"); if (descriptors[0].revents & (POLLIN | POLLHUP)) { @@ -401,6 +413,7 @@ struct fixture { } if (!backend.dispatch(events, clock_type::now()).ok()) throw std::runtime_error("backend dispatch failed"); return true; +#endif } }; } // namespace diff --git a/test/integ/native_http1_conformance_test.cpp b/test/integ/native_http1_conformance_test.cpp index d5726a46a..9f465451b 100644 --- a/test/integ/native_http1_conformance_test.cpp +++ b/test/integ/native_http1_conformance_test.cpp @@ -64,7 +64,11 @@ int main(int argc, char** argv) { io_loopback::write_all(r.pair.peer(), wire.data(), end); require(until([&] { return first.load() == 1; }), c, "admission before EOF"); io_loopback::write_all(r.pair.peer(), wire.data() + end, wire.size() - end); +#if defined(_WIN32) + ::shutdown(r.pair.peer(), SD_SEND); +#else ::shutdown(r.pair.peer(), SHUT_WR); +#endif } else { io_loopback::write_all(r.pair.peer(), wire.data(), wire.size()); } diff --git a/test/integ/native_protocol_memory_test.cpp b/test/integ/native_protocol_memory_test.cpp index d799643aa..9543d2183 100644 --- a/test/integ/native_protocol_memory_test.cpp +++ b/test/integ/native_protocol_memory_test.cpp @@ -21,6 +21,22 @@ #if defined(__APPLE__) #include +#elif defined(__FreeBSD__) +#include +#include +#include +#include +#elif defined(_WIN32) +// Lean windows.h keeps the later websocket_engine_helpers.hpp Winsock include +// conflict-free (io_poll_sys.hpp applies the same guard pair). +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include #else #include #include @@ -46,6 +62,22 @@ std::size_t resident_bytes() { check(task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast(&info), &count) == KERN_SUCCESS, "process memory measurement unavailable"); return info.resident_size; +#elif defined(__FreeBSD__) + // FreeBSD ships no procfs by default; the native source is the + // per-process sysctl MIB (kinfo_proc's resident page count). + int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, static_cast(::getpid())}; + kinfo_proc info{}; + size_t size = sizeof info; + check(::sysctl(mib, 4, &info, &size, nullptr, 0) == 0 + && size >= offsetof(kinfo_proc, ki_rssize) + sizeof info.ki_rssize, + "process memory measurement unavailable"); + return static_cast(info.ki_rssize) + * static_cast(::sysconf(_SC_PAGESIZE)); +#elif defined(_WIN32) + PROCESS_MEMORY_COUNTERS counters{}; + check(::GetProcessMemoryInfo(::GetCurrentProcess(), &counters, sizeof counters) != 0, + "process memory measurement unavailable"); + return counters.WorkingSetSize; #else std::ifstream stat("/proc/self/statm"); std::size_t total = 0, resident = 0; @@ -55,8 +87,8 @@ std::size_t resident_bytes() { } void small_sockets(rig& r) { int small = 2048; - check(setsockopt(r.pair.local(), SOL_SOCKET, SO_SNDBUF, &small, sizeof small) == 0, "local send buffer"); - check(setsockopt(r.pair.peer(), SOL_SOCKET, SO_SNDBUF, &small, sizeof small) == 0, "peer send buffer"); + check(shrink_send_buffer(r.pair.local(), small), "local send buffer"); + check(shrink_send_buffer(r.pair.peer(), small), "peer send buffer"); r.config.body.max_staged_bytes = 1024; r.config.outbox.max_queue_bytes = 1024; r.config.timeouts.body_idle = 10s; r.config.timeouts.write_idle = 10s; @@ -191,6 +223,17 @@ void http_output() { return engine_access::queues(*r.engine).output == 1024 && std::chrono::steady_clock::now() - steady >= 20ms; }), "stalled peer stops outbox admission"); plateau(r, "HTTP output", produce); + // The CPU-sample window inside plateau() is idle, and a peer whose kernel + // buffers outlast the shrunken send buffers (Windows loopback auto-tunes + // the receive side) can drain the whole 1024-byte outbox during it, so + // re-saturate to a steady full queue before asserting admission stopped. + steady = std::chrono::steady_clock::now(); + check(until([&] { + auto before = accepted; produce(1024); + if (accepted != before) steady = std::chrono::steady_clock::now(); + std::this_thread::sleep_for(1ms); + return engine_access::queues(*r.engine).output == 1024 && std::chrono::steady_clock::now() - steady >= 20ms; + }), "output re-saturated after the parked window"); check(sink.push(data).kind == h::detail::body_push::full, "output admission stopped"); std::string wire; std::array scratch; @@ -292,6 +335,17 @@ void websocket_output() { return driver->usage().output_bytes >= 462 && std::chrono::steady_clock::now() - steady >= 20ms; }), "stalled peer stops WebSocket output admission"); plateau(r, "WebSocket output", produce); + // The same idle-window absorption as the HTTP output phase: the parked + // CPU-sample window can drain the buffered output into peer kernel buffers + // that outlast the shrunken send buffers, so re-saturate to a steady + // watermark before asserting admission stopped. + steady = std::chrono::steady_clock::now(); + check(until([&] { + auto before = messages; produce(1024); + if (messages != before) steady = std::chrono::steady_clock::now(); + std::this_thread::sleep_for(1ms); + return driver->usage().output_bytes >= 462 && std::chrono::steady_clock::now() - steady >= 20ms; + }), "WebSocket output re-saturated after the parked window"); check(session.try_send(h::websocket::message_kind::binary, data).disposition == h::websocket::send_disposition::backpressured, "WebSocket output admission stopped"); std::string wire; diff --git a/test/integ/native_websocket_client.py b/test/integ/native_websocket_client.py index ae70c706a..ae97c6093 100644 --- a/test/integ/native_websocket_client.py +++ b/test/integ/native_websocket_client.py @@ -10,11 +10,34 @@ import subprocess import threading import time +from pathlib import Path + + +def launch(binary): + """Resolve the fixture command per host. + + POSIX spawn goes through the libtool wrapper unchanged. A native Windows + CreateProcess cannot execute that wrapper (a shell script without an + extension), and the real binary under .libs imports the built DLLs from + src/.libs, which only the wrapper would have put on PATH; spawn the real + binary with the build's DLL directories prepended instead. + """ + if os.name != 'nt': + return [binary], None + exe = Path(str(binary) + '.exe') + real = exe.parent / '.libs' / exe.name + command = str(real) if real.is_file() else str(exe) + env = dict(os.environ) + build = exe.resolve().parent.parent + for directory in (build / 'src' / '.libs', build / 'test' / '.libs'): + env['PATH'] = str(directory) + os.pathsep + env.get('PATH', '') + return [command], env def start(binary): - process = subprocess.Popen([binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, text=True, bufsize=1) + argv, env = launch(binary) + process = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, bufsize=1, env=env) events = queue.Queue() threading.Thread(target=lambda: [events.put(line.strip()) for line in process.stdout], daemon=True).start() process.task122_errors = [] @@ -35,7 +58,12 @@ def drain_errors(): except BaseException: process.kill() process.wait(timeout=5) - raise + # The fixture's stderr is otherwise invisible: the drain thread only + # reports it when stop()'s exit-code assert fires, which start-time + # deaths never reach. Surface it with the exit code before re-raising. + process.task122_error_reader.join(timeout=1) + raise RuntimeError('fixture produced no READY: exit=' + str(process.returncode) + + ' stderr=' + ''.join(process.task122_errors)[-2000:]) from None def wait_event(events, prefix, deadline=10): @@ -164,6 +192,34 @@ def close(self): self.socket.close() +def attempted(port, drive, restarts, attempts=4): + """Run one fresh connection through drive, restarting within bounds. + + The fixture deliberately keeps the HTTP header deadline short (100ms), and + that deadline anchors at the connection start, so on a loaded slow VM one + accept-to-parse span of the many connections these churn loops open can + legitimately expire before the 101 is written; the server then closes the + connection gracefully (the client sees EOF before any bytes). That + deadline expiration is not the wire contract under test, so a connection + the server closed before its handshake completed is retried on a fresh + connection, with the restart count reported. A deterministic close (a real + server defect) exhausts the bound and still fails; everything after the + 101 (frame echoes, close handshake) is never retried. + """ + for attempt in range(attempts): + peer = Peer(port) + try: + drive(peer) + if attempt: + restarts.append(attempt) + return peer + except AssertionError as error: + peer.close() + if attempt + 1 == attempts or 'EOF before handshake' not in str(error): + raise + raise AssertionError('unreachable') + + def raw_cases(port, events, process): peer = Peer(port) peer.socket.sendall(request('/idle')) @@ -178,36 +234,46 @@ def raw_cases(port, events, process): assert peer.receive() == (8, b'\x03\xe8') peer.close() print('Parked writer/application send wake/HTTP timer removal PASS', flush=True) + restarts = [] malformed = [({'Sec-WebSocket-Key': 'YQ=='}, 400), ({'Sec-WebSocket-Version': '12'}, 426), ({'Origin': 'https://evil.example.com'}, 403), ({'Upgrade': 'websocket,'}, 400), ({'Connection': 'xupgrade'}, 400), ({'Sec-WebSocket-Key': None}, 400), ({'Sec-WebSocket-Protocol': 'chat,chat'}, 400), ({'Content-Length': '1'}, 400)] for replacement, status in malformed: - peer = Peer(port) - peer.socket.sendall(request(**replacement)) - head = peer.head() - assert head.startswith(f'HTTP/1.1 {status} '.encode()), head - if status == 426: - assert b'Sec-WebSocket-Version: 13' in head - peer.close() + payload = request(**replacement) + + def drive(peer, payload=payload, status=status): + peer.socket.sendall(payload) + head = peer.head() + assert head.startswith(f'HTTP/1.1 {status} '.encode()), head + if status == 426: + assert b'Sec-WebSocket-Version: 13' in head + + attempted(port, drive, restarts).close() # Every boundary of the handshake; masked first frame in the final read. head = request() for split in range(len(head) + 1): - peer = Peer(port) - peer.socket.sendall(head[:split]) - peer.socket.sendall(head[split:] + frame(1, b'first') + frame(2, b'second') + frame(1, b'third')) - response = peer.head() - assert response.startswith(b'HTTP/1.1 101 '), response - accept = base64.b64encode(hashlib.sha1(b'dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()) - assert b'Sec-WebSocket-Accept: ' + accept in response - assert b'Connection: Upgrade' in response - assert b'Content-Length' not in response and b'Transfer-Encoding' not in response + first, rest = head[:split], head[split:] + frame(1, b'first') + frame(2, b'second') + frame(1, b'third') + + def drive(peer, first=first, rest=rest): + peer.socket.sendall(first) + peer.socket.sendall(rest) + response = peer.head() + assert response.startswith(b'HTTP/1.1 101 '), response + accept = base64.b64encode(hashlib.sha1(b'dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()) + assert b'Sec-WebSocket-Accept: ' + accept in response + assert b'Connection: Upgrade' in response + assert b'Content-Length' not in response and b'Transfer-Encoding' not in response + + peer = attempted(port, drive, restarts) assert peer.receive() == (1, b'first') assert peer.receive() == (2, b'second') assert peer.receive() == (1, b'third') peer.socket.sendall(frame(8, b'\x03\xe8')) assert peer.receive() == (8, b'\x03\xe8') peer.close() + if restarts: + print(str(len(restarts)) + ' header-deadline restarts on fresh connections', flush=True) print('Raw refusals/all handshake splits/coalesced frames/queue-full suffix PASS', flush=True) peer = Peer(port) peer.socket.sendall(request() + b'GET / HTTP/1.1\r\n\r\n') diff --git a/test/integ/native_websocket_fixture.cpp b/test/integ/native_websocket_fixture.cpp index 3eed268e0..276975511 100644 --- a/test/integ/native_websocket_fixture.cpp +++ b/test/integ/native_websocket_fixture.cpp @@ -211,7 +211,17 @@ int main() { while (std::getline(std::cin, command)) { if (command == "STOP") break; if (command == "DRAIN" || command == "DRAIN-DROP" || command == "DRAIN-LATE") { - auto begun = server.begin_drain(std::chrono::milliseconds(250), ticket); + // DRAIN-LATE expires by design (the client never answers the + // server Close), and the drain-scope expiry cancel hook stops + // every listener, truncating the in-flight /slow response. The + // body flush must precede that hard stop by a margin that + // tolerates loaded-runner scheduling of the 100ms park (2026-12-06 + // darwin acceptance, drain truncated in-flight HTTP): only the + // expiry-bound budget widens to 1500ms, still inside the client's + // 3s transport-close window. DRAIN completes its handshake and + // DRAIN-DROP drops its ticket, so they keep the tight budget. + auto begun = server.begin_drain( + std::chrono::milliseconds(command == "DRAIN-LATE" ? 1500 : 250), ticket); if (!begun.ok()) { failed = true; break; diff --git a/test/integ/protocol_fuzz_runner_test.py b/test/integ/protocol_fuzz_runner_test.py index 4b56d9f10..d3039e94d 100755 --- a/test/integ/protocol_fuzz_runner_test.py +++ b/test/integ/protocol_fuzz_runner_test.py @@ -1,17 +1,66 @@ #!/usr/bin/env python3 +import os import pathlib +import platform +import shutil import subprocess import tempfile import unittest ROOT = pathlib.Path(__file__).resolve().parents[2] +BASH = 'bash' + + +def native_compile_argv(tokens): + """compile.sh records the bash-side argv: script-derived paths carry msys + form on Windows -- both the drive spelling (/d/...) and mount spellings + (/tmp/... for directories under an msys mount such as the root tmp, which + is how bash pwd canonicalizes the build directory) -- while user-supplied + arguments stay verbatim in the native form the exec conversion and + compile.jsonl show. Resolve every bash-side path token through the same + bash (cygpath), then compare paths separator- and case-insensitively.""" + if os.name != 'nt': + return tokens + import re + paths = [] + for token in tokens: + match = re.match(r'^(-[A-Za-z])?(/.+)$', token) + if match: + paths.append(match.group(2)) + resolved = subprocess.run([BASH, '-c', 'for path; do cygpath -w "$path"; done', + 'cygpath', *paths], capture_output=True, text=True, timeout=10) + assert resolved.returncode == 0, resolved.stderr + spelling = dict(zip(paths, resolved.stdout.splitlines())) + comparable = [] + for token in tokens: + match = re.match(r'^(-[A-Za-z])?(/.+)$', token) + if match is None: + comparable.append(os.path.normcase(os.path.normpath(token))) + else: + text = (match.group(1) or '') + spelling[match.group(2)] + comparable.append(os.path.normcase(os.path.normpath(text))) + return comparable + + +def windows_comparable(argv): + """The compile.jsonl side of the comparison already carries the native + form; normalize it with the same rule so both representations meet.""" + if os.name != 'nt': + return argv + return [os.path.normcase(os.path.normpath(a)) for a in argv] +if platform.system() == 'Windows': + # CreateProcess searches System32 before PATH for an unqualified name; + # resolve through PATH like scripts/lib/release_ci.py does. + found = shutil.which('bash', path=os.environ.get('PATH', '')) + if found: + BASH = str(pathlib.Path(found).resolve()) class FuzzRunnerTest(unittest.TestCase): def test_unknown_or_empty_target_fails_before_compiler(self): for selection in ('', 'hpack bogus'): with tempfile.TemporaryDirectory() as build: - result = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + result = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', selection, '--compiler', '/missing/compiler'], capture_output=True, text=True, timeout=10) @@ -20,7 +69,7 @@ def test_unknown_or_empty_target_fails_before_compiler(self): def test_selected_http2_missing_compiler_is_fatal(self): with tempfile.TemporaryDirectory() as build: - result = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + result = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', 'hpack http2_engine', '--compiler', '/missing/compiler'], capture_output=True, text=True, timeout=10) @@ -29,7 +78,7 @@ def test_selected_http2_missing_compiler_is_fatal(self): def test_selected_quic_missing_compiler_is_fatal(self): with tempfile.TemporaryDirectory() as build: - result = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + result = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', 'quic_parser quic_state', '--compiler', '/missing/compiler'], capture_output=True, text=True, timeout=10) @@ -39,7 +88,7 @@ def test_selected_quic_missing_compiler_is_fatal(self): def test_quic_state_requires_tls_off_configuration_before_building(self): for config in (None, '#define NATIVE_V3_TLS 1\n'): with tempfile.TemporaryDirectory() as build: - args = ['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + args = [BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', 'quic_state', '--compiler', '/usr/bin/true'] if config is not None: pathlib.Path(build, 'config.h').write_text(config) @@ -57,7 +106,7 @@ def test_stateful_selections_validate_configuration_before_compilation(self): ('quic_tls_callbacks', '#define NATIVE_V3_TLS 1\n', 'provider flags')] for target, config, expected in cases: with self.subTest(target=target, config=config), tempfile.TemporaryDirectory() as build: - args = ['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + args = [BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', target, '--compiler', '/usr/bin/true'] if config is not None: pathlib.Path(build, 'config.h').write_text(config) @@ -71,7 +120,7 @@ def test_http3_and_qpack_missing_compiler_is_fatal(self): for target in ('http3_engine', 'qpack'): with self.subTest(target=target), tempfile.TemporaryDirectory() as build: result = subprocess.run([ - 'bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', target, '--compiler', '/missing/compiler'], capture_output=True, text=True, timeout=10) @@ -82,7 +131,7 @@ def test_http3_and_qpack_require_tls_off_before_compilation(self): for target in ('http3_engine', 'qpack'): for config in (None, '#define NATIVE_V3_TLS 1\n'): with self.subTest(target=target, config=config), tempfile.TemporaryDirectory() as build: - args = ['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + args = [BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', target, '--compiler', '/usr/bin/true'] if config is not None: pathlib.Path(build, 'config.h').write_text(config) @@ -118,7 +167,7 @@ def test_http3_qpack_build_and_invocation_contract(self): environment = dict(os.environ, FUZZ_ARGUMENT_LOG=str(location / 'compile.jsonl'), FUZZ_RUN_LOG=str(location / 'run.jsonl')) result = subprocess.run([ - 'bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', str(build), '--targets', 'http3_engine qpack http1_head', '--compiler', str(compiler), '--native-config-dir', str(config), '--runs', '9', '--seconds', '2'], env=environment, @@ -134,8 +183,8 @@ def test_http3_qpack_build_and_invocation_contract(self): self.assertIn('-I' + str(config), arguments) self.assertIn(str(ROOT / 'src/detail/http3_connection.cpp'), arguments) self.assertEqual(arguments[-2:], ['-o', str(build / target / 'fuzz')]) - self.assertEqual(shlex.split((build / target / 'compile.sh').read_text()), - [str(compiler)] + arguments) + self.assertEqual(native_compile_argv(shlex.split((build / target / 'compile.sh').read_text())), + windows_comparable([str(compiler)] + arguments)) self.assertTrue((build / target / 'sources.list').is_file()) invocation = next(args for args in runs if args[0] == str(build / target / 'fuzz')) for flag in ('-runs=9', '-max_total_time=2', '-timeout=5', '-rss_limit_mb=512', @@ -148,8 +197,8 @@ def test_http3_qpack_build_and_invocation_contract(self): self.assertNotIn('', head) self.assertIn('-fsanitize=fuzzer,address,undefined', head) self.assertEqual(head[-2:], ['-o', str(build / 'http1_head/fuzz')]) - self.assertEqual(shlex.split((build / 'http1_head/compile.sh').read_text()), - [str(compiler)] + head) + self.assertEqual(native_compile_argv(shlex.split((build / 'http1_head/compile.sh').read_text())), + windows_comparable([str(compiler)] + head)) self.assertEqual(len(builds), 4) # Instrumentation probe and three selected targets. def test_callback_provider_arguments_preserve_boundaries_and_link_order(self): @@ -179,7 +228,7 @@ def test_callback_provider_arguments_preserve_boundaries_and_link_order(self): + '\nV3_TLS_LIBS = ' + shlex.join(libs) + '\n') build = location / 'fuzz output' log = location / 'compile.jsonl' - result = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + result = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', str(build), '--targets', 'quic_tls_callbacks', '--compiler', str(compiler), '--native-config-dir', str(config), '--runs', '1', '--seconds', '1'], @@ -192,14 +241,14 @@ def test_callback_provider_arguments_preserve_boundaries_and_link_order(self): self.assertEqual(arguments[start:start + 5], ['-DQUIC_TLS_CALLBACKS_LIBFUZZER', '-I' + str(ROOT / 'test'), '-I' + str(config)] + cflags) self.assertEqual(arguments[-5:], libs + ['-o', str(build / 'quic_tls_callbacks/fuzz')]) - self.assertEqual(shlex.split((build / 'quic_tls_callbacks/compile.sh').read_text()), - [str(compiler)] + arguments) + self.assertEqual(native_compile_argv(shlex.split((build / 'quic_tls_callbacks/compile.sh').read_text())), + windows_comparable([str(compiler)] + arguments)) self.assertEqual((build / 'quic_tls_callbacks/provider.log').read_text().splitlines(), cflags + libs) def test_seed_and_corpus_arguments_reject_invalid_inputs_before_compilation(self): for seed in ('0', '-1', '4294967296', '$(touch marker)', '12x'): with self.subTest(seed=seed), tempfile.TemporaryDirectory() as build: - result = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + result = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--seed', seed, '--compiler', '/missing/compiler'], capture_output=True, text=True, timeout=10) self.assertEqual(result.returncode, 2) @@ -220,7 +269,7 @@ def test_restored_corpus_is_merged_without_following_links_or_overwriting_seeds( restored = corpus / 'http1_head' / 'extra' restored.write_bytes(b'unique restored input') build = location / 'build' - result = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + result = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', str(build), '--compiler', str(compiler), '--targets', 'http1_head', '--seed', '987', '--corpus-dir', str(corpus)], capture_output=True, text=True, timeout=10) self.assertEqual(result.returncode, 0, result.stderr) @@ -230,10 +279,25 @@ def test_restored_corpus_is_merged_without_following_links_or_overwriting_seeds( self.assertIn(fixture.read_bytes(), inputs) reproduction = (build / 'http1_head/reproduce.sh').read_text() self.assertIn('-seed=987', reproduction) - self.assertIn(str(corpus / 'http1_head'), reproduction) + if os.name != 'nt': + self.assertIn(str(corpus / 'http1_head'), reproduction) + else: + # reproduce.sh records the bash-side command, whose paths + # carry msys form (/tmp/..., /d/...) on Windows; resolve the + # recorded paths through the same bash before comparing. + import shlex + recorded = [token for token in shlex.split(reproduction) if token.startswith('/')] + resolved = subprocess.run([BASH, '-c', 'for path; do cygpath -w "$path"; done', + 'cygpath', *recorded], capture_output=True, text=True, timeout=10) + self.assertEqual(resolved.returncode, 0, resolved.stderr) + self.assertIn(os.path.normcase(os.path.normpath(str(corpus / 'http1_head'))), + [os.path.normcase(os.path.normpath(line)) for line in resolved.stdout.splitlines()]) restored.unlink() - restored.symlink_to(ROOT / 'configure.ac') - bad = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + try: + restored.symlink_to(ROOT / 'configure.ac') + except OSError: + self.skipTest('symlink creation unavailable on this platform') + bad = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', str(location / 'bad'), '--compiler', str(compiler), '--targets', 'http1_head', '--corpus-dir', str(corpus)], capture_output=True, text=True, timeout=10) @@ -242,7 +306,7 @@ def test_restored_corpus_is_merged_without_following_links_or_overwriting_seeds( def test_requested_unavailable_compiler_fails(self): with tempfile.TemporaryDirectory() as build: - result = subprocess.run(['bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + result = subprocess.run([BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--compiler', '/missing/compiler'], capture_output=True, text=True, timeout=10) self.assertNotEqual(result.returncode, 0) @@ -257,7 +321,7 @@ def test_callback_provider_flags_reject_unresolved_or_malformed_arguments(self): (source / 'Makefile').write_text( 'V3_TLS_CFLAGS = ' + flags + '\nV3_TLS_LIBS = -lssl -lcrypto\n') result = subprocess.run([ - 'bash', str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), + BASH, str(ROOT / 'scripts/run-v3-protocol-fuzz.sh'), '--build-dir', build, '--targets', 'quic_tls_callbacks', '--native-config-dir', build, '--compiler', '/usr/bin/true'], cwd=build, capture_output=True, text=True, timeout=10) diff --git a/test/integ/protocol_gate_runner_test.py b/test/integ/protocol_gate_runner_test.py index 046bfc4f1..5fe925bb5 100755 --- a/test/integ/protocol_gate_runner_test.py +++ b/test/integ/protocol_gate_runner_test.py @@ -2,17 +2,26 @@ """Exercise the task-local runner's fail-closed contract.""" import os import pathlib +import platform +import shutil import subprocess import tempfile import unittest ROOT = pathlib.Path(__file__).resolve().parents[2] RUNNER = ROOT / 'scripts/run-v3-http1-websocket-gates.sh' +BASH = 'bash' +if platform.system() == 'Windows': + # CreateProcess searches System32 before PATH for an unqualified name; + # resolve through PATH like scripts/lib/release_ci.py does. + found = shutil.which('bash', path=os.environ.get('PATH', '')) + if found: + BASH = str(pathlib.Path(found).resolve()) class GateRunnerTest(unittest.TestCase): def invoke(self, build, *args): - return subprocess.run(['bash', str(RUNNER), '--build-dir', str(build), + return subprocess.run([BASH, str(RUNNER), '--build-dir', str(build), '--log-dir', str(build / 'logs'), *args], capture_output=True, text=True, timeout=15) @@ -52,7 +61,7 @@ def test_source_archive_preserves_executable_failure(self): env = os.environ.copy() # This miniature source fixture is independent of the enclosing release archive. env.pop('V3_RELEASE_IDENTITY', None) - result = subprocess.run(['bash', str(runner), '--build-dir', str(build), + result = subprocess.run([BASH, str(runner), '--build-dir', str(build), '--tests', 'failing'], capture_output=True, timeout=15, env=env) self.assertEqual(result.returncode, 7) diff --git a/test/integ/quic_interop_endpoint.cpp b/test/integ/quic_interop_endpoint.cpp index eff667dc0..7883777ba 100644 --- a/test/integ/quic_interop_endpoint.cpp +++ b/test/integ/quic_interop_endpoint.cpp @@ -1,6 +1,5 @@ /* Copyright (C) 2026 Sebastiano Merlino; SPDX-License-Identifier: LGPL-2.1-or-later */ #include -#include #include #include #include @@ -20,6 +19,7 @@ #include #include #include "../support/http3_network_owner.hpp" +#include "../../examples/host_poll.hpp" #include "../unit/io_udp_backend_contract.hpp" namespace { volatile std::sig_atomic_t stopping = 0; @@ -294,30 +294,16 @@ struct fixture { if (executor.pending() || (send && send->state()->applied()) || receive->state()->applied()) return true; auto snapshot = backend.interests(); - if (snapshot.wake) - snapshot.sockets.push_back(*snapshot.wake); - std::vector descriptors; - for (auto& interest : snapshot.sockets) - descriptors.push_back( - {static_cast(interest.handle.value), static_cast((interest.readable ? POLLIN : 0) | (interest.writable ? POLLOUT : 0)), 0}); auto due = lifetime; for (auto& [id, connection] : connections) if (auto deadline = connection->deadline()) due = std::min(due, *deadline); if (snapshot.next_deadline) due = std::min(due, *snapshot.next_deadline); - int timeout = std::min(1000, std::max(std::int64_t{0}, std::chrono::ceil(due - clock_type::now()).count())); - if (poll(descriptors.data(), descriptors.size(), timeout) < 0 && !stopping) - throw std::runtime_error("poll failed"); - std::vector events; - for (unsigned i = 0; i < snapshot.sockets.size(); ++i) - if (descriptors[i].revents) { - auto& interest = snapshot.sockets[i]; - auto revents = descriptors[i].revents; - events.push_back({interest.key, interest.generation, static_cast(revents & POLLIN), static_cast(revents & POLLOUT), - static_cast(revents & POLLHUP), static_cast(revents & (POLLERR | POLLNVAL))}); - } - if (!backend.dispatch(events, clock_type::now()).ok()) + // Park at most one second past the earliest due work; the shared + // host helper owns the platform poll (WSAPoll on Windows). + const auto park = std::min(due, clock_type::now() + std::chrono::milliseconds(1000)); + if (!backend.dispatch(v3_host::wait(snapshot, park), clock_type::now()).ok()) throw std::runtime_error("backend dispatch failed"); return true; } @@ -333,7 +319,9 @@ int main() { hqnet::files root_check(env("LIBHTTPSERVER_INTEROP_WWW", "/www")); const auto logs = env("LIBHTTPSERVER_INTEROP_LOGS", "/logs"); std::filesystem::create_directories(logs); +#if !defined(_WIN32) if (chmod(logs.c_str(), 0700) != 0) throw std::runtime_error("log permissions failed"); +#endif const auto pcap = logs + "/packets.pcap"; std::signal(SIGTERM, stop); std::signal(SIGINT, stop); diff --git a/test/integ/release_artifact_test.py b/test/integ/release_artifact_test.py index 589e9469b..cdec65b2c 100644 --- a/test/integ/release_artifact_test.py +++ b/test/integ/release_artifact_test.py @@ -5,6 +5,7 @@ import json import os from pathlib import Path +import platform import shutil import subprocess import sys @@ -90,7 +91,14 @@ def test_http1_archive_runner_records_verified_snapshot_and_rejects_changed_sour build = self.directory / 'build'; (build / 'test').mkdir(parents=True) program = build / 'test/probe'; program.write_text('#!/bin/sh\nexit 0\n'); program.chmod(0o755) runner = self.source / 'scripts/run-v3-http1-websocket-gates.sh' - argv = ['bash', str(runner), '--build-dir', str(build), '--tests', 'probe', '--compiler', sys.executable] + # CreateProcess searches System32 before PATH for an unqualified name; + # resolve through PATH like scripts/lib/release_ci.py does. + bash = 'bash' + if platform.system() == 'Windows': + found = shutil.which('bash', path=os.environ.get('PATH', '')) + if found: + bash = str(Path(found).resolve()) + argv = [bash, str(runner), '--build-dir', str(build), '--tests', 'probe', '--compiler', sys.executable] with patch.dict(os.environ, {'V3_RELEASE_IDENTITY': str(self.path)}): result = subprocess.run(argv, capture_output=True, text=True, timeout=15) self.assertEqual(result.returncode, 0, result.stderr) diff --git a/test/integ/release_ci_test.py b/test/integ/release_ci_test.py index 6bed1fbe9..1cd0c5bff 100755 --- a/test/integ/release_ci_test.py +++ b/test/integ/release_ci_test.py @@ -215,19 +215,28 @@ def test_immutable_download_checks_source_run_attempt_digest_and_zip_members(sel expected=dict(repository='etr/libhttpserver',run_id='12',run_attempt='1',workflow_head='d'*40,artifact_id='23') metadata=dict(id=23,expired=False,created_at='2026-10-15T03:01:00Z',workflow_run={'id':12,'head_sha':'d'*40},digest='sha256:'+hashlib.sha256(archive.read_bytes()).hexdigest()) run=dict(id=12,run_attempt=1,run_started_at='2026-10-15T03:00:00Z',repository={'full_name':'etr/libhttpserver'},head_sha='d'*40) - ci.verify_download(archive,metadata,run,expected,metadata['digest'],self.directory/'download') + ci.verify_download(archive,metadata,run,'2026-10-15T03:00:00Z',expected,metadata['digest'],self.directory/'download') for field,value in [('id',24),('expired',True),('digest','sha256:'+'a'*64),('created_at','2026-10-14T03:01:00Z')]: altered=dict(metadata,**{field:value}) with self.subTest(field=field),self.assertRaises(ValueError): - ci.verify_download(archive,altered,run,expected,metadata['digest'],self.directory/field) + ci.verify_download(archive,altered,run,'2026-10-15T03:00:00Z',expected,metadata['digest'],self.directory/field) for changed in (dict(run,run_attempt=2),dict(run,head_sha='a'*40),dict(run,repository={'full_name':'other/repo'})): - with self.assertRaises(ValueError): ci.verify_download(archive,metadata,changed,expected,metadata['digest'],self.directory/'wrongrun') + with self.assertRaises(ValueError): ci.verify_download(archive,metadata,changed,'2026-10-15T03:00:00Z',expected,metadata['digest'],self.directory/'wrongrun') + # A --failed rerun (attempt 2) legitimately re-consumes the attempt-1 + # artifact: created after the run, before the rerun attempt started. + rerun=dict(expected,run_attempt='2') + ci.verify_download(archive,metadata,dict(run,run_attempt=2,run_started_at='2026-10-15T05:00:00Z'), + '2026-10-15T03:00:00Z',rerun,metadata['digest'],self.directory/'rerun-download') + with self.assertRaises(ValueError): + ci.verify_download(archive,dict(metadata,created_at='2026-10-14T03:01:00Z'), + dict(run,run_attempt=2,run_started_at='2026-10-15T05:00:00Z'),'2026-10-15T03:00:00Z', + rerun,metadata['digest'],self.directory/'rerun-stale') for index,name in enumerate(('../outside','/outside','C:/outside','a\\..\\outside')): bad=self.directory/('escape-%d.zip'%index) with zipfile.ZipFile(bad,'w') as stream: stream.writestr(name,'escape') digest='sha256:'+hashlib.sha256(bad.read_bytes()).hexdigest() with self.subTest(name=name),self.assertRaises(ValueError): - ci.verify_download(bad,dict(metadata,digest=digest),run,expected,digest,self.directory/('badzip-%d'%index)) + ci.verify_download(bad,dict(metadata,digest=digest),run,'2026-10-15T03:00:00Z',expected,digest,self.directory/('badzip-%d'%index)) def test_pr_download_binds_api_branch_head_and_retains_merge_source_descriptor(self): import hashlib @@ -245,16 +254,16 @@ def test_pr_download_binds_api_branch_head_and_retains_merge_source_descriptor(s run=dict(id=38848731938,run_attempt=1,head_sha=head,event='pull_request', repository={'full_name':'etr/libhttpserver'},run_started_at='2026-10-16T04:04:45Z') destination=self.directory/'pr-download' - ci.verify_download(archive,metadata,run,expected,digest,destination) + ci.verify_download(archive,metadata,run,'2026-10-16T04:04:45Z',expected,digest,destination) self.assertEqual(json.loads((destination/'selected.json').read_text())['commit'],merge) for index, altered in enumerate((dict(expected,workflow_head=merge),dict(expected,workflow_head='a'*40), dict(expected,run_id='38848731939'),dict(expected,run_attempt='2'),dict(expected,repository='other/repo'))): with self.subTest(expected=altered),self.assertRaises(ValueError): - ci.verify_download(archive,metadata,run,altered,digest,self.directory/('wrong-pr-'+str(index))) + ci.verify_download(archive,metadata,run,'2026-10-16T04:04:45Z',altered,digest,self.directory/('wrong-pr-'+str(index))) for field,value in (('id',12024142303),('workflow_run',dict(id=38848731939,head_sha=head)), ('workflow_run',dict(id=38848731938,head_sha=merge)),('digest','sha256:'+'a'*64)): with self.subTest(field=field,value=value),self.assertRaises(ValueError): - ci.verify_download(archive,dict(metadata,**{field:value}),run,expected,digest,self.directory/'wrong-origin') + ci.verify_download(archive,dict(metadata,**{field:value}),run,'2026-10-16T04:04:45Z',expected,digest,self.directory/'wrong-origin') def test_download_entrypoint_uses_trusted_api_head_instead_of_pr_merge_sha(self): import argparse @@ -278,7 +287,8 @@ def transport(argv,stdout,check): env=dict(GITHUB_REPOSITORY='etr/libhttpserver',GITHUB_RUN_ID='38848731938',GITHUB_RUN_ATTEMPT='1', GITHUB_SHA=merge,WORKFLOW_HEAD_SHA=head) args=argparse.Namespace(artifact_id='12024142302',digest=digest,output=self.directory/'cli-download') - with patch.dict(os.environ,env),patch('subprocess.check_output',side_effect=[json.dumps(metadata),json.dumps(run)]),patch('subprocess.run',side_effect=transport): + with patch.dict(os.environ,env),patch('subprocess.check_output', + side_effect=[json.dumps(metadata),json.dumps(run),json.dumps(dict(created_at='2026-10-16T04:04:45Z'))]),patch('subprocess.run',side_effect=transport): entrypoint.download(args) self.assertEqual(json.loads((args.output/'selected.json').read_text())['commit'],merge) diff --git a/test/integ/release_gate_runner_test.py b/test/integ/release_gate_runner_test.py index 378dd5cf2..c22e33a9e 100644 --- a/test/integ/release_gate_runner_test.py +++ b/test/integ/release_gate_runner_test.py @@ -62,6 +62,7 @@ def test_inventory_cannot_omit_duplicate_or_change_required_gate(self): with self.subTest(edit=edit), self.assertRaises(ValueError): self.gate.validate_inventory(bad) + @unittest.skipIf(os.name == 'nt', 'the fake make/native-case/deadline tools and check-examples.sh are POSIX executable scripts, and a deadline kill surfaces as a signal exit; Windows-native equivalents are exercised by the real lanes') def test_packaged_example_guard_requires_http3_source_and_rejects_unknown_target(self): root = self.directory / 'examples-package' (root / 'scripts').mkdir(parents=True) @@ -300,6 +301,7 @@ def test_platform_import_requires_same_artifact_and_rejects_duplicates(self): row['archive_sha256'] = 'historical'; path.write_text(json.dumps(row)) with self.assertRaises(ValueError): self.gate.import_platform_receipts(manifest, [path]) + @unittest.skipIf(os.name == 'nt', 'the fake make/native-case/deadline tools and check-examples.sh are POSIX executable scripts, and a deadline kill surfaces as a signal exit; Windows-native equivalents are exercised by the real lanes') def test_native_fixture_discovers_success_tool_on_path(self): from unittest.mock import patch selected = self.directory / 'selected-tools'; selected.mkdir() @@ -310,6 +312,7 @@ def test_native_fixture_discovers_success_tool_on_path(self): commands = json.loads((self.directory / 'suite-logs/commands.json').read_text()) self.assertEqual(commands[0]['argv'][0], str(executable)) + @unittest.skipIf(os.name == 'nt', 'the fake make/native-case/deadline tools and check-examples.sh are POSIX executable scripts, and a deadline kill surfaces as a signal exit; Windows-native equivalents are exercised by the real lanes') def test_positive_native_suite_cannot_bypass_packaged_library_equivalence(self): from types import SimpleNamespace from release_execution import ReleaseAttempt @@ -340,6 +343,7 @@ def test_tag_check_rejects_receipt_from_another_gate(self): manifest['stages'][0]['receipt']['gate'] = 'parity' with self.assertRaises(ValueError): self.gate.check_tag_ready(manifest) + @unittest.skipIf(os.name == 'nt', 'the fake make/native-case/deadline tools and check-examples.sh are POSIX executable scripts, and a deadline kill surfaces as a signal exit; Windows-native equivalents are exercised by the real lanes') def test_native_fixtures_do_not_require_a_host_timeout_installation(self): from unittest.mock import patch import release_execution @@ -373,6 +377,7 @@ def test_native_check_rejects_missing_deadline_before_make(self): attempt.native_check(commands, self.directory, attempt.env, 10) self.assertEqual(commands.records, []) + @unittest.skipIf(os.name == 'nt', 'the fake make/native-case/deadline tools and check-examples.sh are POSIX executable scripts, and a deadline kill surfaces as a signal exit; Windows-native equivalents are exercised by the real lanes') def test_cxx_gate_bounds_each_native_test_before_waiting_for_aggregate(self): from types import SimpleNamespace from release_execution import ReleaseAttempt @@ -491,6 +496,7 @@ def validate(_): self.assertEqual(row['status'], 'failed') (self.directory / 'child.json').unlink(missing_ok=True) + @unittest.skipIf(os.name == 'nt', 'the fake make/native-case/deadline tools and check-examples.sh are POSIX executable scripts, and a deadline kill surfaces as a signal exit; Windows-native equivalents are exercised by the real lanes') def test_timeout_nonzero_and_missing_tool_retain_prior_success_and_logs(self): self.manifest = {'stages': []} self.run_stage('ok', 'print("success witness")') @@ -755,6 +761,7 @@ def test_tsan_timer_allocation_hook_has_only_its_named_existing_exclusion(self): with self.subTest(output=bad), self.assertRaises(ValueError): checks.native_counts(ROOT, 'task_resume_signal_lifetime', bad, True) + @unittest.skipIf(os.name == 'nt', 'the fake make/native-case/deadline tools and check-examples.sh are POSIX executable scripts, and a deadline kill surfaces as a signal exit; Windows-native equivalents are exercised by the real lanes') def test_package_receipt_survives_later_native_build_and_check(self): from types import SimpleNamespace from release_execution import ReleaseAttempt diff --git a/test/integ/release_platform_bundle_test.py b/test/integ/release_platform_bundle_test.py index c646844c0..2e8a66000 100755 --- a/test/integ/release_platform_bundle_test.py +++ b/test/integ/release_platform_bundle_test.py @@ -132,7 +132,7 @@ def test_valid_archive_import_rejects_duplicate_members_and_namespace_collisions stream.add(root/'Darwin/catalog.json',arcname='Darwin/catalog.json') with self.assertRaises(ValueError): module.unpack(duplicate,root/'duplicate') - def platform_origin_fixture(self): + def platform_origin_fixture(self, platform='Darwin'): module = self.module() import package_matrix as matrix import release_artifact as identity @@ -147,7 +147,7 @@ def write(path, value): path.write_text(json.dumps(value)) header = root / 'provider.h'; header.write_bytes(b'selected OpenSSL\r\n') selected = dict(archive_sha256='a'*64, snapshot_sha256='b'*64, extracted_sha256=hashlib.sha256(json.dumps({},sort_keys=True).encode()).hexdigest(), tls='both', sanitizer='none') - write(package/'summary.json', dict(status='passed', host='Darwin', lanes={'no':{},'yes':{}}, + write(package/'summary.json', dict(status='passed', host=platform, lanes={'no':{},'yes':{}}, revision='d'*40, provider_header_sha256=identity.sha256(header), release_artifact={'archive':{'sha256':'a'*64}, 'source':{'snapshot_sha256':'b'*64,'head':'d'*40}})) for mode in ('no','yes'): @@ -160,7 +160,7 @@ def write(path, value): public[linkage]=dict(dependencies=graph, compile={'dependencies':[]}, cells=[{'configurations':inventory['cases']},{'configurations':inventory['cases']}]) suites={} - for name, definition in matrix.suites(inventory, 'Darwin', mode).items(): + for name, definition in matrix.suites(inventory, platform, mode).items(): cases=definition.get('required_cases',[]) or ['fixture_case'] log=lane/('integration-'+linkage)/(name+'.log') log.parent.mkdir(parents=True, exist_ok=True) @@ -171,28 +171,56 @@ def write(path, value): write(lane/'audit.json',dict(violations=[],tls_mode=mode,public=public)) origin=dict(package=str(package), source_root=str(root/'source'), source_commit='d'*40, provider_header=str(header), native={}) # This test checks installed matrix origin independently; native origin is mandatory in complete bundles. - counts=module.package_origin(ROOT, origin, lambda p: json.loads(Path(p).read_text()), lambda p: Path(p).read_text(), selected, 'Darwin') + counts=module.package_origin(ROOT, origin, lambda p: json.loads(Path(p).read_text()), lambda p: Path(p).read_text(), selected, platform) self.assertGreater(counts['tests'],0) wrong_origin=dict(origin,source_commit='e'*40) with self.assertRaises(ValueError): - module.package_origin(ROOT,wrong_origin,lambda p:json.loads(Path(p).read_text()),lambda p:Path(p).read_text(),selected,'Darwin') + module.package_origin(ROOT,wrong_origin,lambda p:json.loads(Path(p).read_text()),lambda p:Path(p).read_text(),selected,platform) for mode in ('no','yes'): build=root/('native-'+mode); (build/'test').mkdir(parents=True) names=['protocol_fuzz_replay','hpack_corpus','http2_fuzz_replay','quic_fuzz_replay', - 'quic_recovery_fuzz_replay','http3_fuzz_replay','qpack_fuzz_replay','io_kqueue_backend'] + 'quic_recovery_fuzz_replay','http3_fuzz_replay','qpack_fuzz_replay','io_' + inventory['platforms'][platform] + '_backend'] if mode=='yes': names.append('quic_tls_callbacks_fuzz_replay') for name in names: (build/'test'/(name+'.trs')).write_text(':test-result: PASS\n') (build/'test/test-suite.log').write_text('# TOTAL: %d\n# PASS: %d\n# SKIP: 0\n# XFAIL: 0\n# FAIL: 0\n# XPASS: 0\n# ERROR: 0\n'%(len(names),len(names))) origin['native'][mode]=dict(build=str(build), tests=names) counts=checks.counts(counts['tests']+len(names),counts['checks']+len(names)) artifacts=[dict(path=str(header),sha256=identity.sha256(header),bytes=header.stat().st_size)] - row=dict(id='Darwin',identity=selected,archive_sha256='a'*64,origin=origin,status='passed',artifacts=artifacts, - receipt=dict(status='passed',gate='Darwin',identity=selected,counts=counts,artifacts=artifacts)) + row=dict(id=platform,identity=selected,archive_sha256='a'*64,origin=origin,status='passed',artifacts=artifacts, + receipt=dict(status='passed',gate=platform,identity=selected,counts=counts,artifacts=artifacts)) retained=root/'retained' - catalog=module.retain(retained,'Darwin',row,[p for p in root.rglob('*') if p.is_file()]) + catalog=module.retain(retained,platform,row,[p for p in root.rglob('*') if p.is_file()]) module.validate_origin(ROOT,row,catalog) return module, root, package, header, selected, origin, row, catalog + def test_windows_origin_retains_static_fault_proof_and_accepts_dll_profile(self): + import package_matrix as matrix + module, _, package, _, selected, origin, _, _ = self.platform_origin_fixture('Windows') + definition = matrix.load()['suites']['external_readiness_adapter'] + + def rewrite(linkage, cases): + directory = package / 'tls-no' / ('integration-' + linkage) + suites_path = directory / 'suites.json' + suites = json.loads(suites_path.read_text()) + receipt = suites['external_readiness_adapter'] + log = Path(receipt['log']) + log.write_text(''.join('Running test (%d): %s\n' % (i, case) for i, case in enumerate(cases)) + + '%d tests executed\n%d checks\n-> 0 failures\n-> 0 skipped\n' % (len(cases), len(cases))) + receipt.update(matrix.suite_result(log.read_text(), 0)) + suites_path.write_text(json.dumps(suites)) + + ordinary = [name for name in definition['required_cases'] if name not in definition['windows_static_cases']] + rewrite('shared', ordinary) + try: + module.package_origin(ROOT, origin, lambda p: json.loads(Path(p).read_text()), + lambda p: Path(p).read_text(), selected, 'Windows') + except ValueError as error: + self.fail('valid DLL/static split rejected: ' + str(error)) + rewrite('static', ordinary) + with self.assertRaisesRegex(ValueError, 'required suite cases absent'): + module.package_origin(ROOT, origin, lambda p: json.loads(Path(p).read_text()), + lambda p: Path(p).read_text(), selected, 'Windows') + def test_platform_origin_rejects_pruned_mandatory_native_suite(self): import release_checks as checks module, root, _, _, _, _, row, catalog = self.platform_origin_fixture() diff --git a/test/support/quic_interop_files.cpp b/test/support/quic_interop_files.cpp index dcf6a5e22..119602441 100644 --- a/test/support/quic_interop_files.cpp +++ b/test/support/quic_interop_files.cpp @@ -3,6 +3,13 @@ #include #include #include +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include // _open/_read/_lseeki64 (no openat/pread in MSYS2). +#include // GetFileAttributes: the O_NOFOLLOW reparse check. +#endif #include #include #include @@ -17,9 +24,23 @@ struct files::request { bool finished = false; ~request() { if (fd >= 0) ::close(fd); } }; +#if defined(_WIN32) +files::files(const std::string& root) : root_path_(root) { + // No directory descriptors on Windows: the root stays a validated + // path instead of the POSIX O_DIRECTORY directory fd. The REPARSE_ + // POINT check refuses a symlinked/junctioned root just like POSIX + // O_NOFOLLOW refuses to follow one. + const DWORD attributes = ::GetFileAttributesA(root_path_.c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_REPARSE_POINT) + || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) { + throw std::runtime_error("interop root unavailable"); + } +} +#else files::files(const std::string& root) : root_(::open(root.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)) { if (root_ < 0) throw std::runtime_error("interop root unavailable"); } +#endif files::~files() { if (root_ >= 0) ::close(root_); } void files::receive(hd::quic_stream_state& stream, hd::quic_flow_control& flow) { auto& owned = requests_[stream.id()]; @@ -43,7 +64,19 @@ void files::receive(hd::quic_stream_state& stream, hd::quic_flow_control& flow) if (end + 2 != r.line.size() || !r.line.starts_with("GET /")) throw std::runtime_error("malformed interop GET"); const auto name = r.line.substr(5, end - 5); if (name.empty() || name == "." || name == ".." || name.find_first_of("/\\\0", 0, 3) != std::string::npos) throw std::runtime_error("unsafe interop path"); +#if defined(_WIN32) + // The O_NOFOLLOW analog: refuse reparse points instead of following + // them (best-effort, not atomic like POSIX O_NOFOLLOW; the name was + // already validated against separators and dot entries above). + const std::string full = root_path_ + '/' + name; + const DWORD attributes = ::GetFileAttributesA(full.c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_REPARSE_POINT)) { + throw std::runtime_error("interop file unavailable"); + } + const auto fd = ::_open(full.c_str(), _O_RDONLY | _O_BINARY | _O_NOINHERIT); +#else const auto fd = ::openat(root_, name.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC); +#endif struct stat info{}; if (fd < 0) throw std::runtime_error("interop file unavailable"); if (fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) || info.st_size < 0 || info.st_size > 16 * 1024 * 1024) { @@ -65,7 +98,22 @@ void files::pump(hd::quic_flow_control& flow, hd::quic_recovery& recovery) { if (!allowance) continue; std::array bytes{}; const auto count = allowance.bytes; +#if defined(_WIN32) + // pread(2) emulation: the fixture pumps requests sequentially on + // one thread, so the lseek-restore dance cannot interleave with + // another reader of the same descriptor. + const __int64 restored = ::_lseeki64(r.fd, 0, SEEK_CUR); + if (::_lseeki64(r.fd, static_cast<__int64>(r.offset), SEEK_SET) < 0) { + throw std::runtime_error("interop file changed or read failed"); + } + const int seen = count ? ::_read(r.fd, bytes.data(), static_cast(count)) : 0; + ::_lseeki64(r.fd, restored, SEEK_SET); + if (seen < 0 || static_cast(seen) != count) { + throw std::runtime_error("interop file changed or read failed"); + } +#else if (count && pread(r.fd, bytes.data(), count, r.offset) != static_cast(count)) throw std::runtime_error("interop file changed or read failed"); +#endif const bool fin = r.offset + count == r.size; auto retained = recovery.retain_stream({id, r.offset, std::span(bytes).first(count), fin}); if (!retained) { diff --git a/test/support/quic_interop_files.hpp b/test/support/quic_interop_files.hpp index 2050b4c70..acaf198d5 100644 --- a/test/support/quic_interop_files.hpp +++ b/test/support/quic_interop_files.hpp @@ -20,6 +20,11 @@ class files final { std::size_t active_files() const; private: struct request; +#if defined(_WIN32) + // Windows has no directory descriptors: the validated root path + // stands in for the POSIX O_DIRECTORY directory fd. + std::string root_path_; +#endif int root_ = -1; std::map> requests_; }; diff --git a/test/timeout-wrapper.sh b/test/timeout-wrapper.sh new file mode 100755 index 000000000..7b962efcf --- /dev/null +++ b/test/timeout-wrapper.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Bound one native test program so a single hung binary cannot consume +# a whole CI make-check command budget. Hosts without timeout(1) +# (macOS by default) run tests exactly as before. +if command -v timeout >/dev/null 2>&1; then + exec timeout -k 60 600 "$@" +fi +exec "$@" diff --git a/test/unit/connection_engine_test.cpp b/test/unit/connection_engine_test.cpp index 5eecea11b..13931924c 100644 --- a/test/unit/connection_engine_test.cpp +++ b/test/unit/connection_engine_test.cpp @@ -68,6 +68,7 @@ #include #include "./io_loopback.hpp" +#include "./websocket_engine_helpers.hpp" #include "./littletest.hpp" namespace { @@ -301,7 +302,7 @@ struct scenario { explicit scenario(srv::timeout_options timeouts_in) : scenario(srv::budget_limits(), timeouts_in) { } - bool start_engine() { + bool create_engine() { if (!pair.ok()) return false; backend.adopt_connection(kConnId, pair.detach_local()); engine = std::make_shared(backend, pool, registry, @@ -310,6 +311,11 @@ struct scenario { [this] { stopped.store(true); }); + return true; + } + + bool start_engine() { + if (!create_engine()) return false; engine->start(); return true; } @@ -1215,6 +1221,45 @@ LT_BEGIN_AUTO_TEST(connection_engine_suite, quiesce_idle_connection_closes_promp LT_CHECK(reaches_eof(s.pair.peer())); LT_END_AUTO_TEST(quiesce_idle_connection_closes_promptly) +// TASK-110 pin: a quiesce that carries a server drain deadline keeps the +// watchdog armed at that deadline. HTTP/1 enforces the drain budget's +// hard stop only through the watchdog (enforce_timeout's scope expiry), +// so the close mark alone must not retire it while the deadline is +// pending -- a stalled close handoff may not outlive the drain budget. +// Loops stay unstarted so the plan is sampled before any close path can +// complete; a deadline-less quiesce stays terminal exactly as before. +LT_BEGIN_AUTO_TEST(connection_engine_suite, quiesce_with_drain_deadline_keeps_watchdog_armed) + srv::timeout_options timeouts; + timeouts.header = std::chrono::milliseconds(10000); + scenario s(timeouts); + LT_CHECK(s.create_engine()); + const auto drain_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + s.engine->quiesce(drain_deadline); + const auto armed = httpserver::detail::connection_engine_test_access::deadline(*s.engine); + LT_CHECK(armed.has_value()); + if (armed) LT_CHECK(*armed <= drain_deadline); + scenario plain; + LT_CHECK(plain.create_engine()); + plain.engine->quiesce(); + LT_CHECK(!httpserver::detail::connection_engine_test_access::deadline(*plain.engine).has_value()); +LT_END_AUTO_TEST(quiesce_with_drain_deadline_keeps_watchdog_armed) + +// The armed drain deadline must not delay the ordinary close chain: a +// started engine quiesced with a far drain budget still ends (and the +// transport closes) promptly, as in the deadline-less case above. +LT_BEGIN_AUTO_TEST(connection_engine_suite, quiesce_with_drain_deadline_still_closes_promptly) + srv::timeout_options timeouts; + timeouts.header = std::chrono::milliseconds(10000); + scenario s(timeouts); + LT_CHECK(s.start_engine()); + const auto began = std::chrono::steady_clock::now(); + s.engine->quiesce(std::chrono::steady_clock::now() + std::chrono::seconds(10)); + LT_CHECK(wait_until([&s] { return s.stopped.load(); })); + const auto elapsed = std::chrono::steady_clock::now() - began; + LT_CHECK(elapsed < std::chrono::milliseconds(5000)); + LT_CHECK(reaches_eof(s.pair.peer())); +LT_END_AUTO_TEST(quiesce_with_drain_deadline_still_closes_promptly) + // TASK-110: the counted units bracket the exchange -- the handler runs // between the connection unit and its own exchange unit (2 live), and // the count returns to zero once the engine finalized. diff --git a/test/unit/external_readiness_adapter_test.cpp b/test/unit/external_readiness_adapter_test.cpp index e10a216e2..70ee2601c 100644 --- a/test/unit/external_readiness_adapter_test.cpp +++ b/test/unit/external_readiness_adapter_test.cpp @@ -39,6 +39,7 @@ #include "./io_backend_contract.hpp" #include "./littletest.hpp" +#ifndef LHS_TEST_DLL_LINKAGE // Fault injection is confined to this test executable and the dispatching // thread. Restore allocation before asserting or shutting down the backend. namespace { @@ -79,6 +80,7 @@ void* operator new(std::size_t size) { void operator delete(void* memory) noexcept { std::free(memory); } void operator delete(void* memory, std::size_t) noexcept { std::free(memory); } #endif +#endif // LHS_TEST_DLL_LINKAGE namespace srv = httpserver::server; namespace { @@ -203,6 +205,7 @@ void detached_reopen(littletest::test_runner* __lt_tr__, const char* __lt_name__ LT_CHECK_EQ(fx.backend.pending_count(), std::size_t{0}); } +#ifndef LHS_TEST_DLL_LINKAGE void failed_direction_collection(littletest::test_runner* __lt_tr__, const char* __lt_name__, hd::io_op_kind kind) { fixture fx; @@ -253,6 +256,8 @@ void failed_direction_collection(littletest::test_runner* __lt_tr__, LT_CHECK_EQ(second.delivered.load(), 1); } +#endif // LHS_TEST_DLL_LINKAGE + void accepted_after_teardown(littletest::test_runner* __lt_tr__, const char* __lt_name__, bool shutdown) { fixture fx; @@ -855,6 +860,9 @@ LT_BEGIN_AUTO_TEST(external_adapter_suite, complete_snapshots_prune_retired_conn } LT_END_AUTO_TEST(complete_snapshots_prune_retired_connection_records) +#ifndef LHS_TEST_DLL_LINKAGE +// PE DLL allocations bind their own allocator imports. These cases run against +// the installed static library, where this executable's override reaches them. LT_BEGIN_AUTO_TEST(external_adapter_suite, allocation_failure_read_batch_remains_owned_until_close) failed_direction_collection(__lt_tr__, __lt_name__, hd::io_op_kind::read); LT_END_AUTO_TEST(allocation_failure_read_batch_remains_owned_until_close) @@ -923,6 +931,7 @@ LT_BEGIN_AUTO_TEST(external_adapter_suite, allocation_failure_due_timers_remain_ LT_CHECK_EQ(first.delivered.load(), 1); LT_CHECK_EQ(second.delivered.load(), 1); LT_END_AUTO_TEST(allocation_failure_due_timers_remain_owned_until_close) +#endif // LHS_TEST_DLL_LINKAGE LT_BEGIN_AUTO_TEST(external_adapter_suite, exhausted_generation_fails_snapshot_and_shutdown_completes_once) fixture fx; diff --git a/test/unit/forms_multipart_files_test.cpp b/test/unit/forms_multipart_files_test.cpp index e69c7b578..023210137 100644 --- a/test/unit/forms_multipart_files_test.cpp +++ b/test/unit/forms_multipart_files_test.cpp @@ -48,6 +48,7 @@ #include #include #include +#include // NOLINT(build/c++17): C++20 tests. #include #include #include @@ -73,8 +74,15 @@ constexpr const char* k_type = "multipart/form-data; boundary=P9B"; class scratch_dir { public: scratch_dir() { - char tmpl[] = "/tmp/lht-multipart-XXXXXX"; - char* made = mkdtemp(tmpl); + // A literal "/tmp" template only exists on POSIX (a native Windows + // binary resolves a leading slash against the current drive's root, + // whose /tmp does not exist), so anchor the mkdtemp template at the + // platform temp directory like the other suites. + std::string pattern = std::filesystem::temp_directory_path().string() + + "/lht-multipart-XXXXXX"; + std::vector tmpl(pattern.begin(), pattern.end()); + tmpl.push_back('\0'); + char* made = mkdtemp(tmpl.data()); if (made != nullptr) path_ = made; } @@ -443,7 +451,10 @@ LT_BEGIN_AUTO_TEST(forms_multipart_files_suite, keep_callback_once) LT_CHECK(drive(sink, body).empty()); } LT_CHECK(dir.entries().size() == static_cast(1)); - LT_CHECK(read_file(dir.path() + "/" + dir.entries()[0]) == "kept"); + // CHECK macros are fail-continue, so guard the follow-up indexing. + if (dir.entries().size() == 1) { + LT_CHECK(read_file(dir.path() + "/" + dir.entries()[0]) == "kept"); + } } { scratch_dir dir; diff --git a/test/unit/http1_websocket_upgrade_test.cpp b/test/unit/http1_websocket_upgrade_test.cpp index 720927c2f..97d8f13e2 100644 --- a/test/unit/http1_websocket_upgrade_test.cpp +++ b/test/unit/http1_websocket_upgrade_test.cpp @@ -19,7 +19,6 @@ 02110-1301 USA */ -#include #include #include #include @@ -44,7 +43,7 @@ LT_END_SUITE(upgrade_transport_suite) LT_BEGIN_AUTO_TEST(upgrade_transport_suite, abandoned_session_during_stalled_101_still_has_deadline) rig r; std::string protocol(32768, 'p'); int small = 1024; - LT_CHECK(::setsockopt(r.pair.local(), SOL_SOCKET, SO_SNDBUF, &small, sizeof small) == 0); + LT_CHECK(shrink_send_buffer(r.pair.local(), small)); r.config.timeouts.handshake = 30ms; r.config.timeouts.write_idle = 10s; r.routes.route(h::http::method::known(h::http::method_id::get), "/", [&](h::exchange& x) -> h::task { h::ws_upgrade_options options; options.subprotocols = {protocol}; @@ -80,7 +79,7 @@ LT_BEGIN_AUTO_TEST(upgrade_transport_suite, shutdown_wakes_receive_and_releases_ LT_END_AUTO_TEST(shutdown_wakes_receive_and_releases_engine_without_cycle) LT_BEGIN_AUTO_TEST(upgrade_transport_suite, prior_http_and_complete_101_precede_frame_under_partial_writes) rig r; std::string protocol(32768, 'p'); int small = 1024; - LT_CHECK(::setsockopt(r.pair.local(), SOL_SOCKET, SO_SNDBUF, &small, sizeof small) == 0); + LT_CHECK(shrink_send_buffer(r.pair.local(), small)); r.routes.route(h::http::method::known(h::http::method_id::get), "/before", [](h::exchange& x) -> h::task { h::http::fields fields; fields.append("Content-Length", "3"); x.start_response(h::http::status::from_code(200), fields); @@ -153,12 +152,14 @@ LT_BEGIN_AUTO_TEST(upgrade_transport_suite, delayed_drain_and_requeue_notificati const auto admitted_deadline = h::detail::connection_engine_test_access::deadline(*r.engine); std::byte buffer[32]; const auto offered = driver->copy_output(buffer); // Mirror the writer's successful socket write, bookkeeping, then consume. - LT_CHECK_EQ(::send(r.pair.local(), buffer, 1, 0), 1); + const auto first_write = sys::write_some(r.pair.local(), buffer, 1); + LT_CHECK(first_write.status == sys::sys_status::ok && first_write.transferred == 1); h::detail::connection_engine_test_access::progress(*r.engine, true); LT_CHECK(driver->consume_output(1).ok()); const auto partial_deadline = h::detail::connection_engine_test_access::deadline(*r.engine); LT_CHECK(partial_deadline && partial_deadline > admitted_deadline); - LT_CHECK_EQ(::send(r.pair.local(), buffer + 1, offered - 1, 0), static_cast(offered - 1)); + const auto rest_write = sys::write_some(r.pair.local(), buffer + 1, offered - 1); + LT_CHECK(rest_write.status == sys::sys_status::ok && rest_write.transferred == offered - 1); h::detail::connection_engine_test_access::progress(*r.engine, true); const auto written_deadline = h::detail::connection_engine_test_access::deadline(*r.engine); @@ -288,7 +289,7 @@ LT_END_AUTO_TEST(ready_peer_reads_output_after_quiet_idle) LT_BEGIN_AUTO_TEST(upgrade_transport_suite, stalled_output_after_quiet_idle_gets_full_write_interval) std::atomic timed_out{false}; h::resume_signal send; rig r; r.config.timeouts.write_idle = 100ms; int small = 1024; - LT_CHECK(::setsockopt(r.pair.local(), SOL_SOCKET, SO_SNDBUF, &small, sizeof small) == 0); + LT_CHECK(shrink_send_buffer(r.pair.local(), small)); r.routes.route(h::http::method::known(h::http::method_id::get), "/", [&](h::exchange& x) -> h::task { auto result = co_await x.upgrade({}); if (!result.session) co_return; @@ -346,7 +347,7 @@ LT_END_AUTO_TEST(prior_app_close_anchor_survives_drain_and_stale_timer_is_reject LT_BEGIN_AUTO_TEST(upgrade_transport_suite, close_during_stalled_101_expires_without_promotion_reset) std::atomic closes{0}; std::string reason; rig r; std::string protocol(32768, 'p'); int small = 1024; - LT_CHECK(::setsockopt(r.pair.local(), SOL_SOCKET, SO_SNDBUF, &small, sizeof small) == 0); + LT_CHECK(shrink_send_buffer(r.pair.local(), small)); r.config.timeouts.ws_close = 30ms; r.config.timeouts.handshake = 2s; r.config.timeouts.write_idle = 10s; r.routes.route(h::http::method::known(h::http::method_id::get), "/", [&](h::exchange& x) -> h::task { h::ws_upgrade_options options; options.subprotocols = {protocol}; diff --git a/test/unit/io_operation_test.cpp b/test/unit/io_operation_test.cpp index 7fd2799d1..dfe9a3382 100644 --- a/test/unit/io_operation_test.cpp +++ b/test/unit/io_operation_test.cpp @@ -426,10 +426,18 @@ LT_BEGIN_AUTO_TEST(io_operation_suite, suspend_races_cross_thread_apply) std::chrono::microseconds(rng() % 100)); state->apply(hd::io_result{hh::outcome_code::ok, 1, 0}); }); + // The applier's sleep is bounded by the host timer granularity (about + // 15ms under Win32 Sleep()), so the drain is bounded by wall clock in + // addition to spins, and apply's posted resume is drained after the + // join instead of being stranded past the last run_one. + const auto drain_deadline = std::chrono::steady_clock::now() + + std::chrono::seconds(2); for (int spin = 0; spin < 100000 && once.load() == 0; ++spin) { + if (std::chrono::steady_clock::now() >= drain_deadline) break; if (!ex.run_one()) std::this_thread::yield(); } applier.join(); + for (int drain = 0; drain < 1000 && once.load() == 0 && ex.run_one(); ++drain) {} if (once.load() != 1) { LT_FAIL("cross-thread suspend/apply: not delivered exactly once"); diff --git a/test/unit/io_poll_sys_listener_test.cpp b/test/unit/io_poll_sys_listener_test.cpp index 251b38910..f327a26d3 100644 --- a/test/unit/io_poll_sys_listener_test.cpp +++ b/test/unit/io_poll_sys_listener_test.cpp @@ -23,8 +23,10 @@ // (pollsys::open_listener). Pins: the three accepted address spellings // (IPv4 literal, any-address "" and "*", IPv6 literal), the resolved // port report (0 -> ephemeral, nonzero -> the requested port), the -// SO_REUSEADDR option, nonblocking accept behavior (the poll backend's -// adopt contract), and the typed rejection of a non-literal address. +// platform's port-ownership socket option (SO_REUSEADDR on POSIX, +// SO_EXCLUSIVEADDRUSE on Winsock), nonblocking accept behavior (the +// poll backend's adopt contract), and the typed rejection of a +// non-literal address. // TASK-119 adds the fill_peer battery (the accept-time peer capture) // over synthesized transport address storages, cross-checked against // net::parse_address so the byte path and the text path of one host @@ -45,16 +47,19 @@ namespace { namespace pollsys = httpserver::detail::pollsys; namespace net = httpserver::net; -// True iff SO_REUSEADDR is enabled on @p handle (both platforms spell -// the option identically; only the option-value pointer type differs). -bool reuseaddr_enabled(pollsys::native_socket_t handle) { +// True iff the platform's port-ownership option is enabled on @p +// handle: SO_REUSEADDR on POSIX, SO_EXCLUSIVEADDRUSE on Winsock (both +// spell the option-value pointer type differently; see open_listener). +bool port_ownership_enabled(pollsys::native_socket_t handle) { int value = 0; #if defined(_WIN32) int length = sizeof(value); + const int option = SO_EXCLUSIVEADDRUSE; #else socklen_t length = sizeof(value); + const int option = SO_REUSEADDR; #endif - return ::getsockopt(handle, SOL_SOCKET, SO_REUSEADDR, + return ::getsockopt(handle, SOL_SOCKET, option, reinterpret_cast(&value), &length) == 0 && value != 0; } @@ -118,13 +123,23 @@ LT_BEGIN_AUTO_TEST(io_poll_sys_listener_suite, requested_port_reported) pollsys::close_socket(listener); LT_END_AUTO_TEST(requested_port_reported) -// SO_REUSEADDR is set so a restarted server can rebind immediately. +// The port-ownership option is set so a restarted server can rebind +// immediately -- and on Winsock, so a second bind onto the live +// listener is refused instead of hijacking the port. LT_BEGIN_AUTO_TEST(io_poll_sys_listener_suite, reuseaddr_set) std::uint16_t port = 0; pollsys::native_socket_t listener = pollsys::open_listener("127.0.0.1", 0, port); LT_CHECK(listener != pollsys::k_invalid_socket); - LT_CHECK(reuseaddr_enabled(listener)); + LT_CHECK(port_ownership_enabled(listener)); + // A second bind of the same specific address while the first + // listener is live must fail on every platform: the listener owns + // its port (the installed-consumer rollback scenarios and the + // partial-bind rollback contract depend on the refusal). + std::uint16_t collision = 0; + pollsys::native_socket_t squatter = + pollsys::open_listener("127.0.0.1", port, collision); + LT_CHECK(squatter == pollsys::k_invalid_socket); pollsys::close_socket(listener); LT_END_AUTO_TEST(reuseaddr_set) diff --git a/test/unit/quic_interop_files_test.cpp b/test/unit/quic_interop_files_test.cpp index c042601b1..fb1ffe5a4 100644 --- a/test/unit/quic_interop_files_test.cpp +++ b/test/unit/quic_interop_files_test.cpp @@ -55,7 +55,14 @@ LT_END_AUTO_TEST(fragmented_request_opens_a_bounded_file) LT_BEGIN_AUTO_TEST(interop_files_suite, rejects_traversal_symlink_malformed_and_long_requests) for (const auto& input : std::vector{"GET /../file\r\n", "GET /escape\r\n", "POST /file\r\n", "GET /file\r\nextra", std::string(4097, 'a')}) { fixture f; - std::filesystem::create_symlink("/etc/passwd", f.root / "escape"); + // Unprivileged Windows cannot create symbolic links (no + // SeCreateSymbolicLinkPrivilege/Developer Mode); the fixture creation + // is environmental, while the refusal logic itself is Windows-covered + // by the support code's REPARSE_POINT branch. + std::error_code symlink_ec; + std::filesystem::create_symlink("/etc/passwd", f.root / "escape", symlink_ec); + LT_SKIP_IF(static_cast(symlink_ec), + "symlink fixtures need symlink privileges; refusal evidence is POSIX-owned"); auto s = f.stream(0); bool rejected = false; try { diff --git a/test/unit/quic_interop_tls_test.cpp b/test/unit/quic_interop_tls_test.cpp index b874e8545..9e23ed799 100644 --- a/test/unit/quic_interop_tls_test.cpp +++ b/test/unit/quic_interop_tls_test.cpp @@ -97,7 +97,13 @@ LT_BEGIN_AUTO_TEST(interop_tls_suite, secret_export_rejects_symlinks_and_fails_c std::filesystem::create_directory(root); const auto destination = root / "destination", path = root / "keys"; std::ofstream(destination).write("original", 8); - std::filesystem::create_symlink(destination, path); + // Unprivileged Windows cannot create symbolic links (no + // SeCreateSymbolicLinkPrivilege/Developer Mode); the fixture creation is + // environmental, and the keylog-symlink refusal evidence is POSIX-owned. + std::error_code symlink_ec; + std::filesystem::create_symlink(destination, path, symlink_ec); + LT_SKIP_IF(static_cast(symlink_ec), + "symlink fixtures need symlink privileges; refusal evidence is POSIX-owned"); setenv("LIBHTTPSERVER_INTEROP_TEST_MODE", "1", 1); setenv("SSLKEYLOGFILE", path.c_str(), 1); hd::tls_credentials_registry registry; diff --git a/test/unit/response_definition_test.cpp b/test/unit/response_definition_test.cpp index 6752021a7..04291150e 100644 --- a/test/unit/response_definition_test.cpp +++ b/test/unit/response_definition_test.cpp @@ -810,10 +810,20 @@ LT_BEGIN_AUTO_TEST(response_definition_suite, file_send_short_of_declared_length LT_END_AUTO_TEST(file_send_short_of_declared_length_fails) // (S3.4b) The same diagnosis covers a file that shrinks MID-send: -// after the send's own prepare, the read bound stays pinned, so the -// next pull meets a clean EOF with bytes still owed. +// after the send's own prepare, the read bound stays pinned, so a +// later pull meets a clean EOF with bytes still owed. The payload must +// dwarf any stdio FILE* readahead: the reopen_file cursor reads +// through std::ifstream whose underlying FILE* buffers up to the +// filesystem's st_blksize ahead of the pulled position (4 KiB on +// Linux/macOS ext4/APFS, 32 KiB on FreeBSD UFS, up to 128 KiB on ZFS), +// and bytes already staged in that user-space buffer legally survive +// the on-disk truncation (FreeBSD 2026-12-02: both parked chunks drove +// ~36.8 KiB of fread refills, the 32 KiB buffer covered the rest of a +// 40 KiB payload, and the send completed as success — correct for what +// pull_file observed). 2 MiB leaves ~2 MiB owed after the parked +// chunk, past any plausible st_blksize, so the shrink must surface. LT_BEGIN_AUTO_TEST(response_definition_suite, file_send_truncated_mid_send_fails) - const std::string payload = repeating(40 * 1024); + const std::string payload = repeating(2 * 1024 * 1024); fake::temp_file asset(payload); response_definition def; @@ -822,8 +832,9 @@ LT_BEGIN_AUTO_TEST(response_definition_suite, file_send_truncated_mid_send_fails def).ok()); capturing_sink sink; - // Capacity fits the first 16 KiB chunk exactly: the second chunk - // parks, and the truncation lands between the send's pulls. + // Capacity fits the first 16 KiB chunk exactly: the send parks + // after one pull, and the truncation lands between the send's + // pulls. fake::scripted_body_sink out(k_file_chunk_capacity); exchange x(make_head(), &sink, 0, nullptr, &out); manual_executor ex; @@ -843,6 +854,17 @@ LT_BEGIN_AUTO_TEST(response_definition_suite, file_send_truncated_mid_send_fails LT_CHECK_EQ(out.drain(1u << 20), static_cast(k_file_chunk_capacity)); ex.run_pending(); + // Each round drains one parked 16 KiB chunk and pulls the next: a + // platform whose stdio readahead staged pre-truncation bytes serves + // those pulls from the buffer, and the drive continues until a pull + // finally reaches the kernel past the shrunk file (128 pulls for + // this payload, plus slack). A permanent stall still fails the + // checks below with the same evidence (FreeBSD + // 2026-10-30/2026-11-30/2026-12-02). + for (int rounds = 1; rounds < 256 && done == 0; ++rounds) { + out.drain(1u << 20); + ex.run_pending(); + } LT_CHECK_EQ(done, 1); LT_CHECK(seen.status.code() == http::outcome_code::protocol_error); LT_CHECK_EQ(sink.respond_calls, 1); diff --git a/test/unit/response_source_rig.hpp b/test/unit/response_source_rig.hpp index f040437b7..f91a7ecdb 100644 --- a/test/unit/response_source_rig.hpp +++ b/test/unit/response_source_rig.hpp @@ -31,12 +31,16 @@ // after the payload). #include +#include // ::open(O_WRONLY|O_TRUNC); the _O_* CRT names on Windows. +#if defined(_WIN32) +#include // _pipe/_open/_write/_close/_fdopen (no POSIX ::pipe in MSYS2). +#endif #include #include +#include #include #include // NOLINT(build/c++17): native v3 requires C++20. -#include #include #include #include @@ -48,6 +52,35 @@ namespace httpserver_test { +// reason: MSYS2/mingw does not expose POSIX ::pipe(); the Windows CRT +// equivalents from / keep the same fd-pair shape in +// binary mode (the restoration plan recorded in +// test/PORTABILITY.md), so the parity /pipe route keeps its coverage +// on every platform. The same shims serve the checked rewrite of the +// scratch asset. +#if defined(_WIN32) +inline int rig_pipe(int* fds, std::size_t payload) noexcept { + // The buffer must cover the whole payload: the constructor writes it + // all before any reader exists, and a _pipe(3) write beyond the + // buffer would block forever. + const unsigned int bytes = payload < 4096u + ? 4096u : static_cast(payload) + 1u; + return ::_pipe(fds, bytes, _O_BINARY); +} +inline ssize_t rig_write(int fd, const char* buffer, std::size_t size) noexcept { + return ::_write(fd, buffer, static_cast(size)); +} +inline int rig_close(int fd) noexcept { return ::_close(fd); } +inline std::FILE* rig_fdopen(int fd) noexcept { return ::_fdopen(fd, "rb"); } +#else +inline int rig_pipe(int* fds, std::size_t) noexcept { return ::pipe(fds); } +inline ssize_t rig_write(int fd, const char* buffer, std::size_t size) noexcept { + return ::write(fd, buffer, size); +} +inline int rig_close(int fd) noexcept { return ::close(fd); } +inline std::FILE* rig_fdopen(int fd) noexcept { return ::fdopen(fd, "rb"); } +#endif + // RAII scratch file: created from `content`, rewritable, removed on // destruction. class temp_file { @@ -72,10 +105,46 @@ class temp_file { const std::string& path() const noexcept { return path_; } + // Checked direct syscalls, verified by the visible size: an ofstream + // whose open fails stays silently bad, leaving the asset untouched -- + // the truncated mid-send suites would then legally succeed on the + // original content and the scenario would be lost (FreeBSD + // 2026-10-30/2026-11-30/2026-12-01, full-stream timings). A platform + // that cannot truncate fails here, with evidence, instead. void rewrite(const std::string& content) { - std::ofstream out(path_, std::ios::binary | std::ios::trunc); - out.write(content.data(), - static_cast(content.size())); +#if defined(_WIN32) + const int fd = ::_open(path_.c_str(), + _O_WRONLY | _O_TRUNC | _O_BINARY | _O_NOINHERIT); +#else + const int fd = ::open(path_.c_str(), O_WRONLY | O_TRUNC); +#endif + if (fd < 0) { + throw std::system_error(errno, std::generic_category(), + "task113: rewrite open " + path_); + } + std::size_t written = 0; + while (written < content.size()) { + const auto n = rig_write(fd, content.data() + written, + content.size() - written); + if (n <= 0) { + const int saved = errno; + rig_close(fd); + throw std::system_error(saved, std::generic_category(), + "task113: rewrite write " + path_); + } + written += static_cast(n); + } + if (rig_close(fd) != 0) { + throw std::system_error(errno, std::generic_category(), + "task113: rewrite close " + path_); + } + const std::uint64_t visible = + static_cast(std::filesystem::file_size(path_)); + if (visible != content.size()) { + throw std::runtime_error("task113: rewrite left " + path_ + " at " + + std::to_string(visible) + " bytes instead of " + + std::to_string(content.size())); + } } private: @@ -135,33 +204,34 @@ inline httpserver::owned_close_fn counting_close( // the payload). One-shot by construction: no seek position, no second // read of the same bytes. // -// reason: MSYS2/mingw does not expose POSIX ::pipe() — Windows pipes -// use _pipe()/CreatePipe() with different fd semantics. The -// Linux/macOS CI matrix exercises this path; the Windows gap is -// tracked in test/PORTABILITY.md. -#ifndef _WIN32 +// The constructor writes the entire payload through a blocking fd +// before any reader exists, so on POSIX the payload must fit the +// kernel pipe capacity: keep it at or under 4 KiB (FreeBSD's default +// capacity is 8 KiB; an 8192-byte payload blocked there forever twice). +// The Windows branch sizes its own buffer to the payload and lifts +// that bound. class filled_pipe { public: explicit filled_pipe(const std::string& payload) { - if (::pipe(fds_) != 0) { + if (rig_pipe(fds_, payload.size()) != 0) { throw std::runtime_error("task113: pipe failed"); } std::size_t written = 0; while (written < payload.size()) { - const ssize_t n = ::write(fds_[1], payload.data() + written, - payload.size() - written); + const auto n = rig_write(fds_[1], payload.data() + written, + payload.size() - written); if (n <= 0) { - ::close(fds_[0]); - ::close(fds_[1]); + rig_close(fds_[0]); + rig_close(fds_[1]); throw std::runtime_error("task113: pipe write failed"); } written += static_cast(n); } - ::close(fds_[1]); + rig_close(fds_[1]); fds_[1] = -1; - read_ = ::fdopen(fds_[0], "r"); + read_ = rig_fdopen(fds_[0]); if (read_ == nullptr) { - ::close(fds_[0]); + rig_close(fds_[0]); throw std::runtime_error("task113: fdopen failed"); } fds_[0] = -1; @@ -187,7 +257,6 @@ class filled_pipe { int fds_[2] = {-1, -1}; std::FILE* read_ = nullptr; }; -#endif // !_WIN32 } // namespace httpserver_test diff --git a/test/unit/response_sources_test.cpp b/test/unit/response_sources_test.cpp index 46c44cd50..ff9174f80 100644 --- a/test/unit/response_sources_test.cpp +++ b/test/unit/response_sources_test.cpp @@ -939,7 +939,13 @@ LT_END_AUTO_TEST(owned_pipe_second_send_rejected_before_writing) // the endpoint closes exactly once across all of them. LT_BEGIN_AUTO_TEST(response_sources_suite, threaded_pipe_sends_single_winner) constexpr int k_threads = 4; - const std::string payload = repeating(8192); + // The rig writes the whole payload into the pipe before any reader + // exists, so the payload must fit every supported kernel pipe + // capacity: FreeBSD's default is 8 KiB, and an 8192-byte write hung + // there twice (the 2026-10-30 and 2026-11-30 acceptance runs). The + // race semantics need only a body that all four threads observe + // identically, so 4096 bytes keep a 2x margin. + const std::string payload = repeating(4096); auto closes = std::make_shared>(0); response_definition def; LT_CHECK(response_definition::owned_pipe( diff --git a/test/unit/tls_psk_fixture.hpp b/test/unit/tls_psk_fixture.hpp index c8ca74d67..3c4784763 100644 --- a/test/unit/tls_psk_fixture.hpp +++ b/test/unit/tls_psk_fixture.hpp @@ -135,17 +135,20 @@ struct connection : mtls_test::adapter_connection { if (host) SSL_set_tlsext_host_name(peer.get(), host); handshake = hd::tls_handshake_operation(owner, 1, std::chrono::steady_clock::now() + timeout); } - void tick() { - ex.run_pending(); - for (const auto& op : raw.pending_ops()) transfer(op); + bool tick() { + bool progressed = ex.run_pending() != 0; + for (const auto& op : raw.pending_ops()) progressed = transfer(op) || progressed; advance_peer(); + return progressed || ex.pending() != 0; } template bool until(Predicate predicate, std::chrono::milliseconds timeout = std::chrono::seconds(3)) { const auto deadline = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < deadline) { - tick(); + const bool progressed = tick(); if (predicate()) return true; - std::this_thread::sleep_for(std::chrono::milliseconds(1)); + // Fragmentation is deliberate; adding a scheduling delay to every + // ready fragment can consume the real handshake deadline. + if (!progressed) std::this_thread::yield(); } return false; } diff --git a/test/unit/tls_psk_test.cpp b/test/unit/tls_psk_test.cpp index 72a642fb5..e59e24d34 100644 --- a/test/unit/tls_psk_test.cpp +++ b/test/unit/tls_psk_test.cpp @@ -119,23 +119,23 @@ LT_BEGIN_AUTO_TEST(psk_suite, blocking_lookup_leaves_owner_responsive_and_cancel auto released = release.get_future().share(); auto config = psk_test::credentials(runtime, [&](auto, const auto&) { entered = true; - released.wait(); + // The owner releases lookup only after checking cancellation. + // A broken blocking implementation must still unwind the fixture. + released.wait_for(5s); returned = true; return hd::psk_lookup_result{hd::psk_lookup_status::accepted, hd::secure_bytes(psk_test::bytes("secret"))}; }); hd::tls_credentials_registry registry; LT_ASSERT(registry.replace(config).ok()); psk_test::connection peer(registry.acquire()->select_default(), version, "identity", psk_test::bytes("secret")); - // Bounded rescue ensures RED cannot leave a fixture hanging in lookup. - auto rescue = std::async(std::launch::async, [&] { std::this_thread::sleep_for(250ms); release.set_value(); }); peer.handshake.submit(*peer.tls); std::chrono::steady_clock::duration longest{}; const auto until = std::chrono::steady_clock::now() + 1s; while (!entered && std::chrono::steady_clock::now() < until) { const auto before = std::chrono::steady_clock::now(); - peer.tick(); + const bool progressed = peer.tick(); longest = std::max(longest, std::chrono::steady_clock::now() - before); - std::this_thread::sleep_for(1ms); + if (!progressed) std::this_thread::yield(); } const auto cancelled = peer.tls->request_cancel(*peer.handshake.state()); peer.ex.run_pending(); @@ -147,7 +147,7 @@ LT_BEGIN_AUTO_TEST(psk_suite, blocking_lookup_leaves_owner_responsive_and_cancel LT_CHECK(peer.handshake.state()->stored_result().code == hh::outcome_code::cancelled); LT_CHECK(!peer.tls->peer_metadata()); peer.close(); - rescue.get(); + release.set_value(); runtime->stop(); LT_CHECK(runtime->drain(std::chrono::steady_clock::now() + 1s)); peer.ex.run_pending(); diff --git a/test/unit/websocket_engine_helpers.hpp b/test/unit/websocket_engine_helpers.hpp index 2ffc22b9d..719765516 100644 --- a/test/unit/websocket_engine_helpers.hpp +++ b/test/unit/websocket_engine_helpers.hpp @@ -19,7 +19,24 @@ 02110-1301 USA */ +#ifndef TEST_UNIT_WEBSOCKET_ENGINE_HELPERS_HPP_ +#define TEST_UNIT_WEBSOCKET_ENGINE_HELPERS_HPP_ +// The rig's only direct socket dependency is the SO_SNDBUF shrink below; +// every other syscall routes through the pollsys shims in io_poll_sys.hpp. +// Match that header's Winsock selection so this rig stays includable after +// windows.h consumers (native_protocol_memory_test.cpp). +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#else #include +#endif #include #include #include @@ -36,9 +53,6 @@ #include "./io_loopback.hpp" #include "./websocket_test_helpers.hpp" #include "./littletest.hpp" - -#ifndef TEST_UNIT_WEBSOCKET_ENGINE_HELPERS_HPP_ -#define TEST_UNIT_WEBSOCKET_ENGINE_HELPERS_HPP_ // Internal seam keeps scheduling and copy-work assertions out of the public API. namespace httpserver::detail { struct connection_engine_test_access { @@ -167,6 +181,17 @@ template bool until(Predicate pred, std::chrono::milliseconds b } return true; } +// Shrinks a loopback send buffer so kernel backpressure becomes observable +// without filling real socket queues. Winsock types option values as char*; +// POSIX uses void*. +inline bool shrink_send_buffer(sys::native_socket_t socket, int bytes) { +#if defined(_WIN32) + const char* option = reinterpret_cast(&bytes); +#else + const void* option = &bytes; +#endif + return ::setsockopt(socket, SOL_SOCKET, SO_SNDBUF, option, sizeof bytes) == 0; +} struct rig { h::server::resource_budget root = h::server::resource_budget::root({}); h::server::route_registry routes;