forked from r.muellner/velum-raycast
fix: isolate failing project analysis batches
This commit is contained in:
66
src/lib/project-analysis.ts
Normal file
66
src/lib/project-analysis.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import type {
|
||||
EntityType,
|
||||
PlaceholderMapping,
|
||||
PseudonymizeResponse,
|
||||
} from "../types";
|
||||
import { makeTextBatches } from "./project-review";
|
||||
import type { TextBatch } from "./project-review";
|
||||
|
||||
type Analyze = (
|
||||
text: string,
|
||||
mapping: PlaceholderMapping,
|
||||
entityTypes: EntityType[],
|
||||
forceMasks: Record<string, string[]>,
|
||||
) => Promise<PseudonymizeResponse>;
|
||||
|
||||
/** Retry a failing server batch in smaller groups, without losing file boundaries. */
|
||||
export async function analyzeProjectBatch(
|
||||
batch: TextBatch,
|
||||
mapping: PlaceholderMapping,
|
||||
entityTypes: EntityType[],
|
||||
forceMasks: Record<string, string[]>,
|
||||
analyze: Analyze,
|
||||
phase: string,
|
||||
): Promise<{
|
||||
mapping: PlaceholderMapping;
|
||||
results: Array<{ batch: TextBatch; result: PseudonymizeResponse }>;
|
||||
}> {
|
||||
try {
|
||||
const result = await analyze(batch.text, mapping, entityTypes, forceMasks);
|
||||
return { mapping: result.mapping, results: [{ batch, result }] };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (!/request failed: 5\d\d\b/i.test(message)) throw error;
|
||||
if (batch.segments.length < 2) {
|
||||
throw new Error(
|
||||
`${phase}: ${batch.segments[0]?.key ?? "unbekannte Datei"}: ${message}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
const middle = Math.floor(batch.segments.length / 2);
|
||||
const halves = [
|
||||
batch.segments.slice(0, middle),
|
||||
batch.segments.slice(middle),
|
||||
];
|
||||
let current = mapping;
|
||||
const results: Array<{ batch: TextBatch; result: PseudonymizeResponse }> =
|
||||
[];
|
||||
for (const segments of halves) {
|
||||
const [part] = makeTextBatches(
|
||||
segments.map(({ key, text }) => ({ key, text })),
|
||||
Number.POSITIVE_INFINITY,
|
||||
);
|
||||
const analyzed = await analyzeProjectBatch(
|
||||
part,
|
||||
current,
|
||||
entityTypes,
|
||||
forceMasks,
|
||||
analyze,
|
||||
phase,
|
||||
);
|
||||
current = analyzed.mapping;
|
||||
results.push(...analyzed.results);
|
||||
}
|
||||
return { mapping: current, results };
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, spansBySegment,
|
||||
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||
} from "./lib/project-review";
|
||||
import { analyzeProjectBatch } from "./lib/project-analysis";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const MAX_REVIEW_HITS = 50000;
|
||||
@@ -144,12 +145,15 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
||||
const batches = makeTextBatches([...texts].map(([key, text]) => ({ key, text })));
|
||||
for (const [index, batch] of batches.entries()) {
|
||||
onProgress(`Textdateien analysieren: Paket ${index + 1}/${batches.length}`);
|
||||
const result = await pseudonymize(batch.text, mapping, entityTypes, masks);
|
||||
mapping = result.mapping;
|
||||
const byFile = spansBySegment(batch, result.spans);
|
||||
for (const segment of batch.segments) {
|
||||
const draft = draftsByPath.get(segment.key)!;
|
||||
addHits(draft, contentHits(draft.file, byFile.get(segment.key) ?? [], segment.text));
|
||||
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, pseudonymize,
|
||||
"Textdateien analysieren");
|
||||
mapping = analyzed.mapping;
|
||||
for (const { batch: part, result } of analyzed.results) {
|
||||
const byFile = spansBySegment(part, result.spans);
|
||||
for (const segment of part.segments) {
|
||||
const draft = draftsByPath.get(segment.key)!;
|
||||
addHits(draft, contentHits(draft.file, byFile.get(segment.key) ?? [], segment.text));
|
||||
}
|
||||
}
|
||||
}
|
||||
const documents = drafts.filter((draft) => draft.file.kind === "document");
|
||||
@@ -185,19 +189,22 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
||||
const byPath = new Map(paths.map((path) => [path.key, path]));
|
||||
for (const [index, batch] of pathBatches.entries()) {
|
||||
onProgress(`Dateinamen analysieren: Paket ${index + 1}/${pathBatches.length}`);
|
||||
const result = await pseudonymize(batch.text, mapping, entityTypes, masks);
|
||||
mapping = result.mapping;
|
||||
const spans = spansBySegment(batch, result.spans);
|
||||
for (const segment of batch.segments) {
|
||||
const path = byPath.get(segment.key)!;
|
||||
const found = toUtf16Offsets(segment.text, spans.get(path.key) ?? []).map((span, hitIndex) => ({
|
||||
...span, id: `${path.key}:path:${hitIndex}`, file: path.key,
|
||||
source: "Datei- oder Ordnername", kind: "path" as const,
|
||||
context: path.value,
|
||||
}));
|
||||
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||
hits.push(...path.hits);
|
||||
if (hits.length > MAX_REVIEW_HITS) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, pseudonymize,
|
||||
"Dateinamen analysieren");
|
||||
mapping = analyzed.mapping;
|
||||
for (const { batch: part, result } of analyzed.results) {
|
||||
const spans = spansBySegment(part, result.spans);
|
||||
for (const segment of part.segments) {
|
||||
const path = byPath.get(segment.key)!;
|
||||
const found = toUtf16Offsets(segment.text, spans.get(path.key) ?? []).map((span, hitIndex) => ({
|
||||
...span, id: `${path.key}:path:${hitIndex}`, file: path.key,
|
||||
source: "Datei- oder Ordnername", kind: "path" as const,
|
||||
context: path.value,
|
||||
}));
|
||||
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||
hits.push(...path.hits);
|
||||
if (hits.length > MAX_REVIEW_HITS) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||
}
|
||||
}
|
||||
}
|
||||
return { drafts, retained, paths, mapping, previousMapping,
|
||||
|
||||
81
tests/project-analysis.test.ts
Normal file
81
tests/project-analysis.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { expect, it } from "bun:test";
|
||||
import { analyzeProjectBatch } from "../src/lib/project-analysis";
|
||||
import { makeTextBatches, spansBySegment } from "../src/lib/project-review";
|
||||
import type { PlaceholderMapping, PseudonymizeResponse } from "../src/types";
|
||||
|
||||
function response(
|
||||
text: string,
|
||||
mapping: PlaceholderMapping,
|
||||
): PseudonymizeResponse {
|
||||
const original = text.includes("Anna") ? "Anna" : "Berta";
|
||||
const placeholder = original === "Anna" ? "PERSON_01" : "PERSON_02";
|
||||
return {
|
||||
pseudonymized_text: text.replace(original, placeholder),
|
||||
selected_entity_types: ["PERSON"],
|
||||
mapping: { ...mapping, [placeholder]: { original, type: "PERSON" } },
|
||||
entity_count: 1,
|
||||
spans: [
|
||||
{
|
||||
start: text.indexOf(original),
|
||||
end: text.indexOf(original) + original.length,
|
||||
original,
|
||||
placeholder,
|
||||
type: "PERSON",
|
||||
score: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
it("zerlegt einen fehlgeschlagenen Analyseblock und erhält Dateigrenzen und Zuordnungen", async () => {
|
||||
const [batch] = makeTextBatches([
|
||||
{ key: "a.md", text: "Anna" },
|
||||
{ key: "b.md", text: "Berta" },
|
||||
]);
|
||||
const calls: string[] = [];
|
||||
const analyzed = await analyzeProjectBatch(
|
||||
batch,
|
||||
{},
|
||||
["PERSON"],
|
||||
{},
|
||||
async (text, mapping) => {
|
||||
calls.push(text);
|
||||
if (text.includes("Anna") && text.includes("Berta"))
|
||||
throw new Error("Velum API request failed: 500 Internal Server Error");
|
||||
return response(text, mapping);
|
||||
},
|
||||
"Textdateien analysieren",
|
||||
);
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(Object.keys(analyzed.mapping)).toEqual(["PERSON_01", "PERSON_02"]);
|
||||
expect(
|
||||
analyzed.results.flatMap(({ batch: part, result }) => [
|
||||
...spansBySegment(part, result.spans).keys(),
|
||||
]),
|
||||
).toEqual(["a.md", "b.md"]);
|
||||
});
|
||||
|
||||
it("nennt nach der Eingrenzung die fehlerhafte Datei", async () => {
|
||||
const [batch] = makeTextBatches([
|
||||
{ key: "a.md", text: "Anna" },
|
||||
{ key: "b.md", text: "Berta" },
|
||||
]);
|
||||
expect(
|
||||
analyzeProjectBatch(
|
||||
batch,
|
||||
{},
|
||||
["PERSON"],
|
||||
{},
|
||||
async (text, mapping) => {
|
||||
if (text.includes("Berta"))
|
||||
throw new Error(
|
||||
"Velum API request failed: 500 Internal Server Error",
|
||||
);
|
||||
return response(text, mapping);
|
||||
},
|
||||
"Textdateien analysieren",
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"Textdateien analysieren: b.md: Velum API request failed: 500",
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user