You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2026/10/08 06:02:49 UTC
(skywalking) branch ai-agent-withhold-followup created (now b77b879271)
This is an automated email from the ASF dual-hosted git repository.
wu-sheng pushed a change to branch ai-agent-withhold-followup
in repository https://gitbox.apache.org/repos/asf/skywalking.git
at b77b879271 Fix what the confirming reviews of AI agent withholding found
This branch includes the following new commits:
new b77b879271 Fix what the confirming reviews of AI agent withholding found
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(skywalking) 01/01: Fix what the confirming reviews of AI agent withholding found
Posted by wu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
wu-sheng pushed a commit to branch ai-agent-withhold-followup
in repository https://gitbox.apache.org/repos/asf/skywalking.git
commit b77b87927105518294d81f692fb40f65c31e2ad4
Author: Wu Sheng <wu...@foxmail.com>
AuthorDate: Thu Oct 8 14:02:42 2026 +0800
Fix what the confirming reviews of AI agent withholding found
The reviews that confirmed the fixes of #14123 found five more places
where the OAP's withholding did not hold, or did not agree with the
Sessionizer's own rules.
- The masking walk stopped at a set of tools, so a prompt key inside one
kept its text. What a set holds besides its tools is now walked like
anything else, as the Sessionizer's walk does.
- A body that is not UTF-8 text was written as a literal under its
stored digest and size, so the served body no longer matched its own
manifest. Such a body cannot be a literal byte for byte, and is now
withheld whole; so is a request that is not one JSON object in UTF-8
text.
- A body is now held as the Session Data page says a reader holds one:
every reference points at a record that landed before it, a copy has
the digest and length it names, and the depth is one more than its
base's, or 0 when it copies nothing. A record that breaks one is not
held, so a request is withheld whole, and whether it is never depends
on which later files a reader reads.
- A record landed again under its id is the one already held, and none
of its pieces is held again. A later body that used a piece only the
repeat held made the whole files request fail, reading a part the held
record does not have. A repeat with another body is withheld whole.
- The page says that a completion's prompts and LangChain JS's message
id are the OAP's own rules, which the Sessionizer does not name a
record by, and states the rules a body is held by.
---
docs/en/setup/backend/ai-agent-conversation.md | 16 ++--
.../agent/conversation/providerbody/BodyStore.java | 64 +++++++++++++--
.../agent/conversation/withhold/Withholding.java | 54 ++++++++++---
.../conversation/providerbody/BodyStoreTest.java | 73 +++++++++++++++++
.../withhold/WithholdingShapesTest.java | 93 ++++++++++++++++++----
5 files changed, 264 insertions(+), 36 deletions(-)
diff --git a/docs/en/setup/backend/ai-agent-conversation.md b/docs/en/setup/backend/ai-agent-conversation.md
index 33cc87c0f2..680c48afcf 100644
--- a/docs/en/setup/backend/ai-agent-conversation.md
+++ b/docs/en/setup/backend/ai-agent-conversation.md
@@ -385,15 +385,21 @@ what is withheld.
completion's `prompts`, becomes `[withheld: system_prompt]`, apart from a block's `type` and `role`, which say what
it is; so does the content of a message of the `system` or `developer` role, wherever it sits, LangChain's pair of
a role and its content, and LangChain's serialized system message, whose role LangChain JS writes only in its
- `id`. Each tool under `tools`, `functions`, `function_declarations`, `tool_definitions` or `available_tools` keeps
- its name, or the name of the one object it wraps, which the transcript's tool calls name anyway, and is otherwise
- `{"withheld":"tool_schemas"}`. The masked request is written
+ `id`. A completion's `prompts` and that `id` are the OAP's own: the Sessionizer names no record by them, since its
+ viewer serves no body. Each tool under `tools`, `functions`, `function_declarations`, `tool_definitions` or
+ `available_tools` keeps its name, or the name of the one object it wraps, which the transcript's tool calls name
+ anyway, and is otherwise `{"withheld":"tool_schemas"}`; what the set holds besides its tools is masked like
+ anything else. The masked request is written
back as a body of its own: one `lit` segment, `depth` 0, no `copy` and no `piece`, its own `sha256` and `bytes`,
and `withheld` naming what was applied, so a reader that checks a body against its manifest still can. The request's
own pieces stay except the ones that are a withheld block's text or a tool, whose bytes are the secret, and a body
kept whole in an `unknown` part, which holds them all. A response holds neither and is the stored line, unless it
- refers to a request's bytes, when it is written whole the same way, which hides nothing. A request that does not
- rebuild, or is not one JSON object, is withheld whole, as a transcript record is; so is one whose rebuild would
+ refers to a request's bytes, when it is written whole the same way, which hides nothing; a body that is not UTF-8
+ text cannot be written as a literal byte for byte, and is withheld whole instead. A body is held as the Session
+ Data page says a reader holds one: every reference points at a record that landed before it, a copy has the
+ digest and length it names, the depth is one more than its base's or 0, and a record landed again under its id is
+ the one already held. A request that is not held, does not rebuild, or is not one JSON object in UTF-8 text, is
+ withheld whole, as a transcript record is; so is one whose rebuild would
hold more than `maxResponseBytes` at once, counted from the manifests before anything is built: the body, and
beside it the body it copies from, so about two bodies for a chain of copies. So is a record with no manifest of a
schema the OAP knows, since it may be a request;
diff --git a/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStore.java b/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStore.java
index afee69e8a5..2bec232a49 100644
--- a/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStore.java
+++ b/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStore.java
@@ -49,6 +49,8 @@ public final class BodyStore {
/** The record and part holding each piece, by the piece's digest; the first record to hold a piece keeps it. */
private final Map<String, int[]> pieceAt = new HashMap<>();
private final Map<String, String> pieceRecord = new HashMap<>();
+ /** Why each record that carries a body is not held, by its id: a reference or a depth the page does not allow. */
+ private final Map<String, String> refused = new HashMap<>();
/** The rebuilt bodies kept, the one kept longest first. */
private final Map<String, byte[]> rebuilt = new LinkedHashMap<>();
private long kept;
@@ -90,8 +92,15 @@ public final class BodyStore {
}
/**
- * @param rec one record of a <code>provider_body</code> file
- * @return the manifest the record carries, or null when it holds no body
+ * Holds a record's body as the Session Data page's "Provider bodies" section lets a reader: every reference points
+ * at a record that landed before it, a copy is of a body with the digest and at least the length it names, and the
+ * depth is one more than its base's, or 0 when it copies nothing, and at most {@link Manifest#MAX_DEPTH}. A record
+ * that breaks one is not held, so whether it is never depends on what lands after it, nor on which later files a
+ * reader happens to read. A record landed again under its id, as one is after an interrupted pass, is the one
+ * already held, and none of its pieces is held again, so every piece points at a part of the record that holds it.
+ *
+ * @param rec one record of a <code>provider_body</code> file, after every record added before it
+ * @return the manifest held under the record's id, or null when it holds no body or is not held
*/
@Nullable
public Manifest add(final SessionDataFile.Record rec) {
@@ -99,10 +108,16 @@ public final class BodyStore {
if (m == null || rec.getId() == null || rec.getId().isEmpty()) {
return null;
}
- // a record landed again under its id, as one is after an interrupted pass, is the one already held
- if (!records.containsKey(rec.getId())) {
- records.put(rec.getId(), new Held(rec, m));
+ final Held already = records.get(rec.getId());
+ if (already != null) {
+ return already.manifest;
+ }
+ final String why = refusal(rec.getId(), m);
+ if (why != null) {
+ refused.putIfAbsent(rec.getId(), why);
+ return null;
}
+ records.put(rec.getId(), new Held(rec, m));
final List<SessionDataFile.Part> parts = rec.getParts();
for (int i = 0; i < m.getPartIndex(); i++) {
final SessionDataFile.Part p = parts.get(i);
@@ -119,6 +134,42 @@ public final class BodyStore {
return m;
}
+ /** @return why a record may not be held, as {@link #add(SessionDataFile.Record)} says, or null when it may */
+ @Nullable
+ private String refusal(final String id, final Manifest m) {
+ if (m.getDepth() < 0 || m.getDepth() > Manifest.MAX_DEPTH) {
+ return id + " claims depth " + m.getDepth();
+ }
+ int copies = 0;
+ for (final Manifest.Segment seg : m.getSegments()) {
+ if (seg.getPart() >= m.getPartIndex()) {
+ return id + " names part " + seg.getPart() + ", which it does not have";
+ }
+ if (seg.getPiece() != null && !pieceRecord.containsKey(seg.getPiece())) {
+ return id + " refers to piece " + seg.getPiece() + ", which no earlier record holds";
+ }
+ if (seg.getCopyFrom() == null) {
+ continue;
+ }
+ copies++;
+ final Held base = records.get(seg.getCopyFrom());
+ if (base == null) {
+ return id + " copies from " + seg.getCopyFrom() + ", which no earlier record holds";
+ }
+ if (!base.manifest.getSha256().equals(seg.getCopySha256()) || seg.getCopyLen() < 0
+ || seg.getCopyLen() > base.manifest.getBytes()) {
+ return id + " copies from " + seg.getCopyFrom() + " with a digest or length it does not have";
+ }
+ if (m.getDepth() != base.manifest.getDepth() + 1) {
+ return id + " claims depth " + m.getDepth() + " over a base of depth " + base.manifest.getDepth();
+ }
+ }
+ if (copies == 0 && m.getDepth() != 0) {
+ return id + " claims depth " + m.getDepth() + " and copies nothing";
+ }
+ return null;
+ }
+
/** @return the bytes of the rebuilt bodies kept */
long keptBytes() {
return kept;
@@ -147,7 +198,7 @@ public final class BodyStore {
}
final Held h = records.get(id);
if (h == null) {
- throw new BodyException("the session holds no body " + id);
+ throw new BodyException(refused.getOrDefault(id, "the session holds no body " + id));
}
// Whether a body fits is decided from the manifests, before anything is built, so it depends on the body
// and the bodies it copies from alone, never on which bodies this store happens to keep: a file asked for
@@ -190,6 +241,7 @@ public final class BodyStore {
} else if (seg.getPart() >= 0 && seg.getPart() < m.getPartIndex()) {
built += Math.max(0, h.record.getParts().get(seg.getPart()).getBytes());
} else if (seg.getPiece() != null && pieceRecord.containsKey(seg.getPiece())) {
+ // a piece is held only by the record whose part it is, so its index is within that record's parts
final Held holder = records.get(pieceRecord.get(seg.getPiece()));
built += Math.max(0, holder.record.getParts().get(pieceAt.get(seg.getPiece())[0]).getBytes());
}
diff --git a/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/Withholding.java b/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/Withholding.java
index 57234bdc3b..950f19d7de 100644
--- a/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/Withholding.java
+++ b/oap-server/analyzer/ai-agent-conversation/src/main/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/Withholding.java
@@ -24,6 +24,9 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -214,6 +217,23 @@ public final class Withholding {
return -1;
}
+ /**
+ * @return the bytes as text, or null when they are not UTF-8: replacing what does not decode would change the
+ * bytes a digest was taken of
+ */
+ @Nullable
+ private static String utf8(final byte[] bytes) {
+ try {
+ return StandardCharsets.UTF_8.newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ } catch (final CharacterCodingException e) {
+ return null;
+ }
+ }
+
private static void write(final ByteArrayOutputStream out, final String line) {
final byte[] bytes = line.getBytes(StandardCharsets.UTF_8);
out.write(bytes, 0, bytes.length);
@@ -233,7 +253,10 @@ public final class Withholding {
if (m == null) {
return withheldLine(rec);
}
- final Manifest held = store == null || StringUtil.isEmpty(rec.getId()) ? null : store.manifest(rec.getId());
+ // held under its id with its own digest: a record landed again with another is not the one held, and a
+ // reader refuses it
+ final Manifest found = store == null || StringUtil.isEmpty(rec.getId()) ? null : store.manifest(rec.getId());
+ final Manifest held = found != null && found.getSha256().equals(m.getSha256()) ? found : null;
if (m.isRequest()) {
return held == null ? withheldLine(rec) : request(rec, m, store, hidden, rewritten);
}
@@ -327,20 +350,24 @@ public final class Withholding {
/**
* @return the record's line with its body rebuilt and written as one literal segment, its own pieces kept, and
- * its digest and size as they were; or null when the body does not rebuild
+ * its digest and size as they were; or null when the body does not rebuild, or is not UTF-8 text, which a literal
+ * segment cannot hold byte for byte
*/
@Nullable
private static String standalone(final SessionDataFile.Record rec, final Manifest m, final BodyStore store) {
- final byte[] body;
+ final String body;
try {
- body = store.body(rec.getId());
+ body = utf8(store.body(rec.getId()));
} catch (final BodyStore.BodyException e) {
return null;
}
+ if (body == null) {
+ return null;
+ }
final JsonObject manifest = m.getJson().deepCopy();
manifest.addProperty("depth", 0);
manifest.remove("segments");
- manifest.add("segments", Manifest.Segment.literal(new String(body, StandardCharsets.UTF_8)));
+ manifest.add("segments", Manifest.Segment.literal(body));
final List<String> parts = new ArrayList<>();
final List<SessionDataFile.Part> own = rec.getParts();
for (int i = 0; i < m.getPartIndex(); i++) {
@@ -361,22 +388,24 @@ public final class Withholding {
/**
* @return the request record's line with its body masked; the line written whole when the body holds nothing
* to withhold but refers to a request's bytes; null for the stored line when it holds nothing and refers to
- * none; the record withheld whole when its body does not rebuild or is not one JSON object
+ * none; the record withheld whole when its body does not rebuild or is not one JSON object in UTF-8 text
*/
@Nullable
private static String request(final SessionDataFile.Record rec, final Manifest m, final BodyStore store,
final List<String> hidden, final Map<String, Boolean> rewritten) {
- final JsonObject body;
+ final String text;
try {
- final JsonElement parsed = Schema.parse(new String(store.body(rec.getId()), StandardCharsets.UTF_8));
- body = parsed != null && parsed.isJsonObject() ? parsed.getAsJsonObject() : null;
+ text = utf8(store.body(rec.getId()));
} catch (final BodyStore.BodyException e) {
return withheldLine(rec);
}
- if (body == null) {
- // a body that is not one JSON object cannot be read for what it holds, so all of it is withheld
+ final JsonElement parsed = text == null ? null : Schema.parse(text);
+ if (parsed == null || !parsed.isJsonObject()) {
+ // a body that is not one JSON object in UTF-8 text cannot be read for what it holds, so all of it is
+ // withheld
return withheldLine(rec);
}
+ final JsonObject body = parsed.getAsJsonObject();
// every string of what is masked, so a piece that held one goes with it
final Set<String> maskedTexts = new HashSet<>();
final boolean changed = mask(body, hidden, maskedTexts);
@@ -482,6 +511,9 @@ public final class Withholding {
changed = true;
} else if (hidden.contains(Hide.TOOL_SCHEMAS) && TOOL_KEYS.contains(k) && offersTools(inner)) {
changed |= maskTools(o, key, maskedTexts);
+ // what the set holds besides its tools is walked like anything else, so a prompt key in it is
+ // masked as the Sessionizer's walk would find it
+ changed |= mask(o.get(key), hidden, maskedTexts);
} else {
changed |= mask(inner, hidden, maskedTexts);
}
diff --git a/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStoreTest.java b/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStoreTest.java
index 0b19635456..7fc7e03973 100644
--- a/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStoreTest.java
+++ b/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/providerbody/BodyStoreTest.java
@@ -18,6 +18,9 @@
package org.apache.skywalking.oap.server.ai.agent.conversation.providerbody;
import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
import java.util.Map;
import org.apache.skywalking.oap.server.ai.agent.conversation.Fixtures;
import org.apache.skywalking.oap.server.ai.agent.conversation.format.Digests;
@@ -150,6 +153,76 @@ public class BodyStoreTest {
+ "\",\"bytes\":" + body.length() + ",\"depth\":" + depth + ",\"segments\":" + segments + "}}]}\n";
}
+ /**
+ * A record landed again under its id is the one already held, and none of its pieces is held again: a later body
+ * that uses a piece only the repeat holds is not held either, and says why, rather than reading a part the held
+ * record does not have.
+ */
+ @Test
+ public void aRecordLandedAgainIsTheOneHeld() throws Exception {
+ final String p0 = "\"" + "p".repeat(20) + "\"";
+ final String p1 = "\"" + "q".repeat(20) + "\"";
+ final String later = "{\"b\":" + p1 + "}";
+ final String file = HEADER
+ + record("x", "{\"a\":1}", 0, "[{\"lit\":\"{\\\"a\\\":1}\"}]")
+ + withPieces("x", "[" + p0 + "," + p1 + "]", Arrays.asList(p0, p1), "[{\"lit\":\"[\"},{\"part\":0},{\"lit\":\",\"},{\"part\":1},{\"lit\":\"]\"}]")
+ + record("y", later, 0, "[{\"lit\":\"{\\\"b\\\":\"},{\"piece\":\"" + Digests.sha256Hex(p1.getBytes(StandardCharsets.UTF_8)) + "\"},{\"lit\":\"}\"}]")
+ + "{\"t\":\"end\",\"records\":3,\"digest\":\"x\"}\n";
+ final BodyStore store = new BodyStore();
+ store.add(SessionDataFile.parse(file.getBytes(StandardCharsets.UTF_8)));
+ assertEquals("{\"a\":1}", new String(store.body("x"), StandardCharsets.UTF_8));
+ assertTrue(assertThrows(BodyStore.BodyException.class, () -> store.body("y")).getMessage().contains("which no earlier record holds"));
+ }
+
+ /**
+ * A reference to a record that lands later is not held, as the page says no reference may be, so a body reads the
+ * same whether or not the later file is read: here it is not held either way.
+ */
+ @Test
+ public void aReferenceToALaterRecordIsNotHeldWhateverIsRead() throws Exception {
+ final String p = "\"" + "r".repeat(20) + "\"";
+ final String early = HEADER
+ + record("e", "{\"e\":" + p + "}", 0, "[{\"lit\":\"{\\\"e\\\":\"},{\"piece\":\"" + Digests.sha256Hex(p.getBytes(StandardCharsets.UTF_8)) + "\"},{\"lit\":\"}\"}]")
+ + "{\"t\":\"end\",\"records\":1,\"digest\":\"x\"}\n";
+ final String late = HEADER.replace("\"seq\":1", "\"seq\":2")
+ + withPieces("l", "[" + p + "]", Collections.singletonList(p), "[{\"lit\":\"[\"},{\"part\":0},{\"lit\":\"]\"}]")
+ + "{\"t\":\"end\",\"records\":1,\"digest\":\"x\"}\n";
+ final BodyStore alone = new BodyStore();
+ alone.add(SessionDataFile.parse(early.getBytes(StandardCharsets.UTF_8)));
+ final BodyStore both = new BodyStore();
+ both.add(SessionDataFile.parse(early.getBytes(StandardCharsets.UTF_8)));
+ both.add(SessionDataFile.parse(late.getBytes(StandardCharsets.UTF_8)));
+ assertTrue(assertThrows(BodyStore.BodyException.class, () -> alone.body("e")).getMessage().contains("which no earlier record holds"));
+ assertTrue(assertThrows(BodyStore.BodyException.class, () -> both.body("e")).getMessage().contains("which no earlier record holds"));
+ }
+
+ /** A depth the page does not allow is not held: one claimed without a copy, and one that is not its base's plus one. */
+ @Test
+ public void aDepthThePageDoesNotAllowIsNotHeld() throws Exception {
+ final String file = HEADER
+ + record("a", "a".repeat(20), 3, "[{\"lit\":\"" + "a".repeat(20) + "\"}]")
+ + record("b", "b".repeat(20), 0, "[{\"lit\":\"" + "b".repeat(20) + "\"}]")
+ + record("c", "b".repeat(10), 2, "[{\"copy\":{\"from\":\"b\",\"sha256\":\"" + Digests.sha256Hex("b".repeat(20).getBytes(StandardCharsets.UTF_8))
+ + "\",\"len\":10}}]")
+ + "{\"t\":\"end\",\"records\":3,\"digest\":\"x\"}\n";
+ final BodyStore store = new BodyStore();
+ store.add(SessionDataFile.parse(file.getBytes(StandardCharsets.UTF_8)));
+ assertTrue(assertThrows(BodyStore.BodyException.class, () -> store.body("a")).getMessage().contains("claims depth 3 and copies nothing"));
+ assertTrue(assertThrows(BodyStore.BodyException.class, () -> store.body("c")).getMessage().contains("claims depth 2 over a base of depth 0"));
+ assertEquals(20, store.body("b").length);
+ }
+
+ /** A request record with its pieces as data parts before the manifest. */
+ private static String withPieces(final String id, final String body, final List<String> pieces, final String segments) {
+ final StringBuilder parts = new StringBuilder();
+ for (final String piece : pieces) {
+ parts.append("{\"k\":\"data\",\"data\":").append(piece).append(",\"state\":\"available\",\"bytes\":").append(piece.length()).append("},");
+ }
+ return "{\"ord\":1,\"off\":0,\"sha\":\"0\",\"bytes\":1,\"id\":\"" + id + "\",\"parts\":[" + parts
+ + "{\"k\":\"data\",\"data\":{\"schema\":\"provider_body/1\",\"role\":\"request\",\"sha256\":\""
+ + Digests.sha256Hex(body.getBytes(StandardCharsets.UTF_8)) + "\",\"bytes\":" + body.length() + ",\"depth\":0,\"segments\":" + segments + "}}]}\n";
+ }
+
@Test
public void aReferenceTheSessionDoesNotHoldIsRefused() {
final SessionDataFile f = SessionDataFile.parse((
diff --git a/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/WithholdingShapesTest.java b/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/WithholdingShapesTest.java
index d074d4109c..8e8c704ed6 100644
--- a/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/WithholdingShapesTest.java
+++ b/oap-server/analyzer/ai-agent-conversation/src/test/java/org/apache/skywalking/oap/server/ai/agent/conversation/withhold/WithholdingShapesTest.java
@@ -78,6 +78,8 @@ public class WithholdingShapesTest {
"{\"system\":[{\"type\":\"text\",\"content\":\"" + SECRET + "\"}],\"messages\":[{\"role\":\"user\",\"content\":\"" + PERSON + "\"}],\"tools\":[{\"name\":\"t\",\"description\":\"" + TOOL_SECRET + "\"}]}",
// Bedrock: the tools under the client's toolConfig, each in a toolSpec
"{\"system\":[{\"text\":\"" + SECRET + "\"}],\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"" + PERSON + "\"}]}],\"toolConfig\":{\"tools\":[{\"toolSpec\":{\"name\":\"t\",\"description\":\"" + TOOL_SECRET + "\",\"inputSchema\":{\"json\":{}}}}]}}",
+ // a prompt key inside a set of tools keyed by name, beside a tool
+ "{\"messages\":[{\"role\":\"user\",\"content\":\"" + PERSON + "\"}],\"tools\":{\"t\":{\"description\":\"" + TOOL_SECRET + "\"},\"system_prompt\":\"" + SECRET + "\"}}",
// LangChain JS: a serialized system message says its role only in the class that ends its id
"{\"messages\":[[{\"lc\":1,\"type\":\"constructor\",\"id\":[\"langchain_core\",\"messages\",\"SystemMessage\"],\"kwargs\":{\"content\":\"" + SECRET + "\",\"additional_kwargs\":{}}},{\"lc\":1,\"type\":\"constructor\",\"id\":[\"langchain_core\",\"messages\",\"HumanMessage\"],\"kwargs\":{\"content\":\"" + PERSON + "\"}}]],\"tools\":[{\"name\":\"t\",\"description\":\"" + TOOL_SECRET + "\"}]}",
})
@@ -519,20 +521,7 @@ public class WithholdingShapesTest {
public void aRequestKeptWholeInAnUnknownPartIsMasked(final boolean base64) {
final String body = "{\"system\":\"" + SECRET + "\",\"messages\":[{\"role\":\"user\",\"content\":\"" + PERSON + "\"}]}";
final byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
- final JsonObject unknown = new JsonObject();
- unknown.addProperty("k", "unknown");
- unknown.addProperty("text", "it did not come back whole");
- unknown.addProperty("data", base64 ? Base64.getEncoder().encodeToString(bytes) : body);
- if (base64) {
- unknown.addProperty("encoding", "base64");
- }
- unknown.addProperty("state", "available");
- unknown.addProperty("bytes", bytes.length);
- final String manifest = "{\"schema\":\"provider_body/1\",\"role\":\"request\",\"src\":\"r1.json\",\"sha256\":\""
- + Digests.sha256Hex(bytes) + "\",\"bytes\":" + bytes.length + ",\"depth\":0,\"why\":\"it did not come back whole\",\"segments\":[{\"part\":0}]}";
- final String rec = "{\"ord\":1,\"off\":0,\"sha\":\"0\",\"bytes\":" + bytes.length + ",\"id\":\"r1\",\"parts\":[" + unknown
- + ",{\"k\":\"data\",\"data\":" + manifest + ",\"state\":\"available\",\"bytes\":" + manifest.length() + "}]}";
- final byte[] stored = bodyFile(rec);
+ final byte[] stored = bodyFile(keptWhole("r1", Manifest.ROLE_REQUEST, bytes, base64));
final BodyStore store = new BodyStore();
store.add(SessionDataFile.parse(stored));
assertEquals(body, assertRebuilds(store, "r1"));
@@ -545,6 +534,82 @@ public class WithholdingShapesTest {
assertTrue(masked.contains("[withheld: system_prompt]") && masked.contains(PERSON), masked);
}
+ /**
+ * A body that is not UTF-8 text cannot be written as a literal byte for byte, so it is withheld whole, never
+ * served with its stored digest over text that no longer has it: a request kept whole, its system prompt beside
+ * the byte FF, which is not one JSON object in UTF-8 text, and a response that copies all of it.
+ */
+ @Test
+ public void aBodyThatIsNotUtf8IsWithheldWholeRatherThanRewritten() {
+ final byte[] head = ("{\"system\":\"" + SECRET + "\",\"x\":\"").getBytes(StandardCharsets.UTF_8);
+ final byte[] bytes = Arrays.copyOf(head, head.length + 3);
+ bytes[head.length] = (byte) 0xff;
+ bytes[head.length + 1] = '"';
+ bytes[head.length + 2] = '}';
+ final String digest = Digests.sha256Hex(bytes);
+ final String response = "{\"ord\":2,\"off\":0,\"sha\":\"0\",\"bytes\":1,\"id\":\"b\",\"parts\":[{\"k\":\"data\",\"data\":"
+ + "{\"schema\":\"provider_body/1\",\"role\":\"response\",\"src\":\"b.json\",\"sha256\":\"" + digest
+ + "\",\"bytes\":" + bytes.length + ",\"depth\":1,\"segments\":[{\"copy\":{\"from\":\"a\",\"sha256\":\"" + digest
+ + "\",\"len\":" + bytes.length + "}}]},\"state\":\"available\",\"bytes\":1}]}";
+ final byte[] stored = bodyFile(keptWhole("a", Manifest.ROLE_REQUEST, bytes, true), response);
+ final BodyStore store = new BodyStore();
+ store.add(SessionDataFile.parse(stored));
+ final byte[] served = Withholding.file(stored, Collections.singletonList(Hide.SYSTEM_PROMPT), store).getBytes();
+ assertFalse(new String(served, StandardCharsets.UTF_8).contains(SECRET));
+ final SessionDataFile after = SessionDataFile.parse(served);
+ assertNull(Manifest.of(after.getRecords().get(0)), "a request that is not UTF-8 text is withheld whole");
+ final BodyStore again = new BodyStore();
+ again.add(after);
+ for (final SessionDataFile.Record rec : after.getRecords()) {
+ if (Manifest.of(rec) != null) {
+ // whatever is served with a manifest rebuilds to it
+ assertRebuilds(again, rec.getId());
+ continue;
+ }
+ for (final SessionDataFile.Part p : rec.getParts()) {
+ assertEquals("omitted", p.getState(), rec.getId());
+ }
+ }
+ }
+
+ /**
+ * A record landed again under an id the session holds, with another body, is not the one held, and a reader
+ * refuses it: it is withheld whole, so its own pieces, which the held body's masking knows nothing of, go too.
+ */
+ @Test
+ public void aRecordLandedAgainWithAnotherBodyIsWithheldWhole() {
+ final String held = "{\"system\":\"short\"}";
+ final String piece = "\"" + SECRET + "\"";
+ final String again = "{\"system\":" + piece + "}";
+ final byte[] stored = bodyFile(request("x", held, Collections.emptyList()),
+ record("x", Manifest.ROLE_REQUEST, again, Collections.singletonList(piece),
+ segments(lit("{\"system\":"), "{\"part\":0}", lit("}"))));
+ final BodyStore store = new BodyStore();
+ store.add(SessionDataFile.parse(stored));
+ final String served = new String(Withholding.file(stored, Collections.singletonList(Hide.SYSTEM_PROMPT), store).getBytes(), StandardCharsets.UTF_8);
+ assertFalse(served.contains(SECRET), served);
+ assertNull(Manifest.of(SessionDataFile.parse(served.getBytes(StandardCharsets.UTF_8)).getRecords().get(1)));
+ }
+
+ /**
+ * A record the Sessionizer kept whole, its body in one unknown part with a why, as plain text or as base64.
+ */
+ private static String keptWhole(final String id, final String role, final byte[] bytes, final boolean base64) {
+ final JsonObject unknown = new JsonObject();
+ unknown.addProperty("k", "unknown");
+ unknown.addProperty("text", "it did not come back whole");
+ unknown.addProperty("data", base64 ? Base64.getEncoder().encodeToString(bytes) : new String(bytes, StandardCharsets.UTF_8));
+ if (base64) {
+ unknown.addProperty("encoding", "base64");
+ }
+ unknown.addProperty("state", "available");
+ unknown.addProperty("bytes", bytes.length);
+ final String manifest = "{\"schema\":\"provider_body/1\",\"role\":\"" + role + "\",\"src\":\"" + id + ".json\",\"sha256\":\""
+ + Digests.sha256Hex(bytes) + "\",\"bytes\":" + bytes.length + ",\"depth\":0,\"why\":\"it did not come back whole\",\"segments\":[{\"part\":0}]}";
+ return "{\"ord\":1,\"off\":0,\"sha\":\"0\",\"bytes\":" + bytes.length + ",\"id\":\"" + id + "\",\"parts\":[" + unknown
+ + ",{\"k\":\"data\",\"data\":" + manifest + ",\"state\":\"available\",\"bytes\":" + manifest.length() + "}]}";
+ }
+
private static String piece(final String bytes) {
return "{\"piece\":\"" + Digests.sha256Hex(bytes.getBytes(StandardCharsets.UTF_8)) + "\"}";
}