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:

image

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:

    processDefinition.eventSubProcess("compensation-subprocess")
        .name("Compensation subprocess")
        // Start the subprocess.
        .startEvent("compensation-start-event")
        .error("java.lang.Exception")
        .intermediateThrowEvent("throw-event")
        .name("Compensation throw event")
        .compensateEventDefinition()
        .compensateEventDefinitionDone()
        .serviceTask("compensation-task")
        .name("Compensation Service Task")
        .camundaClass(SleepingCompensationTask.class)
        // End the subprocess.
        .endEvent("compensation-end-event");

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

            …
            .name("Compensation throw event")
            .compensateEventDefinition()
            .activityRef("first-task-id")
            .compensateEventDefinitionDone()
            …

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'

at
org.camunda.bpm.model.bpmn.builder.AbstractCompensateEventDefinitionBuilder.activityRef(AbstractCompensateEventDefinitionBuilder.java:46)
/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">
  <incoming>sequenceFlow_58ac1b9f-eafe-4c2e-963f-c284b27d82ab</incoming>
  <outgoing>sequenceFlow_a1bde82f-be4b-4aed-9226-59d0e922911f</outgoing>
  <compensateEventDefinition id="compensateEventDefinition_16939bdc-50b6-467e-b0e8-f69d1e6e7743" activityRef="first-task-id" />
</intermediateThrowEvent>

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.