Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(topics): name what a topic definition readback lost (#19072)

Lysander Kiesel6cebaed475af
diff --git a/packages/shared/src/server/topics/postgres.test.ts b/packages/shared/src/server/topics/postgres.test.ts
index 24478f9df9..f9d4892e53 100644
--- a/packages/shared/src/server/topics/postgres.test.ts
+++ b/packages/shared/src/server/topics/postgres.test.ts
@@ -426,6 +426,39 @@ describe("Topics immutable definitions and run membership", () => {
expect(mocks.runUpdate).not.toHaveBeenCalled();
});
+ it("names the fields a definition readback lost, never their values", async () => {
+ const row = runRow({ id: "run-b" });
+ const created = {
+ ...topic,
+ createdByRunId: row.id,
+ name: "Secret topic name",
+ metadata: { count: 1, namingSampled: undefined },
+ };
+ mocks.runFind.mockResolvedValue(row);
+ let definitionInserted = false;
+ mocks.topicWrite.mockImplementation(async () => {
+ definitionInserted = true;
+ });
+ mocks.topicFind.mockImplementation(async () =>
+ definitionInserted
+ ? [{ ...created, name: "Other", metadata: { count: 2 } }]
+ : [],
+ );
+ const run = (await getTopicRun("project-a", row.id))!;
+ const failure = await saveTopicRun({
+ ...run,
+ topics: [created],
+ status: "completed",
+ }).catch((error: unknown) => error);
+ expect(failure).toMatchObject({
+ name: "TopicDefinitionReadbackError",
+ message:
+ "Topic definition readback did not match for 1 of 1 new definitions (name, metadata.count, metadata.namingSampled).",
+ });
+ expect((failure as Error).message).not.toMatch(/Secret|Other/);
+ expect(mocks.runUpdate).not.toHaveBeenCalled();
+ });
+
it("fails hydration instead of exposing only the definitions that remain", async () => {
mocks.runFind.mockResolvedValue(
runRow({
diff --git a/packages/shared/src/server/topics/postgres.ts b/packages/shared/src/server/topics/postgres.ts
index bd0a8f6cb5..efec97c940 100644
--- a/packages/shared/src/server/topics/postgres.ts
+++ b/packages/shared/src/server/topics/postgres.ts
@@ -525,10 +525,7 @@ export async function saveTopicRun(run: TopicRun): Promise<TopicRun> {
definitionTimeRange!,
);
for (const topic of inserted) saved.set(topic.topicVersionId, topic);
- for (const topic of missing) {
- if (!sameTopicDefinition(saved.get(topic.topicVersionId), topic))
- throw new Error("Topic definition readback did not match.");
- }
+ assertDefinitionsReadBack(missing, saved);
}
const row = await prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM topic_clustering_runs WHERE project_id = ${run.projectId} AND id = ${run.id} FOR UPDATE`;
@@ -561,3 +558,56 @@ export async function saveTopicRun(run: TopicRun): Promise<TopicRun> {
? runResult(row, saved)
: (await hydrateRuns(run.projectId, [row]))[0];
}
+
+/** Throws unless every new definition reads back identically, naming what differs. */
+function assertDefinitionsReadBack(
+ missing: TopicDefinition[],
+ saved: Map<string, TopicDefinition>,
+): void {
+ const mismatched = missing.filter(
+ (topic) => !sameTopicDefinition(saved.get(topic.topicVersionId), topic),
+ );
+ if (mismatched.length === 0) return;
+ const differences = new Set(
+ mismatched.flatMap((topic) =>
+ definitionDifferences(saved.get(topic.topicVersionId), topic),
+ ),
+ );
+ throw new TopicDefinitionReadbackError(
+ `Topic definition readback did not match for ${mismatched.length} of ${missing.length} new definitions (${[...differences].join(", ")}).`,
+ );
+}
+
+/** A written definition did not read back identically; the message names fields, never values. */
+export class TopicDefinitionReadbackError extends Error {
+ readonly name = "TopicDefinitionReadbackError";
+}
+
+/** Names what differs between a stored definition and its candidate, including metadata keys. */
+function definitionDifferences(
+ stored: TopicDefinition | undefined,
+ candidate: TopicDefinition,
+): string[] {
+ if (!stored) return ["not readable"];
+ const differs = (left: object, right: object, key: string) =>
+ key in left !== key in right ||
+ !isEqual(
+ (left as Record<string, unknown>)[key],
+ (right as Record<string, unknown>)[key],
+ );
+ const differences = sameTopicGeometry(stored, candidate) ? [] : ["geometry"];
+ const fields = new Set([...Object.keys(stored), ...Object.keys(candidate)]);
+ for (const field of fields) {
+ if (field === "centroid" || field === "radius" || field === "metadata")
+ continue;
+ if (differs(stored, candidate, field)) differences.push(field);
+ }
+ const keys = new Set([
+ ...Object.keys(stored.metadata),
+ ...Object.keys(candidate.metadata),
+ ]);
+ for (const key of keys)
+ if (differs(stored.metadata, candidate.metadata, key))
+ differences.push(`metadata.${key}`);
+ return differences;
+}
diff --git a/worker/src/features/topics/README.md b/worker/src/features/topics/README.md
index 58447d05d7..686d2a99c3 100644
--- a/worker/src/features/topics/README.md
+++ b/worker/src/features/topics/README.md
@@ -557,7 +557,9 @@ payloads. Retries can re-enter behind newer jobs, so this is head age, not the
oldest creation time anywhere in the backlog.
`.errors` reasons include `input_too_large` (transcript above the summary input
-limit) and `trace_too_large` (trace above the transcript load limits).
+limit), `trace_too_large` (trace above the transcript load limits) and
+`definition_readback` (a new topic definition did not read back identically; the
+error names the differing fields, never their values).
Summary `.results` carry `source:model|rule` and `facet` (the built-in facet's
name, or `custom`): the model decides `applicable`, `not_applicable` or
diff --git a/worker/src/features/topics/metrics.ts b/worker/src/features/topics/metrics.ts
index bef2494253..36bf3712d2 100644
--- a/worker/src/features/topics/metrics.ts
+++ b/worker/src/features/topics/metrics.ts
@@ -38,6 +38,7 @@ type TopicErrorReason =
| "numerical"
| "input_too_large"
| "trace_too_large"
+ | "definition_readback"
| "unknown";
// Statuses with their own operational meaning; exact codes are on the span.
@@ -153,6 +154,8 @@ export class TopicMetrics {
reason = "timeout";
if (error.name === "TopicInputTooLarge") reason = "input_too_large";
if (error.name === "TopicTraceTooLarge") reason = "trace_too_large";
+ if (error.name === "TopicDefinitionReadbackError")
+ reason = "definition_readback";
if (
[
"PrismaClientKnownRequestError",