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:
@@ -0,0 +1,92 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// wikiLogEntryRepository implements interfaces.WikiLogEntryRepository.
|
||||
type wikiLogEntryRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewWikiLogEntryRepository constructs a GORM-backed WikiLogEntryRepository.
|
||||
func NewWikiLogEntryRepository(db *gorm.DB) interfaces.WikiLogEntryRepository {
|
||||
return &wikiLogEntryRepository{db: db}
|
||||
}
|
||||
|
||||
// AppendBatch inserts every entry in one statement. Empty batches are a
|
||||
// no-op so callers can invoke unconditionally at the end of a wiki ingest
|
||||
// batch without guarding against the "no events this round" case.
|
||||
func (r *wikiLogEntryRepository) AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error {
|
||||
if len(entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).Create(&entries).Error
|
||||
}
|
||||
|
||||
// List returns up to `limit` entries strictly older than `cursor`, newest
|
||||
// first. `cursor` is the stringified ID of the oldest entry from the
|
||||
// previous page; an empty string starts from the newest. Callers get back
|
||||
// a nextCursor string to pass on the next request — empty means no more.
|
||||
//
|
||||
// `limit` is clamped to [1, 200]. Values outside that range are coerced
|
||||
// silently to keep the handler simple.
|
||||
func (r *wikiLogEntryRepository) List(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
cursor string,
|
||||
limit int,
|
||||
) ([]*types.WikiLogEntry, string, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
|
||||
q := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Order("id DESC").
|
||||
Limit(limit)
|
||||
|
||||
if cursor != "" {
|
||||
cursorID, err := strconv.ParseUint(cursor, 10, 64)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("invalid cursor %q: %w", cursor, err)
|
||||
}
|
||||
q = q.Where("id < ?", cursorID)
|
||||
}
|
||||
|
||||
var entries []*types.WikiLogEntry
|
||||
if err := q.Find(&entries).Error; err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
nextCursor := ""
|
||||
// Only emit a cursor when we actually filled the page — a short page
|
||||
// is guaranteed to be the tail, so returning a cursor would just cause
|
||||
// the frontend to fire a final empty request.
|
||||
if len(entries) == limit {
|
||||
nextCursor = strconv.FormatUint(entries[len(entries)-1].ID, 10)
|
||||
}
|
||||
return entries, nextCursor, nil
|
||||
}
|
||||
|
||||
// DeleteByKB drops every log entry for a KB. No "affected rows" signal is
|
||||
// surfaced — missing rows are a legitimate state (e.g., a KB that was
|
||||
// created before wiki_log_entries existed) and not a failure condition.
|
||||
func (r *wikiLogEntryRepository) DeleteByKB(ctx context.Context, kbID string) error {
|
||||
if kbID == "" {
|
||||
return errors.New("wiki log entries: empty kb id")
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Delete(&types.WikiLogEntry{}).Error
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// wikiLogEntriesTestDDL mirrors migrations/versioned/000040_wiki_log_entries.up.sql
|
||||
// but uses SQLite-compatible types so we can exercise the repo layer without
|
||||
// spinning up Postgres. INTEGER PRIMARY KEY AUTOINCREMENT gives us the same
|
||||
// monotonically-increasing ID semantics the production schema relies on for
|
||||
// cursor pagination.
|
||||
const wikiLogEntriesTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS wiki_log_entries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
knowledge_base_id VARCHAR(36) NOT NULL,
|
||||
action VARCHAR(32) NOT NULL,
|
||||
knowledge_id VARCHAR(36) NOT NULL DEFAULT '',
|
||||
doc_title TEXT NOT NULL DEFAULT '',
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
pages_affected TEXT NOT NULL DEFAULT '[]',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`
|
||||
|
||||
func setupWikiLogTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(wikiLogEntriesTestDDL).Error)
|
||||
return db
|
||||
}
|
||||
|
||||
func makeLogEntry(kbID, action, knowledgeID, title string, pages ...string) *types.WikiLogEntry {
|
||||
refs := make(types.WikiLogPageRefs, 0, len(pages))
|
||||
for _, slug := range pages {
|
||||
// Tests only care about round-tripping; title is derived from
|
||||
// the slug so assertions don't have to spell out both fields.
|
||||
refs = append(refs, types.WikiLogPageRef{Slug: slug, Title: "title-of-" + slug})
|
||||
}
|
||||
return &types.WikiLogEntry{
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: kbID,
|
||||
Action: action,
|
||||
KnowledgeID: knowledgeID,
|
||||
DocTitle: title,
|
||||
Summary: "summary for " + title,
|
||||
PagesAffected: refs,
|
||||
}
|
||||
}
|
||||
|
||||
// TestWikiLogEntryRepository_AppendBatch_WritesAllRows verifies a batch
|
||||
// insert persists every entry with a monotonic ID and respects the caller-
|
||||
// provided column values.
|
||||
func TestWikiLogEntryRepository_AppendBatch_WritesAllRows(t *testing.T) {
|
||||
db := setupWikiLogTestDB(t)
|
||||
repo := NewWikiLogEntryRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
entries := []*types.WikiLogEntry{
|
||||
makeLogEntry("kb-a", "ingest", "k1", "Doc 1", "entity/a", "summary/k1"),
|
||||
makeLogEntry("kb-a", "ingest", "k2", "Doc 2"),
|
||||
makeLogEntry("kb-a", "retract", "k3", "Doc 3", "concept/c"),
|
||||
}
|
||||
|
||||
require.NoError(t, repo.AppendBatch(ctx, entries))
|
||||
|
||||
// Every row should have a non-zero ID assigned by the DB, and IDs
|
||||
// should increase in insertion order so the cursor pagination logic
|
||||
// can rely on them.
|
||||
for i := range entries {
|
||||
assert.NotZero(t, entries[i].ID, "row %d should have a DB-assigned ID", i)
|
||||
if i > 0 {
|
||||
assert.Greater(t, entries[i].ID, entries[i-1].ID,
|
||||
"AppendBatch should preserve insertion order")
|
||||
}
|
||||
}
|
||||
|
||||
// Round-trip sanity: select back and confirm payload was preserved.
|
||||
var got []types.WikiLogEntry
|
||||
require.NoError(t, db.Order("id ASC").Find(&got).Error)
|
||||
require.Len(t, got, len(entries))
|
||||
assert.Equal(t, "ingest", got[0].Action)
|
||||
assert.Equal(t, "Doc 1", got[0].DocTitle)
|
||||
assert.Equal(t, types.WikiLogPageRefs{
|
||||
{Slug: "entity/a", Title: "title-of-entity/a"},
|
||||
{Slug: "summary/k1", Title: "title-of-summary/k1"},
|
||||
}, got[0].PagesAffected)
|
||||
assert.Equal(t, "retract", got[2].Action)
|
||||
}
|
||||
|
||||
// TestWikiLogEntryRepository_AppendBatch_Empty asserts an empty batch is a
|
||||
// cheap no-op — callers at the end of a wiki ingest pass can invoke it
|
||||
// unconditionally without a DB round trip.
|
||||
func TestWikiLogEntryRepository_AppendBatch_Empty(t *testing.T) {
|
||||
db := setupWikiLogTestDB(t)
|
||||
repo := NewWikiLogEntryRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.AppendBatch(ctx, nil))
|
||||
require.NoError(t, repo.AppendBatch(ctx, []*types.WikiLogEntry{}))
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&types.WikiLogEntry{}).Count(&count).Error)
|
||||
assert.Equal(t, int64(0), count)
|
||||
}
|
||||
|
||||
// TestWikiLogEntryRepository_List_CursorPagination walks the feed with a
|
||||
// limit smaller than the population size and confirms:
|
||||
// - newest entries surface first (id DESC order),
|
||||
// - passing next_cursor returns the next batch strictly older than it,
|
||||
// - end-of-feed is signalled by an empty cursor.
|
||||
func TestWikiLogEntryRepository_List_CursorPagination(t *testing.T) {
|
||||
db := setupWikiLogTestDB(t)
|
||||
repo := NewWikiLogEntryRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
// 5 entries in one KB + a sibling row in another KB to ensure the
|
||||
// WHERE filter actually narrows by KB.
|
||||
entries := []*types.WikiLogEntry{
|
||||
makeLogEntry("kb-a", "ingest", "k1", "Doc 1"),
|
||||
makeLogEntry("kb-a", "ingest", "k2", "Doc 2"),
|
||||
makeLogEntry("kb-a", "ingest", "k3", "Doc 3"),
|
||||
makeLogEntry("kb-a", "ingest", "k4", "Doc 4"),
|
||||
makeLogEntry("kb-a", "retract", "k5", "Doc 5"),
|
||||
}
|
||||
require.NoError(t, repo.AppendBatch(ctx, entries))
|
||||
|
||||
other := makeLogEntry("kb-other", "ingest", "kx", "Other doc")
|
||||
require.NoError(t, repo.AppendBatch(ctx, []*types.WikiLogEntry{other}))
|
||||
|
||||
// First page: latest 2 of kb-a, newest first.
|
||||
page1, cursor1, err := repo.List(ctx, "kb-a", "", 2)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, page1, 2)
|
||||
assert.Equal(t, "Doc 5", page1[0].DocTitle)
|
||||
assert.Equal(t, "Doc 4", page1[1].DocTitle)
|
||||
assert.NotEmpty(t, cursor1, "should emit next_cursor when the page is full")
|
||||
|
||||
// Second page continues strictly older than cursor1.
|
||||
page2, cursor2, err := repo.List(ctx, "kb-a", cursor1, 2)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, page2, 2)
|
||||
assert.Equal(t, "Doc 3", page2[0].DocTitle)
|
||||
assert.Equal(t, "Doc 2", page2[1].DocTitle)
|
||||
assert.NotEmpty(t, cursor2)
|
||||
|
||||
// Third (final) page: one row remains, so cursor is empty — the repo
|
||||
// must NOT emit a cursor for a short page, otherwise the frontend
|
||||
// would fire a doomed follow-up request.
|
||||
page3, cursor3, err := repo.List(ctx, "kb-a", cursor2, 2)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, page3, 1)
|
||||
assert.Equal(t, "Doc 1", page3[0].DocTitle)
|
||||
assert.Empty(t, cursor3, "short page should signal end-of-feed with an empty cursor")
|
||||
|
||||
// Sibling KB row must NOT leak into kb-a's feed.
|
||||
for _, p := range append(append(page1, page2...), page3...) {
|
||||
assert.Equal(t, "kb-a", p.KnowledgeBaseID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWikiLogEntryRepository_List_InvalidCursor rejects a non-numeric
|
||||
// cursor rather than silently returning the newest page, so clients
|
||||
// notice bugs before they turn into phantom paginations.
|
||||
func TestWikiLogEntryRepository_List_InvalidCursor(t *testing.T) {
|
||||
db := setupWikiLogTestDB(t)
|
||||
repo := NewWikiLogEntryRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _, err := repo.List(ctx, "kb-a", "not-a-number", 10)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
// TestWikiLogEntryRepository_DeleteByKB purges one KB's rows without
|
||||
// touching others. Used during KB deletion so the log table does not
|
||||
// accumulate orphans after the parent KB is gone.
|
||||
func TestWikiLogEntryRepository_DeleteByKB(t *testing.T) {
|
||||
db := setupWikiLogTestDB(t)
|
||||
repo := NewWikiLogEntryRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, repo.AppendBatch(ctx, []*types.WikiLogEntry{
|
||||
makeLogEntry("kb-a", "ingest", "k1", "Doc 1"),
|
||||
makeLogEntry("kb-a", "ingest", "k2", "Doc 2"),
|
||||
makeLogEntry("kb-b", "ingest", "k3", "Doc 3"),
|
||||
}))
|
||||
|
||||
require.NoError(t, repo.DeleteByKB(ctx, "kb-a"))
|
||||
|
||||
aEntries, _, err := repo.List(ctx, "kb-a", "", 100)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, aEntries)
|
||||
|
||||
bEntries, _, err := repo.List(ctx, "kb-b", "", 100)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, bEntries, 1)
|
||||
}
|
||||
|
||||
// TestWikiLogPageRefs_ScanAcceptsLegacyStringArray covers the backward-
|
||||
// compat path in the Scan method. Any rows the ingest pipeline wrote
|
||||
// before pages_affected gained a title field are stored as a plain JSON
|
||||
// string array; the repo must decode them as slug-only refs so the log
|
||||
// feed renders without a data migration.
|
||||
func TestWikiLogPageRefs_ScanAcceptsLegacyStringArray(t *testing.T) {
|
||||
var refs types.WikiLogPageRefs
|
||||
require.NoError(t, refs.Scan([]byte(`["entity/acme","concept/rag"]`)))
|
||||
require.Len(t, refs, 2)
|
||||
assert.Equal(t, "entity/acme", refs[0].Slug)
|
||||
assert.Empty(t, refs[0].Title, "legacy rows have no title until re-ingest overwrites them")
|
||||
assert.Equal(t, "concept/rag", refs[1].Slug)
|
||||
}
|
||||
@@ -208,6 +208,57 @@ func (r *wikiPageRepository) ListByType(ctx context.Context, kbID string, pageTy
|
||||
return pages, nil
|
||||
}
|
||||
|
||||
// ListByTypeLight projects only the columns needed to render an index
|
||||
// directory entry (slug, title, summary) and paginates by title ASC.
|
||||
// This keeps the GET /wiki/index response cheap on KBs with tens of
|
||||
// thousands of pages — the old path loaded every row including its TEXT
|
||||
// content just to throw the content away on the way out.
|
||||
//
|
||||
// Archived pages are excluded. `limit` clamps to [1, 200]; `offset` is
|
||||
// honored as-is. Returns the total non-archived count for the type
|
||||
// alongside the page so the caller can render "showing N of M".
|
||||
func (r *wikiPageRepository) ListByTypeLight(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
pageType string,
|
||||
limit int,
|
||||
offset int,
|
||||
) ([]types.WikiIndexEntry, int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
|
||||
base := r.db.WithContext(ctx).
|
||||
Model(&types.WikiPage{}).
|
||||
Where("knowledge_base_id = ? AND page_type = ? AND status <> ?",
|
||||
kbID, pageType, types.WikiPageStatusArchived)
|
||||
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if total == 0 {
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
var entries []types.WikiIndexEntry
|
||||
if err := base.
|
||||
Select("slug", "title", "summary").
|
||||
Order("title ASC").
|
||||
Limit(limit).
|
||||
Offset(offset).
|
||||
Scan(&entries).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return entries, total, nil
|
||||
}
|
||||
|
||||
// ListBySourceRef retrieves all wiki pages that reference a given source knowledge ID.
|
||||
// Handles both old format ("knowledgeID") and new format ("knowledgeID|title") in source_refs JSON array.
|
||||
func (r *wikiPageRepository) ListBySourceRef(ctx context.Context, kbID string, sourceKnowledgeID string) ([]*types.WikiPage, error) {
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// wikiPagesTestDDL is a minimal SQLite-compatible subset of the
|
||||
// production wiki_pages DDL (migrations/versioned/000037_wiki_and_indexing.up.sql).
|
||||
// JSONB is stored as TEXT in SQLite; the StringArray Scan/Value pair
|
||||
// handles the JSON round-trip unchanged.
|
||||
const wikiPagesTestDDL = `
|
||||
CREATE TABLE IF NOT EXISTS wiki_pages (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
knowledge_base_id VARCHAR(36) NOT NULL,
|
||||
slug VARCHAR(255) NOT NULL,
|
||||
title VARCHAR(512) NOT NULL DEFAULT '',
|
||||
page_type VARCHAR(32) NOT NULL DEFAULT 'summary',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'published',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
source_refs TEXT DEFAULT '[]',
|
||||
chunk_refs TEXT DEFAULT '[]',
|
||||
in_links TEXT DEFAULT '[]',
|
||||
out_links TEXT DEFAULT '[]',
|
||||
page_metadata TEXT DEFAULT '{}',
|
||||
aliases TEXT DEFAULT '[]',
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
func setupWikiPagesTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(wikiPagesTestDDL).Error)
|
||||
return db
|
||||
}
|
||||
|
||||
// makeWikiPage builds a minimal WikiPage suitable for insert. Title is
|
||||
// derived from the slug so ORDER BY title ASC yields a predictable
|
||||
// test ordering without callers having to spell out both fields.
|
||||
func makeWikiPage(kbID, slug, pageType, status string) *types.WikiPage {
|
||||
title := slug
|
||||
if idx := strings.LastIndex(slug, "/"); idx >= 0 {
|
||||
title = slug[idx+1:]
|
||||
}
|
||||
return &types.WikiPage{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: 1,
|
||||
KnowledgeBaseID: kbID,
|
||||
Slug: slug,
|
||||
Title: title,
|
||||
PageType: pageType,
|
||||
Status: status,
|
||||
Content: "body of " + slug,
|
||||
Summary: "summary of " + slug,
|
||||
Version: 1,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// TestListByTypeLight_ProjectsNarrowColumnsAndExcludesArchived verifies
|
||||
// that the index-view projection only emits the slug/title/summary
|
||||
// triples and respects the archived-status filter. This is the whole
|
||||
// point of splitting the method off ListByType — the index reader must
|
||||
// not pay for TEXT content transport.
|
||||
func TestListByTypeLight_ProjectsNarrowColumnsAndExcludesArchived(t *testing.T) {
|
||||
db := setupWikiPagesTestDB(t)
|
||||
repo := NewWikiPageRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
pages := []*types.WikiPage{
|
||||
makeWikiPage("kb-a", "entity/alpha", types.WikiPageTypeEntity, types.WikiPageStatusPublished),
|
||||
makeWikiPage("kb-a", "entity/beta", types.WikiPageTypeEntity, types.WikiPageStatusDraft),
|
||||
makeWikiPage("kb-a", "entity/gamma", types.WikiPageTypeEntity, types.WikiPageStatusArchived),
|
||||
makeWikiPage("kb-a", "concept/delta", types.WikiPageTypeConcept, types.WikiPageStatusPublished),
|
||||
makeWikiPage("kb-other", "entity/leaked", types.WikiPageTypeEntity, types.WikiPageStatusPublished),
|
||||
}
|
||||
for _, p := range pages {
|
||||
require.NoError(t, repo.Create(ctx, p))
|
||||
}
|
||||
|
||||
entries, total, err := repo.ListByTypeLight(ctx, "kb-a", types.WikiPageTypeEntity, 50, 0)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Archived is excluded; sibling KB is excluded; everything else
|
||||
// surfaces regardless of draft/published status (the index shows
|
||||
// both so admins notice newly-drafted pages).
|
||||
assert.Equal(t, int64(2), total)
|
||||
require.Len(t, entries, 2)
|
||||
|
||||
// ORDER BY title ASC => alpha, beta.
|
||||
assert.Equal(t, "entity/alpha", entries[0].Slug)
|
||||
assert.Equal(t, "alpha", entries[0].Title)
|
||||
assert.Equal(t, "summary of entity/alpha", entries[0].Summary)
|
||||
assert.Equal(t, "entity/beta", entries[1].Slug)
|
||||
}
|
||||
|
||||
// TestListByTypeLight_Pagination walks the type list using offsets and
|
||||
// asserts the count stays stable regardless of where in the list we
|
||||
// are — the index handler uses total to render "showing N of M".
|
||||
func TestListByTypeLight_Pagination(t *testing.T) {
|
||||
db := setupWikiPagesTestDB(t)
|
||||
repo := NewWikiPageRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, s := range []string{"entity/a", "entity/b", "entity/c", "entity/d", "entity/e"} {
|
||||
require.NoError(t, repo.Create(ctx, makeWikiPage("kb-a", s, types.WikiPageTypeEntity, types.WikiPageStatusPublished)))
|
||||
}
|
||||
|
||||
page1, total1, err := repo.ListByTypeLight(ctx, "kb-a", types.WikiPageTypeEntity, 2, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(5), total1)
|
||||
require.Len(t, page1, 2)
|
||||
assert.Equal(t, "entity/a", page1[0].Slug)
|
||||
assert.Equal(t, "entity/b", page1[1].Slug)
|
||||
|
||||
page2, total2, err := repo.ListByTypeLight(ctx, "kb-a", types.WikiPageTypeEntity, 2, 2)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(5), total2, "total should be stable across pages")
|
||||
require.Len(t, page2, 2)
|
||||
assert.Equal(t, "entity/c", page2[0].Slug)
|
||||
assert.Equal(t, "entity/d", page2[1].Slug)
|
||||
|
||||
page3, total3, err := repo.ListByTypeLight(ctx, "kb-a", types.WikiPageTypeEntity, 2, 4)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(5), total3)
|
||||
require.Len(t, page3, 1)
|
||||
assert.Equal(t, "entity/e", page3[0].Slug)
|
||||
|
||||
// Offset past the end yields an empty list, not an error — the
|
||||
// handler relies on this to short-circuit pagination tails.
|
||||
page4, total4, err := repo.ListByTypeLight(ctx, "kb-a", types.WikiPageTypeEntity, 2, 10)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(5), total4)
|
||||
assert.Empty(t, page4)
|
||||
}
|
||||
|
||||
// TestListByTypeLight_EmptyType_ReturnsZero exercises the "no rows"
|
||||
// short-circuit. We skip the SELECT entirely when count is zero, so
|
||||
// a KB with no pages of a type shouldn't burn a pointless query.
|
||||
func TestListByTypeLight_EmptyType_ReturnsZero(t *testing.T) {
|
||||
db := setupWikiPagesTestDB(t)
|
||||
repo := NewWikiPageRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
entries, total, err := repo.ListByTypeLight(ctx, "kb-empty", types.WikiPageTypeSynthesis, 50, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), total)
|
||||
assert.Empty(t, entries)
|
||||
}
|
||||
|
||||
// TestListByTypeLight_ClampsLimit verifies the [1, 200] clamp. We don't
|
||||
// want a client passing limit=100000 and forcing the DB to return a
|
||||
// multi-MB response.
|
||||
func TestListByTypeLight_ClampsLimit(t *testing.T) {
|
||||
db := setupWikiPagesTestDB(t)
|
||||
repo := NewWikiPageRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
for i := 0; i < 250; i++ {
|
||||
slug := "entity/bulk-"
|
||||
// Use a stable, zero-padded suffix so title ordering is
|
||||
// deterministic for the cap assertion below.
|
||||
slug += string(rune('a'+(i/26)%26)) + string(rune('a'+i%26))
|
||||
require.NoError(t, repo.Create(ctx, makeWikiPage("kb-cap", slug, types.WikiPageTypeEntity, types.WikiPageStatusPublished)))
|
||||
}
|
||||
|
||||
// limit=0 falls back to the default of 50.
|
||||
defaultEntries, _, err := repo.ListByTypeLight(ctx, "kb-cap", types.WikiPageTypeEntity, 0, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, defaultEntries, 50)
|
||||
|
||||
// limit=5000 clamps to 200.
|
||||
clampedEntries, _, err := repo.ListByTypeLight(ctx, "kb-cap", types.WikiPageTypeEntity, 5000, 0)
|
||||
require.NoError(t, err)
|
||||
assert.LessOrEqual(t, len(clampedEntries), 200)
|
||||
}
|
||||
@@ -97,6 +97,17 @@ const (
|
||||
// tick (GC pause, Redis blip) doesn't let the lock slip out from under a
|
||||
// live handler.
|
||||
wikiActiveLockRenew = 20 * time.Second
|
||||
|
||||
// wikiLLMMaxAttempts is the total attempt count (initial + retries) for
|
||||
// every LLM call routed through generateWithTemplate. 3 was chosen to
|
||||
// absorb transient 504/timeouts from upstream gateways without
|
||||
// materially prolonging task runtime when the remote is genuinely down.
|
||||
wikiLLMMaxAttempts = 3
|
||||
|
||||
// wikiLLMBackoffBase is the base delay for the exponential backoff
|
||||
// between retry attempts. The nth retry waits base << (n-1) — so with
|
||||
// a 2s base we wait 2s, 4s, 8s between attempts.
|
||||
wikiLLMBackoffBase = 2 * time.Second
|
||||
)
|
||||
|
||||
// WikiDeletedTombstoneKey returns the Redis key used to mark a knowledge as
|
||||
@@ -156,6 +167,7 @@ type wikiIngestService struct {
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
logEntrySvc interfaces.WikiLogEntryService
|
||||
redisClient *redis.Client // nil in Lite mode (no Redis)
|
||||
// liteLocks provides per-KB mutual exclusion in Lite mode (no Redis).
|
||||
// Keys are kbID strings; values are unused (presence = locked).
|
||||
@@ -170,6 +182,7 @@ func NewWikiIngestService(
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
modelService interfaces.ModelService,
|
||||
task interfaces.TaskEnqueuer,
|
||||
logEntrySvc interfaces.WikiLogEntryService,
|
||||
redisClient *redis.Client,
|
||||
) interfaces.TaskHandler {
|
||||
svc := &wikiIngestService{
|
||||
@@ -179,6 +192,7 @@ func NewWikiIngestService(
|
||||
chunkRepo: chunkRepo,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
logEntrySvc: logEntrySvc,
|
||||
redisClient: redisClient,
|
||||
}
|
||||
return svc
|
||||
@@ -427,8 +441,11 @@ func (s *wikiIngestService) requeueFailedOps(ctx context.Context, payload WikiIn
|
||||
type docIngestResult struct {
|
||||
KnowledgeID string
|
||||
DocTitle string
|
||||
Summary string // one-line summary of the document (from summary page)
|
||||
Pages []string // affected page slugs
|
||||
Summary string // one-line summary of the document (from summary page)
|
||||
// Pages records the wiki pages this document touched, carrying both
|
||||
// the slug (for navigation / retract lookups) and the human-readable
|
||||
// title captured at ingest time (for the log feed's display layer).
|
||||
Pages []types.WikiLogPageRef
|
||||
}
|
||||
|
||||
// WikiBatchContext holds shared data across Map and Reduce phases
|
||||
@@ -695,62 +712,72 @@ type combinedExtraction struct {
|
||||
Concepts []extractedItem `json:"concepts"`
|
||||
}
|
||||
|
||||
// rebuildIndexPage regenerates the index page.
|
||||
// rebuildIndexPage refreshes the LLM-generated intro that sits on the
|
||||
// index wiki_pages row.
|
||||
//
|
||||
// Strategy: Index = LLM-generated intro (stored in Summary field) + code-generated directory.
|
||||
// - Intro: stored in indexPage.Summary. First time: generated from document summaries.
|
||||
// Subsequent: incrementally updated with changeDescription.
|
||||
// - Directory: pure code, rebuilt every time. O(N) string concat, no LLM.
|
||||
// History: the index page used to store "intro + full directory listing" as
|
||||
// a single multi-MB markdown blob in content. Every ingest batch rewrote
|
||||
// the whole column, which on KBs with tens of thousands of pages caused
|
||||
// O(N) TOAST writes per batch. The directory was lifted out into the
|
||||
// structured GET /wiki/index endpoint (see wikiPageService.GetIndexView),
|
||||
// and this method now only maintains the intro.
|
||||
//
|
||||
// Intro lifecycle:
|
||||
// - First time (empty or legacy placeholder): generate from all document
|
||||
// summaries via WikiIndexIntroPrompt.
|
||||
// - Subsequent calls with a change description: incremental update via
|
||||
// WikiIndexIntroUpdatePrompt so the intro reflects what just landed.
|
||||
// - No change description: keep the existing intro untouched.
|
||||
//
|
||||
// The new intro is written to both Content and Summary so readers that
|
||||
// still fall back to Summary (older clients, legacy migrations) stay in
|
||||
// sync with the column the view actually renders.
|
||||
func (s *wikiIngestService) rebuildIndexPage(ctx context.Context, chatModel chat.Chat, payload WikiIngestPayload, changeDesc, lang string) error {
|
||||
indexPage, _ := s.wikiService.GetIndex(ctx, payload.KnowledgeBaseID)
|
||||
if indexPage == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// List all live pages
|
||||
allPages, err := s.wikiService.ListAllPages(ctx, payload.KnowledgeBaseID)
|
||||
// Gather just the Summary-type pages the LLM needs for intro framing.
|
||||
// We do NOT load or iterate every wiki page here — the directory is
|
||||
// now assembled on demand by GetIndexView, which is the only reader
|
||||
// that needs the full enumeration.
|
||||
summaries, err := s.wikiService.ListByType(ctx, payload.KnowledgeBaseID, types.WikiPageTypeSummary)
|
||||
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++
|
||||
}
|
||||
|
||||
// Build document summaries listing (only summary-type pages — they represent documents)
|
||||
var docSummaries strings.Builder
|
||||
for _, p := range grouped[types.WikiPageTypeSummary] {
|
||||
for _, p := range summaries {
|
||||
if p == nil || p.Status == types.WikiPageStatusArchived {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&docSummaries, "<document>\n<title>%s</title>\n<summary>%s</summary>\n</document>\n\n", p.Title, p.Summary)
|
||||
}
|
||||
if docSummaries.Len() == 0 {
|
||||
docSummaries.WriteString("(no documents yet)")
|
||||
}
|
||||
|
||||
// Generate or update intro
|
||||
existingIntro := indexPage.Summary
|
||||
var intro string
|
||||
// The intro lives on both Content and Summary. Prefer Content since
|
||||
// that's what the new index view returns; fall back to Summary for
|
||||
// rows written before this refactor so the incremental-update prompt
|
||||
// has something to work with.
|
||||
existingIntro := strings.TrimSpace(indexPage.Content)
|
||||
if existingIntro == "" {
|
||||
existingIntro = strings.TrimSpace(indexPage.Summary)
|
||||
}
|
||||
// Detect the legacy "intro + directory" payload. Such rows embed the
|
||||
// fence-separated "## Summary" sections right after the intro, so we
|
||||
// clip everything from the first directory heading onward to keep the
|
||||
// intro length bounded when we feed it back into the update prompt.
|
||||
if idx := strings.Index(existingIntro, "\n## "); idx >= 0 {
|
||||
existingIntro = strings.TrimSpace(existingIntro[:idx])
|
||||
}
|
||||
|
||||
if existingIntro == "" || existingIntro == "Wiki index - table of contents" {
|
||||
// First time — generate intro from scratch
|
||||
var intro string
|
||||
switch {
|
||||
case existingIntro == "" || existingIntro == "Wiki index - table of contents":
|
||||
// First time — generate intro from scratch.
|
||||
generatedIntro, genErr := s.generateWithTemplate(ctx, chatModel, agent.WikiIndexIntroPrompt, map[string]string{
|
||||
"DocumentSummaries": docSummaries.String(),
|
||||
"Language": lang,
|
||||
@@ -760,8 +787,8 @@ func (s *wikiIngestService) rebuildIndexPage(ctx context.Context, chatModel chat
|
||||
} else {
|
||||
intro = strings.TrimSpace(generatedIntro)
|
||||
}
|
||||
} else if changeDesc != "" {
|
||||
// Incremental update — tell LLM what changed
|
||||
case changeDesc != "":
|
||||
// Incremental update — tell the LLM what changed.
|
||||
updatedIntro, genErr := s.generateWithTemplate(ctx, chatModel, agent.WikiIndexIntroUpdatePrompt, map[string]string{
|
||||
"ExistingIntro": existingIntro,
|
||||
"ChangeDescription": changeDesc,
|
||||
@@ -773,45 +800,23 @@ func (s *wikiIngestService) rebuildIndexPage(ctx context.Context, chatModel chat
|
||||
} else {
|
||||
intro = strings.TrimSpace(updatedIntro)
|
||||
}
|
||||
} else {
|
||||
intro = existingIntro // no change description, keep as-is
|
||||
default:
|
||||
// No change description and an existing intro: leave it as-is so
|
||||
// we don't bump the version for a no-op.
|
||||
intro = existingIntro
|
||||
}
|
||||
|
||||
// Build directory (pure code, no LLM)
|
||||
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 {
|
||||
summary := p.Summary
|
||||
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, 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")
|
||||
// Defensive: some LLM outputs occasionally bleed into a directory-
|
||||
// like section even when the intro prompt doesn't ask for one. If
|
||||
// the freshly-generated intro starts to look like a legacy payload,
|
||||
// clip it at the first "\n## " just like we did on the read path
|
||||
// above. This keeps indexPage.Content a bounded intro-only blob.
|
||||
if idx := strings.Index(intro, "\n## "); idx >= 0 {
|
||||
intro = strings.TrimSpace(intro[:idx])
|
||||
}
|
||||
|
||||
indexPage.Content = intro + "\n" + dir.String()
|
||||
indexPage.Summary = intro // persist intro for next incremental update
|
||||
indexPage.Content = intro
|
||||
indexPage.Summary = intro
|
||||
_, err = s.wikiService.UpdatePage(ctx, indexPage)
|
||||
return err
|
||||
}
|
||||
@@ -834,34 +839,31 @@ func splitSummaryLine(raw string) (summary string, content string) {
|
||||
return "", raw
|
||||
}
|
||||
|
||||
// appendLogEntry appends a structured, grep-parseable entry to the log page.
|
||||
// Format: ## [2026-04-07 19:50:02] action | title
|
||||
// Followed by key-value metadata lines. No sub-headings — keeps `grep "^## \[" log.md` clean.
|
||||
func (s *wikiIngestService) appendLogEntry(ctx context.Context, kbID string, action, knowledgeID, docTitle, summary string, pagesAffected []string) {
|
||||
logPage, _ := s.wikiService.GetLog(ctx, kbID)
|
||||
if logPage == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, "\n## [%s] %s | %s\n",
|
||||
time.Now().Format("2006-01-02 15:04:05"),
|
||||
action,
|
||||
docTitle,
|
||||
)
|
||||
if knowledgeID != "" {
|
||||
fmt.Fprintf(&sb, "- **KnowledgeID**: %s\n", knowledgeID)
|
||||
}
|
||||
if summary != "" {
|
||||
fmt.Fprintf(&sb, "- **Summary**: %s\n", summary)
|
||||
}
|
||||
// buildLogEntry builds a WikiLogEntry struct for the current batch. It is
|
||||
// pure (no DB access) so callers can accumulate entries cheaply under their
|
||||
// lock and flush them in a single AppendBatch call at the end of the batch.
|
||||
//
|
||||
// Historically this was a per-event `GetLog + UpdatePage` round trip, which
|
||||
// rewrote the entire log page's TEXT column on every ingest/retract op —
|
||||
// O(n^2) write amplification as the log grew. The batch writer now uses
|
||||
// wikiLogEntryService.AppendBatch instead; see ProcessWikiIngest.
|
||||
func (s *wikiIngestService) buildLogEntry(tenantID uint64, kbID, action, knowledgeID, docTitle, summary string, pagesAffected []types.WikiLogPageRef) *types.WikiLogEntry {
|
||||
// Copy pagesAffected so the entry does not alias caller-owned slices.
|
||||
// The batch accumulates SlugUpdate results that may be reused downstream.
|
||||
var pages types.WikiLogPageRefs
|
||||
if len(pagesAffected) > 0 {
|
||||
fmt.Fprintf(&sb, "- **Pages affected**: %d (%s)\n", len(pagesAffected), strings.Join(pagesAffected, ", "))
|
||||
pages = make(types.WikiLogPageRefs, len(pagesAffected))
|
||||
copy(pages, pagesAffected)
|
||||
}
|
||||
|
||||
logPage.Content = logPage.Content + sb.String()
|
||||
if _, err := s.wikiService.UpdatePage(ctx, logPage); err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: failed to update log page: %v", err)
|
||||
return &types.WikiLogEntry{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
Action: action,
|
||||
KnowledgeID: knowledgeID,
|
||||
DocTitle: docTitle,
|
||||
Summary: summary,
|
||||
PagesAffected: pages,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1017,7 +1019,23 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
|
||||
return entities, concepts
|
||||
}
|
||||
|
||||
// generateWithTemplate executes a prompt template and calls the LLM
|
||||
// generateWithTemplate executes a prompt template and calls the LLM with
|
||||
// bounded exponential-backoff retries for transient infrastructure errors.
|
||||
//
|
||||
// Retry policy:
|
||||
// - Up to wikiLLMMaxAttempts total attempts (initial + retries).
|
||||
// - Only retry errors classified as transient by isTransientLLMError:
|
||||
// HTTP 408/429/5xx, context deadline exceeded (when the parent ctx is
|
||||
// still alive), or generic "timeout"/"connection reset" wording.
|
||||
// 4xx (except 408/429) is a caller-side fault and fails fast.
|
||||
// - Backoff is exponential base 2s: 2s, 4s, 8s — roughly wikiLLMBackoffBase
|
||||
// * 2^(attempt-1). Honors ctx cancellation so the task can abort.
|
||||
//
|
||||
// This exists because wiki ingest makes several independent LLM calls per
|
||||
// document (extraction, summary, dedup, citations, intro) and a single
|
||||
// transient 504 from the upstream gateway used to drop the document's
|
||||
// summary page permanently. Retries plus failedOps requeuing (see
|
||||
// mapOneDocument) turn those events into at-most-a-few-minute hiccups.
|
||||
func (s *wikiIngestService) generateWithTemplate(ctx context.Context, chatModel chat.Chat, promptTpl string, data map[string]string) (string, error) {
|
||||
tmpl, err := template.New("wiki").Parse(promptTpl)
|
||||
if err != nil {
|
||||
@@ -1031,17 +1049,98 @@ func (s *wikiIngestService) generateWithTemplate(ctx context.Context, chatModel
|
||||
|
||||
prompt := buf.String()
|
||||
thinking := false
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
{Role: "user", Content: prompt},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("LLM call failed: %w", err)
|
||||
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= wikiLLMMaxAttempts; attempt++ {
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
{Role: "user", Content: prompt},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err == nil {
|
||||
return response.Content, nil
|
||||
}
|
||||
lastErr = err
|
||||
|
||||
// Abort immediately on non-retryable errors (4xx except 408/429,
|
||||
// parse/marshal failures, tool-side bugs, etc.). Retrying a
|
||||
// hard "invalid arguments" error just wastes the model's budget.
|
||||
if !isTransientLLMError(ctx, err) {
|
||||
return "", fmt.Errorf("LLM call failed: %w", err)
|
||||
}
|
||||
if attempt == wikiLLMMaxAttempts {
|
||||
break
|
||||
}
|
||||
|
||||
backoff := wikiLLMBackoffBase << (attempt - 1)
|
||||
logger.Warnf(ctx, "wiki ingest: LLM call failed (attempt %d/%d), retrying in %s: %v",
|
||||
attempt, wikiLLMMaxAttempts, backoff, err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", fmt.Errorf("LLM call aborted during backoff: %w", ctx.Err())
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("LLM call failed after %d attempts: %w", wikiLLMMaxAttempts, lastErr)
|
||||
}
|
||||
|
||||
// isTransientLLMError reports whether an error from the chat provider
|
||||
// looks like an infrastructure hiccup worth retrying. Classification is
|
||||
// intentionally conservative: the truthful "could not tell, assume
|
||||
// permanent" choice keeps retries cheap and avoids masking real bugs.
|
||||
//
|
||||
// We treat the following as transient:
|
||||
// - HTTP 408 (client request timeout — upstream usually didn't process),
|
||||
// 429 (rate-limited — retry after backoff may succeed), 5xx (any
|
||||
// server-side fault, including the 504 "Remote error, timeout with
|
||||
// 60" we see from the gateway in front of several LLM providers).
|
||||
// - Wrapped context.DeadlineExceeded when the parent ctx is still alive
|
||||
// (nested per-call timeouts).
|
||||
// - Substring matches on the error text for common transport failures
|
||||
// ("timeout", "connection reset", "EOF") that providers surface
|
||||
// without a structured status code.
|
||||
func isTransientLLMError(ctx context.Context, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
// Never retry after the parent ctx itself expired — the task is
|
||||
// being cancelled and the next attempt would just fail again.
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return response.Content, nil
|
||||
msg := err.Error()
|
||||
// Providers that bubble HTTP status up formatted as
|
||||
// "API request failed with status NNN: ..." — match that first.
|
||||
for _, s := range []string{
|
||||
"status 408", "status 429",
|
||||
"status 500", "status 501", "status 502", "status 503", "status 504",
|
||||
"status 520", "status 521", "status 522", "status 523", "status 524",
|
||||
} {
|
||||
if strings.Contains(msg, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
lower := strings.ToLower(msg)
|
||||
for _, s := range []string{
|
||||
"timeout",
|
||||
"timed out",
|
||||
"connection reset",
|
||||
"connection refused",
|
||||
"broken pipe",
|
||||
"no such host", // DNS hiccup
|
||||
"i/o timeout",
|
||||
"unexpected eof",
|
||||
"tls handshake",
|
||||
"context deadline exceeded", // nested per-call deadline
|
||||
} {
|
||||
if strings.Contains(lower, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
@@ -392,14 +392,42 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
|
||||
totalPagesAffected = len(allPagesAffected)
|
||||
|
||||
// Append log entries — one per operation for chronological traceability
|
||||
// Collect log entries for this batch and flush them in a single INSERT.
|
||||
// Historically each op triggered its own `GetLog + UpdatePage` round
|
||||
// trip, which rewrote the entire log page TEXT column and caused O(n^2)
|
||||
// write amplification as the log grew. AppendBatch writes one row per
|
||||
// event into wiki_log_entries instead.
|
||||
//
|
||||
// slugsToRefs resolves each retract slug against the batch-start
|
||||
// snapshot (batchCtx.SlugTitleMap) so the log feed carries titles for
|
||||
// pages that existed when the batch began. Pages created or renamed
|
||||
// during this batch fall through the map lookup and log as slug-only
|
||||
// refs, which the frontend renders as the slug itself — a sensible
|
||||
// fallback given retracts only touch pre-existing pages.
|
||||
slugsToRefs := func(slugs []string) []types.WikiLogPageRef {
|
||||
if len(slugs) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]types.WikiLogPageRef, 0, len(slugs))
|
||||
for _, slug := range slugs {
|
||||
title := batchCtx.SlugTitleMap[slug]
|
||||
out = append(out, types.WikiLogPageRef{Slug: slug, Title: title})
|
||||
}
|
||||
return out
|
||||
}
|
||||
logEntries := make([]*types.WikiLogEntry, 0, len(pendingOps)+len(docResults))
|
||||
for _, op := range pendingOps {
|
||||
if op.Op == WikiOpRetract {
|
||||
s.appendLogEntry(ctx, payload.KnowledgeBaseID, "retract", op.KnowledgeID, op.DocTitle, op.DocSummary, op.PageSlugs)
|
||||
logEntries = append(logEntries, s.buildLogEntry(payload.TenantID, payload.KnowledgeBaseID, "retract", op.KnowledgeID, op.DocTitle, op.DocSummary, slugsToRefs(op.PageSlugs)))
|
||||
}
|
||||
}
|
||||
for _, r := range docResults {
|
||||
s.appendLogEntry(ctx, payload.KnowledgeBaseID, "ingest", r.KnowledgeID, r.DocTitle, r.Summary, r.Pages)
|
||||
logEntries = append(logEntries, s.buildLogEntry(payload.TenantID, payload.KnowledgeBaseID, "ingest", r.KnowledgeID, r.DocTitle, r.Summary, r.Pages))
|
||||
}
|
||||
if len(logEntries) > 0 && s.logEntrySvc != nil {
|
||||
if err := s.logEntrySvc.AppendBatch(ctx, logEntries); err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: failed to append %d log entries: %v", len(logEntries), err)
|
||||
}
|
||||
}
|
||||
|
||||
// Build change description for the Index Intro LLM prompt
|
||||
@@ -625,9 +653,18 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
}
|
||||
}
|
||||
|
||||
extractedPages := make([]string, 0, len(slugItems)+1)
|
||||
for slug := range slugItems {
|
||||
extractedPages = append(extractedPages, slug)
|
||||
// extractedPages records every wiki page this document materialized
|
||||
// (entities, concepts, plus the summary page appended below). The
|
||||
// slug is used for link/retract bookkeeping; the title is captured
|
||||
// for the log feed so the user sees "提供本学位在线验证报告查询…"
|
||||
// rather than "entity/xue-xin-wang".
|
||||
extractedPages := make([]types.WikiLogPageRef, 0, len(slugItems)+1)
|
||||
for slug, item := range slugItems {
|
||||
title := item.Name
|
||||
if title == "" {
|
||||
title = slug
|
||||
}
|
||||
extractedPages = append(extractedPages, types.WikiLogPageRef{Slug: slug, Title: title})
|
||||
}
|
||||
|
||||
// Count total distinct chunks cited across all slugs for logging.
|
||||
@@ -647,32 +684,44 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
var docSummary string
|
||||
|
||||
if summaryErr != nil {
|
||||
logger.Errorf(ctx, "wiki ingest: generate summary failed for %s: %v", knowledgeID, summaryErr)
|
||||
} else {
|
||||
sumLine, sumBody := splitSummaryLine(summaryContent)
|
||||
if sumBody == "" {
|
||||
sumBody = summaryContent
|
||||
}
|
||||
if sumLine == "" {
|
||||
sumLine = docTitle
|
||||
}
|
||||
docSummaryLine = sumLine
|
||||
docSummary = sumBody
|
||||
if strings.TrimSpace(docSummary) == "" {
|
||||
docSummary = sumLine
|
||||
}
|
||||
updates = append(updates, SlugUpdate{
|
||||
Slug: summarySlug,
|
||||
Type: types.WikiPageTypeSummary,
|
||||
DocTitle: docTitle,
|
||||
KnowledgeID: knowledgeID,
|
||||
SourceRef: sourceRef,
|
||||
Language: lang,
|
||||
SummaryLine: sumLine,
|
||||
SummaryBody: sumBody,
|
||||
})
|
||||
extractedPages = append(extractedPages, summarySlug)
|
||||
// Summary is the headline artifact of an ingested document — a
|
||||
// document with no summary page is half-ingested and leaves the
|
||||
// entity/concept updates hanging without a root to link back to
|
||||
// from the index. Historically we just logged and moved on,
|
||||
// which meant a single transient 504 permanently dropped the
|
||||
// summary page for that document.
|
||||
//
|
||||
// Returning an error here sends the op to failedOps (see the
|
||||
// map-phase loop in ProcessWikiIngest), which requeueFailedOps
|
||||
// appends back onto the pending list so the next batch retries.
|
||||
// The internal retries in generateWithTemplate already exhaust
|
||||
// the LLM's own transient-error budget before we give up here.
|
||||
logger.Errorf(ctx, "wiki ingest: generate summary failed for %s, will requeue: %v", knowledgeID, summaryErr)
|
||||
return nil, nil, fmt.Errorf("generate summary: %w", summaryErr)
|
||||
}
|
||||
sumLine, sumBody := splitSummaryLine(summaryContent)
|
||||
if sumBody == "" {
|
||||
sumBody = summaryContent
|
||||
}
|
||||
if sumLine == "" {
|
||||
sumLine = docTitle
|
||||
}
|
||||
docSummaryLine = sumLine
|
||||
docSummary = sumBody
|
||||
if strings.TrimSpace(docSummary) == "" {
|
||||
docSummary = sumLine
|
||||
}
|
||||
updates = append(updates, SlugUpdate{
|
||||
Slug: summarySlug,
|
||||
Type: types.WikiPageTypeSummary,
|
||||
DocTitle: docTitle,
|
||||
KnowledgeID: knowledgeID,
|
||||
SourceRef: sourceRef,
|
||||
Language: lang,
|
||||
SummaryLine: sumLine,
|
||||
SummaryBody: sumBody,
|
||||
})
|
||||
extractedPages = append(extractedPages, types.WikiLogPageRef{Slug: summarySlug, Title: docTitle})
|
||||
|
||||
// Entities
|
||||
for _, item := range extractedEntities {
|
||||
@@ -740,7 +789,7 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
|
||||
newSlugSet := make(map[string]bool, len(extractedPages))
|
||||
for _, ns := range extractedPages {
|
||||
newSlugSet[ns] = true
|
||||
newSlugSet[ns.Slug] = true
|
||||
}
|
||||
|
||||
var reparseOverlap, staleCount int
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestIsTransientLLMError_HTTPStatuses covers the status codes we know
|
||||
// the generic REST chat provider bubbles up as "API request failed with
|
||||
// status NNN: ...". The status-code arm of the classifier is the one
|
||||
// that actually fires for the 504 gateway timeouts the upstream LLM
|
||||
// vendors throw most often.
|
||||
func TestIsTransientLLMError_HTTPStatuses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cases := []struct {
|
||||
msg string
|
||||
want bool
|
||||
}{
|
||||
{"API request failed with status 504: Remote error, timeout with 60", true},
|
||||
{"API request failed with status 503: service unavailable", true},
|
||||
{"API request failed with status 502: bad gateway", true},
|
||||
{"API request failed with status 500: internal server error", true},
|
||||
{"API request failed with status 429: rate limited", true},
|
||||
{"API request failed with status 408: request timeout", true},
|
||||
{"API request failed with status 520: Web server returned unknown", true},
|
||||
{"API request failed with status 524: timeout (Cloudflare)", true},
|
||||
// 4xx permanent: a retry will just fail the same way.
|
||||
{"API request failed with status 400: bad request", false},
|
||||
{"API request failed with status 401: unauthorized", false},
|
||||
{"API request failed with status 403: forbidden (quota exhausted)", false},
|
||||
{"API request failed with status 404: model not found", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := isTransientLLMError(ctx, errors.New(tc.msg))
|
||||
if got != tc.want {
|
||||
t.Errorf("isTransientLLMError(%q) = %v, want %v", tc.msg, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsTransientLLMError_TransportSubstrings covers providers (and Go
|
||||
// stdlib errors) that surface transient conditions as free-form text
|
||||
// without a numeric status code — DNS blips, TLS handshake failures,
|
||||
// broken pipes during an in-flight body read, etc.
|
||||
func TestIsTransientLLMError_TransportSubstrings(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cases := []struct {
|
||||
msg string
|
||||
want bool
|
||||
}{
|
||||
{"send request: dial tcp: lookup api.example.com: no such host", true},
|
||||
{"send request: read tcp 10.0.0.1: i/o timeout", true},
|
||||
{"send request: Post \"...\": context deadline exceeded", true},
|
||||
{"send request: connection reset by peer", true},
|
||||
{"send request: connection refused", true},
|
||||
{"send request: broken pipe", true},
|
||||
{"send request: tls handshake timeout", true},
|
||||
{"send request: unexpected EOF", true},
|
||||
// Not transient: the error is actionable (missing model id,
|
||||
// malformed tool call, etc.) — retry is just wasted budget.
|
||||
{"model not configured for tool use", false},
|
||||
{"invalid JSON in tool arguments", false},
|
||||
{"parse template: syntax error", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := isTransientLLMError(ctx, errors.New(tc.msg))
|
||||
if got != tc.want {
|
||||
t.Errorf("isTransientLLMError(%q) = %v, want %v", tc.msg, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsTransientLLMError_AbortsWhenParentCtxDone ensures a cancelled
|
||||
// outer context short-circuits the retry decision. Without this guard
|
||||
// an ingest task that was interrupted (asynq shutdown, deletion race,
|
||||
// parent timeout) would keep retrying the LLM during its teardown
|
||||
// window and waste the remainder of the backoff budget.
|
||||
func TestIsTransientLLMError_AbortsWhenParentCtxDone(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
// This exact error would normally be classified transient (see
|
||||
// TestIsTransientLLMError_HTTPStatuses), but a cancelled ctx must
|
||||
// override that so the task can unwind promptly.
|
||||
err := errors.New("API request failed with status 504: Remote error")
|
||||
if isTransientLLMError(ctx, err) {
|
||||
t.Fatal("cancelled ctx should short-circuit to non-transient")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsTransientLLMError_NilError is a sanity check — nil should never
|
||||
// be treated as retryable, otherwise callers that forget to handle the
|
||||
// happy path would spin forever.
|
||||
func TestIsTransientLLMError_NilError(t *testing.T) {
|
||||
if isTransientLLMError(context.Background(), nil) {
|
||||
t.Fatal("nil error should not be transient")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// wikiLogEntryService is a thin wrapper over WikiLogEntryRepository. The
|
||||
// event layer carries no business rules today, so the service just
|
||||
// forwards to the repo — the indirection exists so handlers / ingest
|
||||
// batch code depend on an interface rather than a concrete repo type.
|
||||
type wikiLogEntryService struct {
|
||||
repo interfaces.WikiLogEntryRepository
|
||||
}
|
||||
|
||||
// NewWikiLogEntryService constructs a WikiLogEntryService backed by the
|
||||
// given repository.
|
||||
func NewWikiLogEntryService(repo interfaces.WikiLogEntryRepository) interfaces.WikiLogEntryService {
|
||||
return &wikiLogEntryService{repo: repo}
|
||||
}
|
||||
|
||||
// AppendBatch records the given events in one database round trip. Empty
|
||||
// batches are a no-op (the repo handles that).
|
||||
func (s *wikiLogEntryService) AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error {
|
||||
return s.repo.AppendBatch(ctx, entries)
|
||||
}
|
||||
|
||||
// List paginates the per-KB event feed. See repo.List for cursor semantics.
|
||||
func (s *wikiLogEntryService) List(ctx context.Context, kbID string, cursor string, limit int) (*types.WikiLogEntryListResponse, error) {
|
||||
entries, nextCursor, err := s.repo.List(ctx, kbID, cursor, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if entries == nil {
|
||||
// Normalise to an empty slice so clients don't need to
|
||||
// distinguish `null` from `[]`.
|
||||
entries = []*types.WikiLogEntry{}
|
||||
}
|
||||
return &types.WikiLogEntryListResponse{
|
||||
Entries: entries,
|
||||
NextCursor: nextCursor,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DeleteByKB removes the log feed for a KB. Called when the KB itself is
|
||||
// being deleted, so no further reads happen.
|
||||
func (s *wikiLogEntryService) DeleteByKB(ctx context.Context, kbID string) error {
|
||||
return s.repo.DeleteByKB(ctx, kbID)
|
||||
}
|
||||
@@ -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