fix(knowledge): address span-tree review feedback

- Collapse migrations 000052 (flat stages) + 000053 (span tree) into a
  single 000052_knowledge_processing_spans migration; the flat stages
  table never escaped this branch and the create-then-drop sequence had
  no value.
- BeginStage: detect an existing (kid, attempt, stage) row before
  inserting and reuse its span_id with reset state, so re-entry from
  asynq retries or adjacent code paths no longer produces duplicate
  timeline segments.
- FailSpan: when sibling-stage cascade flips a dependent stage to
  cancelled, also CancelDescendants on its subtree so already-running
  subspans (embedding.batch[i] etc.) cannot remain as orphan running
  rows under a cancelled parent.
- Dead-letter callback: replace two sequential UpdateKnowledgeColumn
  writes with a single UpdateKnowledgeColumns map update so we cannot
  end up with parse_status=failed and stale error_message (or vice
  versa) when one of the two writes fails.
- touchKnowledgeHeartbeat: skip subspan/generation transitions; only
  root and stage transitions poke knowledge.updated_at. Spans-table
  MAX(updated_at) already covers subspan progress for housekeeping, so
  this avoids 2*N+ UPDATE bursts on the same hot row when a multimodal
  stage fans out to many images.
- Add regression tests for the BeginStage idempotency contract and the
  cascade-into-subspans behaviour.
This commit is contained in:
wizardchen
2026-05-27 15:31:32 +08:00
committed by lyingbug
parent 414749681f
commit c82b098f44
10 changed files with 233 additions and 161 deletions
@@ -0,0 +1,9 @@
-- Migration: 000052_knowledge_processing_spans (rollback)
DO $$ BEGIN RAISE NOTICE '[Migration 000052 rollback] Dropping table: knowledge_processing_spans'; END $$;
DROP INDEX IF EXISTS idx_kpspan_parent;
DROP INDEX IF EXISTS idx_kpspan_status_started;
DROP INDEX IF EXISTS idx_kpspan_knowledge_attempt;
DROP TABLE IF EXISTS knowledge_processing_spans;
DO $$ BEGIN RAISE NOTICE '[Migration 000052 rollback] complete'; END $$;
@@ -1,50 +1,35 @@
-- Migration: 000053_knowledge_processing_spans
-- Replace the flat 5-stage tracking from migration 000052 with a tree-shaped
-- span model inspired by Langfuse traces.
-- Migration: 000052_knowledge_processing_spans
-- Per-(knowledge, attempt) span tree for the document parsing pipeline,
-- inspired by Langfuse's trace / span / generation hierarchy.
--
-- Why redesign?
-- Background: knowledge.parse_status is a 4-state field (pending /
-- processing / completed / failed). When users hit "stuck in processing",
-- they have no way to tell which stage is actually running — DocReader,
-- chunking, embedding, multimodal OCR/VLM, or the final post-process
-- handoff. Operators face the same problem.
--
-- The flat (knowledge_id, stage) model from 000052 had four shortcomings the
-- "stuck parsing" UX requires us to solve:
-- This table persists per-stage progress (and finer-grained subspans) so:
-- 1. The frontend can render a five-segment timeline showing where
-- each document is in the pipeline, with collapsible per-image /
-- per-batch subspans underneath.
-- 2. Failures carry a stable error_code (DOCREADER_TIMEOUT,
-- EMBEDDING_RATE_LIMIT, ...) the UI can map to localized
-- remediation text.
-- 3. Reparse history is preserved across attempts — operators can
-- navigate ?attempt=N to post-mortem "why did it fail twice?".
-- 4. Cascade-cancel rules use the parent_span_id tree to flip
-- dependent subspans/stages to "cancelled" when an upstream
-- span fails, so the UI shows a clear blast radius instead of
-- orphan spinners.
--
-- 1. Reparse semantics — a re-trigger of parsing on the same knowledge
-- reset the existing rows, erasing the previous attempt's history.
-- Operators investigating "why did it fail twice?" had no record of
-- attempt 1 once attempt 2 began.
--
-- 2. No DAG — Embedding and Multimodal both depend on Chunking but are
-- independent of each other. The flat model couldn't represent that,
-- so a Chunking failure couldn't auto-cascade "cancelled" to its
-- downstream stages and the UI had to guess.
--
-- 3. No subspans — a Multimodal stage produces N parallel image tasks;
-- Embedding produces M batches; PostProcess fans out into Summary /
-- Question / Wiki / Graph. Those finer-grained units have their own
-- success / failure / duration that operators want to see (and that
-- Langfuse generations already capture for the LLM-call subset).
--
-- 4. No input/output — duration alone hides the WHY of a slow run. With
-- input ({pages:48, images:5}) and output ({tokens:5840, dim:1024})
-- JSON, the timeline answers "how big was the work" without a log
-- dive.
--
-- The new schema mirrors Langfuse's trace/span/generation hierarchy:
-- Schema mirrors Langfuse's vocabulary:
-- * one ROOT span per (knowledge_id, attempt) acting as the trace
-- * STAGE spans (docreader/chunking/embedding/multimodal/postprocess)
-- are children of root
-- * SUBSPANs (multimodal.image[i], embedding.batch[i], postprocess.spawn.X)
-- hang off their stage. The kind="generation" subset corresponds 1:1 to
-- a Langfuse generation; metadata.langfuse_trace_id stitches them.
--
-- We keep the OLD 000052 table untouched on rollback so a `migrate down`
-- doesn't lose either schema. The forward path drops it because no UI
-- callers use it (the API was only added in the same branch and is being
-- replaced as part of this migration).
DO $$ BEGIN RAISE NOTICE '[Migration 000053] Replacing knowledge_processing_stages with knowledge_processing_spans'; END $$;
DROP INDEX IF EXISTS idx_kps_status_started;
DROP INDEX IF EXISTS idx_kps_knowledge;
DROP TABLE IF EXISTS knowledge_processing_stages;
DO $$ BEGIN RAISE NOTICE '[Migration 000052] Creating table: knowledge_processing_spans'; END $$;
CREATE TABLE IF NOT EXISTS knowledge_processing_spans (
id BIGSERIAL PRIMARY KEY,
@@ -76,7 +61,7 @@ CREATE INDEX IF NOT EXISTS idx_kpspan_knowledge_attempt
ON knowledge_processing_spans (knowledge_id, attempt);
-- Operator query: "find spans stuck in running too long". Used by ad-hoc
-- diagnostics and a future housekeeping sweep.
-- diagnostics and the housekeeping sweep.
CREATE INDEX IF NOT EXISTS idx_kpspan_status_started
ON knowledge_processing_spans (status, started_at);
@@ -87,4 +72,4 @@ CREATE INDEX IF NOT EXISTS idx_kpspan_parent
ON knowledge_processing_spans (parent_span_id)
WHERE parent_span_id IS NOT NULL;
DO $$ BEGIN RAISE NOTICE '[Migration 000053] knowledge_processing_spans table ready'; END $$;
DO $$ BEGIN RAISE NOTICE '[Migration 000052] knowledge_processing_spans table ready'; END $$;
@@ -1,8 +0,0 @@
-- Migration: 000052_knowledge_processing_stages (rollback)
DO $$ BEGIN RAISE NOTICE '[Migration 000052 rollback] Dropping table: knowledge_processing_stages'; END $$;
DROP INDEX IF EXISTS idx_kps_status_started;
DROP INDEX IF EXISTS idx_kps_knowledge;
DROP TABLE IF EXISTS knowledge_processing_stages;
DO $$ BEGIN RAISE NOTICE '[Migration 000052 rollback] complete'; END $$;
@@ -1,61 +0,0 @@
-- Migration: 000052_knowledge_processing_stages
-- Per-knowledge stage progress for the document parsing pipeline.
--
-- Background: knowledge.parse_status is a 4-state field (pending /
-- processing / completed / failed). When users hit "stuck in processing",
-- they have no way to tell which stage is actually running — DocReader,
-- chunking, embedding, multimodal OCR/VLM, or the final post-process
-- handoff. Operators face the same problem: a 500MB PDF stuck in
-- "processing" for 90 minutes could be legitimate OCR work or a frozen
-- docreader call, and the only signal is the absence of progress.
--
-- This table persists per-stage progress so:
-- 1. The frontend can render a five-segment timeline showing where
-- each document is in the pipeline (PR③ work).
-- 2. Failures carry a stable error_code (DOCREADER_TIMEOUT,
-- EMBEDDING_RATE_LIMIT, ...) the UI can map to localized
-- remediation text.
-- 3. Operators can SQL-query "all rows stuck on stage=embedding for
-- >30 min" without log-scraping.
--
-- Schema decisions:
-- - One row per (knowledge_id, stage). Retry attempts BUMP attempt
-- counter and reset status; we don't keep historical attempt rows
-- because the timeline UI only needs the latest state per stage.
-- - error_message holds the user-facing summary (≤1KB);
-- error_detail is the full stack/payload (≤8KB) gated behind
-- admin views in the UI.
-- - Sweeps that recover stuck knowledge will leave these rows
-- intact so operators can post-mortem the failure.
DO $$ BEGIN RAISE NOTICE '[Migration 000052] Creating table: knowledge_processing_stages'; END $$;
CREATE TABLE IF NOT EXISTS knowledge_processing_stages (
id BIGSERIAL PRIMARY KEY,
knowledge_id VARCHAR(64) NOT NULL,
stage VARCHAR(32) NOT NULL,
status VARCHAR(16) NOT NULL,
started_at TIMESTAMP WITH TIME ZONE,
finished_at TIMESTAMP WITH TIME ZONE,
duration_ms BIGINT,
error_code VARCHAR(64),
error_message TEXT,
error_detail TEXT,
attempt INT NOT NULL DEFAULT 1,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uq_kps_knowledge_stage UNIQUE (knowledge_id, stage)
);
-- Primary read path: "give me every stage row for this knowledge_id".
-- The unique constraint already covers point lookups by (knowledge_id,
-- stage); this index lets us fetch all 5 rows for a knowledge with one
-- index range scan, which is the API surface the frontend timeline calls.
CREATE INDEX IF NOT EXISTS idx_kps_knowledge
ON knowledge_processing_stages (knowledge_id);
-- Operator query: "find stages stuck in running too long". Used by the
-- housekeeping cron in a future iteration and by ad-hoc SQL diagnostics.
CREATE INDEX IF NOT EXISTS idx_kps_status_started
ON knowledge_processing_stages (status, started_at);
DO $$ BEGIN RAISE NOTICE '[Migration 000052] knowledge_processing_stages table ready'; END $$;
@@ -1,33 +0,0 @@
-- Migration: 000053_knowledge_processing_spans (rollback)
-- Restores the 000052 flat-stage table so the system is operational on a
-- back-rev. We do NOT migrate data back — the spans table carries strict
-- supersets of the stages table's information, so a forward-and-back round
-- trip silently drops the new tree shape (acceptable; rollback is a rare
-- emergency lever).
DO $$ BEGIN RAISE NOTICE '[Migration 000053 rollback] Dropping spans, restoring stages table'; END $$;
DROP INDEX IF EXISTS idx_kpspan_parent;
DROP INDEX IF EXISTS idx_kpspan_status_started;
DROP INDEX IF EXISTS idx_kpspan_knowledge_attempt;
DROP TABLE IF EXISTS knowledge_processing_spans;
CREATE TABLE IF NOT EXISTS knowledge_processing_stages (
id BIGSERIAL PRIMARY KEY,
knowledge_id VARCHAR(64) NOT NULL,
stage VARCHAR(32) NOT NULL,
status VARCHAR(16) NOT NULL,
started_at TIMESTAMP WITH TIME ZONE,
finished_at TIMESTAMP WITH TIME ZONE,
duration_ms BIGINT,
error_code VARCHAR(64),
error_message TEXT,
error_detail TEXT,
attempt INT NOT NULL DEFAULT 1,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uq_kps_knowledge_stage UNIQUE (knowledge_id, stage)
);
CREATE INDEX IF NOT EXISTS idx_kps_knowledge ON knowledge_processing_stages (knowledge_id);
CREATE INDEX IF NOT EXISTS idx_kps_status_started ON knowledge_processing_stages (status, started_at);
DO $$ BEGIN RAISE NOTICE '[Migration 000053 rollback] complete'; END $$;