perf(wiki): move ingest log to event table and index to on-demand API

Fixes O(n²) write amplification during wiki ingest on large KBs. Previously
every ingest/retract op re-wrote the single `slug='log'` row end-to-end and
every batch re-wrote the entire `slug='index'` directory markdown. On a 40k-
doc KB the log row grew to tens of MB and the index row to several MB, so
each batch triggered giant TOAST updates that dominated ingest wall time.

Log: new `wiki_log_entries` event table (`id DESC` indexed per KB) replaces
the single TEXT row. Batch ingest now collects entries and flushes them
once per batch via `AppendBatch`. Each entry stores `pages_affected` as
JSONB `[{slug,title}]` so the UI can render real titles; custom Scan falls
back to legacy `[]string` so older rows still deserialize.

Index: `wiki_pages[slug=index].content` keeps only the LLM-generated intro
(a few KB). The directory is now served by a structured paginated API
(`GetIndexView`) that reads `slug/title/summary` per type with cursor
pagination, so the agent and the frontend only pull the slice they need.
`RebuildIndexPage` degrades to a no-op; agent `wiki_read_page('index')`
synthesizes a small top-K overview and points callers at `wiki_search`.

Ingest resilience: LLM calls wrap with 3-attempt exponential backoff on
transient errors (5xx/408/429, transport resets/timeouts). Summary/extract
failures now bubble up so the batch's failed-op requeue path runs instead
of silently dropping the doc.

Frontend: sidebar Index/Log entries switch to dedicated views. Index view
streams intro → Summary → Entity → Concept → Synthesis → Comparison via
IntersectionObserver (with a nextTick re-check so small KBs still load
every section). Log view uses cursor pagination; pages_affected renders
titles with slug tooltip.

- new migration: migrations/versioned/000040_wiki_log_entries.{up,down}.sql
- tests: log repo pagination + legacy Scan, ListByTypeLight windowing,
  renderIndexOverviewForAgent output, isTransientLLMError classifier

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
wizardchen
2026-05-08 21:43:53 +08:00
committed by lyingbug
parent bf12868923
commit d0144f3586
25 changed files with 2353 additions and 272 deletions
@@ -0,0 +1,41 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// WikiLogEntryRepository persists per-KB wiki operation events. The table
// is append-only; updates are never issued. Reads paginate newest-first
// with a stable numeric cursor.
type WikiLogEntryRepository interface {
// AppendBatch inserts a batch of events in a single INSERT...VALUES
// statement. All entries in a batch must belong to the same KB in
// practice, but the repo does not enforce that — the caller owns the
// grouping.
AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error
// List returns up to `limit` entries in (knowledge_base_id, id DESC)
// order. `cursor` is the ID of the last entry from the previous page
// ("return entries strictly older than this"); empty string means
// "from the newest".
//
// The returned nextCursor is empty when no further rows remain; the
// caller can treat that as end-of-stream.
List(ctx context.Context, kbID string, cursor string, limit int) (entries []*types.WikiLogEntry, nextCursor string, err error)
// DeleteByKB removes every log entry belonging to the given KB. Used
// when a wiki KB is deleted so the log table does not accumulate
// orphans. Safe to call even if no rows exist.
DeleteByKB(ctx context.Context, kbID string) error
}
// WikiLogEntryService is the service layer over WikiLogEntryRepository.
// Kept intentionally thin — it mirrors the repo today because the events
// are pure bookkeeping and carry no business rules.
type WikiLogEntryService interface {
AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error
List(ctx context.Context, kbID string, cursor string, limit int) (*types.WikiLogEntryListResponse, error)
DeleteByKB(ctx context.Context, kbID string) error
}
+36 -1
View File
@@ -50,10 +50,33 @@ type WikiPageService interface {
// GetIndex returns the index page for a knowledge base.
// Creates a default one if it doesn't exist.
//
// The index row now carries only the LLM-generated intro in its content
// column — the heavy directory listing was moved out of wiki_pages.
// Callers that want a renderable directory should use GetIndexView,
// which assembles {intro, groups} structured output on demand.
GetIndex(ctx context.Context, kbID string) (*types.WikiPage, error)
// GetIndexView returns the structured index response — intro (from the
// index row) plus a paginated window of directory entries per requested
// page_type. `types` restricts which page types to include (empty =
// all), `limit` bounds the per-type window size, `cursor` is an opaque
// offset string resumed from a previous response.
//
// Keeping the directory as JSON rather than a multi-MB markdown blob
// means a 40k-page KB no longer pays O(N) transport + rendering cost
// on every index open. See /wiki/index handler + WikiBrowser.vue for
// the consumer.
GetIndexView(ctx context.Context, kbID string, pageTypes []string, limit int, cursor string) (*types.WikiIndexResponse, error)
// GetLog returns the log page for a knowledge base.
// Creates a default one if it doesn't exist.
//
// Wiki operation events now live in the dedicated wiki_log_entries
// table, so this method no longer auto-creates a placeholder row on
// miss and may legitimately return (nil, nil) for KBs that never had
// the legacy row written. Retained for back-compat with callers that
// still probe the row (lint, knowledge delete); new code should use
// WikiLogEntryService.List for the event feed instead.
GetLog(ctx context.Context, kbID string) (*types.WikiPage, error)
// GetGraph returns the link graph data for visualization. The caller
@@ -81,6 +104,12 @@ type WikiPageService interface {
// Used for index rebuild, graph generation, cross-link injection, etc.
ListAllPages(ctx context.Context, kbID string) ([]*types.WikiPage, error)
// ListByType returns every wiki page of the given type. Used by
// callers that need the full set for a specific type (e.g. intro
// regeneration needs summary pages). For directory rendering, use
// GetIndexView instead — it paginates via ListByTypeLight.
ListByType(ctx context.Context, kbID string, pageType string) ([]*types.WikiPage, error)
// ListPagesBySourceRef retrieves all wiki pages whose source_refs reference
// the given knowledge ID. Used by delete/ingest reconciliation paths that
// need to find pages touched by a specific document at read time (rather
@@ -136,6 +165,12 @@ type WikiPageRepository interface {
// ListByType retrieves all wiki pages of a given type within a knowledge base.
ListByType(ctx context.Context, kbID string, pageType string) ([]*types.WikiPage, error)
// ListByTypeLight returns a paginated window of lightweight entries
// (slug/title/summary only) for the given page_type plus the total
// non-archived count. Used by the structured index API so reads do not
// have to materialize TEXT content for every wiki_pages row.
ListByTypeLight(ctx context.Context, kbID string, pageType string, limit int, offset int) ([]types.WikiIndexEntry, int64, error)
// ListBySourceRef retrieves all wiki pages that reference a given source knowledge ID.
ListBySourceRef(ctx context.Context, kbID string, sourceKnowledgeID string) ([]*types.WikiPage, error)
+117
View File
@@ -0,0 +1,117 @@
package types
import (
"database/sql/driver"
"encoding/json"
"fmt"
"time"
)
// WikiLogPageRef identifies a wiki page that was affected by a log event,
// paired with the human-readable title at the time of the event. Title is
// captured at write time so the log feed stays readable even if the page
// is later renamed or deleted — the previously-stored title is the one
// the user remembers seeing in the event stream.
type WikiLogPageRef struct {
Slug string `json:"slug"`
Title string `json:"title,omitempty"`
}
// WikiLogPageRefs is a JSON-marshalled list of page references. The
// column is TEXT/JSONB depending on driver; the Value/Scan pair keeps
// GORM happy on both Postgres and the SQLite tests.
type WikiLogPageRefs []WikiLogPageRef
// Value implements the driver.Valuer interface.
func (r WikiLogPageRefs) Value() (driver.Value, error) {
if r == nil {
return []byte("[]"), nil
}
return json.Marshal(r)
}
// Scan implements the sql.Scanner interface. Also tolerates the legacy
// []string shape so we can roll forward without a data migration — any
// rows the ingest pipeline wrote before this commit surface as refs
// with a slug and an empty title, which the frontend renders identically.
func (r *WikiLogPageRefs) Scan(value interface{}) error {
if value == nil {
*r = nil
return nil
}
var raw []byte
switch v := value.(type) {
case []byte:
raw = v
case string:
raw = []byte(v)
default:
return fmt.Errorf("unsupported type for WikiLogPageRefs: %T", value)
}
// Try the new [{slug,title}] shape first.
var refs []WikiLogPageRef
if err := json.Unmarshal(raw, &refs); err == nil {
*r = refs
return nil
}
// Fall back to the legacy []string shape.
var slugs []string
if err := json.Unmarshal(raw, &slugs); err != nil {
return err
}
out := make([]WikiLogPageRef, 0, len(slugs))
for _, s := range slugs {
out = append(out, WikiLogPageRef{Slug: s})
}
*r = out
return nil
}
// WikiLogEntry is a single ingest/retract/edit event appended to the
// per-KB operation log. It replaces the legacy "single giant TEXT column
// on slug='log' wiki_pages row" model, which rewrote the whole column on
// every event and caused O(n^2) write amplification as the KB grew.
//
// Each event is one INSERT; reads paginate by (knowledge_base_id, id DESC).
type WikiLogEntry struct {
// Auto-increment identifier. Monotonic within a single database, so
// frontend pagination uses it as a stable cursor without needing to
// disambiguate identical created_at values.
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
// Tenant scope, mirrored from the enclosing knowledge base.
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Knowledge base this event belongs to.
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`
// Short operation tag: "ingest", "retract", etc. Matches the `action`
// argument historically passed to appendLogEntry.
Action string `json:"action" gorm:"type:varchar(32)"`
// Knowledge ID the event was about (may be empty for KB-level events).
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
// Document title at the time of the event. Stored verbatim rather than
// joined at read time so deleted knowledge still has a human-readable
// label in the log.
DocTitle string `json:"doc_title" gorm:"type:text"`
// One-line summary of the change, as it was when the event was logged.
Summary string `json:"summary" gorm:"type:text"`
// Wiki pages affected by this event. Each ref carries both slug (for
// navigation) and title (for display) so the log renders human-
// readable text without a post-hoc slug→title lookup that might fail
// for now-deleted pages.
PagesAffected WikiLogPageRefs `json:"pages_affected" gorm:"type:jsonb;default:'[]'"`
// Server-side timestamp (UTC).
CreatedAt time.Time `json:"created_at"`
}
// TableName specifies the database table name.
func (WikiLogEntry) TableName() string {
return "wiki_log_entries"
}
// WikiLogEntryListResponse is the paginated response for GET /wiki/log.
// NextCursor is the stringified ID of the oldest entry in `Entries`; pass
// it back as `cursor` to fetch the next page. Empty string means "no more".
type WikiLogEntryListResponse struct {
Entries []*WikiLogEntry `json:"entries"`
NextCursor string `json:"next_cursor,omitempty"`
}
+32
View File
@@ -292,3 +292,35 @@ type WikiPageIssue struct {
func (WikiPageIssue) TableName() string {
return "wiki_page_issues"
}
// WikiIndexEntry is a single row in the structured wiki index response.
// Only the columns needed to render a clickable directory entry are
// carried — the backend projects SELECT slug, title, summary so a 40k-
// page KB does not pay for TEXT content transport on every index open.
type WikiIndexEntry struct {
Slug string `json:"slug"`
Title string `json:"title"`
Summary string `json:"summary"`
}
// WikiIndexGroup bundles the entries for one page_type into a page-sized
// slice. `Total` is the full count across the KB for the type; `Items`
// holds the current paginated window starting at `NextOffset - len(Items)`.
// An empty NextCursor means the window is already at the end of the type.
type WikiIndexGroup struct {
Type string `json:"type"`
Total int64 `json:"total"`
Items []WikiIndexEntry `json:"items"`
NextCursor string `json:"next_cursor,omitempty"`
}
// WikiIndexResponse is what GET /wiki/index returns. The heavy directory
// markdown that used to sit in wiki_pages.content is gone — only the LLM-
// generated intro survives there. Everything else is assembled on demand
// from the index repo's light-column projection, keeping index reads
// O(page_size) regardless of KB size.
type WikiIndexResponse struct {
Intro string `json:"intro"`
Version int `json:"version"`
Groups []WikiIndexGroup `json:"groups"`
}