package v071 import ( "context" "encoding/json" "errors" "fmt" "log" "net/http" "sort" "knowledge-governance/internal/librarysnapshot" ) type indexWriteGuard struct { ID string `json:"_id"` Index string `json:"_index"` Found bool `json:"found"` Source json.RawMessage `json:"_source"` SeqNo *int64 `json:"_seq_no"` PrimaryTerm *int64 `json:"_primary_term"` Error json.RawMessage `json:"error"` } // Elasticsearch IDs belong to the entire index, not to a KB. Every requested // ID must be explicitly present or absent in the response, never inferred from // a truncated/malformed response or a transport error. func (e *SearchExporter) indexWriteGuards(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity) (map[string]indexWriteGuard, error) { guards := map[string]indexWriteGuard{} for start := 0; start < len(documents); start += 500 { end := start + 500 if end > len(documents) { end = len(documents) } ids := []string{} wanted := map[string]bool{} for _, doc := range documents[start:end] { if doc.ID == "" || wanted[doc.ID] { return nil, errors.New("invalid or duplicate index identity") } if _, exists := guards[doc.ID]; exists { return nil, errors.New("duplicate index identity") } wanted[doc.ID] = true ids = append(ids, doc.ID) } var response struct { Docs []indexWriteGuard `json:"docs"` } if err := e.requestJSON(ctx, http.MethodPost, "/"+e.index+"/_mget", map[string]any{"ids": ids}, &response); err != nil { return nil, err } if len(response.Docs) != len(ids) { return nil, errors.New("incomplete index identity preflight") } for _, doc := range response.Docs { if !wanted[doc.ID] || doc.Index != e.index || len(doc.Error) > 0 && string(doc.Error) != "null" { return nil, errors.New("invalid index identity preflight") } if _, exists := guards[doc.ID]; exists { return nil, errors.New("duplicate index preflight result") } if doc.Found { var owner struct { Tenant uint64 `json:"tenant_id"` KB string `json:"knowledge_base_id"` } if json.Unmarshal(doc.Source, &owner) != nil || owner.KB != identity.KnowledgeBaseID || (!identity.NoTenantField && owner.Tenant != identity.TenantID) { log.Printf("index guard conflict id=%s owner_kb=%q want_kb=%q owner_tenant=%d want_tenant=%d no_tenant_field=%t", doc.ID, owner.KB, identity.KnowledgeBaseID, owner.Tenant, identity.TenantID, identity.NoTenantField) return nil, fmt.Errorf("index-level ID conflict: %s is not owned by target tenant/KB", doc.ID) } if doc.SeqNo == nil || doc.PrimaryTerm == nil { return nil, errors.New("index lacks optimistic concurrency identity") } } guards[doc.ID] = doc } } return guards, nil } func (t *ProductionLibraryTarget) preflightArchiveIndex(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error { for _, part := range manifest.Parts { if part.Kind != "index" { continue } reader, err := archive.OpenPart(part) if err != nil { return err } docs, err := librarysnapshot.ReadIndexDocuments(reader) reader.Close() if err != nil { return err } if t.mappingActive { // Plan/Apply 的索引身份已在 planIndex/ApplyIndex 统一映射;前置预检 // 必须对同一目标物理 _id 做归属检查,否则旧库占用源 _id 会被误报冲突。 mapped := make(map[string]json.RawMessage, len(docs)) for _, doc := range docs { id, source, err := t.targetIDs.remapIndexDocument(doc.ID, doc.Source) if err != nil { return err } if _, exists := mapped[id]; exists { return errors.New("index target id collision") } mapped[id] = source } ids := make([]string, 0, len(mapped)) for id := range mapped { ids = append(ids, id) } sort.Strings(ids) docs = make([]librarysnapshot.IndexDocument, 0, len(ids)) for _, id := range ids { docs = append(docs, librarysnapshot.IndexDocument{ID: id, Source: mapped[id]}) } } if _, err := t.search.indexWriteGuards(ctx, docs, SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID, NoTenantField: !t.schema.IndexTenantField}); err != nil { return err } } return nil } func (e *SearchExporter) BulkIndexGuarded(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity) error { guards, err := e.indexWriteGuards(ctx, documents, identity) if err != nil { return err } return e.bulkIndex(ctx, documents, identity, guards) }