Skip to content

Refactor PostgreSQLExecutor to support Windows compatibility for process management#1182

Open
tboy1337 wants to merge 8 commits intodbfixtures:mainfrom
tboy1337:edit
Open

Refactor PostgreSQLExecutor to support Windows compatibility for process management#1182
tboy1337 wants to merge 8 commits intodbfixtures:mainfrom
tboy1337:edit

Conversation

@tboy1337
Copy link

@tboy1337 tboy1337 commented Aug 30, 2025

Refactors PostgreSQLExecutor to improve Windows compatibility and security for PostgreSQL process management. This change addresses platform-specific issues with process termination and command formatting that could cause failures on Windows systems.

Changes

  • Unified command format: Converted _get_base_command method to BASE_PROC_START_COMMAND class attribute with cross-platform compatible syntax (removed single quotes around PostgreSQL config values that caused issues on Windows)
  • Graceful Windows termination: Added _windows_terminate_process method that attempts graceful shutdown before force-killing stuck processes
  • Improved security: Updated stop() method to use list arguments instead of shell=True to prevent shell injection vulnerabilities
  • Platform-specific logic: Added intelligent platform detection with fallback handling for os.killpg AttributeError on Windows
  • Comprehensive test coverage: Added 186 lines of Windows compatibility tests covering various termination scenarios and command formatting

Test plan

  • ✅ New test suite in tests/test_windows_compatibility.py with 7 test cases
  • ✅ Tests verify unified command format without single quotes
  • ✅ Tests verify graceful termination and force-kill timeout handling
  • ✅ Tests verify platform-specific stop behavior (Windows vs Unix)
  • ✅ Tests verify fallback logic for killpg AttributeError
  • ✅ Tests verify command formatting with Windows paths

Summary by CodeRabbit

  • Bug Fixes

    • Improved cross‑platform PostgreSQL handling: unified startup command formatting and more reliable shutdown on Windows with graceful terminate plus force‑kill fallback, and a fallback when platform signalling is unavailable.
  • Tests

    • Added comprehensive Windows compatibility tests for command formatting, startup/shutdown flows, forced‑kill and signalling fallbacks.
  • Chores

    • CI updated to detect/use PostgreSQL on Windows and expanded Windows test matrix; test setup registration tidied.

@tboy1337 tboy1337 mentioned this pull request Aug 30, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 21, 2026

📝 Walkthrough

Walkthrough

Added a Windows-specific process-termination helper and Windows branching in stop(); changed pg_ctl command assembly to use an argument list (removed single-quote quoting); introduced a module logger; added Windows-focused tests and CI jobs; removed a wildcard plugin import from tests/conftest.py.

Changes

Cohort / File(s) Summary
Core executor
pytest_postgresql/executor.py
Added _windows_terminate_process(self, _sig: Optional[int]=None); introduced module-level logger; updated BASE_PROC_START_COMMAND formatting (no single-quote wrapping); stop() now builds pg_ctl stop as an args list, routes Windows termination through the new helper, and falls back to _windows_terminate_process on AttributeError. Review process termination sequencing and command arg assembly.
Windows compatibility tests
tests/test_windows_compatibility.py
New TestWindowsCompatibility suite validating base command formatting, _windows_terminate_process graceful and force-kill flows, stop() branching for Windows/Unix/fallback, and Windows command assembly. Uses mocks/patches for subprocess, platform detection and internal methods.
CI workflows
.github/workflows/single-postgres.yml, .github/workflows/tests.yml
CI updated to discover/set POSTGRESQL_EXEC cross-platform (Windows and macOS/Homebrew fallbacks), conditionally run locale/libpq steps, add Windows Postgres job variants (16/17/18) using single-postgres workflow, tighten libpq install on Linux/PyPy, and update artifact paths. Review job matrices and executable resolution.
Tests setup
tests/conftest.py
Removed from pytest_postgresql.plugin import * (plugin is registered via entry point). Confirm tests continue to load plugin via packaging entry points.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Executor as PostgreSQLExecutor
    participant OS as OperatingSystem
    participant Proc as PostgreSQLProcess

    Client->>Executor: call stop()
    Executor->>Executor: build `pg_ctl stop` args list
    alt Platform == "Windows"
        Executor->>OS: run `pg_ctl stop` (subprocess with args list)
        Executor->>Executor: invoke _windows_terminate_process()
        Executor->>Proc: send terminate()
        Proc-->>Executor: exit or timeout
        alt timeout
            Executor->>Proc: send kill()
            Proc-->>Executor: killed
        end
    else Non-Windows
        Executor->>Executor: call super().stop()
        alt super() raises AttributeError
            Executor->>Executor: fallback to _windows_terminate_process()
        end
    end
    Executor-->>Client: return self / stop result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐇 I tap the sleepy DB with care,
On Windows paths I tiptoe there,
A gentle stop, then firmer shove,
If stubborn still, a final shove,
Logs cosy, sockets hum — all fair.

🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Newsfragment Check ⚠️ Warning No newsfragment file for PR #1182 was found in the newsfragments directory, despite substantive changes including Windows process handling, new tests, and workflow updates. Add a newsfragment file (1182.[type].rst) to the newsfragments/ directory to document the Windows compatibility improvements and security enhancements in the changelog.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Refactor PostgreSQLExecutor to support Windows compatibility for process management' clearly and accurately summarises the main objective of the changeset, which is to refactor the PostgreSQLExecutor class to add Windows compatibility support for process termination and management.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

No actionable comments were generated in the recent review. 🎉

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@pytest_postgresql/executor.py`:
- Around line 263-283: In stop(self, sig: Optional[int] = None, exp_sig:
Optional[int] = None) replace the subprocess.check_output call that builds a
shell string with a list-style invocation (e.g., [self.executable, "stop", "-D",
self.datadir, "-m", "f"]) and remove shell=True so subprocess runs the
executable directly; this avoids breaking paths with spaces and removes the
shell injection risk while keeping the same arguments and behavior before the
platform-specific termination logic (_windows_terminate_process / super().stop).
- Around line 53-66: The _get_base_command constructs the -o string with
unix_socket_directories unquoted which breaks for paths with spaces; update
_get_base_command to detect whitespace in the unixsocketdir variable and wrap
that value in double quotes (or escape quotes) when building the -o option so
the produced fragment becomes -c unix_socket_directories="/path/with space"
(referencing the unix_socket_directories token and BASE_PROC_START_COMMAND
assignment), and add a unit test that passes a datadir/unixsocketdir containing
a space to ensure the command line includes the quoted socket directory (or
alternatively, add explicit validation/documentation and raise a clear error
when whitespace is present).
🧹 Nitpick comments (1)
pytest_postgresql/executor.py (1)

231-262: Tidy up the termination helper API surface.

sig is unused in _windows_terminate_process, and _unix_terminate_process is currently unused. Either wire _unix_terminate_process into stop() for symmetry and use sig, or drop/rename the parameter to avoid dead code and lint noise.

@tboy1337 tboy1337 force-pushed the edit branch 2 times, most recently from 5d4fb91 to efa4633 Compare January 21, 2026 07:59
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@tests/test_windows_compatibility.py`:
- Around line 35-39: The test assertions in tests/test_windows_compatibility.py
don't match the actual string produced by _get_base_command(): update the
assertions to expect the escaped-quote form for unix_socket_directories (i.e.,
include the backslash-escaped double quotes around {unixsocketdir}) and assert
that the non-quoted form is not present; specifically change the positive
assertion referencing unix_socket_directories to look for
unix_socket_directories=\"{unixsocketdir}\" and keep the negative assertion for
unix_socket_directories='{unixsocketdir}' to ensure consistency with
_get_base_command().
- Around line 189-204: The test's expected_parts entry for
unix_socket_directories doesn't match the actual command string (which includes
escaped quotes), so update the expectation in the test to match the
implementation: replace the "-c unix_socket_directories=C:/temp/socket" entry
with the escaped-quote form that appears in executor.command (e.g., -c
unix_socket_directories=\"C:/temp/socket\"), keeping the rest of the
expected_parts and the loop over executor.command unchanged; reference the test
variable executor.command and the expected_parts list when making the change.
🧹 Nitpick comments (2)
pytest_postgresql/executor.py (2)

25-25: Unused import signal.

The signal module is imported but not used anywhere in the file. This appears to be a leftover from development.

🧹 Suggested fix
-import signal

250-269: Good refactor to list-based subprocess call.

The change from shell string to list format ([self.executable, "stop", "-D", self.datadir, "-m", "f"]) properly addresses the previous security concern and handles paths with spaces correctly.

One minor observation: the AttributeError fallback (lines 263-268) uses string matching "killpg" in str(e) which is somewhat fragile. Consider whether this fallback is still needed given the explicit platform.system() check now handles Windows upfront.

@tboy1337 tboy1337 requested a review from fizyk January 21, 2026 08:33
@tboy1337 tboy1337 force-pushed the edit branch 2 times, most recently from b02c61b to 4a0b22e Compare January 21, 2026 10:24
@tboy1337 tboy1337 force-pushed the edit branch 2 times, most recently from 059e4bc to 54140ac Compare January 29, 2026 05:40
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@pytest_postgresql/executor.py`:
- Around line 226-246: The parameter sig in _windows_terminate_process is
intentionally unused and triggers Ruff ARG002; either rename it to _sig to
indicate it’s intentionally unused or keep sig and add a local lint suppression
(e.g., append a noqa comment for ARG002) where the function is defined to
silence the warning; update the function signature (or add the noqa) in the
_windows_terminate_process definition and run linters to confirm the ARG002
warning is resolved.

…ess management

- Convert _get_base_command method to BASE_PROC_START_COMMAND class attribute

- Use unified command format without single quotes around PostgreSQL config values

- Add _windows_terminate_process method for graceful Windows process termination

- Update stop() method to use list args instead of shell=True for security

- Add platform-specific termination logic with killpg fallback

- Add comprehensive Windows compatibility test suite

- Rename parameter in _windows_terminate_process method for clarity
Copy link
Member

@fizyk fizyk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tboy1337 are we able to add ci windows-based tests?

tboy1337 and others added 2 commits February 11, 2026 20:45
…environment variable usage

- Added detection of PostgreSQL path for Windows runners.
- Set PostgreSQL path for Unix/macOS environments.
- Updated test commands to utilize the dynamically set PostgreSQL executable path.
- Introduced new Windows job configurations for PostgreSQL versions 16, 17, and 18 in tests.yml.
- Removed unnecessary import in conftest.py as the plugin is registered via entry point.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
.github/workflows/single-postgres.yml (1)

82-86: ⚠️ Potential issue | 🟡 Minor

Artifact upload path is Unix-only.

/tmp/pytest-of-runner/** on line 86 won't match anything on Windows. This is gated behind if: failure() so it won't fail the build, but Windows test failure artefacts will be silently lost. Consider adding a platform-conditional path or using ${{ runner.temp }}.

🤖 Fix all issues with AI agents
In @.github/workflows/single-postgres.yml:
- Around line 59-62: The workflow hardcodes POSTGRESQL_EXEC to
/usr/lib/postgresql/... which breaks macOS runners; change the step that sets
POSTGRESQL_EXEC (the block under the if: runner.os != 'Windows') to detect
pg_ctl on Unix-like systems instead of a Debian path — use command -v pg_ctl and
if that fails try macOS Homebrew locations (e.g.,
/opt/homebrew/opt/postgresql@${{ inputs.postgresql }}/bin/pg_ctl and
/usr/local/opt/postgresql@${{ inputs.postgresql }}/bin/pg_ctl) or set a fallback
to the current Debian path; ensure the final value exported as POSTGRESQL_EXEC
is the first existing pg_ctl found so CI on macos_postgres_* with
ankane/setup-postgres works correctly.
🧹 Nitpick comments (4)
pytest_postgresql/executor.py (2)

226-246: Broadly swallowing exceptions in cleanup is acceptable but consider logging.

The except (OSError, AttributeError): pass on lines 244–246 silently discards all OSError variants (including permission errors) and AttributeError. For a teardown helper this is pragmatic, but a debug-level log would aid troubleshooting when processes fail to terminate.


261-266: String-based AttributeError matching is fragile.

Checking "killpg" in str(e) couples the fallback to the exact wording of CPython's error message, which could change across versions or implementations. Consider catching the missing attribute directly.

Proposed fix
         except AttributeError as e:
-            # Fallback for edge cases where os.killpg doesn't exist
-            if "killpg" in str(e):
+            # Fallback for edge cases where os.killpg doesn't exist (e.g. Windows)
+            if not hasattr(os, "killpg"):
                 self._windows_terminate_process(sig)
             else:
                 raise
tests/conftest.py (1)

7-9: Remove the commented-out import rather than leaving dead code.

The commented-out line still triggers a Ruff warning (RUF100) for the stale noqa directive. Since the comment on line 8 already explains the rationale, the old import line adds no value.

Proposed fix
 
 # Plugin is registered via entry point in pyproject.toml - no need to import here
-# from pytest_postgresql.plugin import *  # noqa: F403,F401
tests/test_windows_compatibility.py (1)

74-98: Patch target for subprocess.check_output should be where it's looked up.

The patch patch("subprocess.check_output") works because executor.py uses import subprocess and then subprocess.check_output(...), so patching the module attribute is fine. However, best practice is to patch where the name is used: pytest_postgresql.executor.subprocess.check_output. This avoids accidentally affecting other code if tests are ever run in parallel or the import style changes.

This applies to all test methods in this class that patch subprocess.check_output.

…compatibility

- Implement dynamic detection of pg_ctl path for Unix/macOS environments in the GitHub Actions workflow.
- Add logging for exception handling during Windows process termination in PostgreSQLExecutor.
- Update test mocks to reference the correct subprocess path for better compatibility.
- Remove unnecessary import in conftest.py to streamline the codebase.
@tboy1337
Copy link
Author

@coderabbitai resume

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 11, 2026

✅ Actions performed

Reviews resumed.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@tests/test_windows_compatibility.py`:
- Around line 127-155: The test fails on Unix because os.killpg exists so the
stop() except branch re-raises; to exercise the fallback, remove killpg from the
executor module's os before calling stop: inside the test's with-block, import
sys and call delattr(sys.modules['pytest_postgresql.executor'].os, "killpg") (or
use monkeypatch.delattr on that module's os) so that hasattr(os, "killpg") is
False when PostgreSQLExecutor.stop() runs; keep references to
PostgreSQLExecutor.stop, os.killpg, and _windows_terminate_process to locate the
code to change.
🧹 Nitpick comments (3)
pytest_postgresql/executor.py (2)

32-34: Logger initialisation breaks import grouping.

The logger = logging.getLogger(__name__) statement is sandwiched between two mirakuru imports. Move it after all top-level imports to keep the import block contiguous and PEP 8–compliant.

Suggested reordering
 from mirakuru import TCPExecutor
-
-logger = logging.getLogger(__name__)
 from mirakuru.exceptions import ProcessFinishedWithError
 from packaging.version import parse
 
 from pytest_postgresql.exceptions import ExecutableMissingException, PostgreSQLUnsupported
+
+logger = logging.getLogger(__name__)

229-254: _windows_terminate_process looks good overall; minor nit on redundant pass.

The graceful-then-force-kill approach is sound. However, the pass on line 254 is redundant — the logger.debug(...) call already satisfies the except block body.

Suggested fix
             logger.debug(
                 "Exception during Windows process termination: %s: %s",
                 type(e).__name__,
                 e,
             )
-            pass
tests/test_windows_compatibility.py (1)

74-98: Windows stop test: consider asserting the exact arguments passed to check_output.

The test asserts mock_subprocess.assert_called_once() but doesn't verify the arguments. Since stop() now uses list-form args ([self.executable, "stop", "-D", self.datadir, "-m", "f"]), asserting the call args would catch regressions in the command construction.

Optional enhancement
             # Should call pg_ctl stop and Windows terminate
-            mock_subprocess.assert_called_once()
+            mock_subprocess.assert_called_once_with(
+                ["/path/to/pg_ctl", "stop", "-D", "/tmp/data", "-m", "f"],
+            )
             mock_terminate.assert_called_once()

- Reintroduce logger initialization in executor.py for improved logging.
- Remove unnecessary pass statement in exception handling within the stop method.
- Update test assertions to ensure correct subprocess call format for Windows compatibility.
- Temporarily modify os.killpg attribute in tests to validate fallback behavior on Windows termination.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@pytest_postgresql/executor.py`:
- Around line 244-246: Replace the blocking self.process.wait() after
self.process.kill() with a timed wait and a fallback path: call
self.process.wait(timeout=...) (or poll in a short loop) and catch
subprocess.TimeoutExpired, then log a warning and avoid hanging (optionally
attempt a forceful termination or continue without blocking); update the code
around self.process.kill() / self.process.wait() in executor.py to use a timeout
and warning on failure to reap the process.
🧹 Nitpick comments (1)
tests/test_windows_compatibility.py (1)

74-100: Consider a more precise mock assertion for _windows_terminate_process.

mock_terminate.assert_called_once() on line 99 does not verify the arguments. Since stop() calls self._windows_terminate_process(sig) (where sig defaults to None), using assert_called_once_with(None) would make the test stricter and catch regressions if the call signature changes.

Proposed fix
-            mock_terminate.assert_called_once()
+            mock_terminate.assert_called_once_with(None)

… test assertions

- Add timeout handling for process cleanup in the stop method to prevent zombie processes.
- Update test to assert correct argument usage for mock_terminate in Windows compatibility tests.
@tboy1337 tboy1337 requested a review from fizyk February 11, 2026 15:38
if: runner.os != 'Windows'
run: |
# Try to find pg_ctl dynamically for cross-platform compatibility
if command -v pg_ctl >/dev/null 2>&1; then
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pytest-postgresql can do that detection as well in case of wrong path :)
Maybe that's why I haven't bothered with specifying separate path for macos

from pathlib import Path

from pytest_postgresql import factories
from pytest_postgresql.plugin import * # noqa: F403,F401
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One other thing I remembered.

We do not install the package on CI with pip install -e, hence, the tests need to import plugin itself 🙈

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.

2 participants