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-9214-d335251c3721f8748db261c9a0bf6e3a28b23684
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 086a129a83a3e396c2aec769ea0a3da551339e5d
Author: Eugene Gu <[email protected]>
AuthorDate: Wed Nov 25 05:20:40 2026 +0000

    fix(amber): decode the PVE websocket packages list as JSON (#9214)
    
    ### What changes were proposed in this PR?
    
    **Root cause.** The frontend sends the PVE websocket's `packages` query
    parameter as a JSON array (`virtual-environment.service.ts:104`), but
    `PveWebsocketResource.onOpen` never decoded it: it stripped the
    brackets, split the whole value on every comma and deleted every double
    quote. A pip requirement that itself contains a comma, such as
    `example>=1,<2`, was therefore split into two entries, and pip was run
    for `example>=1` and for the invalid fragment `<2`. JSON escapes were
    lost the same way, and a truncated value was accepted silently.
    
    ```text
    Before:  ["example>=1,<2"] -> strip/split/delete quotes -> 
List("example>=1", "<2") -> two pip runs
    After:   ["example>=1,<2"] -> Jackson List[String]      -> 
List("example>=1,<2")    -> one pip run
    ```
    
    **Before (local main 92e86d420, package `tabulate`, operator `>=`,
    version `0.8,<1`; the frontend sent `packages=["tabulate>=0.8,<1"]`).**
    
    <img width="1456" height="829" alt="01-add-package-tabulate-ge-0 8-lt-1"
    
src="https://github.com/user-attachments/assets/0364cd41-1077-44dc-b041-a7608224cede";
    />
    
    The package row filled in as `tabulate` / `>=` / `0.8,<1`, before
    clicking OK.
    
    <img width="1456" height="829"
    alt="02-pip-log-first-fragment-tabulate-ge-0 8-installed"
    
src="https://github.com/user-attachments/assets/0d840134-4b10-49f6-9b64-88f05fe392c9";
    />
    
    Pip is run for the first fragment `tabulate>=0.8` alone, and the
    installed-package list persists it as a package named `tabulate>=0.8`
    with an empty version.
    
    <img width="1456" height="829"
    alt="03-pip-log-second-fragment-lt-1-invalid-requirement"
    
src="https://github.com/user-attachments/assets/19fc1c1b-f8d6-48b7-b49e-37667e3cde57";
    />
    
    Pip is then run for the second fragment and rejects it: `ERROR: Invalid
    requirement: '<1'`, `Failed to install package: <1`.
    
    **After (this branch, same unit, same input; the environment was
    re-created first).**
    
    <img width="1201" height="726" alt="after-01-add-package-tabulate-ge-0
    8-lt-1"
    
src="https://github.com/user-attachments/assets/c1c2ce0f-ffdc-4997-9440-37b38f2aca4d";
    />
    
    The same package row, `tabulate` / `>=` / `0.8,<1`.
    
    <img width="1201" height="726"
    alt="after-02-pip-log-single-requirement-tabulate-ge-0 8-lt-1"
    
src="https://github.com/user-attachments/assets/f2c59e98-79b8-495d-b223-ee6b9f5afa64";
    />
    
    One requirement reaches pip: `Installing package: tabulate>=0.8,<1`,
    `Collecting tabulate<1,>=0.8`, tabulate 0.10.0 installed.
    
    <img width="1201" height="726"
    alt="after-03-pip-log-exit-code-0-final-package-list"
    
src="https://github.com/user-attachments/assets/1574f8fc-961c-40b9-b546-9f43dad6084a";
    />
    
    `install(tabulate>=0.8,<1) finished with exit code 0`, and the final
    user package list records the whole requirement.
    
    **Change.** The decoding moves into a package-private
    `PveWebsocketResource.parsePackages` helper that reads the value with
    the shared `JSONUtils.objectMapper` as `java.util.List[String]`, then
    trims entries and drops blank or null ones as before. A value that is
    not well-formed JSON or not an array of strings raises
    `IllegalArgumentException("Invalid packages parameter: <value>")`, which
    the existing catch arm turns into the `[ERR] ...` line followed by
    `__DONE__`. An absent parameter still defaults to `[]`, and the wire
    format is unchanged, so no frontend change is needed. A
    present-but-empty `packages=` value is now reported as `[ERR] Invalid
    packages parameter: ` followed by `__DONE__` instead of being treated as
    no packages; the frontend always sends at least `[]`, so only
    hand-rolled requests see this.
    
    ### Any related issues, documentation, discussions?
    
    Closes #9212
    
    ### How was this PR tested?
    
    Added to `PveWebsocketResourceSpec`:
    
    - `parsePackages` tests: empty array, several entries, one entry
    containing a comma, JSON escapes, trimming plus blank and `null`
    entries, malformed JSON, non-array JSON (object, bare string, nested
    array), empty value, whitespace around the array, non-ASCII and URL-like
    characters kept unchanged, `[null]`, a trailing comma (rejected: the
    shared mapper keeps Jackson's strict default), duplicate entries kept.
    - An `onOpen` test with a truncated `packages` value that asserts the
    `[ERR] Invalid packages parameter: ...` line and the `__DONE__`
    sentinel.
    
    The spec header's note that the parse chain was unobservable is updated
    accordingly.
    
    ```
    sbt "WorkflowExecutionService/testOnly 
org.apache.texera.web.resource.pythonvirtualenvironment.PveWebsocketResourceSpec"
    ```
    
    - Red (tests against the original parsing extracted unchanged into the
    helper): 11 passed, 10 failed, e.g. `List("example>=1", "<2") was not
    equal to List("example>=1,<2")`.
    - Green (with this change): 23 passed(7 existing + 16 new)
    - Mutation check: dropping the `filter(_.nonEmpty)` from the helper
    fails `trim entries and drop blank or null ones` (20 passed, 1 failed);
    restoring the original comma split inside the helper fails 10 of the 21
    (11 passed, 10 failed); restored afterwards.
    - `sbt WorkflowExecutionService/scalafmtCheck
    WorkflowExecutionService/Test/scalafmtCheck
    "WorkflowExecutionService/scalafix --check"
    "WorkflowExecutionService/Test/scalafix --check"`: all pass.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Yes. Generated-by: Claude Code (claude-fable-5-1). Co-authored with
    Claude; the author reviewed the change before submission.
---
 .../PveWebsocketResource.scala                     |  46 ++++++--
 .../PveWebsocketResourceSpec.scala                 | 117 +++++++++++++++++++--
 2 files changed, 145 insertions(+), 18 deletions(-)

diff --git 
a/amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResource.scala
 
b/amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResource.scala
index 81bf1a1085..1c495c5203 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResource.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResource.scala
@@ -19,11 +19,44 @@
 
 package org.apache.texera.web.resource.pythonvirtualenvironment
 
+import com.fasterxml.jackson.core.JsonProcessingException
+import com.fasterxml.jackson.core.`type`.TypeReference
+import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectReader}
+import org.apache.texera.amber.util.JSONUtils.objectMapper
+
 import javax.websocket._
 import javax.websocket.server.ServerEndpoint
 import java.util.concurrent.LinkedBlockingQueue
 import scala.concurrent.Future
 import scala.concurrent.ExecutionContext.Implicits.global
+import scala.jdk.CollectionConverters._
+
+object PveWebsocketResource {
+
+  // Built once: the shared mapper ignores whatever follows the first value, 
this reader does not.
+  private val packagesReader: ObjectReader = objectMapper
+    .readerFor(new TypeReference[java.util.List[String]] {})
+    .`with`(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+
+  /**
+    * Decodes the `packages` query parameter, a JSON array of pip requirement 
strings, into a
+    * trimmed list without blank entries. Anything that is not exactly one 
JSON array of strings
+    * is rejected, including a JSON `null` and content after the array.
+    */
+  private[pythonvirtualenvironment] def parsePackages(json: String): 
List[String] = {
+    val decoded: java.util.List[String] =
+      try packagesReader.readValue[java.util.List[String]](json)
+      catch {
+        case e: JsonProcessingException =>
+          throw new IllegalArgumentException(s"Invalid packages parameter: 
$json", e)
+      }
+    // Jackson maps a JSON `null` to a null list instead of failing.
+    if (decoded == null) {
+      throw new IllegalArgumentException(s"Invalid packages parameter: $json")
+    }
+    decoded.asScala.toList.filter(_ != null).map(_.trim).filter(_.nonEmpty)
+  }
+}
 
 /**
   *  WebSocket endpoint for PVE creation and user package installation that 
streams
@@ -76,16 +109,9 @@ class PveWebsocketResource {
             PveManager.createNewPve(cuid, queue, pveName)
 
           case "install" =>
-            val packages =
-              params
-                .getOrDefault("packages", java.util.List.of("[]"))
-                .get(0)
-                .stripPrefix("[")
-                .stripSuffix("]")
-                .split(",")
-                .toList
-                .map(_.replace("\"", "").trim)
-                .filter(_.nonEmpty)
+            val packages = PveWebsocketResource.parsePackages(
+              params.getOrDefault("packages", java.util.List.of("[]")).get(0)
+            )
 
             PveManager.installUserPackages(packages, cuid, queue, pveName)
 
diff --git 
a/amber/src/test/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResourceSpec.scala
 
b/amber/src/test/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResourceSpec.scala
index 7ae0bbf2e3..4f50971f2f 100644
--- 
a/amber/src/test/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResourceSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResourceSpec.scala
@@ -65,11 +65,10 @@ import scala.jdk.CollectionConverters._
   *     laundered into that suite's idea of the real runner. `PveResourceSpec` 
owns the
   *     create path instead. Consequence: the `getOrDefault("action", 
List.of("create"))`
   *     default can be replaced with any garbage string and both tests still 
pass.
-  *   - the `packages` query parameter's parse chain is unobservable, and 
mutations to it
-  *     survive: `installUserPackages` reports the missing interpreter and 
returns before it
-  *     ever reads the list, so replacing the parsed list with `Nil` — or 
inverting the
-  *     `filter(_.nonEmpty)` — changes nothing any assertion can see. Pinning 
it needs the
-  *     same fake runner.
+  *   - the decoded `packages` list never reaches an assertion through 
`onOpen`:
+  *     `installUserPackages` reports the missing interpreter and returns 
before it reads the
+  *     list. The decoding itself is pinned directly through `parsePackages` 
below; only the
+  *     hand-off of the decoded list to `PveManager` stays unobserved.
   *   - the pump's guard is pinned at ENTRY ONLY. `while (!done && 
session.isOpen)` narrowed
   *     to `while (!done)` survives, because every session here is open for 
the whole
   *     exchange; killing it needs a test that enters the loop with an 
already-closed
@@ -192,9 +191,9 @@ class PveWebsocketResourceSpec extends AnyFlatSpec with 
Matchers with MockFactor
     val cuid = 313131
     val pveName = "ws-install-env"
 
-    // No `packages` parameter on purpose: whatever this test passed would be 
unobservable
-    // (see the header), and the `getOrDefault` default takes over. Its 
absence is the honest
-    // signal — version-pinned literals here would imply a contract nothing 
pins.
+    // No `packages` parameter on purpose: the list handed to `PveManager` is 
unobservable here
+    // (see the header), and the `getOrDefault` default takes over. The 
decoding of a present
+    // parameter is pinned by the `parsePackages` tests below.
     val f = fixture(
       "cuid" -> cuid.toString,
       "pveName" -> pveName,
@@ -320,4 +319,106 @@ class PveWebsocketResourceSpec extends AnyFlatSpec with 
Matchers with MockFactor
     f.sentLines shouldBe List("[ERR] Missing required parameter: pveName", 
"__DONE__")
     f.assertPumpStopped()
   }
+
+  it should "report an unparseable packages parameter and still send the 
sentinel" in {
+    // The frontend sends `packages` as a JSON array; a truncated one must be 
reported through
+    // the same `[ERR]` line and sentinel as every other failure, not 
swallowed or split apart.
+    val f = fixture(
+      "cuid" -> "424245",
+      "pveName" -> "ws-bad-packages",
+      "action" -> "install",
+      "packages" -> """["example>=1,<2"""
+    )
+
+    new PveWebsocketResource().onOpen(f.session)
+    f.awaitClose()
+
+    f.sentLines should have size 2
+    f.sentLines.head shouldBe """[ERR] Invalid packages parameter: 
["example>=1,<2"""
+    f.sentLines.last shouldBe "__DONE__"
+    f.assertPumpStopped()
+  }
+
+  // -------------------- packages parameter decoding --------------------
+
+  "PveWebsocketResource.parsePackages" should "decode an empty array to no 
packages" in {
+    PveWebsocketResource.parsePackages("[]") shouldBe Nil
+  }
+
+  it should "keep every array element as its own requirement" in {
+    PveWebsocketResource.parsePackages("""["numpy==1.26.0","scipy"]""") 
shouldBe
+      List("numpy==1.26.0", "scipy")
+  }
+
+  it should "keep a comma inside one requirement" in {
+    // `example>=1,<2` is a single pip requirement with two version specifiers.
+    PveWebsocketResource.parsePackages("""["example>=1,<2"]""") shouldBe 
List("example>=1,<2")
+  }
+
+  it should "decode JSON escapes instead of deleting quote characters" in {
+    PveWebsocketResource.parsePackages("""["say \"hi\"", "tab\tsep"]""") 
shouldBe
+      List("say \"hi\"", "tab\tsep")
+  }
+
+  it should "trim entries and drop blank or null ones" in {
+    PveWebsocketResource.parsePackages("""["  numpy  ", "", "   ", null, 
"scipy"]""") shouldBe
+      List("numpy", "scipy")
+  }
+
+  it should "reject malformed JSON, naming the parameter and echoing the 
value" in {
+    val error = intercept[IllegalArgumentException] {
+      PveWebsocketResource.parsePackages("""["numpy"""")
+    }
+    error.getMessage shouldBe """Invalid packages parameter: ["numpy""""
+  }
+
+  it should "reject JSON that is not an array of strings" in {
+    // An object, a bare string and a nested array are all well-formed JSON 
that the frontend
+    // never sends; each has to be refused rather than coerced into package 
names.
+    
intercept[IllegalArgumentException](PveWebsocketResource.parsePackages("""{"numpy":"1"}"""))
+    
intercept[IllegalArgumentException](PveWebsocketResource.parsePackages(""""numpy""""))
+    
intercept[IllegalArgumentException](PveWebsocketResource.parsePackages("""[["numpy"]]"""))
+  }
+
+  it should "reject an empty value" in {
+    intercept[IllegalArgumentException](PveWebsocketResource.parsePackages(""))
+  }
+
+  it should "reject a JSON null, naming the parameter" in {
+    // Jackson decodes a bare `null` to a null list; it must fail like any 
other non-array.
+    val error = intercept[IllegalArgumentException] {
+      PveWebsocketResource.parsePackages("null")
+    }
+    error.getMessage shouldBe "Invalid packages parameter: null"
+  }
+
+  it should "reject content after the array" in {
+    // A second value and stray characters are both refused rather than 
silently dropped.
+    intercept[IllegalArgumentException](
+      PveWebsocketResource.parsePackages("""["numpy"]["scipy"]""")
+    )
+    
intercept[IllegalArgumentException](PveWebsocketResource.parsePackages("""["numpy"]x"""))
+  }
+
+  it should "accept whitespace around the array" in {
+    PveWebsocketResource.parsePackages(" [] ") shouldBe Nil
+    PveWebsocketResource.parsePackages("""["numpy"] """) shouldBe List("numpy")
+  }
+
+  it should "keep non-ASCII and URL-like characters in an entry unchanged" in {
+    PveWebsocketResource.parsePackages("""["naïve-pkg", "a+b%2Fc"]""") shouldBe
+      List("naïve-pkg", "a+b%2Fc")
+  }
+
+  it should "decode an array holding only null to no packages" in {
+    PveWebsocketResource.parsePackages("[null]") shouldBe Nil
+  }
+
+  it should "reject a trailing comma" in {
+    
intercept[IllegalArgumentException](PveWebsocketResource.parsePackages("""["a",]"""))
+  }
+
+  it should "keep duplicate entries" in {
+    PveWebsocketResource.parsePackages("""["a","a"]""") shouldBe List("a", "a")
+  }
 }

Reply via email to