You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@daffodil.apache.org by sl...@apache.org on 2024/09/09 17:25:05 UTC

(daffodil) branch main updated: Remove absolute URI from SchemaFileLocation to improve reproducibility

This is an automated email from the ASF dual-hosted git repository.

slawrence pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/daffodil.git


The following commit(s) were added to refs/heads/main by this push:
     new 9fb833786 Remove absolute URI from SchemaFileLocation to improve reproducibility
9fb833786 is described below

commit 9fb8337863f1277b7aa8edc0a8407fe8536ad6f5
Author: Steve Lawrence <sl...@apache.org>
AuthorDate: Mon Sep 9 13:02:29 2024 -0400

    Remove absolute URI from SchemaFileLocation to improve reproducibility
    
    When we create a saved parser, the absolute URI of the schema context is
    stored in the ScemaFileLocation. This absolute URI is very likely to be
    different if compiled on different machines or in different directories.
    This makes verify reproducible saved processors difficult.
    
    To fix this, this removes the URI from the SchemaFileLocation.
    SchemaFileLocation is only used for diagnostics so does not need the
    absolute URI--diagnosticFile should be used for that. The URI is still
    stored in some objects where it is needed (e.g. import/include), but not
    in any places that are serialized when we created a saved parser.
    
    Previous places that used the URI from SchemaFileLocation are modified
    to either get the URI from somewhere else (that isn't serialized) or use
    diagnosticFile, which is depersonalized and allows for reproducible
    builds.
    
    To verify correctness, this adds a CLI test that builds the same saved
    parser in two different randomly created directories and ensures they
    have the same hash. Some CLI test utilities were updated to support
    this, including the ability to specific a different working directory to
    run the CLI command from. Note however that this tests is disabled due
    to differences sometimes caused by inconsistent JVM optimizations (see
    DAFFODIL-2925).
    
    DAFFODIL-2918
---
 .../org/apache/daffodil/cli/cliTest/Util.scala     | 29 ++++++----
 .../dsom/SchemaDocIncludesAndImportsMixin.scala    |  4 +-
 .../core/runtime1/SchemaSetRuntime1Mixin.scala     | 12 ++++-
 .../lib/exceptions/SchemaFileLocatable.scala       | 30 -----------
 .../processors/DaffodilParseXMLReader.scala        |  2 +-
 .../runtime1/processors/DataProcessor.scala        |  7 +--
 .../daffodil/runtime1/processors/RuntimeData.scala |  5 --
 .../runtime1/processors/SchemaSetRuntimeData.scala | 12 ++++-
 .../org/apache/daffodil/cliTest/TestCLIMisc.scala  | 61 ++++++++++++++++++++++
 9 files changed, 108 insertions(+), 54 deletions(-)

diff --git a/daffodil-cli/src/test/scala/org/apache/daffodil/cli/cliTest/Util.scala b/daffodil-cli/src/test/scala/org/apache/daffodil/cli/cliTest/Util.scala
index e9612a771..3dd42d928 100644
--- a/daffodil-cli/src/test/scala/org/apache/daffodil/cli/cliTest/Util.scala
+++ b/daffodil-cli/src/test/scala/org/apache/daffodil/cli/cliTest/Util.scala
@@ -88,14 +88,14 @@ object Util {
    * passing in the Path to that new file, and delete the file when the
    * function returns.
    */
-  def withTempFile(f: (Path) => Unit): Unit = withTempFile(null, f)
+  def withTempFile[A](f: (Path) => A): A = withTempFile(null, f)
 
   /**
    * Create a temporary file in /tmp/daffodil/ with a given suffix, call a user
    * provided function passing in the Path to that new file, and delete the
    * file when the function returns.
    */
-  def withTempFile(suffix: String, f: (Path) => Unit): Unit = {
+  def withTempFile[A](suffix: String, f: (Path) => A): A = {
     val tempRoot = Paths.get(System.getProperty("java.io.tmpdir"), "daffodil")
     Files.createDirectories(tempRoot)
     val tempFile = Files.createTempFile(tempRoot, "daffodil-", suffix)
@@ -111,7 +111,7 @@ object Util {
    * function passing in the Path to that new directory, and delete the
    * directory and all of its contents when the function returns
    */
-  def withTempDir(f: (Path) => Unit): Unit = {
+  def withTempDir[A](f: (Path) => A): A = {
     val tempRoot = Paths.get(System.getProperty("java.io.tmpdir"), "daffodil")
     Files.createDirectories(tempRoot)
     val tempDir = Files.createTempDirectory(tempRoot, "daffodil-")
@@ -127,7 +127,7 @@ object Util {
    * provided function, and reset or clear the property when the function
    * returns.
    */
-  def withSysProp(keyVal: (String, String))(f: => Unit): Unit = {
+  def withSysProp[A](keyVal: (String, String))(f: => A): A = {
     val key = keyVal._1
     val newVal = keyVal._2
     val oldVal = System.setProperty(key, newVal)
@@ -150,22 +150,24 @@ object Util {
    * verifies the expected exit code.
    *
    * For performance reasons, this defaults to running the CLI in a new thread
-   * unless the classpaths parameter is nonempty or the fork parameter is set to
-   * true. Otherwise a new process is spawned.
+   * unless forking is explicity enabled with the "fork" option, or implicity
+   * by setting one of the options that enables forking.
    *
    * @param args arguments to pass to the CLI. This should not include the
    *   daffodil binary
    * @param classpaths sequence of paths to add to the classpath. If non-empty,
    *   runs the CLI in a new process instead of a thread and will likely decrease
-   *   performance
+   *   performance, enables forking
    * @param envs map of environment varibles to set. If non-empty,
    *   runs the CLI in a new process instead of a thread and will likely decrease
-   *   performance
+   *   performance, enables forking
    * @param fork if true, forces the the CLI to run in a new process
    * @param timeout how long to wait, in seconds, for the testFunc to finish after
    *   the CLI has completed. Test testFunc is interrupted if this timeout is reached
    * @param debug if true, prints arguments and classpath information to
    *   stdout. Also echos all CLITester input and output to stdout.
+   * @param directory if specified, run the CLI command from a different working
+   *   directory, enables forking
    * @param testFunc function to call to send input to the CLI and validate
    *   output from CLI stdout/stderr
    * @param expectedExitCode the expected exit code of the CLI
@@ -179,11 +181,12 @@ object Util {
     envs: Map[String, String] = Map(),
     fork: Boolean = false,
     timeout: Int = 10,
-    debug: Boolean = false
+    debug: Boolean = false,
+    directory: Option[Path] = None
   )(testFunc: (CLITester) => Unit)(expectedExitCode: ExitCode.Value): Unit = {
 
     val (toIn, fromOut, fromErr, cliThreadOrProc: Either[CLIThread, Process]) =
-      if (classpaths.nonEmpty || envs.nonEmpty || fork) {
+      if (classpaths.nonEmpty || envs.nonEmpty || directory.isDefined || fork) {
         // spawn a new process to run Daffodil, needed if a custom classpath is
         // defined or if the caller explicitly wants to fork
         val processBuilder = new ProcessBuilder()
@@ -198,7 +201,11 @@ object Util {
           processBuilder.environment().putAll(envs.asJava)
         }
 
-        val cmd = daffodilBinPath.toString +: args
+        if (directory.isDefined) {
+          processBuilder.directory(directory.get.toFile)
+        }
+
+        val cmd = daffodilBinPath.toAbsolutePath.toString +: args
         if (debug) System.out.println(cmd.mkString(" "))
         processBuilder.command(cmd.toList.asJava)
 
diff --git a/daffodil-core/src/main/scala/org/apache/daffodil/core/dsom/SchemaDocIncludesAndImportsMixin.scala b/daffodil-core/src/main/scala/org/apache/daffodil/core/dsom/SchemaDocIncludesAndImportsMixin.scala
index 6950fb7bb..f68202797 100644
--- a/daffodil-core/src/main/scala/org/apache/daffodil/core/dsom/SchemaDocIncludesAndImportsMixin.scala
+++ b/daffodil-core/src/main/scala/org/apache/daffodil/core/dsom/SchemaDocIncludesAndImportsMixin.scala
@@ -70,7 +70,7 @@ trait SchemaDocIncludesAndImportsMixin { self: XMLSchemaDocument =>
                 schemaDefinitionUnless(
                   inc.targetNamespace =:= tns,
                   "Included schema does not have the same namespace as the file %s including it.",
-                  uriString
+                  diagnosticFile.toString
                 )
                 tns
               }
@@ -142,7 +142,7 @@ trait SchemaDocIncludesAndImportsMixin { self: XMLSchemaDocument =>
   }
 
   override lazy val uriString = {
-    this.uriStringFromAttribute.getOrElse("file:unknown")
+    this.fileAttribute.map(_.toString).getOrElse("file:unknown")
   }
 
   override lazy val diagnosticFile = if (self.schemaFile.isDefined) {
diff --git a/daffodil-core/src/main/scala/org/apache/daffodil/core/runtime1/SchemaSetRuntime1Mixin.scala b/daffodil-core/src/main/scala/org/apache/daffodil/core/runtime1/SchemaSetRuntime1Mixin.scala
index 2887d056a..c055940fd 100644
--- a/daffodil-core/src/main/scala/org/apache/daffodil/core/runtime1/SchemaSetRuntime1Mixin.scala
+++ b/daffodil-core/src/main/scala/org/apache/daffodil/core/runtime1/SchemaSetRuntime1Mixin.scala
@@ -78,10 +78,20 @@ trait SchemaSetRuntime1Mixin {
       !rootERD.dpathElementCompileInfo.isOutputValueCalc,
       "The root element cannot have the dfdl:outputValueCalc property."
     )
+    // stored transiently in the SSRD, only used for full validation
+    val mainSchemaURI = self.schemaSource.uriForLoading
     val p = if (!root.isError) parser else null
     val u = if (!root.isError) unparser else null
     val ssrd =
-      new SchemaSetRuntimeData(p, u, rootERD, variableMap, allLayers, layerRuntimeCompiler)
+      new SchemaSetRuntimeData(
+        p,
+        u,
+        rootERD,
+        variableMap,
+        allLayers,
+        layerRuntimeCompiler,
+        mainSchemaURI
+      )
     if (root.numComponents > root.numUniqueComponents)
       Logger.log.debug(
         s"Compiler: component counts: unique ${root.numUniqueComponents}, actual ${root.numComponents}."
diff --git a/daffodil-lib/src/main/scala/org/apache/daffodil/lib/exceptions/SchemaFileLocatable.scala b/daffodil-lib/src/main/scala/org/apache/daffodil/lib/exceptions/SchemaFileLocatable.scala
index fdf538045..9357aacc1 100644
--- a/daffodil-lib/src/main/scala/org/apache/daffodil/lib/exceptions/SchemaFileLocatable.scala
+++ b/daffodil-lib/src/main/scala/org/apache/daffodil/lib/exceptions/SchemaFileLocatable.scala
@@ -39,7 +39,6 @@ object SchemaFileLocation {
     new SchemaFileLocation(
       context.lineNumber,
       context.columnNumber,
-      context.uriString,
       context.diagnosticFile,
       context.toString,
       context.diagnosticDebugName
@@ -49,7 +48,6 @@ object SchemaFileLocation {
 class SchemaFileLocation protected (
   val lineNumber: Option[String],
   val columnNumber: Option[String],
-  val uriString: String,
   val diagnosticFile: File,
   contextToString: String,
   val diagnosticDebugName: String
@@ -116,35 +114,8 @@ trait SchemaFileLocatable extends LocationInSchemaFile with HasSchemaFileLocatio
     txt
   }
 
-  /**
-   * It would appear that this is only used for informational purposes
-   * and as such, doesn't need to be a URL.  Can just be String.
-   *
-   * override if you don't have a fileName attribute appended
-   * but are in a context where some enclosing construct does
-   * normally only a root node would have a file attribute.
-   *
-   * implement as
-   * @example {{{
-   *     lazy val uriString = uriStringFromAttribute().getOrElse("unknown")
-   * }}}
-   * or delegate like
-   * @example {{{
-   *     lazy val uriString = schemaDocument.uriString
-   * }}}
-   */
-  def uriString: String
-
   def diagnosticFile: File
 
-  lazy val uriStringFromAttribute = {
-    fileAttribute match {
-      case Some(seqNodes) => Some(seqNodes.toString)
-      case None => None
-    }
-
-  }
-
   override lazy val schemaFileLocation = SchemaFileLocation(this)
 }
 
@@ -154,7 +125,6 @@ class XercesSchemaFileLocation(
 ) extends SchemaFileLocation(
     Option(xercesError.getLineNumber.toString),
     Option(xercesError.getColumnNumber.toString),
-    xercesError.getSystemId,
     schemaFileLocation.diagnosticFile,
     schemaFileLocation.toString,
     schemaFileLocation.diagnosticDebugName
diff --git a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DaffodilParseXMLReader.scala b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DaffodilParseXMLReader.scala
index d1c3c073b..cdfab7f44 100644
--- a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DaffodilParseXMLReader.scala
+++ b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DaffodilParseXMLReader.scala
@@ -194,7 +194,7 @@ class DaffodilParseXMLReader(dp: DataProcessor) extends DFDL.DaffodilParseXMLRea
               val sl = s.asInstanceOf[SchemaFileLocation]
               val ln = sl.lineNumber.getOrElse("0").toInt
               val cn = sl.columnNumber.getOrElse("0").toInt
-              val sId = sl.uriString
+              val sId = sl.diagnosticFile.toString
               (ln, cn, sId)
             }
             .getOrElse((0, 0, null))
diff --git a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DataProcessor.scala b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DataProcessor.scala
index 98525bc07..2d325b564 100644
--- a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DataProcessor.scala
+++ b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/DataProcessor.scala
@@ -225,9 +225,10 @@ class DataProcessor(
       case ValidationMode.Limited => null
       case ValidationMode.Custom(cv) => cv
       case ValidationMode.Full => {
-        val cfg = XercesValidatorFactory.makeConfig(
-          ssrd.elementRuntimeData.schemaURIStringsForFullValidation
-        )
+        // we only need to provide the main schema, Xerces will find imported/included schemas
+        // using the Daffodil resolver set in the XercesValidatorFactory
+        val sources = Seq(ssrd.mainSchemaUriForFullValidation.toString)
+        val cfg = XercesValidatorFactory.makeConfig(sources)
         XercesValidatorFactory.makeValidator(cfg)
       }
     }
diff --git a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/RuntimeData.scala b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/RuntimeData.scala
index ffae1eafc..9c38a6cc7 100644
--- a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/RuntimeData.scala
+++ b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/RuntimeData.scala
@@ -724,11 +724,6 @@ sealed class ElementRuntimeData(
 
   override def dfdlType: DFDLPrimType = primType.dfdlType
 
-  lazy val schemaURIStringsForFullValidation: Seq[String] =
-    schemaURIStringsForFullValidation1.distinct
-  private def schemaURIStringsForFullValidation1: Seq[String] = (schemaFileLocation.uriString +:
-    childERDs.flatMap { _.schemaURIStringsForFullValidation1 })
-
   def isComplexType = !isSimpleType
 
   lazy val prefix = this.minimizedScope.getPrefix(namedQName.namespace)
diff --git a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/SchemaSetRuntimeData.scala b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/SchemaSetRuntimeData.scala
index bb02faeff..8302a5a3f 100644
--- a/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/SchemaSetRuntimeData.scala
+++ b/daffodil-runtime1/src/main/scala/org/apache/daffodil/runtime1/processors/SchemaSetRuntimeData.scala
@@ -17,6 +17,8 @@
 
 package org.apache.daffodil.runtime1.processors
 
+import java.net.URI
+
 import org.apache.daffodil.lib.exceptions.ThrowsSDE
 import org.apache.daffodil.runtime1.layers.LayerRuntimeCompiler
 import org.apache.daffodil.runtime1.layers.LayerRuntimeData
@@ -33,7 +35,15 @@ final class SchemaSetRuntimeData(
    */
   variables: VariableMap,
   allLayers: Seq[LayerRuntimeData],
-  @transient layerRuntimeCompilerArg: LayerRuntimeCompiler
+  @transient layerRuntimeCompilerArg: LayerRuntimeCompiler,
+  /**
+   * URI to the root schema, used only for compiling a validator for full validation--this
+   * should not be used for any other purposes. This is marked as transient so that if the
+   * DataProcessor is serialized this URI will not be serialized, which ensures the absolute URI
+   * does not cause issues with save processor reproducibility. Note that saved parsers cannot
+   * be used with full validation so this does not break anything.
+   */
+  @transient val mainSchemaUriForFullValidation: URI
 ) extends Serializable
   with ThrowsSDE {
 
diff --git a/daffodil-test-integration/src/test/scala/org/apache/daffodil/cliTest/TestCLIMisc.scala b/daffodil-test-integration/src/test/scala/org/apache/daffodil/cliTest/TestCLIMisc.scala
new file mode 100644
index 000000000..ba8efd2d2
--- /dev/null
+++ b/daffodil-test-integration/src/test/scala/org/apache/daffodil/cliTest/TestCLIMisc.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.daffodil.cli.cliTest
+
+import java.nio.file.Files
+
+import org.apache.daffodil.cli.Main.ExitCode
+import org.apache.daffodil.cli.cliTest.Util._
+
+import org.junit.Assert.assertEquals
+//import org.junit.Test
+
+class TestCLIMisc {
+
+  /**
+   * Create a saved parser for the same schema but in two different directories, the resulting
+   * saved parsers should be exactly the same
+   *
+   * Note that this test is disabled because JVM optimizations (e.g. serializing zero-length
+   * arrays to singletons) are somewhat inconsistently applied and can lead to saved parsers
+   * that are functionally the same but not bit-for-bit identical, causing CI to randomly fail.
+   * This should be enabled when DAFFODIL-2925 is fixed.
+   */
+  /*@Test*/
+  def test_CLI_SaveParser_reproducible(): Unit = {
+    val schema = path(
+      "daffodil-test/src/test/resources/org/apache/daffodil/section06/entities/charClassEntities.dfdl.xsd"
+    )
+    val schemaName = schema.getFileName
+
+    val md5sums: Seq[String] = (1 to 2).map { _ =>
+      withTempDir { dir =>
+        withTempFile { parser =>
+          val newSchema = dir.resolve(schemaName)
+          Files.copy(schema, newSchema)
+          runCLI(args"save-parser -s $schemaName $parser", directory = Some(dir)) { cli => }(
+            ExitCode.Success
+          )
+          Util.md5sum(parser)
+        }
+      }
+    }
+
+    assertEquals(md5sums(0), md5sums(1))
+  }
+}