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)
|
||||
}
|
||||
Reference in New Issue
Block a user