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:
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -246,13 +247,125 @@ func (s *wikiPageService) GetIndex(ctx context.Context, kbID string) (*types.Wik
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// GetLog returns the log page for a knowledge base
|
||||
// wikiIndexContentPageTypes enumerates the page types that make up a wiki's
|
||||
// user-visible directory. System pages (index/log) are excluded; any
|
||||
// LLM-created type we do not recognize surfaces under a generic "other"
|
||||
// bucket.
|
||||
var wikiIndexContentPageTypes = []string{
|
||||
types.WikiPageTypeSummary,
|
||||
types.WikiPageTypeEntity,
|
||||
types.WikiPageTypeConcept,
|
||||
types.WikiPageTypeSynthesis,
|
||||
types.WikiPageTypeComparison,
|
||||
}
|
||||
|
||||
// GetIndexView builds the structured index response without ever
|
||||
// materializing a multi-MB directory markdown string. Intro is read from
|
||||
// the index wiki_page row (which now carries only intro text — see
|
||||
// rebuildIndexPage). Each requested page_type is paginated independently
|
||||
// with ListByTypeLight so reads stay O(page_size) rather than O(total
|
||||
// pages in the KB).
|
||||
//
|
||||
// `pageTypes` narrows which groups to include; empty = all content types.
|
||||
// `limit` is the per-group window size (defaults to 50, capped at 200).
|
||||
// `cursor` is an opaque offset string; currently we use the stringified
|
||||
// offset so clients can resume where they left off. Because different
|
||||
// page_types paginate independently, `cursor` applies uniformly to every
|
||||
// group — if the caller wants per-group cursors it should request one
|
||||
// type at a time via `pageTypes`. That simplifies the wire format and
|
||||
// matches the frontend's tabbed UX.
|
||||
func (s *wikiPageService) GetIndexView(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
pageTypes []string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (*types.WikiIndexResponse, error) {
|
||||
indexPage, err := s.GetIndex(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load index page: %w", err)
|
||||
}
|
||||
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
offset := 0
|
||||
if cursor != "" {
|
||||
v, parseErr := strconv.Atoi(cursor)
|
||||
if parseErr != nil || v < 0 {
|
||||
return nil, fmt.Errorf("invalid cursor %q", cursor)
|
||||
}
|
||||
offset = v
|
||||
}
|
||||
|
||||
// Default to every known content type when the caller passes no
|
||||
// filter. Any unknown request-time type is passed through verbatim so
|
||||
// future page types (declared in types/wiki_page.go) start showing
|
||||
// up in the index the moment the LLM starts creating them, without a
|
||||
// handler change.
|
||||
selected := pageTypes
|
||||
if len(selected) == 0 {
|
||||
selected = append([]string{}, wikiIndexContentPageTypes...)
|
||||
}
|
||||
|
||||
groups := make([]types.WikiIndexGroup, 0, len(selected))
|
||||
for _, pt := range selected {
|
||||
entries, total, listErr := s.repo.ListByTypeLight(ctx, kbID, pt, limit, offset)
|
||||
if listErr != nil {
|
||||
return nil, fmt.Errorf("list %s pages: %w", pt, listErr)
|
||||
}
|
||||
if entries == nil {
|
||||
entries = []types.WikiIndexEntry{}
|
||||
}
|
||||
next := ""
|
||||
// Only emit a cursor when a full page was returned AND more rows
|
||||
// remain past `offset + limit`. A short page or one that exactly
|
||||
// consumed the remainder should signal end-of-feed.
|
||||
if len(entries) == limit && int64(offset+len(entries)) < total {
|
||||
next = strconv.Itoa(offset + limit)
|
||||
}
|
||||
groups = append(groups, types.WikiIndexGroup{
|
||||
Type: pt,
|
||||
Total: total,
|
||||
Items: entries,
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
|
||||
// The intro used to be stored on indexPage.Summary while
|
||||
// indexPage.Content held intro + directory markdown. After the
|
||||
// directory was lifted out of wiki_pages the content column holds
|
||||
// only the intro. Fall back to Summary for KBs that haven't been
|
||||
// re-ingested since the change so the response is never blank.
|
||||
intro := indexPage.Content
|
||||
if strings.TrimSpace(intro) == "" {
|
||||
intro = indexPage.Summary
|
||||
}
|
||||
|
||||
return &types.WikiIndexResponse{
|
||||
Intro: intro,
|
||||
Version: indexPage.Version,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetLog returns the wiki_pages row for slug='log' if it exists.
|
||||
//
|
||||
// Log events are now stored in the dedicated `wiki_log_entries` table and
|
||||
// paginated via wikiLogEntryService — the per-KB log is no longer a single
|
||||
// TEXT column on a wiki_pages row (that model caused O(n^2) write
|
||||
// amplification as logs grew). This method is retained for callers that
|
||||
// still probe the legacy row (wiki_lint, knowledge delete, etc.), but it
|
||||
// no longer auto-creates the placeholder page on miss; a missing row is a
|
||||
// normal state and the helper returns `nil, nil`.
|
||||
func (s *wikiPageService) GetLog(ctx context.Context, kbID string) (*types.WikiPage, error) {
|
||||
page, err := s.repo.GetBySlug(ctx, kbID, "log")
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrWikiPageNotFound) {
|
||||
return s.createDefaultPage(ctx, kbID, "log", "Log", types.WikiPageTypeLog,
|
||||
"# Wiki Operation Log\n\nChronological record of wiki operations.\n")
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
@@ -619,6 +732,13 @@ func (s *wikiPageService) ListAllPages(ctx context.Context, kbID string) ([]*typ
|
||||
return s.repo.ListAll(ctx, kbID)
|
||||
}
|
||||
|
||||
// ListByType returns every wiki page of a given type for a KB. Exposed so
|
||||
// callers like intro regeneration can load only the page type they need
|
||||
// (summaries) instead of paying for the full ListAll scan.
|
||||
func (s *wikiPageService) ListByType(ctx context.Context, kbID string, pageType string) ([]*types.WikiPage, error) {
|
||||
return s.repo.ListByType(ctx, kbID, pageType)
|
||||
}
|
||||
|
||||
// ListPagesBySourceRef exposes the repository's source-ref lookup so higher
|
||||
// layers (delete flow, retract reconciliation) can re-query the current wiki
|
||||
// state without depending on a stale caller-captured slug list.
|
||||
@@ -821,79 +941,23 @@ func (s *wikiPageService) InjectCrossLinks(ctx context.Context, kbID string, aff
|
||||
}
|
||||
}
|
||||
|
||||
// RebuildIndexPage regenerates the index page directory.
|
||||
// RebuildIndexPage was historically called by agent write/rename tools to
|
||||
// refresh the index page's directory listing after a page mutation.
|
||||
//
|
||||
// The directory is no longer persisted in wiki_pages.content — it is
|
||||
// assembled on demand by GetIndexView from the lightweight ListByTypeLight
|
||||
// projection, so individual page writes don't need to redo O(N) string
|
||||
// concatenation and rewrite a multi-MB TEXT column anymore. Keeping the
|
||||
// method name lets existing agent tool call sites (wiki_write_page,
|
||||
// wiki_rename_page) compile unchanged; the body is now intentionally a
|
||||
// no-op.
|
||||
//
|
||||
// The intro that still lives on the index row is managed separately by
|
||||
// the ingest pipeline (see wikiIngestService.rebuildIndexPage) on batch
|
||||
// completion, which is where we actually have the LLM + change description
|
||||
// context needed to rewrite it.
|
||||
func (s *wikiPageService) RebuildIndexPage(ctx context.Context, kbID string) error {
|
||||
indexPage, err := s.GetIndex(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
allPages, err := s.ListAllPages(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
typeOrder := []string{
|
||||
types.WikiPageTypeSummary, types.WikiPageTypeEntity, types.WikiPageTypeConcept,
|
||||
types.WikiPageTypeSynthesis, types.WikiPageTypeComparison,
|
||||
}
|
||||
typeLabels := map[string]string{
|
||||
types.WikiPageTypeSummary: "Summary", types.WikiPageTypeEntity: "Entity",
|
||||
types.WikiPageTypeConcept: "Concept", types.WikiPageTypeSynthesis: "Synthesis",
|
||||
types.WikiPageTypeComparison: "Comparison",
|
||||
}
|
||||
|
||||
grouped := make(map[string][]*types.WikiPage)
|
||||
totalPages := 0
|
||||
for _, p := range allPages {
|
||||
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {
|
||||
continue
|
||||
}
|
||||
if p.Status == types.WikiPageStatusArchived {
|
||||
continue
|
||||
}
|
||||
grouped[p.PageType] = append(grouped[p.PageType], p)
|
||||
totalPages++
|
||||
}
|
||||
|
||||
var dir strings.Builder
|
||||
for _, pt := range typeOrder {
|
||||
pages := grouped[pt]
|
||||
if len(pages) == 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", typeLabels[pt], len(pages))
|
||||
for _, p := range pages {
|
||||
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, p.Summary)
|
||||
}
|
||||
}
|
||||
for pt, pages := range grouped {
|
||||
inOrder := false
|
||||
for _, o := range typeOrder {
|
||||
if o == pt {
|
||||
inOrder = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if inOrder || len(pages) == 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", pt, len(pages))
|
||||
for _, p := range pages {
|
||||
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, p.Summary)
|
||||
}
|
||||
}
|
||||
if totalPages == 0 {
|
||||
dir.WriteString("\n*No wiki pages yet. Upload documents to get started.*\n")
|
||||
}
|
||||
|
||||
intro := indexPage.Summary
|
||||
if intro == "" {
|
||||
intro = "# Wiki Index\n\nThis wiki contains knowledge extracted from uploaded documents.\n"
|
||||
indexPage.Summary = intro
|
||||
}
|
||||
|
||||
indexPage.Content = intro + "\n" + dir.String()
|
||||
_, err = s.UpdatePage(ctx, indexPage)
|
||||
return err
|
||||
_ = ctx
|
||||
_ = kbID
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user