Skip to content
Development preview · 2.0.0-SNAPSHOT

Advanced Engine Usage

This guide shows how to prepare flows before their first request, inspect generated source, supply a class loader, map typed inputs and outputs, and execute versions or Aliases. For publishing flows and changing traffic, see Hot deployment.

The examples assume an engine created and reused as shown in Quick Start. Unless stated otherwise, the host supplies engine, definitions, variables, and application components. Replace example process codes and resource paths with your own.

The first execution must prepare a runtime if it is not already cached. Depending on the selected backend, this can include parsing, code generation, and compilation. Check and warm critical definitions during startup to reduce the first request’s preparation time. This listener runs on ApplicationReadyEvent; if warmup must finish before business requests arrive, let the host admit traffic only after warmup completes:

import com.alibaba.compileflow.engine.ProcessDefinition;
import com.alibaba.compileflow.engine.ProcessEngine;
import com.alibaba.compileflow.engine.ProcessModelType;
import com.alibaba.compileflow.engine.preflight.ProcessPreflightOptions;
import com.alibaba.compileflow.engine.preflight.ProcessPreflightReport;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public final class FlowWarmup {
private final ProcessEngine engine;
public FlowWarmup(ProcessEngine engine) {
this.engine = engine;
}
@EventListener(ApplicationReadyEvent.class)
public void warm() {
ProcessDefinition definition =
ProcessDefinition.classpath(ProcessModelType.TBBPM, "order.process", "flows/order.bpm");
ProcessPreflightReport report = engine.tooling()
.preflight(definition, ProcessPreflightOptions.fast());
if (report.getOverallStatus() != ProcessPreflightReport.OverallStatus.PASS) {
throw new IllegalStateException(
"Flow preflight failed: "
+ report.getItems().stream()
.filter(item -> item.getStatus()
!= ProcessPreflightReport.ItemStatus.PASS)
.map(item -> item.getType() + "/" + item.getStatus())
.toList());
}
engine.runtime().warmUp(definition);
}
}

The example checks the definition with fast(), then uses warmUp to prepare and cache the runtime. Neither operation executes process Actions. The exception reports only stage names and statuses; inspect detailed diagnostics in a trusted environment because they may contain definition content.

Choose the operation according to what you need:

Operation Use it to Effect on local runtimes
preflight(..., fast()) Check the definition’s semantics Does not prepare a runtime
preflight(..., strict()) Check preparation for the selected COMPILED or INTERPRETED backend Reuses an exact cached runtime if available; otherwise prepares one for the check without installing or retaining it
runtime().warmUp(definition) Reduce preparation during the first execution Caches the prepared runtime for the supplied definition in this engine without binding a process code or Version

strict() enables LINT and RUNTIME_CHECK. For semantic validation alone, use fast() or set runtimeCheckEnabled(false) on the builder. Preflight and warmup handle only the supplied definitions; they do not recursively check or prepare referenced child processes. Warmup affects only this engine: it does not publish a definition, change an Alias, or warm up other application instances.

The preflight timeout defaults to one minute and covers the whole operation, not each stage separately. Use ProcessPreflightOptions.builder().timeout(duration) to change it; the duration must be positive and a whole number of milliseconds. At least one check must remain enabled. In strict mode, a failed lint check does not by itself suppress the runtime check, so inspect both stage results.

A preflight timeout returns a failed report whose current check stage has TIMEOUT status and requests cancellation of the background check. It does not guarantee that an uninterruptible preparation operation has already stopped. Errors thrown by a check (such as an AssertionError) propagate rather than becoming a failed report. If the calling thread is interrupted, preflight requests cancellation, preserves the interrupt flag, and throws instead of returning a normal report. If the preflight executor rejects the submission, the call throws rather than returning a report.

Direct ProcessDefinition execution reads the source bytes on each call before looking for an exact cached runtime. Warm-up can avoid repeated preparation, but it does not avoid that read. To use an already loaded version on each request, call load during application startup:

engine.runtime().load(
ProcessRef.version("default", "order.process", "2026-07-25.1"),
ProcessDefinition.inline(ProcessModelType.TBBPM, "order.process", xml));

load binds the Version to its runtime in the current engine. The manager returned by runtime() retains a reference to that runtime. Calls through ProcessRef.Version use that binding without reading the source again on each request. unload releases the reference. load prepares only the supplied definition; make referenced child Versions available separately. Before running Actions, execution checks the complete call graph.

The engine has no permanent version registry. Your application must ensure that a Version keeps the same content after unload or restart. Local Version management does not require Deploy. If you need publication and routing, let DeploymentRuntime manage installation and runtime references.

ProcessTooling generates the Java source for an explicit definition without executing it:

ProcessDefinition definition =
ProcessDefinition.classpath(ProcessModelType.TBBPM, "order.process", "flows/order.bpm");
String javaSource = engine.tooling().generateJavaCode(definition);

Generated source may expose business rules and action calls. Treat it as sensitive diagnostic output. Parser AST classes remain implementation details.

The engine uses its configured class loader to discover format modules and extensions, and as the parent of generated flow classes. An application-supplied applicationLoader must be able to load action classes, required modules, and extension implementations, and read their service declarations:

ProcessEngineConfig config = ProcessEngineConfig.builder()
.classLoader(applicationLoader)
.build();
try (ProcessEngine engine = ProcessEngineFactory.create(config)) {
engine.execute(definition, variables).orElseThrow();
}

The engine uses ProcessRuntimeIdentity to distinguish prepared runtimes. The class loader is part of that identity, so keep its effective classpath unchanged after creating the engine. An externally supplied loader belongs to the application. Keep it available until engine cleanup finishes. If close() times out or is interrupted, a later successful close() confirms that cleanup has completed. See Resource management.

For typed execution, ProcessDataMapper converts the request to process variables and maps output to the requested type. For the Spring Boot addition example in Quick Start, declare these public records inside your application class:

public record AddInput(Integer value) {}
public record AddOutput(Integer result) {}

With the default mapper, the request’s Jackson property names match process variable names. Reuse the engine from Quick Start, with the QLExpress module on the classpath:

ProcessDefinition definition = ProcessDefinition.classpath(
ProcessModelType.TBBPM, "bpm.sample.hello", "flows/hello.bpm");
ProcessResult<AddOutput> result = engine.execute(
definition,
new AddInput(40),
AddOutput.class,
ProcessExecutionOptions.defaults());
org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger("compileflow.example.typed");
logger.info("Typed process completed: result={}", result.orElseThrow().result());

The log should contain Typed process completed: result=42. The input supplies only the param variable value; the flow’s result maps to AddOutput.result. A custom mapper can change object mapping, but cannot bypass the definition’s variable and type checks.

The default mapper uses Jackson metadata to discover and bind the request’s top-level properties. Property naming, visibility, @JsonProperty, @JsonIgnore, @JsonIgnoreProperties, and @JsonIncludeProperties determine the variable keys. READ_ONLY properties are readable input; WRITE_ONLY properties are omitted. Each member remains a Java value: nested application objects, collections, enums, arrays, and Maps are not recursively serialized. Explicit null remains a present key, including when @JsonInclude would omit it in JSON. Serializer-only rules, including @JsonIgnoreType on a member’s type, do not filter these Java member values.

Use an application bean/record or a string-keyed Map as the request. Map keys must be unique under String.equals, even when the supplied Map uses reference identity to distinguish keys. The default mapper rejects duplicate string keys rather than silently overwriting a value. Wrap a scalar, collection, array, reference, enum, or JDK value object in such a request. Input mapping does not run JSON serializers or apply value-based JSON inclusion. Effective @JsonValue and @JsonAnyGetter mappings on the request object are rejected because they replace or expand the variable keys. @JsonUnwrapped is rejected on properties that participate in variable binding; excluded properties do not participate in that check. A Map.class output request returns the variable map directly, without calling even a custom mapper for output conversion. For other output types, the default mapper uses Jackson conversion to rebuild the requested DTO, including nested values; object identity is not guaranteed.

Ordinary input conversion failures (RuntimeException) return CF_EXEC_010 before process execution starts. Ordinary output conversion failures return CF_EXEC_009 after execution has returned normally (at an End or Wait entry). They do not roll back action side effects. An Error that escapes a mapper propagates to the caller; the default input mapper preserves Errors thrown by getters.

To replace the mapper, implement ProcessDataMapper, annotate it with @ExtensionRealization, and list the implementation class in the standard Extension service file. Use a public no-argument constructor. Higher priorities take precedence; the default mapper uses Integer.MIN_VALUE. The framework constructs the mapper; Spring mapper beans do not participate. The implementation must return the same result or error for the same input and support concurrent calls. See Extension Guide for the complete setup.

ProcessResult<Map<String, Object>> result =
engine.execute(definition, variables);
if (result.isFailure()) {
ProcessError error = result.getError();
logger.warn(
"Process failed: invocationId={}, errorCode={}",
result.getExecution().getInvocationId(),
error.getCode());
return;
}
Map<String, Object> output = result.getOutput();

Use the stable error code for branching. Do not parse the human message, and do not log raw variables, source content, routing keys, or arbitrary error context.

map, orElse, orElseGet, and orElseThrow operate on the immutable result; they do not retry or change the original process execution. map also calls its mapper for a successful null output; an exception thrown by that mapper propagates to the caller.

An exact Version must be installed on this node before execution. Use runtime().load(...) for local definitions or acquire a runtime lease for a published version through Deploy. Alias execution also requires a locally ready route.

ProcessRef.Version exact =
ProcessRef.version("default", "order.process", "2026-07-25.1");
ProcessRef.Alias production =
ProcessRef.alias("default", "order.process", "production");
ProcessExecutionOptions options = ProcessExecutionOptions.builder()
.aliasRouting(new AliasRoutingOptions(customerId))
.build();
ProcessResult<OrderResponse> result = engine.execute(
production,
request,
OrderResponse.class,
options);

To execute the specific version, call engine.execute(exact, request, OrderResponse.class, ProcessExecutionOptions.defaults()). The version must already be installed on the node. Do not pass Alias-only routing options to an exact Version; the engine rejects the call. For an Alias, the engine chooses between the stable and candidate versions in the locally ready route. If root or child runtime acquisition fails with CF_EXEC_012, the engine checks whether the route has changed; only then may it repeat selection and acquisition of the complete call graph once, before any process Action runs. An unchanged route or another acquisition failure does not trigger an additional retry. It never guesses a fallback version. An exact Version or previously fixed selection is not rerouted. A retired Alias rejects new admissions once the local route has converged; an exact installed Version can still be invoked independently of that Alias.

Process extension interfaces live in compileflow-api; the shared extension framework lives in compileflow-common:

  • @ExtensionRealization and standard service declarations for implementation discovery;
  • ProcessEventListener for events;
  • ScriptExecutor for script languages;
  • RetryPolicy and FailureHandler for named action retry and final failure policies;
  • named ProcessAliasTargetingPolicy values for route-bound targeting rules.

Annotate implementation classes with @ExtensionRealization and list their names, one per line, in META-INF/services/com.alibaba.compileflow.common.extension.Extension. Each engine creates and manages its own instances. Higher priority values come first. Fixed single and named selection reject ties at the highest priority; ordered traversal breaks ties by binary class name. See the Extension Guide for service files, context matching, and shutdown behavior.

See Extension Guide, API Reference, and Configuration.