Skip to content
Development preview · 2.0.0-SNAPSHOT

CompileFlow Extension Guide

This guide shows how to add listeners, script languages, and application policies. Implement an extension interface, annotate the class with @ExtensionRealization, and list it in a service file so the engine can discover and construct it. Start with the listener example below, then use the selection and lifecycle rules for other extensions. The examples assume an engine created as shown in Quick Start.

The general extension framework is in compileflow-common, under com.alibaba.compileflow.common.extension. Process SPI contracts remain in compileflow-api, which depends on compileflow-common.

Create src/main/java/com/example/FlowEvents.java with a listener that accepts completed execution events. Higher priority values come first; see Common protocol and ordering for the full selection rules:

package com.example;
import com.alibaba.compileflow.common.extension.ExtensionRealization;
import com.alibaba.compileflow.engine.spi.event.ProcessEvent;
import com.alibaba.compileflow.engine.spi.event.ProcessEventListener;
@ExtensionRealization(priority = 600)
public final class FlowEvents implements ProcessEventListener {
private static final System.Logger LOGGER = System.getLogger(FlowEvents.class.getName());
@Override
public boolean support(ProcessEvent event) {
return event instanceof ProcessEvent.ExecutionCompleted;
}
@Override
public void onEvent(ProcessEvent event) {
LOGGER.log(System.Logger.Level.INFO, "Process event: type={0}", event.getType());
}
}

Create the UTF-8 resource src/main/resources/META-INF/services/com.alibaba.compileflow.common.extension.Extension with:

com.example.FlowEvents

If the file already exists, append this entry and keep the other implementations. Package the class and service file in the application or a dependency JAR, then start the engine. Plain Java and Spring Boot use the same declaration. Execute the Quick Start flow and look for a completed-event log entry beginning with Process event: type=. The engine creates and closes the listener. Events are asynchronous and best-effort by default and may be dropped when the queue is full; use them for monitoring, not as reliable audit records or proof of a business commit.

Create src/main/java/com/example/TransactionConflictPolicy.java. The SPI method returns the policy’s business name:

package com.example;
import com.alibaba.compileflow.common.extension.ExtensionRealization;
import com.alibaba.compileflow.engine.spi.execution.RetryPolicy;
import java.sql.SQLTransactionRollbackException;
@ExtensionRealization(priority = 600)
public final class TransactionConflictPolicy implements RetryPolicy {
@Override
public String name() {
return "transaction-conflict";
}
@Override
public boolean shouldRetryOn(Throwable failure) {
return failure instanceof SQLTransactionRollbackException;
}
}

Add com.example.TransactionConflictPolicy to the same service file and use transaction-conflict in the flow’s retryOn setting. Setting retryOn alone does not increase the number of attempts. Set maxAttempts above 1 in the ProcessEngine Action’s invocation policy; this count includes the initial call. The Action must be safe to retry. For syntax and usage conditions, see the TBBPM invocation policy or BPMN invocation policy.

Custom retry and failure-handler names must be exact lowercase kebab-case identifiers of 1–256 characters. Retry names never, transient, and always, and handler names propagate and continue, are reserved in their respective registries. Unknown names, thrown exceptions, or null failure resolutions fail execution without selecting another implementation.

Protocol Responsibility
Extension<C extends ExtensionContext> initialize(ExtensionResources) receives borrowed collaborators once; support(C) determines applicability and defaults to true
ExtensionResources Immutable exact-type bindings for application-owned collaborators
@ExtensionPoint(code = "...") Declares a unique operation code on an extension interface method
@ExtensionRealization(priority = ...) Declares an implementation class; its only property is priority, defaulting to 500
ExtensionManager Reads service declarations, orders candidates, and constructs, initializes, caches, and closes implementations in one engine
ExtensionInvoker Invokes the first matching implementation or notifies all matches for the current context

Higher priority values take precedence. Fixed single selection requires a unique highest-priority implementation; named selection applies the same rule separately to each business key. A tie at the winning priority fails assembly. Explicit first-match and broadcast traversal use descending priority, then ascending implementation binary name. Declared framework defaults use Integer.MIN_VALUE. Use distinct priorities when one implementation should override another.

An operation code and a business name serve different purposes. For example, RetryPolicy.EXT_CODE identifies the retry decision operation, while RetryPolicy.name() returns the name used by a definition’s retryOn. ScriptExecutor.language() returns a Script Task’s language key. The implementation annotation has no name property.

Candidate declarations and ordering stay fixed for the manager’s lifetime. Context-aware first/all invocations evaluate support(context) each time; they do not cache the first context’s match as a global choice. A null context skips this predicate. Business-name bindings remain the responsibility of the typed SPI consumer.

Extension Consumption Behavior
ProcessDataMapper Select one implementation Convert application objects and process variables
ProcessEventListener Filter each event, then notify all matches in order Best-effort lifecycle telemetry
TraceIdProvider Select one implementation Supply correlation IDs; retain the runtime MDC/random fallback
ProcessContextPropagator Select one implementation Capture, apply, and restore context at engine-owned thread boundaries
ScriptExecutor Select one implementation per language() Validate, compile, and evaluate Script Tasks
ProcessAliasTargetingPolicy Select one implementation per name() Select a target when a route explicitly references the policy
RetryPolicy Select one implementation per name() Classify failures referenced by retryOn
FailureHandler Select one implementation per name() Handle terminal failures referenced by onFailure

Durable reuses scripts and Alias targeting and provides these additional extensions:

Extension Selection When no implementation matches
DurableWaitDescriptionProvider First ordered implementation whose support(context) is true for the Wait Adds no descriptive attributes
DurableOutboxSink First ordered implementation whose support(event) is true for the delivery With no declared sink, this node has no publisher; with declared sinks but no match, delivery fails and follows the Outbox retry policy
DurableTurnEmissionSource Unique highest-priority implementation, without per-Run matching No business data is extracted from process state for publication

A failed applicability check or callback in a Wait description provider or sink does not fall through to the next candidate. Reliable delivery still follows Durable’s transaction, retry, and idempotency contracts.

Wait descriptions read only the supplied context and must not block or perform I/O. The emission source extracts candidate records outside the Store transaction; only an accepted Turn commit publishes them. It must not mutate external business state.

The application explicitly configures ProcessAliasRouteSource, DurableStore, DurableVersionDefinitionSource, and DurableAliasStateSource to provide routing, storage, or definition data; they are not extension candidates. ProcessComponentResolver looks up existing application objects by name and type and does not participate in extension selection.

Every published implementation needs a public no-argument constructor. The implementation creates and manages its own internal helpers. An extension that needs an existing application collaborator overrides initialize(ExtensionResources) and requests its exact declared resource type. For example, an extension can borrow the application’s clock:

import com.alibaba.compileflow.common.extension.ExtensionResources;
import java.time.Clock;
// Members of an existing declared extension:
private Clock clock;
@Override
public void initialize(ExtensionResources resources) {
clock = resources.require(Clock.class);
}

The application binds the collaborator and supplies the immutable bindings to the engine it creates:

import com.alibaba.compileflow.common.extension.ExtensionResources;
import com.alibaba.compileflow.engine.config.ProcessEngineConfig;
import com.alibaba.compileflow.durable.runtime.DurableProcessEngineConfig;
import java.time.Clock;
Clock applicationClock = Clock.systemUTC();
ExtensionResources resources = ExtensionResources.builder()
.bind(Clock.class, applicationClock)
.build();
ProcessEngineConfig ordinary = ProcessEngineConfig.builder()
.extensionResources(resources)
.build();
// store is the application's already configured DurableStore.
DurableProcessEngineConfig durable = DurableProcessEngineConfig.builder(store)
.extensionResources(resources)
.build();

bind(Clock.class, applicationClock) is retrieved only with Clock.class; there is no assignable-type search. find(type) returns an optional value, while require(type) fails initialization when the key is absent. Duplicate keys, nulls, and extension instances are rejected. build() snapshots the bindings and retains the original collaborator objects; later builder changes do not change an existing resource set. The framework does not construct these collaborators, bind constructor arguments, or discover them from a container.

Each engine owns an ExtensionManager. A fixed selection (getExtension) requires a unique highest-priority candidate. An ordered invokeFirst without a context selects the first candidate, including when priorities tie. Both initialize only the selected implementation. Contextual invokeFirst initializes candidates in order until support(context) finds a match. Named lookups, all-candidate lookups and broadcasts initialize matching candidates. Every lookup takes the operation code and the interface declaring it or a type inheriting that interface. The typed callback performs the Java invocation; the code does not dispatch methods reflectively. A class is published once after successful initialization even when it implements several operations. Extensions without borrowed collaborators can use the default no-op initialization. Engine assembly queries the operations it needs, so initialization can run while an engine is being created. A construction or initialization failure rejects that lookup and closes the failed instance if closeable. It neither tries the next candidate nor closes other initialized instances. Failed engine assembly closes the entire manager; a standalone manager is closed by its owner.

Implementations and borrowed collaborators must support concurrent calls and bound their caches, blocking work, and external resources. After accepted work and executor tasks actually exit, the engine closes initialized AutoCloseable extensions in reverse successful initialization order, calling each object’s close() once. Different engines do not share extension instances. The application owns the bound collaborator objects; neither the manager nor the extensions close them. Keep those objects usable until all engines borrowing them have actually finished closing their owned extensions. A timed-out or interrupted engine.close() can leave cleanup running, so the return from that call alone does not authorize closing borrowed objects. See Resource management for shutdown completion and cleanup failures.

An extension’s close() releases its own resources and must not call its owning engine’s close(). Ordinary and Durable engines immediately reject this cleanup callback reentry with IllegalStateException to avoid waiting for the callback itself to finish.

The Starter binds settings and creates and closes the engine. Extensions still come from standard service declarations and are constructed by the framework. @Component, @Bean, @Order, @Primary, and bean names do not provide an extension source. Container mapper, listener, trace-provider, and script-executor objects do not replace framework instances. Do not create a second bean merely to publish an extension.

To supply borrowed collaborators, declare your own ProcessEngineConfig or DurableProcessEngineConfig bean with extensionResources(...); the Starter uses that configuration. For ProcessEngine, start from ProcessEngineProperties.toProcessEngineConfigBuilder() when retaining property-bound settings. For Durable, use DurableProcessEngineConfig.builder(store) and retain the application’s intended engine and admission settings. The configuration bean may receive existing application beans and explicitly bind them as resources. Their ownership and shutdown obligations remain with the application as described above. Service declarations still determine the extension implementation classes.

With Deploy’s embedded topology or Core runtime worker role enabled, use the auto-configured engine and customize its ProcessEngineConfig. Installation, execution admission, and final-owner release must share the same installed-version state; deployment runtime construction rejects a mismatched engine before accepting work. Deployment runtime managers and ownership capabilities are internal integration contracts, not application extension APIs.

For a type="bean" action, the Starter obtains a business object from the engine’s ApplicationContext: bean specifies the bean name, class the required type, and method the method to call. Register the object as an ordinary Spring bean; no additional CompileFlow registration is needed. Ordinary engines and Durable use the same approach.

The Starter closes each engine through Spring’s phased lifecycle before singleton destruction. With Spring Boot graceful Web shutdown enabled, HTTP admission closes before workers drain. The auto-configured workers and Deploy lifecycle components stop before the owning engine drains. This ordering is independent of the application event multicaster, and a child Context’s closure does not close the parent engine.

An explicit ApplicationContext.stop() permanently closes the owned engine; start() cannot recreate it. Use Spring’s pause() and restart() for a reversible Context pause. The engine owner opts out of pausing because engine closure is irreversible. Normal closure, explicit stopping, and failed-startup cleanup share one shutdown owner, which joins the same physical cleanup for each owned engine. Concurrent shutdown callers wait for the same close attempt. This does not change the engine’s explicit repeated-close contract.

During failed refresh, the shutdown owner follows the engine bean’s dependency order, before its declared Spring dependencies, including dependencies of its configuration, are destroyed. Failed refresh does not provide the normal phased-drain guarantee for dynamically borrowed components. The owner waits for active work and physical cleanup before returning; an explicit ProcessEngine.close() caller timeout does not release this ownership barrier. Cleanup failures are logged without preventing later lifecycle owners from attempting their own shutdown. Stop external producers before closing the Context. The host owns parent-context and scoped-object lifetimes, and must not destroy borrowed resources in an earlier close listener or lifecycle phase. Keep borrowed resources available until actual shutdown completion as described in Resource management.

Using the bean returned by the container preserves its dependency injection, scope, and proxy behavior. A missing bean or incompatible type fails the call with a configuration error; the engine does not instantiate the declared class as a substitute. Framework extensions continue to use the declaration and discovery mechanism above.

A plain Java host can pass ProcessComponentResolver to ProcessEngineFactory.create(config, components) when a flow must call an existing object. Use type="bean" with its bean name and required class; this action uses the supplied lookup without requiring Spring. The resolver must return the original object, perform the required-type check, and support concurrent lookup. The host owns both the resolver and returned objects and keeps them usable until engine execution stops. They are not extension implementations and are not listed in the Common extension service file. The factory does not discover or close them.

For per-invocation construction, a plain Java application uses type="class" with a public business class, public no-argument constructor, and public method identified by class and method. The adapter calls new DeclaredClass().method(...), creating a business instance for each invocation. If the target method is static, this generated expression still constructs the class first. Use a bean action for an object that receives its dependencies from the host. See the complete standalone example.

ProcessContextPropagator captures context on the submitting thread, applies it on engine-owned timeout-action, parallel-execution, and event-delivery threads, then restores the worker’s previous context. Capture or binding failure fails an affected action or parallel branch; for best-effort events it drops the event. Durable does not persist or restore this context.

Publish a declared no-argument implementation when an application needs propagation, using the relevant context library inside that implementation. The Starter neither finds propagator beans nor creates a Micrometer extension adapter.

To use an existing SPI, declare an implementation. To define a new operation for a framework or library, extend Extension<C> and annotate the interface method with a unique operation code; the manager needs no modification. This example calculates a VIP quote and can run independently with only the compileflow-common dependency. Put each Java file below in src/main/java/com/example/.

QuoteContext.java defines the data for one invocation:

package com.example;
import com.alibaba.compileflow.common.extension.ExtensionContext;
public record QuoteContext(String tier, int originalCents) implements ExtensionContext {}

DiscountPolicy.java declares the operation:

package com.example;
import com.alibaba.compileflow.common.extension.Extension;
import com.alibaba.compileflow.common.extension.ExtensionPoint;
public interface DiscountPolicy extends Extension<QuoteContext> {
String EXT_CODE = "example.quote.discount";
/** Computes the discounted quote amount in cents. */
@ExtensionPoint(code = EXT_CODE)
int apply(QuoteContext context);
}

VipDiscount.java implements the operation for VIP contexts. The intermediate product uses long so a valid int amount does not overflow before division. Integer division truncates fractional cents; choose the rounding rule required by your application:

package com.example;
import com.alibaba.compileflow.common.extension.ExtensionRealization;
@ExtensionRealization(priority = 600)
public final class VipDiscount implements DiscountPolicy {
@Override
public boolean support(QuoteContext context) {
return "vip".equals(context.tier());
}
@Override
public int apply(QuoteContext context) {
return Math.toIntExact(context.originalCents() * 9L / 10);
}
}

Declare the implementation in src/main/resources/META-INF/services/com.alibaba.compileflow.common.extension.Extension. For this standalone example, the file contains one line:

com.example.VipDiscount

If you use the same project as the listener example, retain that listener’s entry as well. DiscountExample.java creates a manager and calls the operation:

package com.example;
import com.alibaba.compileflow.common.extension.ExtensionInvoker;
import com.alibaba.compileflow.common.extension.ExtensionManager;
public final class DiscountExample {
private static final System.Logger LOGGER = System.getLogger(DiscountExample.class.getName());
public static void main(String[] args) {
try (ExtensionManager manager = new ExtensionManager(VipDiscount.class.getClassLoader())) {
ExtensionInvoker invoker = new ExtensionInvoker(manager);
QuoteContext context = new QuoteContext("vip", 1_500);
int total = invoker.invokeFirst(
context, DiscountPolicy.EXT_CODE, DiscountPolicy.class, extension -> extension.apply(context));
LOGGER.log(System.Logger.Level.INFO, "Discounted total: " + total);
}
}
}

Run DiscountExample.main and check for Discounted total: 1350 in the log. A long-running framework or library should reuse one manager and close it after all extension calls finish; the example uses try-with-resources for its short-lived execution.

The explicit DiscountPolicy.class selects only implementations of that interface, including when an operation is inherited from a parent interface. The compiler also checks that the context and callback match the interface.

invokeFirst selects and calls the first typed implementation that supports the current context. No match raises ExtensionException. A failure in support or the callback propagates; it does not try another implementation.

invokeAll notifies observers in order, checking support immediately before each callback. It logs ordinary exceptions from either support or the callback and continues with the remaining observers. Errors propagate, and the returned list contains only non-null results. Candidate construction and initialization happen before this callback loop; a failure there rejects the lookup rather than being isolated as an observer failure. Business operations, transactions, and reliable delivery follow the failure-handling contract of their respective extension points.

Retry policies and failure handlers run synchronously with trusted application code. They must be thread-safe, deterministic, non-blocking, and return valid results. Before invoking an Action, CompileFlow resolves every policy and handler that its invocation policy might use. An unknown name therefore fails before application side effects. A RuntimeException from a policy or handler, or a null failure-handler result, is reported as CF_CONFIG_003. An Error propagates.

Do not use a failure handler for reliable external delivery. Use ProcessEventListener for best-effort telemetry, or Durable Outbox when delivery must be reliable.

Core includes a Java script executor. It runs with the host JVM’s permissions and requires trusted definitions; it is not sandboxed. QLExpress 4 is supplied by the optional compileflow-script-qlexpress module. Adding that dependency makes QlExpressScriptExecutor available through the JAR’s standard service declaration; no bean or registration call is needed. See Quick Start. This executor cannot call host-object methods.

The optional compileflow-script-mvel module supplies the mvel executor for property and method access on mapped inputs. Runtime preparation (including strict() preflight’s runtime check) checks its expression grammar and input names; MVEL’s own compilation is deferred to evaluation, so a script that passes preflight can still fail compilation at execution time. It borrows input objects rather than applying QLExpress’s snapshot isolation and has no built-in timeout. QLExpress’s one-second evaluation timeout is cooperative, not a hard interruption, and starts after the input snapshot is made. See the MVEL module guide.

Declare language implementations with @ExtensionRealization and list them in the standard service file. For each language(), the unique highest-priority implementation wins; a tie fails assembly. Executor beans in a Spring container do not participate. Use distinct keys when definitions in one engine need different language semantics. The QL executor holds only heap state and needs no close operation. Stateful executors must bound their caches and use the intended class loader; their resources follow the ownership rules above.

ScriptExecutor.language() returns a lowercase kebab-case key of 1–256 characters. Core uses it exactly as supplied. The key identifies the script language, independently of which executor implements it. For example:

@Override
public String language() {
return "custom-script";
}

Implement the following methods as well; see ScriptExecutor for complete signatures:

Method Implementation requirement
validate(spec) Check syntax and the provider’s compile-time constraints without executing the script or observing application or external state
compile(spec) Prepare a node-local script program; do not persist it or make recovery depend on it
evaluate(ScriptProgram program, Map<String, ?> context) Read supplied variables and their referenced objects without mutating them, and return the result for output mapping; support concurrent calls

Provider implementations and script authors must both respect the read-only input contract; the SPI does not guarantee a deep copy. The Java and MVEL script executors borrow declared inputs by reference. Return changes to Process state through the declared output mapping.

Successful validation does not guarantee successful evaluation. The provider must enforce access restrictions that depend on runtime values in evaluate(...).

ScriptProgramSpec.language() and the returned ScriptProgram.language() must use the same key. Script Tasks reference this key: TBBPM uses <action type="script" language="language-name"> inside scriptTask, and BPMN uses <scriptTask scriptFormat="language-name">. A script reconcileAction in an Effect recovery policy uses the same language key and executor contract. Unknown languages fail during Java source generation or runtime preparation (including the runtime check in strict() preflight). A fast() preflight checks process semantics, not the registered script providers; use strict() to check that this engine can prepare the definition.

For Durable execution, TBBPM declares execution=replayable|effect on the nested Action; BPMN declares cf:execution="replayable|effect" on scriptTask. The script executor remains responsible for its own resources and security restrictions; the Kernel does not persist script programs. Gateway and loop conditions, transition expressions, Timer expressions, and Wait deadline expressions use Java expression semantics rather than ScriptExecutor. Durable imposes additional restrictions on control and scheduling expressions. Generated runtime code escapes Script Action source and variable names as Java literals.

Compiler, parser, graph-analysis, and format-dispatch classes are internal. See Supported Surfaces for the public interfaces. ProcessEngineProvider connects matching API and Core versions during bootstrap and is not an extension SPI. Core supplies the sole bootstrap provider; missing or multiple providers fail engine construction. Semantic frontends are discovered separately. Without Deploy, declare a ProcessEngine bean to replace the entire engine in Spring; auto-configuration leaves its creation to you. A custom engine can still inject ProcessEngineConfig to reuse default property binding. The Deploy data plane follows the shared installation-state requirements above. Engine assembly creates the extension manager, whose discovered candidates stay fixed for that engine’s lifetime. Creating a configuration does not discover or instantiate extensions. The same rule applies to DurableProcessEngineConfig.

By default, the engine reads its local routing state. To supply a custom source, configure one ProcessAliasRouteSource through aliasRouteSource(...) or a Spring bean. It must return complete, immutable routes ready for local execution. The engine uses that source without merging routes or falling back to the local source. Return an empty result for an unavailable (including retired) Alias. Source failures reject admission. A source that performs I/O must bound its deadlines and preserve interruption; its lifecycle belongs to the application.

Declare a ProcessAliasTargetingPolicy with @ExtensionRealization and return a stable lowercase kebab-case name from name(). The engine evaluates it when the route has a candidate and names the policy through AliasTargeting. It receives the route’s stable and candidate versions, immutable route parameters, the effective routing key, and immutable string attributes from ProcessExecutionOptions. It does not receive the candidate weight or unrelated process variables. Without an explicit routing key (null or empty), ProcessEngine uses the invocation ID; Durable admission uses the Run ID. The policy returns STABLE, CANDIDATE, or an empty result to use the default deterministic selector based on the routing key and configured weights. There is no public SPI for replacing that selector.

AliasTargeting holds configuration for the route, not attributes of an individual request. Its policy name is limited to 256 characters and must match [a-z][a-z0-9]*(?:-[a-z0-9]+)*. The parameter map accepts at most 32 entries; names and values are limited to 128 and 2,048 Unicode code points respectively, and their combined UTF-8 size must not exceed 32 KiB. Names must be nonblank, without surrounding whitespace, control or Unicode format characters. Values may be empty but not null and must be valid Unicode without U+0000. Supply a stable map during construction; the resulting configuration is immutable. Deploy can persist and distribute these parameter names and values as part of the route, so do not use them to carry credentials or personal data.

Normally, the engine reads the route source once. A CF_EXEC_012 failure while acquiring the root runtime or binding its child runtimes can cause another read to check for a route change. If the route has changed, the engine retries selection and full graph acquisition once, before executing any process Action. The root and its child runtimes share this retry budget. Fixed selections do not reroute. After successful binding, the invocation keeps its selected call graph. A node cannot activate a route if its named policy is unavailable. If an explicitly supplied route source returns such a route anyway, selection fails; Durable admission also fails when a referenced policy is missing. If the selected policy throws a RuntimeException or LinkageError, or returns null instead of an Optional, the engine selects stable and records TARGETING_ERROR; it does not use the default selector. Other Error types propagate.

Policies must produce the same result for the same inputs, support concurrent calls, and finish within a bounded time. They must not perform blocking remote I/O. Routing keys and attributes select the route and never become process variables. Their raw values may contain sensitive data and must not be logged or persisted. Workbench Server includes these inputs in the SHA-256 request fingerprint persisted for async invocation idempotency.

package com.example;
import com.alibaba.compileflow.engine.ProcessAliasTarget;
import com.alibaba.compileflow.common.extension.ExtensionRealization;
import com.alibaba.compileflow.engine.spi.routing.ProcessAliasTargetingContext;
import com.alibaba.compileflow.engine.spi.routing.ProcessAliasTargetingPolicy;
import java.util.Optional;
@ExtensionRealization(priority = 600)
public final class TierTargetingPolicy implements ProcessAliasTargetingPolicy {
@Override
public String name() {
return "tier-targeting";
}
@Override
public Optional<ProcessAliasTarget> target(ProcessAliasTargetingContext context) {
return "vip".equals(context.getAttributes().get("tier"))
? Optional.of(ProcessAliasTarget.CANDIDATE)
: Optional.empty();
}
}

Save this class as src/main/java/com/example/TierTargetingPolicy.java and add com.example.TierTargetingPolicy to the service file. It returns CANDIDATE for tier=vip and an empty result otherwise. In a real application, derive the tier on a trusted backend from the authenticated customer’s data; an unverified client attribute is not proof of membership or authorization. To use it:

  • Pass the Alias through ProcessRef.Alias, and the routing key and policy attributes through immutable ProcessExecutionOptions. A policy sees only its immutable context, not unrelated business variables.
  • When building CreateRolloutCommand.canary(...), call .targeting(new AliasTargeting("tier-targeting")) before build(). Import AliasTargeting from com.alibaba.compileflow.engine.spi.routing. See Hot deployment for the full release sequence. Declaring an implementation alone does not activate it; a route naming an unavailable policy cannot become locally ready.
  • Keep the decision fast and free of side effects. An empty result delegates to the protocol’s default deterministic selector; custom policies cannot replace that algorithm.

The listener example gives the service file’s location and content. All extensions in an implementation module share that file, with one implementation binary name per line.

An implementation must be a public concrete class annotated with @ExtensionRealization, with a public no-argument constructor. A nested implementation must also be static. Its extension interfaces extend Extension<C> and declare operations with method-level @ExtensionPoint annotations. List an implementation once even when it supports several extension interfaces; the framework follows its interfaces and superclasses to find all supported operations. Use the binary name containing $ for a nested class. Blank lines and # comments are supported, and duplicate declarations do not create duplicate instances.

Package the classes and service file in a normal JAR, then add that JAR to the application. Neither extension authors nor consumers need an annotation processor or build plugin. A process SPI implementation normally depends on compileflow-api, which brings in compileflow-common. A library using only the general extension framework can depend directly on compileflow-common.

Each manager reads standard service declarations through its engine’s ClassLoader and discovers types without creating objects. The manager constructs an implementation on its first lookup. Operation codes come from interface-method annotations, so there is no interface catalog, fixed SPI list, or package scan. Invalid declarations, conflicting operation codes, and implementations that do not meet the constructor requirements raise ExtensionException; engine assembly reports these as CF_CONFIG_001. Update the service file when removing or renaming an implementation.

Normal JAR packaging includes the service file from src/main/resources. When creating an uber JAR, merge all resources named META-INF/services/com.alibaba.compileflow.common.extension.Extension and preserve the entries from every dependency.

Before delivering an immutable lifecycle event, the engine calls ProcessEventListener.support(ProcessEvent). Return false to skip onEvent(ProcessEvent). A RuntimeException from either method is logged and isolated. Event dispatch does not catch Errors; they interrupt delivery and can propagate to the caller during synchronous execution. The event types are:

Event type Payload highlights
ExecutionStarted process code and invocation ID
ExecutionCompleted / ExecutionFailed execution details (ProcessExecution), operational attribution (ExecutionAttribution), duration, and typed ProcessError on failure
TriggerStarted process code, invocation ID, and typed ProcessTrigger
TriggerCompleted / TriggerFailed execution details (ProcessExecution), operational attribution (ExecutionAttribution), trigger, duration, and typed error on failure

ProcessObservabilityConfig.eventsAsync defaults to true. Events run on an engine-owned executor, which closes with the engine. The trace ID is captured on the publishing thread before asynchronous dispatch. Filter cheaply with event.getType(), then use the event subtype to access its fields. Events contain no routing keys, variables, source content, arbitrary metadata, or raw exceptions.

Asynchronous delivery is best-effort. Different events may overlap or arrive out of order. If the executor is full, the rejected event is dropped; listeners do not run on the process caller’s thread as a fallback. Listeners for one event still run in a deterministic order.

Package Contents
engine Engine entry points and shared value types
engine.config Immutable engine settings
common.extension General Extension, contexts, method declarations, Manager, Invoker, and ExtensionException
engine.spi ProcessComponentResolver: look up business objects by name and type
engine.spi.event ProcessEvent, ProcessEventListener
engine.spi.execution RetryPolicy, FailureHandler, ProcessContextPropagator, and execution context values
engine.spi.script ScriptExecutor
engine.spi.observability TraceIdProvider
engine.spi.routing Alias route sources, route-bound targeting configuration, and named targeting policies

Add or change extension JARs before application startup, then restart to use them. The engine does not install, replace, or unload extension implementations at runtime. Flow definitions, in contrast, can be hot-deployed through compileflow-deploy. See Supported Surfaces for the supported extension interfaces.

Each engine constructs and closes its extension instances. The application or its container manages business objects called by flows; stop the engines using those objects before closing the business resources.