This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9306-5647f440c7b3ddd86906ba000277fbcb2a564c22 in repository https://gitbox.apache.org/repos/asf/texera.git
commit cfca8e1e5de816c4f0d3f0d97e2b8fe3276f9c34 Author: Prateek Ganigi <[email protected]> AuthorDate: Tue Nov 10 04:33:35 2026 +0000 fix(workflow-operator): cap a column value at the remote-fetch limit before parsing it (#9306) ### What changes were proposed in this PR? `_read_binary_value` turned an image or audio cell into bytes whatever its size: the whole value was stripped, checked for HTML and base64-decoded, once per row. A remote fetch of the same payload already stops at `MAX_REMOTE_FETCH_BYTES` (25 MiB), so the same data was refused over HTTP and accepted from a column. The generated Python now checks a cell's size first, against the same constant: - a `bytes` cell is checked before it is returned - any other value is checked right after `str(value)`, before `strip()`, the HTML check, the decodes and the remote fetch An oversized value raises `ValueError("Column value exceeds the 26214400 character limit.")` (or `byte limit` for a `bytes` cell). Both callers already turn an exception into a per-row `Image data error` / `Audio data error`, so one oversized cell fails its own row and the run continues. Worth knowing: for a string the cap counts characters, so a base64 cell, which is 4 characters per 3 bytes, holds at most about 18.75 MiB of decoded data. Images are compressed to about 33 KB before they are sent anyway. ### Any related issues? Closes #8962 ### How was this PR tested? The tests were written first. - `HuggingFaceCodegenBaseSpec`: the size check comes before `strip()`, `_looks_like_html`, `base64.b64decode` and `_fetch_remote_url`, and the `bytes` branch is checked before it returns. - New `HuggingFaceBinaryValueBehaviorSpec`: it runs the generated `_read_binary_value` under a real interpreter, with the parsing helpers replaced by recorders. An oversized string or `bytes` value raises, and nothing parses it first. Values exactly at the limit are still parsed and returned. Before the change, a 26,214,401-character cell was checked for HTML and base64-decoded, and came back as 26 MB of bytes. All three new assertions failed on `main` and pass with the change. Reverting the change makes exactly those three fail again. The Hugging Face suites pass (173 tests), the generated Python of all 117 operators compiles, and scalafmt and scalafix are clean. The behaviour spec has its own small probe (`hf_binary_value_probe.py`) rather than extending `HuggingFaceParseBehaviorSpec`, because #9102 has that spec open. It uses the same interpreter lookup and method-lifting approach, so the two could share a helper once #9102 lands. ### Was this PR authored or co-authored using generative AI tooling? Yes, this PR was co-authored with Claude in compliance with ASF policy. Co-authored-by: Xuan Gu <[email protected]> --- .../codegen/HuggingFaceCodegenBase.scala | 15 +- .../test/resources/python/hf_binary_value_probe.py | 105 ++++++++++++++ .../HuggingFaceBinaryValueBehaviorSpec.scala | 160 +++++++++++++++++++++ .../codegen/HuggingFaceCodegenBaseSpec.scala | 24 ++++ 4 files changed, 303 insertions(+), 1 deletion(-) diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBase.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBase.scala index 81a4b58a62..5d4bf695ec 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBase.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBase.scala @@ -999,6 +999,7 @@ object HuggingFaceCodegenBase { | if value is None: | return None | if isinstance(value, bytes): + | self._check_column_value_size(len(value), "byte") | return value | # Treat scalar pandas/numpy missing sentinels (NaN, pd.NA, NaT) as empty. | # isinstance(value, float) only catches float('nan'); pd.NA / NaT are not @@ -1010,7 +1011,11 @@ object HuggingFaceCodegenBase { | return None | except (TypeError, ValueError): | pass - | val = str(value).strip() + | val = str(value) + | # Bound the cell before it is stripped, sniffed or decoded: each of + | # those passes over the whole value, once per row. + | self._check_column_value_size(len(val), "character") + | val = val.strip() | if not val: | return None | if self._looks_like_html(val): @@ -1030,6 +1035,14 @@ object HuggingFaceCodegenBase { | except Exception: | return val.encode("utf-8") | + | def _check_column_value_size(self, size, unit): + | # The bound _fetch_remote_url applies, so a payload refused over HTTP + | # is not accepted from a column instead. + | if size > self.MAX_REMOTE_FETCH_BYTES: + | raise ValueError( + | f"Column value exceeds the {self.MAX_REMOTE_FETCH_BYTES} {unit} limit." + | ) + | | def _looks_like_html(self, val): | s = val.lstrip()[:200].lower() | if s.startswith("<!doctype html") or s.startswith("<html"): diff --git a/common/workflow-operator/src/test/resources/python/hf_binary_value_probe.py b/common/workflow-operator/src/test/resources/python/hf_binary_value_probe.py new file mode 100644 index 0000000000..3d4dbbaaf3 --- /dev/null +++ b/common/workflow-operator/src/test/resources/python/hf_binary_value_probe.py @@ -0,0 +1,105 @@ +# +# 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. +# + +"""Run the generated `_read_binary_value` against column values at and over the size limit. + +Reads the generated operator Python on stdin and writes, for each case, +{"raised": "<ExcType>", "message": ..., "calls": [...]} or +{"returned": <length>, "calls": [...]} on stdout as one JSON object. + +The method and its size check are lifted out of the source and run on their +own (the generated module depends on the pytexera runtime). The helpers that +parse a value are replaced by recorders, so `calls` shows whether anything +looked at a value before it was refused. +""" +import base64 +import json +import re +import sys + +WANTED = ("_read_binary_value", "_check_column_value_size") + + +def lift(source, name): + """Return the text of a 4-space-indented method, or '' when absent.""" + out, started = [], False + for line in source.split("\n"): + stripped = line.strip() + if stripped.startswith("def " + name + "("): + started = True + elif started and (line.startswith(" def ") or (line and not line.startswith(" "))): + break + if started: + out.append(line) + return "\n".join(out) + + +def main(): + source = sys.stdin.read() + expr = re.search(r"MAX_REMOTE_FETCH_BYTES = ([0-9 *]+)", source).group(1) + limit = eval(expr, {"__builtins__": {}}) + calls = [] + + class RecordingBase64: + def b64decode(self, *args, **kwargs): + calls.append("b64decode") + return base64.b64decode(*args, **kwargs) + + class PandasStub: + # Only pd.isna is used; enough of it for the values below. + @staticmethod + def isna(value): + return value is None or (isinstance(value, float) and value != value) + + def recorder(name, result): + def method(self, *args, **kwargs): + calls.append(name) + return result + return method + + namespace = {"base64": RecordingBase64(), "pd": PandasStub()} + methods = "\n".join(lift(source, name) for name in WANTED) + exec("class Reader:\n MAX_REMOTE_FETCH_BYTES = %d\n%s\n" % (limit, methods), namespace) + reader_class = namespace["Reader"] + reader_class._looks_like_html = recorder("_looks_like_html", False) + reader_class._html_to_image_bytes = recorder("_html_to_image_bytes", b"") + reader_class._fetch_remote_url = recorder("_fetch_remote_url", ("", b"")) + reader = reader_class() + + # "A" * n is valid base64 when n is a multiple of 4, so the at-limit string + # goes through the ordinary decode path rather than the UTF-8 fallback. + cases = { + "str_at_limit": lambda: "A" * limit, + "str_over_limit": lambda: "A" * (limit + 1), + "bytes_at_limit": lambda: b"\0" * limit, + "bytes_over_limit": lambda: b"\0" * (limit + 1), + } + results = {"limit": limit} + for name, make in cases.items(): + del calls[:] + try: + value = reader._read_binary_value(make()) + results[name] = {"returned": len(value), "calls": list(calls)} + except Exception as e: + results[name] = {"raised": type(e).__name__, "message": str(e), "calls": list(calls)} + json.dump(results, sys.stdout) + + +if __name__ == "__main__": + main() diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceBinaryValueBehaviorSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceBinaryValueBehaviorSpec.scala new file mode 100644 index 0000000000..5c51f5ffbe --- /dev/null +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceBinaryValueBehaviorSpec.scala @@ -0,0 +1,160 @@ +/* + * 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.texera.amber.operator.huggingFace.codegen + +import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} +import com.typesafe.config.ConfigFactory +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import java.nio.charset.StandardCharsets +import java.nio.file.{Files, Path} +import java.util.concurrent.TimeUnit +import scala.jdk.CollectionConverters._ +import scala.util.Try + +/** + * Executes the *generated* `_read_binary_value` against column values at and + * over the size limit (#8962). + * + * A column value used to be stripped, sniffed for HTML and decoded whatever its + * size, while a remote fetch of the same payload stops at MAX_REMOTE_FETCH_BYTES. + * The probe lifts the method out of the rendered operator, replaces the helpers + * that parse a value with recorders, and reports whether each value was refused + * and what touched it first. + */ +class HuggingFaceBinaryValueBehaviorSpec extends AnyFlatSpec with Matchers { + + private val mapper = new ObjectMapper() + + private object AnyCodegen extends TaskCodegen { + override def task: String = "image-classification" + override def payloadPython(ctx: CodegenContext): String = " payload = {}" + override def parsePython(ctx: CodegenContext): String = " return ''" + } + + /** Same resolution order as PythonCodeRawInvalidTextSpec: udf.conf, then PATH. */ + private lazy val pythonExe: Option[String] = { + def fromConfig: Option[String] = + Try(ConfigFactory.parseResources("udf.conf").resolve()).toOption + .orElse(Try(ConfigFactory.load()).toOption) + .flatMap(c => Try(c.getConfig("python").getString("path")).toOption) + .map(_.trim) + .filter(_.nonEmpty) + def isRunnable(exe: String): Boolean = + Try(new ProcessBuilder(exe, "--version").redirectErrorStream(true).start()).toOption + .exists { p => + if (!p.waitFor(5, TimeUnit.SECONDS)) { p.destroyForcibly(); false } + else p.exitValue() == 0 + } + (fromConfig.toList ++ List("python3", "python", "py")).distinct.find(isRunnable) + } + + private lazy val probe: Path = { + val script = scala.io.Source.fromInputStream( + getClass.getResourceAsStream("/python/hf_binary_value_probe.py"), + "UTF-8" + ) + val body = + try script.mkString + finally script.close() + val file = Files.createTempFile("hf_binary_value_probe", ".py") + Files.write(file, body.getBytes(StandardCharsets.UTF_8)) + file.toFile.deleteOnExit() + file + } + + /** Runs the probe once over the rendered operator; one entry per case. */ + private lazy val outcomes: JsonNode = { + val exe = pythonExe.getOrElse(cancel("no python interpreter available to run the probe")) + val ctx = CodegenContext( + hfApiToken = "token", + modelId = "google/vit-base-patch16-224", + promptColumn = "prompt", + resultColumn = "hf_response", + task = AnyCodegen.task, + systemPrompt = "", + safeMaxTokens = 256, + safeTemp = 0.7 + ) + val source = HuggingFaceCodegenBase.render(ctx, AnyCodegen) + + // Files rather than pipes for the child's output, so a hung probe still + // reaches the timeout below (see HuggingFaceParseBehaviorSpec). + val outFile = Files.createTempFile("hf_binary_value_probe_out", ".json") + val errFile = Files.createTempFile("hf_binary_value_probe_err", ".txt") + try { + val process = new ProcessBuilder(exe, probe.toString) + .redirectOutput(outFile.toFile) + .redirectError(errFile.toFile) + .start() + process.getOutputStream.write(source.getBytes(StandardCharsets.UTF_8)) + process.getOutputStream.close() + if (!process.waitFor(120, TimeUnit.SECONDS)) { + process.destroyForcibly() + fail("probe timed out") + } + val out = new String(Files.readAllBytes(outFile), StandardCharsets.UTF_8) + val err = new String(Files.readAllBytes(errFile), StandardCharsets.UTF_8) + withClue(s"probe stderr: $err\nprobe stdout: $out\n") { process.exitValue() shouldBe 0 } + mapper.readTree(out) + } finally { + Files.deleteIfExists(outFile) + Files.deleteIfExists(errFile) + } + } + + private def limit: Long = outcomes.get("limit").asLong() + private def calls(node: JsonNode): List[String] = + node.get("calls").elements().asScala.map(_.asText()).toList + + "The generated _read_binary_value" should "refuse a string value over the limit before parsing it" in { + val over = outcomes.get("str_over_limit") + withClue(s"$over: ") { + over.path("raised").asText() shouldBe "ValueError" + over.path("message").asText() shouldBe s"Column value exceeds the $limit character limit." + calls(over) shouldBe empty + } + } + + it should "refuse a bytes value over the limit" in { + val over = outcomes.get("bytes_over_limit") + withClue(s"$over: ") { + over.path("raised").asText() shouldBe "ValueError" + over.path("message").asText() shouldBe s"Column value exceeds the $limit byte limit." + } + } + + it should "still parse a string value exactly at the limit" in { + val at = outcomes.get("str_at_limit") + withClue(s"$at: ") { + at.has("raised") shouldBe false + calls(at) should contain allOf ("_looks_like_html", "b64decode") + } + } + + it should "still return a bytes value exactly at the limit" in { + val at = outcomes.get("bytes_at_limit") + withClue(s"$at: ") { + at.has("raised") shouldBe false + at.get("returned").asLong() shouldBe limit + } + } +} diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBaseSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBaseSpec.scala index f293515dae..f838de74ac 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBaseSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/huggingFace/codegen/HuggingFaceCodegenBaseSpec.scala @@ -197,4 +197,28 @@ class HuggingFaceCodegenBaseSpec extends AnyFlatSpec with Matchers { helper should include("isinstance(content, str)") helper should include("isinstance(content, list)") } + + // #8962: a column value was stripped, sniffed for HTML and decoded whatever its + // size, while _fetch_remote_url stops the same payload at MAX_REMOTE_FETCH_BYTES. + // Both kinds of cell have to be bounded before any of that work starts. + it should "bound a column value's size before parsing it" in { + val out = HuggingFaceCodegenBase.render(makeCtx(), StubCodegen) + val reader = out.split("def _read_binary_value")(1).split(" def ")(0) + + val bytesCheck = reader.indexOf("self._check_column_value_size(len(value), \"byte\")") + bytesCheck should be >= 0 + bytesCheck should be < reader.indexOf("return value") + + val stringCheck = reader.indexOf("self._check_column_value_size(len(val), \"character\")") + stringCheck should be >= 0 + val parsingSteps = + Seq(".strip()", "self._looks_like_html(", "base64.b64decode(", "self._fetch_remote_url(") + for (step <- parsingSteps) { + withClue(s"$step: ") { stringCheck should be < reader.indexOf(step) } + } + + val check = out.split("def _check_column_value_size")(1).split(" def ")(0) + check should include("if size > self.MAX_REMOTE_FETCH_BYTES:") + check should include("raise ValueError(") + } }
