Skip to content

[#41] Use AllocateFile and PG_TRY/PG_CATCH in pgmoneta_ext_receive_file_chunk - #42

Open
hardikkaurani wants to merge 1 commit into
pgmoneta:mainfrom
hardikkaurani:fix-receive-file-chunk-leak
Open

hardikkaurani wants to merge 1 commit into
pgmoneta:mainfrom
hardikkaurani:fix-receive-file-chunk-leak

Conversation

@hardikkaurani

@hardikkaurani hardikkaurani commented Nov 15, 2026 •

Copy link
Copy Markdown

Fixes #41

Description

In pgmoneta_ext_receive_file_chunk(), target files were opened using bare libc fopen() and locked with flock() without PostgreSQL resource tracking or exception handling. If base64_decode() or fwrite() raised an ereport(ERROR), PostgreSQL aborted the transaction via siglongjmp(), leaving the file descriptor open and the advisory flock() lock held in the PostgreSQL backend process. Any subsequent chunk upload to that file within the same backend session failed with:

ERROR: pgmoneta_ext_receive_file_chunk: File is already locked by another thread

Changes

  1. PostgreSQL Tracked File APIs (AllocateFile / FreeFile):

    • Replaced bare libc fopen() / fclose() with PostgreSQL's AllocateFile() and FreeFile().
    • Included <storage/fd.h>.
  2. Exception & Lock Safety (PG_TRY / PG_CATCH):

    • Enclosed chunk decode and write operations inside PG_TRY() / PG_CATCH().
    • Added volatile qualification to local variables examined in PG_CATCH() across siglongjmp().
    • In PG_CATCH(), cleaned up decoded_data if non-NULL, and reset pointers to NULL to prevent double-free or double-close.
    • Checked flock(fd, LOCK_UN) on both error (ereport(WARNING) with %m so as not to interrupt PG_RE_THROW()) and success paths (ereport(ERROR) with %m after closing the file).
    • Wrote decoded bytes via VARDATA(decoded_data) so the actual payload (rather than the varlena length header) is written to disk.
  3. Regression Tests & Test Framework Improvements:

    • In test/lib/pgmoneta_ext_test.c, updated execute_command() to inspect pclose() status using WIFEXITED() and WEXITSTATUS() with <sys/wait.h>.
    • In test_pgmoneta_ext_receive_file_chunk:
      • Verified initial chunk write succeeds.
      • Verified invalid base64 input fails with non-zero exit code (ON_ERROR_STOP=1) and expected error message (Failed to decode base64 chunk) without leaking lock/handle.
      • Verified subsequent write to the same file succeeds without lock conflict.
      • Verified actual file contents match hello worldmore data.
      • Registered test in dedicated TCase with checked setup and teardown fixtures to ensure reliable file cleanup even on assertion failure.
  4. Authors:

    • Added Hardik Kaurani to AUTHORS.

Copilot AI balanced review requested due to automatic review settings November 15, 2026 19:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@hardikkaurani

Copy link
Copy Markdown
Author

Hi @jesperpedersen,

This PR is ready for review.

Summary of Changes:

  • Replaced libc fopen() / fclose() in pgmoneta_ext_receive_file_chunk() with PostgreSQL's resource-tracked AllocateFile() and FreeFile() APIs to prevent handle leaks across transaction aborts.
  • Wrapped chunk decoding and writing in PG_TRY() / PG_CATCH() blocks to ensure flock(fd, LOCK_UN) and FreeFile(file) are executed before re-throwing via PG_RE_THROW().
  • Added volatile qualification to local variables examined in PG_CATCH() across siglongjmp(), and guarded cleanup to prevent double-free or double-close.
  • Checked flock(fd, LOCK_UN) return codes: logged a WARNING with %m during exception unwinding without interrupting PG_RE_THROW(), and raised an ERROR on the success path if unlocking fails.
  • Wrote decoded bytes via VARDATA(decoded_data) directly to disk.
  • Updated execute_command() in test/lib/pgmoneta_ext_test.c to inspect WIFEXITED() and return the actual child exit status WEXITSTATUS() using <sys/wait.h>.
  • Added test_pgmoneta_ext_receive_file_chunk verifying chunk writes, error handling without lock leakage (ON_ERROR_STOP=1), immediate retries, file content equality (hello worldmore data), and registered checked setup/teardown fixture hooks for reliable test file cleanup.

@Pranav-error

Copy link
Copy Markdown
Collaborator

Step 2 of the new test can't pass: for 'invalid base64!!!', base64_decode() raises Failed to decode Base64 data itself (lib.c:668), so the caller's Failed to decode base64 chunk is never reached. I built this head against PG 14 and ran the call: ERROR: Failed to decode Base64 data. Could the regex match that?

The VARDATA() change also fixes a real bug: on main, hello world is written to disk as <\0\0\0hello w (the varlena header plus the first 7 bytes). Worth saying in the commit message.

@hardikkaurani
hardikkaurani force-pushed the fix-receive-file-chunk-leak branch from ed5a863 to f894282 Compare November 30, 2026 21:57
@hardikkaurani

Copy link
Copy Markdown
Author

@Pranav-error Thanks for catching that! Updated PGMONETA_EXT_BASE64_ERROR_REGEX in est/lib/pgmoneta_ext_test.c to match Failed to decode Base64 data from �ase64_decode(), noted the VARDATA(decoded_data) fix in the commit message, and squashed/rebased onto main.

@Pranav-error

Copy link
Copy Markdown
Collaborator

The regex fix looks right, but f894282 also undoes 4bff1ac (Support PostgreSQL 19): the CHECKPOINT_FAST fallback in lib.c and -std=gnu17 in both CMakeLists.txt files are back to the old lines. Against PG 19 headers, lib.c from main compiles and from this PR fails with "use of undeclared identifier 'CHECKPOINT_IMMEDIATE'". Can you drop those hunks so the PR only has the #41 changes?

@hardikkaurani
hardikkaurani force-pushed the fix-receive-file-chunk-leak branch from f894282 to ef38681 Compare December 1, 2026 08:28
@hardikkaurani

Copy link
Copy Markdown
Author

@Pranav-error Good catch — restored CMakeLists.txt, src/CMakeLists.txt, and the CHECKPOINT_FAST fallback in src/pgmoneta_ext/lib.c from main (4bff1ac), and squashed/rebased onto main (ef38681) so only the #41 changes remain.

…ceive_file_chunk

Use PostgreSQL AllocateFile/FreeFile and PG_TRY/PG_CATCH in pgmoneta_ext_receive_file_chunk() so file descriptors and flock() locks are released on ereport(ERROR). Also write decoded bytes via VARDATA(decoded_data) instead of the varlena header.

Signed-off-by: Hardik Kaurani <[email protected]>
@Pranav-error

Copy link
Copy Markdown
Collaborator

Re-checked at ef38681: only the #41 changes now, and lib.c builds against PG 19 again. On PG 14, write / invalid base64 / write: main fails the third call with "File is already locked by another thread" and writes <\0\0\0hello w; with this PR the third call returns 0 and the file is hello worldmore data. Didn't run the CMake test suite here.

@hardikkaurani

Copy link
Copy Markdown
Author

@Pranav-error Thanks for verifying at ef38681!

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.

pgmoneta_ext_receive_file_chunk uses libc fopen/flock instead of PostgreSQL AllocateFile, causing leaked file handles on error/abort

3 participants