Files
seal-use/src/domains/langfuse/flows.test.ts
T
gitea 8d7f930596 Split Langfuse flow heuristics out of the trace service
service.ts interleaved orchestration (cache-first trace access) with ~200
lines of flow heuristics — stage word tables, evidence collection, source
classification — and carried near-isomorphic copies of the collector for the
attachment and rule flows. None of it had tests.

flows.ts now owns the heuristics: one collectEvidence shared by both flows,
stage vocabulary as data tables so tuning a word list cannot alter a code
path, and an explicit attachment/rule difference (only the rule flow falls
back to scanning every observation when a stage has no named candidates).
summary.ts holds the trace/observation projections both the service and the
flows need, which also keeps service <-> flows acyclic.

Adds 15 tests over the previously untested branches, including the two
behaviors the extraction surfaced: the "unknown" classification arm is
unreachable as written, and a filename-only needle set can never reach the
OCR/inference grading.
2026-10-11 19:33:29 +08:00

247 lines
9.6 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import {
ATTACHMENT_STAGES,
buildAttachmentFlow,
buildRuleFlow,
candidatesForStage,
classifyAttachmentEvidence,
collectEvidence,
RULE_FLOW_STAGES,
stageTerms,
summarizeEvidenceFields
} from "./flows.js";
import type { LangfuseObservationSummary } from "./types.js";
function observation(overrides: Partial<LangfuseObservationSummary> & { id: string }): LangfuseObservationSummary {
return {
traceId: "trace-1",
type: "SPAN",
...overrides
} as LangfuseObservationSummary;
}
describe("stage vocabulary", () => {
test("every stage resolves bilingual search terms", () => {
for (const stage of ATTACHMENT_STAGES) {
expect(stageTerms(stage, "attachment").length).toBeGreaterThan(0);
}
for (const stage of RULE_FLOW_STAGES) {
expect(stageTerms(stage, "rule").length).toBeGreaterThan(0);
}
});
test("matches observation names case-insensitively in either language", () => {
const observations = [
observation({ id: "a", name: "Attachment_Parsing" }),
observation({ id: "b", name: "文档解析 worker" }),
observation({ id: "c", name: "unrelated" })
];
const matched = candidatesForStage(observations, stageTerms("document_parsing", "attachment"));
expect(matched.map((item) => item.id)).toEqual(["b"]);
// The rule vocabulary is broader, so it also picks up the English name.
const ruleParsed = candidatesForStage(observations, stageTerms("document parsing", "rule"));
expect(ruleParsed.map((item) => item.id)).toEqual(["a", "b"]);
});
});
describe("collectEvidence", () => {
const obs = observation({
id: "obs-1",
name: "attachment parsing",
input: "folder/invoice.pdf",
output: "解析完成 invoice.pdf",
metadata: { file: "invoice.pdf" }
});
test("scans input, output and metadata and pads the snippet with context", () => {
const hits = collectEvidence(obs, ["invoice.pdf"], 5, 10);
expect(hits.map((hit) => hit.field)).toEqual(["input", "output", "metadata"]);
expect(hits[0]?.matched).toBe("invoice.pdf");
// contextChars=5 → 5 chars of lead-in before the needle (index 7 - 5 = 2).
expect(hits[0]?.snippet).toBe("lder/invoice.pdf");
// Needle sits at index 5 (4 CJK chars + space), so 5 chars of lead-in
// reaches the start of the string.
expect(hits[1]?.snippet).toBe("解析完成 invoice.pdf");
});
test("caps the number of hits so a pathological trace cannot balloon", () => {
const noisy = observation({
id: "obs-2",
input: "x".repeat(500),
output: "x".repeat(500),
metadata: { a: "x".repeat(500) }
});
expect(collectEvidence(noisy, ["x"], 10, 3)).toHaveLength(3);
expect(collectEvidence(noisy, ["nope"], 10, 3)).toHaveLength(0);
});
test("matching is case-insensitive on both sides", () => {
const hits = collectEvidence(obs, ["INVOICE.PDF"], 5, 10);
expect(hits.length).toBeGreaterThan(0);
// `matched` preserves the original casing from the trace text.
expect(hits[0]?.matched).toBe("invoice.pdf");
});
});
describe("classifyAttachmentEvidence", () => {
test("returns absent when nothing matched", () => {
expect(classifyAttachmentEvidence([], "file-1", "a.pdf")).toBe("absent");
});
test("filename-only and file-id-only when those are the sole hits", () => {
expect(
classifyAttachmentEvidence([{ matched: "a.pdf", snippet: "a.pdf" }], "file-1", "a.pdf")
).toBe("filename-only");
expect(
classifyAttachmentEvidence([{ matched: "file-1", snippet: "file-1" }], "file-1", "a.pdf")
).toBe("file-id-only");
});
test("some other hint wins over filename/id and is graded by the snippet", () => {
const other = [{ matched: "some extra token", snippet: "..." }];
expect(classifyAttachmentEvidence(other, "file-1", "a.pdf")).toBe("parsed-text");
expect(
classifyAttachmentEvidence(
[...other, { matched: "ocr", snippet: "run OCR on the scan" }],
"file-1",
"a.pdf"
)
).toBe("image-ocr");
expect(
classifyAttachmentEvidence(
[...other, { matched: "推断", snippet: "模型认为金额为 120" }],
"file-1",
"a.pdf"
)
).toBe("model-inferred");
});
test("with no identifiers every hit is an 'other hint' graded from the snippet", () => {
// fileName/fileId undefined → `matched !== undefined` is always true, so
// hasOtherHint fires and the snippet decides. Note: the union's "unknown"
// arm is unreachable — with both identifiers defined, hasOtherHint false
// already implies one of them matched. Kept as a defensive fallback only.
expect(
classifyAttachmentEvidence([{ matched: "x", snippet: "raw parsed text" }], undefined, undefined)
).toBe("parsed-text");
expect(
classifyAttachmentEvidence([{ matched: "x", snippet: "OCR pipeline output" }], undefined, undefined)
).toBe("image-ocr");
});
});
describe("summarizeEvidenceFields", () => {
test("counts hits per field and de-duplicates repeated matches", () => {
const summary = summarizeEvidenceFields([
{ field: "input", matched: "rule-a" } as never,
{ field: "input", matched: "rule-a" } as never,
{ field: "input", matched: "rule-b" } as never,
{ field: "output", matched: "rule-a" } as never
]);
expect(summary.input).toEqual({ count: 3, matched: ["rule-a", "rule-b"] });
expect(summary.output).toEqual({ count: 1, matched: ["rule-a"] });
expect(summary.metadata).toBeUndefined();
});
});
describe("buildAttachmentFlow", () => {
const observations = [
observation({ id: "p1", name: "attachment parsing", input: "读取 a.pdf" }),
observation({ id: "p2", name: "document_parsing", output: "解析 a.pdf 得到 120 元" }),
observation({ id: "p3", name: "approval_review", output: "OCR 结果 a.pdf 金额 120" }),
observation({ id: "other", name: "unrelated", input: "nothing here" })
];
test("labels a stage seen and classifies the evidence source", () => {
const stages = buildAttachmentFlow({
observations,
fileName: "a.pdf",
// A second, non-identifier needle is what makes hasOtherHint fire — a
// filename-only query can never reach the OCR/inference grading.
needles: ["a.pdf", "金额"],
contextChars: 20
});
expect(stages).toHaveLength(ATTACHMENT_STAGES.length);
expect(stages.map((stage) => stage.stage)).toEqual([...ATTACHMENT_STAGES]);
const parsing = stages.find((stage) => stage.stage === "document_parsing");
expect(parsing?.status).toBe("seen");
expect(parsing?.source).toBe("filename-only");
expect(parsing?.observations.map((item) => item.id)).toEqual(["p2"]);
expect(parsing?.evidence[0]?.observationId).toBe("p2");
const review = stages.find((stage) => stage.stage === "approval_review");
expect(review?.evidence.length).toBeGreaterThan(0);
// 金额 is a non-identifier hit, so hasOtherHint fires and "OCR" in the
// snippet grades this stage as image-ocr.
expect(review?.source).toBe("image-ocr");
});
test("stages with no matching observation report absent", () => {
const stages = buildAttachmentFlow({
observations,
fileId: "file-xyz",
needles: ["file-xyz"],
contextChars: 20
});
const understanding = stages.find(
(stage) => stage.stage === "image/document understanding"
);
expect(understanding?.status).toBe("absent");
expect(understanding?.source).toBe("absent");
expect(understanding?.observations).toEqual([]);
});
});
describe("buildRuleFlow", () => {
const observations = [
observation({ id: "r1", name: "rule matching", input: "规则:禁止差旅超标" }),
observation({ id: "g1", name: "generic span", output: "命中规则 禁止差旅超标" }),
observation({ id: "f1", name: "final review", output: "审核结论:驳回" })
];
test("falls back to every observation when no stage name matches", () => {
const flow = buildRuleFlow({
observations,
needles: ["禁止差旅超标"],
contextChars: 30
});
expect(flow.stages.ruleMatching?.matched).toBe(true);
expect(flow.stages.ruleMatching?.matchedObservationIds).toContain("r1");
// g1 sits in a generically-named span, reachable only via the fallback pool.
expect(flow.relatedObservationIds).toContain("g1");
expect(flow.evidenceCount).toBeGreaterThan(0);
// No observation is named for "document parsing", so the stage has zero
// *named* candidates but still scans the whole trace via the fallback —
// that is what keeps a rule applied inside a generically-named span visible.
const documentParsing = flow.stages.documentParsing;
expect(documentParsing?.observations).toEqual([]);
expect(documentParsing?.matched).toBe(true);
expect(documentParsing?.matchedObservationIds).toContain("r1");
});
test("reports extracted fields grouped by source field", () => {
const flow = buildRuleFlow({
observations,
needles: ["禁止差旅超标", "驳回"],
contextChars: 30
});
expect(flow.stages.ruleMatching?.extractedFields.input?.matched).toEqual(["禁止差旅超标"]);
expect(flow.stages.finalReview?.extractedFields.output?.matched).toEqual(["驳回"]);
expect(flow.stages.finalReview?.matched).toBe(true);
});
test("returns the documented stage keys in order", () => {
const flow = buildRuleFlow({ observations, needles: ["nothing-matches"], contextChars: 30 });
expect(Object.keys(flow.stages)).toEqual(["ruleMatching", "documentParsing", "finalReview"]);
expect(flow.evidenceCount).toBe(0);
expect(flow.relatedObservationIds).toEqual([]);
});
});