From e1e13b47acb23cd638aa6521a580127eb055a306 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Wed, 11 Nov 2026 09:34:51 +0000 Subject: [PATCH] fix(compiler): enforce deterministic semantic facts in IR contract --- .../models/IRBackendExecutableFunction.java | 2 +- .../IRBackendExecutableContractTest.java | 63 +++++++++++++++++++ .../studio/utilities/json/ImmutableJson.java | 22 +++++++ 3 files changed, 86 insertions(+), 1 deletion(-) diff --git a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/IRBackendExecutableFunction.java b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/IRBackendExecutableFunction.java index 2658e424..1c2ebfed 100644 --- a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/IRBackendExecutableFunction.java +++ b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/IRBackendExecutableFunction.java @@ -75,7 +75,7 @@ public record IRBackendExecutableFunction( } public IRBackendExecutableFunction { - semanticFacts = p.studio.utilities.json.ImmutableJson.object(semanticFacts); + semanticFacts = p.studio.utilities.json.ImmutableJson.canonicalObject(semanticFacts); fileId = Objects.requireNonNull(fileId, "fileId"); moduleId = moduleId == null ? ModuleId.none() : moduleId; if (!moduleId.isNone()) { diff --git a/prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java b/prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java index 5009e2b3..616877e5 100644 --- a/prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java +++ b/prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java @@ -18,6 +18,7 @@ import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -286,6 +287,60 @@ class IRBackendExecutableContractTest { "public IRBackend contract must expose only serializable-by-design shapes: " + violations); } + @Test + void semanticFactsMustSnapshotImmutableJsonWithDeterministicObjectOrder() { + final var nested = new LinkedHashMap(); + nested.put("z", null); + nested.put("a", 1); + final var array = new ArrayList<>(List.of("second", "first", nested)); + final var facts = new LinkedHashMap(); + facts.put("z", nested); + facts.put("array", array); + facts.put("a", true); + + final var function = functionWithSemanticFacts(facts); + final var snapshot = function.semanticFacts(); + assertEquals(List.of("a", "array", "z"), new ArrayList<>(snapshot.keySet())); + final var nestedSnapshot = (Map) snapshot.get("z"); + assertEquals(List.of("a", "z"), new ArrayList<>(nestedSnapshot.keySet())); + final var arraySnapshot = (List) snapshot.get("array"); + assertEquals(List.of("second", "first"), arraySnapshot.subList(0, 2)); + assertEquals(List.of("a", "z"), new ArrayList<>(((Map) arraySnapshot.get(2)).keySet())); + assertTrue(nestedSnapshot.containsKey("z")); + assertNull(nestedSnapshot.get("z")); + + final var reordered = new LinkedHashMap(); + reordered.put("a", true); + reordered.put("array", array); + reordered.put("z", new LinkedHashMap<>(nested.reversed())); + assertEquals(snapshot.toString(), functionWithSemanticFacts(reordered).semanticFacts().toString()); + + facts.clear(); + nested.clear(); + array.clear(); + assertEquals(3, snapshot.size()); + assertEquals(2, nestedSnapshot.size()); + assertEquals(3, arraySnapshot.size()); + assertThrows(UnsupportedOperationException.class, () -> snapshot.put("new", 2)); + assertThrows(UnsupportedOperationException.class, nestedSnapshot::clear); + assertThrows(UnsupportedOperationException.class, arraySnapshot::clear); + assertThrows(UnsupportedOperationException.class, ((Map) arraySnapshot.get(2))::clear); + assertTrue(functionWithSemanticFacts(null).semanticFacts().isEmpty()); + } + + @Test + void semanticFactsMustRejectLiveObjectsAndUnorderedArrays() { + for (final var value : List.of(new Object(), (Runnable) () -> {}, Set.of("unordered"), Map.of(1, "bad key"))) { + assertThrows(IllegalArgumentException.class, () -> functionWithSemanticFacts(Map.of("fact", value))); + assertThrows(IllegalArgumentException.class, () -> functionWithSemanticFacts(Map.of("array", List.of(value)))); + } + } + + private static IRBackendExecutableFunction functionWithSemanticFacts(Map facts) { + return new IRBackendExecutableFunction(new FileId(0), ModuleId.none(), "main", new CallableId(0), + 0, 0, 0, 0, 0, 0, ReadOnlyList.empty(), Span.none(), IRRegistry.FunctionMetadata.empty(), facts); + } + @Test void callInstructionMustRequireCategorySpecificMetadata() { assertThrows(IllegalArgumentException.class, () -> new IRBackendExecutableFunction.Instruction( @@ -1001,6 +1056,14 @@ class IRBackendExecutableContractTest { return; } if (type instanceof ParameterizedType parameterizedType) { + // Compiler spec 20 ยง4.2 permits maps with deterministic ordering. This one + // field is recursively validated, sorted and frozen by its constructor. + if ((owner.equals(IRBackendExecutableFunction.class.getName() + "#semanticFacts") + || owner.equals(IRBackendExecutableFunction.class.getName() + "#")) + && parameterizedType.getRawType().equals(Map.class) + && List.of(parameterizedType.getActualTypeArguments()).equals(List.of(String.class, Object.class))) { + return; + } inspectSerializableContractType(owner, parameterizedType.getRawType(), violations); for (final var argument : parameterizedType.getActualTypeArguments()) { inspectSerializableContractType(owner, argument, violations); diff --git a/prometeu-infra/src/main/java/p/studio/utilities/json/ImmutableJson.java b/prometeu-infra/src/main/java/p/studio/utilities/json/ImmutableJson.java index 6e7b1e7d..3417077b 100644 --- a/prometeu-infra/src/main/java/p/studio/utilities/json/ImmutableJson.java +++ b/prometeu-infra/src/main/java/p/studio/utilities/json/ImmutableJson.java @@ -10,6 +10,28 @@ public final class ImmutableJson { if (source != null) source.forEach((key, value) -> result.put(Objects.requireNonNull(key), value(value))); return Collections.unmodifiableMap(result); } + /** Copies JSON data with sorted object keys at every depth and ordered arrays only. */ + public static Map canonicalObject(Map source) { + return canonicalMap(source == null ? Map.of() : source); + } + private static Map canonicalMap(Map source) { + var result = new TreeMap(); + source.forEach((key, value) -> { + if (!(key instanceof String name)) { + throw new IllegalArgumentException("Expected JSON object key to be a string"); + } + result.put(name, canonicalValue(value)); + }); + return Collections.unmodifiableMap(result); + } + private static Object canonicalValue(Object source) { + if (source instanceof Map values) return canonicalMap(values); + if (source instanceof List values) return values.stream().map(ImmutableJson::canonicalValue).toList(); + if (source instanceof Collection) { + throw new IllegalArgumentException("Expected ordered JSON array as a list"); + } + return value(source); + } public static Object value(Object source) { if (source == null || source instanceof String || source instanceof Boolean || source instanceof Byte || source instanceof Short || source instanceof Integer || source instanceof Long || source instanceof Float