This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 82c110b51e fix(bindings/java): release native writer and JNI local
refs (#8870)
82c110b51e is described below
commit 82c110b51e6ef4fc7d5a42a5d87052e0ae9e7235
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 00:14:42 2026 +0800
fix(bindings/java): release native writer and JNI local refs (#8870)
* fix(bindings/java): release native writer and JNI local refs
OperatorOutputStream.close() ran flush() then writer.close() without
ensuring the writer was released when flush() failed. A failed flush
leaked the native blocking::Writer and left the stream usable, so later
writes kept going into a broken writer. Always close the writer, and when
both flush() and close() fail, attach the secondary close error as
suppressed so the original flush error is preserved.
The JNI list conversions accumulated local references: jni 0.22 JObject
values do not delete local references on drop, so each listed entry pinned
a dozen or more references for the whole native call. Scope the per-entry
allocations with Env::with_local_frame in intern_list, make_entries,
jmap_to_hashmap and hashmap_to_jmap.
* fix(bindings/java): never commit a failed output stream
`OperatorOutputStream.close()` flushed and then always released the native
writer through `blocking::Writer::close()`. When the flush failed, closing
the
writer still committed whatever bytes had reached it, so a failed stream
published an empty or truncated object.
Track the first failure of a native write or flush on the Java side.
`close()`
still releases the native writer so the handle does not leak, but a failed
stream is discarded: `disposeWriter` now takes a `commit` flag and skips
`blocking::Writer::close()` when it is false, leaving the object
uncommitted.
Only bytes that reached the native writer before the failure are dropped
this
way, which is why the stream must not commit after any failure.
Because the original failure already reached the caller from the write or
flush that raised it, `close()` reports a fresh exception carrying the same
`OpenDALException.Code` and the original as its cause. Rethrowing the
original
instance would make try-with-resources suppress it into itself, which the
JVM
rejects with `IllegalArgumentException`.
Tests assert that neither the empty object nor a partially written object is
committed, that the stream rejects further use with `IllegalStateException`,
and that a try-with-resources block still surfaces the original
`RateLimited`.
* fix(bindings/java): reject use after a failed output stream
Gate the commit in close() on whether flushing succeeded instead of on the
recorded failure. A subclass that overrides flush(), or a JNI exception that
is neither a RuntimeException nor an Error, leaves the failure field unset
while flushing has failed, so close() committed a partially flushed object.
Report an unrecovered failure with a fresh exception in every case,
including
when close() is the first caller to observe it. A try-with-resources
statement
suppresses whatever close() throws into the exception its body is
propagating,
so rethrowing that same instance made the JVM reject the self-suppression
with
IllegalArgumentException, which replaced the real failure.
Reject write() and flush() once a failure is recorded. The stream can no
longer
reach the service, and a failed flush leaves the offset at the end of the
buffer, which made the next write overrun the array.
* fix(bindings/java): keep first output stream failure exact
Rethrow a failure that close() observes first unchanged instead of wrapping
it, so callers see the exact OpenDALException, Error, or RuntimeException
subclass. Only a stream that already reported a failure raises a fresh
exception with the original as cause, to avoid the JVM rejecting
self-suppression in try-with-resources; a discard failure attaches to that
fresh exception.
Record failures thrown by a flush() override while write() fills its buffer,
and catch Throwable from writeByteRange. Before this, such a failure left
the
buffer offset at the end of the array with no recorded failure, so the next
write overran the array or spun on a zero-length batch, and close() flushed
again and could commit buffered bytes.
---
bindings/java/src/async_operator.rs | 10 +-
bindings/java/src/convert.rs | 38 +++-
.../org/apache/opendal/OperatorOutputStream.java | 167 +++++++++++++-
bindings/java/src/operator.rs | 10 +-
bindings/java/src/operator_output_stream.rs | 16 +-
.../org/apache/opendal/test/JniLocalRefTest.java | 70 ++++++
.../test/OperatorInputOutputStreamTest.java | 246 +++++++++++++++++++++
7 files changed, 530 insertions(+), 27 deletions(-)
diff --git a/bindings/java/src/async_operator.rs
b/bindings/java/src/async_operator.rs
index 68b9c568b6..59268faa5d 100644
--- a/bindings/java/src/async_operator.rs
+++ b/bindings/java/src/async_operator.rs
@@ -518,8 +518,14 @@ fn make_entries<'local>(env: &mut Env<'local>, entries:
Vec<Entry>) -> Result<JO
)?;
for (idx, entry) in entries.into_iter().enumerate() {
- let entry = make_entry(env, entry)?;
- jarray.set_element(env, idx, &entry)?;
+ // `make_entry` creates a dozen or more local references. Release them
at
+ // the end of each iteration so a large listing cannot exhaust the JNI
+ // local reference table.
+ env.with_local_frame(16, |env| -> Result<()> {
+ let entry = make_entry(env, entry)?;
+ jarray.set_element(env, idx, &entry)?;
+ Ok(())
+ })?;
}
Ok(jarray.into())
diff --git a/bindings/java/src/convert.rs b/bindings/java/src/convert.rs
index 0649b3f610..a0f04c990f 100644
--- a/bindings/java/src/convert.rs
+++ b/bindings/java/src/convert.rs
@@ -39,13 +39,25 @@ pub(crate) fn jmap_to_hashmap(env: &mut Env, params:
&JObject) -> Result<HashMap
let mut iter = map.iter(env)?;
let mut result: HashMap<String, String> = HashMap::new();
- while let Some(entry) = iter.next(env)? {
- let k = entry.key(env)?;
- let v = entry.value(env)?;
- // SAFETY: a `java.util.Map<String, String>` only yields String keys
and values.
- let k = unsafe { JString::from_raw(env, k.into_raw()) };
- let v = unsafe { JString::from_raw(env, v.into_raw()) };
- result.insert(k.mutf8_chars(env)?.into(), v.mutf8_chars(env)?.into());
+ loop {
+ // Each iteration creates several local references. Release them per
+ // iteration so a large map does not exhaust the JNI local reference
+ // table.
+ let has_next = env.with_local_frame(8, |env| -> Result<bool> {
+ let Some(entry) = iter.next(env)? else {
+ return Ok(false);
+ };
+ let k = entry.key(env)?;
+ let v = entry.value(env)?;
+ // SAFETY: a `java.util.Map<String, String>` only yields String
keys and values.
+ let k = unsafe { JString::from_raw(env, k.into_raw()) };
+ let v = unsafe { JString::from_raw(env, v.into_raw()) };
+ result.insert(k.mutf8_chars(env)?.into(),
v.mutf8_chars(env)?.into());
+ Ok(true)
+ })?;
+ if !has_next {
+ break;
+ }
}
Ok(result)
@@ -58,9 +70,15 @@ pub(crate) fn hashmap_to_jmap<'a, K: AsRef<str>, V:
AsRef<str>>(
let map_object = env.new_object(jni_str!("java/util/HashMap"),
jni_sig!("()V"), &[])?;
let jmap = env.new_cast_local_ref::<JMap>(&map_object)?;
for (k, v) in map {
- let key = env.new_string(k.as_ref())?;
- let value = env.new_string(v.as_ref())?;
- jmap.put(env, &key, &value)?;
+ // The key and value strings are only needed until `put` returns. Scope
+ // them per entry so a large map does not exhaust the JNI local
+ // reference table.
+ env.with_local_frame(4, |env| -> Result<()> {
+ let key = env.new_string(k.as_ref())?;
+ let value = env.new_string(v.as_ref())?;
+ jmap.put(env, &key, &value)?;
+ Ok(())
+ })?;
}
Ok(map_object)
}
diff --git
a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
index 20afd04172..bb5eb31ff1 100644
--- a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
+++ b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
@@ -25,13 +25,27 @@ import java.util.Objects;
public class OperatorOutputStream extends OutputStream {
private static class Writer extends NativeObject {
+ /**
+ * Whether disposing this object commits it. Guarded by the owning
+ * {@link OperatorOutputStream}, which owns the only reference.
+ */
+ private boolean commitOnDispose = true;
+
private Writer(long nativeHandle) {
super(nativeHandle);
}
+ /**
+ * Releases the native writer without committing the object it was
writing.
+ */
+ private void discard() {
+ commitOnDispose = false;
+ close();
+ }
+
@Override
protected void disposeInternal(long handle) {
- disposeWriter(handle);
+ disposeWriter(handle, commitOnDispose);
}
}
@@ -44,6 +58,16 @@ public class OperatorOutputStream extends OutputStream {
private int offset = 0;
+ /**
+ * The first write or flush failure, if any, including a failure thrown by
a subclass
+ * override of {@link #flush()} while {@link #write} ascends through it.
+ *
+ * <p>OpenDAL publishes an object when the native writer is closed. After
a failure the native
+ * writer may hold only a prefix of the content, so {@link #close()}
discards the writer instead
+ * of committing a truncated object.
+ */
+ private Throwable failure;
+
public OperatorOutputStream(Operator operator, String path, WriteOptions
options) {
this(operator, path, DEFAULT_MAX_BYTES, MAX_DIRECT_WRITE_BYTES,
options);
}
@@ -72,7 +96,12 @@ public class OperatorOutputStream extends OutputStream {
ensureOpen();
bytes[offset++] = (byte) b;
if (offset == bytes.length) {
- flush();
+ try {
+ flush();
+ } catch (Throwable t) {
+ recordFailure(t);
+ OperatorOutputStream.<RuntimeException>sneakyThrow(t);
+ }
}
}
@@ -87,13 +116,18 @@ public class OperatorOutputStream extends OutputStream {
final int count;
if (offset == 0 && len >= bytes.length) {
count = Math.min(len, maxBatchBytes);
- writeByteRange(writer.nativeHandle, b, off, count);
+ writeNative(b, off, count);
} else {
count = Math.min(len, bytes.length - offset);
System.arraycopy(b, off, bytes, offset, count);
offset += count;
if (offset == bytes.length) {
- flush();
+ try {
+ flush();
+ } catch (Throwable t) {
+ recordFailure(t);
+ OperatorOutputStream.<RuntimeException>sneakyThrow(t);
+ }
}
}
off += count;
@@ -105,28 +139,141 @@ public class OperatorOutputStream extends OutputStream {
public synchronized void flush() {
ensureOpen();
if (offset != 0) {
- writeByteRange(writer.nativeHandle, bytes, 0, offset);
- offset = 0;
+ flushBuffer();
}
}
@Override
public synchronized void close() {
- if (!writer.isDisposed()) {
- flush();
- writer.close();
+ if (writer.isDisposed()) {
+ return;
+ }
+ // A failure recorded by an earlier write() or flush() is already
propagating from
+ // the caller, possibly from the try-with-resources body of this very
close() call.
+ final Throwable priorFailure = failure;
+ Throwable primary = priorFailure;
+ if (priorFailure == null) {
+ try {
+ flush();
+ } catch (Throwable t) {
+ primary = t;
+ }
+ }
+ // Release the native writer even when the stream failed, otherwise
the handle
+ // leaks and the stream keeps accepting writes. A failed stream is
discarded
+ // instead of closed, because closing would commit the bytes that did
reach the
+ // native writer, possibly truncated. `primary` also covers first
failures that
+ // never reached `writeNative`, such as a subclass override of
`flush()` or a JNI
+ // exception that is neither a RuntimeException nor an Error.
+ Throwable secondary = null;
+ try {
+ if (primary == null) {
+ writer.close();
+ } else {
+ writer.discard();
+ }
+ } catch (Throwable t) {
+ secondary = t;
+ }
+ if (primary == null) {
+ primary = secondary;
+ secondary = null;
}
+ if (primary == null) {
+ return;
+ }
+ if (priorFailure == null) {
+ // close() is the first caller to observe this failure, so nobody
is propagating
+ // it yet. Rethrow it directly instead of wrapping it: the exact
OpenDALException,
+ // Error, or RuntimeException subclass carries the most useful
context and cannot
+ // trigger self-suppression.
+ if (secondary != null && secondary != primary) {
+ primary.addSuppressed(secondary);
+ }
+ OperatorOutputStream.<RuntimeException>sneakyThrow(primary);
+ return;
+ }
+ // The caller may already be propagating this exact instance, and
try-with-resources
+ // suppresses whatever close() throws into it. The JVM rejects
self-suppression with
+ // IllegalArgumentException, so raise a fresh exception and attach the
discard failure
+ // to that new exception instead of the one already in flight.
+ final Throwable reopened = unrecovered(priorFailure);
+ if (secondary != null && secondary != reopened) {
+ reopened.addSuppressed(secondary);
+ }
+ OperatorOutputStream.<RuntimeException>sneakyThrow(reopened);
+ }
+
+ private void flushBuffer() {
+ // Clear the buffered range only after the native write succeeded, so
a failed
+ // flush() keeps the bytes instead of dropping them silently.
+ writeNative(bytes, 0, offset);
+ offset = 0;
+ }
+
+ private void writeNative(byte[] source, int off, int len) {
+ try {
+ writeByteRange(writer.nativeHandle, source, off, len);
+ } catch (Throwable t) {
+ recordFailure(t);
+ OperatorOutputStream.<RuntimeException>sneakyThrow(t);
+ }
+ }
+
+ /** Keeps the first failure and never clears it, so later calls reject the
stream. */
+ private void recordFailure(Throwable t) {
+ if (failure == null) {
+ failure = t;
+ }
+ }
+
+ /**
+ * Throws an exception for a failure that did not commit the object.
+ *
+ * <p>The original throwable may already be the exception a
try-with-resources statement is
+ * propagating, and that statement suppresses whatever {@link #close()}
throws into it.
+ * Suppressing an exception into itself makes the JVM throw
+ * {@link IllegalArgumentException}, which would replace the real failure,
so raise a fresh
+ * exception that keeps the original one as its cause.
+ */
+ private static void throwUnrecovered(Throwable failure) {
+
OperatorOutputStream.<RuntimeException>sneakyThrow(unrecovered(failure));
+ }
+
+ private static Throwable unrecovered(Throwable failure) {
+ if (failure instanceof Error) {
+ return new Error("OperatorOutputStream failed, the object was not
committed", failure);
+ }
+ if (failure instanceof OpenDALException) {
+ final OpenDALException original = (OpenDALException) failure;
+ final OpenDALException reopened = new
OpenDALException(original.getCode(), original.getMessage());
+ reopened.initCause(original);
+ return reopened;
+ }
+ return new IllegalStateException("OperatorOutputStream failed, the
object was not committed", failure);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T extends Throwable> void sneakyThrow(Throwable t) throws
T {
+ throw (T) t;
}
private void ensureOpen() {
if (writer.isDisposed()) {
throw new IllegalStateException("OperatorOutputStream is closed");
}
+ // The native writer can no longer receive the buffered bytes, so
report the sticky
+ // failure instead of buffering writes that will never be sent.
Checking the failure
+ // also keeps a full buffer from overrunning its array when a failed
flush left
+ // `offset` at the end of the buffer.
+ if (failure != null) {
+ throwUnrecovered(failure);
+ }
}
private static native long constructWriter(long op, String path,
WriteOptions options);
- private static native void disposeWriter(long writer);
+ private static native void disposeWriter(long writer, boolean commit);
private static native void writeByteRange(long writer, byte[] bytes, int
off, int len);
}
diff --git a/bindings/java/src/operator.rs b/bindings/java/src/operator.rs
index 8cc47c20b4..e28c799e0e 100644
--- a/bindings/java/src/operator.rs
+++ b/bindings/java/src/operator.rs
@@ -335,8 +335,14 @@ fn intern_list<'local>(
)?;
for (idx, entry) in entries.into_iter().enumerate() {
- let entry = make_entry(env, entry)?;
- jarray.set_element(env, idx, &entry)?;
+ // `make_entry` creates a dozen or more local references. Release them
at
+ // the end of each iteration so a large listing cannot exhaust the JNI
+ // local reference table.
+ env.with_local_frame(16, |env| -> Result<()> {
+ let entry = make_entry(env, entry)?;
+ jarray.set_element(env, idx, &entry)?;
+ Ok(())
+ })?;
}
Ok(jarray)
diff --git a/bindings/java/src/operator_output_stream.rs
b/bindings/java/src/operator_output_stream.rs
index f121efd674..4b99829455 100644
--- a/bindings/java/src/operator_output_stream.rs
+++ b/bindings/java/src/operator_output_stream.rs
@@ -21,6 +21,7 @@ use jni::objects::JByteArray;
use jni::objects::JClass;
use jni::objects::JObject;
use jni::objects::JString;
+use jni::sys::jboolean;
use jni::sys::jint;
use jni::sys::jlong;
use opendal::blocking;
@@ -70,16 +71,25 @@ pub unsafe extern "system" fn
Java_org_apache_opendal_OperatorOutputStream_dispo
mut env: EnvUnowned<'local>,
_: JClass<'local>,
writer: *mut blocking::Writer,
+ commit: jboolean,
) {
env.with_env(|_env| {
let mut writer = unsafe { Box::from_raw(writer) };
- intern_dispose_write(&mut writer)
+ intern_dispose_write(&mut writer, commit)
})
.resolve::<ThrowException>()
}
-fn intern_dispose_write(writer: &mut blocking::Writer) -> crate::Result<()> {
- writer.close()?;
+/// Release the native writer, committing the object only when `commit` is set.
+///
+/// Releasing without `blocking::Writer::close()` drops the writer instead of
+/// closing it, so staged or buffered writes are not committed.
`blocking::Writer`
+/// commits on `close` and never on drop, and dropping it inside the runtime
+/// handle keeps the async writer's cleanup in the runtime context.
+fn intern_dispose_write(writer: &mut blocking::Writer, commit: bool) ->
crate::Result<()> {
+ if commit {
+ writer.close()?;
+ }
Ok(())
}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/JniLocalRefTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/JniLocalRefTest.java
new file mode 100644
index 0000000000..ebd5a93528
--- /dev/null
+++ b/bindings/java/src/test/java/org/apache/opendal/test/JniLocalRefTest.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.opendal.test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.Operator;
+import org.apache.opendal.ServiceConfig;
+import org.apache.opendal.WriteOptions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Regression tests for JNI local reference accumulation: listing a directory
with many entries
+ * must not pin one local reference per entry for the whole native call. Run
the tests with
+ * {@code -Xcheck:jni} to surface a local reference table overflow.
+ */
+public class JniLocalRefTest {
+ private static final int ENTRY_COUNT = 250;
+ private static final int USER_METADATA_COUNT = 5;
+
+ private static WriteOptions writeOptionsWithUserMetadata() {
+ final Map<String, String> userMetadata = new HashMap<>();
+ for (int i = 0; i < USER_METADATA_COUNT; i++) {
+ userMetadata.put("key-" + i, "value-" + i);
+ }
+ return WriteOptions.builder().userMetadata(userMetadata).build();
+ }
+
+ @Test
+ void testBlockingListReleasesLocalReferences() {
+ final WriteOptions options = writeOptionsWithUserMetadata();
+ try (final Operator op =
Operator.of(ServiceConfig.Memory.builder().build())) {
+ for (int i = 0; i < ENTRY_COUNT; i++) {
+ op.write("blocking/file-" + i, "x", options);
+ }
+ assertThat(op.list("blocking/")).hasSize(ENTRY_COUNT);
+ }
+ }
+
+ @Test
+ void testAsyncListReleasesLocalReferences() {
+ final WriteOptions options = writeOptionsWithUserMetadata();
+ try (final AsyncOperator op =
+ AsyncOperator.of(ServiceConfig.Memory.builder().build())) {
+ for (int i = 0; i < ENTRY_COUNT; i++) {
+ op.write("async/file-" + i, "x", options).join();
+ }
+ assertThat(op.list("async/").join()).hasSize(ENTRY_COUNT);
+ }
+ }
+}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
index 7d89ee399a..de927cfe00 100644
---
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
+++
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
@@ -30,6 +30,7 @@ import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils;
+import org.apache.opendal.AsyncOperator;
import org.apache.opendal.OpenDALException;
import org.apache.opendal.Operator;
import org.apache.opendal.OperatorInputStream;
@@ -39,6 +40,7 @@ import org.apache.opendal.ReadOptions;
import org.apache.opendal.ReaderOptions;
import org.apache.opendal.ServiceConfig;
import org.apache.opendal.WriteOptions;
+import org.apache.opendal.layer.ThrottleLayer;
import org.apache.opendal.test.condition.OpenDALExceptionCondition;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -269,6 +271,250 @@ public class OperatorInputOutputStreamTest {
}
}
+ @Test
+ void testOutputStreamCloseReleasesWriterWhenFlushFails() throws Exception {
+ try (final AsyncOperator op =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ final AsyncOperator throttled = op.layer(new
ThrottleLayer(1024, 4));
+ final Operator layeredOp = throttled.blocking()) {
+ final String path = "close-flush-failure";
+ final OperatorOutputStream out =
layeredOp.createOutputStream(path);
+ // The 8 buffered bytes exceed the throttle burst of 4, so the
flush
+ // performed by close() fails with RateLimited.
+ out.write(new byte[8]);
+
+ assertThatThrownBy(out::close)
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited))
+ // close() is the first caller to observe the failed
flush, so the
+ // original exception is rethrown instead of being wrapped.
+ .hasNoCause();
+
+ // A failed close must not publish the object, not even an empty
one.
+ assertNotExist(layeredOp, path);
+
+ // The native writer is released even though flush() failed, so the
+ // stream rejects any further use instead of leaking the handle.
+ assertThatThrownBy(() ->
out.write(1)).isInstanceOf(IllegalStateException.class);
+
assertThatThrownBy(out::flush).isInstanceOf(IllegalStateException.class);
+
+ // Closing again is a safe no-op that does not touch the released
writer.
+ out.close();
+ out.close();
+ }
+ }
+
+ @Test
+ void testOutputStreamCloseDiscardsPartialWrite() throws Exception {
+ try (final AsyncOperator op =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ final AsyncOperator throttled = op.layer(new
ThrottleLayer(1024, 4));
+ final Operator layeredOp = throttled.blocking()) {
+ final String path = "partial-flush-failure";
+ final OperatorOutputStream out =
layeredOp.createOutputStream(path);
+ // The first chunk fits into the burst and reaches the native
writer.
+ out.write(new byte[4]);
+ out.flush();
+ assertNotExist(layeredOp, path);
+
+ // The second chunk exceeds the burst, so this flush fails after
the
+ // native writer already holds the first chunk.
+ out.write(new byte[8]);
+
assertThatThrownBy(out::flush).is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited));
+
+ // close() reports the unrecovered failure and discards the writer.
+ // Committing would publish a truncated object.
+
assertThatThrownBy(out::close).is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited));
+ assertNotExist(layeredOp, path);
+
+ assertThatThrownBy(() ->
out.write(1)).isInstanceOf(IllegalStateException.class);
+
assertThatThrownBy(out::flush).isInstanceOf(IllegalStateException.class);
+ }
+ }
+
+ @Test
+ void testOutputStreamTryWithResourcesKeepsOriginalFailure() throws
Exception {
+ try (final AsyncOperator op =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ final AsyncOperator throttled = op.layer(new
ThrottleLayer(1024, 4));
+ final Operator layeredOp = throttled.blocking()) {
+ final String path = "try-with-resources-failure";
+ final Throwable[] thrown = new Throwable[1];
+ try (final OperatorOutputStream out =
layeredOp.createOutputStream(path)) {
+ out.write(new byte[4]);
+ out.flush();
+ out.write(new byte[8]);
+ out.flush();
+ } catch (Throwable t) {
+ thrown[0] = t;
+ }
+
+ // close() must not add the original failure as a suppressed
exception of itself,
+ // because the JVM rejects self-suppression with
IllegalArgumentException.
+
assertThat(thrown[0]).is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited));
+ assertNotExist(layeredOp, path);
+ }
+ }
+
+ @Test
+ void testOutputStreamCloseDiscardsWhenFlushOverrideFails() throws
Exception {
+ final ServiceConfig.Fs fs =
+ ServiceConfig.Fs.builder().root(tempDir.toString()).build();
+ final String path = "override-flush-failure";
+ final RuntimeException flushFailure = new RuntimeException("flush
failed");
+ try (final Operator op = Operator.of(fs)) {
+ final OperatorOutputStream out =
+ new OperatorOutputStream(op, path,
WriteOptions.builder().build()) {
+ @Override
+ public synchronized void flush() {
+ // A subclass can fail without reaching the native
writer, so the
+ // stream never records this failure in its own
field.
+ throw flushFailure;
+ }
+ };
+ out.write(new byte[8]);
+
+ // Committing here would publish the 8 buffered bytes that never
reached the service.
+ assertThatThrownBy(out::close)
+ .as("first failure observed by close()")
+ .isSameAs(flushFailure);
+ assertNotExist(op, path);
+
+ // The native writer is released even though the stream never
flushed.
+ assertThatThrownBy(() ->
out.write(1)).isInstanceOf(IllegalStateException.class);
+ }
+ }
+
+ @Test
+ void testOutputStreamTryWithResourcesKeepsOriginalError() throws Exception
{
+ final ServiceConfig.Fs fs =
+ ServiceConfig.Fs.builder().root(tempDir.toString()).build();
+ final String path = "try-with-resources-error";
+ final Error flushFailure = new Error("flush failed");
+ final int[] flushes = {0};
+ final Throwable[] thrown = new Throwable[1];
+ try (final Operator op = Operator.of(fs)) {
+ try (final OperatorOutputStream out =
+ new OperatorOutputStream(op, path, 4,
WriteOptions.builder().build()) {
+ @Override
+ public synchronized void flush() {
+ flushes[0]++;
+ throw flushFailure;
+ }
+ }) {
+ out.write(new byte[] {1, 2});
+ // Filling the buffer flushes it, which fails.
+ out.write(new byte[] {3, 4});
+ } catch (Throwable t) {
+ thrown[0] = t;
+ }
+
+ // close() must not rethrow the Error the body is already
propagating, because
+ // try-with-resources would suppress it into itself and the JVM
would replace the
+ // failure with IllegalArgumentException: Self-suppression not
permitted.
+ assertThat(thrown[0]).as("original Error
propagates").isSameAs(flushFailure);
+ // The failure was recorded when write() ascended through flush(),
so close()
+ // discards without flushing again.
+ assertThat(flushes[0]).as("flush() calls").isEqualTo(1);
+ assertThat(thrown[0].getSuppressed()).hasSize(1);
+ assertThat(thrown[0].getSuppressed()[0])
+ .isInstanceOf(Error.class)
+ .hasMessageContaining("not committed")
+ .hasCause(flushFailure);
+ assertNotExist(op, path);
+ }
+ }
+
+ @Test
+ void testOutputStreamRecordsFlushOverrideFailureDuringWrite() throws
Exception {
+ final ServiceConfig.Fs fs =
+ ServiceConfig.Fs.builder().root(tempDir.toString()).build();
+ final String path = "write-flush-override-failure";
+ final RuntimeException flushFailure = new RuntimeException("flush
failed");
+ final int[] flushes = {0};
+ try (final Operator op = Operator.of(fs)) {
+ final OperatorOutputStream out =
+ new OperatorOutputStream(op, path, 4,
WriteOptions.builder().build()) {
+ @Override
+ public synchronized void flush() {
+ flushes[0]++;
+ // Succeed on a later call, so close() flushing
again would commit.
+ if (flushes[0] == 1) {
+ throw flushFailure;
+ }
+ super.flush();
+ }
+ };
+ out.write(1);
+ out.write(2);
+ out.write(3);
+ assertThatThrownBy(() -> out.write(4))
+ .as("flushing the full buffer")
+ .isSameAs(flushFailure);
+ assertThat(flushes[0]).isEqualTo(1);
+
+ // The failure is recorded even though the override never reached
the native writer,
+ // so later writes are rejected instead of overrunning the buffer
array or spinning
+ // on a zero-length batch.
+ assertThatThrownBy(() -> out.write(5))
+ .as("write(int) after failure")
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not committed")
+ .hasCause(flushFailure);
+ assertThatThrownBy(() -> out.write(new byte[] {5, 6}))
+ .as("write(byte[]) after failure")
+ .isInstanceOf(IllegalStateException.class)
+ .hasCause(flushFailure);
+
+ // close() discards without flushing again, even though the
override would now succeed.
+ assertThatThrownBy(out::close)
+ .as("close after failure")
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not committed")
+ .hasCause(flushFailure);
+ assertThat(flushes[0]).as("flush() calls").isEqualTo(1);
+ assertNotExist(op, path);
+ }
+ }
+
+ @Test
+ void testOutputStreamRejectsUseAfterBufferedFlushFailure() throws
Exception {
+ try (final AsyncOperator op =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ final AsyncOperator throttled = op.layer(new
ThrottleLayer(1024, 4));
+ final Operator layeredOp = throttled.blocking()) {
+ final String path = "buffered-flush-failure";
+ // The buffer is larger than the burst, so filling it and flushing
fails while the
+ // offset still points past the end of the buffer.
+ final OperatorOutputStream out = new OperatorOutputStream(
+ layeredOp, path, 8, WriteOptions.builder().build());
+ out.write(new byte[] {1, 2, 3, 4});
+ assertThatThrownBy(() -> out.write(new byte[] {5, 6, 7, 8}))
+ .as("flushing the full buffer")
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited));
+
+ // A sticky failure rejects further use instead of overrunning the
buffer array or
+ // silently accepting bytes that will never be written.
+ assertThatThrownBy(() -> out.write(1))
+ .as("write after failure")
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited))
+ .hasCauseInstanceOf(OpenDALException.class);
+ assertThatThrownBy(out::flush)
+ .as("flush after failure")
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited))
+ .hasCauseInstanceOf(OpenDALException.class);
+
+ // Committing an empty writer would publish an empty object, so
close() discards.
+ assertThatThrownBy(out::close)
+ .as("close after failure")
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RateLimited));
+ assertNotExist(layeredOp, path);
+ }
+ }
+
+ private static void assertNotExist(Operator op, String path) {
+ assertThatThrownBy(() ->
op.stat(path)).is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.NotFound));
+ }
+
@ParameterizedTest
@ValueSource(ints = {0, -1})
void testInvalidOutputBufferSize(int bufferSize) {