Skip to content

Fix ThreadSanitizer data races between bundle processing and async background writer closing in FileBasedSink and WriteFiles - #39458

Open
stankiewicz wants to merge 1 commit into
apache:masterfrom
stankiewicz:tsan_filebasedsink
Open

Fix ThreadSanitizer data races between bundle processing and async background writer closing in FileBasedSink and WriteFiles#39458
stankiewicz wants to merge 1 commit into
apache:masterfrom
stankiewicz:tsan_filebasedsink

Conversation

@stankiewicz

@stankiewicz stankiewicz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes ThreadSanitizer data races during asynchronous file closing in WriteFiles / FileBasedSink and an OS file-descriptor race in TFRecordSchemaTransformProviderTest.

Root Cause

  • Async Writer Close (FileBasedSink / WriteFiles): FileBasedSink.Writer instances are written to on the bundle processing thread and closed asynchronously via MoreFutures.runAsync. Lacking a release-acquire memory barrier between threads, TSAN reported cross-thread data races on:
    1. FileBasedSink.Writer.close()V (FileBasedSink.java:1066 reading channel.isOpen() vs. Writer.open() at FileBasedSink.java:993 writing channel = factory.create(...)).
    2. CRC32.getValue()J (reading GZIP checksums during close() vs. crc.update(...) during write(value)).
  • Test Resource Leak (TFRecordSchemaTransformProviderTest): An unclosed FileInputStream caused a syscall race when the JDK background Cleaner thread closed the unreferenced file descriptor during test execution.

Solution

  • Release-Acquire Handoff (readyToClose): Added an AtomicBoolean readyToClose handoff to FileBasedSink.Writer. Calling releaseForBackgroundClose() (readyToClose.set(true)) before spawning the async task and calling readyToClose.get() at the start of close()/cleanup() ensures that open(), write(), and all stream mutations happen-before background closing.
  • Try-With-Resources: Wrapped FileInputStream in TFRecordSchemaTransformProviderTest.runTestWrite in a try-with-resources block for deterministic closure.

Testing

  • All TSAN runs of TFRecordSchemaTransformProviderTest (--config=tsan-chlor) pass cleanly with zero data race reports.

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@github-actions github-actions Bot added the java label Jul 23, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@github-actions

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @chamikaramj for label java.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

@stankiewicz

Copy link
Copy Markdown
Contributor Author

R: @sjvanrossum

@github-actions

Copy link
Copy Markdown
Contributor

Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment assign set of reviewers

@sjvanrossum

Copy link
Copy Markdown
Contributor

If I understand correctly, open(String) initializes all relevant fields which are thereafter never written to again, correct?
Calling open(String) concurrently looks unsafe, so ideally it should be marked as synchronized along with close() to ensure mutually exclusive initialization after construction and to ensure visibility of those writes.

Alternatively, attempt a CAS on id before writing any of the other fields for exclusive initialization after construction (note that visibility of the other fields is not yet guaranteed) followed by CAS on either resourceId or channel to establish a release barrier. That same field must be acquired (e.g., volatile get or getAcquire) before reading any other field in close().

@stankiewicz
stankiewicz force-pushed the tsan_filebasedsink branch 2 times, most recently from 05f9167 to 32eea5d Compare July 28, 2026 17:27
@stankiewicz

Copy link
Copy Markdown
Contributor Author

@sjvanrossum It's not only open() and async close(), it is also racing between write() and async close. take a look at this approach.

@stankiewicz

Copy link
Copy Markdown
Contributor Author

R: @sjvanrossum

@sjvanrossum

Copy link
Copy Markdown
Contributor

Ah, of course. We may expect any method to be called on the writer thread and close, writeFooter, finishWrite and cleanup on a closer thread.

Any sane implementation of Channel should return a value from isOpen that's consistent across threads since close is documented to guarantee the following behavior (docs):

This method may be invoked at any time. If some other thread has already invoked it, however, then another invocation will block until the first invocation is complete, after which it will return without effect.

If you mark channel as volatile and immediately assign that field to a local variable in close and cleanup, condition the rest of close and cleanup logic on isOpen, then you're set I think.

…ckground writer closing in FileBasedSink and WriteFiles
@sjvanrossum

sjvanrossum commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Something like this perhaps?
I'll run TSAN checks in a bit.

    /** The channel to write to. */
    private volatile @Nullable WritableByteChannel channel;

    /**
     * Opens a uniquely named temporary file and initializes the writer using {@link #prepareWrite}.
     *
     * <p>The unique id that is given to open should be used to ensure that the writer's output does
     * not interfere with the output of other Writers, as a bundle may be executed many times for
     * fault tolerance.
     */
    public final void open(String uId) throws Exception {
      // Shadow members as local variables to ensure local consistency and force member access
      // through this.
      final @Nullable String id;
      final @Nullable ResourceId outputFile;
      final @Nullable WritableByteChannel channel;

      try {
        this.id = id = spreadUid(uId); // normal store
        ResourceId tempDirectory = getWriteOperation().getTempDirectory();
        this.outputFile =
            outputFile =
                tempDirectory.resolve(id, StandardResolveOptions.RESOLVE_FILE); // normal store
        verifyNotNull(
            outputFile,
            "FileSystems are not allowed to return null from resolve: %s",
            tempDirectory);

        final WritableByteChannelFactory factory =
            getWriteOperation().getSink().writableByteChannelFactory;
        // The factory may force a MIME type or it may return null, indicating to use the sink's
        // MIME.
        String channelMimeType = firstNonNull(factory.getMimeType(), mimeType);
        CreateOptions createOptions =
            StandardCreateOptions.builder()
                .setMimeType(channelMimeType)
                // The file is based upon a uuid and thus we expect it to be unique and to not
                // already
                // exist. A new uuid is generated on each bundle processing and thus this also holds
                // across bundle retries. Collisions of filenames would result in data loss as we
                // would otherwise overwrite already finalized data.
                .setExpectFileToNotExist(true)
                .build();
        WritableByteChannel tempChannel = FileSystems.create(outputFile, createOptions);
        try {
          this.channel =
              channel =
                  factory.create(tempChannel); // volatile store (sequentially consistent release)
        } catch (Exception e) {
          // If we have opened the underlying channel but fail to open the compression channel,
          // we should still close the underlying channel.
          try (tempChannel) {
            throw e;
          }
        }
      } catch (Throwable t) {
        // Ensure that memory visibility matches non-exception case before throwing.
        this.channel = null; // volatile store (sequentially consistent release)
        throw t;
      }

      // The caller shouldn't have to close() this Writer if it fails to open(), so close
      // the channel if prepareWrite() or writeHeader() fails.
      try {
        LOG.debug("Preparing write to {}.", outputFile);
        prepareWrite(channel);

        LOG.debug("Writing header to {}.", outputFile);
        writeHeader();
      } catch (Exception e) {
        LOG.error("Beginning write to {} failed, closing channel.", outputFile, e);
        try (channel) {
          throw e;
        }
      }

      LOG.debug("Starting write of bundle {} to {}.", id, outputFile);
    }

    public final void cleanup() throws Exception {
      final @Nullable WritableByteChannel channel = this.channel; // volatile load (acquire)
      final @Nullable ResourceId outputFile = this.outputFile; // normal load

      try (channel) {
        if (channel != null && channel.isOpen()) {
          LOG.warn("Channel to {} is still open after cleanup() was called.", outputFile);
        }

        // channel and outputFile may be null if open() was not called or failed.
        if (outputFile != null) {
          LOG.info("Deleting temporary file {}", outputFile);
          FileSystems.delete(
              Collections.singletonList(outputFile), StandardMoveOptions.IGNORE_MISSING_FILES);
        }
      }
    }

    /** Closes the channel and returns the bundle result. */
    public final void close() throws Exception {
      final @Nullable WritableByteChannel channel = this.channel; // volatile load (acquire)
      final @Nullable ResourceId outputFile = this.outputFile; // normal load

      try (channel) {
        checkState(outputFile != null, "FileResult.close cannot be called with a null outputFile");

        LOG.debug("Closing {}", outputFile);

        writeFooter();
        finishWrite();

        LOG.debug("Closing channel to {}.", outputFile);
      }

      LOG.info("Successfully wrote temporary file {}", outputFile);
    }

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants