This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 2a460a2d77e0 CAMEL-26839: Prepare immutable WASM data once per pool
instance (#29835)
2a460a2d77e0 is described below
commit 2a460a2d77e0f3e12882f0af1da3b361ac7d4160
Author: Andrea Cosentino <[email protected]>
AuthorDate: Mon Nov 16 22:55:01 2026 +0100
CAMEL-26839: Prepare immutable WASM data once per pool instance (#29835)
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Codex <[email protected]>
---
.../apache/camel/catalog/docs/opa-component.adoc | 8 +
.../camel-opa/src/main/docs/opa-component.adoc | 8 +
.../camel/component/opa/OpaWasmEvaluator.java | 34 ++--
.../camel/component/opa/OpaWasmPolicyPool.java | 7 +-
.../component/opa/OpaWasmStaticDataBenchmark.java | 208 +++++++++++++++++++++
.../camel/component/opa/OpaWasmStaticDataIT.java | 176 +++++++++++++++++
.../test/resources/wasm-benchmark/permissions.rego | 40 ++++
design/opa-wasm-static-data.adoc | 65 +++++++
parent/pom.xml | 2 +
9 files changed, 532 insertions(+), 16 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
index 13d20db8a0d4..5a6920987e40 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
@@ -674,6 +674,14 @@ xref:spiffe-component.adoc[SPIFFE] component page
describes the rest of its opti
None of this applies in `wasm` mode, where there is no server to reach.
+=== Static data in pooled WASM instances
+
+Each WASM pool instance prepares its fixed entrypoint and bundled data once
when created. New inputs reuse that
+instance's static data while the SDK resets transient input allocations for
each evaluation. Instances are never
+shared concurrently. An evaluation failure discards the instance, and its
replacement loads the same configured
+entrypoint and data before use. Large static data therefore adds
initialization work per instance, rather than
+being parsed again for every exchange.
+
[[failure-handling]]
== Failure handling
diff --git a/components/camel-opa/src/main/docs/opa-component.adoc
b/components/camel-opa/src/main/docs/opa-component.adoc
index 13d20db8a0d4..5a6920987e40 100644
--- a/components/camel-opa/src/main/docs/opa-component.adoc
+++ b/components/camel-opa/src/main/docs/opa-component.adoc
@@ -674,6 +674,14 @@ xref:spiffe-component.adoc[SPIFFE] component page
describes the rest of its opti
None of this applies in `wasm` mode, where there is no server to reach.
+=== Static data in pooled WASM instances
+
+Each WASM pool instance prepares its fixed entrypoint and bundled data once
when created. New inputs reuse that
+instance's static data while the SDK resets transient input allocations for
each evaluation. Instances are never
+shared concurrently. An evaluation failure discards the instance, and its
replacement loads the same configured
+entrypoint and data before use. Large static data therefore adds
initialization work per instance, rather than
+being parsed again for every exchange.
+
[[failure-handling]]
== Failure handling
diff --git
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
index 7e909b0b2f50..b411f3a668b5 100644
---
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
+++
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
@@ -64,11 +64,16 @@ public class OpaWasmEvaluator extends OpaPolicyEvaluator
implements AutoCloseabl
this.data = data;
// OpaPolicy carries mutable input/data and is not thread-safe, while
a Camel producer is invoked
// concurrently - so each exchange borrows its own instance rather
than sharing one
- this.pool = new OpaWasmPolicyPool(() ->
OpaPolicy.builder().withPolicy(wasm).build(), poolSize, borrowTimeout);
+ this.pool = new OpaWasmPolicyPool(() -> {
+ OpaPolicy policy = OpaPolicy.builder().withPolicy(wasm).build();
+ prepare(policy);
+ return policy;
+ }, poolSize, borrowTimeout);
// fail at startup rather than on the first exchange: the OpaPolicy
constructor is what rejects a module
// that is not a valid OPA bundle, and the pool creates instances
lazily
- try (OpaWasmPolicyPool.Lease warmup = pool.borrow()) {
- prepare(warmup.policy());
+ try {
+ // The factory validates and prepares every instance, including
replacements after evaluation failures.
+ pool.borrow().close();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while loading the
WebAssembly policy", e);
@@ -78,10 +83,11 @@ public class OpaWasmEvaluator extends OpaPolicyEvaluator
implements AutoCloseabl
}
/**
- * Applies the entrypoint and data to a borrowed instance.
+ * Applies the immutable entrypoint and data once to each newly
constructed instance.
* <p/>
- * Done on every borrow rather than once at creation, so that a pooled
instance always evaluates the configured rule
- * against the bundle's data regardless of what a previous borrower left
on it. See
+ * The pool is private to this evaluator and no borrower changes these
values. The managed SDK rewinds its input
+ * heap to the saved data boundary on every evaluate(String), so
reapplying data only reparses the same document. A
+ * failed evaluation discards the instance; its replacement goes through
this preparation again. See
* {@link OpaWasmPolicyPool.Lease#close()} for why nothing is reset on
return.
*/
private void prepare(OpaPolicy policy) {
@@ -181,19 +187,21 @@ public class OpaWasmEvaluator extends OpaPolicyEvaluator
implements AutoCloseabl
@Override
protected Object evaluateDecision(Map<String, Object> input) throws
Exception {
+ // serialized before borrowing, so an input that cannot be serialized
costs no pooled instance
+ String json = MAPPER.writeValueAsString(input);
OpaWasmPolicyPool.Lease lease = pool.borrow();
+ String result;
try {
- prepare(lease.policy());
- Object decision =
unwrap(lease.policy().evaluate(MAPPER.writeValueAsString(input)));
- lease.close();
- return decision;
+ result = lease.policy().evaluate(json);
} catch (Exception e) {
- // a trap part-way through an evaluation can leave the instance in
an undefined state, so drop it
- // rather than hand it to the next exchange. Safe to call
unconditionally: a lease ends exactly once,
- // so this is a no-op when close() above already returned it
+ // a trap part-way through an evaluation can leave the instance in
an undefined state, so drop it rather
+ // than hand it to the next exchange. A replacement pays for
module creation and the full data parse,
+ // which is why an undefined decision, found by unwrap below and
not a trap, keeps the instance
lease.discard();
throw e;
}
+ lease.close();
+ return unwrap(result);
}
/**
diff --git
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmPolicyPool.java
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmPolicyPool.java
index f7617f5d59bb..18631e487e3c 100644
---
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmPolicyPool.java
+++
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmPolicyPool.java
@@ -138,9 +138,10 @@ final class OpaWasmPolicyPool implements AutoCloseable {
* Returns the instance to the pool for reuse.
* <p/>
* Nothing is reset on the way in. {@code OpaPolicy.reset()} is
package-private to the SDK and so cannot be
- * called from here, but it is also not needed: the borrower sets the
entrypoint and the data document on every
- * borrow, and {@code OpaPolicy.input()} - which {@code
evaluate(String)} calls - rewinds the WebAssembly heap
- * to the data pointer each time, so nothing accumulates across reuses.
+ * called from here, but it is also not needed: the evaluator's
factory initializes each instance with its fixed
+ * entrypoint and data, and borrowers never modify them. {@code
OpaPolicy.input()} - which
+ * {@code evaluate(String)} calls - rewinds the WebAssembly heap to
the saved data boundary each time, so
+ * per-request allocations do not accumulate across reuses. A failed
evaluation discards the instance.
*/
@Override
public void close() {
diff --git
a/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmStaticDataBenchmark.java
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmStaticDataBenchmark.java
new file mode 100644
index 000000000000..1aeae27ca62a
--- /dev/null
+++
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmStaticDataBenchmark.java
@@ -0,0 +1,208 @@
+/*
+ * 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.camel.component.opa;
+
+import java.lang.management.ManagementFactory;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Locale;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.styra.opa.wasm.OpaPolicy;
+import com.sun.management.ThreadMXBean;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.test.infra.opa.services.OpaWasmBundleBuilder;
+
+/**
+ * Opt-in executable smoke benchmark of the actual Camel pool and managed SDK.
Not a unit test or a JMH substitute.
+ * Compile permissions.rego with the pinned test-infra OPA compiler first; no
precompiled WASM is checked in. Arguments:
+ * bare-module-path-or---compile [entries=1000] [threads=1] [warmup-ms=1000]
[measurement-ms=2000].
+ */
+public final class OpaWasmStaticDataBenchmark {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String ALLOW =
"{\"subject\":\"user0\",\"resource\":\"document0\",\"action\":\"read\"}";
+ private static final String DENY =
"{\"subject\":\"user0\",\"resource\":\"other\",\"action\":\"read\"}";
+
+ private OpaWasmStaticDataBenchmark() {
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 1) {
+ throw new IllegalArgumentException("Expected bare WASM module
path; see design/opa-wasm-static-data.adoc");
+ }
+ byte[] wasm = "--compile".equals(args[0]) ? compileModule() :
Files.readAllBytes(Path.of(args[0]));
+ int entries = args.length > 1 ? Integer.parseInt(args[1]) : 1000;
+ int threads = args.length > 2 ? Integer.parseInt(args[2]) : 1;
+ long warmup = args.length > 3 ? Long.parseLong(args[3]) : 1000;
+ long measurement = args.length > 4 ? Long.parseLong(args[4]) : 2000;
+ if (entries < 1 || threads < 1 || warmup < 1 || measurement < 1) {
+ throw new IllegalArgumentException("All numeric arguments must be
positive");
+ }
+ String data = data(entries);
+ System.out.printf("java=%s vm=%s arch=%s dataEntries=%d dataBytes=%d
threads=%d warmupMs=%d measurementMs=%d%n",
+ System.getProperty("java.version"),
System.getProperty("java.vm.name"), System.getProperty("os.arch"),
+ entries, data.getBytes(StandardCharsets.UTF_8).length,
threads, warmup, measurement);
+ System.out.println(
+
"mode,operations,operationsPerSecond,allocatedBytesPerOperation,createdInstances,meanFirstEvaluationMs,checksum");
+ run(wasm, data, threads, warmup, measurement, false);
+ run(wasm, data, threads, warmup, measurement, true);
+ }
+
+ static byte[] compileModule() throws Exception {
+ String policy;
+ try (var in =
OpaWasmStaticDataBenchmark.class.getResourceAsStream("/wasm-benchmark/permissions.rego"))
{
+ if (in == null) {
+ throw new IllegalStateException("Missing permissions.rego");
+ }
+ policy = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ byte[] bundle = OpaWasmBundleBuilder.build("permissions.rego", policy,
"benchmark/allow", "benchmark/strict",
+ "benchmark/isolation");
+ Path temporary = Files.createTempFile("camel-opa-static-data",
".tar.gz");
+ try (var context = new DefaultCamelContext()) {
+ Files.write(temporary, bundle);
+ return OpaWasmEvaluator.loadPolicy(context,
temporary.toUri().toString()).wasm();
+ } finally {
+ Files.deleteIfExists(temporary);
+ }
+ }
+
+ static String data(int entries) throws Exception {
+ var grants = MAPPER.createObjectNode();
+ for (int i = 0; i < entries; i++) {
+ grants.putObject("user" + i).put("resource", "document" +
i).put("enabled", true)
+ .put("tenant", "tenant" + (i % 100)).put("description",
"static authorization grant");
+ }
+ return
MAPPER.writeValueAsString(MAPPER.createObjectNode().set("permissions", grants));
+ }
+
+ private static void run(byte[] wasm, String data, int threads, long
warmup, long measurement, boolean prepareOnce)
+ throws Exception {
+ var created = new AtomicInteger();
+ var firstEvaluationNanos = new AtomicLong();
+ var allocations = ManagementFactory.getThreadMXBean() instanceof
ThreadMXBean bean
+ && bean.isThreadAllocatedMemorySupported() ? bean : null;
+ if (allocations != null &&
!allocations.isThreadAllocatedMemoryEnabled()) {
+ allocations.setThreadAllocatedMemoryEnabled(true);
+ }
+ try (var pool = new OpaWasmPolicyPool(() -> {
+ created.incrementAndGet();
+ OpaPolicy policy = OpaPolicy.builder().withPolicy(wasm).build();
+ if (prepareOnce) {
+ prepare(policy, data);
+ }
+ return policy;
+ }, threads, 30000)) {
+ var executor = Executors.newFixedThreadPool(threads);
+ var ready = new CountDownLatch(threads);
+ var start = new CountDownLatch(1);
+ var tasks = new ArrayList<Future<Sample>>();
+ try {
+ for (int worker = 0; worker < threads; worker++) {
+ tasks.add(executor.submit((Callable<Sample>) () -> {
+ long count = 0;
+ try {
+ // Exclude lazy module compilation and initial
data loading from the warmup clock as well.
+ long firstEvaluationStart = System.nanoTime();
+ evaluate(pool, data, prepareOnce, 0);
+ firstEvaluationNanos.addAndGet(System.nanoTime() -
firstEvaluationStart);
+ long deadline = System.nanoTime() +
TimeUnit.MILLISECONDS.toNanos(warmup);
+ do {
+ evaluate(pool, data, prepareOnce, count++);
+ } while (System.nanoTime() < deadline);
+ } finally {
+ ready.countDown();
+ }
+ if (!start.await(30, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Timed out waiting
for benchmark start");
+ }
+ long allocatedBefore = allocated(allocations);
+ long deadline = System.nanoTime() +
TimeUnit.MILLISECONDS.toNanos(measurement);
+ count = 0;
+ long checksum = 0;
+ do {
+ checksum += evaluate(pool, data, prepareOnce,
count++);
+ } while (System.nanoTime() < deadline);
+ return new Sample(count, allocated(allocations) -
allocatedBefore, checksum);
+ }));
+ }
+ if (!ready.await(60, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Benchmark warmup failed
or timed out");
+ }
+ long begin = System.nanoTime();
+ start.countDown();
+ long operations = 0;
+ long bytes = 0;
+ long checksum = 0;
+ for (var task : tasks) {
+ Sample sample = task.get(measurement + 30000,
TimeUnit.MILLISECONDS);
+ operations += sample.operations;
+ bytes += sample.allocated;
+ checksum += sample.checksum;
+ }
+ double seconds = (System.nanoTime() - begin) / 1_000_000_000.0;
+ System.out.printf(Locale.ROOT, "%s,%d,%.2f,%.2f,%d,%.2f,%d%n",
prepareOnce ? "prepare-once" : "per-borrow",
+ operations, operations / seconds, allocations != null
? (double) bytes / operations : -1.0,
+ created.get(), firstEvaluationNanos.get() / (threads *
1_000_000.0), checksum);
+ } finally {
+ start.countDown();
+ executor.shutdownNow();
+ }
+ }
+ }
+
+ private static long allocated(ThreadMXBean bean) {
+ return bean != null ? bean.getCurrentThreadAllocatedBytes() : 0;
+ }
+
+ private static int evaluate(OpaWasmPolicyPool pool, String data, boolean
prepareOnce, long sequence) throws Exception {
+ var lease = pool.borrow();
+ try {
+ if (!prepareOnce) {
+ prepare(lease.policy(), data);
+ }
+ boolean allow = sequence % 2 == 0;
+ String result = lease.policy().evaluate(allow ? ALLOW : DENY);
+ if (!result.equals(allow ? "[{\"result\":true}]" :
"[{\"result\":false}]")) {
+ throw new IllegalStateException("Unexpected decision or
cross-request state: " + result);
+ }
+ lease.close();
+ return result.hashCode();
+ } catch (Exception e) {
+ lease.discard();
+ throw e;
+ }
+ }
+
+ private static void prepare(OpaPolicy policy, String data) {
+ policy.entrypoint("benchmark/allow");
+ policy.data(data);
+ }
+
+ private record Sample(long operations, long allocated, long checksum) {
+ }
+}
diff --git
a/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmStaticDataIT.java
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmStaticDataIT.java
new file mode 100644
index 000000000000..b98cbcd05151
--- /dev/null
+++
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmStaticDataIT.java
@@ -0,0 +1,176 @@
+/*
+ * 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.camel.component.opa;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.styra.opa.wasm.OpaPolicy;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Real WASM coverage for immutable per-instance data and input heap
isolation, with no committed module binary. */
+@Timeout(60)
+class OpaWasmStaticDataIT {
+
+ private static byte[] wasm;
+ private static String data;
+
+ @BeforeAll
+ static void compilePolicy() throws Exception {
+ String module = System.getProperty("camel.opa.staticDataModule");
+ if (module != null) {
+ // Explicit local compiler output also permits running these
checks without Docker.
+ wasm = Files.readAllBytes(Path.of(module));
+ } else {
+ wasm = OpaWasmStaticDataBenchmark.compileModule();
+ }
+ data = OpaWasmStaticDataBenchmark.data(1000);
+ }
+
+ private OpaWasmEvaluator evaluator(String entrypoint, int size) {
+ return new OpaWasmEvaluator(
+ wasm, data, entrypoint, size, 10000,
+ entrypoint, "allow", "*", "", false, false);
+ }
+
+ private static Map<String, Object> input(int user, boolean allow) {
+ return Map.of("subject", "user" + user, "resource", allow ? "document"
+ user : "other",
+ "action", "read", "trap", false);
+ }
+
+ @Test
+ void alternatesAllowDenyAndInputSizesWithoutLeakingState() throws
Exception {
+ try (var evaluator = evaluator("benchmark/allow", 1)) {
+ for (int i = 0; i < 1000; i++) {
+ boolean allow = i % 2 == 0;
+ var input = new HashMap<>(input(i % 1000, allow));
+ input.put("padding", "x".repeat(i % 2 == 0 ? 4096 : 1));
+ assertThat(evaluator.evaluateDecision(input)).as("iteration
%d", i).isEqualTo(allow);
+ }
+ }
+ }
+
+ @Test
+ void preservesStaticDataAcrossConcurrentReuseAndPoolContention() throws
Exception {
+ int threads = 8;
+ var executor = Executors.newFixedThreadPool(threads);
+ var ready = new CountDownLatch(threads);
+ var start = new CountDownLatch(1);
+ try (var evaluator = evaluator("benchmark/allow", 4)) {
+ var tasks = new ArrayList<Future<Void>>();
+ for (int worker = 0; worker < threads; worker++) {
+ int user = worker;
+ tasks.add(executor.submit((Callable<Void>) () -> {
+ ready.countDown();
+ assertThat(start.await(10, TimeUnit.SECONDS)).isTrue();
+ for (int i = 0; i < 200; i++) {
+ boolean allow = i % 2 == 0;
+ assertThat(evaluator.evaluateDecision(input(user,
allow))).isEqualTo(allow);
+ }
+ return null;
+ }));
+ }
+ assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
+ start.countDown();
+ for (var task : tasks) {
+ task.get(30, TimeUnit.SECONDS);
+ }
+ } finally {
+ start.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ void
realRuntimeFailuresAreFollowedByCorrectDecisionsFromPreparedReplacements()
throws Exception {
+ try (var evaluator = evaluator("benchmark/strict", 1)) {
+ for (int i = 0; i < 10; i++) {
+ assertThatThrownBy(() ->
evaluator.evaluateDecision(Map.of("trap", true)))
+ .isInstanceOf(RuntimeException.class);
+ assertThat(evaluator.evaluateDecision(input(i,
true))).isEqualTo(true);
+ assertThat(evaluator.evaluateDecision(input(i,
false))).isEqualTo(false);
+ }
+ }
+ }
+
+ @Test
+ void
requestScopedDataOverrideDoesNotChangeTheFollowingRequestsStaticData() throws
Exception {
+ try (var evaluator = evaluator("benchmark/isolation", 1)) {
+ var overridden = new HashMap<>(input(0, true));
+ overridden.put("resource", "overridden-document");
+ overridden.put("override", Map.of("user0", Map.of("resource",
"overridden-document", "enabled", true)));
+ for (int i = 0; i < 100; i++) {
+
assertThat(evaluator.evaluateDecision(overridden)).isEqualTo(true);
+ assertThat(evaluator.evaluateDecision(input(0,
true))).isEqualTo(true);
+ var noOverride = new HashMap<>(input(0, true));
+ noOverride.put("resource", "overridden-document");
+
assertThat(evaluator.evaluateDecision(noOverride)).isEqualTo(false);
+ }
+ }
+ }
+
+ @Test
+ void discardedRealInstanceIsReplacedAndPreparedWithOriginalData() throws
Exception {
+ var created = new AtomicInteger();
+ try (var pool = new OpaWasmPolicyPool(() -> {
+ created.incrementAndGet();
+ return
OpaPolicy.builder().withPolicy(wasm).build().entrypoint("benchmark/strict").data(data);
+ }, 1, 1000)) {
+ var broken = pool.borrow();
+ try {
+ assertThatThrownBy(() ->
broken.policy().evaluate("{\"trap\":true}"))
+ .isInstanceOf(RuntimeException.class);
+ } finally {
+ // otherwise a failed assertion turns into a borrow timeout
that hides it
+ broken.discard();
+ }
+ try (var replacement = pool.borrow()) {
+ assertThat(replacement.policy()).isNotSameAs(broken.policy());
+ assertThat(replacement.policy()
+
.evaluate("{\"subject\":\"user0\",\"resource\":\"document0\",\"action\":\"read\",\"trap\":false}"))
+ .isEqualTo("[{\"result\":true}]");
+ }
+ assertThat(created.get()).isEqualTo(2);
+ }
+ }
+
+ @Test
+ void
validatesEntrypointAtConstructionAndAcceptsBareModuleWithoutBundledData()
throws Exception {
+ assertThatThrownBy(() -> evaluator("benchmark/missing",
1)).isInstanceOf(IllegalArgumentException.class);
+ try (var evaluator = new OpaWasmEvaluator(
+ wasm, null, "benchmark/strict", 1, 1000,
+ "benchmark/strict", "allow", "*", "", false, false)) {
+ for (int i = 0; i < 100; i++) {
+ assertThat(evaluator.evaluateDecision(input(i,
true))).isEqualTo(false);
+ }
+ }
+ }
+}
diff --git
a/components/camel-opa/src/test/resources/wasm-benchmark/permissions.rego
b/components/camel-opa/src/test/resources/wasm-benchmark/permissions.rego
new file mode 100644
index 000000000000..ef280f8be34f
--- /dev/null
+++ b/components/camel-opa/src/test/resources/wasm-benchmark/permissions.rego
@@ -0,0 +1,40 @@
+#
+# 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 benchmark
+
+default allow := false
+
+allow if {
+ input.action == "read"
+ grant := data.permissions[input.subject]
+ grant.enabled
+ input.resource == grant.resource
+}
+
+# Conflicting complete-rule outputs cause an OPA runtime error for
input.trap=true.
+# This exercises discard/replacement with a real WASM failure, rather than an
undefined decision.
+strict := true if { input.trap == true }
+strict := false if { input.trap == true }
+strict := allow if { not input.trap }
+
+# A request-scoped data override must not mutate the static data retained for
the next evaluation.
+isolation := result if {
+ input.override
+ result := allow with data.permissions as input.override
+}
+isolation := allow if { not input.override }
diff --git a/design/opa-wasm-static-data.adoc b/design/opa-wasm-static-data.adoc
new file mode 100644
index 000000000000..a3ac614607e5
--- /dev/null
+++ b/design/opa-wasm-static-data.adoc
@@ -0,0 +1,65 @@
+---
+title: OPA WASM static data preparation
+authors:
+ - "@oscerd"
+reviewers: []
+approvers: []
+creation-date: 2026-11-11
+last-updated: 2026-11-16
+status: implemented
+see-also: []
+replaces: []
+superseded-by: []
+---
+
+== Decision
+
+CAMEL-26839 prepares the configured entrypoint and immutable data once in each
`OpaWasmEvaluator` pool-instance
+factory. The constructor still borrows an instance to validate initialization
before startup completes. A failed
+evaluation still discards its lease, and every replacement is prepared by the
same factory. Pool capacity,
+borrowing timeouts, decision normalization and `failOpen` behavior are
unchanged.
+
+This deliberately revises the previous comment that every borrow must restore
the configured entrypoint and data.
+The evaluator owns its private pool; borrowers supply input and evaluate, and
never replace its entrypoint or data.
+The SDK's input operation already resets the transient heap. Reapplying the
same data therefore adds parsing work
+without establishing an additional boundary between requests. Tests pin both
ordinary reuse and request-scoped
+data overrides, so future SDK upgrades must preserve this contract or restore
defensive preparation.
+
+== SDK and ABI evidence
+
+The managed SDK is `com.styra.opa:opa-java-wasm:1.1.0`. Inspection of its
installed bytecode with `javap -p -c`
+agrees with the
https://github.com/open-policy-agent/opa-java-wasm/blob/1.1.0/core/src/main/java/com/styra/opa/wasm/OpaPolicy.java[official
1.1.0 source]:
+
+* `entrypoint(String)` exports and parses the entrypoint map to resolve the
numeric entrypoint.
+* `data(String)` frees the previous data value, rewinds to `baseHeapPtr`,
UTF-8 encodes and parses the document,
+ then saves `dataHeapPtr`.
+* `input(String)`, called by `evaluate(String)`, rewinds to `dataHeapPtr`
before loading the next input.
+* `reset()` is package-private and also clears data and entrypoint. Camel's
own pool does not call the SDK pool
+ or its reset operation.
+
+The https://www.openpolicyagent.org/docs/wasm[OPA WASM ABI documentation]
describes the data/input heap boundary.
+The tests use the exact OPA compiler pinned by test-infra, `1.22.2`, and
exercise real compiled WASM, including a
+conflicting complete-rule result that causes a runtime error. There are no
reflection-based SDK modifications,
+shared SDK policy instances, or committed WASM binaries.
+
+== Correctness coverage
+
+`OpaWasmStaticDataIT` compiles the fixture using test-infra by default. It
checks:
+
+* 1000 alternating allow/deny decisions with varying input sizes on a single
reused instance.
+* Eight workers sharing four pooled instances, with per-user inputs and
alternating decisions.
+* Actual WASM runtime failures followed by correct allow/deny decisions from
replacements.
+* Discarding a real failed instance creates a different, initialized instance
with the configured static data.
+* A request-scoped `with data.permissions as ...` override does not change
following requests' static data.
+* Missing entrypoint startup validation and bare-module evaluation without
bundled data.
+
+All six tests also passed using a locally generated module from the pinned
official compiler. This standalone run
+used the explicit `camel.opa.staticDataModule` test override, without Docker.
The default Docker compilation path
+and the regular Maven integration-test lifecycle still require normal project
validation.
+
+== Measurements and reproduction
+
+The smoke measurements that led to this decision (a per-borrow parse of about
1 MiB of data cost about 50 decisions
+per second on one thread, against about 400,000 per second when the data is
prepared once), their raw samples and the
+commands that reproduce them with `OpaWasmStaticDataBenchmark` are recorded in
the pull request of CAMEL-26839. They
+are not JMH results and not capacity targets.
diff --git a/parent/pom.xml b/parent/pom.xml
index 372f6b2e3c94..23f054b70cb1 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -423,6 +423,8 @@
<olingo4-version>5.0.0</olingo4-version>
<onnxruntime-version>1.31.1</onnxruntime-version>
<opa-version>2.1.1</opa-version>
+ <!-- camel-opa prepares each pooled WASM instance once (CAMEL-26839):
after a bump, run its ITs (-Pit, they
+ compile the fixtures with the OPA container) to confirm the SDK
still rewinds to the data boundary -->
<opa-wasm-version>1.1.0</opa-wasm-version>
<openfeature-sdk-version>1.23.0</openfeature-sdk-version>
<openfga-version>0.11.0</openfga-version>