Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(wiki): 唯一写出口 UpdatePage 拦住丢表格行的机器重写(agent 整页写入不再静默改短页面) (#3793)

linus-liu-webabc365f91919
diff --git a/internal/agent/tools/wiki_replace_text.go b/internal/agent/tools/wiki_replace_text.go
index ca4a57759..30c669493 100644
--- a/internal/agent/tools/wiki_replace_text.go
+++ b/internal/agent/tools/wiki_replace_text.go
@@ -74,6 +74,11 @@ func (t *wikiReplaceTextTool) Execute(ctx context.Context, args json.RawMessage)
// Attribute every page write performed by this tool to the agent so
// revision history distinguishes agent edits from pipeline/user ones.
ctx = types.WithWikiEditSource(ctx, types.WikiEditSourceAgent)
+ // This tool edits by naming the exact text it removes, so a write that
+ // shortens the page is a deliberate removal — including deleting table
+ // rows, which is a normal request. The whole-page writer is deliberately
+ // NOT marked: there a shorter body is how truncation shows up.
+ ctx = types.WithWikiShrinkAllowed(ctx)
var params struct {
Slug string `json:"slug"`
OldText string `json:"old_text"`
diff --git a/internal/application/service/wiki_ingest_batch.go b/internal/application/service/wiki_ingest_batch.go
index 06988a826..6b44a5ada 100644
--- a/internal/application/service/wiki_ingest_batch.go
+++ b/internal/application/service/wiki_ingest_batch.go
@@ -742,6 +742,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
changed bool
affectedType string
additionFailed bool
+ updateDeferred bool
reduceErr error
)
// Serialize same-slug read-modify-write across concurrent batches
@@ -755,7 +756,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
reduceErr = fmt.Errorf("wiki reduce panicked for slug %s: %v", slug, r)
}
}()
- changed, affectedType, additionFailed, reduceErr = s.reduceSlugUpdates(
+ changed, affectedType, additionFailed, updateDeferred, reduceErr = s.reduceSlugUpdates(
reduceCtx, chatModel, payload.KnowledgeBaseID, slug, updates, payload.TenantID, batchCtx, kidToWikiSpan)
return reduceErr
})
@@ -774,6 +775,18 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
collectUnapplied(updates)
return nil
}
+ if updateDeferred {
+ // The page kept its previous body because the rewrite dropped
+ // table rows that are still on it. Not an error and the page is
+ // not damaged, but this slug's contribution never landed, so the
+ // documents behind it must survive the trim phase and come back
+ // in a later batch — trimming them here would delete their
+ // pending row and lose the addition for good.
+ logger.Warnf(reduceCtx,
+ "wiki ingest: slug %s kept its previous content (rewrite dropped rows), deferring update",
+ slug)
+ collectUnapplied(updates)
+ }
if reduceErr != nil {
// The page's read-modify-write failed, so this slug's update
// never landed. Re-queue the contributing documents (same
@@ -1858,6 +1871,11 @@ func resolveSlugUpdateLanguage(ctx context.Context, updates []SlugUpdate) string
// refreshed for it. Callers use this to sanitize dead [[slug]] links
// elsewhere (e.g. in the doc's summary page) and to drop the slug from
// the wiki log feed so users don't see a clickable entry that 404s.
+// - updateDeferred: true iff the page write was refused by the row guard
+// (ErrWikiWriteDroppedTableRows): the page kept its previous body, so this
+// slug's contribution never landed and its documents must be re-queued
+// rather than trimmed. Distinct from err: a successful write that changes
+// nothing user-visible also leaves `version` alone, and that one IS applied.
// - err: transport / repo error from the persisted upsert.
func (s *wikiIngestService) reduceSlugUpdates(
ctx context.Context,
@@ -1868,7 +1886,7 @@ func (s *wikiIngestService) reduceSlugUpdates(
tenantID uint64,
batchCtx *WikiBatchContext,
kidToWikiSpan map[string]*Span,
-) (changed bool, affectedType string, additionFailed bool, err error) {
+) (changed bool, affectedType string, additionFailed bool, updateDeferred bool, err error) {
// Final safety net for the ingest/delete race: between Map (which already
// checks isKnowledgeGone) and Reduce there is a long LLM call where the
// source document may be deleted. Drop any addition/summary updates whose
@@ -1877,10 +1895,10 @@ func (s *wikiIngestService) reduceSlugUpdates(
// want when the doc is gone.
updates, err = s.filterLiveUpdates(ctx, kbID, updates)
if err != nil {
- return false, "", false, err
+ return false, "", false, false, err
}
if len(updates) == 0 {
- return false, "", false, nil
+ return false, "", false, false, nil
}
// Per-slug page span attribution: a single slug can receive
@@ -1964,7 +1982,7 @@ func (s *wikiIngestService) reduceSlugUpdates(
}
}
if !hasAdditions {
- return false, "", false, nil
+ return false, "", false, false, nil
}
page = &types.WikiPage{
@@ -2015,11 +2033,17 @@ func (s *wikiIngestService) reduceSlugUpdates(
changed = true
if exists {
- _, err = s.wikiService.UpdatePage(ctx, page)
+ // A summary rewrite can drop table rows too, and the refusal has
+ // the same meaning here: the page kept its previous body, so this
+ // slug's contribution never landed and its documents must survive
+ // the trim phase. Classify the explicit signal; do not read it off
+ // the page version.
+ _, writeErr := s.wikiService.UpdatePage(ctx, page)
+ updateDeferred, err = classifyWikiPageWrite(writeErr)
} else {
_, err = s.wikiService.CreatePage(ctx, page)
}
- return changed, affectedType, false, err
+ return changed, affectedType, false, updateDeferred, err
}
var remainingSourcesContent strings.Builder
@@ -2270,14 +2294,51 @@ func (s *wikiIngestService) reduceSlugUpdates(
// on top of what was already there, deduplicated.
page.ChunkRefs = mergeChunkRefs(page.ChunkRefs, additions)
if exists {
- _, err = s.wikiService.UpdatePage(ctx, page)
+ // A retraction removes a deleted document's contribution on
+ // purpose, so this write is allowed to drop the table rows that
+ // contribution owned. Saying so explicitly is what lets the choke
+ // point in UpdatePage refuse an accidental truncation everywhere
+ // else; without it a retract round would be refused and the stale
+ // content would stay on the page for good.
+ writeCtx := ctx
+ if len(retracts) > 0 {
+ writeCtx = types.WithWikiShrinkAllowed(ctx)
+ }
+ // UpdatePage refuses a machine rewrite that drops too many table
+ // rows still on the page and says so with
+ // ErrWikiWriteDroppedTableRows. That refusal is not a failure — the
+ // page is intact and this caller did nothing wrong — but it does
+ // mean this slug's contribution never landed, and its documents
+ // must be kept for a later batch. The version cannot stand in for
+ // that signal: a successful write that changes nothing
+ // user-visible leaves `version` alone too (see the version-bump
+ // policy in wiki_page.go), so only the explicit refusal is
+ // classified as deferred.
+ _, updateErr := s.wikiService.UpdatePage(writeCtx, page)
+ updateDeferred, err = classifyWikiPageWrite(updateErr)
} else {
_, err = s.wikiService.CreatePage(ctx, page)
}
- return true, affectedType, additionFailed, err
+ return true, affectedType, additionFailed, updateDeferred, err
}
- return false, "", additionFailed, nil
+ return false, "", additionFailed, false, nil
+}
+
+// classifyWikiPageWrite turns the result of one guarded UpdatePage call into
+// the reduce phase's (updateDeferred, err) pair.
+//
+// ErrWikiWriteDroppedTableRows means the row guard refused the write: the page
+// was not modified, but nothing failed, so the caller must keep this slug's
+// contributing documents for a later batch (updateDeferred) instead of
+// reporting an error. Every other outcome — including a successful write that
+// only refreshed bookkeeping and therefore did not bump `version` — was
+// applied and is not deferred.
+func classifyWikiPageWrite(updateErr error) (deferred bool, err error) {
+ if errors.Is(updateErr, ErrWikiWriteDroppedTableRows) {
+ return true, nil
+ }
+ return false, updateErr
}
// mergeChunkRefs unions the chunk IDs currently on the page with the ones
diff --git a/internal/application/service/wiki_ingest_cancellation_test.go b/internal/application/service/wiki_ingest_cancellation_test.go
index aa764eb76..7e0bf094c 100644
--- a/internal/application/service/wiki_ingest_cancellation_test.go
+++ b/internal/application/service/wiki_ingest_cancellation_test.go
@@ -56,7 +56,7 @@ func TestWikiReducePreservesLookupFailures(t *testing.T) {
svc := &wikiIngestService{knowledgeSvc: &wikiKnowledgeLookupStub{
lookup: func(context.Context, string) (*types.Knowledge, error) { return nil, lookupErr },
}}
- changed, _, _, err := svc.reduceSlugUpdates(context.Background(), nil, "kb-1", "entity/example",
+ changed, _, _, _, err := svc.reduceSlugUpdates(context.Background(), nil, "kb-1", "entity/example",
[]SlugUpdate{{Slug: "entity/example", Type: "entity", KnowledgeID: "k-1"}}, 7, nil, nil)
require.ErrorIs(t, err, lookupErr)
assert.False(t, changed)
diff --git a/internal/application/service/wiki_ingest_reduce_row_guard_test.go b/internal/application/service/wiki_ingest_reduce_row_guard_test.go
new file mode 100644
index 000000000..b36e1a379
--- /dev/null
+++ b/internal/application/service/wiki_ingest_reduce_row_guard_test.go
@@ -0,0 +1,177 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+// liveKnowledgeStub keeps filterLiveUpdates from dropping the test's addition:
+// reduce treats an unreadable knowledge as deleted and skips the whole slug.
+type liveKnowledgeStub struct{ interfaces.KnowledgeService }
+
+func (liveKnowledgeStub) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
+ return &types.Knowledge{ID: "k-row-guard", ParseStatus: types.ParseStatusCompleted}, nil
+}
+
+// reduceGuardedEntityPage runs one reduce round for an entity page over a real
+// wiki page store, with modelResponse as the editor's answer. The returned
+// updateDeferred is what ProcessWikiIngest turns into collectUnapplied — the
+// set of knowledge ids kept out of the trim phase so a later batch retries them.
+func reduceGuardedEntityPage(
+ t *testing.T, svc *wikiIngestService, slug, modelResponse string,
+) (deferred bool, err error) {
+ t.Helper()
+ model := &templateCaptureChatModel{response: modelResponse}
+ batchCtx := &WikiBatchContext{
+ SlugTitleMany: func(context.Context, []string) map[string]string { return nil },
+ }
+ updates := []SlugUpdate{{
+ Slug: slug,
+ Type: types.WikiPageTypeEntity,
+ KnowledgeID: "k-row-guard",
+ DocTitle: "证书台账",
+ SourceRef: "k-row-guard|证书台账",
+ Item: extractedItem{Name: "证书台账", Description: "持证人员明细"},
+ }}
+ _, _, _, deferred, err = svc.reduceSlugUpdates(
+ context.Background(), model, "kb-row-guard", slug, updates, 1, batchCtx, nil)
+ return deferred, err
+}
+
+// Regression for the version-based deferral signal: UpdatePage leaves `version`
+// alone for a successful write that changes nothing user-visible (identical
+// body with refreshed bookkeeping — see the version-bump policy in
+// wiki_page.go). Reading "same version" as "the guard refused" re-queued those
+// applied contributions forever, so reduce must see no refusal here.
+func TestReduceSlugUpdatesDoesNotDeferAWriteThatChangedNothing(t *testing.T) {
+ // reduce splits the SUMMARY line off with strings.TrimSpace, so the stored
+ // body has to be the trimmed form for the editor's identical answer to be
+ // a true no-op.
+ stored := strings.TrimSpace(ledger("PMP", "张三", "李四", "王五"))
+ pageSvc, page := newWikiWriteGuardStore(t, stored)
+ svc := &wikiIngestService{wikiService: pageSvc, knowledgeSvc: liveKnowledgeStub{}}
+
+ // The editor re-emits the stored page verbatim; only source_refs change.
+ deferred, err := reduceGuardedEntityPage(t, svc, "entity/pmp", stored)
+
+ require.NoError(t, err)
+ require.False(t, deferred,
+ "a successful write that did not bump the version is applied, not deferred")
+
+ after, err := pageSvc.GetPageBySlug(context.Background(), "kb-row-guard", "entity/pmp")
+ require.NoError(t, err)
+ require.Equal(t, stored, after.Content)
+ require.Equal(t, page.Version, after.Version,
+ "the write really was a no-op, so the version must not move")
+}
+
+// The other half of the same regression: a write the row guard really refused
+// was never applied, so its contributing documents must survive the trim phase
+// and come back in a later batch.
+func TestReduceSlugUpdatesDefersAWriteTheRowGuardRefused(t *testing.T) {
+ stored := ledger("PMP", "张三", "李四", "王五", "赵六", "钱七")
+ pageSvc, page := newWikiWriteGuardStore(t, stored)
+ svc := &wikiIngestService{wikiService: pageSvc, knowledgeSvc: liveKnowledgeStub{}}
+
+ // Four of the five stored identities are gone: far above the ingest limit,
+ // so UpdatePage refuses and reduce must defer instead of reporting success.
+ deferred, err := reduceGuardedEntityPage(t, svc, "entity/pmp", ledger("PMP", "张三"))
+
+ require.NoError(t, err, "a guard refusal is not a reduce failure")
+ require.True(t, deferred,
+ "the refused contribution must be kept for a later batch")
+
+ after, err := pageSvc.GetPageBySlug(context.Background(), "kb-row-guard", "entity/pmp")
+ require.NoError(t, err)
+ require.Equal(t, stored, after.Content)
+ require.Equal(t, page.Version, after.Version)
+}
+
+// A same-identity merge is inside the ingest tolerance, so the write lands and
+// the documents are not re-queued.
+func TestReduceSlugUpdatesAppliesAMergeInsideTheLossLimit(t *testing.T) {
+ stored := ledger("证书", "张三", "张三", "李四", "王五")
+ pageSvc, page := newWikiWriteGuardStore(t, stored)
+ svc := &wikiIngestService{wikiService: pageSvc, knowledgeSvc: liveKnowledgeStub{}}
+
+ merged := ledger("证书", "张三", "李四", "王五")
+ deferred, err := reduceGuardedEntityPage(t, svc, "entity/pmp", merged)
+
+ require.NoError(t, err)
+ require.False(t, deferred)
+ after, err := pageSvc.GetPageBySlug(context.Background(), "kb-row-guard", "entity/pmp")
+ require.NoError(t, err)
+ require.Equal(t, strings.TrimSpace(merged), after.Content)
+ require.Equal(t, page.Version+1, after.Version)
+}
+
+// Only the guard's own signal counts as a deferral: a genuine write failure is
+// still an error, and the caller's reduceErr path (not the deferred path) owns
+// it.
+func TestReduceSlugUpdatesSurfacesAGenuineWriteError(t *testing.T) {
+ writeErr := errors.New("postgres unavailable")
+ svc := &wikiIngestService{
+ wikiService: &failingPageWriteStub{page: &types.WikiPage{Slug: "entity/pmp"}, err: writeErr},
+ knowledgeSvc: liveKnowledgeStub{},
+ }
+
+ deferred, err := reduceGuardedEntityPage(t, svc, "entity/pmp", ledger("PMP", "张三"))
+
+ require.ErrorIs(t, err, writeErr)
+ require.False(t, deferred)
+}
+
+type failingPageWriteStub struct {
+ interfaces.WikiPageService
+ page *types.WikiPage
+ err error
+}
+
+func (s *failingPageWriteStub) GetPageBySlug(context.Context, string, string) (*types.WikiPage, error) {
+ return s.page, nil
+}
+
+func (s *failingPageWriteStub) UpdatePage(context.Context, *types.WikiPage) (*types.WikiPage, error) {
+ return nil, s.err
+}
+
+// classifyWikiPageWrite is the whole decision table: the sentinel (bare or
+// wrapped, as UpdatePage returns it) defers; everything else is passed through.
+func TestClassifyWikiPageWrite(t *testing.T) {
+ writeErr := errors.New("postgres unavailable")
+ unrelated := errors.New("dropped rows")
+ cases := []struct {
+ name string
+ in error
+ deferred bool
+ wantErr error
+ }{
+ {"applied write", nil, false, nil},
+ {"bare refusal", ErrWikiWriteDroppedTableRows, true, nil},
+ {
+ "wrapped refusal",
+ fmt.Errorf("update wiki page: %w", ErrWikiWriteDroppedTableRows),
+ true, nil,
+ },
+ {"write failure", writeErr, false, writeErr},
+ {"unrelated error", unrelated, false, unrelated},
+ }
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ deferred, err := classifyWikiPageWrite(testCase.in)
+ require.Equal(t, testCase.deferred, deferred)
+ if testCase.wantErr == nil {
+ require.NoError(t, err)
+ return
+ }
+ require.ErrorIs(t, err, testCase.wantErr)
+ })
+ }
+}
diff --git a/internal/application/service/wiki_page.go b/internal/application/service/wiki_page.go
index 3e38a5cc0..3755f211f 100644
--- a/internal/application/service/wiki_page.go
+++ b/internal/application/service/wiki_page.go
@@ -13,6 +13,7 @@ import (
"github.com/Tencent/WeKnora/internal/application/access"
"github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/common"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -132,6 +133,92 @@ func (s *wikiPageService) UpdatePage(ctx context.Context, page *types.WikiPage)
}
stripWikiPageInlineChunkCitations(page)
+ // ── Truncation choke point ────────────────
+ //
+ // Machine edits hand the *whole* page to a model and persist whatever comes
+ // back, and markdown tables are the shape it gets wrong most often: a
+ // hundred-row certificate ledger returns with thirty rows, finish_reason=
+ // stop, no provider error. That is not the completion-budget truncation
+ // handled on the ingest side (which continues and then refuses) — the answer
+ // is complete, it is simply short on rows. Storing it shrinks the page with
+ // no error, no failed addition, and a revision entry that reads like any
+ // other edit. Measured on a table-heavy knowledge base: a bulk ingest left a
+ // batch of untouched pages shorter than before it ran.
+ //
+ // The check lives here, on the one write path every caller shares, because a
+ // guard in the ingest caller only covers the ingest caller: the agent's
+ // whole-page writer hands its own model output to this same method.
+ //
+ // The two machine callers get different allowances:
+ //
+ // - The agent's whole-page writer can be told to try again, so it is held
+ // to "no stored row identity may vanish": its loss limit is zero and any
+ // loss refuses the write, which the tool returns to the model so it can
+ // re-emit the page (or switch to exact-text replacement).
+ // - Ingest cannot retry cheaply — a refusal keeps the contributing
+ // documents queued for another full Map and spends their retry budget —
+ // and its editor prompt explicitly allows de-duplicating rows, so only a
+ // loss STRICTLY above wikiWriteIngestRowIdentityLossLimit counts as
+ // truncation. The ratio is computed over distinct identities (see
+ // wikiWriteUniqueRowIdentityCount), never over row counts.
+ //
+ // Deliberate shrinkages are exempt: a human deleting rows through the wiki
+ // UI, a revert to an older (possibly shorter) revision, and any caller that
+ // knows it is removing content and says so with types.WithWikiShrinkAllowed
+ // (the ingest retract path and the agent's exact-text replacement do).
+ source := types.WikiEditSourceFromContext(ctx)
+ if source != types.WikiEditSourceUser && source != types.WikiEditSourceRevert &&
+ !types.WikiShrinkAllowedFromContext(ctx) {
+ if missing := wikiWriteMissingRowIdentities(existing.Content, page.Content); len(missing) > 0 {
+ storedIdentities := wikiWriteUniqueRowIdentityCount(existing.Content)
+ lossRatio := wikiWriteRowIdentityLossRatio(len(missing), storedIdentities)
+ lossLimit := wikiWriteIngestRowIdentityLossLimit
+ if source == types.WikiEditSourceAgent {
+ lossLimit = 0
+ }
+ if lossRatio > lossLimit {
+ examples := strings.Join(wikiWriteDroppedRowExamples(missing), ", ")
+ // Identities, not rows: several rows of the stored page may
+ // share one identity, and mixing the two counts would make the
+ // ratio unreadable.
+ logger.Warnf(ctx,
+ "wiki page write refused (rewrite dropped %d of %d distinct table row identities, "+
+ "ratio %.2f > limit %.2f): slug=%s source=%s content %d -> %d chars; "+
+ "keeping the stored version (e.g. %s)",
+ len(missing), storedIdentities, lossRatio, lossLimit, page.Slug, source,
+ len(existing.Content), len(page.Content), examples)
+ common.PipelineWarn(ctx, "WikiWrite", "page_write_dropped_table_rows", map[string]interface{}{
+ "slug": page.Slug,
+ "source": source,
+ "stored_identities": storedIdentities,
+ "missing_identities": len(missing),
+ "loss_ratio": lossRatio,
+ "loss_limit": lossLimit,
+ "examples": examples,
+ })
+ // The refusal is an explicit error, not "the stored page came
+ // back unchanged": a successful write that changes nothing
+ // user-visible leaves `version` alone too (see the version-bump
+ // policy above), so the version cannot tell a caller whether
+ // its write landed. Ingest maps this sentinel to a deferred
+ // update — the documents behind it are kept for a later batch
+ // instead of being trimmed — while the agent surfaces it to the
+ // model, which can re-emit the rows.
+ return nil, fmt.Errorf(
+ "%w: slug %s lost %d of %d table row identities (e.g. %s); the stored page is unchanged",
+ ErrWikiWriteDroppedTableRows, page.Slug, len(missing), storedIdentities, examples)
+ }
+ // Inside the ingest tolerance: the rewrite is written, and the loss
+ // is recorded for anyone tuning the limit. The identity is only the
+ // row's first non-empty cell, so a tolerated loss may be a merge of
+ // same-identity rows and says nothing about their other columns.
+ logger.Debugf(ctx,
+ "wiki page write kept a rewrite that dropped %d of %d distinct table row identities "+
+ "(ratio %.2f <= limit %.2f): slug=%s source=%s",
+ len(missing), storedIdentities, lossRatio, lossLimit, page.Slug, source)
+ }
+ }
+
oldOutLinks := existing.OutLinks
// Snapshot user-visible fields BEFORE mutation so we can decide whether
diff --git a/internal/application/service/wiki_write_row_guard.go b/internal/application/service/wiki_write_row_guard.go
new file mode 100644
index 000000000..dd2533a10
--- /dev/null
+++ b/internal/application/service/wiki_write_row_guard.go
@@ -0,0 +1,187 @@
+package service
+
+import (
+ "errors"
+ "sort"
+ "strings"
+)
+
+// ErrWikiWriteDroppedTableRows is the explicit refusal signal a machine write
+// gets when the incoming body no longer carries table rows the stored page
+// still has. The stored page is left untouched.
+//
+// It is returned for both guarded policies — see UpdatePage — and it exists
+// because an unchanged `version` cannot stand in for it: UpdatePage leaves the
+// version alone for a successful write that changes nothing user-visible, so
+// callers that must retry a refused contribution (wiki ingest's reduce) need a
+// signal of its own. See wikiWriteMissingRowIdentities.
+var ErrWikiWriteDroppedTableRows = errors.New("wiki page write dropped table rows the stored page still has")
+
+// wikiWriteGuardLogLimit caps how many example row identities a refusal names.
+const wikiWriteGuardLogLimit = 5
+
+// wikiWriteIngestRowIdentityLossLimit is the largest share of a stored page's
+// distinct row identities that an ingest rewrite may stop carrying and still be
+// written: it refuses only when the loss is strictly GREATER than this, so a
+// rewrite that loses exactly one identity in five (0.20) goes through.
+//
+// Ingest needs the tolerance because its editor prompt explicitly allows
+// de-duplicating rows, and a refused write keeps the contributing documents
+// queued for another full Map — a legitimate de-duplication that tripped the
+// guard on every batch would spend the documents' retry budget and end in the
+// dead-letter lane with their additions never stored. The agent's whole-page
+// writer has no such allowance; see UpdatePage.
+const wikiWriteIngestRowIdentityLossLimit = 0.20
+
+// wikiWriteEmphasisMarkers are the inline markers that change how a cell
+// renders but not which entity it names, so they are ignored when comparing
+// one spelling of a row against another.
+var wikiWriteEmphasisMarkers = strings.NewReplacer("*", "", "_", "", "`", "")
+
+// isWikiWriteTableRow reports whether line is a markdown table row: trimmed it
+// starts with '|' and carries at least two pipes. A single pipe is a stray
+// character in prose, not a table.
+func isWikiWriteTableRow(line string) bool {
+ trimmed := strings.TrimSpace(line)
+ return strings.HasPrefix(trimmed, "|") && strings.Count(trimmed, "|") >= 2
+}
+
+// isWikiWriteDelimiterRow reports whether line is the `| --- | :--: |` row that
+// separates a table's header from its data: every cell is built only from '-',
+// ':' and spaces. The delimiter names no entity of its own.
+func isWikiWriteDelimiterRow(line string) bool {
+ for _, cell := range strings.Split(line, "|") {
+ if strings.Trim(cell, "-: \t") != "" {
+ return false
+ }
+ }
+ return true
+}
+
+// normalizeWikiWriteCell makes two spellings of the same cell compare equal:
+// the full-width space becomes an ordinary one, emphasis/code markers are
+// dropped, whitespace runs collapse, and the result is lower-cased. Formatting
+// and case are the two things a model changes freely while re-emitting a page,
+// so neither may read as a lost row.
+func normalizeWikiWriteCell(cell string) string {
+ cell = strings.ReplaceAll(cell, "\u3000", " ")
+ cell = wikiWriteEmphasisMarkers.Replace(cell)
+ return strings.ToLower(strings.Join(strings.Fields(cell), " "))
+}
+
+// wikiWriteRowIdentity returns the normalized first non-empty cell of a table
+// row — the cell that says what the row is about — or "" when the row names
+// nothing at all.
+func wikiWriteRowIdentity(line string) string {
+ for _, cell := range strings.Split(line, "|") {
+ if identity := normalizeWikiWriteCell(cell); identity != "" {
+ return identity
+ }
+ }
+ return ""
+}
+
+// wikiWriteTableRowIdentities lists the data-row identities of every markdown
+// table in content, in file order. Header rows are skipped: the row directly
+// above the `| --- |` delimiter names columns, not entities, and a model
+// renames it freely, so counting it would refuse healthy rewrites.
+func wikiWriteTableRowIdentities(content string) []string {
+ lines := strings.Split(content, "\n")
+ identities := make([]string, 0, 8)
+ for i, line := range lines {
+ if !isWikiWriteTableRow(line) || isWikiWriteDelimiterRow(line) {
+ continue
+ }
+ if i+1 < len(lines) && isWikiWriteTableRow(lines[i+1]) && isWikiWriteDelimiterRow(lines[i+1]) {
+ continue
+ }
+ if identity := wikiWriteRowIdentity(line); identity != "" {
+ identities = append(identities, identity)
+ }
+ }
+ return identities
+}
+
+// wikiWriteUniqueRowIdentityCount counts the DISTINCT data-row identities in
+// content — the denominator of the loss ratio. Rows that name the same entity
+// in their first non-empty cell count once, however many times the page lists
+// them, so a page that repeats a holder does not dilute the ratio.
+func wikiWriteUniqueRowIdentityCount(content string) int {
+ identities := wikiWriteTableRowIdentities(content)
+ if len(identities) == 0 {
+ return 0
+ }
+ unique := make(map[string]struct{}, len(identities))
+ for _, identity := range identities {
+ unique[identity] = struct{}{}
+ }
+ return len(unique)
+}
+
+// wikiWriteRowIdentityLossRatio is the share of the stored page's distinct row
+// identities a rewrite no longer carries: missing / stored. A page with no
+// identifiable rows has no ratio (0).
+func wikiWriteRowIdentityLossRatio(missing, stored int) float64 {
+ if stored <= 0 {
+ return 0
+ }
+ return float64(missing) / float64(stored)
+}
+
+// wikiWriteMissingRowIdentities reports which data rows of existing are no
+// longer present in rewritten, as a sorted, de-duplicated list of identities.
+//
+// Rows are matched by identity rather than by whole line, so re-flowing
+// whitespace, bolding a name or updating a date/amount cell keeps the row
+// counted as present; only a row whose subject disappeared counts as lost.
+//
+// Identities are compared as a SET, not as a multiset: an identity is present
+// as soon as the rewrite carries it once, so merging two rows that share a
+// first non-empty cell into one is not a loss, however many times the stored
+// page listed them.
+//
+// The scope of that identity is deliberately narrow — it is only the row's
+// first non-empty cell — so this reports rows that vanished, not rows that
+// lost information: a rewrite that keeps the holder name but blanks, truncates
+// or rewrites the other columns is NOT reported. Merging same-identity rows is
+// therefore allowed without any guarantee that their remaining columns stay
+// complete; the guard catches truncation, not cell-level data loss.
+func wikiWriteMissingRowIdentities(existing, rewritten string) []string {
+ oldIdentities := wikiWriteTableRowIdentities(existing)
+ if len(oldIdentities) == 0 {
+ return nil
+ }
+ // Set membership, not occurrence count: presence anywhere in the rewrite
+ // keeps an identity alive.
+ present := make(map[string]struct{}, len(oldIdentities))
+ for _, identity := range wikiWriteTableRowIdentities(rewritten) {
+ present[identity] = struct{}{}
+ }
+ missing := make([]string, 0, 4)
+ reported := make(map[string]struct{}, 4)
+ for _, identity := range oldIdentities {
+ if _, ok := present[identity]; ok {
+ continue
+ }
+ // The same identity can appear on several stored rows; an identity
+ // that is gone is one lost identity, not one per row.
+ if _, ok := reported[identity]; ok {
+ continue
+ }
+ reported[identity] = struct{}{}
+ missing = append(missing, identity)
+ }
+ if len(missing) == 0 {
+ return nil
+ }
+ sort.Strings(missing)
+ return missing
+}
+
+// wikiWriteDroppedRowExamples caps a missing-row list for a log line.
+func wikiWriteDroppedRowExamples(missing []string) []string {
+ if len(missing) > wikiWriteGuardLogLimit {
+ return missing[:wikiWriteGuardLogLimit]
+ }
+ return missing
+}
diff --git a/internal/application/service/wiki_write_row_guard_test.go b/internal/application/service/wiki_write_row_guard_test.go
new file mode 100644
index 000000000..ab8df9928
--- /dev/null
+++ b/internal/application/service/wiki_write_row_guard_test.go
@@ -0,0 +1,314 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+)
+
+// ledger is the shape that regressed in production: the rows ARE the data, so a
+// rewrite that drops some of them shrinks the page. The first column names the
+// holder, and the guard keys a row on exactly that column.
+func ledger(title string, holders ...string) string {
+ body := "# " + title + "\n\n## 持证人员明细\n\n" +
+ "| 姓名 | 证书编号 | 有效期止 |\n| --- | --- | --- |\n"
+ for _, holder := range holders {
+ body += "| " + holder + " | CERT-2020 | 2099-01-01 |\n"
+ }
+ return body
+}
+
+func TestWikiWriteMissingRowIdentities(t *testing.T) {
+ full := ledger("PMP", "张三", "李四", "王五")
+ cases := []struct {
+ name string
+ existing string
+ rewritten string
+ want []string
+ }{
+ {"identical body keeps every row", full, full, nil},
+ {
+ "reordered rows are all still there",
+ full, ledger("PMP", "王五", "张三", "李四"), nil,
+ },
+ {
+ "emphasis, padding and case changes are not lost rows",
+ full, ledger("PMP", "**张三**", " 李四 ", "王五"), nil,
+ },
+ {
+ "a renamed header is not a lost row",
+ full,
+ "# PMP 证书\n\n## 持证人员明细\n\n" +
+ "| 持证人 | 证书编号 | 有效期至 |\n| --- | --- | --- |\n" +
+ "| 张三 | CERT-2020 | 2099-01-01 |\n| 李四 | CERT-2020 | 2099-01-01 |\n" +
+ "| 王五 | CERT-2020 | 2099-01-01 |\n",
+ nil,
+ },
+ {
+ "an added row is not a loss",
+ full, ledger("PMP", "张三", "李四", "王五", "赵六"), nil,
+ },
+ {"prose-only pages have nothing to guard", "just prose", "shorter prose", nil},
+ {
+ "one dropped row is reported",
+ full, ledger("PMP", "张三", "李四"),
+ []string{"王五"},
+ },
+ {
+ "a truncated rewrite reports every missing row",
+ full, ledger("PMP", "张三"),
+ []string{"李四", "王五"},
+ },
+ }
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ require.Equal(t, testCase.want,
+ wikiWriteMissingRowIdentities(testCase.existing, testCase.rewritten))
+ })
+ }
+}
+
+// Duplicate identities are compared as a set, not as a multiset: two stored
+// rows whose first non-empty cell is the same are ONE identity, so a rewrite
+// that keeps it once has kept it — merging them into one row is not a loss.
+// Only when the identity no longer appears at all is it reported, and then
+// once, not once per stored row.
+func TestWikiWriteMissingRowIdentitiesComparesIdentitiesAsASet(t *testing.T) {
+ existing := ledger("证书", "张三", "张三")
+ require.Empty(t, wikiWriteMissingRowIdentities(existing, ledger("证书", "张三")))
+ require.Equal(t, []string{"张三"}, wikiWriteMissingRowIdentities(existing, ledger("证书")))
+}
+
+// The ratio denominator is the number of DISTINCT identities: repeating a
+// holder on the stored page must not dilute the share of identities lost, or a
+// page full of duplicates could lose whole subjects under the threshold.
+func TestWikiWriteUniqueRowIdentityCountCountsEachIdentityOnce(t *testing.T) {
+ require.Equal(t, 0, wikiWriteUniqueRowIdentityCount("just prose"))
+ require.Equal(t, 1, wikiWriteUniqueRowIdentityCount(ledger("证书", "张三", "张三")))
+ repeated := ledger("证书", "张三", "张三", "李四", "王五", "李四")
+ require.Equal(t, 3, wikiWriteUniqueRowIdentityCount(repeated))
+}
+
+// The threshold boundary is exact: a loss of exactly 20% is allowed, anything
+// above it is not, and an empty stored identity set has no ratio at all.
+func TestWikiWriteRowIdentityLossRatioBoundary(t *testing.T) {
+ require.Equal(t, 0.0, wikiWriteRowIdentityLossRatio(2, 0), "an empty identity set cannot lose anything")
+ require.LessOrEqual(t, wikiWriteRowIdentityLossRatio(1, 5), wikiWriteIngestRowIdentityLossLimit)
+ require.Greater(t, wikiWriteRowIdentityLossRatio(1, 4), wikiWriteIngestRowIdentityLossLimit)
+}
+
+// The row above a `| --- |` delimiter names columns rather than an entity, and
+// every table in the page is surveyed: a rewrite that keeps one table intact
+// while emptying another is still a truncation.
+func TestWikiWriteTableRowIdentitiesSkipsHeadersAndCoversEveryTable(t *testing.T) {
+ content := "| 姓名 | 证书编号 |\n| --- | --- |\n| 张三 | CERT-1 |\n\nprose\n\n" +
+ "| 项目 | 金额 |\n| --- | --- |\n| 差旅 | 100 |\n| 会务 | 200 |\n"
+ require.Equal(t, []string{"张三", "差旅", "会务"}, wikiWriteTableRowIdentities(content))
+
+ rewritten := "| 姓名 | 证书编号 |\n| --- | --- |\n| 张三 | CERT-1 |\n\nprose\n\n" +
+ "| 项目 | 金额 |\n| --- | --- |\n| 差旅 | 100 |\n"
+ require.Equal(t, []string{"会务"}, wikiWriteMissingRowIdentities(content, rewritten))
+}
+
+// A row whose first cell is empty still names an entity in its next non-empty
+// cell, so it is counted rather than silently ignored.
+func TestWikiWriteRowIdentityFallsBackToTheNextNonEmptyCell(t *testing.T) {
+ content := "| 姓名 | 证书编号 |\n| --- | --- |\n| | CERT-1 |\n"
+ require.Equal(t, []string{"cert-1"}, wikiWriteTableRowIdentities(content))
+}
+
+// prose that merely mentions a pipe is not a table, so it cannot be read as one
+// losing rows.
+func TestWikiWriteTableRowIdentitiesIgnoresLonePipesInProse(t *testing.T) {
+ require.Empty(t, wikiWriteTableRowIdentities("a | b\n\nc"))
+}
+
+func newWikiWriteGuardHarness(t *testing.T) (interfaces.WikiPageService, *types.WikiPage) {
+ t.Helper()
+ return newWikiWriteGuardStore(t, ledger("PMP", "张三", "李四", "王五"))
+}
+
+// newWikiWriteGuardStore builds the same isolated page store as
+// newWikiWriteGuardHarness, with a caller-chosen stored body.
+func newWikiWriteGuardStore(t *testing.T, content string) (interfaces.WikiPageService, *types.WikiPage) {
+ t.Helper()
+ db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
+
+ ctx := context.Background()
+ svc := NewWikiPageService(repository.NewWikiPageRepository(db), nil, nil, nil, nil, nil)
+ page, err := svc.CreatePage(ctx, &types.WikiPage{
+ TenantID: 1, KnowledgeBaseID: "kb-row-guard", Slug: "entity/pmp",
+ Title: "PMP", PageType: types.WikiPageTypeEntity,
+ Content: content,
+ })
+ require.NoError(t, err)
+ return svc, page
+}
+
+// ledgerHolders builds n distinct ledger identities.
+func ledgerHolders(n int) []string {
+ names := make([]string, 0, n)
+ for i := 1; i <= n; i++ {
+ names = append(names, fmt.Sprintf("持证人%02d", i))
+ }
+ return names
+}
+
+// An ingest rewrite that loses more than the threshold is refused with an
+// explicit signal, and the stored page survives the refusal untouched.
+func TestUpdatePageRefusesAnIngestRewriteAboveTheLossLimit(t *testing.T) {
+ // Four stored identities, one gone: 25% > 20%.
+ svc, page := newWikiWriteGuardStore(t, ledger("PMP", ledgerHolders(4)...))
+ ctx := context.Background()
+
+ truncated := *page
+ truncated.Content = ledger("PMP", ledgerHolders(4)[:3]...)
+ kept, err := svc.UpdatePage(ctx, &truncated)
+ require.ErrorIs(t, err, ErrWikiWriteDroppedTableRows)
+ require.Nil(t, kept, "a refused write has no updated page to hand back")
+
+ stored, err := svc.GetPageBySlug(ctx, "kb-row-guard", "entity/pmp")
+ require.NoError(t, err)
+ require.Equal(t, page.Content, stored.Content, "the stored body must survive the refusal")
+ require.Equal(t, page.Version, stored.Version, "a refusal is not an edit")
+}
+
+// The tolerance is a strictly-greater-than limit: losing exactly one identity
+// in five (20%) is written, and the version advances like any other edit.
+func TestUpdatePageWritesAnIngestRewriteAtTheLossLimit(t *testing.T) {
+ svc, page := newWikiWriteGuardStore(t, ledger("PMP", ledgerHolders(5)...))
+ rewritten := *page
+ rewritten.Content = ledger("PMP", ledgerHolders(5)[:4]...)
+
+ updated, err := svc.UpdatePage(context.Background(), &rewritten)
+ require.NoError(t, err)
+ require.Equal(t, rewritten.Content, updated.Content)
+ require.Equal(t, page.Version+1, updated.Version)
+}
+
+// Below the limit is written too: one identity gone out of ten is 10%.
+func TestUpdatePageWritesAnIngestRewriteBelowTheLossLimit(t *testing.T) {
+ svc, page := newWikiWriteGuardStore(t, ledger("PMP", ledgerHolders(10)...))
+ rewritten := *page
+ rewritten.Content = ledger("PMP", ledgerHolders(10)[:9]...)
+
+ updated, err := svc.UpdatePage(context.Background(), &rewritten)
+ require.NoError(t, err)
+ require.Equal(t, rewritten.Content, updated.Content)
+ require.Equal(t, page.Version+1, updated.Version)
+}
+
+// An ingest rewrite that keeps every stored identity while de-duplicating a
+// repeated row is a normal write: identities are compared as a set, so merging
+// the two 张三 rows into one loses nothing. Under occurrence counting this was
+// a refusal on every batch.
+func TestUpdatePageWritesAnIngestRewriteThatMergesDuplicateRows(t *testing.T) {
+ svc, page := newWikiWriteGuardStore(t, ledger("证书", "张三", "张三", "李四", "王五"))
+ rewritten := *page
+ rewritten.Content = ledger("证书", "张三", "李四", "王五")
+
+ updated, err := svc.UpdatePage(context.Background(), &rewritten)
+ require.NoError(t, err)
+ require.Equal(t, rewritten.Content, updated.Content)
+ require.Equal(t, page.Version+1, updated.Version)
+}
+
+// The ratio denominator counts distinct identities, not rows: three stored rows
+// naming 张三 are one identity, so losing 李四 from that page is a loss of 1/3,
+// not of 1/5. Counting rows here would have let a whole subject disappear.
+func TestUpdatePageWeighsDuplicateIdentitiesOnceInTheLossRatio(t *testing.T) {
+ svc, page := newWikiWriteGuardStore(t, ledger("证书", "张三", "张三", "张三", "李四", "王五"))
+ rewritten := *page
+ rewritten.Content = ledger("证书", "张三", "王五")
+
+ kept, err := svc.UpdatePage(context.Background(), &rewritten)
+ require.ErrorIs(t, err, ErrWikiWriteDroppedTableRows)
+ require.Nil(t, kept)
+
+ stored, err := svc.GetPageBySlug(context.Background(), "kb-row-guard", "entity/pmp")
+ require.NoError(t, err)
+ require.Equal(t, page.Content, stored.Content)
+}
+
+// The agent's whole-page writer is told the write was refused, instead of being
+// told it edited a page it never touched.
+func TestUpdatePageReportsTheRefusalToTheAgentWriter(t *testing.T) {
+ svc, page := newWikiWriteGuardHarness(t)
+ ctx := types.WithWikiEditSource(context.Background(), types.WikiEditSourceAgent)
+
+ truncated := *page
+ truncated.Content = ledger("PMP", "张三")
+ _, err := svc.UpdatePage(ctx, &truncated)
+ require.ErrorIs(t, err, ErrWikiWriteDroppedTableRows)
+
+ stored, err := svc.GetPageBySlug(context.Background(), "kb-row-guard", "entity/pmp")
+ require.NoError(t, err)
+ require.Equal(t, page.Content, stored.Content)
+}
+
+// The agent gets no tolerance at all: a rewrite that loses exactly the share
+// ingest would accept is still refused, because the tool can hand the refusal
+// back to the model and ask it to re-emit the page.
+func TestUpdatePageRefusesForTheAgentAtTheIngestLossLimit(t *testing.T) {
+ svc, page := newWikiWriteGuardStore(t, ledger("PMP", ledgerHolders(5)...))
+ truncated := *page
+ truncated.Content = ledger("PMP", ledgerHolders(5)[:4]...)
+
+ // The agent's write loses 1 of 5 identities (exactly the ingest limit).
+ _, err := svc.UpdatePage(
+ types.WithWikiEditSource(context.Background(), types.WikiEditSourceAgent), &truncated)
+ require.ErrorIs(t, err, ErrWikiWriteDroppedTableRows)
+
+ // The same body is accepted when the ingest pipeline writes it.
+ updated, err := svc.UpdatePage(context.Background(), &truncated)
+ require.NoError(t, err)
+ require.Equal(t, truncated.Content, updated.Content)
+ require.Equal(t, page.Version+1, updated.Version)
+}
+
+// Deliberate shrinkages go through: a human deleting rows, a revert to an older
+// (possibly shorter) revision, and a caller that marked the write.
+func TestUpdatePageAllowsDeliberateShrinkage(t *testing.T) {
+ cases := []struct {
+ name string
+ ctx context.Context
+ }{
+ {"user edit", types.WithWikiEditSource(context.Background(), types.WikiEditSourceUser)},
+ {"revert", types.WithWikiEditSource(context.Background(), types.WikiEditSourceRevert)},
+ {"explicitly allowed", types.WithWikiShrinkAllowed(context.Background())},
+ {"retract round", types.WithWikiShrinkAllowed(
+ types.WithWikiEditSource(context.Background(), types.WikiEditSourcePipeline))},
+ }
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ svc, page := newWikiWriteGuardHarness(t)
+ truncated := *page
+ truncated.Content = ledger("PMP", "张三")
+ updated, err := svc.UpdatePage(testCase.ctx, &truncated)
+ require.NoError(t, err)
+ require.Equal(t, truncated.Content, updated.Content)
+ require.Equal(t, page.Version+1, updated.Version)
+ })
+ }
+}
+
+// A rewrite that keeps every row but reflows the table is an ordinary edit.
+func TestUpdatePageWritesARewriteThatKeepsEveryRow(t *testing.T) {
+ svc, page := newWikiWriteGuardHarness(t)
+ rewritten := *page
+ rewritten.Content = ledger("PMP 证书", "李四", "**张三**", "王五", "赵六")
+
+ updated, err := svc.UpdatePage(context.Background(), &rewritten)
+ require.NoError(t, err)
+ require.Equal(t, rewritten.Content, updated.Content)
+ require.Equal(t, page.Version+1, updated.Version)
+}
diff --git a/internal/types/const.go b/internal/types/const.go
index e20a2a067..8a63bc8c0 100644
--- a/internal/types/const.go
+++ b/internal/types/const.go
@@ -62,6 +62,10 @@ const (
// page write (user / agent / revert). Absent means the wiki ingest
// pipeline. See types.WithWikiEditSource.
WikiEditSourceContextKey ContextKey = "WikiEditSource"
+ // WikiShrinkAllowedContextKey marks one wiki page write as allowed to
+ // remove table rows the stored page still has; see
+ // types.WithWikiShrinkAllowed.
+ WikiShrinkAllowedContextKey ContextKey = "WikiShrinkAllowed"
// LanguageContextKey is the context key for user language preference (e.g. "zh-CN", "en-US")
LanguageContextKey ContextKey = "Language"
// EmbedVisitorContextKey is the anonymous visitor id for embed OAuth isolation.
diff --git a/internal/types/context_clone.go b/internal/types/context_clone.go
index f207f6abe..79b6ad940 100644
--- a/internal/types/context_clone.go
+++ b/internal/types/context_clone.go
@@ -110,6 +110,11 @@ var contextCloneAcrossDetach = map[ContextKey]bool{
// ingest pipeline, which is what detached work should look like; an
// inherited "user" would attribute a background rewrite to a person.
WikiEditSourceContextKey: false,
+ // One write's licence to remove table rows the stored page still has. A
+ // grant, and a detach must not widen it: the marker is put on the context
+ // immediately around a single write by a caller that knows the removal is
+ // deliberate, so it means nothing on any other context.
+ WikiShrinkAllowedContextKey: false,
// The parser engine resolved from one agent's ChatParserEngineRules for
// one attachment's file type. Read by the attachment processor on the same
// context that set it, and meaningless for anything else.
diff --git a/internal/types/context_helpers.go b/internal/types/context_helpers.go
index 35cdab262..f89429530 100644
--- a/internal/types/context_helpers.go
+++ b/internal/types/context_helpers.go
@@ -69,6 +69,25 @@ func WikiEditSourceFromContext(ctx context.Context) string {
return NormalizeWikiEditSource(v)
}
+// WithWikiShrinkAllowed marks ctx so ONE wiki page write may drop table rows
+// the stored page still carries.
+//
+// UpdatePage refuses such a write by default, because a model asked to re-emit
+// a whole page silently returns it with rows missing and the page then shrinks
+// with no trace. Callers that are removing content on purpose — a retraction
+// after a source document was deleted, an exact-text replacement that deletes
+// rows — say so here, and only for the write that does it.
+func WithWikiShrinkAllowed(ctx context.Context) context.Context {
+ return context.WithValue(ctx, WikiShrinkAllowedContextKey, true)
+}
+
+// WikiShrinkAllowedFromContext reports whether ctx was marked with
+// WithWikiShrinkAllowed.
+func WikiShrinkAllowedFromContext(ctx context.Context) bool {
+ v, _ := ctx.Value(WikiShrinkAllowedContextKey).(bool)
+ return v
+}
+
// WithEmbedQuery marks ctx as embedding a search query rather than content
// being indexed. Asymmetric retrieval models encode the two sides differently
// and lose accuracy when a query is embedded as a passage; the embedding