This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git
The following commit(s) were added to refs/heads/main by this push:
new e9e5fda4bb fix(workflow-core): fail a presigned dataset download that
ends before its Content-Length (#9348)
e9e5fda4bb is described below
commit e9e5fda4bbd010ce4f096d806a082f2eebaafed8
Author: Kunwoo (Chris) <[email protected]>
AuthorDate: Tue Nov 10 19:18:03 2026 +0000
fix(workflow-core): fail a presigned dataset download that ends before its
Content-Length (#9348)
### What changes were proposed in this PR?
`LakeFSFileDocument` opened presigned URLs with `new
URL(url).openStream()`. When a proxy closes the connection before the
declared `Content-Length` (for example, the gateway's 15s request
timeout on a multi-GB download), `HttpURLConnection` reports an ordinary
end of stream. So `asInputStream()` callers got a short body with no
error, and `asFile()` saved it as the file. The failure then surfaced
later as a format error such as Arrow's `missing Magic number`, with
different bytes on every attempt.
This PR:
- Opens presigned URLs through a small `LengthCheckedInputStream`. When
the stream ends short of the declared length, it throws an `IOException`
that names the file and both byte counts. Streams without a declared
length pass through unchanged.
- Uses it on both paths that open a presigned URL (with and without a
user JWT).
- Makes `asFile()` delete its temp file when the copy does not finish,
so a failed download no longer leaves a partial file on disk. The copy
goes through `Using.resources` and `transferTo`, so a failing close
cannot replace the truncation error.
The truncation surfaces during the read, after `asInputStream()` has
returned, so it does not trigger the LakeFS fallback. The caller gets
the error.
### Any related issues, documentation, discussions?
Closes #9350, part of #9347.
The gateway-side cause (no request timeout on the RustFS route) is fixed
separately in #9349.
### How was this PR tested?
Added four cases to `LakeFSFileDocumentSpec`, driven by two new modes in
its loopback stub. `truncating` declares the full `Content-Length`,
sends half the body, and closes. `undeclaredLength` sends the body
chunked, with no `Content-Length`.
- `asInputStream` fails the read with an `IOException`, instead of
ending it early.
- `asFile` throws, leaves no `versionedFile*` temp file behind, and a
later `asFile` on the same document reads the file in full.
- `asFile` leaves no temp file behind when the download cannot start at
all (the presign lookup and the LakeFS fallback both fail).
- A chunked body with no declared length still reads in full.
The first three fail on `main` and pass with this change. The two
truncation cases fail with "Expected exception java.io.IOException to be
thrown, but no exception was thrown", and the third because `main`
leaves the temp file behind. The fourth passes on both, so it pins the
pass-through.
```
sbt "WorkflowCore/testOnly
org.apache.texera.amber.core.storage.DocumentFactorySpec
org.apache.texera.amber.core.storage.model.*"
# Tests: succeeded 65, failed 0
sbt "WorkflowCore/scalafixAll --check" WorkflowCore/scalafmtCheckAll #
clean
```
We also confirmed it against a real deployment, where a 1.3 GB `.arrow`
dataset failed intermittently with `missing Magic number`. With the
gateway timeout still in place, the same read now fails with a message
saying the download was cut off.
### Was this PR authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../core/storage/model/LakeFSFileDocument.scala | 71 +++++++++++++++-----
.../storage/model/LakeFSFileDocumentSpec.scala | 78 ++++++++++++++++++----
2 files changed, 120 insertions(+), 29 deletions(-)
diff --git
a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocument.scala
b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocument.scala
index b43768e43c..6f7d226e6c 100644
---
a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocument.scala
+++
b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocument.scala
@@ -25,11 +25,12 @@ import org.apache.texera.amber.core.storage.ResourceType
import
org.apache.texera.amber.core.storage.model.LakeFSFileDocument.userJwtToken
import org.apache.texera.amber.core.storage.util.LakeFSStorageClient
-import java.io.{File, FileOutputStream, InputStream}
+import java.io.{File, IOException, InputStream}
import java.net._
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, Paths, StandardOpenOption}
import scala.jdk.CollectionConverters.IteratorHasAsScala
+import scala.util.Using
object LakeFSFileDocument {
// Since requests need to be sent to the FileService in order to read the
file, we store USER_JWT_TOKEN in the environment vars
@@ -124,7 +125,7 @@ private[storage] class LakeFSFileDocument(uri: URI, val
resourceType: ResourceTy
getVersionHash(),
getFileRelativePath()
)
- new URL(presignUrl).openStream()
+ openPresigned(presignUrl)
} catch {
case e: Exception =>
fallbackToLakeFS(e)
@@ -154,7 +155,7 @@ private[storage] class LakeFSFileDocument(uri: URI, val
resourceType: ResourceTy
.split("\"presignedUrl\"\\s*:\\s*\"")(1)
.split("\"")(0)
- new URL(presignedUrl).openStream()
+ openPresigned(presignedUrl)
} catch {
case e: Exception =>
fallbackToLakeFS(e)
@@ -164,24 +165,24 @@ private[storage] class LakeFSFileDocument(uri: URI, val
resourceType: ResourceTy
}
}
+ private def openPresigned(presignedUrl: String): InputStream = {
+ val connection = new URL(presignedUrl).openConnection()
+ val stream = connection.getInputStream
+ new LengthCheckedInputStream(stream, connection.getContentLengthLong,
getFileRelativePath())
+ }
+
override def asFile(): File = {
tempFile match {
case Some(file) => file
case None =>
val tempFilePath = Files.createTempFile("versionedFile", ".tmp")
- val tempFileStream = new FileOutputStream(tempFilePath.toFile)
- val inputStream = asInputStream()
-
- val buffer = new Array[Byte](1024)
-
- // Create an iterator to repeatedly call inputStream.read, and direct
buffered data to file
- Iterator
- .continually(inputStream.read(buffer))
- .takeWhile(_ != -1)
- .foreach(tempFileStream.write(buffer, 0, _))
-
- inputStream.close()
- tempFileStream.close()
+ try Using.resources(asInputStream(),
Files.newOutputStream(tempFilePath))(_.transferTo(_))
+ catch {
+ // A copy that did not finish is not the file; leaving it would also
leak it on disk.
+ case e: Throwable =>
+ Files.deleteIfExists(tempFilePath)
+ throw e
+ }
val file = tempFilePath.toFile
tempFile = Some(file)
@@ -204,3 +205,41 @@ private[storage] class LakeFSFileDocument(uri: URI, val
resourceType: ResourceTy
override def getFileRelativePath(): String = fileRelativePath.toString
}
+
+/**
+ * Fails a read that ends before the length the server declared.
HttpURLConnection reports a
+ * connection closed mid-body as an ordinary end of stream, so without this a
proxy that times out
+ * a large presigned download hands the caller a silently truncated file,
which a format reader
+ * then rejects as corrupt.
+ *
+ * Extends InputStream rather than FilterInputStream so that skip reads (and
counts) through
+ * `read`, and mark/reset stay unsupported instead of rewinding the wrapped
stream behind the count.
+ */
+private class LengthCheckedInputStream(in: InputStream, expectedLength: Long,
what: String)
+ extends InputStream {
+ private var received = 0L
+
+ override def read(): Int = {
+ val byte = in.read()
+ if (byte == -1) checkComplete() else received += 1
+ byte
+ }
+
+ override def read(buffer: Array[Byte], offset: Int, length: Int): Int = {
+ val count = in.read(buffer, offset, length)
+ if (count == -1) checkComplete() else received += count
+ count
+ }
+
+ override def available(): Int = in.available()
+
+ override def close(): Unit = in.close()
+
+ // An undeclared length is -1, which `received` never falls below, so such
streams pass through.
+ private def checkComplete(): Unit =
+ if (received < expectedLength)
+ throw new IOException(
+ s"Download of $what ended after $received of $expectedLength bytes:
the connection was " +
+ "closed before the whole file arrived."
+ )
+}
diff --git
a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocumentSpec.scala
b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocumentSpec.scala
index bd9c87573c..6a18ec5342 100644
---
a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocumentSpec.scala
+++
b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/model/LakeFSFileDocumentSpec.scala
@@ -27,7 +27,7 @@ import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach}
-import java.io.{ByteArrayInputStream, InputStream}
+import java.io.{ByteArrayInputStream, IOException, InputStream}
import java.net.{InetSocketAddress, URI, URLDecoder, URLEncoder}
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
@@ -88,6 +88,15 @@ class LakeFSFileDocumentSpec
/** Request paths that should answer 500 instead of being served, for this
one test. */
@volatile private var failing: Set[String] = Set.empty
+ /**
+ * Request paths that should declare their full Content-Length but send
only half the body, for
+ * this one test.
+ */
+ @volatile private var truncating: Set[String] = Set.empty
+
+ /** Request paths that should send their body chunked, with no
Content-Length, for this one test. */
+ @volatile private var undeclaredLength: Set[String] = Set.empty
+
private val repositoryName = "texera-file-doc"
private val fileName = "records.csv"
// Most dataset and model files live under a directory, so the read path is
driven over both
@@ -104,8 +113,6 @@ class LakeFSFileDocumentSpec
private def objectPath =
s"/api/v1/repositories/$repositoryName/refs/$versionHash/objects"
private def presignedPath = "/signed-blob/records.csv"
- // Longer than asFile's 1024-byte copy buffer and not a multiple of it (2502
bytes), so the copy
- // loop runs several times and ends on a short read that must not be padded
out to a full buffer.
private val presignedContent: String = "presigned-payload;" * 139
// Deliberately different bytes, and a different length, from the presigned
payload.
private val fallbackContent: String = "direct-lakefs-download"
@@ -147,8 +154,12 @@ class LakeFSFileDocumentSpec
if (uri.getPath == statPath || failing.contains(uri.getPath))
"application/json"
else "application/octet-stream"
exchange.getResponseHeaders.set("Content-Type", contentType)
- exchange.sendResponseHeaders(status, bytes.length.toLong)
- exchange.getResponseBody.write(bytes)
+ // The JDK server reads a response length of 0 as "chunked, no
Content-Length".
+ val declaredLength = if (undeclaredLength.contains(uri.getPath)) 0L else
bytes.length.toLong
+ // Closing short of the declared length makes the JDK server drop the
connection.
+ val sentLength = if (truncating.contains(uri.getPath)) bytes.length / 2
else bytes.length
+ exchange.sendResponseHeaders(status, declaredLength)
+ exchange.getResponseBody.write(bytes, 0, sentLength)
} finally exchange.close()
}
@@ -175,6 +186,8 @@ class LakeFSFileDocumentSpec
super.beforeEach()
requests.clear()
failing = Set.empty
+ truncating = Set.empty
+ undeclaredLength = Set.empty
}
private def hits: List[Hit] = requests.asScala.toList
@@ -191,12 +204,15 @@ class LakeFSFileDocumentSpec
private def nestedRelativePath: String =
Paths.get(nestedSegments.head, nestedSegments.tail: _*).toString
- /** Temp files the lakeFS SDK writes for a direct download, by name. */
- private def sdkTempFiles(): Set[String] =
+ /**
+ * Temp files on disk by name prefix: "download-" for the lakeFS SDK's
direct downloads,
+ * "versionedFile" for asFile's copies.
+ */
+ private def tempFiles(prefix: String): Set[String] =
Option(new java.io.File(System.getProperty("java.io.tmpdir")).list())
.map(_.toSet)
.getOrElse(Set.empty[String])
- .filter(_.startsWith("download-"))
+ .filter(_.startsWith(prefix))
private def readFully(doc: LakeFSFileDocument): String = {
val stream = doc.asInputStream()
@@ -397,11 +413,25 @@ class LakeFSFileDocumentSpec
it should "delete the temp file a direct lakeFS download writes once the
stream is closed" in {
failing = Set(statPath)
- val before = sdkTempFiles()
+ val before = tempFiles("download-")
readFully(servedDoc()) shouldBe fallbackContent
- (sdkTempFiles() -- before) shouldBe empty
+ (tempFiles("download-") -- before) shouldBe empty
+ }
+
+ it should "fail the read, not end it early, when the presigned body stops
short" in {
+ truncating = Set(presignedPath)
+
+ // The cut arrives after asInputStream has returned, so there is nothing
to fall back to.
+ val thrown = intercept[IOException](readFully(servedDoc()))
+ thrown.getMessage should include(s"of ${presignedContent.length} bytes")
+ }
+
+ it should "pass a presigned body with no declared length through unchecked"
in {
+ undeclaredLength = Set(presignedPath)
+
+ readFully(servedDoc()) shouldBe presignedContent
}
it should "name the whole nested relative path on both hops, not the file's
last segment" in {
@@ -426,9 +456,6 @@ class LakeFSFileDocumentSpec
val doc = servedDoc()
val first = doc.asFile()
try {
- // The payload is longer than the 1024-byte copy buffer and not a
multiple of it, so this
- // pins the buffered copy loop: writing a whole buffer on the final
short read would append
- // trailing garbage, and stopping after one buffer would truncate.
new String(Files.readAllBytes(first.toPath), StandardCharsets.UTF_8)
shouldBe presignedContent
// Callers hand the File to operator code that opens it more than once,
so the document must
@@ -441,6 +468,31 @@ class LakeFSFileDocumentSpec
} finally Files.deleteIfExists(first.toPath)
}
+ it should "fail, and leave no partial temp file, when the download is cut
short" in {
+ truncating = Set(presignedPath)
+ val doc = servedDoc()
+ val before = tempFiles("versionedFile")
+
+ intercept[IOException](doc.asFile())
+ (tempFiles("versionedFile") -- before) shouldBe empty
+
+ // Nor does the document remember the failure: once the connection holds,
it reads in full.
+ truncating = Set.empty
+ val file = doc.asFile()
+ try {
+ new String(Files.readAllBytes(file.toPath), StandardCharsets.UTF_8)
shouldBe presignedContent
+ } finally Files.deleteIfExists(file.toPath)
+ }
+
+ it should "leave no temp file when the download cannot start at all" in {
+ // Both routes refuse, so asInputStream itself throws before any byte is
copied.
+ failing = Set(statPath, objectPath)
+ val before = tempFiles("versionedFile")
+
+ an[Exception] should be thrownBy servedDoc().asFile()
+ (tempFiles("versionedFile") -- before) shouldBe empty
+ }
+
it should "close the stream it copied from" in {
// A leaked stream here is a leaked socket per versioned-file read in a
long-running worker
// (the shape of the Iceberg reader leak, #6882). The HTTP stub cannot
observe the close, so