feat(snapshot): 增加整库独立快照及测试停写恢复基础
build / build (push) Successful in 1m20s

This commit is contained in:
姚章浩
2026-10-27 23:44:12 +08:00
parent 74aef1e373
commit 9105f8316c
27 changed files with 3511 additions and 0 deletions
@@ -0,0 +1,238 @@
package v071
import (
"bytes"
"context"
"encoding/json"
"errors"
"strings"
"time"
"knowledge-governance/internal/librarysnapshot"
)
// ArchiveLibraryCandidate persists independent recovery bytes. "Candidate" is
// intentional: matching IDs/counts does not prove shared Wiki semantic retraction
// or a common cross-system cut. No release worker consumes it as authorization.
func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archive, scope string, identity PostgresIdentity, contract librarysnapshot.Compatibility, pg PostgresSnapshot, es SearchSnapshot, objects ObjectReader, createdAt time.Time) (string, error) {
if archive == nil || objects == nil || identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) || identity.KnowledgeID != "" {
return "", errors.New("invalid library candidate configuration")
}
if err := validateLibraryCandidate(identity, pg, es); err != nil {
return "", err
}
if es.MappingSHA256 != contract.IndexMappingSHA256 {
return "", errors.New("library mapping contract mismatch")
}
manifest := librarysnapshot.Manifest{Format: librarysnapshot.Format, Scope: scope, TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, CreatedAt: createdAt, Compatibility: contract}
put := func(kind, name string, count int64, data []byte) error {
if err := ctx.Err(); err != nil {
return err
}
p, err := archive.Put(bytes.NewReader(data))
if err != nil {
return err
}
p.Kind = kind
p.Name = name
p.Count = count
manifest.Parts = append(manifest.Parts, p)
return nil
}
for _, table := range pg.Tables {
rows := table.Rows
if rows == nil {
rows = []json.RawMessage{}
}
data, err := json.Marshal(rows)
if err != nil {
return "", errors.New("encode library rows")
}
kind := "database"
if strings.HasPrefix(table.Name, "wiki_") {
kind = "wiki"
}
if err = put(kind, table.Name, int64(len(rows)), data); err != nil {
return "", err
}
}
documents := es.Documents
if documents == nil {
documents = []SearchDocument{}
}
data, err := json.Marshal(documents)
if err != nil {
return "", errors.New("encode library index")
}
if err = put("index", "chunks", int64(len(documents)), data); err != nil {
return "", err
}
for _, raw := range pg.Table("resources").Rows {
if err = ctx.Err(); err != nil {
return "", err
}
var resource struct {
ID string `json:"id"`
Provider string `json:"provider"`
PhysicalPath string `json:"physical_path"`
Size *int64 `json:"size"`
ContentHash string `json:"content_hash"`
}
if json.Unmarshal(raw, &resource) != nil || resource.Size == nil || *resource.Size < 0 || !validObjectProvider(resource.Provider) || !validObjectKey(resource.PhysicalPath) || resource.ContentHash != "" && !validLowerSHA256(resource.ContentHash) {
return "", errors.New("invalid library resource metadata")
}
reader, err := objects.Open(ctx, resource.Provider, resource.PhysicalPath)
if err != nil {
return "", errors.New("read library resource")
}
part, readErr := archive.Put(reader)
closeErr := reader.Close()
if readErr != nil || closeErr != nil {
return "", errors.New("archive library resource")
}
if part.Bytes != *resource.Size || resource.ContentHash != "" && part.SHA256 != resource.ContentHash {
return "", errors.New("library resource integrity mismatch")
}
part.Kind = "resource"
part.Name = resource.ID
part.Count = 1
manifest.Parts = append(manifest.Parts, part)
}
if err = ctx.Err(); err != nil {
return "", err
}
return archive.Seal(manifest)
}
type libraryRow struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeID string `json:"knowledge_id"`
ChunkID string `json:"chunk_id"`
TagID string `json:"tag_id"`
ResourceID string `json:"resource_id"`
Handle string `json:"handle"`
OwnerType string `json:"owner_type"`
OwnerID string `json:"owner_id"`
Content string `json:"content"`
}
func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error {
required := map[string]bool{"resources": true}
for _, entry := range libraryContentQueries {
required[entry.name] = true
}
tables := map[string]map[string]libraryRow{}
for _, table := range pg.Tables {
if !required[table.Name] || tables[table.Name] != nil || table.RowCount != len(table.Rows) || table.SHA256 != newTableSnapshot(table.Name, table.Rows).SHA256 {
return errors.New("invalid library table inventory")
}
rows := map[string]libraryRow{}
tables[table.Name] = rows
for _, raw := range table.Rows {
// Log identities are BIGSERIAL. All other owned rows use string IDs.
if table.Name == "wiki_log_entries" {
var row struct {
ID json.Number `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
}
if json.Unmarshal(raw, &row) != nil || row.ID == "" || row.TenantID != identity.TenantID || row.KnowledgeBaseID != identity.KnowledgeBaseID {
return errors.New("invalid Wiki log scope")
}
if _, ok := rows[string(row.ID)]; ok {
return errors.New("duplicate Wiki log identity")
}
rows[string(row.ID)] = libraryRow{}
continue
}
var row libraryRow
if json.Unmarshal(raw, &row) != nil {
return errors.New("invalid library content row")
}
if table.Name == "knowledge_tag_relations" {
if !validSearchIdentifier(row.KnowledgeID) || !validSearchIdentifier(row.TagID) {
return errors.New("invalid library tag relation")
}
row.ID = row.KnowledgeID + "/" + row.TagID
} else {
if !validSearchIdentifier(row.ID) || row.TenantID != identity.TenantID {
return errors.New("invalid library row identity")
}
if table.Name != "resources" && table.Name != "resource_bindings" && row.KnowledgeBaseID != identity.KnowledgeBaseID {
return errors.New("cross-scope library row")
}
}
if _, ok := rows[row.ID]; ok {
return errors.New("duplicate library row")
}
rows[row.ID] = row
}
}
for name := range required {
if tables[name] == nil {
return errors.New("missing library table")
}
}
for _, chunk := range tables["chunks"] {
if _, ok := tables["knowledges"][chunk.KnowledgeID]; !ok {
return errors.New("orphan library chunk")
}
}
for _, relation := range tables["knowledge_tag_relations"] {
_, hasKnowledge := tables["knowledges"][relation.KnowledgeID]
_, hasTag := tables["knowledge_tags"][relation.TagID]
if !hasKnowledge || !hasTag {
return errors.New("orphan library tag relation")
}
}
for _, binding := range tables["resource_bindings"] {
_, hasResource := tables["resources"][binding.ResourceID]
hasOwner := false
if binding.OwnerType == "knowledge" {
_, hasOwner = tables["knowledges"][binding.OwnerID]
} else if binding.OwnerType == "chunk" {
_, hasOwner = tables["chunks"][binding.OwnerID]
}
if !hasResource || !hasOwner {
return errors.New("orphan library resource binding")
}
}
handles := map[string]bool{}
for _, resource := range tables["resources"] {
if len(resource.Handle) != 22 || handles[resource.Handle] {
return errors.New("invalid resource handle")
}
handles[resource.Handle] = true
}
var bodies []json.RawMessage
for _, name := range []string{"knowledges", "chunks", "wiki_pages"} {
bodies = append(bodies, pg.Table(name).Rows...)
}
for _, handle := range referencedResourceHandles(bodies) {
if !handles[handle] {
return errors.New("unresolved library resource")
}
}
sha, err := searchDocumentsDigest(es.Documents)
if err != nil || !validLowerSHA256(es.MappingSHA256) || sha != es.DocumentsSHA256 {
return errors.New("invalid library index digest")
}
seen := map[string]bool{}
for _, document := range es.Documents {
var row libraryRow
if json.Unmarshal(document.Source, &row) != nil || !validSearchIdentifier(document.ID) || seen[document.ID] {
return errors.New("invalid library search document")
}
seen[document.ID] = true
chunk, ok := tables["chunks"][row.ChunkID]
if !ok || row.KnowledgeID != chunk.KnowledgeID || row.Content != chunk.Content {
return errors.New("library index does not match database chunks")
}
if !searchHitMatches(document.Source, SearchIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: row.KnowledgeID}) {
return errors.New("cross-scope library index")
}
}
return nil
}
@@ -0,0 +1,96 @@
package v071
import (
"bytes"
"context"
"encoding/json"
"io"
"os"
"testing"
"time"
"knowledge-governance/internal/librarysnapshot"
)
func TestArchiveLibraryCandidateOwnsEveryLaneAndRejectsMismatch(t *testing.T) {
for _, mode := range []string{"complete", "missing-resource", "bad-resource-hash", "cross-scope", "orphan-search", "missing-wiki", "search-digest", "duplicate-table"} {
t.Run(mode, func(t *testing.T) {
root := t.TempDir()
_ = os.Chmod(root, 0700)
archive, err := librarysnapshot.Open(root, 1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
pg, es, reader := libraryCandidateFixture()
switch mode {
case "missing-resource":
reader.data = nil
case "bad-resource-hash":
reader.data = []byte("wrong")
case "cross-scope":
pg.Tables[0] = newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-safe","tenant_id":20000,"knowledge_base_id":"kb-safe","parse_status":"completed"}`)})
case "orphan-search":
es.Documents[0].Source = json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"unknown"}`)
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
case "missing-wiki":
pg.Tables = pg.Tables[:6]
case "search-digest":
es.DocumentsSHA256 = shaBytes([]byte("wrong"))
case "duplicate-table":
pg.Tables = append(pg.Tables, pg.Tables[0])
}
contract := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
id, err := ArchiveLibraryCandidate(context.Background(), archive, "internal", PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, contract, pg, es, reader, time.Date(2026, 10, 27, 0, 0, 0, 0, time.UTC))
if mode != "complete" {
if err == nil {
t.Fatal("inconsistent candidate archived")
}
return
}
if err != nil {
t.Fatal(err)
}
reader.data = nil
saved, err := archive.Load(id)
if err != nil {
t.Fatal(err)
}
if len(saved.Parts) != 12 {
t.Fatalf("parts=%d", len(saved.Parts))
}
for _, part := range saved.Parts {
if part.Kind == "resource" {
r, err := archive.OpenPart(part)
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(r)
r.Close()
if err != nil || string(data) != "file" {
t.Fatal("resource not independently recoverable")
}
}
}
})
}
}
type libraryCandidateReader struct{ data []byte }
func (r *libraryCandidateReader) Open(context.Context, string, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(r.data)), nil
}
func libraryCandidateFixture() (PostgresSnapshot, SearchSnapshot, *libraryCandidateReader) {
tables := []TableSnapshot{
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","parse_status":"completed","file_path":"resource://ABCDEFGHIJKLMNOPQRSTUV"}`)}),
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"chunk"}`)}),
newTableSnapshot("resources", []json.RawMessage{json.RawMessage(`{"id":"res-safe","tenant_id":10000,"handle":"ABCDEFGHIJKLMNOPQRSTUV","provider":"oss","physical_path":"oss://fixture/source.txt","size":4}`)}),
}
for _, name := range []string{"resource_bindings", "knowledge_tags", "knowledge_tag_relations", "wiki_folders", "wiki_pages", "wiki_page_issues", "wiki_log_entries"} {
tables = append(tables, newTableSnapshot(name, nil))
}
es := SearchSnapshot{MappingSHA256: shaBytes([]byte("mapping")), Documents: []SearchDocument{{ID: "es-safe", Source: json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"chunk-safe","content":"chunk"}`)}}}
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
return PostgresSnapshot{Tables: tables}, es, &libraryCandidateReader{data: []byte("file")}
}
@@ -0,0 +1,70 @@
package v071
import (
"context"
"errors"
"time"
"knowledge-governance/internal/libraryfreeze"
"knowledge-governance/internal/librarysnapshot"
)
type LibraryCaptureRequest struct {
JobID, Scope string
Identity PostgresIdentity
Compatibility librarysnapshot.Compatibility
CreatedAt time.Time
MaxDocuments int
}
// CaptureLibrary connects maintenance to the actual PG/PIT/object archive path.
// sourceReady is mandatory and must verify the whole writer group (both scopes,
// ingress and background jobs), not only this KB. It runs before stopping and
// again inside the stopped window. Deployment must establish that the group
// contains every source writer. This function does not certify Wiki semantics,
// approve a release, or give the worker any production credentials.
func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, archive *librarysnapshot.Archive, db librarySnapshotDB, search *SearchExporter, objects ObjectReader, sourceReady func(context.Context) error, req LibraryCaptureRequest) (libraryfreeze.Result, error) {
if freeze == nil || archive == nil || db == nil || search == nil || objects == nil || sourceReady == nil || req.CreatedAt.IsZero() || req.MaxDocuments < 1 || req.Identity.TenantID == 0 || !validSearchIdentifier(req.Identity.KnowledgeBaseID) || req.Identity.KnowledgeID != "" || (req.Scope != "internal" && req.Scope != "external") {
return libraryfreeze.Result{}, errors.New("invalid library capture configuration")
}
result, err := freeze.RunPrepared(ctx, req.JobID, func(ctx context.Context) error {
if err := sourceReady(ctx); err != nil {
return err
}
// Check readiness before a maintenance window, then repeat the export inside
// that window: work can arrive between preflight and the graceful stop.
_, err := ExportLibrary(ctx, db, req.Identity)
return err
}, func(ctx context.Context) (string, error) {
if err := sourceReady(ctx); err != nil {
return "", err
}
pg, err := ExportLibrary(ctx, db, req.Identity)
if err != nil {
return "", err
}
es, err := search.ExportLibrary(ctx, SearchIdentity{TenantID: req.Identity.TenantID, KnowledgeBaseID: req.Identity.KnowledgeBaseID}, req.MaxDocuments)
if err != nil {
return "", err
}
return ArchiveLibraryCandidate(ctx, archive, req.Scope, req.Identity, req.Compatibility, pg, es, objects, req.CreatedAt)
})
if err != nil {
return result, err
}
// A successful old operation is replayable only while its exact independent
// archive still verifies, and never under another KB/scope/model contract.
saved, err := archive.Load(result.SnapshotID)
if err != nil {
return libraryfreeze.Result{}, errors.New("captured library archive no longer verifies")
}
if saved.Scope != req.Scope || saved.TenantID != req.Identity.TenantID || saved.KnowledgeBaseID != req.Identity.KnowledgeBaseID || saved.Compatibility != req.Compatibility || !saved.CreatedAt.Equal(req.CreatedAt) {
return libraryfreeze.Result{}, errors.New("library capture request conflicts with existing job")
}
for _, part := range saved.Parts {
if part.Kind == "index" && part.Count > int64(req.MaxDocuments) {
return libraryfreeze.Result{}, errors.New("replayed library exceeds requested document limit")
}
}
return result, nil
}
@@ -0,0 +1,131 @@
package v071
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"sync/atomic"
"testing"
"time"
"knowledge-governance/internal/libraryfreeze"
"knowledge-governance/internal/librarysnapshot"
)
type captureWriter struct {
running atomic.Bool
db *libraryFixture
late bool
stops int
}
func (c *captureWriter) Inventory(context.Context) ([]libraryfreeze.Service, error) {
r := c.running.Load()
return []libraryfreeze.Service{{ID: "test-writer", Running: r, Healthy: r}}, nil
}
func (c *captureWriter) Stop(context.Context, string) error {
c.stops++
c.running.Store(false)
if c.late {
c.db.tx.pending = 1
}
return nil
}
func (c *captureWriter) Start(context.Context, string) error { c.running.Store(true); return nil }
func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T) {
for _, mode := range []string{"success", "initial-busy", "late-pending", "search-failure"} {
t.Run(mode, func(t *testing.T) {
db := newLibraryFixture()
writer := &captureWriter{db: db, late: mode == "late-pending"}
writer.running.Store(true)
if mode == "initial-busy" {
db.tx.pending = 1
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/chunks/_mapping":
fmt.Fprint(w, `{"chunks":{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"tenant_id":{"type":"long"}}}}}`)
case "/chunks/_pit":
if writer.running.Load() {
t.Error("PIT opened before writers stopped")
}
fmt.Fprint(w, `{"id":"fixed-pit"}`)
case "/_search":
if mode == "search-failure" {
http.Error(w, "fixture failure", 503)
return
}
fmt.Fprint(w, `{"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}}`)
case "/_pit":
fmt.Fprint(w, `{"succeeded":true}`)
default:
http.Error(w, "unexpected", 400)
}
}))
defer server.Close()
search, err := NewSearchExporter(SearchExporterConfig{BaseURL: server.URL, Index: "chunks", PageSize: 10})
if err != nil {
t.Fatal(err)
}
mapping, err := search.inspectMapping(context.Background())
if err != nil {
t.Fatal(err)
}
root := t.TempDir()
_ = os.Chmod(root, 0700)
freeze, err := libraryfreeze.Open(root, "test-source", writer)
if err != nil {
t.Fatal(err)
}
defer freeze.Close()
archiveRoot := t.TempDir()
_ = os.Chmod(archiveRoot, 0700)
archive, err := librarysnapshot.Open(archiveRoot, 1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
req := LibraryCaptureRequest{JobID: "capture-job", Scope: "internal", Identity: PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: mapping.digest}, CreatedAt: time.Date(2026, 10, 27, 0, 0, 0, 0, time.UTC), MaxDocuments: 100}
checks := 0
ready := func(context.Context) error { checks++; return nil }
result, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req)
if !writer.running.Load() {
t.Fatal("test writer left stopped")
}
if mode != "success" {
if err == nil {
t.Fatal("invalid candidate succeeded")
}
if mode == "initial-busy" && writer.stops != 0 {
t.Fatal("busy source stopped")
}
return
}
if err != nil || result.State != "succeeded" {
t.Fatalf("capture=%+v err=%v", result, err)
}
saved, err := archive.Load(result.SnapshotID)
if err != nil || saved.Scope != "internal" || checks != 2 {
t.Fatalf("archive=%+v checks=%d err=%v", saved, checks, err)
}
db.tx.pending = 1
replay, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req)
if err != nil || replay.SnapshotID != result.SnapshotID || writer.stops != 1 {
t.Fatal("sealed replay consulted current source")
}
req.Scope = "external"
if got, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req); err == nil || got.State == "succeeded" {
t.Fatal("conflicting replay returned a successful candidate")
}
req.Scope = "internal"
if err := os.Remove(archiveRoot + "/versions/" + result.SnapshotID + ".json"); err != nil {
t.Fatal(err)
}
if got, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req); err == nil || got.State == "succeeded" {
t.Fatal("missing archive returned a successful candidate")
}
})
}
}
@@ -0,0 +1,118 @@
package v071
import (
"context"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
)
type librarySnapshotDB interface {
BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)
}
// ExportLibrary reads one PostgreSQL MVCC snapshot, including empty Wiki tables.
// It does not certify semantic quality, freeze Elasticsearch/objects, or authorize
// publication. Those require a separately verified, complete library version.
func ExportLibrary(ctx context.Context, db librarySnapshotDB, identity PostgresIdentity) (PostgresSnapshot, error) {
if db == nil || identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) || identity.KnowledgeID != "" {
return PostgresSnapshot{}, errors.New("invalid library snapshot scope")
}
tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return PostgresSnapshot{}, errors.New("begin library snapshot")
}
defer tx.Rollback(context.WithoutCancel(ctx))
var version int
var dirty bool
if err := tx.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty {
return PostgresSnapshot{}, errors.New("source library schema contract mismatch")
}
var graph bool
if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil {
return PostgresSnapshot{}, errors.New("source library unavailable")
}
if graph {
return PostgresSnapshot{}, errors.New("Neo4j graph snapshot is not supported")
}
var unsettled, pending, failed int64
if err := tx.QueryRow(ctx, librarySettlementSQL, identity.TenantID, identity.KnowledgeBaseID).Scan(&unsettled, &pending, &failed); err != nil {
return PostgresSnapshot{}, errors.New("read library settlement")
}
if unsettled != 0 || pending != 0 || failed != 0 {
return PostgresSnapshot{}, errors.New("library has unfinished or failed processing; semantic acceptance is still required after settlement")
}
exporter := PostgresExporter{db: tx}
var snapshot PostgresSnapshot
for _, entry := range libraryContentQueries {
rows, err := exporter.queryRows(ctx, entry.sql, identity.TenantID, identity.KnowledgeBaseID)
if err != nil {
return PostgresSnapshot{}, err
}
snapshot.Tables = append(snapshot.Tables, newTableSnapshot(entry.name, rows))
}
// Resources can be owned by a document/chunk or only referenced in body text.
// The latter includes Wiki manual pages, which document bundles used to miss.
var bodies []json.RawMessage
for _, name := range []string{"knowledges", "chunks", "wiki_pages"} {
bodies = append(bodies, snapshot.Table(name).Rows...)
}
handles := referencedResourceHandles(bodies)
resources, err := exporter.queryRows(ctx, libraryResourcesSQL, identity.TenantID, identity.KnowledgeBaseID, handles)
if err != nil {
return PostgresSnapshot{}, err
}
resourceIDs, resourceHandles := map[string]bool{}, map[string]bool{}
for _, raw := range resources {
var row struct {
ID string `json:"id"`
Handle string `json:"handle"`
TenantID uint64 `json:"tenant_id"`
}
if json.Unmarshal(raw, &row) != nil || row.ID == "" || row.TenantID != identity.TenantID || resourceIDs[row.ID] || resourceHandles[row.Handle] {
return PostgresSnapshot{}, errors.New("invalid library resource identity")
}
resourceIDs[row.ID] = true
resourceHandles[row.Handle] = true
}
for _, handle := range handles {
if !resourceHandles[handle] {
return PostgresSnapshot{}, errors.New("library references an unavailable resource")
}
}
for _, raw := range snapshot.Table("resource_bindings").Rows {
var row struct {
ResourceID string `json:"resource_id"`
}
if json.Unmarshal(raw, &row) != nil || !resourceIDs[row.ResourceID] {
return PostgresSnapshot{}, errors.New("library binding references an unavailable resource")
}
}
snapshot.Tables = append(snapshot.Tables, newTableSnapshot("resources", resources))
if err = tx.Commit(ctx); err != nil {
return PostgresSnapshot{}, errors.New("commit library snapshot")
}
return snapshot, nil
}
// Deleted document retract/finalize tasks are scoped to the KB, not a live
// knowledge row. Never join them to only non-deleted documents. Dead letters
// have no resolution marker in this schema, so presence blocks automatically.
const librarySettlementSQL = `SELECT
(SELECT count(*) FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL AND (parse_status IS DISTINCT FROM 'completed' OR pending_subtasks_count IS NULL OR pending_subtasks_count<>0)),
(SELECT count(*) FROM task_pending_ops WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)))),
(SELECT count(*) FROM task_dead_letters WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2))))`
var libraryContentQueries = []struct{ name, sql string }{
{"knowledges", `SELECT to_jsonb(k) FROM knowledges k WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL ORDER BY k.id`},
{"chunks", `SELECT to_jsonb(c) FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND c.deleted_at IS NULL ORDER BY c.id`},
{"knowledge_tags", `SELECT to_jsonb(t) FROM knowledge_tags t WHERE t.tenant_id=$1 AND t.knowledge_base_id=$2 AND t.deleted_at IS NULL ORDER BY t.id`},
{"knowledge_tag_relations", `SELECT to_jsonb(r) FROM knowledge_tag_relations r JOIN knowledges k ON k.id=r.knowledge_id JOIN knowledge_tags t ON t.id=r.tag_id AND t.tenant_id=k.tenant_id AND t.knowledge_base_id=k.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY r.knowledge_id,r.tag_id`},
{"resource_bindings", `SELECT to_jsonb(b) FROM resource_bindings b WHERE b.tenant_id=$1 AND ((b.owner_type='knowledge' AND EXISTS (SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL)) OR (b.owner_type='chunk' AND EXISTS (SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL AND k.deleted_at IS NULL))) ORDER BY b.id`},
{"wiki_pages", `SELECT to_jsonb(w) FROM wiki_pages w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
{"wiki_folders", `SELECT to_jsonb(w) FROM wiki_folders w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
{"wiki_page_issues", `SELECT to_jsonb(w) FROM wiki_page_issues w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
{"wiki_log_entries", `SELECT to_jsonb(w) FROM wiki_log_entries w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 ORDER BY w.id`},
}
const libraryResourcesSQL = `SELECT to_jsonb(r) FROM resources r WHERE r.tenant_id=$1 AND r.deleted_at IS NULL AND (r.handle=ANY($3::text[]) OR EXISTS (SELECT 1 FROM resource_bindings b WHERE b.resource_id=r.id AND b.tenant_id=$1 AND ((b.owner_type='knowledge' AND EXISTS (SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL)) OR (b.owner_type='chunk' AND EXISTS (SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL AND k.deleted_at IS NULL))))) ORDER BY r.id`
@@ -0,0 +1,178 @@
package v071
import (
"context"
"encoding/json"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// This fixture creates only synthetic content in an explicitly named disposable
// database. Never point this test at an application database.
func TestLibraryExportIsolatedPostgres(t *testing.T) {
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated database required")
}
ctx := context.Background()
db, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err = db.Exec(ctx, libraryTestSchema); err != nil {
t.Fatal(err)
}
scope := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}
run := func() PostgresSnapshot {
t.Helper()
s, e := ExportLibrary(ctx, db, scope)
if e != nil {
t.Fatal(e)
}
return s
}
snap := run()
if snap.Table("knowledges").RowCount != 1 || snap.Table("wiki_pages").RowCount != 1 || snap.Table("resources").RowCount != 1 {
t.Fatal("incorrect scoped export")
}
if snap.Table("wiki_log_entries").RowCount != 1 || snap.Table("wiki_page_issues").RowCount != 1 {
t.Fatal("Wiki associated data lost")
}
for _, tab := range snap.Tables {
for _, raw := range tab.Rows {
if strings.Contains(string(raw), "other-scope") {
t.Fatalf("cross scope leak in %s", tab.Name)
}
}
}
t.Run("MVCC concurrent update", func(t *testing.T) {
wrapper := libraryHookDB{pool: db, hook: func() {
if _, err := db.Exec(ctx, `UPDATE wiki_pages SET content='new-content' WHERE id='wiki-safe'`); err != nil {
t.Fatal(err)
}
}}
old, err := ExportLibrary(ctx, wrapper, scope)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(old.Table("wiki_pages").Rows[0]), "old-content") {
t.Fatal("mixed PostgreSQL versions during export")
}
fresh := run()
if !strings.Contains(string(fresh.Table("wiki_pages").Rows[0]), "new-content") {
t.Fatal("concurrent writer did not actually commit")
}
})
t.Run("deleted knowledge tasks", func(t *testing.T) {
for _, test := range []struct{ table, task, scope, id string }{
{"task_pending_ops", "wiki:ingest", "knowledge_base", "kb-safe"},
{"task_pending_ops", "wiki:finalize", "knowledge_base", "kb-safe"},
{"task_dead_letters", "wiki:ingest", "knowledge", "deleted-doc"},
} {
_, err := db.Exec(ctx, `INSERT INTO `+test.table+`(tenant_id,task_type,scope,scope_id) VALUES(10000,$1,$2,$3)`, test.task, test.scope, test.id)
if err != nil {
t.Fatal(err)
}
if _, err = ExportLibrary(ctx, db, scope); err == nil {
t.Fatalf("ignored %s %s", test.table, test.task)
}
if _, err = db.Exec(ctx, `DELETE FROM `+test.table); err != nil {
t.Fatal(err)
}
}
})
t.Run("dangling resource blocks", func(t *testing.T) {
_, err := db.Exec(ctx, `UPDATE wiki_pages SET content='resource://abcdefghijklmnopqrstuv' WHERE id='wiki-safe'`)
if err != nil {
t.Fatal(err)
}
if _, err = ExportLibrary(ctx, db, scope); err == nil {
t.Fatal("accepted missing Wiki resource dependency")
}
if _, err = db.Exec(ctx, `UPDATE wiki_pages SET content='new-content' WHERE id='wiki-safe'`); err != nil {
t.Fatal(err)
}
})
t.Run("empty library has explicit empty tables", func(t *testing.T) {
s, err := ExportLibrary(ctx, db, PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-empty"})
if err != nil {
t.Fatal(err)
}
if len(s.Tables) != 10 {
t.Fatal("empty library snapshot incomplete")
}
for _, tab := range s.Tables {
if tab.RowCount != 0 {
t.Fatal("empty library leaked content")
}
}
})
// The exporter may not mutate content: only fixture updates above are visible.
var count int
if err := db.QueryRow(ctx, `SELECT count(*) FROM sessions`).Scan(&count); err != nil || count != 1 {
t.Fatal("nonknowledge data changed")
}
encoded, err := json.Marshal(snap)
if err != nil || strings.Contains(string(encoded), "private-session-marker") {
t.Fatal("nonknowledge data exported")
}
}
type libraryHookDB struct {
pool *pgxpool.Pool
hook func()
}
func (d libraryHookDB) BeginTx(ctx context.Context, o pgx.TxOptions) (pgx.Tx, error) {
tx, err := d.pool.BeginTx(ctx, o)
return &libraryHookTx{Tx: tx, hook: d.hook}, err
}
type libraryHookTx struct {
pgx.Tx
hook func()
fired bool
}
func (d *libraryHookTx) Query(ctx context.Context, q string, args ...any) (pgx.Rows, error) {
if !d.fired {
d.fired = true
d.hook()
}
return d.Tx.Query(ctx, q, args...)
}
const libraryTestSchema = `
CREATE TABLE schema_migrations(version int,dirty bool); INSERT INTO schema_migrations VALUES(74,false);
CREATE TABLE knowledge_bases(id text,tenant_id bigint,indexing_strategy jsonb,deleted_at timestamptz);
INSERT INTO knowledge_bases VALUES('kb-safe',10000,'{}',NULL),('kb-empty',10000,'{}',NULL);
CREATE TABLE knowledges(id text PRIMARY KEY,tenant_id bigint,knowledge_base_id text,parse_status text,pending_subtasks_count int,file_path text,deleted_at timestamptz);
INSERT INTO knowledges VALUES('doc-safe',10000,'kb-safe','completed',0,'resource://ABCDEFGHIJKLMNOPQRSTUV',NULL),('other-scope',20000,'kb-safe','completed',0,'',NULL),('deleted-doc',10000,'kb-safe','completed',0,'',now());
CREATE TABLE chunks(id text,tenant_id bigint,knowledge_base_id text,knowledge_id text,content text,deleted_at timestamptz);
INSERT INTO chunks VALUES('chunk-safe',10000,'kb-safe','doc-safe','chunk',NULL),('other-scope',20000,'kb-safe','other-scope','secret',NULL);
CREATE TABLE knowledge_tags(id text,tenant_id bigint,knowledge_base_id text,deleted_at timestamptz);
CREATE TABLE knowledge_tag_relations(knowledge_id text,tag_id text);
CREATE TABLE resources(id text,handle text,tenant_id bigint,physical_path text,deleted_at timestamptz);
INSERT INTO resources VALUES('res-safe','ABCDEFGHIJKLMNOPQRSTUV',10000,'source.txt',NULL),('other-scope','abcdefghijklmnopqrstuv',20000,'other-scope',NULL);
CREATE TABLE resource_bindings(id text,tenant_id bigint,resource_id text,owner_type text,owner_id text);
INSERT INTO resource_bindings VALUES('binding-safe',10000,'res-safe','knowledge','doc-safe');
CREATE TABLE wiki_pages(id text,tenant_id bigint,knowledge_base_id text,slug text,content text,deleted_at timestamptz);
INSERT INTO wiki_pages VALUES('wiki-safe',10000,'kb-safe','index','old-content',NULL),('other-scope',20000,'kb-safe','secret','other-scope',NULL);
CREATE TABLE wiki_folders(id text,tenant_id bigint,knowledge_base_id text,deleted_at timestamptz);
CREATE TABLE wiki_page_issues(id text,tenant_id bigint,knowledge_base_id text,deleted_at timestamptz);
INSERT INTO wiki_page_issues VALUES('issue-safe',10000,'kb-safe',NULL);
CREATE TABLE wiki_log_entries(id bigint,tenant_id bigint,knowledge_base_id text);
INSERT INTO wiki_log_entries VALUES(1,10000,'kb-safe');
CREATE TABLE task_pending_ops(tenant_id bigint,task_type text,scope text,scope_id text);
CREATE TABLE task_dead_letters(tenant_id bigint,task_type text,scope text,scope_id text);
CREATE TABLE sessions(marker text); INSERT INTO sessions VALUES('private-session-marker');
`
@@ -0,0 +1,125 @@
package v071
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/jackc/pgx/v5"
)
func TestLibraryExportIncludesEmptyAndCompleteWiki(t *testing.T) {
db := newLibraryFixture()
snapshot, err := ExportLibrary(context.Background(), db, PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"})
if err != nil {
t.Fatal(err)
}
if len(snapshot.Tables) != 10 {
t.Fatalf("table count=%d, want all ten content tables including empty ones", len(snapshot.Tables))
}
for _, name := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations", "wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} {
if !tablePresent(snapshot, name) {
t.Fatalf("missing table %s", name)
}
}
if db.options.IsoLevel != pgx.RepeatableRead || db.options.AccessMode != pgx.ReadOnly {
t.Fatalf("unsafe snapshot options: %+v", db.options)
}
if !db.tx.committed {
t.Fatal("snapshot transaction not committed")
}
for _, q := range db.tx.queries {
for _, forbidden := range []string{"from users", "from sessions", "from api_keys", "from messages"} {
if strings.Contains(strings.ToLower(q), forbidden) {
t.Fatalf("nonknowledge export: %s", forbidden)
}
}
}
}
func TestLibraryExportBlocksUnsettledWorkIncludingDeletedDocumentRetracts(t *testing.T) {
for _, test := range []struct {
name string
setup func(*libraryFixtureTx)
}{
{"document failed or parsing", func(d *libraryFixtureTx) { d.unsettled = 1 }},
{"deleted document retract or finalizer", func(d *libraryFixtureTx) { d.pending = 1 }},
{"dead letter not semantic success", func(d *libraryFixtureTx) { d.failed = 1 }},
{"unsupported graph data", func(d *libraryFixtureTx) { d.graph = true }},
} {
t.Run(test.name, func(t *testing.T) {
db := newLibraryFixture()
test.setup(db.tx)
_, err := ExportLibrary(context.Background(), db, PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"})
if err == nil {
t.Fatal("unsettled library was exported")
}
if db.tx.committed {
t.Fatal("blocked snapshot committed")
}
})
}
}
func TestLibraryExportDoesNotReturnPartialSnapshot(t *testing.T) {
db := newLibraryFixture()
db.tx.queryError = true
got, err := ExportLibrary(context.Background(), db, PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"})
if err == nil || len(got.Tables) != 0 || db.tx.committed {
t.Fatal("partial snapshot escaped")
}
}
type libraryFixture struct {
options pgx.TxOptions
tx *libraryFixtureTx
}
type libraryFixtureTx struct {
pgx.Tx
queries []string
committed bool
pending, failed, unsettled int64
graph bool
queryError bool
}
func newLibraryFixture() *libraryFixture { return &libraryFixture{tx: &libraryFixtureTx{}} }
func (d *libraryFixture) BeginTx(_ context.Context, o pgx.TxOptions) (pgx.Tx, error) {
d.options = o
return d.tx, nil
}
func (d *libraryFixtureTx) Commit(context.Context) error { d.committed = true; return nil }
func (d *libraryFixtureTx) Rollback(context.Context) error { return nil }
func (d *libraryFixtureTx) QueryRow(_ context.Context, q string, _ ...any) pgx.Row {
d.queries = append(d.queries, q)
return libraryFixtureRow{d: d, sql: q}
}
func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Rows, error) {
d.queries = append(d.queries, q)
if d.queryError {
return nil, errors.New("fixture failure")
}
return &jsonRows{values: []json.RawMessage{}}, nil
}
type libraryFixtureRow struct {
d *libraryFixtureTx
sql string
}
func (r libraryFixtureRow) Scan(dest ...any) error {
switch {
case strings.Contains(r.sql, "schema_migrations"):
*dest[0].(*int) = 74
*dest[1].(*bool) = false
case strings.Contains(r.sql, "indexing_strategy"):
*dest[0].(*bool) = r.d.graph
default:
*dest[0].(*int64) = r.d.unsettled
*dest[1].(*int64) = r.d.pending
*dest[2].(*int64) = r.d.failed
}
return nil
}
@@ -0,0 +1,140 @@
package v071
import (
"context"
"encoding/json"
"errors"
"net/http"
"sort"
"time"
)
// ExportLibrary uses one Elasticsearch point-in-time rather than offset paging
// against a changing index. A PIT does not freeze PostgreSQL or object storage;
// the coordinator must still prove cross-lane consistency before publication.
func (e *SearchExporter) ExportLibrary(ctx context.Context, identity SearchIdentity, maxDocuments int) (snapshot SearchSnapshot, resultErr error) {
if identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) || identity.KnowledgeID != "" || maxDocuments < 1 {
return SearchSnapshot{}, errors.New("invalid library search scope or limit")
}
inspection, err := e.inspectMapping(ctx)
if err != nil {
return SearchSnapshot{}, err
}
var opened struct {
ID string `json:"id"`
}
if err = e.requestJSON(ctx, http.MethodPost, "/"+e.index+"/_pit?keep_alive=2m&allow_partial_search_results=false", nil, &opened); err != nil {
return SearchSnapshot{}, err
}
if opened.ID == "" {
return SearchSnapshot{}, errors.New("missing Elasticsearch PIT")
}
pit := opened.ID
defer func() {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
var result struct {
Succeeded bool `json:"succeeded"`
}
err := e.requestJSON(cleanup, http.MethodDelete, "/_pit", map[string]any{"id": pit}, &result)
if (err != nil || !result.Succeeded) && resultErr == nil {
snapshot = SearchSnapshot{}
resultErr = errors.New("close library snapshot PIT")
}
}()
filter := []any{map[string]any{"term": map[string]any{inspection.fields.base: identity.KnowledgeBaseID}}}
if inspection.fields.tenant != "" {
filter = append(filter, map[string]any{"term": map[string]any{inspection.fields.tenant: identity.TenantID}})
}
var cursor json.RawMessage
documents := make([]SearchDocument, 0)
seen := map[string]bool{}
var total *int64
for {
body := map[string]any{"pit": map[string]any{"id": pit, "keep_alive": "2m"}, "size": e.pageSize, "sort": []any{"_shard_doc"}, "track_total_hits": true, "query": map[string]any{"bool": map[string]any{"filter": filter}}}
if cursor != nil {
body["search_after"] = cursor
}
var page struct {
PITID string `json:"pit_id"`
TimedOut *bool `json:"timed_out"`
Shards struct {
Total int `json:"total"`
Successful int `json:"successful"`
Failed int `json:"failed"`
} `json:"_shards"`
Hits struct {
Total struct {
Value *int64 `json:"value"`
Relation string `json:"relation"`
} `json:"total"`
Hits []struct {
ID string `json:"_id"`
Source json.RawMessage `json:"_source"`
Sort json.RawMessage `json:"sort"`
} `json:"hits"`
} `json:"hits"`
}
if err = e.requestJSON(ctx, http.MethodPost, "/_search?allow_partial_search_results=false", body, &page); err != nil {
return SearchSnapshot{}, err
}
if page.PITID != "" {
pit = page.PITID
}
if page.TimedOut == nil || *page.TimedOut || page.Shards.Total < 1 || page.Shards.Successful != page.Shards.Total || page.Shards.Failed != 0 || page.Hits.Total.Value == nil || page.Hits.Total.Relation != "eq" {
return SearchSnapshot{}, errors.New("incomplete Elasticsearch library snapshot")
}
if total == nil {
total = page.Hits.Total.Value
}
if *total < 0 || *total > int64(maxDocuments) || *total != *page.Hits.Total.Value {
return SearchSnapshot{}, errors.New("Elasticsearch library total changed or exceeds limit")
}
for _, hit := range page.Hits.Hits {
var scope struct {
KnowledgeID string `json:"knowledge_id"`
}
if json.Unmarshal(hit.Source, &scope) != nil || !validSearchIdentifier(scope.KnowledgeID) || !validSearchIdentifier(hit.ID) || seen[hit.ID] {
return SearchSnapshot{}, errors.New("invalid or duplicate library search identity")
}
expected := identity
expected.KnowledgeID = scope.KnowledgeID
if !searchHitMatches(hit.Source, expected) {
return SearchSnapshot{}, errors.New("cross-scope library search document")
}
source, err := canonicalJSON(hit.Source)
if err != nil {
return SearchSnapshot{}, errors.New("invalid library search data")
}
seen[hit.ID] = true
documents = append(documents, SearchDocument{ID: hit.ID, Source: source})
}
if int64(len(documents)) > *total {
return SearchSnapshot{}, errors.New("library search total mismatch")
}
if len(page.Hits.Hits) > 0 {
next := page.Hits.Hits[len(page.Hits.Hits)-1].Sort
var values []json.RawMessage
if json.Unmarshal(next, &values) != nil || len(values) == 0 || string(next) == string(cursor) {
return SearchSnapshot{}, errors.New("library search cursor did not advance")
}
cursor = next
}
if int64(len(documents)) == *total {
break
}
if len(page.Hits.Hits) == 0 {
return SearchSnapshot{}, errors.New("library search snapshot truncated")
}
}
finalMapping, err := e.inspectMapping(ctx)
if err != nil || finalMapping.digest != inspection.digest {
return SearchSnapshot{}, errors.New("library search mapping changed")
}
sort.Slice(documents, func(i, j int) bool { return documents[i].ID < documents[j].ID })
sha, err := searchDocumentsDigest(documents)
if err != nil {
return SearchSnapshot{}, err
}
return SearchSnapshot{Documents: documents, MappingSHA256: inspection.digest, DocumentsSHA256: sha}, nil
}
@@ -0,0 +1,81 @@
package v071
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"os"
"strings"
"testing"
"time"
)
func TestLibrarySearchIsolatedElasticsearch(t *testing.T) {
base := os.Getenv("KG_LIBRARY_TEST_ELASTIC_URL")
if base == "" {
t.Skip("requires explicit isolated Elasticsearch fixture opt-in")
}
if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated fixture authorization required")
}
var id [8]byte
if _, err := rand.Read(id[:]); err != nil {
t.Fatal(err)
}
index := "kg_library_test_" + hex.EncodeToString(id[:])
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
request := func(method, path, body, contentType string) int {
t.Helper()
r, err := http.NewRequest(method, base+path, strings.NewReader(body))
if err != nil {
t.Fatal("invalid fixture endpoint")
}
r.Header.Set("Content-Type", contentType)
response, err := client.Do(r)
if err != nil {
t.Fatal("fixture request failed")
}
defer response.Body.Close()
return response.StatusCode
}
if status := request(http.MethodPut, "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"}}}}`, "application/json"); status != 200 {
t.Fatalf("create synthetic index HTTP %d", status)
}
defer func() {
if status := request(http.MethodDelete, "/"+index, "", "application/json"); status != 200 {
t.Errorf("remove fixture index HTTP %d", status)
}
if status := request(http.MethodHead, "/"+index, "", "application/json"); status != 404 {
t.Errorf("fixture index remains HTTP %d", status)
}
}()
var bulk bytes.Buffer
for i := 1; i <= 3; i++ {
baseID := "kb-safe"
if i == 3 {
baseID = "kb-other"
}
fmt.Fprintf(&bulk, "{\"index\":{\"_id\":\"chunk-%d\"}}\n{\"tenant_id\":10000,\"knowledge_base_id\":%q,\"knowledge_id\":\"doc-safe\"}\n", i, baseID)
}
if status := request(http.MethodPost, "/"+index+"/_bulk?refresh=true", bulk.String(), "application/x-ndjson"); status != 200 {
t.Fatalf("fixture bulk HTTP %d", status)
}
exporter, err := NewSearchExporter(SearchExporterConfig{BaseURL: base, Index: index, PageSize: 1, HTTPClient: client})
if err != nil {
t.Fatal(err)
}
s, err := exporter.ExportLibrary(context.Background(), SearchIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, 10)
if err != nil {
t.Fatal(err)
}
if len(s.Documents) != 2 {
t.Fatalf("documents=%d", len(s.Documents))
}
empty, err := exporter.ExportLibrary(context.Background(), SearchIdentity{TenantID: 10000, KnowledgeBaseID: "kb-empty"}, 10)
if err != nil || len(empty.Documents) != 0 {
t.Fatalf("empty snapshot err=%v documents=%d", err, len(empty.Documents))
}
}
@@ -0,0 +1,90 @@
package v071
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestLibrarySearchUsesPITAndChecksExactTotal(t *testing.T) {
for _, mode := range []string{"complete", "partial", "truncated", "wrong-scope", "repeated-cursor", "limit"} {
t.Run(mode, func(t *testing.T) {
searches, closed := 0, false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/chunks/_mapping":
fmt.Fprint(w, `{"chunks":{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"tenant_id":{"type":"long"}}}}}`)
case r.Method == http.MethodPost && r.URL.Path == "/chunks/_pit":
if r.URL.Query().Get("allow_partial_search_results") != "false" {
t.Error("partial PIT allowed")
}
fmt.Fprint(w, `{"id":"pit-0"}`)
case r.Method == http.MethodPost && r.URL.Path == "/_search":
var body map[string]any
if json.NewDecoder(r.Body).Decode(&body) != nil {
t.Error("bad query")
}
searches++
if _, ok := body["from"]; ok {
t.Error("offset paging is not a fixed snapshot")
}
pit, _ := body["pit"].(map[string]any)
if pit["id"] != fmt.Sprintf("pit-%d", searches-1) {
t.Error("latest PIT identity not used")
}
if searches > 1 {
if _, ok := body["search_after"]; !ok {
t.Error("missing cursor")
}
}
failed := 0
if mode == "partial" {
failed = 1
}
base := "kb-safe"
if mode == "wrong-scope" {
base = "kb-wrong"
}
hits := fmt.Sprintf(`[{"_id":"chunk-%d","_source":{"tenant_id":10000,"knowledge_base_id":%q,"knowledge_id":"doc-safe"},"sort":[%d]}]`, searches, base, searches)
if mode == "truncated" && searches == 2 {
hits = "[]"
}
if mode == "repeated-cursor" && searches == 2 {
hits = `[{"_id":"chunk-2","_source":{"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe"},"sort":[1]}]`
}
fmt.Fprintf(w, `{"pit_id":"pit-%d","timed_out":false,"_shards":{"total":1,"successful":1,"failed":%d},"hits":{"total":{"value":2,"relation":"eq"},"hits":%s}}`, searches, failed, hits)
case r.Method == http.MethodDelete && r.URL.Path == "/_pit":
closed = true
fmt.Fprint(w, `{"succeeded":true,"num_freed":1}`)
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
http.Error(w, "unexpected", 400)
}
}))
defer server.Close()
exporter, err := NewSearchExporter(SearchExporterConfig{BaseURL: server.URL, Index: "chunks", PageSize: 1})
if err != nil {
t.Fatal(err)
}
limit := 10
if mode == "limit" {
limit = 1
}
snapshot, err := exporter.ExportLibrary(context.Background(), SearchIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, limit)
if mode == "complete" {
if err != nil || len(snapshot.Documents) != 2 {
t.Fatalf("export err=%v documents=%d", err, len(snapshot.Documents))
}
} else if err == nil {
t.Fatal("invalid snapshot accepted")
}
if !closed {
t.Fatal("PIT leaked")
}
})
}
}