ingest-api: versioned noise rules and CRM-style fingerprint normalization

- Add NOISE_RULESET_VERSION 1.0.0 with CRM/WDMI parity (external resource,
  ResizeObserver, WDMI media prefix, stale-bundle and transient JS strings).
- Skip ingest for matched noise; never suppress when level maps to critical.
- FINGERPRINT_POLICY_VERSION 1: NFKC/whitespace-normalized first line plus
  project_slug|message|file|line basis (SHA-256) when client omits fingerprint.
- Response includes noise_filtered_count and policy version fields; OpenAPI
  documents stored vs skipped result shapes.

Paperclip-Issue: BIT-727
Paperclip-Run-Id: ae412312-f71a-4efd-93e0-ca7289c93362
Made-with: Cursor
This commit is contained in:
David Santos committed 2026-04-02 10:55:11 +00:00
1 parent 7b2be679cd
commit c4e0b03ed8
9 files changed
+491 -20

No files matched your search

+34 -9
View File
@@ -43,6 +43,30 @@ const _ingestBodySchema = {
},
} as const;
const _ingestResultStoredSchema = {
type: "object",
additionalProperties: false,
required: ["incident_id", "occurrence_id", "fingerprint"],
properties: {
incident_id: { type: "string" },
occurrence_id: { type: "string" },
fingerprint: { type: "string" },
},
} as const;
const _ingestResultSkippedSchema = {
type: "object",
additionalProperties: false,
required: ["skipped", "rule_id", "reason", "noise_ruleset_version", "fingerprint_policy_version"],
properties: {
skipped: { type: "boolean", enum: [true] },
rule_id: { type: "string" },
reason: { type: "string" },
noise_ruleset_version: { type: "string" },
fingerprint_policy_version: { type: "integer" },
},
} as const;
function _rateLimitKey(request: { headers: Record<string, unknown>; ip: string }): string {
const _auth = request.headers.authorization;
const _ak = request.headers["x-api-key"];
@@ -127,21 +151,22 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
200: {
type: "object",
properties: {
fingerprint_policy_version: { type: "integer" },
noise_ruleset_version: { type: "string" },
noise_filtered_count: { type: "integer" },
results: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
incident_id: { type: "string" },
occurrence_id: { type: "string" },
fingerprint: { type: "string" },
},
required: ["incident_id", "occurrence_id", "fingerprint"],
oneOf: [_ingestResultStoredSchema, _ingestResultSkippedSchema],
},
},
},
required: ["results"],
required: [
"fingerprint_policy_version",
"noise_ruleset_version",
"noise_filtered_count",
"results",
],
},
401: {
type: "object",
@@ -124,6 +124,42 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
expect(Number((checkB[0] as { c: number }).c)).toBe(1);
});
it("skips known browser noise without inserting rows", async () => {
const [before] = await _pool.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`,
[_projectIdA],
);
const _nBefore = Number((before[0] as { c: number }).c);
const _res = await _app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: { authorization: `Bearer ${_tokenA}` },
payload: {
events: [
{
schema_version: 1,
occurred_at: "2026-03-22T10:30:00.000Z",
level: "error",
message: "ResizeObserver loop completed with undelivered notifications.",
},
],
},
});
expect(_res.statusCode).toBe(200);
const _body = JSON.parse(_res.body) as {
noise_filtered_count: number;
results: Array<{ skipped?: boolean; rule_id?: string }>;
};
expect(_body.noise_filtered_count).toBe(1);
expect(_body.results[0]?.skipped).toBe(true);
expect(_body.results[0]?.rule_id).toBe("resize_observer_loop");
const [after] = await _pool.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`,
[_projectIdA],
);
expect(Number((after[0] as { c: number }).c)).toBe(_nBefore);
});
it("replays identical idempotent requests", async () => {
const _payload = {
events: [
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import {
computeFingerprintFromBasis,
extractLocationFromContext,
extractProjectStableKey,
normalizeMessageForFingerprint,
} from "./fingerprintPolicy.js";
describe("normalizeMessageForFingerprint", () => {
it("uses first line and collapses whitespace", () => {
expect(normalizeMessageForFingerprint("a b\nc")).toBe("a b");
});
});
describe("extractLocationFromContext", () => {
it("reads stack_info.filename", () => {
expect(
extractLocationFromContext({
stack_info: { filename: "/app/x.js", line_number: 12 },
}),
).toEqual({ filePath: "/app/x.js", lineNumber: 12 });
});
it("prefers file_path", () => {
expect(
extractLocationFromContext({
file_path: "/b.php",
line_number: 5,
}),
).toEqual({ filePath: "/b.php", lineNumber: 5 });
});
});
describe("extractProjectStableKey", () => {
it("prefers project_slug", () => {
expect(extractProjectStableKey({ project_slug: "wdmi-store", project_name: "X" })).toBe(
"wdmi-store",
);
});
});
describe("computeFingerprintFromBasis", () => {
it("is deterministic", () => {
const _a = computeFingerprintFromBasis({
projectStableKey: "p",
normalizedMessage: "m",
filePath: "/f",
lineNumber: 3,
});
const _b = computeFingerprintFromBasis({
projectStableKey: "p",
normalizedMessage: "m",
filePath: "/f",
lineNumber: 3,
});
expect(_a).toBe(_b);
expect(_a).toMatch(/^[a-f0-9]{64}$/);
});
});
+87
View File
@@ -0,0 +1,87 @@
import { sha256Hex } from "./hash.js";
/** Bumped when fingerprint basis algorithm changes (dedup / parity). */
export const FINGERPRINT_POLICY_VERSION = 1;
/**
* Normalize message text for stable dedup (CRM-style: trim, collapse whitespace, NFKC).
*/
export function normalizeMessageForFingerprint(message: string): string {
const _line = message.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
const _oneLine = _line.split(/\n/)[0] ?? _line;
try {
return _oneLine.normalize("NFKC").trim().replace(/\s+/g, " ");
} catch {
return _oneLine.trim().replace(/\s+/g, " ");
}
}
function _asTrimmedString(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}
/**
* Pull file + line from ingest `context` (CRM / WDMI ErrorCollector shapes).
*/
export function extractLocationFromContext(
context: Record<string, unknown> | null | undefined,
): { filePath: string; lineNumber: number } {
if (!context || typeof context !== "object") {
return { filePath: "", lineNumber: 0 };
}
const _directFile = _asTrimmedString(context.file_path) || _asTrimmedString(context.file);
if (_directFile !== "") {
const _ln = context.line_number ?? context.line ?? context.lineno;
return { filePath: _directFile, lineNumber: _parseLine(_ln) };
}
const _si = context.stack_info;
if (_si !== null && typeof _si === "object" && !Array.isArray(_si)) {
const _o = _si as Record<string, unknown>;
const _fn = _asTrimmedString(_o.filename) || _asTrimmedString(_o.file);
if (_fn !== "") {
const _ln = _o.line_number ?? _o.line ?? _o.lineno;
return { filePath: _fn, lineNumber: _parseLine(_ln) };
}
}
return { filePath: "", lineNumber: 0 };
}
function _parseLine(value: unknown): number {
if (typeof value === "number" && Number.isFinite(value)) {
return Math.trunc(value);
}
if (typeof value === "string" && value.trim() !== "") {
const _n = parseInt(value, 10);
return Number.isFinite(_n) ? _n : 0;
}
return 0;
}
/**
* Stable product key: `project_slug` (hub / Paperclip) or `project_name` fallback.
*/
export function extractProjectStableKey(context: Record<string, unknown> | null | undefined): string {
if (!context || typeof context !== "object") {
return "";
}
const _slug = _asTrimmedString(context.project_slug);
if (_slug !== "") {
return _slug;
}
return _asTrimmedString(context.project_name) || _asTrimmedString(context.project);
}
/**
* Hub fingerprint when the client does not send one: CRM capture parity
* (`project|message|file|line`) then SHA-256 hex (64 chars). `project_id` is
* already scoped per row — this key matches cross-reporter CRM strings.
*/
export function computeFingerprintFromBasis(input: {
projectStableKey: string;
normalizedMessage: string;
filePath: string;
lineNumber: number;
}): string {
const _basis = `${input.projectStableKey}|${input.normalizedMessage}|${input.filePath}|${input.lineNumber}`;
return sha256Hex(_basis);
}
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { evaluateNoise, NOISE_RULESET_VERSION } from "./noisePolicy.js";
describe("evaluateNoise", () => {
it("matches ResizeObserver browser noise", () => {
const _r = evaluateNoise({
level: "error",
message: "ResizeObserver loop completed with undelivered notifications.",
filePathHint: "",
});
expect(_r).toEqual({
matched: true,
ruleId: "resize_observer_loop",
reason: "filtered_browser_noise",
});
});
it("does not suppress when level maps to critical", () => {
const _r = evaluateNoise({
level: "fatal",
message: "ResizeObserver loop completed with undelivered notifications.",
filePathHint: "",
});
expect(_r).toEqual({ matched: false });
});
it("matches CRM external resource + cloudflare filename", () => {
const _r = evaluateNoise({
level: "error",
message: "Resource failed to load",
filePathHint: "https://cdn.cloudflare.com/beacon.min.js",
});
expect(_r.matched).toBe(true);
if (_r.matched) {
expect(_r.ruleId).toBe("external_resource_cloudflare_beacon");
}
});
it("reads url from browser_info for cloudflare check", () => {
const _r = evaluateNoise({
level: "error",
message: "Resource failed to load",
filePathHint: "",
context: {
browser_info: { url: "https://static.cloudflare.com/x.js" },
},
});
expect(_r.matched).toBe(true);
});
it("exports a semver-ish ruleset version", () => {
expect(NOISE_RULESET_VERSION).toMatch(/^\d+\.\d+\.\d+$/);
});
});
+150
View File
@@ -0,0 +1,150 @@
import { normalizeLevelToSeverity } from "./normalize.js";
/**
* Versioned ruleset id (document in release notes when rules change).
*/
export const NOISE_RULESET_VERSION = "1.0.0";
export type NoiseEvaluation =
| { matched: false }
| { matched: true; ruleId: string; reason: string };
type NoiseRule = {
id: string;
reason: string;
match: (input: {
message: string;
messageLower: string;
fileHint: string;
fileHintLower: string;
urlHints: string[];
}) => boolean;
};
function _collectUrlHints(context: Record<string, unknown> | undefined): string[] {
const _out: string[] = [];
if (!context || typeof context !== "object") {
return _out;
}
const _push = (s: unknown) => {
if (typeof s === "string" && s.trim() !== "") {
_out.push(s);
}
};
_push(context.url);
const _bi = context.browser_info;
if (_bi && typeof _bi === "object" && !Array.isArray(_bi)) {
_push(((_bi as Record<string, unknown>).url as string) ?? "");
}
const _pi = context.page_info;
if (_pi && typeof _pi === "object" && !Array.isArray(_pi)) {
_push(((_pi as Record<string, unknown>).page_url as string) ?? "");
}
return _out;
}
/** CRM ErrorMonitoringController::isNoiseExternalResource */
function _matchExternalResourceCloudflareBeacon(input: {
message: string;
messageLower: string;
fileHint: string;
fileHintLower: string;
urlHints: string[];
}): boolean {
if (!input.messageLower.includes("resource failed to load")) {
return false;
}
const _candidates = [input.fileHintLower, ...input.urlHints.map((u) => u.toLowerCase())].filter(
(s) => s.length > 0,
);
for (const _u of _candidates) {
if (_u.includes("cloudflare") || _u.includes("beacon")) {
return true;
}
}
return false;
}
const _RULES: NoiseRule[] = [
{
id: "external_resource_cloudflare_beacon",
reason: "filtered_external_resource_noise",
match: (input) => _matchExternalResourceCloudflareBeacon(input),
},
{
id: "resize_observer_loop",
reason: "filtered_browser_noise",
match: (i) =>
i.message.includes("ResizeObserver loop completed with undelivered notifications"),
},
{
id: "wdmi_media_bitreport_load",
reason: "filtered_media_404_noise",
match: (i) =>
i.message.startsWith("Resource failed to load: https://wdmi-media.bitreport.pt/media/"),
},
{
id: "transient_offset_null",
reason: "filtered_transient_frontend_noise",
match: (i) =>
i.message.includes("Uncaught TypeError: Cannot read properties of null (reading 'offset')"),
},
{
id: "transient_after_undefined",
reason: "filtered_transient_frontend_noise",
match: (i) =>
i.message.includes(
"Uncaught TypeError: Cannot read properties of undefined (reading 'after')",
),
},
{
id: "stale_bundle_switch_selection_tab",
reason: "filtered_stale_frontend_bundle_noise",
match: (i) =>
i.message.includes("Uncaught ReferenceError: switchSelectionEditorTab is not defined"),
},
{
id: "stale_bundle_description_editor_ready",
reason: "filtered_stale_frontend_bundle_noise",
match: (i) =>
i.message.includes("Uncaught ReferenceError: descriptionEditorReady is not defined"),
},
{
id: "transient_parser_promise",
reason: "filtered_transient_frontend_noise",
match: (i) => i.message.includes("Unhandled Promise Rejection: Error: parser Error"),
},
];
/**
* Conservative: never classify fatal/critical ingest levels as noise (avoid hiding real outages).
*/
export function evaluateNoise(input: {
level: string;
message: string;
context?: Record<string, unknown>;
filePathHint: string;
}): NoiseEvaluation {
const _sev = normalizeLevelToSeverity(input.level);
if (_sev === "critical") {
return { matched: false };
}
const _msg = input.message;
const _msgLower = _msg.toLowerCase();
const _file = input.filePathHint;
const _fileLower = _file.toLowerCase();
const _urlHints = _collectUrlHints(input.context);
const _env = {
message: _msg,
messageLower: _msgLower,
fileHint: _file,
fileHintLower: _fileLower,
urlHints: _urlHints,
};
for (const _r of _RULES) {
if (_r.match(_env)) {
return { matched: true, ruleId: _r.id, reason: _r.reason };
}
}
return { matched: false };
}
+12 -4
View File
@@ -26,11 +26,19 @@ describe("computeFingerprint", () => {
).toBe("my-fp");
});
it("hashes when fingerprint missing", () => {
const _a = computeFingerprint({ message: "same" });
const _b = computeFingerprint({ message: "same" });
it("hashes when fingerprint missing (CRM-style basis)", () => {
const _ctx = { project_slug: "acme", file_path: "/src/a.php", line_number: 9 };
const _a = computeFingerprint({ message: "same", context: _ctx });
const _b = computeFingerprint({ message: "same", context: _ctx });
expect(_a).toBe(_b);
expect(_a.length).toBeLessThanOrEqual(128);
expect(_a).toMatch(/^[a-f0-9]{64}$/);
});
it("collapses whitespace in message for fingerprint", () => {
const _ctx = { file_path: "x", line_number: 0 };
expect(computeFingerprint({ message: "a b", context: _ctx })).toBe(
computeFingerprint({ message: "a b", context: _ctx }),
);
});
});
+17 -3
View File
@@ -1,4 +1,9 @@
import { sha256Hex } from "./hash.js";
import {
computeFingerprintFromBasis,
extractLocationFromContext,
extractProjectStableKey,
normalizeMessageForFingerprint,
} from "./fingerprintPolicy.js";
export function normalizeLevelToSeverity(level: string): string {
const _l = level.trim().toLowerCase();
@@ -24,6 +29,7 @@ export function computeFingerprint(input: {
clientFingerprint?: string;
message: string;
stacktrace?: string;
context?: Record<string, unknown> | null;
}): string {
if (typeof input.clientFingerprint === "string") {
const _fp = input.clientFingerprint.trim().slice(0, 128);
@@ -31,8 +37,16 @@ export function computeFingerprint(input: {
return _fp;
}
}
const _basis = `${input.message}\n${input.stacktrace ?? ""}`;
return sha256Hex(_basis).slice(0, 128);
const _ctx = input.context ?? undefined;
const _loc = extractLocationFromContext(_ctx);
const _proj = extractProjectStableKey(_ctx);
const _normMsg = normalizeMessageForFingerprint(input.message);
return computeFingerprintFromBasis({
projectStableKey: _proj,
normalizedMessage: _normMsg,
filePath: _loc.filePath,
lineNumber: _loc.lineNumber,
});
}
export function incidentTitleFromMessage(message: string): string {
+42 -4
View File
@@ -1,5 +1,9 @@
import type { Pool, PoolConnection } from "mysql2/promise";
import type { ResultSetHeader, RowDataPacket } from "mysql2";
import {
extractLocationFromContext,
FINGERPRINT_POLICY_VERSION,
} from "../lib/fingerprintPolicy.js";
import { stableJsonHash } from "../lib/hash.js";
import {
computeFingerprint,
@@ -7,6 +11,7 @@ import {
normalizeLevelToSeverity,
parseOccurredAt,
} from "../lib/normalize.js";
import { evaluateNoise, NOISE_RULESET_VERSION } from "../lib/noisePolicy.js";
export type IngestEventInput = {
schema_version: number;
@@ -18,12 +23,22 @@ export type IngestEventInput = {
context?: Record<string, unknown>;
};
export type IngestResultItem = {
export type IngestStoredResult = {
incident_id: string;
occurrence_id: string;
fingerprint: string;
};
export type IngestSkippedResult = {
skipped: true;
rule_id: string;
reason: string;
noise_ruleset_version: string;
fingerprint_policy_version: number;
};
export type IngestResultItem = IngestStoredResult | IngestSkippedResult;
function _parseStoredJson(raw: unknown): unknown {
if (raw === null || raw === undefined) {
return raw;
@@ -92,10 +107,17 @@ export async function processIngestBatch(input: {
_results.push(_item);
}
const _responseBody = { results: _results };
const _noiseFiltered = _results.filter((r) => "skipped" in r && r.skipped === true).length;
const _responseBody = {
fingerprint_policy_version: FINGERPRINT_POLICY_VERSION,
noise_ruleset_version: NOISE_RULESET_VERSION,
noise_filtered_count: _noiseFiltered,
results: _results,
};
if (input.idempotencyKey !== null) {
const _firstIncidentId = _results[0]?.incident_id;
const _firstStored = _results.find((r): r is IngestStoredResult => !("skipped" in r));
const _firstIncidentId = _firstStored?.incident_id;
if (typeof _firstIncidentId === "string") {
await _client.execute(
`INSERT INTO er_ingest_idempotency (
@@ -140,14 +162,30 @@ async function _ingestOneEvent(
const _levelRaw = _ev.level.trim().slice(0, 32);
const _severity = normalizeLevelToSeverity(_ev.level);
const _message = _ev.message.trim();
const _context = _ev.context && typeof _ev.context === "object" ? _ev.context : null;
const _noise = evaluateNoise({
level: _ev.level,
message: _message,
context: _context ?? undefined,
filePathHint: extractLocationFromContext(_context).filePath,
});
if (_noise.matched) {
return {
skipped: true,
rule_id: _noise.ruleId,
reason: _noise.reason,
noise_ruleset_version: NOISE_RULESET_VERSION,
fingerprint_policy_version: FINGERPRINT_POLICY_VERSION,
};
}
const _fingerprint = computeFingerprint({
clientFingerprint: _ev.fingerprint,
message: _message,
stacktrace: _ev.stacktrace,
context: _context,
});
const _title = incidentTitleFromMessage(_message);
const _stack = typeof _ev.stacktrace === "string" ? _ev.stacktrace : null;
const _context = _ev.context && typeof _ev.context === "object" ? _ev.context : null;
await client.execute(
`INSERT INTO er_incidents (