Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Package libraries Java code as Java Modules #10714

Draft
wants to merge 97 commits into
base: develop
Choose a base branch
from

Conversation

JaroslavTulach
Copy link
Member

@JaroslavTulach JaroslavTulach commented Jul 30, 2024

Pull Request Description

Implements #7082 by creating a module layer per library. Removes the obsolete add_to_class_path concept as there is no longer a single ClassPath to load from. Each library with polyglot/java JARs gets its own. Need a way to express dependencies between Java APIs among multiple libraries - created requires: flag in package.yaml.

Important Notes

Checklist

Please ensure that the following checklist has been satisfied before submitting the PR:

  • The documentation has been updated, if necessary.
  • Screenshots/screencasts have been attached, if there are any visual changes. For interactive or animated visual changes, a screencast is preferred.
  • All code follows the
    Scala,
    Java,
    TypeScript,
    and
    Rust
    style guides. In case you are using a language not listed above, follow the Rust style guide.
  • Unit tests have been written where possible.
  • Report decent exception of layer resolution problem

@JaroslavTulach JaroslavTulach force-pushed the wip/jtulach/ClassPath7082 branch from ba4db96 to 873c418 Compare July 30, 2024 07:32
@JaroslavTulach JaroslavTulach linked an issue Jul 30, 2024 that may be closed by this pull request
@JaroslavTulach
Copy link
Member Author

Question for @radeusgd - we seem to get the encapsulation with all the consequences. There is dozen of failures:

I can think of ways to fix the tests, but some failures show intended cross-library usage we don't have any alternative yet.

@radeusgd
Copy link
Member

Question for @radeusgd - we seem to get the encapsulation with all the consequences. There is dozen of failures:

I can think of ways to fix the tests, but some failures show intended cross-library usage we don't have any alternative yet.

I imagine we can come up with some workarounds, although that may not be trivial. I'm worried the most about the read autodetection - does it look like the classpath separation breaks the SPI? How can we fix that?

Alternatively, as suggested in #7082 (title Re-exporting), could we provide a way for a library to opt-in to being able to access modules of another lib? e.g. Standard.Table asking to be able to user Java helpers of Standard.Base, e.g. by adding some entry in its package.yaml? That would still prevent users from accessing the internals (unless they also add such an override) while allowing us to more easily share utilities between our libraries.

@JaroslavTulach JaroslavTulach added the CI: Clean build required CI runners will be cleaned before and after this PR is built. label Jul 30, 2024
@JaroslavTulach
Copy link
Member Author

I can think of ways to fix the tests

My plan was:

enso$ git diff distribution/ test/Base_Tests/src/Data/Text/Utils_Spec.enso
diff --git distribution/lib/Standard/Base/0.0.0-dev/src/Internal/Extra_Imports.enso distribution/lib/Standard/Base/0.0.0-dev/src/Internal/Extra_Imports.enso
index 7771401cf4..c42ee36ec6 100644
--- distribution/lib/Standard/Base/0.0.0-dev/src/Internal/Extra_Imports.enso
+++ distribution/lib/Standard/Base/0.0.0-dev/src/Internal/Extra_Imports.enso
@@ -9,7 +9,7 @@ private
 polyglot java import java.io.PrintStream
 
 # needed by Util_Spec
-polyglot java import org.enso.base.text.CaseFoldedString
+polyglot java import org.enso.base.text.CaseFoldedString as JCaseFoldedString
 polyglot java import org.enso.base.text.CaseFoldedString.Grapheme
 
 # needed by Comparator_Spec:
@@ -29,3 +29,5 @@ polyglot java import java.util.function.Function
 polyglot java import java.lang.Thread
 polyglot java import java.lang.Thread.State
 polyglot java import java.lang.Float
+
+CaseFoldedString = JCaseFoldedString
diff --git test/Base_Tests/src/Data/Text/Utils_Spec.enso test/Base_Tests/src/Data/Text/Utils_Spec.enso
index d0b987bea2..7d8d006ff7 100644
--- test/Base_Tests/src/Data/Text/Utils_Spec.enso
+++ test/Base_Tests/src/Data/Text/Utils_Spec.enso
@@ -1,7 +1,7 @@
 from Standard.Base import all
 
 polyglot java import org.enso.base.Text_Utils
-polyglot java import org.enso.base.text.CaseFoldedString
+import Standard.Base.Internal.Extra_Imports.CaseFoldedString
 polyglot java import com.ibm.icu.text.BreakIterator
 
 from Standard.Test import all

but that requires us to run with --disable-private-check. I can add such option, but then I am getting test failures at

[FAILED] Private constructors: [6/11, 26ms]
  | => enso / runEngineDistribution 111s
    - [FAILED] cannot directly call private constructor [4ms]
        Reason: Expected a Panic Private_Access to be thrown, but the action succeeded and returned [(Cons 42)] (at test/Base_Tests/src/Semantic/Private_Spec.enso:18:13-65).
    - [FAILED] can get reference to private constructor, but cannot call it [2ms]
        Reason: Expected a Panic Private_Access to be thrown, but the action succeeded and returned [(Cons 42)] (at test/Base_Tests/src/Semantic/Private_Spec.enso:27:13-58).
    - [FAILED] cannot get private field [2ms]
        Reason: Expected a Panic Private_Access to be thrown, but the action succeeded and returned [42] (at test/Base_Tests/src/Semantic/Private_Spec.enso:35:13-56).
    - [FAILED] cannot call private constructor from Java [3ms]
        Reason: Expected a Panic Private_Access to be thrown, but the action succeeded and returned [(Cons 42)] (at test/Base_Tests/src/Semantic/Private_Spec.enso:59:13-88).
    - [FAILED] cannot call private constructor from a lambda method [3ms]
        Reason: Expected a Panic Private_Access to be thrown, but the action succeeded and returned [(Cons 42)] (at test/Base_Tests/src/Semantic/Private_Spec.enso:62-64).

[FAILED] Private methods: [2/5, 9ms]

I guess we cannot have both: Run with --disable-private-check and these Private tests.

@JaroslavTulach
Copy link
Member Author

Heuréka. JVM tests are green.

@JaroslavTulach
Copy link
Member Author

JaroslavTulach commented Oct 21, 2024

There are seven [FAILED] tests when running the standard library tests on Linux:

  • SQLServer fails with An unexpected dataflow error ((Missing_Data_Link_Library.Error 'Standard.Microsoft' 'SQLServer_Connection'))
  • Table_Tests fail on PostgreSQL with An unexpected dataflow error (Not_Found) probably not founding the driver

I need to find a way to simulate the problem locally!

Update: I manage to simulate similar problem with 208d05d:

sbt:enso> engine-runner/buildNativeImage
sbt:enso> runEngineDistribution --run test/Base_Tests/src/Data/XML/XML_Spec.enso Can.read.from.a.file
- [FAILED] Can read from a file [26ms]
        Reason: An unexpected dataflow error ((Unsupported_Type (File_Format_Metadata.Value '/Base_Tests/data/xml/sample.xml' 'sample.xml' '.xml' File.read_first_bytes[File.enso:732-734] self=org.enso.interpreter.runtime.data.EnsoFile@1e09a7bb n=_ Nothing))) h

looks like there is a problem in discovery of XMLFormatSPI somewhere in Lookup class.

@radeusgd
Copy link
Member

  • Table_Tests fail on PostgreSQL with An unexpected dataflow error (Not_Found) probably not founding the driver

This Not_Found is not about the driver. It looks like #11278. So theoretically merging develop should help, but it looks like you have already done this. So that's weird.

@JaroslavTulach
Copy link
Member Author

JaroslavTulach commented Nov 22, 2024

I tried to workaround the GraalVM ServiceLoader bugs (like oracle/graal#9952 (comment)) with:

diff --git build.sbt build.sbt
index 101f03aa16..f3d1e4a9c9 100644
--- build.sbt
+++ build.sbt
@@ -3777,7 +3777,6 @@ lazy val `engine-runner` = project
               "com.sun.jna",
               "com.microsoft",
               "akka.http",
-              "org.enso.base",
               "org.enso.image",
               "org.enso.table"
             )
diff --git engine/runner/src/main/java/org/enso/runner/EnsoLibraryFeature.java engine/runner/src/main/java/org/enso/runner/EnsoLibraryFeature.java
index 433271da46..2d17c38fcb 100644
--- engine/runner/src/main/java/org/enso/runner/EnsoLibraryFeature.java
+++ engine/runner/src/main/java/org/enso/runner/EnsoLibraryFeature.java
@@ -16,6 +16,34 @@ import org.graalvm.nativeimage.hosted.RuntimeReflection;
 public final class EnsoLibraryFeature implements Feature {
   @Override
   public void beforeAnalysis(BeforeAnalysisAccess access) {
+    try {
+      var lookupClass = access.findClassByName("org.enso.base.lookup.Lookup");
+      var foundField = lookupClass.getDeclaredField("found");
+      foundField.setAccessible(true);
+      var reloadMethod = lookupClass.getDeclaredMethod("reload");
+      access.registerFieldValueTransformer(
+          foundField,
+          (receiver, originalValue) -> {
+            try {
+              System.err.println("  transform " + receiver);
+              reloadMethod.invoke(receiver);
+              var newValue = foundField.get(receiver);
+              System.err.println("  value " + newValue);
+              return newValue;
+            } catch (ReflectiveOperationException ex) {
+              throw new IllegalStateException(ex);
+            }
+          });
+
+    } catch (ReflectiveOperationException | SecurityException ex) {
+      throw new IllegalStateException(ex);
+    }
+
+    registerPolyglotJavaImportForReflectiveAccess(access);
+  }
+
+  private void registerPolyglotJavaImportForReflectiveAccess(BeforeAnalysisAccess access)
+      throws IllegalStateException {
     var libs = new LinkedHashSet<Path>();
     for (var p : access.getApplicationClassPath()) {
       var p1 = p.getParent();
@@ -30,18 +58,18 @@ public final class EnsoLibraryFeature implements Feature {
     }
 
     /*
-      To run Standard.Test one shall analyze its polyglot/java files. But there are none
-      to include on classpath as necessary test classes are included in Standard.Base!
-      We can locate the Test library by following code or we can make sure all necessary
-      imports are already mentioned in Standard.Base itself.
+    To run Standard.Test one shall analyze its polyglot/java files. But there are none
+    to include on classpath as necessary test classes are included in Standard.Base!
+    We can locate the Test library by following code or we can make sure all necessary
+    imports are already mentioned in Standard.Base itself.
 
     if (!libs.isEmpty()) {
-      var f = libs.iterator().next();
-      var stdTest = f.getParent().getParent().resolve("Test").resolve(f.getFileName());
-      if (stdTest.toFile().exists()) {
-        libs.add(stdTest);
-      }
-      System.err.println("Testing library: " + stdTest);
+    var f = libs.iterator().next();
+    var stdTest = f.getParent().getParent().resolve("Test").resolve(f.getFileName());
+    if (stdTest.toFile().exists()) {
+    libs.add(stdTest);
+    }
+    System.err.println("Testing library: " + stdTest);
     }
     */
 
diff --git engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoClassPath.java engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoClassPath.java
index 2d249e3401..bf9a7f11ea 100644
--- engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoClassPath.java
+++ engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoClassPath.java
@@ -120,6 +120,7 @@ public final class EnsoClassPath {
 
   @SuppressWarnings("unchecked")
   private static void registerLayer(ModuleLayer moduleLayer) {
+    new Exception("registerLayer").printStackTrace();
     var props = System.getProperties();
     Collection<ModuleLayer> layers;
     if (props.get("enso.class.path") instanceof Collection registeredLayers) {
diff --git std-bits/base/src/main/java/org/enso/base/lookup/Lookup.java std-bits/base/src/main/java/org/enso/base/lookup/Lookup.java
index 439bf03f22..f42b182d27 100644
--- std-bits/base/src/main/java/org/enso/base/lookup/Lookup.java
+++ std-bits/base/src/main/java/org/enso/base/lookup/Lookup.java
@@ -33,7 +33,7 @@ public final class Lookup<T> implements Iterable<T> {
   }
 
   public void reload() {
-    found = null;
+    found = findAll();
   }
 
   private List<ServiceLoader.Provider<T>> findAll() {

The idea is to populate all the ServiceLoader instances during image build time. There is FieldValueTransformer trying to locate all services. However that doesn't work as the list of packages isn't yet registered!

@JaroslavTulach
Copy link
Member Author

JaroslavTulach commented Dec 2, 2024

This PR oracle/graal#10202 shows the substitutions needed to make the ServiceLoader work in modular environment.

Native Image support for ServiceLoader is implemented and will be part of next GraalVM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CI: Clean build required CI runners will be cleaned before and after this PR is built. CI: No changelog needed Do not require a changelog entry for this PR.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Encapsulation of polyglot/java Dependencies
3 participants