This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 35761d76ca6d CAMEL-27632: camel-pgvector - escape control characters
in the embeddings metadata JSON, transformer description (#31015)
35761d76ca6d is described below
commit 35761d76ca6dc794422cbdd79dd20632a71b205f
Author: allthingssecurity <[email protected]>
AuthorDate: Sat Nov 28 00:27:08 2026 +0530
CAMEL-27632: camel-pgvector - escape control characters in the embeddings
metadata JSON, transformer description (#31015)
1. PgVectorEmbeddingsDataTypeTransformer writes the metadata of the
TextSegment as JSON by hand, and escapeJson() only escaped the
backslash, the double quote, newline, carriage return and tab. Another
control character, such as a form feed or U+0001, went into the
CamelPgVectorMetadata header as it was, so the JSON was not valid and a
later metadata::jsonb cast failed on the row. Every character below
U+0020 is now escaped, as \uXXXX unless it has a short escape. Values
without control characters are written as before.
3. The description of the pgvector:embeddings transformer now says what
it does: the vector of the CamelLangChain4jEmbeddingsVector header
becomes the body as a List of Float, and the record id, text content
and metadata headers of an UPSERT are set.
Point 2 of the ticket (mark dataSource required) is not changed: the
option is autowired, as the dataSource of camel-sql, so it can come from
the component or the registry, and required = true would make tools
report it missing on URIs that work.
Regenerated pgvector-embeddings.json of the transformer and its catalog
copy.
CAMEL-27632: camel-pgvector - review: fail on a NUL character in the
metadata, naming the key
A NUL character (U+0000) in the name or value of a metadata key was
written as the escape \^@. That is valid JSON and the TEXT column
stores it, but PostgreSQL jsonb rejects it, so every later
metadata::jsonb filter that reaches the row would fail. The transformer
now throws an IllegalArgumentException that names the key and says
whether its name or its value has the NUL, so the exchange fails at the
write instead, as it did before the change when PostgreSQL refused the
raw NUL in the TEXT column. The value is not changed silently.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../catalog/transformers/pgvector-embeddings.json | 2 +-
.../camel/transformer/pgvector-embeddings.json | 2 +-
.../PgVectorEmbeddingsDataTypeTransformer.java | 56 ++++++++++---
.../PgVectorEmbeddingsMetadataJsonTest.java | 94 ++++++++++++++++++++++
4 files changed, 143 insertions(+), 11 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/transformers/pgvector-embeddings.json
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/transformers/pgvector-embeddings.json
index cffbd290ee3f..2d2261eb2d3a 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/transformers/pgvector-embeddings.json
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/transformers/pgvector-embeddings.json
@@ -3,7 +3,7 @@
"kind": "transformer",
"name": "pgvector:embeddings",
"title": "Pgvector (Embeddings)",
- "description": "Prepares the message to become an object writable by
PgVector component",
+ "description": "Turns the embedding of camel-langchain4j-embeddings into
the message of a pgvector UPSERT: the vector of the
CamelLangChain4jEmbeddingsVector header becomes the body, as a List of Float,
and the CamelPgVectorRecordId, CamelPgVectorTextContent and
CamelPgVectorMetadata headers are set",
"deprecated": false,
"javaType":
"org.apache.camel.component.pgvector.transform.PgVectorEmbeddingsDataTypeTransformer",
"groupId": "org.apache.camel",
diff --git
a/components/camel-ai/camel-pgvector/src/generated/resources/META-INF/services/org/apache/camel/transformer/pgvector-embeddings.json
b/components/camel-ai/camel-pgvector/src/generated/resources/META-INF/services/org/apache/camel/transformer/pgvector-embeddings.json
index cffbd290ee3f..2d2261eb2d3a 100644
---
a/components/camel-ai/camel-pgvector/src/generated/resources/META-INF/services/org/apache/camel/transformer/pgvector-embeddings.json
+++
b/components/camel-ai/camel-pgvector/src/generated/resources/META-INF/services/org/apache/camel/transformer/pgvector-embeddings.json
@@ -3,7 +3,7 @@
"kind": "transformer",
"name": "pgvector:embeddings",
"title": "Pgvector (Embeddings)",
- "description": "Prepares the message to become an object writable by
PgVector component",
+ "description": "Turns the embedding of camel-langchain4j-embeddings into
the message of a pgvector UPSERT: the vector of the
CamelLangChain4jEmbeddingsVector header becomes the body, as a List of Float,
and the CamelPgVectorRecordId, CamelPgVectorTextContent and
CamelPgVectorMetadata headers are set",
"deprecated": false,
"javaType":
"org.apache.camel.component.pgvector.transform.PgVectorEmbeddingsDataTypeTransformer",
"groupId": "org.apache.camel",
diff --git
a/components/camel-ai/camel-pgvector/src/main/java/org/apache/camel/component/pgvector/transform/PgVectorEmbeddingsDataTypeTransformer.java
b/components/camel-ai/camel-pgvector/src/main/java/org/apache/camel/component/pgvector/transform/PgVectorEmbeddingsDataTypeTransformer.java
index cbdbc72d587f..ad0480f42a0a 100644
---
a/components/camel-ai/camel-pgvector/src/main/java/org/apache/camel/component/pgvector/transform/PgVectorEmbeddingsDataTypeTransformer.java
+++
b/components/camel-ai/camel-pgvector/src/main/java/org/apache/camel/component/pgvector/transform/PgVectorEmbeddingsDataTypeTransformer.java
@@ -38,7 +38,10 @@ import org.apache.camel.spi.Transformer;
* database.
*/
@DataTypeTransformer(name = "pgvector:embeddings",
- description = "Prepares the message to become an object
writable by PgVector component")
+ description = "Turns the embedding of
camel-langchain4j-embeddings into the message of a pgvector UPSERT:"
+ + " the vector of the
CamelLangChain4jEmbeddingsVector header becomes the body, as a List"
+ + " of Float, and the
CamelPgVectorRecordId, CamelPgVectorTextContent and"
+ + " CamelPgVectorMetadata headers are set")
@BodyTypes(transformerIn = @BodyType(value = Carrier.ANY,
description = "A LangChain4j TextSegment,
or a String the converter of"
+ "
camel-langchain4j-embeddings turns into one, whose text and metadata"
@@ -76,26 +79,61 @@ public class PgVectorEmbeddingsDataTypeTransformer extends
Transformer {
private static String toJson(Map<String, Object> map) {
return "{" + map.entrySet().stream()
- .map(e -> "\"" + escapeJson(String.valueOf(e.getKey())) +
"\":" + formatJsonValue(e.getValue()))
+ .map(e -> {
+ String key = String.valueOf(e.getKey());
+ return "\"" + escapeJson(rejectNul(key, "name", key)) +
"\":" + formatJsonValue(key, e.getValue());
+ })
.collect(Collectors.joining(","))
+ "}";
}
- private static String formatJsonValue(Object value) {
+ private static String formatJsonValue(String key, Object value) {
if (value == null) {
return "null";
}
if (value instanceof Number || value instanceof Boolean) {
return String.valueOf(value);
}
- return "\"" + escapeJson(String.valueOf(value)) + "\"";
+ return "\"" + escapeJson(rejectNul(key, "value",
String.valueOf(value))) + "\"";
}
+ /**
+ * Fails on a NUL character (U+0000) in the name or value of a metadata
key. JSON can write it as an escape, but
+ * PostgreSQL jsonb rejects that escape, so the row would be stored and
every later metadata::jsonb filter that
+ * reaches it would fail.
+ */
+ private static String rejectNul(String key, String part, String text) {
+ if (text.indexOf('\u0000') >= 0) {
+ throw new IllegalArgumentException(
+ "The " + part + " of the metadata key '" +
key.replace("\u0000", "\\u0000")
+ + "' has a NUL character
(U+0000), which PostgreSQL jsonb cannot store");
+ }
+ return text;
+ }
+
+ /**
+ * Escapes a string for a JSON string value: the backslash, the double
quote, and every control character from
+ * U+0000 to U+001F, which JSON does not allow unescaped.
+ */
private static String escapeJson(String value) {
- return value.replace("\\", "\\\\")
- .replace("\"", "\\\"")
- .replace("\n", "\\n")
- .replace("\r", "\\r")
- .replace("\t", "\\t");
+ StringBuilder sb = new StringBuilder(value.length() + 16);
+ for (int i = 0; i < value.length(); i++) {
+ char c = value.charAt(i);
+ switch (c) {
+ case '"' -> sb.append("\\\"");
+ case '\\' -> sb.append("\\\\");
+ case '\n' -> sb.append("\\n");
+ case '\r' -> sb.append("\\r");
+ case '\t' -> sb.append("\\t");
+ default -> {
+ if (c < 0x20) {
+ sb.append("\\u00").append(Character.forDigit(c >> 4,
16)).append(Character.forDigit(c & 0xF, 16));
+ } else {
+ sb.append(c);
+ }
+ }
+ }
+ }
+ return sb.toString();
}
}
diff --git
a/components/camel-ai/camel-pgvector/src/test/java/org/apache/camel/component/pgvector/transform/PgVectorEmbeddingsMetadataJsonTest.java
b/components/camel-ai/camel-pgvector/src/test/java/org/apache/camel/component/pgvector/transform/PgVectorEmbeddingsMetadataJsonTest.java
new file mode 100644
index 000000000000..573167bf7987
--- /dev/null
+++
b/components/camel-ai/camel-pgvector/src/test/java/org/apache/camel/component/pgvector/transform/PgVectorEmbeddingsMetadataJsonTest.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.pgvector.transform;
+
+import dev.langchain4j.data.document.Metadata;
+import dev.langchain4j.data.embedding.Embedding;
+import dev.langchain4j.data.segment.TextSegment;
+import org.apache.camel.Exchange;
+import org.apache.camel.ai.CamelLangchain4jAttributes;
+import org.apache.camel.component.pgvector.PgVectorHeaders;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.DataType;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * The pgvector:embeddings transformer writes the metadata of the TextSegment
as valid JSON, with every control
+ * character escaped, and fails on a NUL character, which PostgreSQL jsonb
cannot store.
+ */
+class PgVectorEmbeddingsMetadataJsonTest {
+
+ private static final String KEY = "title\u001f";
+ private static final String VALUE = "a\fb\u0001c\\d\"e\nf\tg\rh";
+
+ @Test
+ void controlCharactersOfTheMetadataAreEscaped() throws Exception {
+ try (DefaultCamelContext context = new DefaultCamelContext()) {
+ context.start();
+ Exchange exchange = transform(context, Metadata.from(KEY, VALUE));
+
+ String json =
exchange.getMessage().getHeader(PgVectorHeaders.METADATA, String.class);
+
assertThat(json).isEqualTo("{\"title\\u001f\":\"a\\u000cb\\u0001c\\\\d\\\"e\\nf\\tg\\rh\"}");
+ assertThat(json.chars()).allMatch(c -> c >= 0x20);
+
+ JsonObject parsed = (JsonObject) Jsoner.deserialize(json);
+ assertThat(parsed).hasSize(1).containsEntry(KEY, VALUE);
+ }
+ }
+
+ @Test
+ void nulInAMetadataValueFailsAndNamesTheKey() throws Exception {
+ try (DefaultCamelContext context = new DefaultCamelContext()) {
+ context.start();
+ Metadata metadata = Metadata.from("title", "ok").put("author",
"a\u0000b\u0001");
+
+ assertThatThrownBy(() -> transform(context, metadata))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The value of the metadata key 'author' has a
NUL character (U+0000),"
+ + " which PostgreSQL jsonb cannot store");
+ }
+ }
+
+ @Test
+ void nulInAMetadataKeyFailsAndNamesTheKey() throws Exception {
+ try (DefaultCamelContext context = new DefaultCamelContext()) {
+ context.start();
+ Metadata metadata = Metadata.from("ti\u0000tle", "ok");
+
+ assertThatThrownBy(() -> transform(context, metadata))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The name of the metadata key 'ti\\u0000tle'
has a NUL character (U+0000),"
+ + " which PostgreSQL jsonb cannot store");
+ }
+ }
+
+ private static Exchange transform(DefaultCamelContext context, Metadata
metadata) {
+ Exchange exchange = new DefaultExchange(context);
+
exchange.getMessage().setHeader(CamelLangchain4jAttributes.CAMEL_LANGCHAIN4J_EMBEDDING_VECTOR,
+ new Embedding(new float[] { 0.1f, 0.2f }));
+ exchange.getMessage().setBody(TextSegment.from("hello", metadata));
+
+ new
PgVectorEmbeddingsDataTypeTransformer().transform(exchange.getMessage(),
DataType.ANY, DataType.ANY);
+ return exchange;
+ }
+}