Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix various issues with metering of automated runs (#7785)

James Bruntonb6c6458a80a2
diff --git a/app/common/src/main/java/stirling/software/common/service/AutomationRunContext.java b/app/common/src/main/java/stirling/software/common/service/AutomationRunContext.java
index 9ef4cb0511..f5b3f2d667 100644
--- a/app/common/src/main/java/stirling/software/common/service/AutomationRunContext.java
+++ b/app/common/src/main/java/stirling/software/common/service/AutomationRunContext.java
@@ -23,7 +23,11 @@ public final class AutomationRunContext {
/** Header carrying the run id on internal sub-step dispatches. */
public static final String RUN_ID_HEADER = "X-Stirling-Run-Id";
+ /** Header carrying the per-document id (run-scoped) on internal sub-step dispatches. */
+ public static final String DOCUMENT_ID_HEADER = "X-Stirling-Document-Id";
+
private static final ThreadLocal<String> CURRENT = new ThreadLocal<>();
+ private static final ThreadLocal<String> CURRENT_DOCUMENT = new ThreadLocal<>();
private AutomationRunContext() {}
@@ -48,6 +52,28 @@ public final class AutomationRunContext {
return CURRENT.get();
}
+ /**
+ * Opens a per-document scope on the current thread (nest inside a run scope, around one
+ * document's dispatch). Returns an {@link AutoCloseable} that restores the previous document
+ * id.
+ */
+ public static Scope openDocument(String documentId) {
+ String previous = CURRENT_DOCUMENT.get();
+ CURRENT_DOCUMENT.set(documentId);
+ return () -> {
+ if (previous == null) {
+ CURRENT_DOCUMENT.remove();
+ } else {
+ CURRENT_DOCUMENT.set(previous);
+ }
+ };
+ }
+
+ /** The document id active on this thread, or {@code null} when not inside a document scope. */
+ public static String currentDocument() {
+ return CURRENT_DOCUMENT.get();
+ }
+
/** AutoCloseable whose {@link #close()} declares no checked exception. */
public interface Scope extends AutoCloseable {
@Override
diff --git a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
index aa9bcaa640..4cb859eedf 100644
--- a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
+++ b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
@@ -136,6 +136,12 @@ public class InternalApiClient {
if (runId != null && !runId.isEmpty()) {
headers.add(AutomationRunContext.RUN_ID_HEADER, runId);
}
+ // Each source document gets its own charge grouping and step allowance on a linked
+ // instance. SaaS groups by lineage instead.
+ String documentId = AutomationRunContext.currentDocument();
+ if (documentId != null && !documentId.isEmpty()) {
+ headers.add(AutomationRunContext.DOCUMENT_ID_HEADER, documentId);
+ }
// Forward the parent policy name (set in MDC by the policy runner) so the audited sub-step
// ties back to its policy. Single-line, length-capped: it becomes an HTTP header value.
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
index 1563e63a9d..3418efd965 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
@@ -357,7 +357,8 @@ public class AccountLinkClient {
parseUnitCalcPolicy(root),
parseDateTime(root, "periodStart"),
parseDateTime(root, "periodEnd"),
- licensedUsers);
+ licensedUsers,
+ root.path("automationStepLimit").asInt(0));
}
/** Parses the nested unit-calc policy; null if absent or any knob is invalid (e.g. zero). */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java
index 6d925e9dda..897935c9ac 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java
@@ -40,7 +40,11 @@ public class AccountLinkWebMvcConfig implements WebMvcConfigurer {
// calls be gated too, while the interceptor lets genuine manual tools through.
registry.addInterceptor(gateInterceptor)
.addPathPatterns("/api/v1/**")
- .excludePathPatterns("/api/v1/account-link/**");
+ .excludePathPatterns(
+ "/api/v1/account-link/**",
+ "/api/v1/config/**",
+ "/api/v1/info/**",
+ "/api/v1/admin/**");
}
/**
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/BillableOperationClassifier.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/BillableOperationClassifier.java
index 476fbd111a..fb0b42573f 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/BillableOperationClassifier.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/BillableOperationClassifier.java
@@ -13,7 +13,9 @@ import stirling.software.proprietary.billing.BillingCategoryClassifier;
* <ul>
* <li><b>AUTOMATION</b> — the automation marker header ({@link
* InternalApiClient#AUTOMATION_HEADER}, set on pipeline / workflow / policy sub-steps);
- * <li><b>AI</b> — the AI surface ({@code /api/v1/ai/**});
+ * <li><b>AI</b> - the AI document-tool namespace ({@code /api/v1/ai/tools/**}); the engine's own
+ * surface ({@code /health}, {@code /orchestrate}, {@code /pdf/edit}) is reasoning/health, not
+ * a charged tool - its dispatched tools bill as AUTOMATION via the header, not here;
* <li><b>API</b> — an API-key authenticated tool call;
* <li><b>BYPASSED</b> — a manual interactive tool call, never billed.
* </ul>
@@ -26,7 +28,9 @@ import stirling.software.proprietary.billing.BillingCategoryClassifier;
*/
public final class BillableOperationClassifier {
- private static final String AI_PATH_PREFIX = "/api/v1/ai/";
+ // Only the /tools/ namespace is billable AI, matching the SaaS classifier - not the broader
+ // /api/v1/ai/ surface (health, orchestrate, pdf/edit), which must not be charged.
+ private static final String AI_PATH_PREFIX = "/api/v1/ai/tools/";
private BillableOperationClassifier() {}
@@ -44,8 +48,8 @@ public final class BillableOperationClassifier {
if (uri == null) {
return false;
}
- // Prefix-match the AI surface (not a loose substring contains), stripping a deployment
- // context path so /<ctx>/api/v1/ai/** still classifies as AI.
+ // Prefix-match the AI tool namespace (not a loose substring contains), stripping a
+ // deployment context path so /<ctx>/api/v1/ai/tools/** still classifies as AI.
String ctx = request.getContextPath();
String path =
ctx != null && !ctx.isEmpty() && uri.startsWith(ctx)
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
index 80479772e6..8f6d4e1432 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
@@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.proprietary.billing.BillingStepLimit;
import stirling.software.proprietary.billing.ContentHasher;
/**
@@ -105,10 +106,11 @@ public class FreeTierUsageService {
}
/**
- * Spends against the current period unless {@code opSignature} was already charged inside the
- * workflow window. Best-effort: callers need not handle persistence errors.
+ * Records successful work against the local grant using the default step limit. A null key
+ * always charges; a run/document key shares its allowance within the workflow window.
+ * Best-effort: callers need not handle persistence errors.
*/
- public void accrue(BillingCategory category, long units, String opSignature) {
+ public void accrue(BillingCategory category, long units, String dedupKey) {
if (category == null || category == BillingCategory.BYPASSED || units <= 0) {
return;
}
@@ -121,7 +123,9 @@ public class FreeTierUsageService {
log.debug("Free-tier period unavailable; skipping accrual: {}", e.getMessage());
return;
}
- if (opSignature != null && !inputWindow.shouldCharge(period, namespaced(opSignature))) {
+ if (dedupKey != null
+ && !inputWindow.shouldCharge(
+ period, namespaced(dedupKey), BillingStepLimit.resolve(null))) {
return;
}
incrementOrInsert(period, category.name(), units);
@@ -206,9 +210,9 @@ public class FreeTierUsageService {
}
}
- private static String namespaced(String opSignature) {
+ private static String namespaced(String dedupKey) {
// Re-hashed rather than prefixed: the signature column holds exactly one SHA-256 hex.
return ContentHasher.sha256(
- (SIGNATURE_NAMESPACE + opSignature).getBytes(StandardCharsets.UTF_8));
+ (SIGNATURE_NAMESPACE + dedupKey).getBytes(StandardCharsets.UTF_8));
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java
index d2da1f697e..2956fad057 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java
@@ -2,16 +2,15 @@ package stirling.software.proprietary.accountlink;
import java.time.LocalDateTime;
+import stirling.software.proprietary.billing.BillingStepLimit;
import stirling.software.proprietary.billing.UnitCalcPolicy;
/**
* Cached, proprietary-local view of the SaaS {@code GET /api/v1/instance/entitlement} response.
* Mirrors the saas {@code EntitlementResponse} shape but carries no saas types.
*
- * <p>The first five fields are what the <b>gate</b> enforces against; the trailing three are the
- * metering inputs (Phase 2) the instance uses to cost + bucket its own usage and reset its
- * per-period counters. The 5-arg constructor builds a gate-only view (metering fields null) for the
- * revoked sentinel and unit tests that don't exercise metering.
+ * <p>The five-argument constructor builds a gate-only view for the revoked sentinel. Older
+ * entitlement responses use the shared default automation step limit.
*
* @param subscribed team has an active subscription
* @param freeRemainingUnits remaining free-pool units (>0 means free work is available)
@@ -22,6 +21,8 @@ import stirling.software.proprietary.billing.UnitCalcPolicy;
* supplied (older SaaS / gate-only sentinel)
* @param periodStart inclusive start of the current billing period; {@code null} if not supplied
* @param periodEnd exclusive end of the current billing period; {@code null} if not supplied
+ * @param automationStepLimit successful sub-steps covered by one automation charge; non-positive
+ * values use the shared billing default
*/
public record InstanceEntitlement(
boolean subscribed,
@@ -32,7 +33,36 @@ public record InstanceEntitlement(
UnitCalcPolicy unitCalcPolicy,
LocalDateTime periodStart,
LocalDateTime periodEnd,
- Integer licensedUsers) {
+ Integer licensedUsers,
+ int automationStepLimit) {
+
+ public InstanceEntitlement {
+ automationStepLimit = BillingStepLimit.resolve(automationStepLimit);
+ }
+
+ /** Entitlement without a supplied automation step limit uses the shared billing default. */
+ public InstanceEntitlement(
+ boolean subscribed,
+ long freeRemainingUnits,
+ long periodSpendUnits,
+ Long periodCapUnits,
+ EntitlementState state,
+ UnitCalcPolicy unitCalcPolicy,
+ LocalDateTime periodStart,
+ LocalDateTime periodEnd,
+ Integer licensedUsers) {
+ this(
+ subscribed,
+ freeRemainingUnits,
+ periodSpendUnits,
+ periodCapUnits,
+ state,
+ unitCalcPolicy,
+ periodStart,
+ periodEnd,
+ licensedUsers,
+ BillingStepLimit.resolve(null));
+ }
/** Gate-only view with no metering config — used by the revoked sentinel and gate tests. */
public InstanceEntitlement(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
index a0eb3f71e3..af8ff8999a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
@@ -2,21 +2,19 @@ package stirling.software.proprietary.accountlink;
import java.io.IOException;
import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
+import java.io.OutputStream;
import java.nio.file.Files;
-import java.nio.file.Path;
-import java.security.DigestOutputStream;
-import java.security.MessageDigest;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Profile;
+import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
+import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
@@ -27,11 +25,13 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.common.annotations.AutoJobPostMapping;
+import stirling.software.common.service.AutomationRunContext;
+import stirling.software.common.service.InternalApiClient;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.jpdfium.PdfDocument;
import stirling.software.proprietary.billing.BillingCategory;
-import stirling.software.proprietary.billing.ContentHasher;
import stirling.software.proprietary.billing.DocumentUnitCalculator;
import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
import stirling.software.proprietary.billing.UnitCalcPolicy;
@@ -91,6 +91,11 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
SecurityContextHolder.getContext().getAuthentication()
instanceof ApiKeyAuthenticationToken;
BillingCategory category = BillableOperationClassifier.categorize(request, apiKey);
+ // API bills only for actual tool endpoints (@AutoJobPostMapping), matching the SaaS
+ // scope gate; a non-tool API-key call (info / config / download) is not billed.
+ if (category == BillingCategory.API && !isToolEndpoint(handler)) {
+ category = BillingCategory.BYPASSED;
+ }
request.setAttribute(ATTR_CATEGORY, category);
// A policy run kicks off billable automation, so block it up front when unentitled
// rather than after its first tool. It carries no automation header itself (category
@@ -121,6 +126,46 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
return false;
}
+ /**
+ * True when the handler is a tool endpoint - carries {@link AutoJobPostMapping} on the method
+ * or its controller. Mirrors the SaaS scope gate so API-key calls bill only on tool endpoints.
+ */
+ private static boolean isToolEndpoint(Object handler) {
+ if (!(handler instanceof HandlerMethod hm)) {
+ return false;
+ }
+ return AnnotationUtils.findAnnotation(hm.getMethod(), AutoJobPostMapping.class) != null
+ || AnnotationUtils.findAnnotation(hm.getBeanType(), AutoJobPostMapping.class)
+ != null;
+ }
+
+ /**
+ * The automation run id ({@link AutomationRunContext#RUN_ID_HEADER}) when this is a genuine
+ * internal dispatch (carries {@link InternalApiClient#AUTOMATION_HEADER}); {@code null}
+ * otherwise. Gated on the automation header so a raw caller can't pin a run id to collapse its
+ * separate calls into one charge - the same trust boundary the SaaS interceptor applies.
+ */
+ private static String automationRunId(HttpServletRequest request) {
+ if (request.getHeader(InternalApiClient.AUTOMATION_HEADER) == null) {
+ return null;
+ }
+ String runId = request.getHeader(AutomationRunContext.RUN_ID_HEADER);
+ return runId != null && !runId.isBlank() ? runId : null;
+ }
+
+ /**
+ * The per-document id ({@link AutomationRunContext#DOCUMENT_ID_HEADER}) on a genuine internal
+ * dispatch, else {@code null} - same automation-header trust boundary as {@link
+ * #automationRunId}. Each source document gets its own charge grouping and step allowance.
+ */
+ private static String automationDocumentId(HttpServletRequest request) {
+ if (request.getHeader(InternalApiClient.AUTOMATION_HEADER) == null) {
+ return null;
+ }
+ String documentId = request.getHeader(AutomationRunContext.DOCUMENT_ID_HEADER);
+ return documentId != null && !documentId.isBlank() ? documentId : null;
+ }
+
@Override
public void afterCompletion(
HttpServletRequest request,
@@ -138,7 +183,9 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
try {
if (request.getAttribute(ATTR_REASON) == GateDecision.Reason.FREE_TIER) {
MeteredOp op = measure(request, UnitCalcPolicy.DEFAULT);
- freeTierUsageService.accrue(category, op.units(), op.opSignature());
+ if (op != null) {
+ freeTierUsageService.accrue(category, op.units(), op.dedupKey());
+ }
return;
}
UsageMeterService meter = meterProvider.getIfAvailable();
@@ -151,69 +198,55 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
return;
}
MeteredOp op = measure(request, ent.unitCalcPolicy());
- meter.accrue(ent.periodStart(), category, op.units(), op.opSignature());
+ if (op != null) {
+ meter.accrue(
+ ent.periodStart(),
+ category,
+ op.units(),
+ op.dedupKey(),
+ ent.automationStepLimit());
+ }
} catch (RuntimeException e) {
// Metering must never affect the response that already completed.
log.debug("Usage metering failed for {}", request.getRequestURI(), e);
}
}
- /** {@code opSignature} null = no dedup. */
- private record MeteredOp(long units, String opSignature) {}
+ private record MeteredOp(long units, String dedupKey) {}
/**
- * Costs the inputs on both the page and byte axes: the instance is authoritative for units and
- * SaaS never sees the file, so a page-heavy but small PDF would otherwise under-bill. A
- * fileless op has no input identity, so no signature and the 1-unit floor each time.
+ * The instance is authoritative for units: SaaS never sees the file, so small page-heavy PDFs
+ * must be page-counted to avoid underbilling. No non-empty inputs means no charge.
*/
private MeteredOp measure(HttpServletRequest request, UnitCalcPolicy policy) {
MultipartHttpServletRequest mreq =
WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
if (mreq == null) {
- return new MeteredOp(DocumentUnitCalculator.unitsForFile(0, 0, policy), null);
+ return null;
}
List<TempFile> temps = new ArrayList<>();
try {
List<FileSize> sizes = new ArrayList<>();
- List<String> hashes = new ArrayList<>();
- int fileCount = 0;
for (List<MultipartFile> files : mreq.getMultiFileMap().values()) {
for (MultipartFile f : files) {
- fileCount++;
- try {
- TempFile temp = tempFileManager.createManagedTempFile(".bin");
- temps.add(temp);
- // Hash in the same pass that writes the temp file — one read of the upload,
- // not a second full read just to fingerprint it.
- MessageDigest digest = ContentHasher.newSha256();
- try (InputStream in = f.getInputStream();
- DigestOutputStream out =
- new DigestOutputStream(
- Files.newOutputStream(temp.getPath()), digest)) {
- in.transferTo(out);
- }
- sizes.add(new FileSize(pageCount(temp.getPath(), f), f.getSize()));
- hashes.add(ContentHasher.toHex(digest.digest()));
- } catch (IOException | RuntimeException perFile) {
- // Couldn't materialise/hash this input — bill on bytes only and, by leaving
- // it out of `hashes`, drop dedup for the whole op rather than risk a
- // mismatch.
- log.debug(
- "Metering materialise/hash failed for {}; bytes-only",
- f.getOriginalFilename());
- sizes.add(new FileSize(0, f.getSize()));
+ if (f.getSize() <= 0) {
+ continue; // skip empty parts, matching SaaS's non-empty input filter
}
+ sizes.add(new FileSize(pageCount(f, temps), f.getSize()));
}
}
- long units =
- sizes.isEmpty()
- ? DocumentUnitCalculator.unitsForFile(0, 0, policy)
- : DocumentUnitCalculator.unitsForGroup(sizes, policy);
- // Only dedup when every input hashed; a partial signature could collide with a
- // different input set, so fall back to no-dedup (bill it) if any file failed.
- String opSignature =
- fileCount > 0 && hashes.size() == fileCount ? opSignature(hashes) : null;
- return new MeteredOp(units, opSignature);
+ if (sizes.isEmpty()) {
+ return null;
+ }
+ // Prefer the per-document key so each source document has its own step allowance;
+ // fall back to the whole-run key for automation sub-steps with no document id. A
+ // standalone op has no key (null) and always accrues - each call is its own charge.
+ String runKey = automationDocumentId(request);
+ if (runKey == null) {
+ runKey = automationRunId(request);
+ }
+ long units = DocumentUnitCalculator.unitsForGroup(sizes, policy);
+ return new MeteredOp(units, runKey);
} finally {
for (TempFile temp : temps) {
try {
@@ -225,15 +258,27 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
}
}
- /** Page count via jpdfium (parser-identical to SaaS); 0 for non-PDF / unreadable inputs. */
- private static int pageCount(Path path, MultipartFile file) {
+ /**
+ * Page count via jpdfium (parser-identical to SaaS); 0 for a non-PDF or unreadable input. A PDF
+ * is materialised to a managed temp file (added to {@code temps} for the caller to close) so
+ * jpdfium can read it; a non-PDF needs no temp.
+ */
+ private int pageCount(MultipartFile file, List<TempFile> temps) {
if (!isPdf(file)) {
return 0;
}
- try (PdfDocument doc = PdfDocument.open(path)) {
- return doc.pageCount();
- } catch (RuntimeException e) {
- // Malformed / encrypted → byte axis only, matching the SaaS classifier.
+ try {
+ TempFile temp = tempFileManager.createManagedTempFile(".bin");
+ temps.add(temp);
+ try (InputStream in = file.getInputStream();
+ OutputStream out = Files.newOutputStream(temp.getPath())) {
+ in.transferTo(out);
+ }
+ try (PdfDocument doc = PdfDocument.open(temp.getPath())) {
+ return doc.pageCount();
+ }
+ } catch (IOException | RuntimeException e) {
+ // Malformed / encrypted / unreadable -> byte axis only, matching the SaaS classifier.
log.debug(
"Page count unavailable for {}; metering on bytes only",
file.getOriginalFilename());
@@ -241,13 +286,6 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
}
}
- /** Order-independent signature of the input set: sorted per-file hashes, hashed together. */
- private static String opSignature(List<String> hashes) {
- List<String> sorted = new ArrayList<>(hashes);
- Collections.sort(sorted);
- return ContentHasher.sha256(String.join("\n", sorted).getBytes(StandardCharsets.UTF_8));
- }
-
private static boolean isPdf(MultipartFile file) {
String contentType = file.getContentType();
if (contentType != null && contentType.toLowerCase().contains("pdf")) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignature.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignature.java
index 278380a5da..91178da9c5 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignature.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignature.java
@@ -15,12 +15,8 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
/**
- * The last time the instance metered a given input set this period — the local equivalent of the
- * cloud's lineage join (combined billing). The meter dedups on a rolling <b>workflow window</b>: an
- * identical input set re-submitted within the window (see {@link AccountLinkProperties.Metering})
- * is treated as workflow chaining and not re-charged, while the same inputs run again after the
- * window are billed afresh — matching the cloud's 5-minute open-job window so the same operation
- * costs the same on the instance and in the cloud.
+ * A run/document billing key with the successful step count for its current charge. Another charge
+ * begins when the configured step limit or rolling workflow window is reached.
*
* <p>{@code lastMeteredAt} is refreshed on every sighting (the window slides, as recording a cloud
* artifact touches its job). One row per {@code (period, signature)}; the unique constraint also
@@ -46,28 +42,26 @@ public class MeteredInputSignature {
@Column(name = "period_start", nullable = false)
private LocalDateTime periodStart;
- /** SHA-256 hex of the op's input set (64 chars); the dedup key within a period. */
+ /** Run-scoped document id, or the run id when the dispatch has no single source document. */
@Column(name = "signature", nullable = false, length = 64)
private String signature;
@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt;
- /**
- * When this input set was last metered — the anchor the workflow-window dedup compares against.
- */
+ /** Last successful step; anchors the rolling workflow window. */
@Column(name = "last_metered_at")
private LocalDateTime lastMeteredAt;
+ /** Null on rows predating step counting; treated as one already-charged step. */
+ @Column(name = "step_count")
+ private Integer stepCount;
+
public MeteredInputSignature(LocalDateTime periodStart, String signature, LocalDateTime at) {
this.periodStart = periodStart;
this.signature = signature;
this.createdAt = at;
this.lastMeteredAt = at;
- }
-
- /** Slides the window forward — the input set was seen again. */
- public void touch(LocalDateTime at) {
- this.lastMeteredAt = at;
+ this.stepCount = 1;
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignatureRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignatureRepository.java
index a31310a7b3..930b604110 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignatureRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputSignatureRepository.java
@@ -4,12 +4,48 @@ import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+import org.springframework.transaction.annotation.Transactional;
-/** Persistence for the per-period metered input-set signatures (combined billing). */
+/** Durable per-document step counts; conditional updates serialize concurrent completions. */
public interface MeteredInputSignatureRepository
extends JpaRepository<MeteredInputSignature, Long> {
- /** The existing row for a seen input set, so the meter can apply the workflow-window check. */
+ /** The billing state for one run/document key in a period. */
Optional<MeteredInputSignature> findByPeriodStartAndSignature(
LocalDateTime periodStart, String signature);
+
+ /** Starts another charge if the window expired or the step limit was reached; 1 means won. */
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MeteredInputSignature s SET s.stepCount = 1, s.lastMeteredAt = :now"
+ + " WHERE s.periodStart = :periodStart AND s.signature = :signature"
+ + " AND (s.lastMeteredAt <= :cutoff OR COALESCE(s.stepCount, 1) >= :stepLimit)")
+ int restartIfFullOrExpired(
+ @Param("periodStart") LocalDateTime periodStart,
+ @Param("signature") String signature,
+ @Param("now") LocalDateTime now,
+ @Param("cutoff") LocalDateTime cutoff,
+ @Param("stepLimit") int stepLimit);
+
+ /**
+ * Adds a successful step to a current charge with capacity; 1 means joined without charging.
+ */
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MeteredInputSignature s SET s.stepCount = COALESCE(s.stepCount, 1) + 1,"
+ + " s.lastMeteredAt = :now"
+ + " WHERE s.periodStart = :periodStart AND s.signature = :signature"
+ + " AND (s.lastMeteredAt IS NULL OR s.lastMeteredAt > :cutoff)"
+ + " AND COALESCE(s.stepCount, 1) < :stepLimit")
+ int joinIfWithinLimit(
+ @Param("periodStart") LocalDateTime periodStart,
+ @Param("signature") String signature,
+ @Param("now") LocalDateTime now,
+ @Param("cutoff") LocalDateTime cutoff,
+ @Param("stepLimit") int stepLimit);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputWindow.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputWindow.java
index 9c3448b51a..8c79db4792 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputWindow.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputWindow.java
@@ -8,11 +8,8 @@ import org.springframework.dao.DataIntegrityViolationException;
import lombok.extern.slf4j.Slf4j;
/**
- * The workflow-window dedup rule, shared by both meters so an op costs the same either way. An
- * identical input set inside {@code metering.workflow-window} is chaining, not a new charge.
- *
- * <p>Not a bean: each meter constructs one, so the rule cannot be on for one ledger and off for the
- * other. {@link MeteredInputSignature} rows are shared, so callers namespace their own.
+ * Groups successful steps by run/document key until the step limit or workflow window is reached.
+ * Both ledgers share this rule; callers namespace keys to keep free-tier and cloud usage separate.
*/
@Slf4j
class MeteredInputWindow {
@@ -26,33 +23,40 @@ class MeteredInputWindow {
}
/**
- * Charge when unseen this period, or last seen outside the window. Records a first sighting as
- * an atomic insert-as-claim, and fails toward charging so a store hiccup drops nothing.
+ * Records one successful step and returns whether it starts a charge. Concurrent completions
+ * share the persisted allowance; persistence errors fail toward charging.
*/
- boolean shouldCharge(LocalDateTime periodStart, String opSignature) {
+ boolean shouldCharge(LocalDateTime periodStart, String dedupKey, int stepLimit) {
LocalDateTime now = LocalDateTime.now();
- MeteredInputSignature seen =
- signatureRepo.findByPeriodStartAndSignature(periodStart, opSignature).orElse(null);
- if (seen == null) {
- try {
- signatureRepo.saveAndFlush(
- new MeteredInputSignature(periodStart, opSignature, now));
- return true; // first sighting this period
- } catch (DataIntegrityViolationException raced) {
- return false; // a concurrent op just claimed it — within window → chaining
- } catch (RuntimeException e) {
- log.debug("Signature claim failed for {}: {}", periodStart, e.getMessage());
- return true;
- }
- }
- LocalDateTime last = seen.getLastMeteredAt() != null ? seen.getLastMeteredAt() : now;
- boolean withinWindow = last.isAfter(now.minus(window));
+ LocalDateTime cutoff = now.minus(window);
try {
- seen.touch(now);
- signatureRepo.save(seen);
+ while (true) {
+ if (signatureRepo.restartIfFullOrExpired(
+ periodStart, dedupKey, now, cutoff, stepLimit)
+ > 0) {
+ return true;
+ }
+ if (signatureRepo.joinIfWithinLimit(periodStart, dedupKey, now, cutoff, stepLimit)
+ > 0) {
+ return false;
+ }
+ try {
+ signatureRepo.saveAndFlush(
+ new MeteredInputSignature(periodStart, dedupKey, now));
+ return true;
+ } catch (DataIntegrityViolationException raced) {
+ // Another completion inserted or filled this key between the conditional
+ // updates. Retry so this successful step still counts toward the limit.
+ if (signatureRepo
+ .findByPeriodStartAndSignature(periodStart, dedupKey)
+ .isEmpty()) {
+ throw raced;
+ }
+ }
+ }
} catch (RuntimeException e) {
- log.debug("Signature touch failed for {}: {}", periodStart, e.getMessage());
+ log.debug("Step counting failed for {}: {}", periodStart, e.getMessage());
+ return true;
}
- return !withinWindow;
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java
index 31ec9e254f..8e7db81453 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java
@@ -10,14 +10,16 @@ import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.proprietary.billing.BillingStepLimit;
/**
* Accrues a linked team's metered usage into the durable per-(period, category) {@link
* UsageCounter}; the daily sync later reports the cumulative totals to SaaS. The cloud ledger only
* — an unlinked instance meters its own grant through {@link FreeTierUsageService}.
*
- * <p>Dedup follows the shared {@link MeteredInputWindow} rule. Fileless ops pass a null signature
- * and always accrue. {@link #accrue} is best-effort: callers need not handle persistence errors.
+ * <p>A run/document key groups successful sub-steps until the configured step limit or workflow
+ * window is reached. Standalone calls have no key and always accrue. Persistence failures are
+ * logged and never affect the completed operation's response.
*/
@Slf4j
@Service
@@ -40,20 +42,36 @@ public class UsageMeterService {
}
/**
- * Adds {@code units} to the {@code (periodStart, category)} counter (creating the row on first
- * use), unless {@code opSignature} was already metered this period. No-ops for non-billable
- * categories, non-positive units, or a missing period.
+ * Records successful work using the default step limit. A null key always charges; a
+ * run/document key groups steps within that limit and the workflow window.
*/
public void accrue(
- LocalDateTime periodStart, BillingCategory category, long units, String opSignature) {
+ LocalDateTime periodStart, BillingCategory category, long units, String dedupKey) {
+ accrue(periodStart, category, units, dedupKey, BillingStepLimit.resolve(null));
+ }
+
+ /**
+ * Records one successful step. Charges its current input units on the first step, after {@code
+ * stepLimit} successful steps, or after the workflow window expires. Each key counts
+ * independently; a null key always charges. Missing periods, non-billable categories and
+ * non-positive units are ignored. Callers must not report failed steps.
+ */
+ public void accrue(
+ LocalDateTime periodStart,
+ BillingCategory category,
+ long units,
+ String dedupKey,
+ int stepLimit) {
if (periodStart == null
|| category == null
|| category == BillingCategory.BYPASSED
|| units <= 0) {
return;
}
- if (opSignature != null && !inputWindow.shouldCharge(periodStart, opSignature)) {
- return; // identical inputs seen within the workflow window — chaining, already billed
+ if (dedupKey != null
+ && !inputWindow.shouldCharge(
+ periodStart, dedupKey, BillingStepLimit.resolve(stepLimit))) {
+ return;
}
incrementOrInsert(periodStart, category.name(), units);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBiller.java b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBiller.java
new file mode 100644
index 0000000000..b6aa6d8284
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBiller.java
@@ -0,0 +1,63 @@
+package stirling.software.proprietary.automation;
+
+import java.util.List;
+
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Component;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.accountlink.EntitlementCache;
+import stirling.software.proprietary.accountlink.InstanceEntitlement;
+import stirling.software.proprietary.accountlink.UsageMeterService;
+import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.proprietary.billing.DocumentUnitCalculator;
+import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
+import stirling.software.proprietary.billing.UnitCalcPolicy;
+
+/**
+ * Charges a client-side Automate run on a linked self-hosted instance: computes the input set's
+ * doc-units with the instance's synced {@link UnitCalcPolicy} and accrues them as {@link
+ * BillingCategory#AUTOMATION}, exactly as the {@code InstanceEntitlementInterceptor} meters a
+ * policy's tool sub-steps. Metering is instance-scoped, so no per-user context is needed.
+ *
+ * <p>Metering itself is optional (the {@link UsageMeterService} bean is absent when {@code
+ * metering.enabled=false}); a null signature is passed so each run is its own charge (the
+ * standalone semantic - no workflow-window dedup).
+ */
+@Slf4j
+@Component
+@Profile("!saas")
+@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+public class AccountLinkAutomationRunBiller implements AutomationRunBiller {
+
+ private final EntitlementCache entitlementCache;
+ private final ObjectProvider<UsageMeterService> meterProvider;
+
+ public AccountLinkAutomationRunBiller(
+ EntitlementCache entitlementCache, ObjectProvider<UsageMeterService> meterProvider) {
+ this.entitlementCache = entitlementCache;
+ this.meterProvider = meterProvider;
+ }
+
+ @Override
+ public void recordAutomationRun(List<FileSize> inputs) {
+ if (inputs.isEmpty()) {
+ return;
+ }
+ UsageMeterService meter = meterProvider.getIfAvailable();
+ if (meter == null) {
+ return; // metering switch off
+ }
+ InstanceEntitlement ent = entitlementCache.current().orElse(null);
+ if (ent == null || ent.unitCalcPolicy() == null || ent.periodStart() == null) {
+ // Not yet synced (no policy/period) - can't compute units; skip until next sync.
+ return;
+ }
+ UnitCalcPolicy policy = ent.unitCalcPolicy();
+ long units = DocumentUnitCalculator.unitsForGroup(inputs, policy);
+ meter.accrue(ent.periodStart(), BillingCategory.AUTOMATION, units, null);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/automation/AutomationMeterController.java b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AutomationMeterController.java
new file mode 100644
index 0000000000..5bb34dd6d9
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AutomationMeterController.java
@@ -0,0 +1,128 @@
+package stirling.software.proprietary.automation;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import io.swagger.v3.oas.annotations.Hidden;
+import io.swagger.v3.oas.annotations.Operation;
+
+import jakarta.servlet.http.HttpServletRequest;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.audit.AuditContext;
+import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
+
+/**
+ * Meters + audits a client-side automation run so a browser-run automation bills like the
+ * equivalent server-side policy. The meter endpoint for every automation that executes in the
+ * browser (rather than through the billing interceptors). Side-effect only; does no processing
+ * itself.
+ */
+@Slf4j
+@Hidden
+@RestController
+@RequestMapping("/api/v1/automation")
+public class AutomationMeterController {
+
+ /** Cap on input documents accepted per call, guarding against a hostile client payload. */
+ private static final int MAX_INPUTS = 10_000;
+
+ /** Cap on operations recorded for the audit label. */
+ private static final int MAX_OPERATIONS = 1_000;
+
+ private final ObjectProvider<AutomationRunBiller> biller;
+
+ public AutomationMeterController(ObjectProvider<AutomationRunBiller> biller) {
+ this.biller = biller;
+ }
+
+ @PostMapping("/meter")
+ @Operation(
+ summary = "Meter a client-side automation run",
+ description =
+ "Records billing + audit for an automation performed in the browser (the"
+ + " Automate tool or the local classification pass). Does no processing"
+ + " itself. Dispatched by the frontend, not for direct use.")
+ public ResponseEntity<Void> meterAutomationRun(
+ @RequestBody(required = false) AutomationMeterRequest body,
+ HttpServletRequest request) {
+ List<FileSize> inputs = sanitizeInputs(body);
+ if (inputs.isEmpty()) {
+ // No billable input set - nothing to charge (an empty run still returns 202).
+ return ResponseEntity.accepted().build();
+ }
+
+ String automationName =
+ body != null && body.automationName() != null && !body.automationName().isBlank()
+ ? body.automationName()
+ : "Automation";
+ List<String> steps = sanitizeOperations(body);
+
+ // Stamp the run so the audit trail records it as an automation, like a server-run policy.
+ request.setAttribute(AuditContext.REQ_ATTR_POLICY_NAME, automationName);
+ request.setAttribute(AuditContext.REQ_ATTR_POLICY_STEPS, steps);
+
+ AutomationRunBiller runBiller = biller.getIfAvailable();
+ if (runBiller != null) {
+ try {
+ runBiller.recordAutomationRun(inputs);
+ } catch (RuntimeException e) {
+ log.warn(
+ "[automate meter] billing failed; the run already completed unbilled: {}",
+ e.getMessage());
+ }
+ }
+ return ResponseEntity.accepted().build();
+ }
+
+ /** Clamp to a sane count and drop malformed entries; negatives are treated as zero. */
+ private static List<FileSize> sanitizeInputs(AutomationMeterRequest body) {
+ if (body == null || body.inputs() == null) {
+ return List.of();
+ }
+ List<FileSize> out = new ArrayList<>();
+ for (InputDoc doc : body.inputs()) {
+ if (doc == null) {
+ continue;
+ }
+ int pages = doc.pages() != null ? Math.max(0, doc.pages()) : 0;
+ long bytes = doc.bytes() != null ? Math.max(0L, doc.bytes()) : 0L;
+ out.add(new FileSize(pages, bytes));
+ if (out.size() >= MAX_INPUTS) {
+ break;
+ }
+ }
+ return out;
+ }
+
+ private static List<String> sanitizeOperations(AutomationMeterRequest body) {
+ if (body == null || body.operations() == null) {
+ return List.of();
+ }
+ List<String> out = new ArrayList<>();
+ for (String op : body.operations()) {
+ if (op != null && !op.isBlank()) {
+ out.add(op.trim());
+ }
+ if (out.size() >= MAX_OPERATIONS) {
+ break;
+ }
+ }
+ return out;
+ }
+
+ /** Frontend payload: the run's name, its operation ids, and per-input page/byte facts. */
+ public record AutomationMeterRequest(
+ String automationName, List<String> operations, List<InputDoc> inputs) {}
+
+ /** One input document's page count (0 for non-PDF / unknown) and byte size. */
+ public record InputDoc(Integer pages, Long bytes) {}
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/automation/AutomationRunBiller.java b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AutomationRunBiller.java
new file mode 100644
index 0000000000..3641d04942
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AutomationRunBiller.java
@@ -0,0 +1,18 @@
+package stirling.software.proprietary.automation;
+
+import java.util.List;
+
+import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
+
+/**
+ * Meters one client-side automation run - the Automate tool or the local classification pass. Both
+ * run their work in the browser (calling each tool's normal endpoint), so no automation sub-step
+ * reaches the billing interceptors; this biller is how those runs are charged instead. SaaS and a
+ * linked self-hosted instance each provide an implementation; other flavors have no bean and the
+ * run is recorded for audit but not charged.
+ */
+public interface AutomationRunBiller {
+
+ /** Charge one run over {@code inputs} (page/byte facts of the original input files). */
+ void recordAutomationRun(List<FileSize> inputs);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/billing/BillingStepLimit.java b/app/proprietary/src/main/java/stirling/software/proprietary/billing/BillingStepLimit.java
new file mode 100644
index 0000000000..f81fea883f
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/billing/BillingStepLimit.java
@@ -0,0 +1,12 @@
+package stirling.software.proprietary.billing;
+
+/** Shared fallback for the number of successful tool calls covered by one charge. */
+public final class BillingStepLimit {
+
+ private BillingStepLimit() {}
+
+ /** Missing or non-positive limits use 10 steps; no value denotes unlimited steps. */
+ public static int resolve(Integer configured) {
+ return configured != null && configured > 0 ? configured : 10;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/classification/ClassificationRunBiller.java b/app/proprietary/src/main/java/stirling/software/proprietary/classification/ClassificationRunBiller.java
deleted file mode 100644
index dd0467c9ca..0000000000
--- a/app/proprietary/src/main/java/stirling/software/proprietary/classification/ClassificationRunBiller.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package stirling.software.proprietary.classification;
-
-/** Meters a client-side classification run; SaaS charges PAYG, other flavors have no bean. */
-public interface ClassificationRunBiller {
-
- /** Charge one classification policy run covering {@code documentCount} documents. */
- void recordClassificationRun(int documentCount);
-}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ClassificationMeterController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ClassificationMeterController.java
deleted file mode 100644
index dc978648b6..0000000000
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ClassificationMeterController.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package stirling.software.proprietary.policy.controller;
-
-import java.util.List;
-
-import org.springframework.beans.factory.ObjectProvider;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.v3.oas.annotations.Hidden;
-import io.swagger.v3.oas.annotations.Operation;
-
-import jakarta.servlet.http.HttpServletRequest;
-
-import lombok.extern.slf4j.Slf4j;
-
-import stirling.software.proprietary.audit.AuditContext;
-import stirling.software.proprietary.classification.ClassificationRunBiller;
-
-/**
- * Meters + audits a client-side (non-AI) classification run so both classify paths bill
- * identically. Side-effect only; does no classification itself.
- */
-@Slf4j
-@Hidden
-@RestController
-@RequestMapping("/api/v1/policies")
-public class ClassificationMeterController {
-
- /** Audit step label mirrors the AI classify tool so both paths read alike in the trail. */
- private static final String CLASSIFY_STEP = "/api/v1/ai/tools/classify-and-label";
-
- /** Client-supplied count cap: the frontend meters one document per call. */
- private static final int MAX_DOCUMENTS = 10_000;
-
- private final ObjectProvider<ClassificationRunBiller> biller;
-
- public ClassificationMeterController(ObjectProvider<ClassificationRunBiller> biller) {
- this.biller = biller;
- }
-
- @PostMapping("/classify/meter")
- @Operation(
- summary = "Meter a client-side classification run",
- description =
- "Records billing + audit for a non-AI classification performed in the browser."
- + " Does no classification itself. Dispatched by the frontend, not for"
- + " direct use.")
- public ResponseEntity<Void> meterClassification(
- @RequestBody(required = false) ClassifyMeterRequest body, HttpServletRequest request) {
- int documents = body != null && body.documentCount() != null ? body.documentCount() : 1;
- if (documents < 1) documents = 1;
- if (documents > MAX_DOCUMENTS) documents = MAX_DOCUMENTS;
- String policyName =
- body != null && body.policyName() != null && !body.policyName().isBlank()
- ? body.policyName()
- : "Classification";
-
- // Stamp the run so ControllerAuditAspect records it as a policy run, like the AI path.
- request.setAttribute(AuditContext.REQ_ATTR_POLICY_NAME, policyName);
- request.setAttribute(AuditContext.REQ_ATTR_POLICY_STEPS, List.of(CLASSIFY_STEP));
-
- ClassificationRunBiller runBiller = biller.getIfAvailable();
- if (runBiller != null) {
- try {
- runBiller.recordClassificationRun(documents);
- } catch (RuntimeException e) {
- log.warn(
- "[classify meter] billing failed; classification proceeds unbilled: {}",
- e.getMessage());
- }
- }
- return ResponseEntity.accepted().build();
- }
-
- /** Frontend payload: documents classified, plus the policy name for the audit label. */
- public record ClassifyMeterRequest(
- String policyName, Integer documentCount, List<String> labels) {}
-}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
index 8a36700460..03b5dd94a9 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
@@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
@@ -19,6 +20,7 @@ import org.springframework.util.MultiValueMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.common.service.AutomationRunContext;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
@@ -58,10 +60,10 @@ public class PolicyExecutor {
// payload the tool surfaced alongside or instead of a file.
private record ToolResult(List<Resource> files, JsonNode report) {}
- // A step's output files paired with each file's origin (the index into the original pipeline
- // inputs it traces back to, or null when it has no single source). Origins compose across steps
- // so the final result can be mapped back onto the files that entered the pipeline.
- private record StepOutput(List<Resource> files, List<Integer> origins, JsonNode report) {}
+ // A merge can lose its single-source attribution while continuing an input's billing group.
+ private record PipelineFile(Resource resource, Integer origin, Integer billingOrigin) {}
+
+ private record StepOutput(List<PipelineFile> files, JsonNode report) {}
/**
* Run every step in order, feeding each step's output into the next. Supporting files in {@code
@@ -78,13 +80,10 @@ public class PolicyExecutor {
throw new IllegalArgumentException("Pipeline definition has no steps");
}
- List<Resource> currentFiles = inputs.primary();
+ List<PipelineFile> currentFiles = new ArrayList<>();
Map<String, List<Resource>> supportingFiles = inputs.supportingFiles();
- // Seed each input with its own index as origin; steps carry these through so the final
- // outputs can be traced back to the files that entered the pipeline.
- List<Integer> currentOrigins = new ArrayList<>();
- for (int k = 0; k < currentFiles.size(); k++) {
- currentOrigins.add(k);
+ for (int k = 0; k < inputs.primary().size(); k++) {
+ currentFiles.add(new PipelineFile(inputs.primary().get(k), k, k));
}
// Last non-null report wins: the terminal step defines the output.
JsonNode lastReport = null;
@@ -98,10 +97,8 @@ public class PolicyExecutor {
"Pipeline step " + (i + 1) + " has no operation");
}
listener.onStepStart(i + 1, steps.size(), operation);
- StepOutput stepResult =
- executeStep(step, currentFiles, currentOrigins, supportingFiles);
+ StepOutput stepResult = executeStep(step, currentFiles, supportingFiles);
currentFiles = stepResult.files();
- currentOrigins = stepResult.origins();
if (stepResult.report() != null) {
lastReport = stepResult.report();
lastReportTool = operation;
@@ -109,7 +106,11 @@ public class PolicyExecutor {
listener.onStepComplete(i + 1, steps.size(), operation);
}
- return new PolicyExecutionResult(currentFiles, currentOrigins, lastReport, lastReportTool);
+ return new PolicyExecutionResult(
+ currentFiles.stream().map(PipelineFile::resource).toList(),
+ currentFiles.stream().map(PipelineFile::origin).toList(),
+ lastReport,
+ lastReportTool);
}
/**
@@ -119,48 +120,66 @@ public class PolicyExecutor {
*/
private StepOutput executeStep(
PipelineStep step,
- List<Resource> inputFiles,
- List<Integer> inputOrigins,
+ List<PipelineFile> inputFiles,
Map<String, List<Resource>> supportingFiles)
throws IOException {
- requireAcceptedTypes(step.operation(), inputFiles);
- List<Resource> files = new ArrayList<>();
- List<Integer> origins = new ArrayList<>();
+ List<Resource> resources = inputFiles.stream().map(PipelineFile::resource).toList();
+ requireAcceptedTypes(step.operation(), resources);
+ List<PipelineFile> files = new ArrayList<>();
JsonNode report = null;
if (toolMetadataService.isMultiInput(step.operation())) {
- // One call over all inputs. The outputs derive from a single input only when exactly
- // one entered; otherwise (a genuine merge) there is no single source.
- ToolResult r = callEndpoint(step, inputFiles, supportingFiles);
- Integer origin = inputOrigins.size() == 1 ? inputOrigins.getFirst() : null;
+ Integer origin = sharedOrigin(inputFiles);
+ // Synchronous, ordered dispatch makes the last surviving input's group the newest,
+ // matching SaaS's choice when a merge joins several previously processed documents.
+ Integer billingOrigin =
+ inputFiles.isEmpty() ? null : inputFiles.getLast().billingOrigin();
+ ToolResult r;
+ try (AutomationRunContext.Scope doc = documentScope(billingOrigin)) {
+ r = callEndpoint(step, resources, supportingFiles);
+ }
for (Resource file : r.files()) {
- files.add(file);
- origins.add(origin);
+ files.add(new PipelineFile(file, origin, billingOrigin));
}
report = r.report();
} else if (inputFiles.isEmpty()) {
ToolResult r = callEndpoint(step, List.of(), supportingFiles);
for (Resource file : r.files()) {
- files.add(file);
- origins.add(null);
+ files.add(new PipelineFile(file, null, null));
}
report = r.report();
} else {
- // One call per file: every output of this call inherits that input's origin, so a 1:1
- // op keeps its chain and a split (one input, many outputs) tags each output with the
- // same source.
- for (int k = 0; k < inputFiles.size(); k++) {
- Integer origin = inputOrigins.get(k);
- ToolResult r = callEndpoint(step, List.of(inputFiles.get(k)), supportingFiles);
+ for (PipelineFile input : inputFiles) {
+ ToolResult r;
+ try (AutomationRunContext.Scope doc = documentScope(input.billingOrigin())) {
+ r = callEndpoint(step, List.of(input.resource()), supportingFiles);
+ }
for (Resource file : r.files()) {
- files.add(file);
- origins.add(origin);
+ files.add(new PipelineFile(file, input.origin(), input.billingOrigin()));
}
if (report == null) {
report = r.report();
}
}
}
- return new StepOutput(files, origins, report);
+ return new StepOutput(files, report);
+ }
+
+ private static Integer sharedOrigin(List<PipelineFile> files) {
+ if (files.isEmpty()) {
+ return null;
+ }
+ Integer origin = files.getFirst().origin();
+ return files.stream().allMatch(file -> Objects.equals(origin, file.origin()))
+ ? origin
+ : null;
+ }
+
+ private static AutomationRunContext.Scope documentScope(Integer billingOrigin) {
+ String runId = AutomationRunContext.current();
+ if (runId == null || billingOrigin == null) {
+ return () -> {};
+ }
+ return AutomationRunContext.openDocument(runId + ":" + billingOrigin);
}
/**
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
index 2bce17d732..9f4ba86ea9 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
@@ -16,6 +16,9 @@ import java.time.LocalDateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import tools.jackson.databind.ObjectMapper;
@@ -141,12 +144,27 @@ class AccountLinkClientTest {
assertEquals(10, e.periodSpendUnits());
assertEquals(100L, e.periodCapUnits());
assertEquals(EntitlementState.OK, e.state());
+ assertEquals(10, e.automationStepLimit());
HttpRequest sent = captor.getValue();
assertEquals("dev-1", sent.headers().firstValue("X-Device-Id").orElse(null));
assertEquals("sec-1", sent.headers().firstValue("X-Device-Secret").orElse(null));
}
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(ints = {-1, 0, 1, 20, Integer.MAX_VALUE})
+ @SuppressWarnings("unchecked")
+ void fetchEntitlementParsesAutomationStepLimit(Integer limit) throws Exception {
+ HttpResponse<String> resp = response(200, "{\"automationStepLimit\":" + limit + "}");
+ when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(resp);
+
+ InstanceEntitlement entitlement = client.fetchEntitlement("dev-1", "sec-1");
+
+ assertNotNull(entitlement);
+ assertEquals(limit != null && limit > 0 ? limit : 10, entitlement.automationStepLimit());
+ }
+
@Test
@SuppressWarnings("unchecked")
void fetchEntitlementMapsOverLimitState() throws Exception {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/BillableOperationClassifierTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/BillableOperationClassifierTest.java
index 0b43069ee9..6b435124ca 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/BillableOperationClassifierTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/BillableOperationClassifierTest.java
@@ -70,9 +70,26 @@ class BillableOperationClassifierTest {
@Test
void aiPathUnderContextPathIsAi() {
- // A real context-path deployment still classifies: /<ctx>/api/v1/ai/** is AI.
+ // A real context-path deployment still classifies: /<ctx>/api/v1/ai/tools/** is AI.
MockHttpServletRequest req = req("/stirling/api/v1/ai/tools/foo");
req.setContextPath("/stirling");
assertEquals(BillingCategory.AI, BillableOperationClassifier.categorize(req, false));
}
+
+ @Test
+ void aiEngineHealthIsBypassed() {
+ // Only the /tools/ namespace is billable AI; the engine's own health surface is not.
+ assertEquals(
+ BillingCategory.BYPASSED,
+ BillableOperationClassifier.categorize(req("/api/v1/ai/health"), false));
+ }
+
+ @Test
+ void aiOrchestrateIsBypassed() {
+ // Orchestrate is AI reasoning; its dispatched tools bill as AUTOMATION, not the call
+ // itself.
+ assertEquals(
+ BillingCategory.BYPASSED,
+ BillableOperationClassifier.categorize(req("/api/v1/ai/orchestrate"), false));
+ }
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/FreeTierUsageServiceDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/FreeTierUsageServiceDbTest.java
index 8550a616b1..9814c472ff 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/FreeTierUsageServiceDbTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/FreeTierUsageServiceDbTest.java
@@ -172,25 +172,59 @@ class FreeTierUsageServiceDbTest {
}
@Test
- void repeatingAnInputSetInsideTheWorkflowWindowIsNotCharged() {
+ void stepsForTheSameDocumentShareACharge() {
FreeTierUsageService service = service(500);
- service.accrue(BillingCategory.API, 20, "a".repeat(64));
- service.accrue(BillingCategory.API, 20, "a".repeat(64));
+ service.accrue(BillingCategory.AUTOMATION, 20, "run:0");
+ service.accrue(BillingCategory.AUTOMATION, 30, "run:0");
assertThat(service.balance().usedUnits()).isEqualTo(20);
}
@Test
- void aDifferentInputSetIsChargedSeparately() {
+ void differentDocumentsAreChargedSeparately() {
FreeTierUsageService service = service(500);
- service.accrue(BillingCategory.API, 20, "a".repeat(64));
- service.accrue(BillingCategory.API, 7, "b".repeat(64));
+ service.accrue(BillingCategory.AUTOMATION, 20, "run:0");
+ service.accrue(BillingCategory.AUTOMATION, 7, "run:1");
assertThat(service.balance().usedUnits()).isEqualTo(27);
}
+ @Test
+ void freeTierRebillsCurrentInputsAfterTheDefaultStepAllowance() {
+ FreeTierUsageService service = service(500);
+ for (int step = 0; step < 10; step++) {
+ service.accrue(BillingCategory.AUTOMATION, 3, "run:0");
+ }
+ assertThat(service.balance().usedUnits()).isEqualTo(3);
+
+ service = service(500);
+ service.accrue(BillingCategory.AUTOMATION, 7, "run:0");
+
+ assertThat(service.balance().usedUnits()).isEqualTo(10);
+ }
+
+ @Test
+ void freeTierAndLinkedStepAllowancesStaySeparate() {
+ FreeTierUsageService service = service(500);
+ UsageMeterService cloud =
+ new UsageMeterService(cloudCounters, signatures, new AccountLinkProperties());
+ service.accrue(BillingCategory.AUTOMATION, 3, "run:0");
+ cloud.accrue(T0, BillingCategory.AUTOMATION, 7, "run:0", 1);
+ cloud.accrue(T0, BillingCategory.AUTOMATION, 7, "run:0", 1);
+ service.accrue(BillingCategory.AUTOMATION, 3, "run:0");
+
+ em.clear();
+ assertThat(service.balance().usedUnits()).isEqualTo(3);
+ assertThat(
+ cloudCounters.findAll().stream()
+ .mapToLong(UsageCounter::getCumulativeUnits)
+ .sum())
+ .isEqualTo(14);
+ assertThat(signatures.count()).isEqualTo(2);
+ }
+
@Test
void freeTierSpendIsInvisibleToTheCloudSyncAndSurvivesALinkUnlinkCycle() {
FreeTierUsageService service = service(500);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
index b6261a3382..9d32b4a73d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
@@ -5,24 +5,31 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
-import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
+import java.lang.reflect.Method;
import java.nio.file.Path;
import java.time.LocalDateTime;
+import java.util.List;
import java.util.Optional;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.ObjectProvider;
@@ -31,11 +38,17 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.method.HandlerMethod;
+import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.proprietary.billing.BillingCategory;
import stirling.software.proprietary.billing.UnitCalcPolicy;
+import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
+import stirling.software.proprietary.security.model.User;
@ExtendWith(MockitoExtension.class)
class InstanceEntitlementInterceptorTest {
@@ -51,10 +64,17 @@ class InstanceEntitlementInterceptorTest {
gate, entitlementCache, meterProvider, freeTierUsageService, tempFileManager);
}
+ @AfterEach
+ void clearAuth() {
+ SecurityContextHolder.clearContext();
+ }
+
private boolean preHandle(MockHttpServletResponse response) throws Exception {
return interceptor()
.preHandle(
- new MockHttpServletRequest("GET", "/api/v1/ai/x"), response, new Object());
+ new MockHttpServletRequest("GET", "/api/v1/ai/tools/x"),
+ response,
+ new Object());
}
@Test
@@ -88,7 +108,7 @@ class InstanceEntitlementInterceptorTest {
.thenReturn(GateDecision.allow(GateDecision.Reason.FREE_TIER));
InstanceEntitlementInterceptor interceptor = interceptor();
- MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/x");
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
interceptor.afterCompletion(req, resp, new Object(), null);
@@ -97,6 +117,38 @@ class InstanceEntitlementInterceptorTest {
verifyNoInteractions(entitlementCache, meterProvider);
}
+ @Test
+ void freeTierAutomationUsesTheSourceDocumentKey() throws Exception {
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.FREE_TIER));
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/general/rotate-pdf");
+ req.addHeader("X-Stirling-Automation", "true");
+ req.addHeader("X-Stirling-Run-Id", "run-1");
+ req.addHeader("X-Stirling-Document-Id", "run-1:0");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ verify(freeTierUsageService).accrue(BillingCategory.AUTOMATION, 1L, "run-1:0");
+ verifyNoInteractions(entitlementCache, meterProvider);
+ }
+
+ @Test
+ void freeTierDoesNotMeterFilelessWork() throws Exception {
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.FREE_TIER));
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/tools/x");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ verifyNoInteractions(freeTierUsageService, entitlementCache, meterProvider);
+ }
+
@Test
void manualToolNeverReachesEitherLedger() throws Exception {
when(gate.evaluate(anyBoolean()))
@@ -117,7 +169,7 @@ class InstanceEntitlementInterceptorTest {
.thenReturn(GateDecision.block(GateDecision.Reason.FREE_TIER_EXHAUSTED));
InstanceEntitlementInterceptor interceptor = interceptor();
- MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/x");
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
interceptor.afterCompletion(req, resp, new Object(), null);
@@ -147,13 +199,34 @@ class InstanceEntitlementInterceptorTest {
when(entitlementCache.current()).thenReturn(Optional.of(entitled(policy, period)));
InstanceEntitlementInterceptor interceptor = interceptor();
- MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/x");
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object()); // stashes AI category
interceptor.afterCompletion(req, resp, new Object(), null);
- // No uploaded files → bytes axis → the 1-unit floor; no input identity → null signature.
- verify(meter).accrue(eq(period), eq(BillingCategory.AI), eq(1L), isNull());
+ // A tiny non-PDF input bills the 1-unit byte floor; a standalone op has a null key.
+ verify(meter).accrue(eq(period), eq(BillingCategory.AI), eq(1L), isNull(), eq(10));
+ }
+
+ @Test
+ void doesNotMeterFilelessBillableOp() throws Exception {
+ // A billable op with no document (no multipart file) is not metered - matching SaaS, which
+ // short-circuits a request that carries no file.
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ when(meterProvider.getIfAvailable()).thenReturn(meter);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(entitlementCache.current()).thenReturn(Optional.of(entitled(policy, period)));
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/tools/x");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ verify(meter, never()).accrue(any(), any(), anyLong(), any(), eq(10));
}
@Test
@@ -167,22 +240,48 @@ class InstanceEntitlementInterceptorTest {
UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
when(entitlementCache.current()).thenReturn(Optional.of(entitled(policy, period)));
- // Materialise to a real path under @TempDir; the interceptor writes the upload there and
- // jpdfium + the hasher read it back.
+ // Materialise to a real path under @TempDir; the interceptor writes the PDF there so
+ // jpdfium can read its page count back.
TempFile temp = mock(TempFile.class);
when(temp.getPath()).thenReturn(tmp.resolve("input.bin"));
when(tempFileManager.createManagedTempFile(any())).thenReturn(temp);
InstanceEntitlementInterceptor interceptor = interceptor();
MockMultipartHttpServletRequest req = new MockMultipartHttpServletRequest();
- req.setRequestURI("/api/v1/ai/x");
+ req.setRequestURI("/api/v1/ai/tools/x");
req.addFile(new MockMultipartFile("file", "doc.pdf", "application/pdf", fivePagePdf()));
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
interceptor.afterCompletion(req, resp, new Object(), null);
- // 5 pages + a non-null input-set signature (file ops carry a dedup key).
- verify(meter).accrue(eq(period), eq(BillingCategory.AI), eq(5L), notNull());
+ // 5 pages, and a null key: a standalone op (no run) is its own charge - never deduped.
+ verify(meter).accrue(eq(period), eq(BillingCategory.AI), eq(5L), isNull(), eq(10));
+ }
+
+ @Test
+ void repeatedStandaloneOpsEachCharge() throws Exception {
+ // A standalone op (no run id) has a null key, so identical calls each accrue - matching
+ // SaaS, which never groups a call outside a run ("charge per API call"). The old
+ // input-signature window wrongly collapsed these on the instance.
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ when(meterProvider.getIfAvailable()).thenReturn(meter);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(entitlementCache.current()).thenReturn(Optional.of(entitled(policy, period)));
+ authenticateWithApiKey();
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ for (int call = 0; call < 2; call++) {
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/general/merge");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, toolHandler());
+ interceptor.afterCompletion(req, resp, toolHandler(), null);
+ }
+
+ verify(meter, times(2))
+ .accrue(eq(period), eq(BillingCategory.API), anyLong(), isNull(), eq(10));
}
@Test
@@ -192,7 +291,7 @@ class InstanceEntitlementInterceptorTest {
when(meterProvider.getIfAvailable()).thenReturn(null); // metering.enabled = false
InstanceEntitlementInterceptor interceptor = interceptor();
- MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/x");
+ MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
interceptor.afterCompletion(req, resp, new Object(), null);
@@ -236,6 +335,217 @@ class InstanceEntitlementInterceptorTest {
verifyNoInteractions(meterProvider, freeTierUsageService);
}
+ @Test
+ void billsApiKeyToolCallAsApi() throws Exception {
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ when(meterProvider.getIfAvailable()).thenReturn(meter);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(entitlementCache.current()).thenReturn(Optional.of(entitled(policy, period)));
+ authenticateWithApiKey();
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/general/merge");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, toolHandler());
+ interceptor.afterCompletion(req, resp, toolHandler(), null);
+
+ verify(meter).accrue(eq(period), eq(BillingCategory.API), eq(1L), isNull(), eq(10));
+ }
+
+ @Test
+ void doesNotBillApiKeyCallToNonToolEndpoint() throws Exception {
+ // Matches SaaS: an API-key call to a non-tool endpoint (no @AutoJobPostMapping) is not
+ // billed. Only tool operations count as API usage.
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ authenticateWithApiKey();
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockHttpServletRequest req =
+ new MockHttpServletRequest("GET", "/api/v1/general/files/some-id");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, plainHandler());
+ interceptor.afterCompletion(req, resp, plainHandler(), null);
+
+ verifyNoInteractions(meterProvider, freeTierUsageService);
+ }
+
+ @Test
+ void policyRunSubStepsAccrueUnderTheSharedRunId() throws Exception {
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ when(meterProvider.getIfAvailable()).thenReturn(meter);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(entitlementCache.current())
+ .thenReturn(
+ Optional.of(
+ new InstanceEntitlement(
+ true,
+ 0,
+ 0,
+ 100L,
+ EntitlementState.OK,
+ policy,
+ period,
+ period.plusMonths(1),
+ null,
+ 20)));
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ for (int step = 0; step < 3; step++) {
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/general/merge");
+ req.addHeader("X-Stirling-Automation", "true");
+ req.addHeader("X-Stirling-Run-Id", "run-1");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+ }
+
+ verify(meter, times(3))
+ .accrue(eq(period), eq(BillingCategory.AUTOMATION), anyLong(), eq("run-1"), eq(20));
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {400, 422, 500})
+ void failedResponsesDoNotConsumeStepAllowance(int status) {
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ response.setStatus(status);
+
+ interceptor()
+ .afterCompletion(
+ fileRequest("/api/v1/general/merge"), response, new Object(), null);
+
+ verifyNoInteractions(meterProvider);
+ }
+
+ @Test
+ void failedRequestsDoNotConsumeStepAllowance() {
+ interceptor()
+ .afterCompletion(
+ fileRequest("/api/v1/general/merge"),
+ new MockHttpServletResponse(),
+ new Object(),
+ new IllegalStateException("failed"));
+
+ verifyNoInteractions(meterProvider);
+ }
+
+ @Test
+ void forgedRunIdWithoutAutomationHeaderIsIgnored() throws Exception {
+ // A raw API-key caller that sets X-Stirling-Run-Id but not the automation header must not
+ // be
+ // able to group its separate calls into one charge: the run id keys the meter only on a
+ // genuine internal dispatch, so here the op falls back to its standalone null key.
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ when(meterProvider.getIfAvailable()).thenReturn(meter);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(entitlementCache.current()).thenReturn(Optional.of(entitled(policy, period)));
+ authenticateWithApiKey();
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/general/merge");
+ req.addHeader("X-Stirling-Run-Id", "forged");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, toolHandler());
+ interceptor.afterCompletion(req, resp, toolHandler(), null);
+
+ verify(meter).accrue(eq(period), eq(BillingCategory.API), anyLong(), isNull(), eq(10));
+ }
+
+ @Test
+ void multiDocumentRunChargesPerDocumentNotPerRun() throws Exception {
+ // Two source documents in one run carry distinct document ids, so each accrues under its
+ // own
+ // key: the meter collapses a document's steps but bills the documents separately (matching
+ // SaaS per-document lineage), rather than collapsing the whole run to a single charge.
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ when(meterProvider.getIfAvailable()).thenReturn(meter);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(entitlementCache.current()).thenReturn(Optional.of(entitled(policy, period)));
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ for (String docId : List.of("run-1:0", "run-1:0", "run-1:1")) {
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/general/merge");
+ req.addHeader("X-Stirling-Automation", "true");
+ req.addHeader("X-Stirling-Run-Id", "run-1");
+ req.addHeader("X-Stirling-Document-Id", docId);
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+ }
+
+ // Keyed on the document id, not the run id: document run-1:0's two steps both accrue under
+ // it (the meter dedups them), and run-1:1 accrues under its own key.
+ verify(meter, times(2))
+ .accrue(
+ eq(period),
+ eq(BillingCategory.AUTOMATION),
+ anyLong(),
+ eq("run-1:0"),
+ eq(10));
+ verify(meter)
+ .accrue(
+ eq(period),
+ eq(BillingCategory.AUTOMATION),
+ anyLong(),
+ eq("run-1:1"),
+ eq(10));
+ }
+
+ private static MockMultipartHttpServletRequest fileRequest(String uri) {
+ MockMultipartHttpServletRequest req = new MockMultipartHttpServletRequest();
+ req.setRequestURI(uri);
+ // A tiny non-PDF part: no page-count temp needed, and it bills the 1-unit byte floor.
+ req.addFile(
+ new MockMultipartFile(
+ "fileInput", "doc.bin", "application/octet-stream", "x".getBytes()));
+ return req;
+ }
+
+ private static void authenticateWithApiKey() {
+ ApiKeyAuthenticationToken token =
+ new ApiKeyAuthenticationToken(
+ new User(),
+ "test-api-key",
+ List.of(new SimpleGrantedAuthority("ROLE_API")));
+ SecurityContextHolder.getContext().setAuthentication(token);
+ }
+
+ private static HandlerMethod toolHandler() {
+ return handlerMethod("tool");
+ }
+
+ private static HandlerMethod plainHandler() {
+ return handlerMethod("plain");
+ }
+
+ private static HandlerMethod handlerMethod(String name) {
+ try {
+ Method m = Fixture.class.getDeclaredMethod(name);
+ return new HandlerMethod(new Fixture(), m);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ static class Fixture {
+ @AutoJobPostMapping(value = "/tool", resourceWeight = 1)
+ public void tool() {}
+
+ public void plain() {}
+ }
+
private static InstanceEntitlement entitled(UnitCalcPolicy policy, LocalDateTime period) {
return new InstanceEntitlement(
true, 0, 0, 100L, EntitlementState.OK, policy, period, period.plusMonths(1), null);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java
new file mode 100644
index 0000000000..17e9d310a8
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java
@@ -0,0 +1,259 @@
+package stirling.software.proprietary.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.IntStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.ResponseEntity;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.mock.web.MockMultipartHttpServletRequest;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.MultiValueMap;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.AutomationRunContext;
+import stirling.software.common.service.InternalApiClient;
+import stirling.software.common.service.ToolMetadataService;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
+import stirling.software.proprietary.billing.UnitCalcPolicy;
+import stirling.software.proprietary.policy.engine.PolicyExecutionResult;
+import stirling.software.proprietary.policy.engine.PolicyExecutor;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.model.PipelineDefinition;
+import stirling.software.proprietary.policy.model.PipelineStep;
+import stirling.software.proprietary.policy.model.PolicyInputs;
+import stirling.software.proprietary.policy.progress.PolicyProgressListener;
+
+import tools.jackson.databind.json.JsonMapper;
+
+/** Exercises workflow file propagation through the real interceptor and persisted usage meter. */
+@DataJpaTest(showSql = false)
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
+@ExtendWith(MockitoExtension.class)
+class PolicyAutomationBillingDbTest {
+
+ private static final String ROTATE = "/api/v1/general/rotate-pdf";
+ private static final String SPLIT = "/api/v1/general/split-pages";
+ private static final String MERGE = "/api/v1/general/merge-pdfs";
+ private static final LocalDateTime PERIOD = LocalDateTime.of(2026, 6, 1, 0, 0);
+
+ @Autowired private UsageCounterRepository counters;
+ @Autowired private MeteredInputSignatureRepository signatures;
+ @Mock private InternalApiClient internalApiClient;
+ @Mock private ToolMetadataService metadata;
+ @Mock private InstanceEntitlementGate gate;
+ @Mock private FreeTierUsageService freeTierUsageService;
+ @Mock private EntitlementCache entitlementCache;
+ @Mock private ObjectProvider<UsageMeterService> meterProvider;
+ @TempDir Path tempDir;
+
+ private PolicyExecutor executor;
+ private InstanceEntitlementInterceptor interceptor;
+
+ @BeforeEach
+ void setUp() throws IOException {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
+ TempFileManager tempFiles = new TempFileManager(new TempFileRegistry(), properties);
+ executor =
+ new PolicyExecutor(
+ internalApiClient, metadata, tempFiles, JsonMapper.builder().build());
+ interceptor =
+ new InstanceEntitlementInterceptor(
+ gate, entitlementCache, meterProvider, freeTierUsageService, tempFiles);
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ when(meterProvider.getIfAvailable())
+ .thenReturn(
+ new UsageMeterService(counters, signatures, new AccountLinkProperties()));
+ when(metadata.isMultiInput(anyString()))
+ .thenAnswer(invocation -> MERGE.equals(invocation.getArgument(0)));
+ when(metadata.shouldUnpackZipResponse(anyString()))
+ .thenAnswer(invocation -> SPLIT.equals(invocation.getArgument(0)));
+ when(internalApiClient.post(anyString(), any()))
+ .thenAnswer(
+ invocation ->
+ dispatch(invocation.getArgument(0), invocation.getArgument(1)));
+ }
+
+ @AfterEach
+ void cleanUp() {
+ counters.deleteAllInBatch();
+ signatures.deleteAllInBatch();
+ }
+
+ @Test
+ void splitProcessAndRemergeBillsTheOriginalDocumentOnce() throws IOException {
+ PolicyExecutionResult result = execute(1, 20, SPLIT, ROTATE, MERGE, ROTATE);
+
+ assertThat(totalUnits()).isEqualTo(1);
+ assertThat(signatures.count()).isEqualTo(1);
+ assertThat(stepCount("run:0")).isEqualTo(5);
+ assertThat(result.origins()).containsExactly(0);
+ }
+
+ @Test
+ void processedDocumentsKeepTheirBillingGroupThroughMergesAndSplits() throws IOException {
+ PolicyExecutionResult result = execute(2, 20, ROTATE, MERGE, SPLIT, ROTATE, MERGE);
+
+ assertThat(totalUnits()).isEqualTo(2);
+ assertThat(signatures.count()).isEqualTo(2);
+ assertThat(stepCount("run:0")).isEqualTo(1);
+ assertThat(stepCount("run:1")).isEqualTo(6);
+ assertThat(result.origins()).hasSize(1).containsOnlyNulls();
+ }
+
+ @Test
+ void mergingFirstStillBillsAllOriginalInputs() throws IOException {
+ PolicyExecutionResult result = execute(2, 20, MERGE, SPLIT, ROTATE, MERGE);
+
+ assertThat(totalUnits()).isEqualTo(2);
+ assertThat(signatures.count()).isEqualTo(1);
+ assertThat(stepCount("run:1")).isEqualTo(5);
+ assertThat(result.origins()).hasSize(1).containsOnlyNulls();
+ }
+
+ @Test
+ void mergeAtTheStepLimitBillsItsCurrentInputs() throws IOException {
+ execute(1, 3, SPLIT, ROTATE, MERGE, ROTATE);
+
+ assertThat(totalUnits()).isEqualTo(3);
+ assertThat(signatures.count()).isEqualTo(1);
+ assertThat(stepCount("run:0")).isEqualTo(2);
+ }
+
+ private PolicyExecutionResult execute(int inputCount, int stepLimit, String... operations)
+ throws IOException {
+ when(entitlementCache.current())
+ .thenReturn(
+ Optional.of(
+ new InstanceEntitlement(
+ true,
+ 100,
+ 0,
+ null,
+ EntitlementState.OK,
+ new UnitCalcPolicy(25, 1024, 1, 1000),
+ PERIOD,
+ PERIOD.plusMonths(1),
+ null,
+ stepLimit)));
+ List<Resource> inputs =
+ IntStream.range(0, inputCount)
+ .mapToObj(
+ index -> file("input-" + index + ".bin", new byte[] {(byte) index}))
+ .toList();
+ PipelineDefinition definition =
+ new PipelineDefinition(
+ "test",
+ Arrays.stream(operations)
+ .map(operation -> new PipelineStep(operation, Map.of()))
+ .toList(),
+ OutputSpec.inline());
+ PolicyExecutionResult result;
+ try (AutomationRunContext.Scope run = AutomationRunContext.open("run")) {
+ result =
+ executor.execute(
+ definition, PolicyInputs.of(inputs), PolicyProgressListener.NOOP);
+ assertThat(AutomationRunContext.currentDocument()).isNull();
+ }
+ return result;
+ }
+
+ private ResponseEntity<Resource> dispatch(String operation, MultiValueMap<String, Object> body)
+ throws Exception {
+ MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
+ request.setRequestURI(operation);
+ request.addHeader(InternalApiClient.AUTOMATION_HEADER, "true");
+ request.addHeader(AutomationRunContext.RUN_ID_HEADER, AutomationRunContext.current());
+ String documentId = AutomationRunContext.currentDocument();
+ if (documentId != null) {
+ request.addHeader(AutomationRunContext.DOCUMENT_ID_HEADER, documentId);
+ }
+ for (Object input : body.get("fileInput")) {
+ Resource resource = (Resource) input;
+ try (var stream = resource.getInputStream()) {
+ request.addFile(
+ new MockMultipartFile(
+ "fileInput",
+ resource.getFilename(),
+ "application/octet-stream",
+ stream));
+ }
+ }
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ assertThat(interceptor.preHandle(request, response, this)).isTrue();
+ Resource output =
+ switch (operation) {
+ case SPLIT -> splitOutput();
+ case MERGE -> file("merged.bin", new byte[] {1, 2});
+ default -> (Resource) body.getFirst("fileInput");
+ };
+ interceptor.afterCompletion(request, response, this, null);
+ return ResponseEntity.ok(output);
+ }
+
+ private static Resource splitOutput() throws IOException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
+ for (int index = 0; index < 2; index++) {
+ zip.putNextEntry(new ZipEntry("part-" + index + ".bin"));
+ zip.write(index);
+ zip.closeEntry();
+ }
+ }
+ return file("split.zip", bytes.toByteArray());
+ }
+
+ private static Resource file(String name, byte[] content) {
+ return new ByteArrayResource(content) {
+ @Override
+ public String getFilename() {
+ return name;
+ }
+ };
+ }
+
+ private long totalUnits() {
+ return counters.findAll().stream().mapToLong(UsageCounter::getCumulativeUnits).sum();
+ }
+
+ private Integer stepCount(String key) {
+ return signatures.findByPeriodStartAndSignature(PERIOD, key).orElseThrow().getStepCount();
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage
+ static class TestApp {}
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageMeterServiceDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageMeterServiceDbTest.java
new file mode 100644
index 0000000000..02850b0871
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageMeterServiceDbTest.java
@@ -0,0 +1,172 @@
+package stirling.software.proprietary.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import stirling.software.proprietary.billing.BillingCategory;
+
+@DataJpaTest(showSql = false)
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
+class UsageMeterServiceDbTest {
+
+ private static final LocalDateTime PERIOD = LocalDateTime.of(2026, 6, 1, 0, 0);
+
+ @Autowired private UsageCounterRepository counters;
+ @Autowired private MeteredInputSignatureRepository signatures;
+ @Autowired private JdbcTemplate jdbc;
+
+ private UsageMeterService meter;
+
+ @BeforeEach
+ void setUp() {
+ meter = new UsageMeterService(counters, signatures, new AccountLinkProperties());
+ }
+
+ @AfterEach
+ void cleanUp() {
+ counters.deleteAllInBatch();
+ signatures.deleteAllInBatch();
+ }
+
+ @Test
+ void stepAfterLimitChargesItsCurrentInputsAndStartsAnotherGroup() {
+ for (int step = 0; step < 20; step++) {
+ accrue("run:0", 3, 20);
+ }
+ assertThat(totalUnits()).isEqualTo(3);
+
+ meter = new UsageMeterService(counters, signatures, new AccountLinkProperties());
+ accrue("run:0", 7, 20);
+ assertThat(totalUnits()).isEqualTo(10);
+ assertThat(state("run:0").getStepCount()).isEqualTo(1);
+
+ for (int step = 0; step < 19; step++) {
+ accrue("run:0", 9, 20);
+ }
+ assertThat(totalUnits()).isEqualTo(10);
+ accrue("run:0", 2, 20);
+ assertThat(totalUnits()).isEqualTo(12);
+ }
+
+ @Test
+ void eachDocumentHasItsOwnStepAllowance() {
+ accrue("run:0", 3, 2);
+ accrue("run:1", 5, 2);
+ accrue("run:0", 3, 2);
+ accrue("run:1", 5, 2);
+ assertThat(totalUnits()).isEqualTo(8);
+
+ accrue("run:0", 7, 2);
+ assertThat(totalUnits()).isEqualTo(15);
+ assertThat(state("run:1").getStepCount()).isEqualTo(2);
+ }
+
+ @Test
+ void expiredWindowResetsTheStepAllowance() {
+ signatures.saveAndFlush(
+ new MeteredInputSignature(PERIOD, "run:0", LocalDateTime.now().minusMinutes(10)));
+
+ accrue("run:0", 3, 2);
+ accrue("run:0", 7, 2);
+ assertThat(totalUnits()).isEqualTo(3);
+ accrue("run:0", 5, 2);
+ assertThat(totalUnits()).isEqualTo(8);
+ }
+
+ @Test
+ void legacyRowsCountAsOnePreviouslyChargedStep() {
+ signatures.saveAndFlush(new MeteredInputSignature(PERIOD, "run:0", LocalDateTime.now()));
+ jdbc.update(
+ "UPDATE account_link_metered_signature SET step_count = NULL, last_metered_at = NULL");
+
+ accrue("run:0", 3, 2);
+ assertThat(totalUnits()).isZero();
+ assertThat(state("run:0").getStepCount()).isEqualTo(2);
+ accrue("run:0", 7, 2);
+ assertThat(totalUnits()).isEqualTo(7);
+ }
+
+ @Test
+ void missingAndNonPositiveLimitsUseTenSteps() {
+ for (int step = 0; step < 10; step++) {
+ accrue("run:0", 1, 0);
+ }
+ assertThat(totalUnits()).isEqualTo(1);
+ accrue("run:0", 1, -1);
+ assertThat(totalUnits()).isEqualTo(2);
+ }
+
+ @Test
+ void limitOfOneChargesEverySuccessfulStep() {
+ accrue("run:0", 3, 1);
+ accrue("run:0", 5, 1);
+ accrue("run:0", 7, 1);
+ assertThat(totalUnits()).isEqualTo(15);
+ assertThat(state("run:0").getStepCount()).isEqualTo(1);
+ }
+
+ @Test
+ void standaloneCallsAlwaysCharge() {
+ accrue(null, 3, 20);
+ accrue(null, 3, 20);
+ assertThat(totalUnits()).isEqualTo(6);
+ assertThat(signatures.count()).isZero();
+ }
+
+ @Test
+ void concurrentCompletionsCountEveryStepAndChargeEachGroupOnce() throws Exception {
+ CountDownLatch start = new CountDownLatch(1);
+ try (var executor = Executors.newFixedThreadPool(4)) {
+ List<Future<?>> futures = new ArrayList<>();
+ for (int step = 0; step < 40; step++) {
+ futures.add(
+ executor.submit(
+ () -> {
+ assertThat(start.await(10, TimeUnit.SECONDS)).isTrue();
+ accrue("run:0", 1, 5);
+ return null;
+ }));
+ }
+ start.countDown();
+ for (Future<?> future : futures) {
+ future.get(30, TimeUnit.SECONDS);
+ }
+ }
+ assertThat(totalUnits()).isEqualTo(8);
+ assertThat(state("run:0").getStepCount()).isEqualTo(5);
+ }
+
+ private void accrue(String key, long units, int stepLimit) {
+ meter.accrue(PERIOD, BillingCategory.AUTOMATION, units, key, stepLimit);
+ }
+
+ private long totalUnits() {
+ return counters.findAll().stream().mapToLong(UsageCounter::getCumulativeUnits).sum();
+ }
+
+ private MeteredInputSignature state(String key) {
+ return signatures.findByPeriodStartAndSignature(PERIOD, key).orElseThrow();
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage
+ static class TestApp {}
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageMeterServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageMeterServiceTest.java
index 0c9ad2c62e..74ca6e13c3 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageMeterServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageMeterServiceTest.java
@@ -77,8 +77,6 @@ class UsageMeterServiceTest {
@Test
void chargesNewSignatureThenAccrues() {
- when(signatureRepo.findByPeriodStartAndSignature(period, "op-sig-new"))
- .thenReturn(Optional.empty());
when(repo.increment(eq(period), eq("AI"), eq(5L), any())).thenReturn(1);
service.accrue(period, BillingCategory.AI, 5, "op-sig-new");
@@ -88,46 +86,57 @@ class UsageMeterServiceTest {
}
@Test
- void skipsConcurrentDuplicateClaim() {
- // Unseen this period, but a concurrent op wins the insert first → treated as within-window
- // chaining, not re-charged.
+ void countsSuccessfulStepWhenAnotherCompletionWinsTheInsert() {
when(signatureRepo.findByPeriodStartAndSignature(period, "op-sig-race"))
- .thenReturn(Optional.empty());
+ .thenReturn(
+ Optional.of(
+ new MeteredInputSignature(
+ period, "op-sig-race", LocalDateTime.now())));
when(signatureRepo.saveAndFlush(any()))
.thenThrow(new DataIntegrityViolationException("dup"));
+ when(signatureRepo.joinIfWithinLimit(eq(period), eq("op-sig-race"), any(), any(), eq(10)))
+ .thenReturn(0, 1);
service.accrue(period, BillingCategory.AI, 5, "op-sig-race");
verify(repo, never()).increment(any(), any(), anyLong(), any());
verify(repo, never()).saveAndFlush(any());
+ verify(signatureRepo, times(2))
+ .joinIfWithinLimit(eq(period), eq("op-sig-race"), any(), any(), eq(10));
}
@Test
void skipsRepeatWithinWorkflowWindow() {
- // Same input set seen moments ago → chaining → not re-charged; the window slides.
- MeteredInputSignature recent =
- new MeteredInputSignature(period, "op-sig", LocalDateTime.now());
- when(signatureRepo.findByPeriodStartAndSignature(period, "op-sig"))
- .thenReturn(Optional.of(recent));
+ when(signatureRepo.joinIfWithinLimit(eq(period), eq("op-sig"), any(), any(), eq(10)))
+ .thenReturn(1);
service.accrue(period, BillingCategory.AI, 5, "op-sig");
verify(repo, never()).increment(any(), any(), anyLong(), any());
- verify(signatureRepo).save(recent); // window touched
+ verify(signatureRepo, never()).saveAndFlush(any());
}
@Test
void chargesRepeatOutsideWorkflowWindow() {
- // Same input set last seen well past the 5-minute window → an independent re-run → charged.
- MeteredInputSignature stale =
- new MeteredInputSignature(period, "op-sig", LocalDateTime.now().minusMinutes(10));
- when(signatureRepo.findByPeriodStartAndSignature(period, "op-sig"))
- .thenReturn(Optional.of(stale));
+ when(signatureRepo.restartIfFullOrExpired(eq(period), eq("op-sig"), any(), any(), eq(10)))
+ .thenReturn(1);
when(repo.increment(eq(period), eq("AI"), eq(5L), any())).thenReturn(1);
service.accrue(period, BillingCategory.AI, 5, "op-sig");
verify(repo).increment(eq(period), eq("AI"), eq(5L), any());
- verify(signatureRepo).save(stale); // window touched
+ verify(signatureRepo, never()).saveAndFlush(any());
+ }
+
+ @Test
+ void doesNotRetryUnrelatedIntegrityFailures() {
+ when(signatureRepo.saveAndFlush(any()))
+ .thenThrow(new DataIntegrityViolationException("invalid key"));
+ when(repo.increment(eq(period), eq("AUTOMATION"), eq(5L), any())).thenReturn(1);
+
+ service.accrue(period, BillingCategory.AUTOMATION, 5, "invalid-key", 20);
+
+ verify(signatureRepo).saveAndFlush(any());
+ verify(repo).increment(eq(period), eq("AUTOMATION"), eq(5L), any());
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBillerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBillerTest.java
new file mode 100644
index 0000000000..148ba04bec
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBillerTest.java
@@ -0,0 +1,116 @@
+package stirling.software.proprietary.automation;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Optional;
+
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentMatchers;
+import org.springframework.beans.factory.ObjectProvider;
+
+import stirling.software.proprietary.accountlink.EntitlementCache;
+import stirling.software.proprietary.accountlink.EntitlementState;
+import stirling.software.proprietary.accountlink.InstanceEntitlement;
+import stirling.software.proprietary.accountlink.UsageMeterService;
+import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
+import stirling.software.proprietary.billing.UnitCalcPolicy;
+
+class AccountLinkAutomationRunBillerTest {
+
+ private static final UnitCalcPolicy POLICY = new UnitCalcPolicy(10, 1_000_000L, 1, 1000);
+ private static final LocalDateTime PERIOD = LocalDateTime.of(2026, 9, 1, 0, 0);
+
+ @SuppressWarnings("unchecked")
+ private static ObjectProvider<UsageMeterService> providerOf(UsageMeterService meter) {
+ ObjectProvider<UsageMeterService> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(meter);
+ return provider;
+ }
+
+ private static InstanceEntitlement entitlement(UnitCalcPolicy policy, LocalDateTime period) {
+ return new InstanceEntitlement(
+ true, 0L, 0L, null, EntitlementState.OK, policy, period, null, null);
+ }
+
+ @Test
+ void accruesComputedUnitsAsAutomation() {
+ EntitlementCache cache = mock(EntitlementCache.class);
+ when(cache.current()).thenReturn(Optional.of(entitlement(POLICY, PERIOD)));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ AccountLinkAutomationRunBiller biller =
+ new AccountLinkAutomationRunBiller(cache, providerOf(meter));
+
+ // 25 pages -> ceil(25/10)=3 page units; 5000 bytes -> 1 byte unit; max = 3.
+ biller.recordAutomationRun(List.of(new FileSize(25, 5000L)));
+
+ verify(meter).accrue(PERIOD, BillingCategory.AUTOMATION, 3L, null);
+ }
+
+ @Test
+ void noAccrueWhenMeterAbsent() {
+ EntitlementCache cache = mock(EntitlementCache.class);
+ AccountLinkAutomationRunBiller biller =
+ new AccountLinkAutomationRunBiller(cache, providerOf(null));
+
+ biller.recordAutomationRun(List.of(new FileSize(1, 10L)));
+
+ verify(cache, never()).current();
+ }
+
+ @Test
+ void noAccrueWhenEntitlementUnknown() {
+ EntitlementCache cache = mock(EntitlementCache.class);
+ when(cache.current()).thenReturn(Optional.empty());
+ UsageMeterService meter = mock(UsageMeterService.class);
+ AccountLinkAutomationRunBiller biller =
+ new AccountLinkAutomationRunBiller(cache, providerOf(meter));
+
+ biller.recordAutomationRun(List.of(new FileSize(1, 10L)));
+
+ verify(meter, never())
+ .accrue(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.anyLong(),
+ ArgumentMatchers.any());
+ }
+
+ @Test
+ void noAccrueWhenPeriodOrPolicyMissing() {
+ EntitlementCache cache = mock(EntitlementCache.class);
+ when(cache.current())
+ .thenReturn(Optional.of(entitlement(POLICY, null)))
+ .thenReturn(Optional.of(entitlement(null, PERIOD)));
+ UsageMeterService meter = mock(UsageMeterService.class);
+ AccountLinkAutomationRunBiller biller =
+ new AccountLinkAutomationRunBiller(cache, providerOf(meter));
+
+ biller.recordAutomationRun(List.of(new FileSize(1, 10L)));
+ biller.recordAutomationRun(List.of(new FileSize(1, 10L)));
+
+ verify(meter, never())
+ .accrue(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.anyLong(),
+ ArgumentMatchers.any());
+ }
+
+ @Test
+ void noAccrueForEmptyInputs() {
+ EntitlementCache cache = mock(EntitlementCache.class);
+ UsageMeterService meter = mock(UsageMeterService.class);
+ AccountLinkAutomationRunBiller biller =
+ new AccountLinkAutomationRunBiller(cache, providerOf(meter));
+
+ biller.recordAutomationRun(List.of());
+
+ verify(cache, never()).current();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/automation/AutomationMeterControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/automation/AutomationMeterControllerTest.java
new file mode 100644
index 0000000000..5190a613d7
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/automation/AutomationMeterControllerTest.java
@@ -0,0 +1,121 @@
+package stirling.software.proprietary.automation;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.stream.IntStream;
+
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.http.HttpStatus;
+import org.springframework.mock.web.MockHttpServletRequest;
+
+import stirling.software.proprietary.audit.AuditContext;
+import stirling.software.proprietary.automation.AutomationMeterController.AutomationMeterRequest;
+import stirling.software.proprietary.automation.AutomationMeterController.InputDoc;
+import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
+
+class AutomationMeterControllerTest {
+
+ @SuppressWarnings("unchecked")
+ private static ObjectProvider<AutomationRunBiller> providerOf(AutomationRunBiller biller) {
+ ObjectProvider<AutomationRunBiller> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(biller);
+ return provider;
+ }
+
+ private static AutomationMeterRequest req(List<InputDoc> inputs) {
+ return new AutomationMeterRequest("My run", List.of("compress", "rotate"), inputs);
+ }
+
+ @Test
+ void billsInputsAndStampsAudit() {
+ AutomationRunBiller biller = mock(AutomationRunBiller.class);
+ AutomationMeterController controller = new AutomationMeterController(providerOf(biller));
+ MockHttpServletRequest http = new MockHttpServletRequest();
+
+ var response =
+ controller.meterAutomationRun(
+ req(List.of(new InputDoc(3, 1000L), new InputDoc(0, 2048L))), http);
+
+ assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());
+ ArgumentCaptor<List<FileSize>> captor = ArgumentCaptor.forClass(List.class);
+ verify(biller).recordAutomationRun(captor.capture());
+ assertEquals(List.of(new FileSize(3, 1000L), new FileSize(0, 2048L)), captor.getValue());
+ assertEquals("My run", http.getAttribute(AuditContext.REQ_ATTR_POLICY_NAME));
+ assertEquals(
+ List.of("compress", "rotate"),
+ http.getAttribute(AuditContext.REQ_ATTR_POLICY_STEPS));
+ }
+
+ @Test
+ void emptyInputsDoesNotBill() {
+ AutomationRunBiller biller = mock(AutomationRunBiller.class);
+ AutomationMeterController controller = new AutomationMeterController(providerOf(biller));
+
+ var response = controller.meterAutomationRun(req(List.of()), new MockHttpServletRequest());
+
+ assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());
+ verify(biller, never()).recordAutomationRun(org.mockito.ArgumentMatchers.anyList());
+ }
+
+ @Test
+ void nullBodyIsAccepted() {
+ AutomationRunBiller biller = mock(AutomationRunBiller.class);
+ AutomationMeterController controller = new AutomationMeterController(providerOf(biller));
+
+ var response = controller.meterAutomationRun(null, new MockHttpServletRequest());
+
+ assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());
+ verify(biller, never()).recordAutomationRun(org.mockito.ArgumentMatchers.anyList());
+ }
+
+ @Test
+ void noBillerBeanStillAccepts() {
+ AutomationMeterController controller = new AutomationMeterController(providerOf(null));
+
+ var response =
+ controller.meterAutomationRun(
+ req(List.of(new InputDoc(1, 10L))), new MockHttpServletRequest());
+
+ assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());
+ }
+
+ @Test
+ void billingExceptionIsSwallowed() {
+ AutomationRunBiller biller = mock(AutomationRunBiller.class);
+ org.mockito.Mockito.doThrow(new RuntimeException("boom"))
+ .when(biller)
+ .recordAutomationRun(org.mockito.ArgumentMatchers.anyList());
+ AutomationMeterController controller = new AutomationMeterController(providerOf(biller));
+
+ var response =
+ controller.meterAutomationRun(
+ req(List.of(new InputDoc(1, 10L))), new MockHttpServletRequest());
+
+ assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());
+ }
+
+ @Test
+ void clampsNegativesAndCapsInputCount() {
+ AutomationRunBiller biller = mock(AutomationRunBiller.class);
+ AutomationMeterController controller = new AutomationMeterController(providerOf(biller));
+
+ List<InputDoc> many =
+ IntStream.range(0, 10_050).mapToObj(i -> new InputDoc(-5, -1L)).toList();
+ controller.meterAutomationRun(
+ new AutomationMeterRequest(null, null, many), new MockHttpServletRequest());
+
+ ArgumentCaptor<List<FileSize>> captor = ArgumentCaptor.forClass(List.class);
+ verify(biller).recordAutomationRun(captor.capture());
+ List<FileSize> billed = captor.getValue();
+ assertEquals(10_000, billed.size());
+ assertTrue(billed.stream().allMatch(f -> f.pages() == 0 && f.bytes() == 0L));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
index 6e2ab66df7..d31183337f 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
@@ -2,6 +2,7 @@ package stirling.software.proprietary.policy.engine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -39,6 +40,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.AutomationRunContext;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
@@ -378,6 +380,35 @@ class PolicyExecutorTest {
return new PipelineDefinition("test", List.of(steps), OutputSpec.inline());
}
+ @Test
+ void perFileStepScopesADistinctDocumentIdForEachFile() throws IOException {
+ // Within a run over several documents, each file's dispatch carries a distinct, run-scoped
+ // document id so a linked instance bills each source document once - not the whole run
+ // once.
+ when(toolMetadataService.isMultiInput(ROTATE)).thenReturn(false);
+ when(toolMetadataService.shouldUnpackZipResponse(ROTATE)).thenReturn(false);
+ List<String> docIds = new ArrayList<>();
+ when(internalApiClient.post(eq(ROTATE), any()))
+ .thenAnswer(
+ inv -> {
+ docIds.add(AutomationRunContext.currentDocument());
+ return ResponseEntity.ok(pdf("rotated", "rotated.pdf"));
+ });
+
+ try (AutomationRunContext.Scope run = AutomationRunContext.open("run-x")) {
+ executor.execute(
+ definition(new PipelineStep(ROTATE, Map.of())),
+ PolicyInputs.of(List.of(pdf("a", "a.pdf"), pdf("b", "b.pdf"))),
+ PolicyProgressListener.NOOP);
+ }
+
+ assertEquals(2, docIds.size());
+ assertNotNull(docIds.get(0));
+ assertNotNull(docIds.get(1));
+ assertNotEquals(docIds.get(0), docIds.get(1)); // distinct per source document
+ assertTrue(docIds.get(0).startsWith("run-x:")); // run-scoped
+ }
+
private void stubEndpoint(String endpoint, Resource body) {
when(internalApiClient.post(eq(endpoint), any())).thenReturn(ResponseEntity.ok(body));
}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java
index 501aad7316..2f9e6a851f 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java
@@ -29,6 +29,7 @@ import stirling.software.saas.payg.entitlement.EntitlementSnapshot;
import stirling.software.saas.payg.instance.InstanceUsageIngestService;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.EntitlementState;
+import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.policy.PricingPolicy;
import stirling.software.saas.payg.policy.PricingPolicyService;
import stirling.software.saas.repository.SaasTeamExtensionsRepository;
@@ -102,7 +103,8 @@ public class InstanceController {
// counters on the [periodStart, periodEnd) boundary.
UnitCalcPolicy unitCalcPolicy,
LocalDateTime periodStart,
- LocalDateTime periodEnd) {}
+ LocalDateTime periodEnd,
+ int automationStepLimit) {}
@GetMapping("/whoami")
@PreAuthorize("hasRole('LINKED_INSTANCE')")
@@ -227,7 +229,8 @@ public class InstanceController {
policy.getMinChargeUnits(),
policy.getFileUnitCap()),
snap.periodStart(),
- snap.periodEnd());
+ snap.periodEnd(),
+ policy.resolveStepLimit(JobSource.PIPELINE));
}
/**
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java b/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java
index 99255966b4..5250847269 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java
@@ -28,7 +28,6 @@ import stirling.software.saas.payg.job.JoinOrOpenResult;
import stirling.software.saas.payg.job.ProcessingJob;
import stirling.software.saas.payg.meter.PaygMeterReportingService;
import stirling.software.saas.payg.model.BillingCategory;
-import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStatus;
import stirling.software.saas.payg.model.LedgerBucket;
import stirling.software.saas.payg.model.LedgerEntryType;
@@ -114,7 +113,7 @@ public class JobChargeService {
}
PricingPolicy policy = policyService.getEffectivePolicy(ctx.ownerTeamId());
- int stepLimit = resolveStepLimit(policy, ctx.source());
+ int stepLimit = policy.resolveStepLimit(ctx.source());
JobContext jobCtx =
new JobContext(
@@ -181,7 +180,7 @@ public class JobChargeService {
PricingPolicy policy = policyService.getEffectivePolicy(ctx.ownerTeamId());
int chargeUnits = Math.max(units, policy.getMinChargeUnits());
- int stepLimit = resolveStepLimit(policy, ctx.source());
+ int stepLimit = policy.resolveStepLimit(ctx.source());
JobContext jobCtx =
new JobContext(
@@ -341,22 +340,6 @@ public class JobChargeService {
ledgerRepository.save(entry);
}
- private int resolveStepLimit(PricingPolicy policy, JobSource source) {
- Integer fromPolicy =
- policy.getStepLimits() == null ? null : policy.getStepLimits().get(source);
- if (fromPolicy != null && fromPolicy > 0) {
- return fromPolicy;
- }
- // Defensive default — every JobSource should have an entry per the V12 seed, but a
- // hand-edited policy could be missing one. Fall back to the smallest documented limit
- // (10 — WEB/API/DESKTOP_APP default) so an admin slip-up never spawns unbounded chains.
- log.debug(
- "PricingPolicy {} missing stepLimit for source={}; using fallback of 10.",
- policy.getId(),
- source);
- return 10;
- }
-
private int computeUnits(List<JobInput> inputs, PricingPolicy policy) {
List<MultipartFile> multiparts = inputs.stream().map(JobInput::multipart).toList();
// Reuse the temp file the caller already wrote (in PaygChargeInterceptor.preHandle for
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasClassificationRunBiller.java b/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasAutomationRunBiller.java
similarity index 50%
rename from app/saas/src/main/java/stirling/software/saas/payg/charge/SaasClassificationRunBiller.java
rename to app/saas/src/main/java/stirling/software/saas/payg/charge/SaasAutomationRunBiller.java
index a4536d6c23..b1d85197c0 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasClassificationRunBiller.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasAutomationRunBiller.java
@@ -1,5 +1,7 @@
package stirling.software.saas.payg.charge;
+import java.util.List;
+
import org.springframework.context.annotation.Profile;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -7,34 +9,53 @@ import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
-import stirling.software.proprietary.classification.ClassificationRunBiller;
+import stirling.software.proprietary.automation.AutomationRunBiller;
+import stirling.software.proprietary.billing.DocumentUnitCalculator;
+import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
+import stirling.software.proprietary.billing.UnitCalcPolicy;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.ProcessType;
+import stirling.software.saas.payg.policy.PricingPolicy;
+import stirling.software.saas.payg.policy.PricingPolicyService;
import stirling.software.saas.util.AuthenticationUtils;
/**
- * Charges one PAYG unit per document as an AUTOMATION job, matching what a server-side classify
- * policy step bills.
+ * Charges one client-side Automate run as a standalone AUTOMATION job, on the input set's doc-units
+ * with the team's effective {@link PricingPolicy} - so a browser-run workflow costs the same as the
+ * equivalent server-side policy over the same inputs.
*/
@Component
@Profile("saas")
@RequiredArgsConstructor
-public class SaasClassificationRunBiller implements ClassificationRunBiller {
+public class SaasAutomationRunBiller implements AutomationRunBiller {
private final UserRepository userRepository;
+ private final PricingPolicyService pricingPolicyService;
private final JobChargeService jobChargeService;
@Override
- public void recordClassificationRun(int documentCount) {
+ public void recordAutomationRun(List<FileSize> inputs) {
+ if (inputs.isEmpty()) {
+ return;
+ }
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = AuthenticationUtils.getCurrentUser(auth, userRepository);
if (user == null || user.getTeam() == null) {
return;
}
+ PricingPolicy policy = pricingPolicyService.getEffectivePolicy(user.getTeam().getId());
+ UnitCalcPolicy unitCalc =
+ new UnitCalcPolicy(
+ policy.getDocPagesPerUnit(),
+ policy.getDocBytesPerUnit(),
+ policy.getMinChargeUnits(),
+ policy.getFileUnitCap());
+ int units = DocumentUnitCalculator.unitsForGroup(inputs, unitCalc);
+
JobSource source =
auth instanceof ApiKeyAuthenticationToken ? JobSource.API : JobSource.WEB;
ChargeContext ctx =
@@ -44,6 +65,7 @@ public class SaasClassificationRunBiller implements ClassificationRunBiller {
source,
ProcessType.AUTOMATION,
BillingCategory.AUTOMATION);
- jobChargeService.chargeStandalone(ctx, Math.max(1, documentCount));
+ // chargeStandalone re-resolves the effective policy and applies its minChargeUnits floor.
+ jobChargeService.chargeStandalone(ctx, units);
}
}
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java b/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
index b758c89787..3375d91a88 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
@@ -65,7 +65,7 @@ import stirling.software.saas.util.AuthenticationUtils;
* service.
*
* <p>{@code afterCompletion}: branches on HTTP status — 2xx hashes the response body for OUTPUT
- * lineage; 4xx records a step append for audit; 5xx triggers refund-and-close (OPENED) or
+ * lineage; any error (4xx or 5xx) is never charged and triggers refund-and-close (OPENED) or
* step-quota return (JOINED). Closes all input temp files and the response wrapper at the end.
*
* <p>Fail-open everywhere: any unexpected {@link RuntimeException} is swallowed, logged at WARN,
@@ -202,7 +202,14 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
// AI document tools (/api/v1/ai/tools/**) live in the proprietary module and can't
// carry @RequiresFeature, so they're recognised by path — see AiToolRoutes.
boolean aiToolRoute = AiToolRoutes.matches(request);
- if (!hasAutoJobPostMapping && !hasRequiresFeature && !aiToolRoute) {
+ // Any internal automation sub-step (X-Stirling-Automation) is billable automation
+ // whatever controller it lands on: integration/third-party steps and other proprietary
+ // tools carry no annotation. Matches self-hosted, which bills by the header regardless.
+ boolean automationSubStep = hasAutomationHeader(request);
+ if (!hasAutoJobPostMapping
+ && !hasRequiresFeature
+ && !aiToolRoute
+ && !automationSubStep) {
callsShortCircuit.increment();
return true;
}
@@ -385,9 +392,14 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
return;
}
if (status >= 400) {
- // 4xx: customer paid for the attempt. No OUTPUT recording, no refund.
- // Still a successful-from-billing-standpoint OPENED process — meter it below.
- meterIfOpened(jobId, disposition);
+ // Errored work is never charged: refund the request that opened the process, or drop
+ // the added step for a joined follow-up.
+ if (disposition == ChargeOutcome.Disposition.OPENED) {
+ chargeService.markFirstStepFailed(jobId, "first-step-4xx:" + status);
+ refundsCounter.increment();
+ } else {
+ chargeService.decrementStepCount(jobId);
+ }
return;
}
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
index 70b14e86c3..da67729962 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
@@ -28,6 +28,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
+import stirling.software.proprietary.billing.BillingStepLimit;
import stirling.software.saas.payg.model.JobSource;
/**
@@ -97,6 +98,11 @@ public class PricingPolicy implements Serializable {
@Column(name = "step_limit", nullable = false)
private Map<JobSource, Integer> stepLimits = new HashMap<>();
+ /** Successful tool calls covered by one charge, using the shared fallback if unconfigured. */
+ public int resolveStepLimit(JobSource source) {
+ return BillingStepLimit.resolve(stepLimits == null ? null : stepLimits.get(source));
+ }
+
/**
* Stripe Price IDs this policy resolves to — one per currency we support. Currency is not
* stored here; it comes from {@code stripe.prices.currency} via Sync Engine when picking the
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.java
index 1a227d7ff0..dbb58ab31b 100644
--- a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.java
@@ -14,6 +14,9 @@ import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -36,6 +39,7 @@ import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
+import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.policy.PricingPolicy;
import stirling.software.saas.payg.policy.PricingPolicyService;
import stirling.software.saas.repository.SaasTeamExtensionsRepository;
@@ -92,6 +96,7 @@ class InstanceControllerTest {
assertThat(body.state()).isEqualTo("OK");
// Phase 2: the metering inputs the instance needs ride along.
assertThat(body.unitCalcPolicy()).isEqualTo(new UnitCalcPolicy(1, 1_048_576L, 1, 1000));
+ assertThat(body.automationStepLimit()).isEqualTo(10);
assertThat(body.periodStart()).isNotNull();
assertThat(body.periodEnd()).isNotNull();
// The instance-facing read drops the cached snapshot first so a just-subscribed team's
@@ -99,6 +104,25 @@ class InstanceControllerTest {
verify(entitlementService).invalidate(42L);
}
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(ints = {-1, 0, 1, 20, Integer.MAX_VALUE})
+ void entitlementUsesThePipelineStepLimit(Integer limit) {
+ PricingPolicy policy = policy();
+ policy.getStepLimits().put(JobSource.PIPELINE, limit);
+ policy.getStepLimits().put(JobSource.LINKED_INSTANCE, 99);
+ when(billingService.forTeam(42L)).thenReturn(subscribedBilling("sub_42", 120L));
+ when(entitlementService.getSnapshot(42L))
+ .thenReturn(snapshot(EntitlementState.FULL, 0L, null));
+ when(pricingPolicyService.getEffectivePolicy(42L)).thenReturn(policy);
+
+ EntitlementResponse body =
+ controller().entitlement(new LinkedInstanceAuthenticationToken(1L, 42L)).getBody();
+
+ assertThat(body).isNotNull();
+ assertThat(body.automationStepLimit()).isEqualTo(limit != null && limit > 0 ? limit : 10);
+ }
+
@Test
void entitlement_uncapped_returnsNullCapUnits() {
Authentication token = new LinkedInstanceAuthenticationToken(2L, 7L);
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/charge/SaasAutomationRunBillerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/charge/SaasAutomationRunBillerTest.java
new file mode 100644
index 0000000000..b6aea045ae
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/payg/charge/SaasAutomationRunBillerTest.java
@@ -0,0 +1,119 @@
+package stirling.software.saas.payg.charge;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.saas.payg.model.BillingCategory;
+import stirling.software.saas.payg.model.JobSource;
+import stirling.software.saas.payg.model.ProcessType;
+import stirling.software.saas.payg.policy.PricingPolicy;
+import stirling.software.saas.payg.policy.PricingPolicyService;
+
+class SaasAutomationRunBillerTest {
+
+ private final UserRepository userRepository = mock(UserRepository.class);
+ private final PricingPolicyService pricingPolicyService = mock(PricingPolicyService.class);
+ private final JobChargeService jobChargeService = mock(JobChargeService.class);
+ private final SaasAutomationRunBiller biller =
+ new SaasAutomationRunBiller(userRepository, pricingPolicyService, jobChargeService);
+
+ @AfterEach
+ void clearContext() {
+ SecurityContextHolder.clearContext();
+ }
+
+ private static User userWithTeam(long userId, long teamId) {
+ Team team = mock(Team.class);
+ when(team.getId()).thenReturn(teamId);
+ User user = mock(User.class);
+ when(user.getId()).thenReturn(userId);
+ when(user.getTeam()).thenReturn(team);
+ return user;
+ }
+
+ private static PricingPolicy policy() {
+ PricingPolicy policy = mock(PricingPolicy.class);
+ when(policy.getDocPagesPerUnit()).thenReturn(10);
+ when(policy.getDocBytesPerUnit()).thenReturn(1_000_000L);
+ when(policy.getMinChargeUnits()).thenReturn(1);
+ when(policy.getFileUnitCap()).thenReturn(1000);
+ return policy;
+ }
+
+ private static void authenticateAs(Authentication auth, User principal) {
+ when(auth.getPrincipal()).thenReturn(principal);
+ SecurityContextHolder.getContext().setAuthentication(auth);
+ }
+
+ @Test
+ void chargesComputedUnitsAsWebAutomation() {
+ User user = userWithTeam(3L, 7L);
+ authenticateAs(mock(Authentication.class), user);
+ PricingPolicy policy = policy();
+ when(pricingPolicyService.getEffectivePolicy(7L)).thenReturn(policy);
+
+ // 25 pages -> ceil(25/10)=3 page units; 5000 bytes -> 1 byte unit; max = 3.
+ biller.recordAutomationRun(List.of(new FileSize(25, 5000L)));
+
+ ArgumentCaptor<ChargeContext> ctx = ArgumentCaptor.forClass(ChargeContext.class);
+ verify(jobChargeService).chargeStandalone(ctx.capture(), eq(3));
+ assertEquals(3L, ctx.getValue().ownerUserId());
+ assertEquals(7L, ctx.getValue().ownerTeamId());
+ assertEquals(JobSource.WEB, ctx.getValue().source());
+ assertEquals(ProcessType.AUTOMATION, ctx.getValue().processType());
+ assertEquals(BillingCategory.AUTOMATION, ctx.getValue().billingCategory());
+ }
+
+ @Test
+ void apiKeyAuthChargesAsApiSource() {
+ User user = userWithTeam(3L, 7L);
+ authenticateAs(mock(ApiKeyAuthenticationToken.class), user);
+ PricingPolicy policy = policy();
+ when(pricingPolicyService.getEffectivePolicy(7L)).thenReturn(policy);
+
+ biller.recordAutomationRun(List.of(new FileSize(1, 10L)));
+
+ ArgumentCaptor<ChargeContext> ctx = ArgumentCaptor.forClass(ChargeContext.class);
+ verify(jobChargeService).chargeStandalone(ctx.capture(), eq(1));
+ assertEquals(JobSource.API, ctx.getValue().source());
+ }
+
+ @Test
+ void noChargeWithoutTeam() {
+ User user = mock(User.class);
+ when(user.getTeam()).thenReturn(null);
+ authenticateAs(mock(Authentication.class), user);
+
+ biller.recordAutomationRun(List.of(new FileSize(1, 10L)));
+
+ verify(jobChargeService, never())
+ .chargeStandalone(
+ org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyInt());
+ }
+
+ @Test
+ void noChargeForEmptyInputs() {
+ biller.recordAutomationRun(List.of());
+
+ verify(jobChargeService, never())
+ .chargeStandalone(
+ org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyInt());
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygBillingParityTest.java b/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygBillingParityTest.java
new file mode 100644
index 0000000000..09f378a643
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygBillingParityTest.java
@@ -0,0 +1,401 @@
+package stirling.software.saas.payg.filter;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.ArgumentCaptor;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.mock.web.MockMultipartHttpServletRequest;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.method.HandlerMethod;
+
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+
+import stirling.software.common.annotations.AutoJobPostMapping;
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
+import stirling.software.proprietary.accountlink.EntitlementCache;
+import stirling.software.proprietary.accountlink.EntitlementState;
+import stirling.software.proprietary.accountlink.FreeTierUsageService;
+import stirling.software.proprietary.accountlink.GateDecision;
+import stirling.software.proprietary.accountlink.InstanceEntitlement;
+import stirling.software.proprietary.accountlink.InstanceEntitlementGate;
+import stirling.software.proprietary.accountlink.InstanceEntitlementInterceptor;
+import stirling.software.proprietary.accountlink.UsageMeterService;
+import stirling.software.proprietary.billing.UnitCalcPolicy;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.saas.payg.charge.ChargeContext;
+import stirling.software.saas.payg.charge.ChargeOutcome;
+import stirling.software.saas.payg.charge.JobChargeService;
+import stirling.software.saas.payg.job.JobService;
+
+/**
+ * Cross-deployment billing parity. One matrix of operations is asserted against BOTH charge paths -
+ * the SaaS {@link PaygChargeInterceptor} and the self-hosted {@link InstanceEntitlementInterceptor}
+ * (this module can see both) - so a change that makes one over- or under-charge relative to the
+ * other fails here.
+ *
+ * <p>The {@code expected} column is the intended charge category ({@code BYPASSED} = not charged).
+ * It is deliberately one shared value today; if a deployment is ever meant to diverge, give that
+ * row a per-deployment expectation here - an explicit, reviewed edit, not a silent drift.
+ */
+class PaygBillingParityTest {
+
+ private enum Handler {
+ TOOL,
+ PLAIN
+ }
+
+ private record Op(
+ String name,
+ String uri,
+ boolean apiKey,
+ boolean automationHeader,
+ Handler handler,
+ String expected) {
+ @Override
+ public String toString() {
+ return name;
+ }
+ }
+
+ private static Stream<Op> operations() {
+ return Stream.of(
+ new Op(
+ "manual tool (jwt)",
+ "/api/v1/security/add-password",
+ false,
+ false,
+ Handler.TOOL,
+ "BYPASSED"),
+ new Op(
+ "automation sub-step (tool)",
+ "/api/v1/security/add-password",
+ false,
+ true,
+ Handler.TOOL,
+ "AUTOMATION"),
+ new Op(
+ "automation sub-step (plain integration step)",
+ "/api/v1/integration/external-call",
+ false,
+ true,
+ Handler.PLAIN,
+ "AUTOMATION"),
+ new Op(
+ "AI tool direct call",
+ "/api/v1/ai/tools/pdf-comment-agent",
+ false,
+ false,
+ Handler.PLAIN,
+ "AI"),
+ new Op(
+ "AI tool via automation",
+ "/api/v1/ai/tools/pdf-comment-agent",
+ false,
+ true,
+ Handler.PLAIN,
+ "AUTOMATION"),
+ new Op(
+ "AI non-tool (orchestrate)",
+ "/api/v1/ai/orchestrate",
+ false,
+ false,
+ Handler.PLAIN,
+ "BYPASSED"),
+ new Op(
+ "api-key tool call",
+ "/api/v1/security/add-password",
+ true,
+ false,
+ Handler.TOOL,
+ "API"),
+ new Op(
+ "api-key non-tool call",
+ "/api/v1/general/files/some-id",
+ true,
+ false,
+ Handler.PLAIN,
+ "BYPASSED"),
+ new Op(
+ "api-key AI tool call",
+ "/api/v1/ai/tools/pdf-comment-agent",
+ true,
+ false,
+ Handler.PLAIN,
+ "AI"));
+ }
+
+ @AfterEach
+ void clearAuth() {
+ SecurityContextHolder.clearContext();
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("operations")
+ void saasAndSelfHostedChargeIdentically(Op op) throws Exception {
+ assertSaas(op);
+ SecurityContextHolder.clearContext();
+ assertSelfHosted(op);
+ }
+
+ @Test
+ void aPolicyRunCarriesOneRunIdIntoBothDeploymentsGrouping() throws Exception {
+ // A policy's sub-steps share X-Stirling-Run-Id; both deployments key their charge grouping
+ // on it so the whole run is one charge, not one-per-step. The collapse itself lives in each
+ // grouping engine - SaaS JobService.joinOrOpen (JobServiceTest), self-hosted
+ // UsageMeterService dedup (UsageMeterServiceTest.skipsRepeatWithinWorkflowWindow); here we
+ // assert the shared key reaches both.
+ String runId = "run-parity";
+
+ // SaaS: the run id flows onto the ChargeContext that JobService groups by.
+ JobChargeService chargeService = mock(JobChargeService.class);
+ UserRepository userRepo = mock(UserRepository.class);
+ PaygChargeInterceptor saas =
+ new PaygChargeInterceptor(
+ chargeService,
+ mock(JobService.class),
+ userRepo,
+ new TempFileManager(new TempFileRegistry(), new ApplicationProperties()),
+ mock(PaygOutputExtractor.class),
+ new PaygFilterProperties(),
+ new SimpleMeterRegistry());
+ when(chargeService.openProcess(any(), anyList()))
+ .thenReturn(
+ new ChargeOutcome(UUID.randomUUID(), 1, ChargeOutcome.Disposition.OPENED));
+ User user = makeUser();
+ String supabaseId = UUID.randomUUID().toString();
+ SecurityContextHolder.getContext()
+ .setAuthentication(
+ new UsernamePasswordAuthenticationToken(
+ supabaseId,
+ null,
+ List.of(new SimpleGrantedAuthority("ROLE_USER"))));
+ when(userRepo.findBySupabaseId(UUID.fromString(supabaseId))).thenReturn(Optional.of(user));
+ MockMultipartHttpServletRequest saasReq = new MockMultipartHttpServletRequest();
+ saasReq.setRequestURI("/api/v1/security/add-password");
+ saasReq.addFile(
+ new MockMultipartFile("fileInput", "x.pdf", "application/pdf", "abc".getBytes()));
+ saasReq.addHeader("X-Stirling-Automation", "true");
+ saasReq.addHeader("X-Stirling-Run-Id", runId);
+ saas.preHandle(saasReq, new MockHttpServletResponse(), handler(Handler.TOOL));
+ SecurityContextHolder.clearContext();
+ ArgumentCaptor<ChargeContext> ctx = ArgumentCaptor.forClass(ChargeContext.class);
+ verify(chargeService).openProcess(ctx.capture(), anyList());
+ assertThat(ctx.getValue().runId()).isEqualTo(runId);
+
+ // Self-hosted: the run id is the meter's dedup key, so the sub-steps collapse.
+ InstanceEntitlementGate gate = mock(InstanceEntitlementGate.class);
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ EntitlementCache cache = mock(EntitlementCache.class);
+ UsageMeterService meter = mock(UsageMeterService.class);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(cache.current()).thenReturn(Optional.of(entitled(policy, period)));
+ InstanceEntitlementInterceptor selfHosted =
+ new InstanceEntitlementInterceptor(
+ gate,
+ cache,
+ meterProviderOf(meter),
+ mock(FreeTierUsageService.class),
+ mock(TempFileManager.class));
+ MockMultipartHttpServletRequest shReq = new MockMultipartHttpServletRequest();
+ shReq.setRequestURI("/api/v1/security/add-password");
+ shReq.addFile(
+ new MockMultipartFile(
+ "fileInput", "doc.bin", "application/octet-stream", "x".getBytes()));
+ shReq.addHeader("X-Stirling-Automation", "true");
+ shReq.addHeader("X-Stirling-Run-Id", runId);
+ MockHttpServletResponse shResp = new MockHttpServletResponse();
+ selfHosted.preHandle(shReq, shResp, handler(Handler.TOOL));
+ selfHosted.afterCompletion(shReq, shResp, handler(Handler.TOOL), null);
+ verify(meter)
+ .accrue(
+ eq(period),
+ eq(stirling.software.proprietary.billing.BillingCategory.AUTOMATION),
+ anyLong(),
+ eq(runId),
+ eq(10));
+ }
+
+ private void assertSaas(Op op) throws Exception {
+ JobChargeService chargeService = mock(JobChargeService.class);
+ JobService jobService = mock(JobService.class);
+ UserRepository userRepo = mock(UserRepository.class);
+ PaygOutputExtractor outputExtractor = mock(PaygOutputExtractor.class);
+ PaygFilterProperties properties = new PaygFilterProperties();
+ TempFileManager tempFileManager =
+ new TempFileManager(new TempFileRegistry(), new ApplicationProperties());
+ PaygChargeInterceptor interceptor =
+ new PaygChargeInterceptor(
+ chargeService,
+ jobService,
+ userRepo,
+ tempFileManager,
+ outputExtractor,
+ properties,
+ new SimpleMeterRegistry());
+
+ UUID jobId = UUID.randomUUID();
+ when(chargeService.openProcess(any(), anyList()))
+ .thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
+
+ User user = makeUser();
+ if (op.apiKey()) {
+ SecurityContextHolder.getContext()
+ .setAuthentication(
+ new ApiKeyAuthenticationToken(
+ user, "k", List.of(new SimpleGrantedAuthority("ROLE_API"))));
+ } else {
+ String supabaseId = UUID.randomUUID().toString();
+ SecurityContextHolder.getContext()
+ .setAuthentication(
+ new UsernamePasswordAuthenticationToken(
+ supabaseId,
+ null,
+ List.of(new SimpleGrantedAuthority("ROLE_USER"))));
+ when(userRepo.findBySupabaseId(UUID.fromString(supabaseId)))
+ .thenReturn(Optional.of(user));
+ }
+
+ MockMultipartHttpServletRequest req = new MockMultipartHttpServletRequest();
+ req.setRequestURI(op.uri());
+ req.addFile(
+ new MockMultipartFile("fileInput", "x.pdf", "application/pdf", "abc".getBytes()));
+ if (op.automationHeader()) {
+ req.addHeader("X-Stirling-Automation", "true");
+ }
+
+ interceptor.preHandle(req, new MockHttpServletResponse(), handler(op.handler()));
+
+ if ("BYPASSED".equals(op.expected())) {
+ verify(chargeService, never()).openProcess(any(), anyList());
+ } else {
+ ArgumentCaptor<ChargeContext> ctx = ArgumentCaptor.forClass(ChargeContext.class);
+ verify(chargeService).openProcess(ctx.capture(), anyList());
+ assertThat(ctx.getValue().billingCategory().name())
+ .as("SaaS category for %s", op.name())
+ .isEqualTo(op.expected());
+ }
+ }
+
+ private void assertSelfHosted(Op op) throws Exception {
+ InstanceEntitlementGate gate = mock(InstanceEntitlementGate.class);
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ EntitlementCache cache = mock(EntitlementCache.class);
+ UsageMeterService meter = mock(UsageMeterService.class);
+ UnitCalcPolicy policy = new UnitCalcPolicy(1, 1_048_576L, 1, 1000);
+ LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
+ when(cache.current()).thenReturn(Optional.of(entitled(policy, period)));
+ InstanceEntitlementInterceptor interceptor =
+ new InstanceEntitlementInterceptor(
+ gate,
+ cache,
+ meterProviderOf(meter),
+ mock(FreeTierUsageService.class),
+ mock(TempFileManager.class));
+
+ if (op.apiKey()) {
+ SecurityContextHolder.getContext()
+ .setAuthentication(
+ new ApiKeyAuthenticationToken(
+ new User(),
+ "k",
+ List.of(new SimpleGrantedAuthority("ROLE_API"))));
+ }
+
+ MockMultipartHttpServletRequest req = new MockMultipartHttpServletRequest();
+ req.setRequestURI(op.uri());
+ req.addFile(
+ new MockMultipartFile(
+ "fileInput", "doc.bin", "application/octet-stream", "x".getBytes()));
+ if (op.automationHeader()) {
+ req.addHeader("X-Stirling-Automation", "true");
+ }
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, handler(op.handler()));
+ interceptor.afterCompletion(req, resp, handler(op.handler()), null);
+
+ if ("BYPASSED".equals(op.expected())) {
+ verify(meter, never()).accrue(any(), any(), anyLong(), any(), eq(10));
+ } else {
+ verify(meter)
+ .accrue(
+ eq(period),
+ eq(
+ stirling.software.proprietary.billing.BillingCategory.valueOf(
+ op.expected())),
+ anyLong(),
+ any(),
+ eq(10));
+ }
+ }
+
+ private static InstanceEntitlement entitled(UnitCalcPolicy policy, LocalDateTime period) {
+ return new InstanceEntitlement(
+ true, 0, 0, 100L, EntitlementState.OK, policy, period, period.plusMonths(1), null);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static ObjectProvider<UsageMeterService> meterProviderOf(UsageMeterService meter) {
+ ObjectProvider<UsageMeterService> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(meter);
+ return provider;
+ }
+
+ private static HandlerMethod handler(Handler kind) {
+ try {
+ Method m = Fixture.class.getDeclaredMethod(kind == Handler.TOOL ? "tool" : "plain");
+ return new HandlerMethod(new Fixture(), m);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static User makeUser() {
+ User user = new User();
+ try {
+ java.lang.reflect.Field idField = User.class.getDeclaredField("id");
+ idField.setAccessible(true);
+ idField.set(user, 1L);
+ } catch (ReflectiveOperationException e) {
+ throw new RuntimeException(e);
+ }
+ return user;
+ }
+
+ static class Fixture {
+ @AutoJobPostMapping(value = "/tool", resourceWeight = 1)
+ public void tool() {}
+
+ public void plain() {}
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygChargeInterceptorTest.java b/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygChargeInterceptorTest.java
index be402dd061..acf845fc44 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygChargeInterceptorTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygChargeInterceptorTest.java
@@ -274,7 +274,7 @@ class PaygChargeInterceptorTest {
}
@Test
- void afterCompletion_4xx_appendsFailedStepNoRefundNoOutputs() throws Exception {
+ void afterCompletion_4xx_opened_refundsAndNeverMeters() throws Exception {
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
@@ -288,13 +288,34 @@ class PaygChargeInterceptorTest {
interceptor.preHandle(req, res, handlerMethodForFakeController());
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
- verify(chargeService, never()).markFirstStepFailed(any(), any());
+ // Errored work is never charged: the opener is refunded, and it never meters.
+ verify(chargeService).markFirstStepFailed(eq(jobId), eq("first-step-4xx:422"));
verify(chargeService, never()).decrementStepCount(any());
verify(jobService, never()).recordOutput(any(), any());
verify(jobService)
.appendStep(eq(jobId), any(), eq(JobStepStatus.FAILED), any(), any(), eq("422"));
- // 4xx is a full charge (customer paid for the attempt), so it still meters.
- verify(chargeService).meterJobUsage(jobId);
+ assertThat(meterRegistry.counter("payg.filter.refunds").count()).isEqualTo(1.0);
+ verify(chargeService, never()).meterJobUsage(any());
+ }
+
+ @Test
+ void afterCompletion_4xx_joined_callsDecrementStepCount() throws Exception {
+ authenticateWithApiKey(makeUser(7L, 42L));
+ UUID jobId = UUID.randomUUID();
+ when(chargeService.openProcess(any(), anyList()))
+ .thenReturn(new ChargeOutcome(jobId, 0, ChargeOutcome.Disposition.JOINED));
+
+ MockMultipartHttpServletRequest req = newMultipart();
+ req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
+ MockHttpServletResponse res = new MockHttpServletResponse();
+ res.setStatus(422);
+
+ interceptor.preHandle(req, res, handlerMethodForFakeController());
+ interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
+
+ verify(chargeService).decrementStepCount(jobId);
+ verify(chargeService, never()).markFirstStepFailed(any(), any());
+ verify(chargeService, never()).meterJobUsage(any());
}
@Test
@@ -725,6 +746,32 @@ class PaygChargeInterceptorTest {
verify(chargeService, never()).openProcess(any(), anyList());
}
+ @Test
+ void preHandle_plainRouteWithAutomationHeader_isAutomation() throws Exception {
+ // A policy/pipeline sub-step to an unannotated proprietary tool (e.g. an integration step)
+ // carries X-Stirling-Automation: true. It must be in scope and billed AUTOMATION, matching
+ // self-hosted, which bills by the header regardless of annotation.
+ authenticateWithUser(makeUser(7L, 42L));
+ UUID jobId = UUID.randomUUID();
+ when(chargeService.openProcess(any(), anyList()))
+ .thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
+ org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
+ org.mockito.ArgumentCaptor.forClass(
+ stirling.software.saas.payg.charge.ChargeContext.class);
+
+ MockMultipartHttpServletRequest req = newMultipart();
+ req.setRequestURI("/api/v1/integration/external-api-call");
+ req.addFile(
+ new MockMultipartFile("fileInput", "x.pdf", "application/pdf", "abc".getBytes()));
+ req.addHeader("X-Stirling-Automation", "true");
+
+ interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForPlain());
+
+ verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
+ assertThat(ctxCaptor.getValue().billingCategory())
+ .isEqualTo(stirling.software.saas.payg.model.BillingCategory.AUTOMATION);
+ }
+
// --- helpers --------------------------------------------------------------------------------
private MockMultipartHttpServletRequest newMultipart() {
diff --git a/docker/embedded/compose/test_cicd.yml b/docker/embedded/compose/test_cicd.yml
index f42087291f..fbe0715e95 100644
--- a/docker/embedded/compose/test_cicd.yml
+++ b/docker/embedded/compose/test_cicd.yml
@@ -32,6 +32,7 @@ services:
SYSTEM_GOOGLEVISIBILITY: "true"
SYSTEM_ENABLEMOBILESCANNER: "true"
SECURITY_CUSTOMGLOBALAPIKEY: "123456789"
+ STIRLING_BILLING_ACCOUNT_LINK_ENABLED: "false"
# Folder management + file-storage features the cucumber
# `folders_and_files.feature` suite needs to upload PDFs against.
# The folder endpoints and the storage upload endpoint short-circuit
diff --git a/frontend/editor/src/core/hooks/tools/automate/useAutomateOperation.ts b/frontend/editor/src/core/hooks/tools/automate/useAutomateOperation.ts
index 4a96532321..82205c52d1 100644
--- a/frontend/editor/src/core/hooks/tools/automate/useAutomateOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/automate/useAutomateOperation.ts
@@ -5,11 +5,18 @@ import {
import { useCallback } from "react";
import { executeAutomationSequence } from "@app/utils/automationExecutor";
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
+import { useFileContext } from "@app/contexts/FileContext";
import { AutomateParameters } from "@app/types/automation";
+import {
+ meterAutomationRun,
+ type AutomationMeterInput,
+} from "@app/services/automationMeter";
+import { isStirlingFile } from "@app/types/fileContext";
export function useAutomateOperation() {
const { allTools } = useToolRegistry();
const toolRegistry = allTools;
+ const { selectors } = useFileContext();
const customProcessor = useCallback(
async (params: AutomateParameters, files: File[]) => {
@@ -21,10 +28,11 @@ export function useAutomateOperation() {
if (!params.automationConfig) {
throw new Error("No automation configuration provided");
}
+ const automationConfig = params.automationConfig;
// Execute the automation sequence and return the final results
const finalResults = await executeAutomationSequence(
- params.automationConfig,
+ automationConfig,
files,
toolRegistry,
(stepIndex: number, operationName: string) => {
@@ -47,12 +55,35 @@ export function useAutomateOperation() {
console.log(
`✅ Automation completed, returning ${finalResults.length} files`,
);
+
+ // Meter the completed run. Charged on the input set's doc-units (once
+ // per run) so an Automate workflow costs the same as the equivalent policy.
+ // Best-effort and post-success - never blocks the returned result.
+ try {
+ const inputs: AutomationMeterInput[] = files.map((file) => ({
+ pages: isStirlingFile(file)
+ ? (selectors.getStirlingFileStub(file.fileId)?.processedFile
+ ?.totalPages ?? 0)
+ : 0,
+ bytes: file.size ?? 0,
+ }));
+ meterAutomationRun({
+ automationName: automationConfig.name,
+ operations: automationConfig.operations.map(
+ (operation) => operation.operation,
+ ),
+ inputs,
+ });
+ } catch (meterError) {
+ console.warn("Automation metering skipped:", meterError);
+ }
+
return {
files: finalResults,
consumedAllInputs: true,
};
},
- [toolRegistry],
+ [toolRegistry, selectors],
);
return useToolOperation<AutomateParameters>(
diff --git a/frontend/editor/src/core/services/automationMeter.ts b/frontend/editor/src/core/services/automationMeter.ts
new file mode 100644
index 0000000000..59f86adcb9
--- /dev/null
+++ b/frontend/editor/src/core/services/automationMeter.ts
@@ -0,0 +1,18 @@
+// Records a completed in-browser automation run.
+
+/** One input document's page count (0 for non-PDF / unknown) and byte size. */
+export interface AutomationMeterInput {
+ pages: number;
+ bytes: number;
+}
+
+export interface AutomationMeterPayload {
+ automationName?: string;
+ operations?: string[];
+ inputs: AutomationMeterInput[];
+}
+
+/** Meter a completed automation run. Fire-and-forget; never awaited, never throws. */
+export function meterAutomationRun(_payload: AutomationMeterPayload): void {
+ // No billing layer in the core build.
+}
diff --git a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
index 7d42434385..30a9cd0353 100644
--- a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
@@ -51,7 +51,7 @@ test("a 10-file upload wave classifies every file into its group", async ({
await page.route("**/api/v1/policies", (route) =>
route.fulfill({ json: [SEEDED_POLICY] }),
);
- await page.route("**/api/v1/policies/classify/meter", (route) =>
+ await page.route("**/api/v1/automation/meter", (route) =>
route.fulfill({ status: 202, body: "" }),
);
await page.goto("/editor", {
diff --git a/frontend/editor/src/desktop/services/operationRouter.test.ts b/frontend/editor/src/desktop/services/operationRouter.test.ts
index 2580a5395f..3ec23bd714 100644
--- a/frontend/editor/src/desktop/services/operationRouter.test.ts
+++ b/frontend/editor/src/desktop/services/operationRouter.test.ts
@@ -49,6 +49,7 @@ describe("operationRouter.getBaseUrl — SaaS mode cloud-only routing", () => {
"/api/v1/team/my",
"/api/v1/policies",
"/api/v1/policies/run",
+ "/api/v1/automation/meter",
])("%s routes to the SaaS backend (not local)", async (endpoint) => {
await expect(operationRouter.getBaseUrl(endpoint)).resolves.toBe(SAAS_URL);
});
diff --git a/frontend/editor/src/desktop/services/operationRouter.ts b/frontend/editor/src/desktop/services/operationRouter.ts
index 0cf557eec7..029ea5b596 100644
--- a/frontend/editor/src/desktop/services/operationRouter.ts
+++ b/frontend/editor/src/desktop/services/operationRouter.ts
@@ -60,6 +60,7 @@ export class OperationRouter {
/^\/api\/v1\/auth\//, // Supabase auth (SaaS mode)
/^\/api\/v1\/payg\//, // PAYG wallet / spend-cap / billing
/^\/api\/v1\/policies(?:\/|$)/, // Policy runs — must bill via the cloud
+ /^\/api\/v1\/automation(?:\/|$)/, // Automate / classification meter - must bill via the cloud
/^\/api\/v1\/ai\//, // AI engine (orchestrate, etc.) — runs in the cloud
// Add more cloud-only feature prefixes here as they land.
];
diff --git a/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts b/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts
index e6d2547740..11a7ebc3e3 100644
--- a/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts
+++ b/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts
@@ -7,7 +7,7 @@
import { fileStorage } from "@app/services/fileStorage";
import { classifyFileHeuristically } from "@app/services/heuristic/heuristicClassification";
-import { meterClassificationRun } from "@app/services/classificationMeter";
+import { meterAutomationRun } from "@app/services/automationMeter";
import {
isDispatched,
markDispatched,
@@ -28,6 +28,10 @@ import type { LocalPass } from "@app/components/policies/policyLocalPass";
const FILE_WAIT_TRIES = 20;
const FILE_WAIT_MS = 250;
+/** Audit step label for a metered classify run; mirrors the AI classify tool so both paths read
+ * alike in the trail. */
+const CLASSIFY_STEP = "/api/v1/ai/tools/classify-and-label";
+
/** localStorage flag: set to "true" for a full per-file scoring breakdown in the console. */
const DEBUG_FLAG = "stirling-classification-debug";
@@ -47,7 +51,12 @@ export const classificationLocalPass: LocalPass = {
// A file that did inherit (or was classified) carries a label array and is skipped.
eligible: (stub) => stub.classificationLabels === undefined,
run: async (fileId, stub) => {
- const verdict = await classifyStub(fileId, stub.name, stub.size ?? 0);
+ const verdict = await classifyStub(
+ fileId,
+ stub.name,
+ stub.size ?? 0,
+ stub.processedFile?.totalPages ?? 0,
+ );
// Bytes never landed (file removed mid-wait): leave unclassified so a reload retries.
if (verdict == null) return null;
return {
@@ -57,16 +66,27 @@ export const classificationLocalPass: LocalPass = {
},
// A confident local verdict stands; anything less asks the AI engine, which overwrites it.
needsServerRun: localVerdictNeedsEscalation(verdict.confidence),
+ // Billed by the engine only if it does not escalate (see meter's contract).
+ meter: verdict.meter,
};
},
};
+/** One file's local classification verdict. {@link meter} is present only when the run should be
+ * charged (first pass, not a heal re-run); the engine fires it iff no server run follows. */
+interface ClassificationVerdict {
+ labels: string[];
+ confidence: HeuristicConfidence;
+ meter?: () => void;
+}
+
/** Classify one file, metering exactly once; null = no verdict, retried later. */
async function classifyStub(
fileId: FileId,
fileName: string,
fileSize: number,
-): Promise<{ labels: string[]; confidence: HeuristicConfidence } | null> {
+ pageCount: number,
+): Promise<ClassificationVerdict | null> {
let file: StirlingFile | null = null;
for (let i = 0; i < FILE_WAIT_TRIES; i++) {
file = await fileStorage.getStirlingFile(fileId).catch(() => null);
@@ -117,15 +137,18 @@ async function classifyStub(
(alreadyMetered ? " [heal: not re-metered]" : ""),
);
if (debug && result.explain) logExplanation(fileName, result);
- // Meter on the first classification only; a healing re-run of an undelivered
- // result (already dispatched) is not a new billable run.
- if (!alreadyMetered) {
- meterClassificationRun({
- policyName: "Classification",
- documentCount: 1,
- labels,
- });
- }
+ // The billable classify run. The engine fires this only when no server run follows: an AI
+ // escalation bills the run, or - when the verdict stands, or the AI engine is off so nothing
+ // escalates - this local pass does. Never both. First pass only; a heal re-run of an
+ // undelivered result is not a new charge.
+ const meter = alreadyMetered
+ ? undefined
+ : () =>
+ meterAutomationRun({
+ automationName: "Classification",
+ operations: [CLASSIFY_STEP],
+ inputs: [{ pages: pageCount, bytes: fileSize }],
+ });
markDispatched(CLASSIFICATION_POLICY_KEY, fileId);
// Labels, no output file - the same settle shape the server-run classification uses.
updateRun(runId, {
@@ -133,7 +156,7 @@ async function classifyStub(
imported: true,
outputFileIds: [fileId as string],
});
- return { labels, confidence: result.confidence };
+ return { labels, confidence: result.confidence, meter };
} catch (err) {
// Never persist a verdict for an unreadable file - the failure may be
// environmental, so it must stay eligible to retry (and meter) later.
diff --git a/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts b/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts
index e0deda6fa2..8016265b31 100644
--- a/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts
+++ b/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts
@@ -15,6 +15,8 @@ export interface LocalPassResult {
stubUpdates: Partial<StirlingFileStub>;
/** Whether the policy's server run should still be dispatched after this pass. */
needsServerRun: boolean;
+ /** Charge this local pass as the billable run. */
+ meter?: () => void;
}
export interface LocalPass {
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
index 3c965d878d..c48fa210d9 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
@@ -125,8 +125,8 @@ vi.mock("@app/services/fileClassification", () => ({
vi.mock("@app/services/heuristic/heuristicClassification", () => ({
classifyFileHeuristically: (file: File) => mocks.classify(file),
}));
-vi.mock("@app/services/classificationMeter", () => ({
- meterClassificationRun: (payload: unknown) => mocks.meter(payload),
+vi.mock("@app/services/automationMeter", () => ({
+ meterAutomationRun: (payload: unknown) => mocks.meter(payload),
}));
import { usePolicyAutoRun } from "@app/components/policies/usePolicyAutoRun";
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx
index 27788f5de5..59c402eb8f 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx
@@ -83,8 +83,8 @@ vi.mock("@app/services/fileStorage", () => ({
vi.mock("@app/services/heuristic/heuristicClassification", () => ({
classifyFileHeuristically: (file: File) => mocks.classify(file),
}));
-vi.mock("@app/services/classificationMeter", () => ({
- meterClassificationRun: (payload: unknown) => mocks.meter(payload),
+vi.mock("@app/services/automationMeter", () => ({
+ meterAutomationRun: (payload: unknown) => mocks.meter(payload),
}));
import { usePolicyLocalPasses } from "@app/components/policies/usePolicyLocalPasses";
@@ -306,6 +306,9 @@ describe("usePolicyLocalPasses delivery", () => {
classificationLabels: ["invoice"],
classificationConfidence: "low",
});
+ // ...but the local pass is not metered: the AI run it escalates to bills it instead, so one
+ // classification is charged once.
+ expect(mocks.meter).not.toHaveBeenCalled();
});
it("lets a confident local verdict stand without asking the AI", async () => {
@@ -325,6 +328,8 @@ describe("usePolicyLocalPasses delivery", () => {
}),
);
expect(mocks.runPolicyOnFile).not.toHaveBeenCalled();
+ // The verdict stands, so the local pass is the billable run.
+ expect(mocks.meter).toHaveBeenCalledTimes(1);
});
it("never escalates when the AI engine is off, however unsure the verdict", async () => {
@@ -344,6 +349,9 @@ describe("usePolicyLocalPasses delivery", () => {
}),
);
expect(mocks.runPolicyOnFile).not.toHaveBeenCalled();
+ // AI is off, so the unsure verdict is final and never escalates - it must still be billed once
+ // here, not fall through the gap between local and (never-run) server billing.
+ expect(mocks.meter).toHaveBeenCalledTimes(1);
});
it("does not run on upload when the policy is set to run on export", async () => {
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
index 5613360350..8063d4eb64 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
@@ -121,6 +121,10 @@ export function usePolicyLocalPasses(): void {
).catch(() => {
// Backstop: runPolicyOnFile handles its own failures.
});
+ } else {
+ // No server run follows (verdict stands, or the AI engine is off so nothing can
+ // escalate): this local pass is the billable run, so charge it here.
+ result.meter?.();
}
}
if (wrote) bumpRevision();
diff --git a/frontend/editor/src/proprietary/services/automationMeter.ts b/frontend/editor/src/proprietary/services/automationMeter.ts
new file mode 100644
index 0000000000..e2139e524c
--- /dev/null
+++ b/frontend/editor/src/proprietary/services/automationMeter.ts
@@ -0,0 +1,17 @@
+// Meters an in-browser automation run.
+
+import apiClient from "@app/services/apiClient";
+import { type AutomationMeterPayload } from "@core/services/automationMeter";
+
+export {
+ type AutomationMeterInput,
+ type AutomationMeterPayload,
+} from "@core/services/automationMeter";
+
+export function meterAutomationRun(payload: AutomationMeterPayload): void {
+ void apiClient
+ .post(`/api/v1/automation/meter`, payload, { suppressErrorToast: true })
+ .catch(() => {
+ // Best-effort billing; the automation already succeeded in the browser.
+ });
+}
diff --git a/frontend/editor/src/proprietary/services/classificationMeter.ts b/frontend/editor/src/proprietary/services/classificationMeter.ts
deleted file mode 100644
index 036b7ef242..0000000000
--- a/frontend/editor/src/proprietary/services/classificationMeter.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// Meters an in-browser (non-AI) classification run for billing/audit parity with
-// the server-side classify path. Fire-and-forget; failures never block the user.
-
-import apiClient from "@app/services/apiClient";
-import { getPolicyOutputBaseUrl } from "@app/services/policyOutputBaseUrl";
-import { resolvePolicyRunTarget } from "@app/services/policyApi";
-
-interface ClassifyMeterPayload {
- /** Policy name for the audit-trail label; defaults to "Classification" server-side. */
- policyName?: string;
- /** Documents covered by this meter call (defaults to 1 server-side). */
- documentCount?: number;
- /** Resolved labels, carried for the audit record. */
- labels?: string[];
-}
-
-/** Meter a completed client-side classification. Does not throw and is not awaited by callers. */
-export function meterClassificationRun(payload: ClassifyMeterPayload): void {
- const base = getPolicyOutputBaseUrl(resolvePolicyRunTarget());
- void apiClient
- .post(`${base}/api/v1/policies/classify/meter`, payload, {
- suppressErrorToast: true,
- })
- .catch(() => {
- // Best-effort billing; the classification already succeeded in the browser.
- });
-}