Skip to content

fix(tests): let asyncio start under the unit-suite network guard - #4115

Merged
kovtcharov-amd merged 1 commit into
mainfrom
kalin/win-unit-network-guard
Sep 24, 2026
Merged

kovtcharov-amd merged 1 commit into
mainfrom
kalin/win-unit-network-guard

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Running pytest tests/unit/ on Windows reported 556 failures and 526 errors on a commit that is green in CI, so a local test run was useless as a gate — and actively misleading to anyone, or any agent, treating it as one. The suite's own network guard caused most of it: Windows has no native socketpair(), CPython emulates it over a loopback TCP connect, and asyncio builds every event loop's self pipe that way, so the guard killed every async test at setup before its body ran. Letting socketpair() through — and only that, only for the duration of the call — takes the same checkout from 556 failures / 526 errors to 108 / 21. The remaining 108 are real, unrelated breakage that was previously buried.

The guard stays strict for every real outbound connect. Exempting loopback wholesale would also have fixed the symptom, but it would let a unit test silently reach a local Lemonade server on 127.0.0.1:8000.

No Windows CI lane yet. It is the only thing that stops this bug class hiding again, but at 108 residual failures (chiefly #4102 console encoding and #3912 Python 3.13) the suite is not green enough to gate on, and a permanently red lane teaches people to ignore it. Follow-up once those land.

Closes #4112

Test plan

  • pytest tests/unit/test_network_guard.py -v — 4 passed; reverting the conftest.py change turns 2 of them red, so the regression test is a real gate
  • pytest tests/unit/test_telegram_adapter.py -q on Windows — 17 passed (was 3 passed, 14 errors)
  • pytest tests/unit/ -q -p no:randomly on Windows — 108 failed, 12551 passed, 21 errors (was 556 failed, 11600 passed, 526 errors)
  • Linux/macOS CI unit lanes stay green — socketpair() is a native syscall there and never touched connect()

Running the unit suite on Windows reported 556 failures and 526 errors on a
commit that is green in CI, so a local run was worthless as a gate. Windows has
no native socketpair(); CPython emulates it over a loopback TCP connect, and
asyncio builds every event loop's self pipe that way — so the guard's global
patch of socket.socket.connect killed every async test at setup, before its own
body ran. Unblocking socketpair() alone, for the duration of that one call,
takes the suite to 108 failures and 21 errors.

Exempting loopback wholesale would have worked too, but it would let a test
silently reach a local Lemonade server on 127.0.0.1:8000. The guard stays
strict for every real outbound connect, loopback included.
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This makes pytest tests/unit/ usable on Windows again by letting the one loopback connect asyncio needs for its event-loop wake-up pipe through the suite's network guard, while still blocking every real outbound connect. The narrow exemption is the right call over whitelisting loopback wholesale, and the new regression test is a genuine gate.

Two things worth handling before or shortly after merge:

  • The workarounds this fix replaces are still in the tree. About ten unit tests carry a blanket "allow network" opt-out added purely to dodge this exact bug. Each one now disables the guard entirely for that test — a much bigger hole than the one this PR just closed narrowly. Sweeping them out is the other half of the fix; if it's too large for this PR, it deserves a tracked follow-up.
  • The new test can't actually catch a regression on the CI lanes that exist. Only Windows routes socketpair() through connect(), and there's no Windows lane. On Linux/macOS the socketpair test passes without touching the code path it's meant to protect. The PR already calls out the missing lane, which is the right diagnosis — just be aware the regression test is not a gate today.

One smaller point: the fix disarms and re-arms the guard by swapping a process-wide attribute, so it briefly opens the guard for the whole process and will stomp on a test that patched connect itself. A thread-local flag does the same job without either problem — details below.

Real-world evidence

N/A — tests-only change, and no evidence-bundle.md was produced for this run. The verdict rests on static review plus the numbers in the PR description (556 failures / 526 errors → 108 / 21 on Windows); I could not reproduce them here, since this reviewer runs on Linux, where socketpair() is a native syscall and never reaches the guarded connect(). pytest is not installed in the review container, so the new test file was not executed.

🔍 Technical details

Issues

🟡 The allow_network workarounds this fix obsoletes are left in place

At least ten sites opted out of _block_network entirely, with comments naming this exact bug as the reason:

  • tests/unit/chat/ui/test_recent_chat_history.py:49, :147 — # Windows asyncio creates a local socket pair.
  • tests/unit/connectors/test_cli.py:371 — # asyncio's Windows event loop uses a local socketpair
  • tests/unit/connectors/test_handler.py:175, :190
  • tests/unit/connectors/test_agent_identity_boundary.py:396
  • tests/unit/test_no_learned_skills_flag.py:69 — needs_event_loop = pytest.mark.allow_network
  • tests/unit/test_talk_voice_commands.py:13, tests/unit/test_local_http_guard.py:24, tests/unit/chat/ui/test_ui_request_guard.py:33

allow_network yields before any patching, so those tests currently run with connect and connect_ex fully live — the PR description's own objection to a blanket loopback exemption ("it would let a unit test silently reach a local Lemonade server on 127.0.0.1:8000") applies to these with more force. Removing them is mechanical now and would also validate the fix across a real slice of the suite. Reasonable to split into a follow-up issue if the diff gets noisy.

🟢 Swapping the class attribute is not thread-safe and clobbers test-local patches (tests/unit/conftest.py:91-96)

socket.socket.connect is process-global, so for the duration of real_socketpair() every thread can connect — and two threads calling socketpair() concurrently will have the first one's finally re-arm the guard while the second is still inside csock.connect(), raising a spurious ConnectionError. The finally also unconditionally writes back _blocked_connect, so a test that patched socket.socket.connect to its own mock loses that mock after any socketpair call.

A thread-local re-entrancy flag avoids all three, keeps the monkeypatch teardown authoritative, and is no harder to read. Replacing _blocked_connect and the wrapper (needs import threading at the top of the file):

    # Windows has no native socketpair(); asyncio builds its event-loop self
    # pipe over a loopback TCP connect, which the guard would otherwise block.
    real_connect = socket.socket.connect
    real_socketpair = socket.socketpair
    in_socketpair = threading.local()

    def _blocked_connect(*args, **kwargs):
        if getattr(in_socketpair, "active", False):
            return real_connect(*args, **kwargs)
        raise ConnectionError(
            "Unit tests must not make real network connections "
            "(mark the test @pytest.mark.allow_network if it uses a local socket)"
        )

    def _blocked_connect_ex(*args, **kwargs):
        return 1

    def _unguarded_socketpair(*args, **kwargs):
        in_socketpair.active = True
        try:
            return real_socketpair(*args, **kwargs)
        finally:
            in_socketpair.active = False

    monkeypatch.setattr(socket, "socketpair", _unguarded_socketpair)

(Applied as written this replaces lines 77-98, i.e. the existing _blocked_connect / _blocked_connect_ex definitions move under real_connect.) test_socketpair_is_allowed_and_leaves_the_guard_armed still covers it unchanged.

🟢 @pytest.mark.asyncio is redundant (tests/unit/test_network_guard.py:78)

pyproject.toml:56 sets asyncio_mode = "auto", so pytest-asyncio already collects bare async def tests. Harmless, but inconsistent with how the rest of the suite is drifting. Leaving it is also defensible as self-documenting — your call.

Strengths

  • The fix is scoped to exactly the syscall that needs it, for exactly the duration of the call. The alternative (exempting 127.0.0.1) was considered and rejected for a concrete reason, and the reason is recorded in the PR body rather than as an inline history comment — which is what CLAUDE.md asks for.
  • test_socketpair_is_allowed_and_leaves_the_guard_armed asserts the re-arm, not just the happy path. That's the assertion that would catch a future refactor leaking the exemption, and it's the one most people would forget to write.
  • The conftest comment is one line and names the invariant (asyncio builds its event-loop self pipe over a loopback TCP connect) rather than the bug history — exactly the WHY-comment shape the repo standard calls for.
  • The PR description quantifies the before/after and is honest about the 108 residual failures being unrelated, with issue numbers. That's the right way to hand off a partial cleanup.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 24, 2026
Merged via the queue into main with commit fc94ec7 Sep 24, 2026
49 of 52 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/win-unit-network-guard branch September 24, 2026 16:48
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 24, 2026
…#4136)

## Why this matters

A Windows contributor running the four shell test suites sees `112
skipped`, which is visually indistinguishable from green. CI on ubuntu
and macOS sees 112 real results. So the loop is: verify locally, see no
red, push, watch CI fail — which is exactly how the confirm-gate defect
in amd#3808 reached CI undetected.

The skip reason is genuine for the tests that actually launch a process:
Windows runs each pipeline through `cmd.exe`, and `os.killpg` / process
groups are POSIX-only. It is *not* genuine for the refusal, parsing,
grant and tool-description tests — those decide before anything reaches
a shell, and a module-level skip was hiding them on the platform most
GAIA contributors develop on. After this change Windows runs **70 passed
/ 42 skipped** instead of `112 skipped`, and every one of those 70 is a
real assertion about the security-adjacent refusal path.

POSIX is untouched: the per-test mark carries the same `sys.platform ==
"win32"` condition the module-level one did, so off Windows it is a
no-op and all 112 still run.

<details>
<summary>🔍 Technical details</summary>

**Membership was measured, not guessed.** A throwaway pytest plugin
stripped the `cmd.exe` skipifs, wrapped `shell_tools.subprocess.Popen` /
`.run`, and recorded which node IDs actually spawned a child. 42 did; 70
did not. The 70 were then run on Windows 11 and all passed; every one of
the 10 failures fell inside the 42. So the split is empirical, not a
reading of the test names.

That measurement mattered, because *running the tests* would have given
the wrong answer. This dev box has MSYS coreutils on `PATH`, so `ls`,
`cat`, `sort` and `date` resolve and most execution tests pass here —
they would not on a clean Windows machine or a `windows-latest` runner.
Classifying on "does it pass on my box" is the hidden-state trap
CLAUDE.md warns about; classifying on "does it spawn a process" is not.

- `pytestmark = pytest.mark.skipif(...)` → `posix_only =
pytest.mark.skipif(...)`, same reason string per module, applied as
`@posix_only` to the 35 spawning tests across three files.
- **No assertion was weakened, relaxed, or deleted.** The diff is 53
insertions / 3 deletions; the 3 deletions are the `pytestmark` name on
each of the three lines.
- Node IDs are unchanged (no reorganisation into classes), so other
in-flight PRs that name these tests in their test plans still resolve.
- `test_shell_env_assignment.py`'s two existing `shutil.which("pytest")`
skipifs stack above `@posix_only`; pytest ORs them, so behaviour off
Windows is identical.
- `tests/unit/test_shell_pipelines.py` keeps its module-level mark — all
seven of its tests genuinely run a pipeline, so there is nothing to
promote. `test_shell_output_encoding.py` already used per-test marks and
is untouched.
- One pleasing side effect:
`test_windows_never_hands_a_compound_line_to_cmd_exe_as_one_string` — a
fully-mocked test *about* the Windows path — was itself skipped on
Windows. It now runs there.

**Merge-conflict note for reviewers:** amd#3721 and amd#3402 both touch
`test_shell_compound_commands.py`, neither near the `pytestmark` line.
Whichever lands second may need a trivial rebase.
</details>

## Scope

This does **not** close amd#4127. That issue asks for `windows-latest` in
the `test_unit.yml` matrix, gated on amd#4115 and amd#4119 landing first so
the lane starts green. This is a prerequisite for that lane being worth
anything — without it, 112 of the tests the new lane would run are
skipped by construction.

## Test plan

- [x] `python -m pytest tests/unit/test_shell_compound_commands.py
tests/unit/test_shell_env_assignment.py -q` on Windows 11 — was `77
skipped`, now `51 passed, 26 skipped`
- [x] Same for all four modules — was `112 skipped`, now `70 passed, 42
skipped`
- [x] `python -m pytest tests/unit/test_shell*.py
tests/unit/test_powershell_command_injection.py -q` — `266 passed, 42
skipped`
- [x] `python util/lint.py --all` — output byte-identical to a clean
`origin/main` worktree (both exit 1 on the same pre-existing mypy
findings in `src/gaia/`, none in files this PR touches)
- [ ] CI on ubuntu/macOS — expect the same counts as before this PR; the
mark is a no-op off Windows

Towards amd#4127.

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unit tests can't run on Windows: the network guard blocks asyncio's event loop

2 participants