This is an automated email from the ASF dual-hosted git repository.
cschneider pushed a commit to branch SLING-13396-batch-install
in repository
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-distribution-journal.git
The following commit(s) were added to refs/heads/SLING-13396-batch-install by
this push:
new ff69289 fix: SLING-13396 - Bound subscriber batches by payload size
ff69289 is described below
commit ff69289c775a154586d943c6b8e43ab3e3b03288
Author: Christian Schneider <[email protected]>
AuthorDate: Wed Nov 25 15:45:47 2026 +0100
fix: SLING-13396 - Bound subscriber batches by payload size
Co-authored-by: Copilot App <[email protected]>
---
docs/documentation.md | 4 +
.../impl/subscriber/DistributionSubscriber.java | 37 +++++
.../impl/subscriber/SubscriberConfiguration.java | 8 +
.../impl/subscriber/SubscriberBatchTest.java | 164 +++++++++++++++++++++
4 files changed, 213 insertions(+)
diff --git a/docs/documentation.md b/docs/documentation.md
index ac42cfa..71ac0f7 100644
--- a/docs/documentation.md
+++ b/docs/documentation.md
@@ -170,6 +170,10 @@ A package builder can implement
`org.apache.sling.distribution.journal.spi.Batch
`packageHandling` controls what happens to FileVault content packages (`.zip`
under `/etc/packages`) contained in imported content: `Off` (default) only
stores them, `Extract` unpacks their content into the repository, `Install`
fully installs them including sub-packages and install hooks. Batching requires
`Off`, because extracting or installing runs in the importer session and any
package error would fail the whole batch.
+`maxBatchByteSize` optionally limits the total serialized payload bytes in an
import batch. Its default, `-1`, leaves the byte size unlimited; any negative
value disables this limit. The subscriber uses the inline payload length when
present, otherwise the package length recorded by the publisher, so blob-backed
packages can be budgeted before downloading them. A package that would exceed
the budget starts a new batch. Oversized packages and packages whose size is
unknown are imported in [...]
+
+This is an aggregate batch-payload budget, not a total heap limit: queued
inline messages, allocation overhead, and memory used by package builders are
additional. An individually imported package can exceed the budget, and
blob-backed sizing relies on the publisher's recorded length.
+
With batching enabled:
* The poller thread hands packages to a separate importer thread through a
queue of `maxBatchSize` entries, so the poller reads at most `maxBatchSize`
packages ahead.
diff --git
a/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/DistributionSubscriber.java
b/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/DistributionSubscriber.java
index acb3f97..2b3753e 100644
---
a/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/DistributionSubscriber.java
+++
b/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/DistributionSubscriber.java
@@ -156,6 +156,8 @@ public class DistributionSubscriber {
private int maxBatchSize = 1;
+ private final long maxBatchByteSize;
+
// Only used when batching is enabled: packages read by the poller,
waiting for the batch importer
private BlockingQueue<QueuedPackage> pendingPackages;
@@ -176,6 +178,7 @@ public class DistributionSubscriber {
Map<String, Object> properties) {
String subSlingId = requireNonNull(slingSettings.getSlingId());
subAgentName = requireNotBlank(config.name());
+ maxBatchByteSize = config.maxBatchByteSize();
this.precondition = requireNonNull(precondition);
this.subscriberMetrics =
new SubscriberMetrics(metricsService, subAgentName,
getFirst(config.agentNames()), config.editable());
@@ -428,6 +431,7 @@ public class DistributionSubscriber {
private void runBatchImporter() {
List<QueuedPackage> batch = new ArrayList<>(maxBatchSize);
int importCount = 0;
+ long batchBytes = 0;
QueuedPackage current = null;
while (running) {
try {
@@ -439,11 +443,40 @@ public class DistributionSubscriber {
// Import collected packages when the queue is empty,
even if the batch is not full.
flushBatch(batch);
importCount = 0;
+ batchBytes = 0;
continue;
}
}
switch (classifyForBatch(current)) {
case COLLECT:
+ if (!current.skip && maxBatchByteSize >= 0) {
+ byte[] inlinePayload =
current.message.getPkgBinary();
+ long packageBytes =
+ inlinePayload != null ?
inlinePayload.length : current.message.getPkgLength();
+ if (inlinePayload == null
+ && current.message.getPkgBinaryRef() !=
null
+ && packageBytes == 0) {
+ packageBytes = -1;
+ }
+ if (packageBytes < 0 || packageBytes >
maxBatchByteSize) {
+ flushBatch(batch);
+ importCount = 0;
+ batchBytes = 0;
+ LOG.debug(
+ "Importing package at offset={}
individually: payload size={} bytes, batch limit={} bytes",
+ current.info.getOffset(),
+ packageBytes,
+ maxBatchByteSize);
+ handlePackageMessage(current);
+ break;
+ }
+ if (packageBytes > maxBatchByteSize - batchBytes) {
+ flushBatch(batch);
+ importCount = 0;
+ batchBytes = 0;
+ }
+ batchBytes += packageBytes;
+ }
if (current.skip && !batch.isEmpty() &&
batch.get(batch.size() - 1).skip) {
QueuedPackage previous = batch.get(batch.size() -
1);
current = new QueuedPackage(
@@ -461,16 +494,19 @@ public class DistributionSubscriber {
// Flush earlier packages before processing this
message on its own.
flushBatch(batch);
importCount = 0;
+ batchBytes = 0;
handlePackageMessage(current);
break;
case WAIT:
flushBatch(batch);
importCount = 0;
+ batchBytes = 0;
awaitPreconditionRetry(current.info.getOffset());
continue;
case RETRY:
flushBatch(batch);
importCount = 0;
+ batchBytes = 0;
awaitFailureBackoff();
continue;
}
@@ -478,6 +514,7 @@ public class DistributionSubscriber {
if (importCount >= maxBatchSize) {
flushBatch(batch);
importCount = 0;
+ batchBytes = 0;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
diff --git
a/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberConfiguration.java
b/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberConfiguration.java
index ebf45f3..d4d91aa 100644
---
a/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberConfiguration.java
+++
b/src/main/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberConfiguration.java
@@ -98,4 +98,12 @@ public @interface SubscriberConfiguration {
+ " Only applies if the package builder implements
BatchDistributionPackageBuilder and"
+ " packageHandling is Off. Default is 1 (no
batching).")
int maxBatchSize() default 1;
+
+ @AttributeDefinition(
+ name = "maxBatchByteSize",
+ description = "Maximum total payload size in bytes of packages
installed together."
+ + " Negative values mean unlimited (default -1). Only
applies when batching is enabled."
+ + " Packages larger than the limit or with unknown size
are imported individually."
+ + " This does not limit the size of a single package or
total heap usage.")
+ long maxBatchByteSize() default -1;
}
diff --git
a/src/test/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberBatchTest.java
b/src/test/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberBatchTest.java
index e47b42a..1f02468 100644
---
a/src/test/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberBatchTest.java
+++
b/src/test/java/org/apache/sling/distribution/journal/impl/subscriber/SubscriberBatchTest.java
@@ -18,6 +18,7 @@
*/
package org.apache.sling.distribution.journal.impl.subscriber;
+import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.net.URI;
import java.util.ArrayList;
@@ -42,6 +43,7 @@ import org.apache.sling.distribution.ImportPostProcessor;
import org.apache.sling.distribution.ImportPreProcessor;
import org.apache.sling.distribution.InvalidationProcessor;
import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.BinaryStore;
import org.apache.sling.distribution.journal.HandlerAdapter;
import org.apache.sling.distribution.journal.MessageHandler;
import org.apache.sling.distribution.journal.MessageSender;
@@ -137,6 +139,9 @@ public class SubscriberBatchTest {
@Mock
private EventAdmin eventAdmin;
+ @Mock
+ private BinaryStore binaryStore;
+
@Mock
private MessageSender<DiscoveryMessage> discoverySender;
@@ -236,6 +241,165 @@ public class SubscriberBatchTest {
verify(packageBuilder,
times(1)).installPackage(any(ResourceResolver.class),
any(DistributionPackage.class));
}
+ @Test
+ public void testByteLimitSplitsBatchesAndIgnoresSkippedMessages() throws
Exception {
+ assertByteLimitedImports(
+ 20,
+ Arrays.asList(
+ message("p1", ReqType.ADD),
+ skippedMessage(1, ReqType.ADD),
+ message("p2", ReqType.DELETE),
+ message("p3", ReqType.ADD),
+ skippedMessage(2, ReqType.ADD),
+ message("p4", ReqType.ADD)),
+ Arrays.asList(Collections.singletonList("p0"),
Arrays.asList("p1", "p2"), Arrays.asList("p3", "p4")));
+ }
+
+ @Test
+ public void testOversizedAndUnknownPackagesAreImportedIndividually()
throws Exception {
+ assertByteLimitedImports(
+ 20,
+ Arrays.asList(
+ message("p1", ReqType.ADD),
+ message("p2", ReqType.ADD),
+ PackageMessage.builder()
+ .pkgId("large")
+ .pubAgentName(PUB1_AGENT_NAME)
+ .pkgType("journal")
+ .reqType(ReqType.ADD)
+ .pkgBinary(new byte[21])
+ .build(),
+ PackageMessage.builder()
+ .pkgId("unknown")
+ .pubAgentName(PUB1_AGENT_NAME)
+ .pkgType("journal")
+ .reqType(ReqType.ADD)
+ .pkgLength(-1)
+ .build(),
+ message("p3", ReqType.ADD),
+ message("p4", ReqType.ADD)),
+ Arrays.asList(
+ Collections.singletonList("p0"),
+ Arrays.asList("p1", "p2"),
+ Collections.singletonList("large"),
+ Collections.singletonList("unknown"),
+ Arrays.asList("p3", "p4")));
+ }
+
+ @Test
+ public void testBlobLengthsAndInlinePayloadLengthsDefineBudget() throws
Exception {
+ when(binaryStore.get("known")).thenAnswer(invocation -> new
ByteArrayInputStream(new byte[10]));
+ when(binaryStore.get("unknown")).thenAnswer(invocation -> new
ByteArrayInputStream(new byte[10]));
+ assertByteLimitedImports(
+ 20,
+ Arrays.asList(
+ PackageMessage.builder()
+ .pkgId("blob")
+ .pubAgentName(PUB1_AGENT_NAME)
+ .pkgType("journal")
+ .reqType(ReqType.ADD)
+ .pkgBinaryRef("known")
+ .pkgLength(10)
+ .build(),
+ PackageMessage.builder()
+ .pkgId("inline")
+ .pubAgentName(PUB1_AGENT_NAME)
+ .pkgType("journal")
+ .reqType(ReqType.ADD)
+ .pkgBinary(new byte[10])
+ .pkgLength(Long.MAX_VALUE)
+ .build(),
+ PackageMessage.builder()
+ .pkgId("unknown")
+ .pubAgentName(PUB1_AGENT_NAME)
+ .pkgType("journal")
+ .reqType(ReqType.ADD)
+ .pkgBinaryRef("unknown")
+ .build(),
+ message("p1", ReqType.ADD),
+ message("p2", ReqType.ADD)),
+ Arrays.asList(
+ Collections.singletonList("p0"),
+ Arrays.asList("blob", "inline"),
+ Collections.singletonList("unknown"),
+ Arrays.asList("p1", "p2")));
+ verify(binaryStore).get("known");
+ verify(binaryStore).get("unknown");
+ }
+
+ @Test
+ public void testRecordedByteSizesDoNotOverflowBudget() throws Exception {
+ List<PackageMessage> packages = new ArrayList<>();
+ long[] sizes = {Long.MAX_VALUE - 1, 3, 4};
+ for (int i = 0; i < sizes.length; i++) {
+ packages.add(PackageMessage.builder()
+ .pkgId("p" + (i + 1))
+ .pubAgentName(PUB1_AGENT_NAME)
+ .pkgType("journal")
+ .reqType(ReqType.ADD)
+ .pkgLength(sizes[i])
+ .build());
+ }
+ assertByteLimitedImports(
+ Long.MAX_VALUE,
+ packages,
+ Arrays.asList(
+ Collections.singletonList("p0"),
Collections.singletonList("p1"), Arrays.asList("p2", "p3")));
+ }
+
+ @Test
+ public void testZeroByteLimitDoesNotBatchNonEmptyPayloads() throws
Exception {
+ assertByteLimitedImports(
+ 0,
+ Arrays.asList(message("p1", ReqType.ADD), message("p2",
ReqType.DELETE)),
+ Arrays.asList(
+ Collections.singletonList("p0"),
+ Collections.singletonList("p1"),
+ Collections.singletonList("p2")));
+ }
+
+ private void assertByteLimitedImports(
+ long byteLimit, List<PackageMessage> packages, List<List<String>>
expectedRuns) throws Exception {
+ List<List<String>> installedRuns = Collections.synchronizedList(new
ArrayList<>());
+ CountDownLatch firstImportStarted = new CountDownLatch(1);
+ CountDownLatch releaseFirstImport = new CountDownLatch(1);
+ when(packageBuilder.installPackage(any(ResourceResolver.class),
any(DistributionPackage.class)))
+ .thenAnswer(invocation -> {
+ DistributionPackage pkg = invocation.getArgument(1);
+ installedRuns.add(Collections.singletonList(pkg.getId()));
+ if ("p0".equals(pkg.getId())) {
+ firstImportStarted.countDown();
+ assertTrue(releaseFirstImport.await(10, SECONDS));
+ }
+ return true;
+ });
+ doAnswer(invocation -> {
+ List<DistributionPackage> batch =
invocation.getArgument(1);
+ List<String> ids = new ArrayList<>();
+ for (DistributionPackage pkg : batch) {
+ ids.add(pkg.getId());
+ }
+ installedRuns.add(ids);
+ return null;
+ })
+ .when(packageBuilder)
+ .installPackages(any(ResourceResolver.class), anyList());
+ initSubscriber(packages.size() + 1,
Collections.singletonMap("maxBatchByteSize", Long.toString(byteLimit)));
+ try {
+ packageHandler.handle(new TestMessageInfo("", 1, 0, 0),
message("p0", ReqType.ADD));
+ assertTrue(firstImportStarted.await(10, SECONDS));
+ for (int i = 0; i < packages.size(); i++) {
+ packageHandler.handle(new TestMessageInfo("", 1, i + 1, 0),
packages.get(i));
+ }
+ releaseFirstImport.countDown();
+
+ await().atMost(10, SECONDS).until(this::getStoredOffset,
equalTo((long) packages.size()));
+ assertThat(installedRuns, equalTo(expectedRuns));
+ } finally {
+ releaseFirstImport.countDown();
+ }
+ }
+
@Test
public void testEmptyQueueFlushesBatchBelowSizeLimit() throws Exception {
recordInstalledBatches();