Error invoking compensation through Java-built subprocess

I am trying to write some compensation tests in Java to invoke specific compensations in my workflow. I am building up the workflow using the builders. This is the workflow:


The 4th Task throws an exception. I’m trying to get only the compensation for the first task to be run (well, ultimately I want to be in control of running them in any order, but for argument’s sake, just the first task will do).

If I define the event subprocess like this, it runs the compensations for 3 → 2 → 1 and then Compensation Service Task, as it should:

        .name("Compensation subprocess")
        // Start the subprocess.
        .name("Compensation throw event")
        .name("Compensation Service Task")
        // End the subprocess.

But if I try to add a reference to the compensation for activity 1 like this:

            .name("Compensation throw event")

I get an exception from Camunda:

org.camunda.bpm.model.bpmn.BpmnModelException: Activity with id 'first-task-id' must be in the same scope as 'throw-event'

/my code/

But if I call Bpmn.writeModelToFile() to save out the Java BPMN, load it up in the Camunda Modeler, edit the throw-event ’s Activity Ref to point to the first task, save, load it back in with Bpmn.readModelFromFile() and run it, it works as expected and calls only the first compensation task ( Rollback 1st ) and then Compensation Service Task.

XML it generates for the throw event:

<intermediateThrowEvent id="throw-event" name="Compensation throw event">
  <compensateEventDefinition id="compensateEventDefinition_16939bdc-50b6-467e-b0e8-f69d1e6e7743" activityRef="first-task-id" />

How do I replicate this behavior in Java using the builders?

This feels a bit similar to this forum post How to recursively trigger compensation from an event subprocess? but I am attempting to do this in Java. The modeler output seems to work fine.