Skip to content

test(sensor): cover the Python probe in-process and gate CI on coverage - #148

Merged
vsn411 merged 2 commits into
secfoo-com:mainfrom
karthickmk2001:fix/115-probe-coverage
Nov 19, 2026
Merged

vsn411 merged 2 commits into
secfoo-com:mainfrom
karthickmk2001:fix/115-probe-coverage

Conversation

@karthickmk2001

Copy link
Copy Markdown
Collaborator

Problem

Closes #115.

sensor/probe.py runs inside users' applications, but almost every probe test ran it in a subprocess, which coverage cannot see. The module sat at 43% (and sensor/__init__.py at 52%), and nothing in CI would notice a regression.

What changed

Tests. tests/test_sensor/test_probe_in_process.py (55 tests) drives Probe in-process and asserts behaviour, not just executed lines:

  • watched calls: counts, entry frame, stack sample, one symbol shared by two findings, modules imported after start (via the import watcher), no argument values in any snapshot
  • the sys.monitoring and setprofile callbacks called directly (coverage cannot trace code running inside them)
  • frame and filename filters, watchlist reload throttling, symbol resolution (methods, static/class methods, functools.wraps)
  • flushing, drops, backpressure (welcome interval, slow doubling), the flusher thread
  • through the Probe ↔ sensor protocol and conformance kit (one contract for every runtime) #73 conformance kit's FakeSensor: every line the probe sends validates as a protocol message and forbidden_data is empty; a dead sensor drops batches without disabling the probe; the probe reconnects and says hello again when the sensor comes back
  • shutdown ordering, fork, no free monitoring tool id, the coverage denominator, loaded packages
  • python -m secfoo.sensor (script, -m module, no arguments) and SECFOO_* configuration, including bad values
Module Before After
sensor/probe.py 43% 96%
sensor/__init__.py 52% 100%
sensor/__main__.py 0% 100%
total 90% 92%

Bugs the new tests found, fixed here. Each has a regression test that fails on main and passes with the fix.

  1. A disabled probe leaked its hooks. stop() returned early once _disable() had cleared _active, so the sys.monitoring tool id (only four exist), the import watcher in sys.meta_path and the transport were never released. stop() now always releases them, and stopping twice is still a no-op.
  2. The final flush could race the flusher thread. stop()'s flush and the daemon flusher shared one socket; SocketTransport._read_control switches it to non-blocking, so the other thread's sendall failed, the socket was closed as "sensor gone" and the final session line was dropped. Flushes are now serialised with a dedicated lock (re-created after fork).
  3. Closing the socket sent RST. Closing with an unread welcome in the receive buffer sends RST instead of FIN, and the sensor discards lines it had received but not yet read. SocketTransport.close() now sends FIN and drains for at most 0.2s (CLOSE_DRAIN_SECONDS) before closing.

Bugs 2 and 3 are the cause of the intermittent no session line failures of test_reference_python_probe_passes_the_kit. Under CPU load, that test failed 3 of 12 runs before and passed 15 of 15 after.

CI. pytest-cov is added to the dev extra. Tests run with --cov=secfoo --cov-fail-under=90 (floor just under today's 92%), the per-file table (lowest first) goes to the job summary, and coverage.xml is uploaded as coverage-py<version>. The changes are confined to the test step, so they shouldn't collide with #141 or #143 beyond trivial context.

Housekeeping. .coverage was committed by accident in cb7bf54; it is untracked and ignored, along with coverage.xml.

Follow-ups (modules under 75%, per #115)

  • src/secfoo/web/port_guard.py: 66%. Measured on Windows, where its SIGTERM tests can't pass, so it is likely higher on CI.
  • src/secfoo/report/code_region.py: 72%.

(runtime/conformance/sample_app.py and vulnerable.py show 0% only because they run as subprocess fixtures.)

Testing

  • pytest tests/test_sensor tests/test_runtime: 216 passed
  • secfoo sensor conformance -- python -m secfoo.sensor -m secfoo.runtime.conformance.sample_app: 6/6 checks passed
  • ruff check clean on the changed files; bandit finds no high-severity issues (same as main)
  • Full suite locally (Windows, Python 3.14): 1404 passed, 10 failed. All 10 also fail on unmodified main and are Windows-only (POSIX permissions, SIGTERM, path length in git clone), unrelated to this change.

🤖 Generated with Claude Code

The probe runs inside users' applications, but almost every probe test ran
it in a subprocess, which coverage cannot see: probe.py sat at 43% and
sensor/__init__.py at 52% with nothing in CI to notice a regression.

Tests (tests/test_sensor/test_probe_in_process.py, 55 tests):
- watched calls: counts, entry frame, stack sample, shared symbols,
  late imports through the import watcher, no argument values
- the sys.monitoring and setprofile callbacks driven directly (coverage
  cannot trace code inside them)
- frame/filename filters, watchlist reload throttling, symbol resolution
- flushing, drops, backpressure (welcome / slow), the flusher thread
- every line sent to the secfoo-com#73 conformance FakeSensor validates as a
  protocol message; dead-sensor drops and reconnect
- shutdown ordering, fork, no free tool id, the coverage denominator
- python -m secfoo.sensor and SECFOO_* configuration, including bad values

Coverage: probe.py 43% -> 96%, sensor/__init__.py 52% -> 100%,
sensor/__main__.py 0% -> 100%; total 92%.

Fixes found by the new tests:
- probe: stop() returned early once _disable() had run, leaking the
  sys.monitoring tool id (only four exist), the import watcher and the
  transport. It now always releases them.
- probe: stop()'s final flush could race the flusher thread on one socket;
  the transport's non-blocking control read made the other sendall fail
  and the final session line was dropped. Flushes are now serialised.
- transport: closing a socket with an unread welcome sends RST, and the
  sensor discarded lines it had not read yet. SocketTransport.close() now
  sends FIN and drains for at most 0.2s first.
  These two caused the intermittent "no session line" failures of
  test_reference_python_probe_passes_the_kit (3/12 under load before,
  15/15 after).

CI: pytest-cov in the dev extra; tests run with --cov-fail-under=90,
the per-file table goes to the job summary and coverage.xml is uploaded.
.coverage was committed by accident in cb7bf54; untrack and ignore it.

Refs secfoo-com#115

Co-Authored-By: Claude Opus 5.5 <[email protected]>
conn.settimeout(CLOSE_DRAIN_SECONDS)
while conn.recv(65536):
pass
except OSError:
…nnect

Review follow-ups for secfoo-com#148 (secfoo-com#115), pushed by the maintainers:

- SocketTransport.close(): the drain now has one overall deadline
  (CLOSE_DRAIN_SECONDS). The per-recv timeout let a sensor that keeps
  writing hold close(), and so the app's exit, open indefinitely.
- Probe.stop() holds the flush lock across the final flush and the close,
  with a bounded wait (STOP_WAIT_SECONDS); flush() is a no-op once stop()
  has begun. A flusher that woke just before stop() could otherwise send
  after the close and leave a second, never-closed socket.
- Profile backend: _disable() and stop() remove the profiler from new
  threads (and all threads on 3.12+), and the profiler records nothing
  once the probe stops or disables itself.
- Flush intervals: NaN/inf from SECFOO_FLUSH_INTERVAL or a sensor welcome
  are rejected (the flusher spun or died); values are clamped to
  0.05-3600 s.
- App-code filter compares real paths, so a symlinked interpreter
  (Homebrew, pyenv) no longer counts the stdlib as app code.
- CI: coverage is gated in its own last step, so a coverage-only drop no
  longer hides the conformance and skills checks.
- Tests: reconnect after a live sensor dies, bounded close drain, no send
  after stop, stack-sample filter on a shallow stack, profiler release on
  disable, symlinked app root, unusable welcome intervals, nan/inf config.
  Each was checked by reintroducing the bug.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
while not stop.is_set() and time.monotonic() < give_up:
conn.sendall(b'{"type":"slow"}\n')
time.sleep(0.05)
except OSError:
@vsn411

vsn411 commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Thank you, @karthickmk2001. This is excellent work: probe coverage went from 43% to 96% on Python 3.12 (87% on 3.10), total coverage is about 92%, the tests ran 42 times without a flake, and most deliberate breakages were caught.

Review found a few gaps, and since they were small I pushed the fixes onto your branch (08ebfa7) rather than sending the PR back:

  • SocketTransport.close(): the drain now has one overall deadline. The per-read timeout let a sensor that keeps writing hold the app's exit open for as long as it kept writing.
  • Probe.stop(): holds the flush lock across the final flush and the close, with a bounded wait, and flush() is a no-op once stop has begun. A flusher that woke just before stop could send after the close and leave a second socket open (4 of 30 runs).
  • Profile backend: disabling or stopping now removes the profiler from new threads (and all threads on 3.12+), and the profiler records nothing afterwards.
  • Flush intervals: NaN or infinity from SECFOO_FLUSH_INTERVAL or a sensor welcome is rejected; NaN made the flusher spin and infinity killed it. Values are clamped to 0.05–3600 s.
  • App-code filter: compares real paths, so a symlinked interpreter (Homebrew, pyenv) no longer counts the stdlib as app code. Your stdlib test now passes on macOS Homebrew Python.
  • CI: coverage is gated in its own last step, so a coverage-only drop no longer hides the conformance and skills checks.
  • New tests: reconnect after a live sensor dies (the Test coverage: the runtime probe is at 43% while the project is at 90%; add probe tests and a coverage floor in CI #115 criterion that had no test), bounded close drain, no send after stop, the stack-sample filter on a shallow stack, profiler release on disable, a symlinked app root, unusable welcome intervals, and nan/inf config. Each was checked by reintroducing the bug.

Two things are left for later, not blockers: the RST-on-close fix is a timing heuristic (the root fix is sensor-side), and test teardown doesn't unregister the at-fork hooks Probe.start() installs (latent, since nothing forks today).

Merging. Thanks again.

@vsn411
vsn411 merged commit 073b08e into secfoo-com:main Nov 19, 2026
6 checks passed
@github-actions

Copy link
Copy Markdown

Leaderboard update

karthickmk2001 now has 82 points (rank #1, Silver). 18 more to reach Gold.

Full leaderboard

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Test coverage: the runtime probe is at 43% while the project is at 90%; add probe tests and a coverage floor in CI

3 participants