Skip to content

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

Add vector database destinations (#7986)

Anthony Stirling9b8b9e30e2fc
diff --git a/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.java b/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.java
index 19f3092b77..0b361ce80a 100644
--- a/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.java
+++ b/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.java
@@ -47,7 +47,7 @@ public class PdfMarkdownConverter {
String md = e.value() instanceof TableBlock tb ? tb.render() : (String) e.value();
blocks.add(new MarkdownBlock(md, e.pageStart(), e.pageEnd()));
}
- return MarkdownBlocks.withHeadingPaths(blocks);
+ return MarkdownBlocks.withHeadingPaths(MarkdownBlocks.normaliseHeadingLevels(blocks));
}
private List<Element> buildElements(PdfDocument doc) throws IOException {
diff --git a/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.java b/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.java
index c6756e7a57..d29e20f9a4 100644
--- a/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.java
+++ b/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.java
@@ -17,6 +17,11 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Stream;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.PDPageContentStream;
+import org.apache.pdfbox.pdmodel.font.PDType1Font;
+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -45,6 +50,33 @@ class PdfMarkdownConverterTest {
@TempDir Path tmp;
+ @Test
+ void rebasesASecondLevelHeadingBeforeBuildingItsPath() throws IOException {
+ Path pdf = tmp.resolve("heading.pdf");
+ try (PDDocument document = new PDDocument()) {
+ PDPage page = new PDPage();
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ var font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
+ content.beginText();
+ content.setFont(font, 15.6f);
+ content.newLineAtOffset(50, 700);
+ content.showText("Section");
+ content.setFont(font, 12);
+ content.newLineAtOffset(0, -40);
+ content.showText(
+ "This body text establishes the normal font size for this document.");
+ content.endText();
+ }
+ document.save(pdf.toFile());
+ }
+ try (PdfDocument document = PdfDocument.open(pdf)) {
+ List<MarkdownBlock> blocks = new PdfMarkdownConverter().extractBlocks(document);
+ assertEquals("# Section", blocks.getFirst().markdown());
+ assertEquals(List.of("Section"), blocks.getFirst().headingPath());
+ }
+ }
+
/** Fixtures that meet the accuracy threshold today and therefore gate CI. */
static Stream<Arguments> gatedFixtures() {
return Stream.of(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbConnectionSettings.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbConnectionSettings.java
new file mode 100644
index 0000000000..40fdb4f6fc
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbConnectionSettings.java
@@ -0,0 +1,24 @@
+package stirling.software.proprietary.integration.api;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/** Credentials belong to a connection; collection and field mapping belong to its source. */
+public record VectorDbConnectionSettings(String vendor, ApiConnectionSettings api) {
+ public static VectorDbConnectionSettings from(Map<String, Object> config) {
+ String vendor = String.valueOf(config.getOrDefault("vendor", "")).trim();
+ if (!vendor.equals("weaviate") && !vendor.equals("pinecone")) {
+ throw new IllegalArgumentException(
+ "Select a supported vector database: Weaviate or Pinecone");
+ }
+ Map<String, Object> api = new LinkedHashMap<>();
+ api.put("baseUrl", config.get("baseUrl"));
+ api.put("token", config.get("token"));
+ api.put("authType", vendor.equals("pinecone") ? "HEADER" : "BEARER");
+ if (vendor.equals("pinecone")) {
+ api.put("headerName", "Api-Key");
+ api.put("headers", Map.of("X-Pinecone-Api-Version", "2025-10"));
+ }
+ return new VectorDbConnectionSettings(vendor, ApiConnectionSettings.from(api));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbIntegrationValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbIntegrationValidator.java
new file mode 100644
index 0000000000..124b960127
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbIntegrationValidator.java
@@ -0,0 +1,32 @@
+package stirling.software.proprietary.integration.api;
+
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.integration.model.IntegrationType;
+import stirling.software.proprietary.integration.service.IntegrationConfigValidator;
+
+@Component
+@RequiredArgsConstructor
+public class VectorDbIntegrationValidator implements IntegrationConfigValidator {
+ private final ApplicationProperties applicationProperties;
+
+ @Override
+ public IntegrationType type() {
+ return IntegrationType.VECTOR_DB;
+ }
+
+ @Override
+ public void validate(Map<String, Object> config) {
+ validate(VectorDbConnectionSettings.from(config));
+ }
+
+ public void validate(VectorDbConnectionSettings settings) {
+ ApiIntegrationValidator.requirePublicHost(
+ settings.api(), applicationProperties, "Vector database URL");
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbWriter.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbWriter.java
new file mode 100644
index 0000000000..867936b75e
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/VectorDbWriter.java
@@ -0,0 +1,270 @@
+package stirling.software.proprietary.integration.api;
+
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.policy.output.CorpusChunk;
+import stirling.software.proprietary.policy.output.VectorDbTarget;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+/**
+ * Replaces a document's chunks; obsolete tail chunks are removed only after all upserts succeed.
+ */
+@Service
+@RequiredArgsConstructor
+public class VectorDbWriter {
+ private static final int BATCH_SIZE = 16;
+ private static final int MAX_CHUNK_BYTES = 60_000;
+ private final ExternalApiCaller caller;
+ private final ObjectMapper objectMapper;
+
+ public void replace(
+ VectorDbConnectionSettings connection,
+ VectorDbTarget target,
+ String documentId,
+ List<CorpusChunk> chunks)
+ throws IOException {
+ for (CorpusChunk chunk : chunks) {
+ if (objectMapper.writeValueAsBytes(properties(target, documentId, chunk)).length
+ > MAX_CHUNK_BYTES) {
+ throw new IOException(
+ "A chunk exceeds the 60000-byte indexing limit; reduce the ingestion chunk size");
+ }
+ }
+ boolean weaviate = connection.vendor().equals("weaviate");
+ if (weaviate) verifyWeaviate(connection, target);
+ else verifyPinecone(connection, target);
+ for (int start = 0; start < chunks.size(); start += BATCH_SIZE) {
+ List<CorpusChunk> batch =
+ chunks.subList(start, Math.min(start + BATCH_SIZE, chunks.size()));
+ if (weaviate) {
+ ObjectNode body = objectMapper.createObjectNode();
+ var objects = body.putArray("objects");
+ for (CorpusChunk chunk : batch) {
+ ObjectNode object = objects.addObject();
+ object.put("class", target.collection());
+ object.put("id", chunkId(documentId, chunk.index()));
+ if (!target.namespace().equals("__default__"))
+ object.put("tenant", target.namespace());
+ object.set("properties", properties(target, documentId, chunk));
+ }
+ JsonNode result =
+ request(
+ connection,
+ "POST",
+ "/v1/batch/objects",
+ "application/json",
+ objectMapper.writeValueAsBytes(body));
+ if (!result.isArray() || result.size() != batch.size()) {
+ throw new IOException("Weaviate returned an incomplete batch result");
+ }
+ for (JsonNode item : result) {
+ if (!"SUCCESS".equals(item.path("result").path("status").asString())) {
+ throw new IOException(
+ "Weaviate rejected a chunk; check the collection schema and vectorizer credentials");
+ }
+ }
+ } else {
+ StringBuilder body = new StringBuilder();
+ for (CorpusChunk chunk : batch) {
+ ObjectNode record = properties(target, documentId, chunk);
+ record.put("_id", chunkId(documentId, chunk.index()));
+ body.append(objectMapper.writeValueAsString(record)).append('\n');
+ }
+ request(
+ connection,
+ "POST",
+ "/records/namespaces/" + encode(target.namespace()) + "/upsert",
+ "application/x-ndjson",
+ body.toString().getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ if (weaviate) {
+ deleteWeaviateTail(connection, target, documentId, chunks.size());
+ } else {
+ ObjectNode body = objectMapper.createObjectNode();
+ body.put("namespace", target.namespace());
+ ObjectNode filter = body.putObject("filter");
+ filter.putObject("documentId").put("$eq", documentId);
+ filter.putObject("chunkIndex").put("$gte", chunks.size());
+ request(
+ connection,
+ "POST",
+ "/vectors/delete",
+ "application/json",
+ objectMapper.writeValueAsBytes(body));
+ }
+ }
+
+ private ObjectNode properties(VectorDbTarget target, String documentId, CorpusChunk chunk) {
+ ObjectNode properties = objectMapper.createObjectNode();
+ properties.put(target.textField(), chunk.text());
+ properties.put("documentId", documentId);
+ properties.put("chunkIndex", chunk.index());
+ if (chunk.pageStart() != null) properties.put("pageStart", chunk.pageStart());
+ if (chunk.pageEnd() != null) properties.put("pageEnd", chunk.pageEnd());
+ if (!chunk.headingPath().isEmpty()) {
+ var headings = properties.putArray("headingPath");
+ chunk.headingPath().forEach(headings::add);
+ }
+ return properties;
+ }
+
+ private void verifyPinecone(VectorDbConnectionSettings connection, VectorDbTarget target)
+ throws IOException {
+ ApiConnectionSettings control =
+ ApiConnectionSettings.from(
+ Map.of(
+ "baseUrl",
+ "https://api.pinecone.io",
+ "authType",
+ "HEADER",
+ "headerName",
+ "Api-Key",
+ "token",
+ connection.api().token(),
+ "headers",
+ connection.api().headers()));
+ ExternalApiCaller.Response response =
+ caller.get(control, "/indexes/" + encode(target.collection()));
+ requireSuccess(response);
+ JsonNode index = objectMapper.readTree(response.body());
+ if (!target.textField()
+ .equals(index.path("embed").path("field_map").path("text").asString())
+ || !connection
+ .api()
+ .baseUri()
+ .getHost()
+ .equalsIgnoreCase(index.path("host").asString())) {
+ throw new IOException(
+ "Pinecone requires an integrated-embedding index with a matching index host and text field");
+ }
+ }
+
+ private void verifyWeaviate(VectorDbConnectionSettings connection, VectorDbTarget target)
+ throws IOException {
+ ExternalApiCaller.Response response =
+ caller.get(connection.api(), "/v1/schema/" + encode(target.collection()));
+ requireSuccess(response);
+ JsonNode schema = objectMapper.readTree(response.body());
+ String vectorizer = schema.path("vectorizer").asString("");
+ boolean embeds = !vectorizer.isBlank() && !vectorizer.equals("none");
+ JsonNode named = schema.path("vectorConfig");
+ if (named.isObject() && !named.isEmpty()) {
+ embeds = true;
+ for (JsonNode vector : named) {
+ JsonNode config = vector.path("vectorizer");
+ embeds &= config.isObject() && !config.isEmpty() && !config.has("none");
+ }
+ }
+ if (!embeds)
+ throw new IOException("The Weaviate collection must have a server-side vectorizer");
+ boolean multiTenant = schema.path("multiTenancyConfig").path("enabled").asBoolean();
+ if (multiTenant == target.namespace().equals("__default__")) {
+ throw new IOException(
+ "Set a tenant for a multi-tenant Weaviate collection; leave it empty for a single-tenant collection");
+ }
+ }
+
+ private void deleteWeaviateTail(
+ VectorDbConnectionSettings connection,
+ VectorDbTarget target,
+ String documentId,
+ int count)
+ throws IOException {
+ ObjectNode body = objectMapper.createObjectNode();
+ body.put("output", "minimal");
+ ObjectNode match = body.putObject("match");
+ match.put("class", target.collection());
+ ObjectNode where = match.putObject("where");
+ where.put("operator", "And");
+ var operands = where.putArray("operands");
+ ObjectNode document = operands.addObject();
+ document.putArray("path").add("documentId");
+ document.put("operator", "Equal");
+ document.put("valueText", documentId);
+ ObjectNode tail = operands.addObject();
+ tail.putArray("path").add("chunkIndex");
+ tail.put("operator", "GreaterThanEqual");
+ tail.put("valueInt", count);
+ String path = "/v1/batch/objects";
+ if (!target.namespace().equals("__default__"))
+ path += "?tenant=" + encode(target.namespace());
+ for (int attempt = 0; attempt < 100; attempt++) {
+ JsonNode result =
+ request(
+ connection,
+ "DELETE",
+ path,
+ "application/json",
+ objectMapper.writeValueAsBytes(body))
+ .path("results");
+ if (!result.has("failed") || result.path("failed").asInt() != 0) {
+ throw new IOException("Weaviate could not remove obsolete document chunks");
+ }
+ if (result.path("matches").asInt() <= result.path("successful").asInt()) return;
+ if (result.path("successful").asInt() == 0) break;
+ }
+ throw new IOException("Weaviate did not finish removing obsolete document chunks");
+ }
+
+ private JsonNode request(
+ VectorDbConnectionSettings connection,
+ String method,
+ String path,
+ String contentType,
+ byte[] body)
+ throws IOException {
+ for (int attempt = 0; ; attempt++) {
+ ExternalApiCaller.Response response =
+ caller.dispatch(
+ connection.api(),
+ method,
+ path,
+ ExternalApiCaller.raw(contentType, body),
+ Map.of());
+ if (attempt < 2 && (response.status() == 429 || response.status() >= 500)) {
+ try {
+ Thread.sleep(250L << attempt);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException("Vector indexing interrupted", e);
+ }
+ continue;
+ }
+ requireSuccess(response);
+ return response.body().length == 0
+ ? objectMapper.createObjectNode()
+ : objectMapper.readTree(response.body());
+ }
+ }
+
+ private static void requireSuccess(ExternalApiCaller.Response response) throws IOException {
+ if (response.status() < 200 || response.status() >= 300) {
+ throw new IOException(
+ "Vector database returned HTTP "
+ + response.status()
+ + "; check credentials, collection, text field and server-side embedding configuration");
+ }
+ }
+
+ private static String chunkId(String documentId, int index) {
+ return UUID.nameUUIDFromBytes((documentId + ":" + index).getBytes(StandardCharsets.UTF_8))
+ .toString();
+ }
+
+ private static String encode(String value) {
+ return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.java
index e372336763..74b7c652ae 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.java
@@ -11,5 +11,6 @@ public enum IntegrationType {
/** Microsoft Purview Information Protection: sensitivity-label taxonomy via Graph. */
PURVIEW,
/** ConsignO Cloud (Notarius) e-signature and notarization. */
- CONSIGNO
+ CONSIGNO,
+ VECTOR_DB
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java
index ea95556155..0674009864 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java
@@ -64,7 +64,7 @@ public class IntegrationConfigService {
&& scope == OwnerScope.USER
&& !ownership.isAdmin(currentUser)) {
throw forbidden(
- "S3 and network connections can only be created by administrators or team"
+ "Storage connections can only be created by administrators or team"
+ " owners");
}
requireCustomApiAllowed(cfg.getIntegrationType(), currentUser);
@@ -152,7 +152,9 @@ public class IntegrationConfigService {
/** Types holding shared host credentials, restricted to admins/team owners like S3. */
private static boolean isInfrastructureType(IntegrationType type) {
- return type == IntegrationType.S3 || type == IntegrationType.NETWORK;
+ return type == IntegrationType.S3
+ || type == IntegrationType.NETWORK
+ || type == IntegrationType.VECTOR_DB;
}
/** Whether this caller may author custom API integrations, for the UI to offer or hide it. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
index 7af0325764..39bac04ef7 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
@@ -367,10 +367,10 @@ public class PolicyController {
policy.outputIds().stream(),
policy.routingRules().stream().map(RoutingRule::outputId))
.distinct()
- .forEach(this::requireAccessibleDestination);
+ .forEach(outputId -> requireAccessibleDestination(outputId, policy.steps()));
}
- private void requireAccessibleDestination(String outputId) {
+ private void requireAccessibleDestination(String outputId, List<PipelineStep> steps) {
Source destination =
sourceStore
.get(outputId)
@@ -386,7 +386,7 @@ public class PolicyController {
HttpStatus.BAD_REQUEST, "The editor can't be used as an output destination");
}
try {
- policyValidator.validateOutput(destination.toOutputSpec());
+ policyValidator.validateOutput(destination.toOutputSpec(), steps);
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
@@ -734,7 +734,7 @@ public class PolicyController {
policyValidator.validateSteps(definition.steps());
// Every destination is checked; an ad-hoc run with no destinations validates nothing.
for (OutputSpec output : definition.outputs()) {
- policyValidator.validateOutput(output);
+ policyValidator.validateOutput(output, definition.steps());
}
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java
index e1e7de4a76..bf04800a3b 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java
@@ -239,7 +239,7 @@ public class ProcessingFolderController {
: existing == null ? List.of() : existing.routingRules();
Stream.concat(outputIds.stream(), routingRules.stream().map(RoutingRule::outputId))
.distinct()
- .forEach(this::requireAccessibleDestination);
+ .forEach(outputId -> requireAccessibleDestination(outputId, request.steps()));
String name = onDisk ? diskFolderName(request.directory()) : folder.getName();
// Held for rollback: the source is written before the policy validates, and a rejected
@@ -887,7 +887,7 @@ public class ProcessingFolderController {
return fileName == null ? path.toString() : fileName.toString();
}
- private void requireAccessibleDestination(String outputId) {
+ private void requireAccessibleDestination(String outputId, List<PipelineStep> steps) {
Source destination =
sourceStore
.get(outputId)
@@ -904,7 +904,7 @@ public class ProcessingFolderController {
}
// Validate on the request thread: connection checks need the caller's authentication.
try {
- policyValidator.validateOutput(destination.toOutputSpec());
+ policyValidator.validateOutput(destination.toOutputSpec(), steps);
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
index 95fb7adb86..e281ac18fe 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
@@ -82,7 +82,28 @@ public class PolicyValidator {
validateSteps(policy.steps());
validateAssetReferences(policy);
validateChain(policy.steps());
- validateOutput(policy.output());
+ validateOutput(policy.output(), policy.steps());
+ }
+
+ /** Corpus files must be delivered to a destination, never imported into the editor. */
+ public void validateEditorOutput(Policy policy) {
+ if (!policy.editor().allowed()
+ || !policy.outputIds().isEmpty()
+ || !"inline".equals(policy.output().type())) {
+ return;
+ }
+ for (PipelineStep step : policy.steps()) {
+ if (!"/api/v1/docparse/ingest".equals(step.operation())) {
+ continue;
+ }
+ Map<String, Object> params = step.parameters();
+ if (Boolean.parseBoolean(String.valueOf(params.get("exportChunksJsonl")))
+ || Boolean.parseBoolean(String.valueOf(params.get("exportMarkdown")))
+ || "false".equalsIgnoreCase(String.valueOf(params.get("includeOriginal")))) {
+ throw new IllegalArgumentException(
+ "Choose a file or database destination for chunk and Markdown exports. These files cannot be returned to the editor.");
+ }
+ }
}
/**
@@ -111,7 +132,7 @@ public class PolicyValidator {
new IllegalArgumentException(
"unknown routing destination: "
+ rule.outputId()));
- validateOutput(destination.toOutputSpec());
+ validateOutput(destination.toOutputSpec(), policy.steps());
}
}
@@ -189,27 +210,6 @@ public class PolicyValidator {
return toolChainValidator.validate(chain, sourceFormat);
}
- /** Corpus files must be delivered to a destination, never imported into the editor. */
- public void validateEditorOutput(Policy policy) {
- if (!policy.editor().allowed()
- || !policy.outputIds().isEmpty()
- || !"inline".equals(policy.output().type())) {
- return;
- }
- for (PipelineStep step : policy.steps()) {
- if (!"/api/v1/docparse/ingest".equals(step.operation())) {
- continue;
- }
- Map<String, Object> params = step.parameters();
- if (Boolean.parseBoolean(String.valueOf(params.get("exportChunksJsonl")))
- || Boolean.parseBoolean(String.valueOf(params.get("exportMarkdown")))
- || "false".equalsIgnoreCase(String.valueOf(params.get("includeOriginal")))) {
- throw new IllegalArgumentException(
- "Choose a file or database destination for chunk and Markdown exports. These files cannot be returned to the editor.");
- }
- }
- }
-
/**
* Validate each step against every registered {@link PipelineStepValidator}. Must be called on
* a request thread (caller's principal present) for the same reason as {@link
@@ -257,6 +257,12 @@ public class PolicyValidator {
outputSinkFor(output).validate(output);
}
+ /** Validate both the connection and the pipeline's deliverable on the caller's thread. */
+ public void validateOutput(OutputSpec output, List<PipelineStep> steps) {
+ validateOutput(output);
+ outputSinkFor(output).validatePipeline(output, steps);
+ }
+
private PolicyTrigger triggerFor(TriggerConfig config) {
return triggers.stream()
.filter(trigger -> trigger.type().equals(config.type()))
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/CorpusChunk.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/CorpusChunk.java
new file mode 100644
index 0000000000..342a3cb5c7
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/CorpusChunk.java
@@ -0,0 +1,24 @@
+package stirling.software.proprietary.policy.output;
+
+import java.util.List;
+
+/** One line of a AI ingestion corpus export. */
+public record CorpusChunk(
+ String documentId,
+ int index,
+ String text,
+ Integer pageStart,
+ Integer pageEnd,
+ List<String> headingPath) {
+ public CorpusChunk {
+ if (documentId == null
+ || documentId.isBlank()
+ || index < 0
+ || text == null
+ || text.isBlank()) {
+ throw new IllegalArgumentException(
+ "Corpus chunks require a document ID, nonnegative index and text");
+ }
+ headingPath = headingPath == null ? List.of() : List.copyOf(headingPath);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java
index 8e745e0b57..8b0f06f224 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java
@@ -3,6 +3,7 @@ package stirling.software.proprietary.policy.output;
import java.util.List;
import stirling.software.proprietary.policy.model.PolicyInputs;
+import stirling.software.proprietary.policy.model.PolicyRun;
/**
* Context for one run's output delivery. {@code policyId} is null for ad-hoc pipelines; when
@@ -10,19 +11,46 @@ import stirling.software.proprietary.policy.model.PolicyInputs;
* re-ingest them. {@code inputs} carries the run's inputs so a sink that writes back to where the
* input lives (e.g. a new version of a stored file) can correlate output to origin. {@code
* fileOwner} is resolved from the input source or uploader by the engine; storage outputs require
- * it and must not substitute the destination's owner.
+ * it and must not substitute the destination's owner. {@code documentIdentity} is a stable
+ * reference to the source document so a re-run upserts a vector document instead of duplicating it.
*/
-public record OutputDelivery(String runId, String policyId, PolicyInputs inputs, String fileOwner) {
+public record OutputDelivery(
+ String runId,
+ String policyId,
+ PolicyInputs inputs,
+ String fileOwner,
+ String documentIdentity) {
public OutputDelivery {
inputs = inputs == null ? PolicyInputs.of(List.of()) : inputs;
}
+ public OutputDelivery(String runId, String policyId, PolicyInputs inputs, String fileOwner) {
+ this(runId, policyId, inputs, fileOwner, null);
+ }
+
public OutputDelivery(String runId, String policyId, PolicyInputs inputs) {
- this(runId, policyId, inputs, null);
+ this(runId, policyId, inputs, null, null);
}
public OutputDelivery(String runId, String policyId) {
- this(runId, policyId, null, null);
+ this(runId, policyId, null, null, null);
+ }
+
+ /** Reuses the run's document reference, scoped to its source or submitting user. */
+ public static OutputDelivery forRun(PolicyRun run, PolicyInputs inputs) {
+ String identity = null;
+ if (inputs.primary().size() == 1) {
+ if (run.getSourceId() != null) {
+ String reference =
+ run.getFileIdentity() != null
+ ? run.getFileIdentity()
+ : inputs.primary().getFirst().getDescription();
+ identity = "source:" + run.getSourceId() + "\n" + reference;
+ } else if (run.getFileIdentity() != null) {
+ identity = "user:" + run.getTriggeringUser() + "\n" + run.getFileIdentity();
+ }
+ }
+ return new OutputDelivery(run.getRunId(), run.getPolicyId(), inputs, null, identity);
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputSink.java
index 7a9744f9e7..059773054b 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputSink.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputSink.java
@@ -7,6 +7,7 @@ import org.springframework.core.io.Resource;
import stirling.software.common.model.job.ResultFile;
import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.model.PipelineStep;
/**
* Delivers a finished run's outputs to a destination, returning {@link ResultFile} descriptors for
@@ -24,6 +25,9 @@ public interface PolicyOutputSink {
/** Throws {@link IllegalArgumentException} on bad config. Called on save to fail fast. */
default void validate(OutputSpec spec) {}
+ /** Validate the final step's output against this destination's input contract. */
+ default void validatePipeline(OutputSpec spec, List<PipelineStep> steps) {}
+
/** Persist/deliver the output files and return their descriptors. */
List<ResultFile> deliver(OutputDelivery delivery, List<Resource> outputs, OutputSpec spec)
throws IOException;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/VectorDbOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/VectorDbOutputSink.java
new file mode 100644
index 0000000000..4edb161d4e
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/VectorDbOutputSink.java
@@ -0,0 +1,161 @@
+package stirling.software.proprietary.policy.output;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.springframework.core.io.Resource;
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.common.model.job.ResultFile;
+import stirling.software.common.service.FileStorage;
+import stirling.software.proprietary.integration.api.ApiConnectionResolver;
+import stirling.software.proprietary.integration.api.VectorDbConnectionSettings;
+import stirling.software.proprietary.integration.api.VectorDbIntegrationValidator;
+import stirling.software.proprietary.integration.api.VectorDbWriter;
+import stirling.software.proprietary.integration.model.IntegrationType;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.model.PipelineStep;
+
+import tools.jackson.databind.ObjectMapper;
+
+@Service
+@RequiredArgsConstructor
+public class VectorDbOutputSink implements PolicyOutputSink {
+ private final ApiConnectionResolver connectionResolver;
+ private final VectorDbIntegrationValidator connectionValidator;
+ private final VectorDbWriter writer;
+ private final ObjectMapper objectMapper;
+ private final FileStorage fileStorage;
+
+ @Override
+ public String type() {
+ return "vectordb";
+ }
+
+ @Override
+ public boolean supports(OutputSpec spec) {
+ return spec != null && type().equals(spec.type());
+ }
+
+ @Override
+ public void validate(OutputSpec spec) {
+ resolve(VectorDbTarget.from(spec.options()));
+ }
+
+ @Override
+ public void validatePipeline(OutputSpec spec, List<PipelineStep> steps) {
+ if (steps.isEmpty()) {
+ throw new IllegalArgumentException(
+ "A vector database destination requires a final AI ingestion step");
+ }
+ PipelineStep last = steps.getLast();
+ Map<String, Object> params = last.parameters();
+ if (!"/api/v1/docparse/ingest".equals(last.operation())
+ || !"true".equals(String.valueOf(params.get("exportChunksJsonl")))
+ || !"false".equals(String.valueOf(params.get("includeOriginal")))
+ || "true".equals(String.valueOf(params.get("exportMarkdown")))) {
+ throw new IllegalArgumentException(
+ "The final AI ingestion step must export chunks only, with the original PDF and Markdown excluded");
+ }
+ }
+
+ @Override
+ public List<ResultFile> deliver(
+ OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) throws IOException {
+ VectorDbTarget target = VectorDbTarget.from(spec.options());
+ VectorDbConnectionSettings connection = resolve(target);
+ if (outputs.isEmpty()) {
+ return List.of();
+ }
+ List<List<CorpusChunk>> documents = new ArrayList<>();
+ for (Resource output : outputs) {
+ documents.add(readCorpus(output));
+ }
+ int indexed = 0;
+ for (int i = 0; i < documents.size(); i++) {
+ List<CorpusChunk> chunks = documents.get(i);
+ String identity =
+ delivery.documentIdentity() != null
+ ? delivery.documentIdentity()
+ : chunks.getFirst().documentId();
+ identity += "\n" + outputs.get(i).getFilename();
+ String documentId =
+ UUID.nameUUIDFromBytes(
+ (delivery.policyId() + "\n" + identity)
+ .getBytes(StandardCharsets.UTF_8))
+ .toString();
+ writer.replace(connection, target, documentId, chunks);
+ indexed += chunks.size();
+ }
+ byte[] receipt =
+ objectMapper.writeValueAsBytes(
+ Map.of(
+ "documentsIndexed",
+ documents.size(),
+ "chunksIndexed",
+ indexed,
+ "collection",
+ target.collection(),
+ "vendor",
+ connection.vendor()));
+ String name = "indexing-report.json";
+ FileStorage.StoredFile stored =
+ fileStorage.storeInputStream(new ByteArrayInputStream(receipt), name);
+ return List.of(
+ ResultFile.builder()
+ .fileId(stored.fileId())
+ .fileName(name)
+ .contentType("application/json")
+ .fileSize(stored.size())
+ .build());
+ }
+
+ private VectorDbConnectionSettings resolve(VectorDbTarget target) {
+ VectorDbConnectionSettings connection =
+ VectorDbConnectionSettings.from(
+ connectionResolver.resolveConfig(
+ target.connectionId(), IntegrationType.VECTOR_DB));
+ connectionValidator.validate(connection);
+ return connection;
+ }
+
+ private List<CorpusChunk> readCorpus(Resource resource) throws IOException {
+ if (resource.getFilename() == null || !resource.getFilename().endsWith(".chunks.jsonl")) {
+ throw new IOException(
+ "Vector database destinations accept only ingestion chunk exports");
+ }
+ if (resource.contentLength() > 32L * 1024 * 1024) {
+ throw new IOException("Corpus exceeds the 32 MiB limit");
+ }
+ List<CorpusChunk> chunks = new ArrayList<>();
+ try (BufferedReader reader =
+ new BufferedReader(
+ new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ if (line.isBlank()) continue;
+ CorpusChunk chunk = objectMapper.readValue(line, CorpusChunk.class);
+ if (chunk.index() != chunks.size()
+ || (!chunks.isEmpty()
+ && !chunk.documentId().equals(chunks.getFirst().documentId()))) {
+ throw new IOException(
+ "Corpus must contain contiguous chunks from one document");
+ }
+ chunks.add(chunk);
+ if (chunks.size() > 10000)
+ throw new IOException("Corpus exceeds the 10000 chunk limit");
+ }
+ }
+ if (chunks.isEmpty()) throw new IOException("AI ingestion produced no chunks to index");
+ return chunks;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/VectorDbTarget.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/VectorDbTarget.java
new file mode 100644
index 0000000000..0deb53698e
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/VectorDbTarget.java
@@ -0,0 +1,38 @@
+package stirling.software.proprietary.policy.output;
+
+import java.util.Map;
+import java.util.Set;
+
+import stirling.software.proprietary.integration.api.ApiConnectionResolver;
+
+/** A pre-existing vector collection and its text field. */
+public record VectorDbTarget(
+ long connectionId, String collection, String namespace, String textField) {
+ public static VectorDbTarget from(Map<String, Object> options) {
+ Long id = ApiConnectionResolver.connectionId(options.get("connectionId"));
+ if (id == null) {
+ throw new IllegalArgumentException("Vector database source requires a connection");
+ }
+ String collection = value(options, "collection", "");
+ String namespace = value(options, "namespace", "__default__");
+ String textField = value(options, "textField", "text");
+ if (!collection.matches("[A-Za-z][A-Za-z0-9_-]{0,254}")) {
+ throw new IllegalArgumentException("Enter a valid collection or index name");
+ }
+ if (namespace.length() > 512) {
+ throw new IllegalArgumentException("Namespace must be at most 512 characters");
+ }
+ if (!textField.matches("[a-zA-Z][a-zA-Z0-9_]{0,127}")
+ || Set.of("id", "documentId", "chunkIndex", "pageStart", "pageEnd", "headingPath")
+ .contains(textField)) {
+ throw new IllegalArgumentException(
+ "Choose a text field distinct from the chunk metadata fields");
+ }
+ return new VectorDbTarget(id, collection, namespace, textField);
+ }
+
+ private static String value(Map<String, Object> options, String key, String fallback) {
+ Object raw = options.get(key);
+ return raw == null || raw.toString().isBlank() ? fallback : raw.toString().trim();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/Source.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/Source.java
index c064a33d9a..32bf75a376 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/Source.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/Source.java
@@ -12,11 +12,10 @@ import stirling.software.proprietary.policy.model.OutputSpec;
* run's files are delivered to it), which is how a folder or bucket can be both the output of one
* pipeline and the input of the next.
*
- * <p>{@code type} keys an {@link stirling.software.proprietary.policy.input.InputSource} bean (and,
- * for writable types, a {@link stirling.software.proprietary.policy.output.PolicyOutputSink}),
- * matching {@link InputSpec#type()}; {@code options} is that location's config. {@code owner} and
- * {@code teamId} scope the source to a team, mirroring {@link
- * stirling.software.proprietary.policy.model.Policy}.
+ * <p>{@code type} keys an {@link stirling.software.proprietary.policy.input.InputSource} bean, a
+ * {@link stirling.software.proprietary.policy.output.PolicyOutputSink}, or both, matching {@link
+ * InputSpec#type()}; {@code options} is that location's config. {@code owner} and {@code teamId}
+ * scope the source to a team, mirroring {@link stirling.software.proprietary.policy.model.Policy}.
*/
public record Source(
String id,
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java
index 7097d60cbd..76d27afa12 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java
@@ -31,6 +31,7 @@ import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
import stirling.software.proprietary.policy.input.InputSource;
import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.output.PolicyOutputSink;
import stirling.software.proprietary.policy.store.PolicyStore;
import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;
import stirling.software.proprietary.util.SecretMasker;
@@ -66,6 +67,7 @@ public class SourceController {
private final PolicyTriggerManager policyTriggerManager;
private final ApplicationProperties applicationProperties;
private final List<InputSource> inputSources;
+ private final List<PolicyOutputSink> outputSinks;
@GetMapping
@Operation(
@@ -253,10 +255,17 @@ public class SourceController {
/** Validate the config against the bean that handles the source's type, as the engine will. */
private void validateConfig(Source source) {
InputSpec spec = source.toInputSpec();
- inputSourceFor(spec)
+ Optional<InputSource> input = inputSourceFor(spec);
+ if (input.isPresent()) {
+ input.get().validate(spec);
+ return;
+ }
+ outputSinks.stream()
+ .filter(sink -> sink.supports(source.toOutputSpec()))
+ .findFirst()
.orElseThrow(
() -> new IllegalArgumentException("unknown source type: " + source.type()))
- .validate(spec);
+ .validate(source.toOutputSpec());
}
private Source withPreparedOptions(Source source, boolean isCreate) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/SecurityExceptionHandler.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/SecurityExceptionHandler.java
new file mode 100644
index 0000000000..9c63b7d4ce
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/SecurityExceptionHandler.java
@@ -0,0 +1,18 @@
+package stirling.software.proprietary.security.controller.api;
+
+import org.springframework.core.Ordered;
+import org.springframework.core.annotation.Order;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ProblemDetail;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+@Order(Ordered.HIGHEST_PRECEDENCE)
+public class SecurityExceptionHandler {
+ @ExceptionHandler(AccessDeniedException.class)
+ public ProblemDetail accessDenied(AccessDeniedException exception) {
+ return ProblemDetail.forStatusAndDetail(HttpStatus.FORBIDDEN, "Access denied");
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java
index c2e47c22c9..e76bd2811c 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java
@@ -144,6 +144,10 @@ public class DocParseService {
// Chunking lives in the engine, so an export-markdown-only run needs no round trip at all.
if (index || includeChunks) {
String callerId = currentUserId();
+ if (callerId == null || callerId.isBlank()) {
+ throw new ResponseStatusException(
+ HttpStatus.UNAUTHORIZED, "Sign in to index documents or export chunks");
+ }
// Null expiresAt = persistent until explicit delete; ingest here is a deliberate
// knowledge-base action, unlike the TTL'd auto-ingest in AiWorkflowService.
IngestRequest request =
@@ -151,9 +155,7 @@ public class DocParseService {
docId,
fileName(file),
callerId,
- // Engine forbids an empty list here (min_length=1); null means
- // "default to the owner" on the engine side.
- callerId == null ? null : List.of(callerId),
+ List.of(callerId),
null,
blocks,
size,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/VectorDbWriterHttpTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/VectorDbWriterHttpTest.java
new file mode 100644
index 0000000000..ce8414ea85
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/VectorDbWriterHttpTest.java
@@ -0,0 +1,112 @@
+package stirling.software.proprietary.integration.api;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import org.junit.jupiter.api.Test;
+
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.output.CorpusChunk;
+import stirling.software.proprietary.policy.output.VectorDbTarget;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+class VectorDbWriterHttpTest {
+ private record Request(String method, String authorization, JsonNode body) {}
+
+ @Test
+ void sendsAuthenticatedBatchesWithStableIdsThenDeletesOnlyTheObsoleteTail() throws Exception {
+ var mapper = JsonMapper.builder().build();
+ var requests = new ConcurrentLinkedQueue<Request>();
+ HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/v1/schema/Documents",
+ exchange -> {
+ byte[] response =
+ "{\"vectorizer\":\"text2vec-openai\"}".getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ });
+ server.createContext(
+ "/v1/batch/objects",
+ exchange -> {
+ JsonNode body = mapper.readTree(exchange.getRequestBody().readAllBytes());
+ requests.add(
+ new Request(
+ exchange.getRequestMethod(),
+ exchange.getRequestHeaders().getFirst("Authorization"),
+ body));
+ byte[] response;
+ if (exchange.getRequestMethod().equals("POST")) {
+ var results = mapper.createArrayNode();
+ body.path("objects")
+ .forEach(
+ ignored ->
+ results.addObject()
+ .putObject("result")
+ .put("status", "SUCCESS"));
+ response = mapper.writeValueAsBytes(results);
+ } else {
+ response =
+ "{\"results\":{\"failed\":0,\"matches\":0,\"successful\":0}}"
+ .getBytes(StandardCharsets.UTF_8);
+ }
+ exchange.sendResponseHeaders(200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ });
+ server.start();
+ try {
+ var properties = new ApplicationProperties();
+ properties.getPolicies().setAllowPrivateApiEndpoints(true);
+ var writer = new VectorDbWriter(new ExternalApiCaller(properties, mapper), mapper);
+ var connection =
+ VectorDbConnectionSettings.from(
+ Map.of(
+ "vendor",
+ "weaviate",
+ "token",
+ "test-key",
+ "baseUrl",
+ "http://127.0.0.1:" + server.getAddress().getPort()));
+ var target = new VectorDbTarget(1, "Documents", "__default__", "content");
+ var chunks = new ArrayList<CorpusChunk>();
+ for (int i = 0; i < 17; i++)
+ chunks.add(new CorpusChunk("old", i, "text " + i, 1, 2, List.of("Heading")));
+ writer.replace(connection, target, "external-doc", chunks);
+ writer.replace(
+ connection,
+ target,
+ "external-doc",
+ List.of(new CorpusChunk("new", 0, "updated", 1, 1, List.of())));
+ List<Request> sent = List.copyOf(requests);
+ assertEquals(
+ List.of("POST", "POST", "DELETE", "POST", "DELETE"),
+ sent.stream().map(Request::method).toList());
+ assertTrue(
+ sent.stream()
+ .allMatch(
+ request -> "Bearer test-key".equals(request.authorization())));
+ JsonNode first = sent.getFirst().body().path("objects").get(0);
+ JsonNode replacement = sent.get(3).body().path("objects").get(0);
+ assertEquals(first.path("id"), replacement.path("id"));
+ assertEquals("updated", replacement.path("properties").path("content").asString());
+ assertEquals("external-doc", first.path("properties").path("documentId").asString());
+ JsonNode operands = sent.getLast().body().path("match").path("where").path("operands");
+ assertEquals("external-doc", operands.get(0).path("valueText").asString());
+ assertEquals(1, operands.get(1).path("valueInt").asInt());
+ } finally {
+ server.stop(0);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/VectorDbWriterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/VectorDbWriterTest.java
new file mode 100644
index 0000000000..5a35ff6b87
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/VectorDbWriterTest.java
@@ -0,0 +1,123 @@
+package stirling.software.proprietary.integration.api;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.proprietary.policy.output.CorpusChunk;
+import stirling.software.proprietary.policy.output.VectorDbTarget;
+
+import tools.jackson.databind.json.JsonMapper;
+
+class VectorDbWriterTest {
+ private final ExternalApiCaller caller = mock(ExternalApiCaller.class);
+ private final VectorDbWriter writer = new VectorDbWriter(caller, JsonMapper.builder().build());
+ private final VectorDbTarget target = new VectorDbTarget(1, "Documents", "__default__", "text");
+ private final List<CorpusChunk> chunks =
+ List.of(new CorpusChunk("doc", 0, "hello", 1, 1, List.of()));
+
+ private VectorDbConnectionSettings connection(String vendor) {
+ return VectorDbConnectionSettings.from(
+ Map.of(
+ "vendor",
+ vendor,
+ "baseUrl",
+ "https://index.example.com",
+ "token",
+ "test-key"));
+ }
+
+ private static ExternalApiCaller.Response response(int status, String body) {
+ return new ExternalApiCaller.Response(
+ status, "application/json", body.getBytes(StandardCharsets.UTF_8), Map.of());
+ }
+
+ @Test
+ void weaviateChecksPerObjectFailuresBeforeRemovingOldChunks() throws IOException {
+ when(caller.get(any(), any()))
+ .thenReturn(response(200, "{\"vectorizer\":\"text2vec-openai\"}"));
+ when(caller.dispatch(any(), eq("POST"), any(), any(), any()))
+ .thenReturn(response(200, "[{\"result\":{\"status\":\"FAILED\"}}]"));
+ assertThrows(
+ IOException.class,
+ () -> writer.replace(connection("weaviate"), target, "doc", chunks));
+ verify(caller, never()).dispatch(any(), eq("DELETE"), any(), any(), any());
+ }
+
+ @Test
+ void weaviateRefusesACollectionWithoutEmbedding() throws IOException {
+ when(caller.get(any(), any())).thenReturn(response(200, "{\"vectorizer\":\"none\"}"));
+ assertThrows(
+ IOException.class,
+ () -> writer.replace(connection("weaviate"), target, "doc", chunks));
+ verify(caller, never()).dispatch(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void cleanupFailureFailsTheDelivery() throws IOException {
+ when(caller.get(any(), any()))
+ .thenReturn(response(200, "{\"vectorizer\":\"text2vec-openai\"}"));
+ when(caller.dispatch(any(), eq("POST"), any(), any(), any()))
+ .thenReturn(response(200, "[{\"result\":{\"status\":\"SUCCESS\"}}]"));
+ when(caller.dispatch(any(), eq("DELETE"), any(), any(), any()))
+ .thenReturn(response(200, "{\"results\":{\"failed\":1}}"));
+ assertThrows(
+ IOException.class,
+ () -> writer.replace(connection("weaviate"), target, "doc", chunks));
+ }
+
+ @Test
+ void pineconeRetriesRateLimitsAndThenRemovesTheObsoleteTail() throws IOException {
+ when(caller.get(any(), eq("/indexes/Documents")))
+ .thenReturn(
+ response(
+ 200,
+ "{\"host\":\"index.example.com\",\"embed\":{\"field_map\":{\"text\":\"text\"}}}"));
+ when(caller.dispatch(any(), eq("POST"), contains("/upsert"), any(), any()))
+ .thenReturn(response(429, "{}"), response(201, ""));
+ when(caller.dispatch(any(), eq("POST"), eq("/vectors/delete"), any(), any()))
+ .thenReturn(response(200, "{}"));
+ writer.replace(connection("pinecone"), target, "doc", chunks);
+ var ordered = inOrder(caller);
+ ordered.verify(caller, times(2))
+ .dispatch(any(), eq("POST"), contains("/upsert"), any(), any());
+ ordered.verify(caller).dispatch(any(), eq("POST"), eq("/vectors/delete"), any(), any());
+ }
+
+ @Test
+ void pineconeRejectsClassicIndexesBeforeWriting() throws IOException {
+ when(caller.get(any(), any()))
+ .thenReturn(response(200, "{\"host\":\"index.example.com\"}"));
+ assertThrows(
+ IOException.class,
+ () -> writer.replace(connection("pinecone"), target, "doc", chunks));
+ verify(caller, never()).dispatch(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void authIsFixedByVendorAndCannotBeOverriddenByConfig() {
+ var config =
+ VectorDbConnectionSettings.from(
+ Map.of(
+ "vendor",
+ "pinecone",
+ "baseUrl",
+ "https://index.example.com",
+ "token",
+ "test-key",
+ "authType",
+ "NONE",
+ "headerName",
+ "Other"));
+ assertEquals(ApiAuthType.HEADER, config.api().authType());
+ assertEquals("Api-Key", config.api().headerName());
+ assertEquals("2025-10", config.api().headers().get("X-Pinecone-Api-Version"));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
index 7b5f3abf6b..67f46593a1 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
@@ -289,7 +289,7 @@ class PolicyControllerTest {
new OutputSpec("s3", Map.of("connectionId", 999)));
doThrow(new IllegalArgumentException("unknown or inaccessible s3 connection"))
.when(policyValidator)
- .validateOutput(any());
+ .validateOutput(any(), any());
assertThatThrownBy(() -> controller.run(definition, null, new PolicyRunFiles()))
.isInstanceOf(ResponseStatusException.class)
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
index ed68df17ae..b46d359971 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
@@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
@@ -348,6 +349,41 @@ class ProcessingFolderControllerTest {
verify(policyRunner, timeout(2000)).run(stored, SweepKind.USER);
}
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void rejectsIncompatibleFallbackAndRoutingDestinationsBeforeSaving(boolean routed) {
+ Source destination =
+ sourceStore.save(
+ new Source(null, "Vectors", "vectordb", Map.of(), true, "reece", 3L));
+ var baseline = request(null, "new_version");
+ doThrow(new IllegalArgumentException("chunks required"))
+ .when(diskFolderSink)
+ .validatePipeline(destination.toOutputSpec(), baseline.steps());
+ var routes =
+ List.of(
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("classification.labels"),
+ List.of("invoice")),
+ destination.id()));
+ var request =
+ new ProcessingFolderController.SaveProcessingFolderRequest(
+ null,
+ FOLDER_ID.toString(),
+ null,
+ true,
+ baseline.steps(),
+ Map.of(),
+ routed ? List.of() : List.of(destination.id()),
+ routed ? routes : List.of());
+
+ assertThatThrownBy(() -> controller.save(request))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("chunks required");
+ assertThat(policyStore.all()).isEmpty();
+ assertThat(sourceStore.all()).hasSize(1);
+ }
+
@Test
void aForeignOutputFolderIdIsOverriddenWithTheOwnedSourceFolder() {
// The caller owns FOLDER_ID but points output at someone else's folder.
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
index cbc9715c37..73a29a04b1 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
@@ -417,6 +417,22 @@ class PolicyValidatorTest {
verify(outputSink).validate(sourceStore.get(destinationId).orElseThrow().toOutputSpec());
}
+ @Test
+ void rejectsRoutingWhenTheDestinationCannotAcceptThePipelineOutput() {
+ when(outputSink.supports(any())).thenReturn(true);
+ String destinationId = folderSourceId();
+ Policy policy = routingPolicy(rule("classification.labels", "invoice", destinationId));
+ doThrow(new IllegalArgumentException("chunks required"))
+ .when(outputSink)
+ .validatePipeline(
+ sourceStore.get(destinationId).orElseThrow().toOutputSpec(),
+ policy.steps());
+
+ IllegalArgumentException error =
+ assertThrows(IllegalArgumentException.class, () -> validator.validate(policy));
+ assertTrue(error.getMessage().contains("chunks required"));
+ }
+
@Test
void rejectsARoutingRuleWithNoField() {
Policy policy = routingPolicy(rule(" ", "invoice", folderSourceId()));
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java
index fd7f5e9d52..93242ccdb1 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java
@@ -147,7 +147,8 @@ class StorageFolderAuthorizationTest {
authority,
mock(PolicyTriggerManager.class),
properties,
- List.of(input));
+ List.of(input),
+ List.of());
runner =
new PolicyRunner(
engine,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java
new file mode 100644
index 0000000000..015ff2a1d7
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java
@@ -0,0 +1,53 @@
+package stirling.software.proprietary.policy.output;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.core.io.FileSystemResource;
+
+import stirling.software.proprietary.policy.model.*;
+
+class OutputDeliveryTest {
+ private static OutputDelivery delivery(
+ String source, String document, String user, String path) {
+ var run =
+ new PolicyRun(
+ "run",
+ "policy",
+ new PipelineDefinition("test", List.of(), OutputSpec.inline()),
+ source,
+ document,
+ user);
+ return OutputDelivery.forRun(run, PolicyInputs.of(List.of(new FileSystemResource(path))));
+ }
+
+ @Test
+ void editorRetriesShareAnIdentityWithinTheSubmittingUser() {
+ var first = delivery(null, "workspace-id", "alice", "/tmp/first");
+ var retry = delivery(null, "workspace-id", "alice", "/tmp/retry");
+ assertEquals(first.documentIdentity(), retry.documentIdentity());
+ assertNotEquals(
+ first.documentIdentity(),
+ delivery(null, "workspace-id", "bob", "/tmp/third").documentIdentity());
+ }
+
+ @Test
+ void sourceIdentityDoesNotDependOnWhoTriggeredTheRun() {
+ assertEquals(
+ delivery("source", "file", null, "/input/pdf").documentIdentity(),
+ delivery("source", "file", "alice", "/input/pdf").documentIdentity());
+ assertNotEquals(
+ delivery("source", "file", null, "/input/pdf").documentIdentity(),
+ delivery("another", "file", null, "/input/pdf").documentIdentity());
+ }
+
+ @Test
+ void snapshotsUseTheirOriginalLocationAndAnonymousUploadsUseTheCorpusIdentity() {
+ assertEquals(
+ delivery("source", null, null, "/input/pdf").documentIdentity(),
+ delivery("source", null, "alice", "/input/pdf").documentIdentity());
+ assertNull(delivery(null, null, "alice", "/tmp/upload").documentIdentity());
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/VectorDbOutputSinkTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/VectorDbOutputSinkTest.java
new file mode 100644
index 0000000000..3d1b4b8183
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/VectorDbOutputSinkTest.java
@@ -0,0 +1,197 @@
+package stirling.software.proprietary.policy.output;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.core.io.ByteArrayResource;
+
+import stirling.software.common.service.FileStorage;
+import stirling.software.proprietary.integration.api.ApiConnectionResolver;
+import stirling.software.proprietary.integration.api.VectorDbIntegrationValidator;
+import stirling.software.proprietary.integration.api.VectorDbWriter;
+import stirling.software.proprietary.integration.model.IntegrationType;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.model.PipelineStep;
+import stirling.software.proprietary.policy.model.PolicyInputs;
+
+import tools.jackson.databind.json.JsonMapper;
+
+class VectorDbOutputSinkTest {
+ private final ApiConnectionResolver resolver = mock(ApiConnectionResolver.class);
+ private final VectorDbWriter writer = mock(VectorDbWriter.class);
+ private final FileStorage fileStorage = mock(FileStorage.class);
+ private final VectorDbOutputSink sink =
+ new VectorDbOutputSink(
+ resolver,
+ mock(VectorDbIntegrationValidator.class),
+ writer,
+ JsonMapper.builder().build(),
+ fileStorage);
+ private final OutputSpec output =
+ new OutputSpec("vectordb", Map.of("connectionId", "42", "collection", "Documents"));
+
+ @Test
+ void changedContentReusesTheOriginalSourceIdentity() throws IOException {
+ when(resolver.resolveConfig(42L, IntegrationType.VECTOR_DB))
+ .thenReturn(
+ Map.of(
+ "vendor",
+ "weaviate",
+ "baseUrl",
+ "https://db.example.com",
+ "token",
+ "test-key"));
+ when(fileStorage.storeInputStream(any(), any()))
+ .thenReturn(new FileStorage.StoredFile("receipt", 80));
+ var original =
+ new ByteArrayResource(new byte[0]) {
+ @Override
+ public String getDescription() {
+ return "s3://bucket/document.pdf";
+ }
+ };
+ var delivery =
+ new OutputDelivery(
+ "run",
+ "policy",
+ PolicyInputs.of(List.of(original)),
+ null,
+ "source:documents/document");
+ sink.deliver(delivery, List.of(corpus("hash-before", 0)), output);
+ sink.deliver(delivery, List.of(corpus("hash-after", 0)), output);
+ ArgumentCaptor<String> ids = ArgumentCaptor.forClass(String.class);
+ verify(writer, times(2)).replace(any(), any(), ids.capture(), any());
+ assertEquals(ids.getAllValues().getFirst(), ids.getAllValues().getLast());
+ }
+
+ @Test
+ void retryUsesTheRunReferenceDespiteDifferentUploadTempPaths() throws IOException {
+ when(resolver.resolveConfig(42L, IntegrationType.VECTOR_DB))
+ .thenReturn(
+ Map.of(
+ "vendor",
+ "weaviate",
+ "baseUrl",
+ "https://db.example.com",
+ "token",
+ "test-key"));
+ when(fileStorage.storeInputStream(any(), any()))
+ .thenReturn(new FileStorage.StoredFile("receipt", 80));
+ var first =
+ new OutputDelivery(
+ "run-1",
+ "policy",
+ PolicyInputs.of(
+ List.of(
+ new org.springframework.core.io.FileSystemResource(
+ "/tmp/upload-one"))),
+ null,
+ "user:alice/document");
+ var retry =
+ new OutputDelivery(
+ "run-2",
+ "policy",
+ PolicyInputs.of(
+ List.of(
+ new org.springframework.core.io.FileSystemResource(
+ "/tmp/upload-two"))),
+ null,
+ "user:alice/document");
+ sink.deliver(first, List.of(corpus("first-content", 0)), output);
+ sink.deliver(retry, List.of(corpus("changed-content", 0)), output);
+ sink.deliver(
+ new OutputDelivery("run-3", "policy", retry.inputs(), null, "user:bob/document"),
+ List.of(corpus("changed-content", 0)),
+ output);
+ ArgumentCaptor<String> ids = ArgumentCaptor.forClass(String.class);
+ verify(writer, times(3)).replace(any(), any(), ids.capture(), any());
+ assertEquals(ids.getAllValues().get(0), ids.getAllValues().get(1));
+ assertNotEquals(ids.getAllValues().get(1), ids.getAllValues().get(2));
+ }
+
+ @Test
+ void malformedCorpusNeverReachesTheWriter() {
+ when(resolver.resolveConfig(42L, IntegrationType.VECTOR_DB))
+ .thenReturn(
+ Map.of(
+ "vendor",
+ "weaviate",
+ "baseUrl",
+ "https://db.example.com",
+ "token",
+ "test-key"));
+ assertThrows(
+ IOException.class,
+ () ->
+ sink.deliver(
+ new OutputDelivery("run", "policy"),
+ List.of(corpus("doc", 3)),
+ output));
+ verifyNoInteractions(writer);
+ }
+
+ private static ByteArrayResource corpus(String id, int index) {
+ String line = "{\"documentId\":\"" + id + "\",\"index\":" + index + ",\"text\":\"hello\"}";
+ return new ByteArrayResource(line.getBytes(StandardCharsets.UTF_8)) {
+ @Override
+ public String getFilename() {
+ return "document.chunks.jsonl";
+ }
+ };
+ }
+
+ @Test
+ void connectionOwnershipIsCheckedDuringValidation() {
+ when(resolver.resolveConfig(42L, IntegrationType.VECTOR_DB))
+ .thenThrow(new IllegalArgumentException("inaccessible"));
+ assertThrows(IllegalArgumentException.class, () -> sink.validate(output));
+ verify(resolver).resolveConfig(42L, IntegrationType.VECTOR_DB);
+ }
+
+ @Test
+ void rejectsMixedOutputsBeforeAnyDatabaseWrite() {
+ when(resolver.resolveConfig(42L, IntegrationType.VECTOR_DB))
+ .thenReturn(
+ Map.of(
+ "vendor",
+ "weaviate",
+ "baseUrl",
+ "https://db.example.com",
+ "token",
+ "test-key"));
+ var pdf =
+ new ByteArrayResource("pdf".getBytes(StandardCharsets.UTF_8)) {
+ @Override
+ public String getFilename() {
+ return "document.pdf";
+ }
+ };
+ assertThrows(
+ IOException.class,
+ () -> sink.deliver(new OutputDelivery("run", "policy"), List.of(pdf), output));
+ verifyNoInteractions(writer);
+ }
+
+ @Test
+ void requiresAChunksOnlyTerminalStep() {
+ var valid =
+ new PipelineStep(
+ "/api/v1/docparse/ingest",
+ Map.of("includeOriginal", false, "exportChunksJsonl", true));
+ sink.validatePipeline(output, List.of(valid));
+ var mixed = new PipelineStep("/api/v1/docparse/ingest", Map.of("exportChunksJsonl", true));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> sink.validatePipeline(output, List.of(mixed)));
+ assertThrows(
+ IllegalArgumentException.class, () -> sink.validatePipeline(output, List.of()));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java
index a9730de452..f63cd6476f 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java
@@ -36,6 +36,7 @@ import stirling.software.proprietary.policy.model.PipelineInput;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.RoutingRule;
+import stirling.software.proprietary.policy.output.PolicyOutputSink;
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
import stirling.software.proprietary.policy.store.PolicyStore;
import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;
@@ -54,6 +55,7 @@ class SourceControllerTest {
private PolicyTriggerManager triggerManager;
private SourceController controller;
private SourceController webhookController;
+ private final PolicyOutputSink vectorSink = mock(PolicyOutputSink.class);
@TempDir Path tempDir;
@@ -75,7 +77,19 @@ class SourceControllerTest {
triggerManager = mock(PolicyTriggerManager.class);
// A permissive input source so config validation passes and save can be exercised.
InputSource folderInput = mock(InputSource.class);
- when(folderInput.supports(any())).thenReturn(true);
+ when(folderInput.supports(any()))
+ .thenAnswer(
+ invocation ->
+ !"vectordb"
+ .equals(
+ ((stirling.software.proprietary.policy.model
+ .InputSpec)
+ invocation.getArgument(0))
+ .type()));
+ when(vectorSink.supports(any()))
+ .thenAnswer(
+ invocation ->
+ "vectordb".equals(((OutputSpec) invocation.getArgument(0)).type()));
when(folderInput.prepareOptionsForSave(any(), anyBoolean()))
.thenAnswer(invocation -> invocation.getArgument(0));
controller =
@@ -88,7 +102,8 @@ class SourceControllerTest {
authority,
triggerManager,
properties,
- List.of(folderInput));
+ List.of(folderInput),
+ List.of(vectorSink));
WebhookInputSource webhookInput =
new WebhookInputSource(new WebhookSpool(tempDir), mock(FileReadinessChecker.class));
webhookController =
@@ -101,7 +116,24 @@ class SourceControllerTest {
authority,
triggerManager,
properties,
- List.of(webhookInput));
+ List.of(webhookInput),
+ List.of());
+ }
+
+ @Test
+ void savesAnOutputOnlySourceWithoutAnInputHandler() {
+ Source source =
+ new Source(
+ null,
+ "Knowledge",
+ "vectordb",
+ Map.of("connectionId", "42", "collection", "Documents"),
+ true,
+ null,
+ null);
+ Source saved = controller.save(source).getBody();
+ assertEquals("vectordb", saved.type());
+ org.mockito.Mockito.verify(vectorSink).validate(source.toOutputSpec());
}
@Test
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/SecurityExceptionHandlerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/SecurityExceptionHandlerTest.java
new file mode 100644
index 0000000000..d2690f5596
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/SecurityExceptionHandlerTest.java
@@ -0,0 +1,43 @@
+package stirling.software.proprietary.security.controller.api;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ProblemDetail;
+import org.springframework.security.authorization.AuthorizationDeniedException;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+class SecurityExceptionHandlerTest {
+ @Test
+ void methodAuthorizationDenialTakesPrecedenceOverGenericRuntimeErrors() throws Exception {
+ MockMvcBuilders.standaloneSetup(new RestrictedController())
+ .setControllerAdvice(new RuntimeErrors(), new SecurityExceptionHandler())
+ .build()
+ .perform(get("/restricted"))
+ .andExpect(status().isForbidden())
+ .andExpect(jsonPath("$.detail").value("Access denied"));
+ }
+
+ @RestController
+ static class RestrictedController {
+ @GetMapping("/restricted")
+ void restricted() {
+ throw new AuthorizationDeniedException("Private connection details");
+ }
+ }
+
+ @RestControllerAdvice
+ static class RuntimeErrors {
+ @ExceptionHandler(RuntimeException.class)
+ ProblemDetail unexpected(RuntimeException exception) {
+ return ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java
index 3fc1605cc3..6e7245a167 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java
@@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -37,6 +36,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.pdf.MarkdownBlock;
import stirling.software.common.pdf.MarkdownBlocks;
import stirling.software.common.pdf.PdfMarkdownExtractor;
+import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.TempFileManager;
import stirling.software.proprietary.model.api.docparse.IngestApiRequest;
import stirling.software.proprietary.model.docparse.IngestOutcome;
@@ -60,6 +60,7 @@ class DocParseServiceTest {
@Mock private PdfMarkdownExtractor markdownExtractor;
@Mock private TempFileManager tempFileManager;
@Mock private FileIdStrategy fileIdStrategy;
+ @Mock private UserServiceInterface userService;
@TempDir Path tmp;
@@ -78,7 +79,7 @@ class DocParseServiceTest {
properties,
jsonMapper,
fileIdStrategy,
- null);
+ userService);
}
private static byte[] pdfBytes(int pages) throws IOException {
@@ -125,9 +126,10 @@ class DocParseServiceTest {
private JsonNode ingestAndCaptureRequest(
String documentId, boolean index, boolean markdown, boolean chunks) throws IOException {
stubConversion(BLOCKS);
+ when(userService.getCurrentUsername()).thenReturn("alice");
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
when(aiEngineClient.postLongRunning(
- eq("/api/v1/docparse/ingest"), body.capture(), isNull()))
+ eq("/api/v1/docparse/ingest"), body.capture(), eq("alice")))
.thenReturn(ENGINE_RESPONSE);
IngestOutcome outcome = ingest(documentId, index, markdown, chunks);
@@ -140,6 +142,7 @@ class DocParseServiceTest {
JsonNode request = ingestAndCaptureRequest("doc-1", true, false, false);
assertEquals("doc-1", request.get("documentId").asString());
+ assertEquals("alice", request.get("ownerId").asString());
assertEquals("invoice.pdf", request.get("source").asString());
assertEquals(2, request.get("blocks").size());
JsonNode heading = request.get("blocks").get(0);
@@ -196,6 +199,19 @@ class DocParseServiceTest {
verifyNoInteractions(aiEngineClient);
}
+ @Test
+ void anonymousIndexAndChunkExportAreRejectedBeforeEngineDispatch() throws IOException {
+ stubConversion(BLOCKS);
+ for (boolean index : List.of(true, false)) {
+ ResponseStatusException error =
+ assertThrows(
+ ResponseStatusException.class,
+ () -> ingest("doc-1", index, false, !index));
+ assertEquals(HttpStatus.UNAUTHORIZED, error.getStatusCode());
+ }
+ verifyNoInteractions(aiEngineClient);
+ }
+
@Test
void aDocumentWithNoTextLayerIs422() throws IOException {
stubConversion(List.of(new MarkdownBlock(" ", 1, 1)));
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 08f3ea10dd..1453aae5f4 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -8190,6 +8190,14 @@ baseUrlPlaceholder = "https://your-org.webhook.office.com/webhookb2/..."
description = "Post a message to a Teams channel when a policy runs."
label = "Microsoft Teams"
+[portal.connections.types.vectordb]
+baseUrlPlaceholder = "https://your-database-host"
+description = "Index document chunks using Weaviate or Pinecone server-side embedding. Use the Weaviate server URL or Pinecone index host. Private endpoints require the operator to enable policies.allowPrivateApiEndpoints."
+label = "Vector database"
+pinecone = "Pinecone"
+vendor = "Database"
+weaviate = "Weaviate"
+
[portal.connections.types.webhook]
baseUrlPlaceholder = "https://example.com/hooks/documents"
description = "Post each document, or just the details, to a URL you choose."
@@ -9030,6 +9038,7 @@ label = "Change icon"
[portal.pipelines.builder.ingest]
chunkSize = "Chunk size"
chunkSizeHint = "Characters per chunk. Smaller chunks retrieve more precisely; larger ones keep more context together."
+destinationNeedsChunks = "This vector database destination needs a final AI ingestion step that exports chunks only."
editorPdfOnly = "Editor policies return PDFs only. To export chunks or Markdown, choose a saved input source and a file destination."
exportChunks = "Export chunks as JSONL"
exportChunksHint = "One chunk per line with its page span, ready to load into another system."
@@ -9043,6 +9052,7 @@ nothingToDo = "Turn on at least one of indexing or an export, or this step has n
overlap = "Overlap"
overlapHint = "Characters repeated between neighbouring chunks, so a sentence split across two is still findable."
overlapTooBig = "Overlap must be smaller than the chunk size ({{chunkSize}})."
+prepareDestination = "Prepare chunks for this destination"
unavailable = "AI ingestion needs the AI engine and DocParse turned on, including when the destination database generates embeddings."
[portal.pipelines.builder.routing]
@@ -9944,6 +9954,7 @@ backToSource = "Back to source setup"
backToTypes = "All source types"
cancel = "Cancel"
chooseHint = "Choose where documents come from. Greyed-out connectors are on the way."
+chooseOutputHint = "Choose where processed documents go. Greyed-out connectors are on the way."
comingSoon = "Coming soon"
comingSoonHeading = "Coming soon"
create = "Create source"
@@ -10099,6 +10110,17 @@ label = "SharePoint"
[portal.sources.types.unknown]
label = "Source"
+[portal.sources.types.vectordb]
+collection = "Collection / index name"
+collectionHint = "Use an existing collection or index configured for server-side embedding."
+connection = "Database connection"
+description = "An output destination for prepared document chunks. The database generates embeddings; originals stay in your input source when track mode is selected."
+label = "Vector database"
+namespace = "Namespace / tenant"
+namespaceHint = "Optional Pinecone namespace or Weaviate tenant. Leave empty for the default namespace or a single-tenant collection."
+textField = "Text field"
+textFieldHint = "The field the database embeds, matching the collection schema or Pinecone field map."
+
[portal.sources.types.webhook]
createNote = "A delivery URL and signing secret are generated when you create this webhook. Senders POST documents to that URL and the referencing policies run on arrival."
description = "Receive documents by signed HTTP POST from any external system."
diff --git a/frontend/editor/src/portal-saas/components/pipelines/outputModes.test.ts b/frontend/editor/src/portal-saas/components/pipelines/outputModes.test.ts
index 093be2d9da..f603744d73 100644
--- a/frontend/editor/src/portal-saas/components/pipelines/outputModes.test.ts
+++ b/frontend/editor/src/portal-saas/components/pipelines/outputModes.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import { availableOutputModes } from "@portal/components/pipelines/outputModes";
describe("availableOutputModes (SaaS)", () => {
- it("offers only s3: no server filesystem, and inline results would expire unseen", () => {
- expect(availableOutputModes()).toEqual(["s3"]);
+ it("offers durable destinations without exposing the server filesystem", () => {
+ expect(availableOutputModes()).toEqual(["s3", "vectordb"]);
});
});
diff --git a/frontend/editor/src/portal/api/integrations.ts b/frontend/editor/src/portal/api/integrations.ts
index 4ced16ca79..5eeb8f2a82 100644
--- a/frontend/editor/src/portal/api/integrations.ts
+++ b/frontend/editor/src/portal/api/integrations.ts
@@ -12,7 +12,8 @@ export type IntegrationType =
| "MCP"
| "API"
| "PURVIEW"
- | "CONSIGNO";
+ | "CONSIGNO"
+ | "VECTOR_DB";
export type OwnerScope = "USER" | "TEAM" | "SERVER";
/** Mirrors the backend IntegrationConfigResponse; `config` values are masked. */
diff --git a/frontend/editor/src/portal/api/pipelines.ts b/frontend/editor/src/portal/api/pipelines.ts
index 129814b594..940d8d9c7f 100644
--- a/frontend/editor/src/portal/api/pipelines.ts
+++ b/frontend/editor/src/portal/api/pipelines.ts
@@ -50,7 +50,7 @@ export interface OutputSpec {
}
/** Source types that can be written to (used as a pipeline's output destination). */
-export type PipelineOutputMode = "folder" | "s3";
+export type PipelineOutputMode = "folder" | "s3" | "vectordb";
/**
* The stored policy record: the create/update body (`id` blank on create) and what
diff --git a/frontend/editor/src/portal/components/pipelines/IngestStepConfig.test.tsx b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.test.tsx
new file mode 100644
index 0000000000..c797fd0d33
--- /dev/null
+++ b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.test.tsx
@@ -0,0 +1,38 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { IngestStepConfig } from "@portal/components/pipelines/IngestStepConfig";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@app/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { aiEngineEnabled: true }, loading: false }),
+}));
+
+describe("ingestion overlap validation", () => {
+ it("marks an excessive overlap invalid and clears the error when corrected", () => {
+ const { rerender } = render(
+ <IngestStepConfig
+ parameters={{ chunkSize: 64, overlap: 64 }}
+ onChange={vi.fn()}
+ />,
+ );
+ const input = screen.getByLabelText(
+ "portal.pipelines.builder.ingest.overlap",
+ );
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ expect(
+ screen.getByText("portal.pipelines.builder.ingest.overlapTooBig"),
+ ).toBeInTheDocument();
+ rerender(
+ <IngestStepConfig
+ parameters={{ chunkSize: 64, overlap: 16 }}
+ onChange={vi.fn()}
+ />,
+ );
+ expect(input).not.toHaveAttribute("aria-invalid", "true");
+ expect(
+ screen.queryByText("portal.pipelines.builder.ingest.overlapTooBig"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx
index b7baa0b6f9..9cb0eb5419 100644
--- a/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx
+++ b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx
@@ -114,12 +114,13 @@ export function IngestStepConfig({
</FormField>
<FormField
label={t("portal.pipelines.builder.ingest.overlap")}
- helperText={
+ helperText={t("portal.pipelines.builder.ingest.overlapHint")}
+ error={
overlapTooBig
? t("portal.pipelines.builder.ingest.overlapTooBig", {
chunkSize,
})
- : t("portal.pipelines.builder.ingest.overlapHint")
+ : undefined
}
>
<Input
@@ -127,6 +128,7 @@ export function IngestStepConfig({
inputSize="sm"
min={0}
max={4096}
+ invalid={overlapTooBig}
step={16}
value={parameters.overlap ?? ""}
onChange={(e) => setNumber("overlap", e.target.value)}
diff --git a/frontend/editor/src/portal/components/pipelines/docparseStep.test.ts b/frontend/editor/src/portal/components/pipelines/docparseStep.test.ts
index c86fa4e1f2..fd17028407 100644
--- a/frontend/editor/src/portal/components/pipelines/docparseStep.test.ts
+++ b/frontend/editor/src/portal/components/pipelines/docparseStep.test.ts
@@ -1,10 +1,62 @@
import { describe, expect, it } from "vitest";
import {
newIngestStep,
+ prepareVectorDestination,
ingestStepConfigured,
+ vectorDestinationConfigured,
} from "@portal/components/pipelines/docparseStep";
+import { isReadableSource } from "@portal/components/sources/sourceTypes";
-describe("RAG chunk parameter limits", () => {
+describe("vector database destinations", () => {
+ it.each([
+ { exportChunksJsonl: true },
+ { exportMarkdown: true },
+ { includeOriginal: false, exportChunksJsonl: true },
+ ])("rejects corpus output for editor input: %o", (params) => {
+ const step = newIngestStep();
+ const corpus = { ...step, params: { ...step.params, ...params } };
+ expect(ingestStepConfigured(corpus, true)).toBe(false);
+ expect(ingestStepConfigured(corpus, false)).toBe(true);
+ expect(ingestStepConfigured(step, true)).toBe(true);
+ });
+ it("adds preparation without indexing into Stirling by default", () => {
+ const steps = prepareVectorDestination([]);
+ expect(vectorDestinationConfigured(steps)).toBe(true);
+ expect(steps[0].params).toMatchObject({
+ index: false,
+ exportChunksJsonl: true,
+ includeOriginal: false,
+ });
+ expect(ingestStepConfigured(steps[0])).toBe(true);
+ });
+ it("preserves an existing step's indexing and chunking settings", () => {
+ const step = newIngestStep();
+ const steps = prepareVectorDestination([step]);
+ expect(steps).toHaveLength(1);
+ expect(steps[0].params).toMatchObject({
+ index: true,
+ chunkSize: 512,
+ overlap: 64,
+ });
+ expect(step.params).toMatchObject({
+ includeOriginal: true,
+ exportChunksJsonl: false,
+ });
+ });
+ it("keeps vector destinations out of the input picker", () => {
+ expect(isReadableSource({ type: "vectordb" })).toBe(false);
+ expect(isReadableSource({ type: "s3" })).toBe(true);
+ expect(isReadableSource({ type: "editor" })).toBe(true);
+ });
+ it("requires an export before dropping the original", () => {
+ const step = newIngestStep();
+ const prepared = prepareVectorDestination([step])[0];
+ expect(vectorDestinationConfigured([step])).toBe(false);
+ expect(vectorDestinationConfigured([prepared])).toBe(true);
+ });
+});
+
+describe("ingestion chunk parameter limits", () => {
it.each([
{ chunkSize: 63 },
{ chunkSize: 32769 },
diff --git a/frontend/editor/src/portal/components/pipelines/docparseStep.ts b/frontend/editor/src/portal/components/pipelines/docparseStep.ts
index f7858ac4b4..ea51aa0815 100644
--- a/frontend/editor/src/portal/components/pipelines/docparseStep.ts
+++ b/frontend/editor/src/portal/components/pipelines/docparseStep.ts
@@ -55,3 +55,37 @@ export function ingestStepConfigured(
params.exportChunksJsonl === true;
return doesSomething && hasFiles && ingestChunkingConfigured(params);
}
+
+/** Vector destinations consume only the final step's chunks export. */
+export function vectorDestinationConfigured(steps: WorkingToolStep[]): boolean {
+ const last = steps.at(-1);
+ if (!last || !isIngestStep(last)) return false;
+ const params = last.params as IngestStepParams;
+ return (
+ params.exportChunksJsonl === true &&
+ params.includeOriginal === false &&
+ params.exportMarkdown !== true
+ );
+}
+
+export function prepareVectorDestination(
+ steps: WorkingToolStep[],
+): WorkingToolStep[] {
+ const last = steps.at(-1);
+ const existing = last && isIngestStep(last);
+ const step = existing ? last : newIngestStep();
+ const params = step.params as IngestStepParams;
+ return [
+ ...(existing ? steps.slice(0, -1) : steps),
+ {
+ ...step,
+ params: {
+ ...params,
+ index: existing ? params.index : false,
+ includeOriginal: false,
+ exportMarkdown: false,
+ exportChunksJsonl: true,
+ } as unknown as ErasedToolParams,
+ },
+ ];
+}
diff --git a/frontend/editor/src/portal/components/sources/SourceModal.test.tsx b/frontend/editor/src/portal/components/sources/SourceModal.test.tsx
index cac2b50942..53314d1f68 100644
--- a/frontend/editor/src/portal/components/sources/SourceModal.test.tsx
+++ b/frontend/editor/src/portal/components/sources/SourceModal.test.tsx
@@ -51,15 +51,17 @@ vi.mock("@portal/api/integrations", () => ({
function renderModal(sourceId: string | null = null) {
const onClose = vi.fn();
const onSaved = vi.fn();
+ const onCreated = vi.fn();
render(
<SourceModal
open
sourceId={sourceId}
onClose={onClose}
onSaved={onSaved}
+ onCreated={onCreated}
/>,
);
- return { onClose, onSaved };
+ return { onClose, onSaved, onCreated };
}
describe("SourceModal", () => {
@@ -78,7 +80,7 @@ describe("SourceModal", () => {
});
it("creates a folder source through the staged flow and closes", async () => {
- const { onClose, onSaved } = renderModal();
+ const { onClose, onSaved, onCreated } = renderModal();
// Stage 1: pick the folder connector, then fill name + directory.
fireEvent.click(screen.getByText("portal.sources.types.folder.label"));
@@ -104,6 +106,7 @@ describe("SourceModal", () => {
);
await waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(onClose).toHaveBeenCalled();
+ expect(onCreated).toHaveBeenCalledWith({ id: "src-1" });
});
it("offers a Folder Access settings link when the folder is outside allowed roots", async () => {
diff --git a/frontend/editor/src/portal/components/sources/SourceModal.tsx b/frontend/editor/src/portal/components/sources/SourceModal.tsx
index eb85e72019..37ec735090 100644
--- a/frontend/editor/src/portal/components/sources/SourceModal.tsx
+++ b/frontend/editor/src/portal/components/sources/SourceModal.tsx
@@ -1,4 +1,5 @@
-import { useEffect, useState, type ReactNode } from "react";
+import { availableOutputModes } from "@portal/components/pipelines/outputModes";
+import { useEffect, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
Banner,
@@ -96,6 +97,9 @@ function connectionTypeById(id: string): CreatableConnectionType {
interface SourceModalProps {
open: boolean;
+ direction?: "input" | "output";
+ allowedTypes?: string[];
+ initialOptions?: Record<string, string>;
/** When set, edit this source; otherwise create a new one. */
sourceId?: string | null;
onClose: () => void;
@@ -104,6 +108,7 @@ interface SourceModalProps {
* regardless, so hosts on the query layer need no handler.
*/
onSaved?: () => void;
+ onCreated?: (source: Source) => void;
}
/**
@@ -117,10 +122,27 @@ export function SourceModal({
sourceId,
onClose,
onSaved,
+ onCreated,
+ direction,
+ allowedTypes,
+ initialOptions,
}: SourceModalProps) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const isEdit = Boolean(sourceId);
+ const offeredTypes = useMemo(
+ () =>
+ OFFERED_TYPES.filter(
+ (entry) => !allowedTypes || allowedTypes.includes(entry.type),
+ ).filter((entry) =>
+ direction === "input"
+ ? entry.readable !== false
+ : direction === "output"
+ ? (availableOutputModes() as string[]).includes(entry.type)
+ : true,
+ ),
+ [direction, allowedTypes],
+ );
// The list is a shared cache entry (Sources view + Home's ProcessorFlow), so
// a create/delete here must invalidate it before the host re-renders it.
@@ -167,13 +189,13 @@ export function SourceModal({
setSubmitting(false);
setDeleting(false);
if (!sourceId) {
- setStage("type");
- setType(OFFERED_TYPES[0]);
+ setStage(offeredTypes.length === 1 ? "configure" : "type");
+ setType(offeredTypes[0]);
setName("");
- setOptions(defaultOptions(OFFERED_TYPES[0]));
+ setOptions({ ...defaultOptions(offeredTypes[0]), ...initialOptions });
setEnabled(true);
setLoaded(null);
- setShowAdvanced(false);
+ setShowAdvanced(Boolean(initialOptions?.mode));
return;
}
setStage("configure");
@@ -195,12 +217,12 @@ export function SourceModal({
})
.catch((e) => setError(errorMessage(e)))
.finally(() => setLoading(false));
- }, [open, sourceId]);
+ }, [open, sourceId, offeredTypes, initialOptions]);
function chooseType(next: CreatableSourceType) {
setType(next);
- setOptions(defaultOptions(next));
- setShowAdvanced(false);
+ setOptions({ ...defaultOptions(next), ...initialOptions });
+ setShowAdvanced(Boolean(initialOptions?.mode));
setStage("configure");
}
@@ -270,6 +292,7 @@ export function SourceModal({
enabled,
});
await invalidateSources();
+ if (!isEdit) onCreated?.(saved);
if (!isEdit && type.type === WEBHOOK_SOURCE_TYPE) {
const webhookId = String(saved.options?.webhookId ?? "");
const secret = String(saved.options?.signingSecret ?? "");
@@ -348,7 +371,7 @@ export function SourceModal({
backLabel: t("portal.sources.builder.backToSource"),
};
}
- if (stage === "configure" && !isEdit) {
+ if (stage === "configure" && !isEdit && offeredTypes.length > 1) {
return {
onBack: () => setStage("type"),
backLabel: t("portal.sources.builder.backToTypes"),
@@ -539,14 +562,18 @@ export function SourceModal({
{stage === "type" && (
<div className="portal-source-modal__catalog">
<p className="portal-source-modal__hint">
- {t("portal.sources.builder.chooseHint")}
+ {t(
+ direction === "output"
+ ? "portal.sources.builder.chooseOutputHint"
+ : "portal.sources.builder.chooseHint",
+ )}
</p>
<div
className="portal-source-modal__grid"
role="listbox"
aria-label={t("portal.sources.wizard.type")}
>
- {OFFERED_TYPES.map((ct) => (
+ {offeredTypes.map((ct) => (
<button
key={ct.type}
type="button"
diff --git a/frontend/editor/src/portal/components/sources/connectionTypes.ts b/frontend/editor/src/portal/components/sources/connectionTypes.ts
index 3591814b4f..1455bf3f37 100644
--- a/frontend/editor/src/portal/components/sources/connectionTypes.ts
+++ b/frontend/editor/src/portal/components/sources/connectionTypes.ts
@@ -898,6 +898,30 @@ export const CREATABLE_CONNECTION_TYPES: CreatableConnectionType[] = [
requiresCustomApi: true,
fields: CUSTOM_API_FIELDS,
},
+ {
+ id: "vectordb",
+ integrationType: "VECTOR_DB",
+ kind: "preset",
+ category: "storage",
+ labelKey: `${PREFIX}.vectordb.label`,
+ descriptionKey: `${PREFIX}.vectordb.description`,
+ searchTerms: ["ingestion", "vector", "weaviate", "pinecone", "knowledge"],
+ fields: [
+ {
+ key: "vendor",
+ control: "select",
+ required: true,
+ defaultValue: "weaviate",
+ labelKey: `${PREFIX}.vectordb.vendor`,
+ options: [
+ { value: "weaviate", labelKey: `${PREFIX}.vectordb.weaviate` },
+ { value: "pinecone", labelKey: `${PREFIX}.vectordb.pinecone` },
+ ],
+ },
+ field.baseUrl("vectordb"),
+ field.apiKey(),
+ ],
+ },
];
/** Free-text match over name, description-agnostic keywords and category. */
diff --git a/frontend/editor/src/portal/components/sources/sourceTypes.ts b/frontend/editor/src/portal/components/sources/sourceTypes.ts
index 33e7dfaa42..b4b5db2491 100644
--- a/frontend/editor/src/portal/components/sources/sourceTypes.ts
+++ b/frontend/editor/src/portal/components/sources/sourceTypes.ts
@@ -25,6 +25,10 @@ export const EDITOR_SOURCE_TYPE = "editor";
export const WEBHOOK_SOURCE_TYPE = "webhook";
const SOURCE_TYPE_META: Record<string, SourceTypeMeta> = {
+ vectordb: {
+ labelKey: "portal.sources.types.vectordb.label",
+ accent: "brand",
+ },
folder: {
labelKey: "portal.sources.types.folder.label",
accent: "default",
@@ -91,6 +95,7 @@ export interface CreatableSourceType {
labelKey: string;
descriptionKey: string;
fields: SourceFieldDef[];
+ readable?: boolean;
}
/**
@@ -308,6 +313,42 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
descriptionKey: "portal.sources.types.webhook.description",
fields: [],
},
+ {
+ type: "vectordb",
+ readable: false,
+ labelKey: "portal.sources.types.vectordb.label",
+ descriptionKey: "portal.sources.types.vectordb.description",
+ fields: [
+ {
+ key: "connectionId",
+ control: "connection",
+ connectionTypeId: "vectordb",
+ required: true,
+ labelKey: "portal.sources.types.vectordb.connection",
+ },
+ {
+ key: "collection",
+ control: "text",
+ required: true,
+ labelKey: "portal.sources.types.vectordb.collection",
+ helperTextKey: "portal.sources.types.vectordb.collectionHint",
+ },
+ {
+ key: "namespace",
+ control: "text",
+ labelKey: "portal.sources.types.vectordb.namespace",
+ helperTextKey: "portal.sources.types.vectordb.namespaceHint",
+ },
+ {
+ key: "textField",
+ control: "text",
+ required: true,
+ defaultValue: "text",
+ labelKey: "portal.sources.types.vectordb.textField",
+ helperTextKey: "portal.sources.types.vectordb.textFieldHint",
+ },
+ ],
+ },
];
/** A source type on the roadmap: shown greyed out in the picker, not creatable. */
@@ -345,3 +386,11 @@ export function defaultOptions(
}
return out;
}
+
+/** Whether a saved location can supply documents to a pipeline. */
+export function isReadableSource(source: { type: string }): boolean {
+ return (
+ CREATABLE_SOURCE_TYPES.find((entry) => entry.type === source.type)
+ ?.readable !== false
+ );
+}
diff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
index 16d48edd5f..92358b20cb 100644
--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
@@ -11,7 +11,7 @@ import { MemoryRouter, Route, Routes } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { qk } from "@portal/queries/keys";
import type { Policy, TriggerOutcome } from "@portal/api/pipelines";
-import type { SourceView } from "@portal/api/sources";
+import type { Source, SourceView } from "@portal/api/sources";
import type { ToolRegistryCatalog } from "@app/contexts/ToolRegistryContext";
import type { ToolRegistryEntry } from "@app/data/toolsTaxonomy";
import { PipelineBuilder } from "@portal/views/PipelineBuilder";
@@ -99,7 +99,7 @@ vi.mock("@portal/components/pipelines/DestinationPicker", () => ({
onEdit: (sourceId: string) => void;
}) => (
<>
- <button type="button" onClick={() => onChange(["src-1"])}>
+ <button type="button" onClick={() => onChange(["src-in"])}>
{value.length > 0 ? `output:${value.join(",")}` : "pick output"}
</button>
<button type="button" onClick={onCreateNew}>
@@ -112,6 +112,8 @@ vi.mock("@portal/components/pipelines/DestinationPicker", () => ({
),
}));
+let createdSource: Source;
+
// The source modal has its own suite; stub it to the two things the builder
// depends on - the record it was opened on, and the sources-cache invalidation
// that follows a save (which is how a new source reaches the pickers).
@@ -119,9 +121,11 @@ vi.mock("@portal/components/sources/SourceModal", () => ({
SourceModal: ({
open,
sourceId,
+ onCreated,
}: {
open: boolean;
sourceId?: string | null;
+ onCreated?: (source: Source) => void;
}) => {
const queryClient = useQueryClient();
if (!open) return null;
@@ -130,9 +134,10 @@ vi.mock("@portal/components/sources/SourceModal", () => ({
<span>source-modal:{sourceId || "new"}</span>
<button
type="button"
- onClick={() =>
- void queryClient.invalidateQueries({ queryKey: qk.sources() })
- }
+ onClick={async () => {
+ await queryClient.invalidateQueries({ queryKey: qk.sources() });
+ onCreated?.(createdSource);
+ }}
>
source saved
</button>
@@ -321,6 +326,12 @@ const SOURCE: SourceView = {
docs30d: 0,
};
+const DESTINATION_SOURCE: SourceView = {
+ ...SOURCE,
+ id: "src-1",
+ name: "Archive",
+};
+
function outcome(overrides: Partial<TriggerOutcome>): TriggerOutcome {
return {
runIds: [],
@@ -349,6 +360,13 @@ function renderBuilder(initial: string) {
describe("PipelineBuilder", () => {
beforeEach(() => {
+ createdSource = {
+ id: "src-new",
+ name: "Scanner drop",
+ type: "folder",
+ options: {},
+ enabled: true,
+ };
fetchPipeline.mockReset();
fetchTriggers.mockReset();
savePipeline.mockReset();
@@ -612,7 +630,7 @@ describe("PipelineBuilder", () => {
name: "Nightly compress",
// The input pairs the chosen source with its trigger (manual by default).
inputs: [{ sourceId: "src-in", trigger: null }],
- outputIds: ["src-1"],
+ outputIds: ["src-in"],
steps: [
expect.objectContaining({ operation: "/api/v1/misc/compress-pdf" }),
],
@@ -710,7 +728,7 @@ describe("PipelineBuilder", () => {
expect(savePipeline).toHaveBeenCalledWith(
expect.objectContaining({
inputs: [{ sourceId: "src-in", trigger: null }],
- outputIds: ["src-1"],
+ outputIds: ["src-in"],
}),
);
});
@@ -768,14 +786,30 @@ describe("PipelineBuilder", () => {
);
});
- it("makes a destination created from the picker the pipeline's output", async () => {
+ it("selects the created destination even when another source arrives concurrently", async () => {
+ createdSource = {
+ ...createdSource,
+ name: "Vector database destination",
+ type: "vectordb",
+ };
fetchSources
.mockResolvedValueOnce({ kpis: [], sources: [SOURCE] })
.mockResolvedValue({
kpis: [],
sources: [
SOURCE,
- { ...SOURCE, id: "src-new", name: "Archive bucket", type: "s3" },
+ {
+ ...SOURCE,
+ id: "src-unrelated",
+ name: "Concurrent folder",
+ type: "folder",
+ },
+ {
+ ...SOURCE,
+ id: "src-new",
+ name: "Vector database destination",
+ type: "vectordb",
+ },
],
});
renderBuilder("/processor/pipelines/new");
@@ -798,6 +832,7 @@ describe("PipelineBuilder", () => {
});
it("leaves a new source that cannot be written to out of the destination", async () => {
+ createdSource = { ...createdSource, id: "src-hook", type: "webhook" };
// A webhook can be read from but not written to, so it must not be picked
// as a destination the dropdown has no option for.
fetchSources
@@ -836,7 +871,7 @@ describe("PipelineBuilder", () => {
await pickDestination();
fireEvent.click(screen.getByText("edit destination"));
- expect(screen.getByText("source-modal:src-1")).toBeInTheDocument();
+ expect(screen.getByText("source-modal:src-in")).toBeInTheDocument();
});
it("saves an editor pipeline as its own flag, not as a wire input", async () => {
@@ -864,7 +899,43 @@ describe("PipelineBuilder", () => {
expect(body.outputIds).toEqual([]);
});
+ it("blocks a vector route with a file fallback until chunks are prepared", async () => {
+ fetchSources.mockResolvedValue({
+ kpis: [],
+ sources: [SOURCE, { ...DESTINATION_SOURCE, type: "vectordb" }],
+ });
+ fetchPipeline.mockResolvedValue({
+ ...POLICY,
+ inputs: [{ sourceId: "src-in", trigger: null }],
+ steps: [CLASSIFY_STEP],
+ outputIds: ["src-in"],
+ routingRules: [routingRule(["invoice"])],
+ });
+ renderBuilder("/processor/pipelines/plc-1");
+ fireEvent.click(
+ await screen.findByLabelText("portal.pipelines.builder.rename"),
+ );
+ fireEvent.change(
+ await screen.findByLabelText("portal.pipelines.composer.name"),
+ {
+ target: { value: "Renamed" },
+ },
+ );
+ await openOutput();
+ expect(
+ screen.getAllByText(
+ "portal.pipelines.builder.ingest.destinationNeedsChunks",
+ ).length,
+ ).toBeGreaterThan(0);
+ fireEvent.click(screen.getByText("portal.pipelines.composer.save"));
+ expect(savePipeline).not.toHaveBeenCalled();
+ });
+
it("carries a saved pipeline's routes through an unrelated edit", async () => {
+ fetchSources.mockResolvedValue({
+ kpis: [],
+ sources: [SOURCE, DESTINATION_SOURCE],
+ });
const routed = routingRule(["invoice"]);
fetchPipeline.mockResolvedValue({
...POLICY,
@@ -892,6 +963,10 @@ describe("PipelineBuilder", () => {
});
it("refuses to save a route with no document types on it", async () => {
+ fetchSources.mockResolvedValue({
+ kpis: [],
+ sources: [SOURCE, DESTINATION_SOURCE],
+ });
fetchPipeline.mockResolvedValue({
...POLICY,
inputs: [{ sourceId: "src-in", trigger: null }],
@@ -916,6 +991,10 @@ describe("PipelineBuilder", () => {
});
it("refuses to save routes whose classify step has been removed", async () => {
+ fetchSources.mockResolvedValue({
+ kpis: [],
+ sources: [SOURCE, DESTINATION_SOURCE],
+ });
fetchPipeline.mockResolvedValue({
...POLICY,
inputs: [{ sourceId: "src-in", trigger: null }],
@@ -1112,7 +1191,7 @@ describe("PipelineBuilder", () => {
},
],
output: { type: "inline", options: {} },
- outputIds: ["src-1"],
+ outputIds: ["src-in"],
});
renderBuilder("/processor/pipelines/plc-sign");
diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsx
index b25561a637..176aa97c0e 100644
--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx
+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx
@@ -3,6 +3,8 @@ import { isConditionComplete } from "@app/conditions/validation";
import {
isIngestStep,
ingestStepConfigured,
+ vectorDestinationConfigured,
+ prepareVectorDestination,
} from "@portal/components/pipelines/docparseStep";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
@@ -78,6 +80,7 @@ import { availableOutputModes } from "@portal/components/pipelines/outputModes";
import { type SourceView } from "@portal/api/sources";
import { useSources } from "@portal/queries/sources";
import { useCanManagePolicies } from "@portal/queries/policyPermissions";
+import { isReadableSource } from "@portal/components/sources/sourceTypes";
import { SourceModal } from "@portal/components/sources/SourceModal";
import { EDITOR_SOURCE_TYPE } from "@portal/components/sources/sourceTypes";
import { useAsync } from "@portal/hooks/useAsync";
@@ -201,7 +204,7 @@ function isClassifyTool(tool: ExecutableTool): boolean {
}
/** Whether a source can be written to, i.e. offered as a pipeline destination. */
-function isWritableSource(source: SourceView): boolean {
+function isWritableSource(source: { type: string }): boolean {
return (availableOutputModes() as string[]).includes(source.type);
}
@@ -353,32 +356,10 @@ export function PipelineBuilder() {
const [sourceModal, setSourceModal] = useState<{
open: boolean;
sourceId: string | null;
+ direction?: "input" | "output";
}>({ open: false, sourceId: null });
- // A source created from here is the one the pipeline was missing, so select it
- // on arrival - as the input or the destination, whichever asked for it.
- const autoSelectRef = useRef<"input" | "output" | null>(null);
- const knownSourceIdsRef = useRef<Set<string>>(new Set());
- useEffect(() => {
- const target = autoSelectRef.current;
- const known = knownSourceIdsRef.current;
- knownSourceIdsRef.current = new Set(availableSources.map((s) => s.id));
- if (!target) return;
- const fresh = availableSources.find((s) => !known.has(s.id));
- if (!fresh) return;
- // One arrival answers the request, whatever type it turned out to be.
- autoSelectRef.current = null;
- if (target === "input") {
- changeInputSource(fresh.id);
- } else if (isWritableSource(fresh)) {
- // A source of an unwritable type is left alone rather than becoming a
- // destination the picker has no option for.
- setOutputIds([fresh.id]);
- }
- }, [availableSources]);
-
function createSourceFor(target: "input" | "output") {
- autoSelectRef.current = target;
- setSourceModal({ open: true, sourceId: null });
+ setSourceModal({ open: true, sourceId: null, direction: target });
}
const mounted = useRef(true);
@@ -464,10 +445,12 @@ export function PipelineBuilder() {
const triggerFitsType = (trigger: TriggerInfo, type: string) =>
!trigger.requiresSource || trigger.supportedSourceTypes.includes(type);
- const sourceOptions = availableSources.map((source) => ({
- value: source.id,
- label: source.name,
- }));
+ const sourceOptions = availableSources
+ .filter(isReadableSource)
+ .map((source) => ({
+ value: source.id,
+ label: source.name,
+ }));
// Manual plus every trigger compatible with this row's source. Manual only until a source is set.
function triggerOptionsFor(sourceId: string) {
@@ -782,15 +765,29 @@ export function PipelineBuilder() {
// Each validity condition is defined exactly once here, then consumed both by the graph (which
// flags each end) and by the blocker list below.
- const sourceChosen = input.sourceId !== "";
+ const sourceChosen = availableSources.some(
+ (source) => source.id === input.sourceId && isReadableSource(source),
+ );
// An editor pipeline has no trigger to schedule: it fires as each file passes through.
const scheduleValid =
isEditorInput ||
input.triggerType !== "schedule" ||
Number(input.scheduleCount) > 0;
const inputValid = sourceChosen && scheduleValid;
- // Nor a destination: an editor pipeline's results land back in the workspace the file came from.
- const outputValid = isEditorInput || outputIds.length === 1;
+ const destinationIds = new Set([
+ ...outputIds,
+ ...routingRules.map((rule) => rule.outputId),
+ ]);
+ const vectorOutput = writableSources.some(
+ (source) => destinationIds.has(source.id) && source.type === "vectordb",
+ );
+ const vectorReady = !vectorOutput || vectorDestinationConfigured(steps);
+ const destinationReady =
+ outputIds.length === 1 &&
+ writableSources.some(
+ (source) => source.id === outputIds[0] && source.status !== "disabled",
+ );
+ const outputValid = isEditorInput || (destinationReady && vectorReady);
const classifies = steps.some(isClassifyStep);
// Mirrors PolicyValidator.validateRoutingRules: a rule with nothing to match on, or nowhere to
// send, would be rejected on save - so it is named here rather than surfaced as a server error.
@@ -808,14 +805,14 @@ export function PipelineBuilder() {
const blockers: string[] = [];
if (name.trim() === "")
blockers.push(t("portal.pipelines.builder.blocker.name"));
- // An editor pipeline has the editor as its chosen source and needs no destination, so sourceChosen
- // is already true and outputValid already passes for it - these checks simply never fire.
if (!sourceChosen)
blockers.push(t("portal.pipelines.builder.blocker.source"));
else if (!scheduleValid)
blockers.push(t("portal.pipelines.builder.blocker.schedule"));
- if (!outputValid)
+ if (!isEditorInput && !destinationReady)
blockers.push(t("portal.pipelines.builder.blocker.destination"));
+ if (!vectorReady)
+ blockers.push(t("portal.pipelines.builder.ingest.destinationNeedsChunks"));
if (!routingValid)
blockers.push(
t(
@@ -1315,7 +1312,7 @@ export function PipelineBuilder() {
if (selected === "input") {
// Nothing to pick from yet: a dropdown of nothing helps no one, so offer only the way to make
// the first source. The trigger has no meaning without a source either, so it waits too.
- const hasSources = availableSources.length > 0;
+ const hasSources = sourceOptions.length > 0;
return (
<>
{hasSources && (
@@ -1407,6 +1404,19 @@ export function PipelineBuilder() {
onCreateNew={() => createSourceFor("output")}
onEdit={(sourceId) => setSourceModal({ open: true, sourceId })}
/>
+ {vectorOutput && !vectorReady && (
+ <>
+ <p className="portal-builder__muted">
+ {t("portal.pipelines.builder.ingest.destinationNeedsChunks")}
+ </p>
+ <Button
+ size="sm"
+ onClick={() => setSteps(prepareVectorDestination(steps))}
+ >
+ {t("portal.pipelines.builder.ingest.prepareDestination")}
+ </Button>
+ </>
+ )}
</>
);
}
@@ -1713,8 +1723,20 @@ export function PipelineBuilder() {
</Modal>
<SourceModal
+ direction={sourceModal.direction}
open={sourceModal.open}
sourceId={sourceModal.sourceId}
+ onCreated={(source) => {
+ if (!source.id) return;
+ if (sourceModal.direction === "input" && isReadableSource(source)) {
+ changeInputSource(source.id);
+ } else if (
+ sourceModal.direction === "output" &&
+ isWritableSource(source)
+ ) {
+ setOutputIds([source.id]);
+ }
+ }}
onClose={() => setSourceModal({ open: false, sourceId: null })}
/>
</div>
diff --git a/frontend/editor/src/proprietary/policies/outputModes.ts b/frontend/editor/src/proprietary/policies/outputModes.ts
index d085f8dac3..158756715b 100644
--- a/frontend/editor/src/proprietary/policies/outputModes.ts
+++ b/frontend/editor/src/proprietary/policies/outputModes.ts
@@ -1,4 +1,6 @@
/** Writable destination types, matching the server's hosted filesystem restriction. */
-export function availableOutputModes(hosted = false): ("folder" | "s3")[] {
- return hosted ? ["s3"] : ["folder", "s3"];
+export function availableOutputModes(
+ hosted = false,
+): ("folder" | "s3" | "vectordb")[] {
+ return hosted ? ["s3", "vectordb"] : ["folder", "s3", "vectordb"];
}