Skip to content

persistent logger - check fd before write in append() (dfs 2624) #9066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

alphaprinz
Copy link
Contributor

@alphaprinz alphaprinz commented Jun 5, 2025

Describe the Problem

Scenario is:
There are two processes.
One is the nsfs s3 endpoint server. This process writes to the active log file.
Second is the "notificator". This process reads the active file and deletes it.

While handling an s3 op, nsfs calls PersistentLogger.append().
The fd is inited to the active file.
After fd is inited, but before write() is invoked, the notificator processes and deletes the active file.
nsfs process' _poll_active_file_change() closes the fd.
When nsfs invokes write() in a closed fd, error is thrown and nsfs panics.

Note that this is not a likely scenario, and the heavy load used for dfs2624 correlates with this.

Explain the Changes

Check fd before writing. If closed, reinit.

Issues: Fixed #xxx / Gap #xxx

  1. https://issues.redhat.com/browse/DFBUGS-2624

Testing Instructions:

Because above scenario is is unlikely, I was able to reproduce it with looping the write() for ~100k times and simultaneously running the notificator.

Another option is with debug-
-add await timer between fd init and write
-break nsfs process at the timer
-run notificator ("manage_nsfs notification").
-wait for notifcator to end
-wait for _poll_active_file_change interval (default is 10 seconds)
-step over await timer
-the async _poll_active_file_change should run and close the fd
-now fd is closed and next line for nsfs is the write.

  • Doc added/updated
  • Tests added

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of log writing to handle cases where log files are deleted or closed by other processes during operation.

Signed-off-by: Amit Prinz Setter <alphaprinz@gmail.com>
@guymguym
Copy link
Member

guymguym commented Jun 6, 2025

we have used file locks for that. producers hold a share lock, and the consumer first renames the file and then takes an exclusive lock to ensure no more producers use the active file. please sync with @tangledbytes on how this is handled fitb glacier logs.

@nimrod-becker
Copy link
Contributor

@coderabbitai review

Copy link

coderabbitai bot commented Jun 12, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented Jun 12, 2025

Walkthrough

A retry mechanism was added to the append method in persistent_logger.js, allowing up to five attempts to write data if the file handle is invalid, such as when the file is deleted or closed by another process. The file handle is re-initialized on each retry, enhancing robustness against concurrent file access issues.

Changes

File(s) Change Summary
src/util/persistent_logger.js Added retry logic to the append method, introducing a constant for attempt limits and updating file handle management.

Poem

A logger hops, it tries, retries,
Five leaps before it says goodbye.
If files vanish in the night,
It sniffs again before it writes.
With every hop, it logs anew—
Persistent bunny, through and through!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-12T07_03_55_789Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a68f6ef and 2ca3230.

📒 Files selected for processing (1)
  • src/util/persistent_logger.js (2 hunks)

Comment on lines +111 to 124
for (let attempt = 0; attempt < APPEND_ATTEMPTS_LIMIT; ++attempt) {
const fh = await this.init();
//if another process has deleted the active file,
//this process' _poll_active_file_change might have closed the fd
//in that case fd is -1
//in order to avoid inter-process locking, we just re-init
//the fd to the new active file.
if (fh.fd === -1) continue;
await fh.write(this.fs_context, buf, buf.length);
break;
}

this.local_size += buf.length;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Retry loop still loses data & can throw unhandled EBADF

  1. local_size is incremented even when no write was performed (e.g. all attempts hit a closed fd). This silently corrupts accounting and drops the log entry.
  2. Between the fd === -1 check and fh.write() another thread can still close the handle, causing an EBADF that will bubble up and abort the whole caller despite the retry logic.
  3. continue without a short delay turns the loop into busy-spin when the fd stays invalid.
  4. When all attempts fail, the method returns undefined as if everything succeeded – the caller has no way to know the line was lost.

A minimal, self-contained fix:

         const buf = Buffer.from(data + '\n', 'utf8');

-        for (let attempt = 0; attempt < APPEND_ATTEMPTS_LIMIT; ++attempt) {
-            const fh = await this.init();
-            //if another process has deleted the active file,
-            //this process' _poll_active_file_change might have closed the fd
-            //in that case fd is -1
-            //in order to avoid inter-process locking, we just re-init
-            //the fd to the new active file.
-            if (fh.fd === -1) continue;
-            await fh.write(this.fs_context, buf, buf.length);
-            break;
-        }
-
-        this.local_size += buf.length;
+        let written = false;
+        for (let attempt = 0; attempt < APPEND_ATTEMPTS_LIMIT; ++attempt) {
+            const fh = await this.init();
+
+            if (fh.fd === -1) {                 // handle already closed
+                await P.delay(1);               // avoid busy-loop
+                continue;
+            }
+
+            try {
+                await fh.write(this.fs_context, buf, buf.length);
+                written = true;
+                break;
+            } catch (err) {
+                if (err.code !== 'EBADF') throw err; // real IO error
+                // someone closed the fd after we checked – retry
+                await this.close();
+            }
+        }
+
+        if (!written) {
+            throw new Error(`append failed after ${APPEND_ATTEMPTS_LIMIT} attempts`);
+        }
+
+        this.local_size += buf.length;

This guarantees either:
• the line was durably appended and local_size reflects that, or
• an explicit error is surfaced to the caller.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for (let attempt = 0; attempt < APPEND_ATTEMPTS_LIMIT; ++attempt) {
const fh = await this.init();
//if another process has deleted the active file,
//this process' _poll_active_file_change might have closed the fd
//in that case fd is -1
//in order to avoid inter-process locking, we just re-init
//the fd to the new active file.
if (fh.fd === -1) continue;
await fh.write(this.fs_context, buf, buf.length);
break;
}
this.local_size += buf.length;
}
const buf = Buffer.from(data + '\n', 'utf8');
let written = false;
for (let attempt = 0; attempt < APPEND_ATTEMPTS_LIMIT; ++attempt) {
const fh = await this.init();
if (fh.fd === -1) { // handle already closed
await P.delay(1); // avoid busy-loop
continue;
}
try {
await fh.write(this.fs_context, buf, buf.length);
written = true;
break;
} catch (err) {
if (err.code !== 'EBADF') throw err; // real IO error
// someone closed the fd after we checked – retry
await this.close();
}
}
if (!written) {
throw new Error(`append failed after ${APPEND_ATTEMPTS_LIMIT} attempts`);
}
this.local_size += buf.length;
🤖 Prompt for AI Agents
In src/util/persistent_logger.js around lines 111 to 124, the retry loop
increments local_size even if no write occurs, can throw unhandled EBADF errors
due to race conditions, busy-spins without delay on invalid fd, and silently
fails without notifying the caller. Fix this by incrementing local_size only
after a successful write, adding a short delay before retrying on invalid fd,
catching and handling EBADF errors to retry properly, and throwing an explicit
error if all attempts fail to ensure the caller knows the write did not succeed.

@tangledbytes
Copy link
Member

tangledbytes commented Jun 12, 2025

@alphaprinz the way we handle this on the tape ops is that the writers must hold shared locks while a reader must acquire an exclusive lock.

Basically the collect_and_process would wait till all the writers have given up the shared locks (hence closed their FDs) before it would start processing the log file for reading.


for (let attempt = 0; attempt < APPEND_ATTEMPTS_LIMIT; ++attempt) {
const fh = await this.init();
//if another process has deleted the active file,
Copy link
Member

Choose a reason for hiding this comment

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

The other process should not be able to delete the file if there is >= 1 process that exists as a writer. The reason is that the delete would happen only after _process would finish processing the active log file and in order to finish this the collect_and_process must have finished which must acquire an EXCLUSIVE lock before doing so.

@tangledbytes
Copy link
Member

tangledbytes commented Jun 12, 2025

It seems that we are deleting the log file after releasing the lock. The following sequence can cause the issue:

  • Reader (R) acquires EX
  • collect_and_process of R closes the log file
  • Writer (W) which had already opened the FD but was waiting for the lock acquires SH.
  • W checks the nlink which is still >= 1.
  • R's _process deletes the file post processing after it has already lost the lock due to collect_and_process closing the file.
  • W succeeds in init but the underlying file got deleted.
  • W's file replace poller detects the deletion and closes the FD.
  • W writes and panics.

cc: @alphaprinz @guymguym

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants