You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fory.apache.org by "pjfanning (via GitHub)" <gi...@apache.org> on 2026/09/20 16:56:58 UTC

[I] fix(scala): fory-json-scala cannot write Queue, primitive mutable ArraySeq, specialised Tuple2, Duration.Undefined, or ScalaTypeRef[Box[Int]] with codegen [fory]

pjfanning opened a new issue, #4068:
URL: https://github.com/apache/fory/issues/4068

   ## Summary
   
   While probing test coverage for `scala/fory-json-scala` (see #4067) I ran a throwaway suite against `main` on Scala 2.13.16 and 3.3.8. Six write-path assertions fail. Each one below is a self-contained ScalaTest block that fails today; the fixtures it needs are listed at the end. Nothing here is a read-path problem: every failing value can be decoded from JSON, it just cannot be encoded (or cannot be compiled by codegen).
   
   Environment: `ForyJsonScala.builder().withCodegen(false).build()` unless the test says otherwise; `runtimes` is that instance plus `withAsyncCompilation(false)`.
   
   ## 1. Non-empty `immutable.Queue` cannot be written
   
   `ScalaCollectionCodecs.RuntimeClasses` is seeded with `Queue.empty`, whose runtime class is the `Queue$EmptyQueue$` singleton, not `scala.collection.immutable.Queue`. A populated queue is a plain `Queue`, which is neither in the identity map nor in the `isAssignableFrom` fallbacks of `supportedRuntime`, so `requireSupportedRuntime` rejects it in `ScalaIterableCodec.writeString`. Decoding works and produces a `Queue`, so a decoded value cannot be re-encoded.
   
   ```
   ForyJsonException: Unsupported Scala collection runtime type scala.collection.immutable.Queue
     at ScalaCollectionCodecs$.requireSupportedRuntime(ScalaCollectionCodecs.scala:1318)
     at ScalaIterableCodec.writeString(ScalaCollectionCodecs.scala:295)
   ```
   
   ```scala
     test("bug: non-empty immutable Queue cannot be written") {
       import scala.collection.{immutable => im}
       val json = runtimes.head
       val queueType = ScalaTypeRef[im.Queue[Int]]
       assert(json.toJson(im.Queue.empty[Int], queueType) == "[]")
       assert(json.fromJson("[1,2]", queueType) == im.Queue(1, 2))
       assert(json.toJson(im.Queue(1, 2), queueType) == "[1,2]")
       assert(json.toJson(im.Queue(1, 2)) == "[1,2]")
     }
   ```
   
   ## 2. Primitive-backed `mutable.ArraySeq` cannot be written
   
   Same root cause. `mutable.ArraySeq.empty[Int]` ignores its `ClassTag` and returns the shared `ofRef` instance, so `RuntimeClasses` only contains `ArraySeq$ofRef`. Any `mutable.ArraySeq` built from primitives (`ofInt`, `ofLong`, `ofDouble`, `ofBoolean`, ...) is rejected. `iterableKind` already selects `MutableArraySeqKind` for these via `isAssignableFrom`, so the kind selection and the runtime check disagree. Immutable `ArraySeq` is unaffected because `supportedRuntime` has an `isAssignableFrom` fallback for it.
   
   ```
   ForyJsonException: Unsupported Scala collection runtime type scala.collection.mutable.ArraySeq$ofInt
   ```
   
   ```scala
     test("bug: primitive-backed mutable ArraySeq cannot be written") {
       import scala.collection.{mutable => mu}
       val json = runtimes.head
       assert(json.toJson(mu.ArraySeq(1, 2)) == "[1,2]")
       assert(json.toJson(mu.ArraySeq("a")) == """["a"]""")
       assert(json.toJson(mu.ArraySeq(1L, 2L)) == "[1,2]")
       assert(json.toJson(mu.ArraySeq(1.5)) == "[1.5]")
       assert(json.toJson(mu.ArraySeq(true)) == "[true]")
       assert(json.toJson(mu.ArraySeq(1L, 2L), ScalaTypeRef[mu.ArraySeq[Long]]) == "[1,2]")
     }
   ```
   
   ## 3. Specialised `Tuple2` instances cannot be written
   
   `ScalaTupleCodec.requireArity` compares `value.getClass != tupleType`. `Tuple2` is `@specialized` on both parameters, so `(1, 2)` is a `Tuple2$mcII$sp` and `(1L, 2.5)` is a `Tuple2$mcJD$sp`; both fail the identity check and raise the arity error even though `productArity == 2`. Only combinations of `Int`, `Long`, `Double`, `Char` and `Boolean` are affected, which is why the existing `(Int, String)` and `(Int, String, Boolean, Long, Double)` tests pass. Both Scala 2.13 and 3 emit the specialised classes.
   
   ```
   ForyJsonException: Scala Tuple2 requires exactly 2 JSON elements
     at ScalaTupleCodec.requireArity(ScalaTupleCodec.scala:448)
     at ScalaTupleCodec.writeString(ScalaTupleCodec.scala:57)
   ```
   
   ```scala
     test("bug: specialised Tuple2 instances cannot be written") {
       val json = runtimes.head
       val intPair = ScalaTypeRef[(Int, Int)]
       assert(json.fromJson("[1,2]", intPair) == ((1, 2)))
       assert(json.toJson((1, 2), intPair) == "[1,2]")
       val longDouble = ScalaTypeRef[(Long, Double)]
       assert(json.toJson((1L, 2.5), longDouble) == "[1,2.5]")
     }
   ```
   
   ## 4. `Duration.Undefined` cannot be written on Scala 2.13
   
   `ScalaDurationCodec.write` matches `case scala.concurrent.duration.Duration.Undefined =>`. `Undefined.equals` is hard-wired to return `false` (like NaN). Scala 2.13 compiles the stable-identifier pattern to `Undefined.equals(value)`, which never matches, so the writer falls through to `invalidDuration()`. Scala 3 compiles the same pattern to `java.util.Objects.equals`, which short-circuits on reference identity, so the test passes there. The reader side returns `Duration.Undefined` correctly, so this is another one-way conversion. A guard on `eq` fixes it for both compilers.
   
   ```
   ForyJsonException: Invalid Scala Duration JSON object
     at ScalaDurationCodec.write(ScalaScalarCodecs.scala:205)
   ```
   
   ```scala
     test("bug: Duration.Undefined cannot be written") {
       for (json <- runtimes) {
         assert(json.toJson(Duration.Undefined, durationType) == """{"special":"UNDEFINED"}""")
       }
     }
   ```
   
   ## 5. `ScalaTypeRef[Box[Int]]` for a generic case class breaks codegen
   
   `ScalaTypeRef` maps the `Int` argument to primitive `int`. When that binds a case-class field declared as an erased type parameter `T`, the generated writer emits a primitive call against an accessor that returns `Object`, and Janino rejects it. The interpreted codec handles the same `TypeRef` correctly, `new TypeRef[ProbeBox[Int]]() {}` (which carries `Object`) works with codegen, and a `ProbeBox[Int]` field inside another case class also works with codegen, so only the `ScalaTypeRef` root path is affected.
   
   ```
   ForyJsonException: Cannot compile generated JSON codec ProbeBoxStringWriterForyJsonCodec_2
   Cause: CompileException: Line 21: No applicable constructor/method found for actual parameters
     "byte[], long, long, long, long, int, java.lang.Object"; candidates are:
     "writeObjectStartWithIntField(byte[], long, long, long, long, int, int)", ...
   generated: writer.writeObjectStartWithIntField(s0, ..., 16, ((ProbeBox)value).value());
   ```
   
   ```scala
     test("bug: ScalaTypeRef primitive argument bound to an erased generic field breaks codegen") {
       val intBox = ScalaTypeRef[ProbeBox[Int]]
       val interpreted = runtimes.head
       assert(interpreted.toJson(ProbeBox(1), intBox) == """{"value":1}""")
       assert(interpreted.fromJson("""{"value":1}""", intBox) == ProbeBox(1))
       val generated = runtimes(1)
       assert(generated.toJson(ProbeBox(1), intBox) == """{"value":1}""")
       assert(generated.fromJson("""{"value":1}""", intBox) == ProbeBox(1))
     }
   ```
   
   ## 6. `Option[Unit]` writer casts `BoxedUnit` to `Void` (minor)
   
   `ScalaTypeRef[Option[Unit]]` resolves the content type to `java.lang.Void`, so `ScalaOptionCodec` delegates `Some(())` to the core `VoidCodec`, which casts the `BoxedUnit` and throws `ClassCastException`. Reading `null` as `None` works. This is an edge case, but it is the only way to get an uncontrolled `ClassCastException` out of the writer.
   
   ```scala
     test("bug: Option[Unit] writer casts BoxedUnit to Void") {
       val json = runtimes.head
       val unitOption = ScalaTypeRef[Option[Unit]]
       assert(json.fromJson("null", unitOption) == None)
       assert(json.toJson(Some(()): Option[Unit], unitOption) == "null")
     }
   ```
   
   ## Fixtures
   
   ```scala
   case class ProbeBox[T](value: T)
   
   private val durationType = classOf[scala.concurrent.duration.Duration]
   
   private def runtimes = Seq(
     ForyJsonScala.builder().withCodegen(false).build(),
     ForyJsonScala.builder().withAsyncCompilation(false).build()
   )
   ```
   
   A seventh failure, `ProbeBox[ProbeBox[Option[Int]]]` being rejected as a "generic recursion", reproduces with a plain Java `Box<Box<Integer>>` and is filed separately against the core resolver.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org


Re: [I] fix(scala): fory-json-scala cannot write Queue, primitive mutable ArraySeq, specialised Tuple2, Duration.Undefined, or ScalaTypeRef[Box[Int]] with codegen [fory]

Posted by "chaokunyang (via GitHub)" <gi...@apache.org>.
chaokunyang closed issue #4068: fix(scala): fory-json-scala cannot write Queue, primitive mutable ArraySeq, specialised Tuple2, Duration.Undefined, or ScalaTypeRef[Box[Int]] with codegen
URL: https://github.com/apache/fory/issues/4068


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org