执行时真实时钟与持久授权回读(撤销/过期即停并保留预备份)、写集合写前落盘、 租约与 attempt 身份、恢复队列与原发送身份分离、成功收尾必须释放维护后再登记终态。
This commit is contained in:
@@ -22,6 +22,12 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi
|
||||
if err := validateLibraryCandidate(identity, pg, es); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return archiveLibraryRows(ctx, archive, scope, identity, contract, pg, es, objects, createdAt)
|
||||
}
|
||||
|
||||
// Private: callers must distinguish a validated source candidate from raw
|
||||
// target before-images. Never run source semantic filtering on recovery bytes.
|
||||
func archiveLibraryRows(ctx context.Context, archive *librarysnapshot.Archive, scope string, identity PostgresIdentity, contract librarysnapshot.Compatibility, pg PostgresSnapshot, es SearchSnapshot, objects ObjectReader, createdAt time.Time) (string, error) {
|
||||
// 空生产基线:索引不存在时没有映射可比,契约仍按目标快照记录;
|
||||
// 只要这次导出的文档是零条,就不存在"拿错映射"的风险。
|
||||
emptyIndex := len(es.Documents) == 0
|
||||
@@ -43,6 +49,15 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi
|
||||
manifest.Parts = append(manifest.Parts, p)
|
||||
return nil
|
||||
}
|
||||
if pg.Catalog != nil {
|
||||
raw, err := json.Marshal(pg.Catalog)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = put("schema", "migration-catalog", 1, raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
for _, table := range pg.Tables {
|
||||
rows := table.Rows
|
||||
if rows == nil {
|
||||
@@ -211,6 +226,9 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
return errors.New("missing library table")
|
||||
}
|
||||
}
|
||||
if err := validateLibraryStructuredReferences(pg); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, chunk := range tables["chunks"] {
|
||||
if _, ok := tables["knowledges"][chunk.KnowledgeID]; !ok {
|
||||
return errors.New("orphan library chunk")
|
||||
@@ -243,10 +261,14 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
handles[resource.Handle] = true
|
||||
}
|
||||
var bodies []json.RawMessage
|
||||
for _, name := range []string{"knowledges", "chunks", "wiki_pages"} {
|
||||
bodies = append(bodies, pg.Table(name).Rows...)
|
||||
for _, table := range pg.Tables {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
}
|
||||
for _, handle := range referencedResourceHandles(bodies) {
|
||||
references, err := libraryResourceHandles(bodies)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, handle := range references {
|
||||
if !handles[handle] {
|
||||
return errors.New("unresolved library resource")
|
||||
}
|
||||
|
||||
@@ -17,8 +17,8 @@ import (
|
||||
// (PG RepeatableRead + ES 导出一致快照 + 资源对象),密封成归档里的一个版本。
|
||||
//
|
||||
// 为什么要有静默检查:预备份期间生产若仍在变,导出的 PG/ES/对象就不是同一个切点,
|
||||
// 恢复它等于恢复到"没人见过的状态"。所以导出前后各读一次行数,不一致就失败,
|
||||
// 让作业重试,而不是拿一个不一致的备份当恢复点。
|
||||
// 恢复它等于恢复到"没人见过的状态"。PG逐行指纹与对象精确版本在导出前后
|
||||
// 必须一致;执行器另行核对索引before-image。此检测不能代替独占写审核。
|
||||
type ProductionBackupStore struct {
|
||||
pool *pgxpool.Pool
|
||||
search *SearchExporter
|
||||
@@ -119,12 +119,16 @@ func (s *ProductionBackupStore) Prepare(ctx context.Context, _ string, current l
|
||||
if err != nil {
|
||||
return libraryrelease.BackupRef{}, err
|
||||
}
|
||||
pg, err := ExportLibrary(ctx, s.pool, s.identity)
|
||||
pg, err := exportLibraryBeforeImage(ctx, s.pool, s.identity)
|
||||
if err != nil {
|
||||
return libraryrelease.BackupRef{}, fmt.Errorf("读取生产整库失败: %w", err)
|
||||
}
|
||||
// 整库导出用 ExportLibrary(按租户+知识库,不带单文档身份),
|
||||
// 与封存路径复用同一份实现,避免两套范围规则。
|
||||
// Every row the actual delete predicate can reach must be present.
|
||||
for _, table := range pg.Tables {
|
||||
if int64(len(table.Rows)) != before[table.Name].Count {
|
||||
return libraryrelease.BackupRef{}, fmt.Errorf("before-image coverage mismatch: %s", table.Name)
|
||||
}
|
||||
}
|
||||
es, err := s.search.ExportLibrary(ctx, SearchIdentity{TenantID: s.identity.TenantID,
|
||||
KnowledgeBaseID: s.identity.KnowledgeBaseID}, s.maxDocuments)
|
||||
if err != nil {
|
||||
@@ -143,9 +147,13 @@ func (s *ProductionBackupStore) Prepare(ctx context.Context, _ string, current l
|
||||
return libraryrelease.BackupRef{}, errors.New("生产索引映射与归档契约不一致")
|
||||
}
|
||||
}
|
||||
objectBefore, err := s.objectVersions(ctx, pg)
|
||||
if err != nil {
|
||||
return libraryrelease.BackupRef{}, err
|
||||
}
|
||||
// ArchiveLibraryCandidate 自己按 resources 行读取对象字节并计算摘要,
|
||||
// 所以这里直接给它生产对象读取器,不再重复导出一次资源。
|
||||
snapshotID, err := ArchiveLibraryCandidate(ctx, archive, s.scope, s.identity, s.compatibility, pg, es, s.objects, createdAt)
|
||||
snapshotID, err := archiveLibraryRows(ctx, archive, s.scope, s.identity, s.compatibility, pg, es, s.objects, createdAt)
|
||||
if err != nil {
|
||||
return libraryrelease.BackupRef{}, fmt.Errorf("密封预备份失败: %w", err)
|
||||
}
|
||||
@@ -179,14 +187,60 @@ func (s *ProductionBackupStore) Prepare(ctx context.Context, _ string, current l
|
||||
if err != nil {
|
||||
return libraryrelease.BackupRef{}, errors.New("预备份封存后无法校验")
|
||||
}
|
||||
objectAfter, err := s.objectVersions(ctx, pg)
|
||||
if err != nil {
|
||||
return libraryrelease.BackupRef{}, err
|
||||
}
|
||||
for id, before := range objectBefore {
|
||||
if objectAfter[id] != before {
|
||||
return libraryrelease.BackupRef{}, errors.New("object changed during prebackup; inconsistent version boundary")
|
||||
}
|
||||
}
|
||||
var total int64
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind == "resource" {
|
||||
observed, ok := objectBefore[part.Name]
|
||||
if !ok || observed.SHA256 != part.SHA256 || observed.Bytes != part.Bytes {
|
||||
return libraryrelease.BackupRef{}, errors.New("archived object differs from prebackup version boundary")
|
||||
}
|
||||
}
|
||||
total += part.Bytes
|
||||
}
|
||||
return libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID, Bytes: total,
|
||||
CreatedAt: createdAt, Universe: universeBefore}, nil
|
||||
}
|
||||
|
||||
// Exact versions, not just bytes, bind the multi-store backup read interval.
|
||||
// An unchanged byte string in a new version is still a different restore base.
|
||||
func (s *ProductionBackupStore) objectVersions(ctx context.Context, pg PostgresSnapshot) (map[string]objectObservation, error) {
|
||||
out := map[string]objectObservation{}
|
||||
reader, ok := s.objects.(interface {
|
||||
ObserveObject(context.Context, string, string) (objectObservation, error)
|
||||
})
|
||||
for _, raw := range pg.Table("resources").Rows {
|
||||
if !ok {
|
||||
return nil, errors.New("prebackup reader lacks exact object-version observations")
|
||||
}
|
||||
var row struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Path string `json:"physical_path"`
|
||||
}
|
||||
if e := json.Unmarshal(raw, &row); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
observed, e := reader.ObserveObject(ctx, row.Provider, row.Path)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if !observed.Exists || observed.VersionID == "" || observed.VersionID == "null" || observed.SHA256 == "" {
|
||||
return nil, errors.New("prebackup requires an existing versioned object")
|
||||
}
|
||||
out[row.ID] = observed
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *ProductionBackupStore) rowCounts(ctx context.Context) (map[string]int64, error) {
|
||||
counts := map[string]int64{}
|
||||
for _, table := range productionLibraryTables {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// Recovery bytes are not a source candidate. The selection must equal the
|
||||
// destructive target predicate, including tombstones and their relationships.
|
||||
// Semantic source validation would discard/reject exactly those historical
|
||||
// rows that an exact rollback must preserve.
|
||||
func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identity PostgresIdentity) (PostgresSnapshot, error) {
|
||||
tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
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("before-image schema contract mismatch")
|
||||
}
|
||||
exporter := PostgresExporter{db: tx}
|
||||
snapshot := PostgresSnapshot{}
|
||||
for _, table := range productionLibraryTables {
|
||||
rows, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s ORDER BY (%s)::text`, table, table, scopeWhere(table), identityExpr(table)), identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
snapshot.Tables = append(snapshot.Tables, newTableSnapshot(table, rows))
|
||||
}
|
||||
var bodies []json.RawMessage
|
||||
for _, table := range snapshot.Tables {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
}
|
||||
handles, err := libraryResourceHandles(bodies)
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
resourceHandles := map[string]bool{}
|
||||
resourceIDs := []string{}
|
||||
for _, raw := range snapshot.Table("resources").Rows {
|
||||
var row struct {
|
||||
ID string `json:"id"`
|
||||
Handle string `json:"handle"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &row); err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
resourceHandles[row.Handle] = true
|
||||
resourceIDs = append(resourceIDs, row.ID)
|
||||
}
|
||||
for _, handle := range handles {
|
||||
if !resourceHandles[handle] {
|
||||
return PostgresSnapshot{}, errors.New("before-image contains unresolved resource reference")
|
||||
}
|
||||
}
|
||||
if err := verifyLibraryResourceOwners(ctx, tx, resourceIDs); err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Validate each ancestor before descending; MkdirAll can follow an ancestor
|
||||
// symlink before the leaf Lstat ever sees it. Sync every directory entry's parent,
|
||||
// not merely the last two levels of a newly-created effect hierarchy.
|
||||
func ensureEvidenceDirectory(path string, syncDirectory func(string) error) error {
|
||||
absolute, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parent := filepath.Dir(absolute)
|
||||
if parent != absolute {
|
||||
if err = ensureEvidenceDirectory(parent, syncDirectory); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
info, err := os.Lstat(absolute)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if err = os.Mkdir(absolute, 0700); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
info, err = os.Lstat(absolute)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return errors.New("evidence ancestor is not a real directory")
|
||||
}
|
||||
if parent != absolute {
|
||||
return syncDirectory(parent)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -58,8 +58,18 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
return PostgresSnapshot{}, errors.New("library has unfinished or failed processing; semantic acceptance is still required after settlement")
|
||||
}
|
||||
}
|
||||
if err := verifyLibraryRelationalClosure(ctx, tx, identity, false); err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
exporter := PostgresExporter{db: tx}
|
||||
var snapshot PostgresSnapshot
|
||||
snapshot.Catalog, _, err = captureMigrationCatalog(ctx, tx)
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
if err = validateMigrationCatalog(snapshot.Catalog); err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
for _, entry := range libraryContentQueries {
|
||||
rows, err := exporter.queryRows(ctx, entry.sql, identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
@@ -70,10 +80,13 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
// 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...)
|
||||
for _, table := range snapshot.Tables {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
}
|
||||
handles, err := libraryResourceHandles(bodies)
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
handles := referencedResourceHandles(bodies)
|
||||
resources, err := exporter.queryRows(ctx, libraryResourcesSQL, identity.TenantID, identity.KnowledgeBaseID, handles)
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
@@ -104,6 +117,13 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
return PostgresSnapshot{}, errors.New("library binding references an unavailable resource")
|
||||
}
|
||||
}
|
||||
ids := make([]string, 0, len(resourceIDs))
|
||||
for id := range resourceIDs {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if err := verifyLibraryResourceOwners(ctx, tx, ids); err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
snapshot.Tables = append(snapshot.Tables, newTableSnapshot("resources", resources))
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return PostgresSnapshot{}, errors.New("commit library snapshot")
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The contract names physical identities, not inferred *_id conventions. A
|
||||
// string ID is preserved byte-for-byte (older archives also contain non-UUID
|
||||
// varchar IDs). Database-local integers must never pass through float64.
|
||||
const migrationIdentityContractVersion = 1
|
||||
|
||||
type rowIdentityContract struct {
|
||||
Columns []string
|
||||
Kind string
|
||||
LocalColumn string
|
||||
Sequence string
|
||||
}
|
||||
|
||||
var migrationIdentityContracts = map[string]rowIdentityContract{
|
||||
"knowledges": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"chunks": {Columns: []string{"id"}, Kind: "stable-string", LocalColumn: "seq_id", Sequence: "chunks_seq_id_seq"},
|
||||
"knowledge_tags": {Columns: []string{"id"}, Kind: "stable-string", LocalColumn: "seq_id", Sequence: "knowledge_tags_seq_id_seq"},
|
||||
"knowledge_tag_relations": {Columns: []string{"knowledge_id", "tag_id"}, Kind: "tuple"},
|
||||
"resources": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"resource_bindings": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_folders": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_pages": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_page_issues": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
||||
}
|
||||
|
||||
type typedRowIdentity struct {
|
||||
Kind string
|
||||
Values []string
|
||||
}
|
||||
|
||||
// key retains the V1 ledger representation, but tuple components are validated
|
||||
// independently and used as separate SQL parameters, never as a single column.
|
||||
func (id typedRowIdentity) key() string { return strings.Join(id.Values, ":") }
|
||||
|
||||
func positiveBigint(raw json.RawMessage) (string, error) {
|
||||
raw = bytes.TrimSpace(raw)
|
||||
if len(raw) == 0 {
|
||||
return "", errors.New("missing integer")
|
||||
}
|
||||
for _, b := range raw {
|
||||
if b < '0' || b > '9' {
|
||||
return "", errors.New("expected JSON integer, not string/fraction/exponent")
|
||||
}
|
||||
}
|
||||
n, err := strconv.ParseInt(string(raw), 10, 64)
|
||||
if err != nil || n <= 0 || strconv.FormatInt(n, 10) != string(raw) {
|
||||
return "", errors.New("integer out of positive bigint range or noncanonical")
|
||||
}
|
||||
return string(raw), nil
|
||||
}
|
||||
|
||||
func parseRowIdentity(table string, row map[string]json.RawMessage) (typedRowIdentity, error) {
|
||||
contract, ok := migrationIdentityContracts[table]
|
||||
if !ok {
|
||||
return typedRowIdentity{}, fmt.Errorf("unknown migration identity contract: %s", table)
|
||||
}
|
||||
id := typedRowIdentity{Kind: contract.Kind}
|
||||
for _, column := range contract.Columns {
|
||||
var value string
|
||||
if contract.Kind == "local-bigint" {
|
||||
n, err := positiveBigint(row[column])
|
||||
if err != nil {
|
||||
return id, fmt.Errorf("%s.%s: %w", table, column, err)
|
||||
}
|
||||
value = n
|
||||
} else if err := json.Unmarshal(row[column], &value); err != nil || !validSearchIdentifier(value) || strings.Contains(value, ":") {
|
||||
return id, fmt.Errorf("invalid %s.%s identity", table, column)
|
||||
}
|
||||
id.Values = append(id.Values, value)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Publish without replacement: a second writer can only verify the already
|
||||
// committed bytes. Sync both the file and directory entries before returning an
|
||||
// anchor that another process may act on. This is not a power-loss test.
|
||||
func persistImmutableJSON(path string, raw []byte) error {
|
||||
directory := filepath.Dir(path)
|
||||
if err := ensureEvidenceDirectory(directory, syncEvidenceDirectory); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := os.Lstat(directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return errors.New("immutable evidence directory is not a real directory")
|
||||
}
|
||||
existing := func() error {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return errors.New("immutable evidence is not a regular file")
|
||||
}
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(body, raw) {
|
||||
return errors.New("immutable evidence already exists with different bytes")
|
||||
}
|
||||
return syncEvidenceDirectory(directory)
|
||||
}
|
||||
if _, err := os.Lstat(path); err == nil {
|
||||
return existing()
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
file, err := os.CreateTemp(directory, ".evidence-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temporary := file.Name()
|
||||
defer os.Remove(temporary)
|
||||
defer file.Close()
|
||||
if _, err := file.Write(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Chmod(0444); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Link(temporary, path); err != nil {
|
||||
if errors.Is(err, os.ErrExist) {
|
||||
return existing()
|
||||
}
|
||||
return fmt.Errorf("commit immutable evidence: %w", err)
|
||||
}
|
||||
if err := os.Remove(temporary); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncEvidenceDirectory(directory)
|
||||
}
|
||||
|
||||
func syncEvidenceDirectory(path string) error {
|
||||
directory, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer directory.Close()
|
||||
if err := directory.Sync(); err != nil {
|
||||
return fmt.Errorf("sync evidence directory: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
const indexClaimPrefix = "kg-release-transient-claim:"
|
||||
|
||||
// The transient marker is only visible inside the maintenance window. Final
|
||||
// content is byte-equivalent to the frozen source, without control-plane fields.
|
||||
// A matching payload alone never establishes ownership of an ambiguous write.
|
||||
func (t *ProductionLibraryTarget) indexClaimBody(c libraryrelease.IndexWrite) (json.RawMessage, error) {
|
||||
if len(c.After) == 0 {
|
||||
return nil, errors.New("deleted index document has no ownership marker")
|
||||
}
|
||||
var body map[string]json.RawMessage
|
||||
if json.Unmarshal(c.After, &body) != nil || body == nil {
|
||||
return nil, errors.New("invalid index claim source")
|
||||
}
|
||||
var content string
|
||||
if json.Unmarshal(body["content"], &content) != nil {
|
||||
return nil, errors.New("index claim requires existing string content field")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(t.activePlan.Digest + "\x00" + c.Index + "\x00" + c.ID + "\x00apply"))
|
||||
body["content"], _ = json.Marshal(indexClaimPrefix + hex.EncodeToString(sum[:]) + "\n" + content)
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return canonicalJSON(encoded)
|
||||
}
|
||||
func (t *ProductionLibraryTarget) applyIndexClaim(ctx context.Context, c libraryrelease.IndexWrite) (indexReceipt, error) {
|
||||
if len(c.After) == 0 {
|
||||
return t.mutatePlannedIndex(ctx, c, nil, c.SeqNo, c.PrimaryTerm, false)
|
||||
}
|
||||
body, err := t.indexClaimBody(c)
|
||||
if err != nil {
|
||||
return indexReceipt{}, err
|
||||
}
|
||||
receipt, err := t.mutatePlannedIndex(ctx, c, body, c.SeqNo, c.PrimaryTerm, len(c.Before) == 0)
|
||||
if err != nil {
|
||||
return receipt, err
|
||||
}
|
||||
receipt.Marked = true
|
||||
if err = t.saveIndexEffect(c, "claimed", &receipt); err != nil {
|
||||
return receipt, err
|
||||
}
|
||||
return t.finalizeIndexClaim(ctx, c)
|
||||
}
|
||||
func (t *ProductionLibraryTarget) reconcileIndexClaim(ctx context.Context, c libraryrelease.IndexWrite) (indexReceipt, error) {
|
||||
empty := indexReceipt{}
|
||||
intent, err := t.loadIndexEffect(c, "apply-intent")
|
||||
if err != nil {
|
||||
return empty, err
|
||||
}
|
||||
if intent == nil {
|
||||
return empty, errors.New("index claim has no durable intent")
|
||||
}
|
||||
finalizing, err := t.loadIndexEffect(c, "finalize-intent")
|
||||
if err != nil {
|
||||
return empty, err
|
||||
}
|
||||
if finalizing != nil {
|
||||
return empty, errors.New("unknown clean finalization cannot be attributed by appearance")
|
||||
}
|
||||
body, err := t.indexClaimBody(c)
|
||||
if err != nil {
|
||||
return empty, err
|
||||
}
|
||||
g, err := t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return empty, err
|
||||
}
|
||||
if !indexBytesEqual(g, body) || g.SeqNo == nil || g.PrimaryTerm == nil {
|
||||
return empty, errors.New("unknown index effect lacks exact operation marker/content/CAS")
|
||||
}
|
||||
claimed, err := t.loadIndexEffect(c, "claimed")
|
||||
if err != nil {
|
||||
return empty, err
|
||||
}
|
||||
if claimed != nil {
|
||||
if claimed.Receipt == nil || !claimed.Receipt.Marked || !sameIndexGeneration(g, claimed.Receipt.SeqNo, claimed.Receipt.PrimaryTerm) {
|
||||
return empty, errors.New("claimed index generation changed")
|
||||
}
|
||||
return *claimed.Receipt, nil
|
||||
}
|
||||
result := "updated"
|
||||
if len(c.Before) == 0 {
|
||||
result = "created"
|
||||
}
|
||||
receipt := indexReceipt{Index: c.Index, ID: c.ID, Result: result, SeqNo: g.SeqNo, PrimaryTerm: g.PrimaryTerm, Marked: true}
|
||||
if err = t.saveIndexEffect(c, "claimed", &receipt); err != nil {
|
||||
return empty, err
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
func (t *ProductionLibraryTarget) finalizeIndexClaim(ctx context.Context, c libraryrelease.IndexWrite) (indexReceipt, error) {
|
||||
receipt, err := t.reconcileIndexClaim(ctx, c)
|
||||
if err != nil {
|
||||
return indexReceipt{}, err
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "finalize-intent", &receipt); err != nil {
|
||||
return indexReceipt{}, err
|
||||
}
|
||||
return t.mutatePlannedIndex(ctx, c, c.After, receipt.SeqNo, receipt.PrimaryTerm, false)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
// Unlike an ambiguous create, deletion of a known CAS generation can settle on
|
||||
// absence: a delayed delete still carries that old seq_no/primary_term and cannot
|
||||
// delete a subsequently recreated generation. This never infers PUT completion.
|
||||
func (t *ProductionLibraryTarget) reconcileIndexCompensationDelete(ctx context.Context, c libraryrelease.IndexWrite) (bool, error) {
|
||||
if len(c.Before) != 0 || len(c.After) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
intent, e := t.loadIndexEffect(c, "restore-intent")
|
||||
if e != nil || intent == nil {
|
||||
return false, e
|
||||
}
|
||||
if intent.Receipt == nil || *intent.Receipt.SeqNo < 0 || *intent.Receipt.PrimaryTerm < 1 {
|
||||
return false, errors.New("index delete compensation lacks known generation")
|
||||
}
|
||||
proof, e := t.loadIndexEffect(c, "applied")
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
if proof == nil {
|
||||
proof, e = t.loadIndexEffect(c, "claimed")
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
}
|
||||
if proof == nil || proof.Receipt == nil {
|
||||
return false, errors.New("index delete compensation lacks persisted ownership")
|
||||
}
|
||||
want, _ := json.Marshal(proof.Receipt)
|
||||
got, _ := json.Marshal(intent.Receipt)
|
||||
if !bytes.Equal(want, got) {
|
||||
return false, errors.New("index delete compensation CAS differs from owned receipt")
|
||||
}
|
||||
observation, e := t.observePlannedIndex(ctx, c)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
if observation.Found {
|
||||
return false, nil
|
||||
}
|
||||
// No fabricated DELETE response/generation: proof is the bound restore intent,
|
||||
// persisted ownership receipt and independent authoritative absent observation.
|
||||
if e = t.saveIndexEffect(c, "restored", nil); e != nil {
|
||||
return false, e
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
type indexReceipt struct {
|
||||
Index string `json:"_index"`
|
||||
ID string `json:"_id"`
|
||||
Result string `json:"result"`
|
||||
SeqNo *int64 `json:"_seq_no"`
|
||||
PrimaryTerm *int64 `json:"_primary_term"`
|
||||
Marked bool `json:"marked,omitempty"`
|
||||
}
|
||||
type indexEffect struct {
|
||||
Plan string `json:"plan"`
|
||||
Change libraryrelease.IndexWrite `json:"change"`
|
||||
Receipt *indexReceipt `json:"receipt,omitempty"`
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) indexEffectPath(c libraryrelease.IndexWrite, phase string) string {
|
||||
sum := sha256.Sum256([]byte(c.Index + "\x00" + c.ID))
|
||||
return filepath.Join(t.config.ArchiveRoot, "effects", t.activePlan.Digest, "index", hex.EncodeToString(sum[:]), phase+".json")
|
||||
}
|
||||
func (t *ProductionLibraryTarget) saveIndexEffect(c libraryrelease.IndexWrite, phase string, r *indexReceipt) error {
|
||||
raw, err := json.Marshal(indexEffect{t.activePlan.Digest, c, r})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return persistImmutableJSON(t.indexEffectPath(c, phase), raw)
|
||||
}
|
||||
func (t *ProductionLibraryTarget) loadIndexEffect(c libraryrelease.IndexWrite, phase string) (*indexEffect, error) {
|
||||
path := t.indexEffectPath(c, phase)
|
||||
exists, err := effectExists(path)
|
||||
if err != nil || !exists {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var e indexEffect
|
||||
if json.Unmarshal(raw, &e) != nil {
|
||||
return nil, errors.New("invalid index effect evidence")
|
||||
}
|
||||
want, _ := json.Marshal(c)
|
||||
got, _ := json.Marshal(e.Change)
|
||||
if e.Plan != t.activePlan.Digest || !bytes.Equal(want, got) {
|
||||
return nil, errors.New("index effect binding differs from immutable plan")
|
||||
}
|
||||
if e.Receipt != nil && (e.Receipt.Index != c.Index || e.Receipt.ID != c.ID || e.Receipt.SeqNo == nil || e.Receipt.PrimaryTerm == nil) {
|
||||
return nil, errors.New("incomplete index receipt")
|
||||
}
|
||||
return &e, nil
|
||||
}
|
||||
func (t *ProductionLibraryTarget) observePlannedIndex(ctx context.Context, c libraryrelease.IndexWrite) (indexWriteGuard, error) {
|
||||
guards, err := t.search.indexWriteGuards(ctx, []librarysnapshot.IndexDocument{{ID: c.ID}}, SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID})
|
||||
if err != nil {
|
||||
return indexWriteGuard{}, err
|
||||
}
|
||||
return guards[c.ID], nil
|
||||
}
|
||||
func indexBytesEqual(g indexWriteGuard, want json.RawMessage) bool {
|
||||
if len(want) == 0 {
|
||||
return !g.Found
|
||||
}
|
||||
if !g.Found {
|
||||
return false
|
||||
}
|
||||
raw, err := canonicalJSON(g.Source)
|
||||
return err == nil && bytes.Equal(raw, want)
|
||||
}
|
||||
func sameIndexGeneration(g indexWriteGuard, seq, term *int64) bool {
|
||||
return g.Found && g.SeqNo != nil && g.PrimaryTerm != nil && seq != nil && term != nil && *g.SeqNo == *seq && *g.PrimaryTerm == *term
|
||||
}
|
||||
|
||||
// Each network mutation has an immutable intent before send and a per-ID
|
||||
// server generation receipt. A lost response is UNKNOWN, never "did not write".
|
||||
// No retry is issued for an unresolved intent; downstream ownership fencing is
|
||||
// required before unknown operations can be conclusively reconciled.
|
||||
func (t *ProductionLibraryTarget) applyPlannedIndex(ctx context.Context) error {
|
||||
for _, c := range t.activePlan.Index {
|
||||
if bytes.Equal(c.Before, c.After) {
|
||||
continue
|
||||
}
|
||||
applied, err := t.loadIndexEffect(c, "applied")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if applied != nil {
|
||||
if applied.Receipt == nil {
|
||||
return errors.New("index receipt missing")
|
||||
}
|
||||
g, err := t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !indexBytesEqual(g, c.After) || (len(c.After) > 0 && !sameIndexGeneration(g, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm)) {
|
||||
return errors.New("index changed after confirmed apply")
|
||||
}
|
||||
continue
|
||||
}
|
||||
intent, err := t.loadIndexEffect(c, "apply-intent")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if intent != nil {
|
||||
if _, err := t.reconcileIndexClaim(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
receipt, err := t.finalizeIndexClaim(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.saveIndexEffect(c, "applied", &receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
g, err := t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !indexBytesEqual(g, c.Before) || (len(c.Before) > 0 && !sameIndexGeneration(g, c.SeqNo, c.PrimaryTerm)) {
|
||||
return errors.New("index changed since frozen plan")
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "apply-intent", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
receipt, err := t.applyIndexClaim(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "applied", &receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
g, err = t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !indexBytesEqual(g, c.After) || (len(c.After) > 0 && !sameIndexGeneration(g, receipt.SeqNo, receipt.PrimaryTerm)) {
|
||||
return errors.New("index readback differs from receipt")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (t *ProductionLibraryTarget) mutatePlannedIndex(ctx context.Context, c libraryrelease.IndexWrite, body json.RawMessage, seq, term *int64, create bool) (indexReceipt, error) {
|
||||
method := http.MethodPut
|
||||
endpoint := "_doc"
|
||||
if create {
|
||||
endpoint = "_create"
|
||||
}
|
||||
if len(body) == 0 {
|
||||
method = http.MethodDelete
|
||||
}
|
||||
query := url.Values{"refresh": {"true"}}
|
||||
if !create {
|
||||
if seq == nil || term == nil {
|
||||
return indexReceipt{}, errors.New("index mutation lacks CAS")
|
||||
}
|
||||
query.Set("if_seq_no", fmt.Sprint(*seq))
|
||||
query.Set("if_primary_term", fmt.Sprint(*term))
|
||||
}
|
||||
path := "/" + url.PathEscape(c.Index) + "/" + endpoint + "/" + url.PathEscape(c.ID) + "?" + query.Encode()
|
||||
var payload any
|
||||
if len(body) > 0 {
|
||||
payload = body
|
||||
}
|
||||
var receipt indexReceipt
|
||||
if err := t.search.requestJSON(ctx, method, path, payload, &receipt); err != nil {
|
||||
return receipt, fmt.Errorf("index effect outcome unknown: %w", err)
|
||||
}
|
||||
if receipt.ID != c.ID || receipt.Index != c.Index || receipt.SeqNo == nil || receipt.PrimaryTerm == nil {
|
||||
return receipt, errors.New("index mutation receipt incomplete")
|
||||
}
|
||||
if len(body) == 0 && receipt.Result != "deleted" || len(body) > 0 && receipt.Result != "created" && receipt.Result != "updated" {
|
||||
return receipt, errors.New("index mutation receipt not confirmed")
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
func (t *ProductionLibraryTarget) restorePlannedIndex(ctx context.Context) error {
|
||||
for _, c := range t.activePlan.Index {
|
||||
intent, err := t.loadIndexEffect(c, "apply-intent")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if intent == nil {
|
||||
continue
|
||||
}
|
||||
// Completed compensation is read back before attempting to reconcile an
|
||||
// old marked apply; the marker was intentionally removed by restoration.
|
||||
done, err := t.loadIndexEffect(c, "restored")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if done != nil {
|
||||
g, err := t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !indexBytesEqual(g, c.Before) || (len(c.Before) > 0 && (done.Receipt == nil || !sameIndexGeneration(g, done.Receipt.SeqNo, done.Receipt.PrimaryTerm))) {
|
||||
return errors.New("restored index changed")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if reconciled, err := t.reconcileIndexCompensationDelete(ctx, c); err != nil {
|
||||
return err
|
||||
} else if reconciled {
|
||||
continue
|
||||
}
|
||||
applied, err := t.loadIndexEffect(c, "applied")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if applied == nil {
|
||||
receipt, err := t.reconcileIndexClaim(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
applied = &indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &receipt}
|
||||
}
|
||||
if applied.Receipt == nil {
|
||||
return errors.New("missing index compensation receipt")
|
||||
}
|
||||
g, err := t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
restoring, err := t.loadIndexEffect(c, "restore-intent")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if restoring != nil {
|
||||
if len(c.Before) > 0 {
|
||||
if err := t.restoreClaimedIndexBefore(ctx, c, *applied.Receipt, false); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
return errors.New("unknown index compensation requires reconciliation")
|
||||
}
|
||||
expected := c.After
|
||||
if applied.Receipt.Marked {
|
||||
expected, err = t.indexClaimBody(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !indexBytesEqual(g, expected) || (len(expected) > 0 && !sameIndexGeneration(g, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm)) {
|
||||
return errors.New("another writer changed index; compensation refused")
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "restore-intent", applied.Receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(c.Before) > 0 {
|
||||
if err := t.restoreClaimedIndexBefore(ctx, c, *applied.Receipt, true); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
receipt, err := t.mutatePlannedIndex(ctx, c, c.Before, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm, len(c.After) == 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "restored", &receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
g, err = t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !indexBytesEqual(g, c.Before) {
|
||||
return errors.New("index compensation readback failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"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.Tenant != identity.TenantID || owner.KB != identity.KnowledgeBaseID {
|
||||
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 _, err := t.search.indexWriteGuards(ctx, docs, SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}); 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)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
func archiveIndexMap(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) (map[string]json.RawMessage, error) {
|
||||
out := map[string]json.RawMessage{}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind != "index" {
|
||||
continue
|
||||
}
|
||||
reader, err := archive.OpenPart(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
docs, err := librarysnapshot.ReadIndexDocuments(reader)
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, doc := range docs {
|
||||
if doc.ID == "" {
|
||||
return nil, errors.New("empty index ID")
|
||||
}
|
||||
if _, ok := out[doc.ID]; ok {
|
||||
return nil, errors.New("duplicate index ID")
|
||||
}
|
||||
raw, err := canonicalJSON(doc.Source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[doc.ID] = raw
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func targetIndexSource(raw json.RawMessage, tenant uint64, kb string) (json.RawMessage, error) {
|
||||
var source map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &source) != nil || source == nil {
|
||||
return nil, errors.New("index source must be object")
|
||||
}
|
||||
var content string
|
||||
if json.Unmarshal(source["content"], &content) != nil || strings.HasPrefix(content, indexClaimPrefix) {
|
||||
return nil, errors.New("index source lacks string content or contains an unfinished transient claim")
|
||||
}
|
||||
source["tenant_id"], _ = json.Marshal(tenant)
|
||||
source["knowledge_base_id"], _ = json.Marshal(kb)
|
||||
encoded, err := json.Marshal(source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return canonicalJSON(encoded)
|
||||
}
|
||||
func (t *ProductionLibraryTarget) planIndex(ctx context.Context, archive *librarysnapshot.Archive, source librarysnapshot.Manifest, set *libraryrelease.WriteSet) error {
|
||||
backup, err := archive.Load(set.BackupSnapshotID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
before, err := archiveIndexMap(archive, backup)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
after, err := archiveIndexMap(archive, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
for id := range before {
|
||||
ids[id] = true
|
||||
}
|
||||
for id := range after {
|
||||
ids[id] = true
|
||||
}
|
||||
sorted := make([]string, 0, len(ids))
|
||||
for id := range ids {
|
||||
sorted = append(sorted, id)
|
||||
}
|
||||
sort.Strings(sorted)
|
||||
docs := make([]librarysnapshot.IndexDocument, 0, len(ids))
|
||||
for _, id := range sorted {
|
||||
docs = append(docs, librarysnapshot.IndexDocument{ID: id})
|
||||
}
|
||||
guards, err := t.search.indexWriteGuards(ctx, docs, SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range sorted {
|
||||
g := guards[id]
|
||||
expected, existed := before[id]
|
||||
if existed != g.Found {
|
||||
return errors.New("index before-image no longer covers exact write set")
|
||||
}
|
||||
if existed {
|
||||
raw, err := canonicalJSON(g.Source)
|
||||
if err != nil || !bytes.Equal(raw, expected) {
|
||||
return errors.New("index changed since before-image")
|
||||
}
|
||||
}
|
||||
var wanted json.RawMessage
|
||||
if raw, ok := after[id]; ok {
|
||||
wanted, err = targetIndexSource(raw, t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
set.Index = append(set.Index, libraryrelease.IndexWrite{Index: t.search.index, ID: id, Before: expected, SeqNo: g.SeqNo, PrimaryTerm: g.PrimaryTerm, After: wanted})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) validateIndexPlanBinding(archive *librarysnapshot.Archive, source, backup librarysnapshot.Manifest, set libraryrelease.WriteSet) error {
|
||||
before, err := archiveIndexMap(archive, backup)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
after, err := archiveIndexMap(archive, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
for id := range before {
|
||||
ids[id] = true
|
||||
}
|
||||
for id := range after {
|
||||
ids[id] = true
|
||||
}
|
||||
if len(ids) != len(set.Index) {
|
||||
return errors.New("index plan coverage mismatch")
|
||||
}
|
||||
for _, change := range set.Index {
|
||||
if !ids[change.ID] || change.Index != t.search.index {
|
||||
return errors.New("index plan physical identity mismatch")
|
||||
}
|
||||
delete(ids, change.ID)
|
||||
var wanted json.RawMessage
|
||||
if raw, ok := after[change.ID]; ok {
|
||||
wanted, err = targetIndexSource(raw, set.TenantID, set.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(before[change.ID], change.Before) || !bytes.Equal(wanted, change.After) {
|
||||
return errors.New("index plan bytes differ from immutable archives")
|
||||
}
|
||||
if len(change.Before) > 0 && (change.SeqNo == nil || change.PrimaryTerm == nil) {
|
||||
return errors.New("existing index document lacks CAS identity")
|
||||
}
|
||||
if len(change.Before) == 0 && (change.SeqNo != nil || change.PrimaryTerm != nil) {
|
||||
return errors.New("absent index document has invalid CAS identity")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
const indexRestoreClaimPrefix = "kg-release-transient-restore-claim:"
|
||||
|
||||
func (t *ProductionLibraryTarget) restoreIndexClaimBody(c libraryrelease.IndexWrite) (json.RawMessage, error) {
|
||||
var body map[string]json.RawMessage
|
||||
if json.Unmarshal(c.Before, &body) != nil || body == nil {
|
||||
return nil, errors.New("restore claim requires frozen before-image")
|
||||
}
|
||||
var content string
|
||||
if json.Unmarshal(body["content"], &content) != nil {
|
||||
return nil, errors.New("restore claim requires existing content field")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(t.activePlan.Digest + "\x00" + c.Index + "\x00" + c.ID + "\x00restore"))
|
||||
body["content"], _ = json.Marshal(indexRestoreClaimPrefix + hex.EncodeToString(sum[:]) + "\n" + content)
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return canonicalJSON(encoded)
|
||||
}
|
||||
|
||||
// Only a plan-specific marker plus the entire frozen body can reconcile a lost
|
||||
// restore-write response. Equal clean content is not proof of who wrote it.
|
||||
// Old unknown writes without this pre-send intent remain held, not adopted.
|
||||
func (t *ProductionLibraryTarget) restoreClaimedIndexBefore(ctx context.Context, c libraryrelease.IndexWrite, applied indexReceipt, start bool) error {
|
||||
body, err := t.restoreIndexClaimBody(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
markIntent, err := t.loadIndexEffect(c, "restore-mark-intent")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
claimed, err := t.loadIndexEffect(c, "restore-claimed")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if markIntent == nil {
|
||||
if !start {
|
||||
return errors.New("legacy unknown index restoration lacks attributable marker intent")
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "restore-mark-intent", &applied); err != nil {
|
||||
return err
|
||||
}
|
||||
receipt, err := t.mutatePlannedIndex(ctx, c, body, applied.SeqNo, applied.PrimaryTerm, len(c.After) == 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
receipt.Marked = true
|
||||
if err = t.saveIndexEffect(c, "restore-claimed", &receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
claimed = &indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &receipt}
|
||||
}
|
||||
finalizing, err := t.loadIndexEffect(c, "restore-finalize-intent")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if finalizing != nil {
|
||||
return errors.New("unknown clean restoration cannot be attributed by appearance; held")
|
||||
}
|
||||
observed, err := t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !indexBytesEqual(observed, body) || observed.SeqNo == nil || observed.PrimaryTerm == nil {
|
||||
return errors.New("unknown restoration lacks exact operation marker/content/CAS; held")
|
||||
}
|
||||
if claimed == nil {
|
||||
receipt := indexReceipt{Index: c.Index, ID: c.ID, Result: "updated", SeqNo: observed.SeqNo, PrimaryTerm: observed.PrimaryTerm, Marked: true}
|
||||
if len(c.After) == 0 {
|
||||
receipt.Result = "created"
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "restore-claimed", &receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
claimed = &indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &receipt}
|
||||
}
|
||||
if claimed.Receipt == nil || !claimed.Receipt.Marked || !sameIndexGeneration(observed, claimed.Receipt.SeqNo, claimed.Receipt.PrimaryTerm) {
|
||||
return errors.New("restoration claim generation changed; held")
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "restore-finalize-intent", claimed.Receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
receipt, err := t.mutatePlannedIndex(ctx, c, c.Before, claimed.Receipt.SeqNo, claimed.Receipt.PrimaryTerm, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = t.saveIndexEffect(c, "restored", &receipt); err != nil {
|
||||
return err
|
||||
}
|
||||
observed, err = t.observePlannedIndex(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !indexBytesEqual(observed, c.Before) || !sameIndexGeneration(observed, receipt.SeqNo, receipt.PrimaryTerm) {
|
||||
return errors.New("restoration clean readback differs from receipt")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// Compile local number requests without changing sequence state. Allocation is
|
||||
// a separate, explicitly mutating phase after the backup and P0 are durable.
|
||||
func (t *ProductionLibraryTarget) localIDRequests(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) ([]libraryrelease.LocalIDMapping, error) {
|
||||
var result []libraryrelease.LocalIDMapping
|
||||
seen := map[string]bool{}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind != "database" && part.Kind != "wiki" {
|
||||
continue
|
||||
}
|
||||
contract, ok := migrationIdentityContracts[part.Name]
|
||||
if !ok {
|
||||
if part.Count != 0 {
|
||||
return nil, fmt.Errorf("unknown table %s", part.Name)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if contract.LocalColumn == "" {
|
||||
continue
|
||||
}
|
||||
reader, err := archive.OpenPart(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rows []map[string]json.RawMessage
|
||||
err = json.NewDecoder(reader).Decode(&rows)
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
raw, ok := row[contract.LocalColumn]
|
||||
if !ok && contract.LocalColumn != "id" {
|
||||
continue
|
||||
} // older snapshots lacking the added column remain explicit legacy input
|
||||
source, err := positiveBigint(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s.%s: %w", part.Name, contract.LocalColumn, err)
|
||||
}
|
||||
key := part.Name + "/" + source
|
||||
if seen[key] {
|
||||
return nil, fmt.Errorf("duplicate local identity %s", key)
|
||||
}
|
||||
seen[key] = true
|
||||
result = append(result, libraryrelease.LocalIDMapping{Table: part.Name, Column: contract.LocalColumn, Source: source})
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].Table != result[j].Table {
|
||||
return result[i].Table < result[j].Table
|
||||
}
|
||||
a, _ := strconv.ParseInt(result[i].Source, 10, 64)
|
||||
b, _ := strconv.ParseInt(result[j].Source, 10, 64)
|
||||
return a < b
|
||||
})
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) allocateLocalIDs(ctx context.Context, set *libraryrelease.WriteSet) error {
|
||||
// Preflight every sequence before consuming even one value. No setval and no
|
||||
// rewind on failure: an unanchored allocation can leave holes, never aliases.
|
||||
checked := map[string]bool{}
|
||||
for _, mapping := range set.LocalIDs {
|
||||
if checked[mapping.Table] {
|
||||
continue
|
||||
}
|
||||
checked[mapping.Table] = true
|
||||
contract := migrationIdentityContracts[mapping.Table]
|
||||
var datatype, def string
|
||||
err := t.pool.QueryRow(ctx, `SELECT format_type(a.atttypid,a.atttypmod),coalesce(pg_get_expr(d.adbin,d.adrelid),'') FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum WHERE n.nspname='public' AND c.relname=$1 AND a.attname=$2 AND NOT a.attisdropped`, mapping.Table, mapping.Column).Scan(&datatype, &def)
|
||||
if err != nil || datatype != "bigint" || def != "nextval('"+contract.Sequence+"'::regclass)" {
|
||||
return fmt.Errorf("local sequence schema mismatch: %s.%s", mapping.Table, mapping.Column)
|
||||
}
|
||||
var increment, maximum, cache int64
|
||||
var cycle bool
|
||||
if err := t.pool.QueryRow(ctx, `SELECT seqincrement,seqmax,seqcache,seqcycle FROM pg_sequence WHERE seqrelid=to_regclass($1)`, contract.Sequence).Scan(&increment, &maximum, &cache, &cycle); err != nil {
|
||||
return err
|
||||
}
|
||||
if increment != 1 || cycle || cache != 1 {
|
||||
return errors.New("unsupported local sequence allocation policy")
|
||||
}
|
||||
var last, maxUsed int64
|
||||
var called bool
|
||||
if err := t.pool.QueryRow(ctx, fmt.Sprintf(`SELECT last_value,is_called FROM %s`, contract.Sequence)).Scan(&last, &called); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.pool.QueryRow(ctx, fmt.Sprintf(`SELECT coalesce(max(%s),0) FROM %s`, mapping.Column, mapping.Table)).Scan(&maxUsed); err != nil {
|
||||
return err
|
||||
}
|
||||
next := last
|
||||
if called {
|
||||
if last >= maximum {
|
||||
return errors.New("local sequence exhausted")
|
||||
}
|
||||
next++
|
||||
}
|
||||
count := int64(0)
|
||||
for _, m := range set.LocalIDs {
|
||||
if m.Table == mapping.Table {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if next <= maxUsed || count-1 > maximum-next {
|
||||
return fmt.Errorf("local sequence behind occupied values or exhausted: %s", contract.Sequence)
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(set)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
if err := persistImmutableJSON(filepath.Join(t.config.ArchiveRoot, "plans-p0", hex.EncodeToString(sum[:])+".json"), raw); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range set.LocalIDs {
|
||||
mapping := &set.LocalIDs[i]
|
||||
contract := migrationIdentityContracts[mapping.Table]
|
||||
var allocated int64
|
||||
if err := t.pool.QueryRow(ctx, `SELECT nextval($1::regclass)`, contract.Sequence).Scan(&allocated); err != nil {
|
||||
return err
|
||||
}
|
||||
var occupied bool
|
||||
if err := t.pool.QueryRow(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM %s WHERE %s=$1)`, mapping.Table, mapping.Column), allocated).Scan(&occupied); err != nil {
|
||||
return err
|
||||
}
|
||||
if occupied {
|
||||
return errors.New("allocated local identity already occupied; maintenance/fence lost")
|
||||
}
|
||||
mapping.Target = strconv.FormatInt(allocated, 10)
|
||||
if contract.Kind == "local-bigint" {
|
||||
set.Rows = append(set.Rows, libraryrelease.WriteSetRow{Table: mapping.Table, ID: mapping.Target})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) mapLocalID(table string, row map[string]json.RawMessage) (bool, error) {
|
||||
if t.activePlan == nil || t.activeSnapshot != t.activePlan.TargetSnapshotID || t.preserveChunkSequence {
|
||||
return false, nil
|
||||
}
|
||||
contract := migrationIdentityContracts[table]
|
||||
if contract.LocalColumn == "" {
|
||||
return false, nil
|
||||
}
|
||||
raw, ok := row[contract.LocalColumn]
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
source, err := positiveBigint(raw)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, mapping := range t.activePlan.LocalIDs {
|
||||
if mapping.Table == table && mapping.Column == contract.LocalColumn && mapping.Source == source {
|
||||
row[contract.LocalColumn] = json.RawMessage(mapping.Target)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, fmt.Errorf("missing persisted local mapping: %s.%s", table, contract.LocalColumn)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
type migrationUniqueKey struct {
|
||||
Name string
|
||||
Columns []string
|
||||
Predicate string
|
||||
NullsEqual bool
|
||||
Expression bool
|
||||
}
|
||||
|
||||
// Preflight all catalog unique keys, including partial indexes. Source-local
|
||||
// sequence keys are checked separately by the allocator, never compared as UUIDs.
|
||||
func (t *ProductionLibraryTarget) preflightNaturalKeys(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error {
|
||||
for _, part := range manifest.Parts {
|
||||
if (part.Kind != "database" && part.Kind != "wiki") || part.Count == 0 {
|
||||
continue
|
||||
}
|
||||
contract, known := migrationIdentityContracts[part.Name]
|
||||
if !known {
|
||||
return errors.New("unknown natural-key contract")
|
||||
}
|
||||
reader, err := archive.OpenPart(part)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var source []map[string]json.RawMessage
|
||||
err = json.NewDecoder(reader).Decode(&source)
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range source {
|
||||
if err := t.retargetRow(part.Name, row); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := t.pool.Query(ctx, `SELECT ic.relname,ARRAY(SELECT a.attname::text FROM unnest(i.indkey) WITH ORDINALITY k(attnum,ord) JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=k.attnum WHERE k.ord<=i.indnkeyatts ORDER BY k.ord),coalesce(pg_get_expr(i.indpred,i.indrelid),''),i.indnullsnotdistinct,i.indexprs IS NOT NULL FROM pg_index i JOIN pg_class c ON c.oid=i.indrelid JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_class ic ON ic.oid=i.indexrelid WHERE n.nspname='public' AND c.relname=$1 AND i.indisunique ORDER BY ic.relname`, part.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var keys []migrationUniqueKey
|
||||
for rows.Next() {
|
||||
var key migrationUniqueKey
|
||||
if err := rows.Scan(&key.Name, &key.Columns, &key.Predicate, &key.NullsEqual, &key.Expression); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
table := pgx.Identifier{"public", part.Name}.Sanitize()
|
||||
recordset := "jsonb_populate_recordset(NULL::" + table + ",$1::jsonb)"
|
||||
for _, key := range keys {
|
||||
if key.Expression || len(key.Columns) == 0 {
|
||||
return fmt.Errorf("unreviewed unique expression: %s", key.Name)
|
||||
}
|
||||
skip := false
|
||||
for _, column := range key.Columns {
|
||||
if column == contract.LocalColumn {
|
||||
skip = true
|
||||
}
|
||||
}
|
||||
if skip {
|
||||
continue
|
||||
}
|
||||
predicate := "true"
|
||||
if key.Predicate != "" {
|
||||
predicate = key.Predicate
|
||||
}
|
||||
cols, nonnull, join := []string{}, []string{}, []string{}
|
||||
for _, column := range key.Columns {
|
||||
q := pgx.Identifier{column}.Sanitize()
|
||||
cols = append(cols, q)
|
||||
nonnull = append(nonnull, q+" IS NOT NULL")
|
||||
op := "="
|
||||
if key.NullsEqual {
|
||||
op = "IS NOT DISTINCT FROM"
|
||||
}
|
||||
join = append(join, "s."+q+" "+op+" t."+q)
|
||||
}
|
||||
sourceFilter := predicate
|
||||
if !key.NullsEqual {
|
||||
sourceFilter += " AND " + strings.Join(nonnull, " AND ")
|
||||
}
|
||||
var conflict bool
|
||||
query := "SELECT EXISTS(SELECT 1 FROM " + recordset + " s WHERE " + sourceFilter + " GROUP BY " + strings.Join(cols, ",") + " HAVING count(*)>1)"
|
||||
if err := t.pool.QueryRow(ctx, query, raw).Scan(&conflict); err != nil {
|
||||
return fmt.Errorf("source unique preflight %s: %w", key.Name, err)
|
||||
}
|
||||
if conflict {
|
||||
return fmt.Errorf("source duplicates natural key %s", key.Name)
|
||||
}
|
||||
targetFilter := predicate
|
||||
args := []any{raw}
|
||||
if part.Name != "resources" {
|
||||
scope := strings.ReplaceAll(strings.ReplaceAll(scopeWhere(part.Name), "$2", "$3"), "$1", "$2")
|
||||
targetFilter += " AND NOT (" + scope + ")"
|
||||
args = append(args, t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||||
}
|
||||
query = "SELECT EXISTS(SELECT 1 FROM (SELECT * FROM " + recordset + " WHERE " + sourceFilter + ") s JOIN (SELECT * FROM " + table + " WHERE " + targetFilter + ") t ON " + strings.Join(join, " AND ") + ")"
|
||||
// Equal resource ID is handled by immutable row/object reuse evidence.
|
||||
if part.Name == "resources" {
|
||||
query = strings.TrimSuffix(query, ")") + " WHERE s.id IS DISTINCT FROM t.id)"
|
||||
}
|
||||
if err := t.pool.QueryRow(ctx, query, args...).Scan(&conflict); err != nil {
|
||||
return fmt.Errorf("target unique preflight %s: %w", key.Name, err)
|
||||
}
|
||||
if conflict {
|
||||
return fmt.Errorf("target natural key conflict outside replace scope: %s", key.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
func (t *ProductionLibraryTarget) planObjects(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest, set *libraryrelease.WriteSet) error {
|
||||
objects := map[string]librarysnapshot.Part{}
|
||||
for _, p := range manifest.Parts {
|
||||
if p.Kind == "resource" {
|
||||
if _, exists := objects[p.Name]; exists {
|
||||
return errors.New("duplicate object resource identity")
|
||||
}
|
||||
objects[p.Name] = p
|
||||
}
|
||||
}
|
||||
if len(objects) == 0 {
|
||||
return nil
|
||||
}
|
||||
store, ok := t.config.Objects.(conditionalObjectStore)
|
||||
if !ok {
|
||||
return errors.New("target lacks conditional object effects")
|
||||
}
|
||||
if err := store.ConditionalCapability(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind != "database" || part.Name != "resources" {
|
||||
continue
|
||||
}
|
||||
reader, err := archive.OpenPart(part)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var rows []map[string]json.RawMessage
|
||||
err = json.NewDecoder(reader).Decode(&rows)
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
var id string
|
||||
if err := json.Unmarshal(row["id"], &id); err != nil {
|
||||
return err
|
||||
}
|
||||
blob, exists := objects[id]
|
||||
if !exists {
|
||||
return errors.New("resource has no bound object blob")
|
||||
}
|
||||
if err := t.retargetRow("resources", row); err != nil {
|
||||
return err
|
||||
}
|
||||
obj := libraryrelease.ObjectWrite{ResourceID: id, SHA256: blob.SHA256, Bytes: blob.Bytes}
|
||||
if json.Unmarshal(row["provider"], &obj.Provider) != nil || json.Unmarshal(row["physical_path"], &obj.Locator) != nil {
|
||||
return errors.New("resource locator missing")
|
||||
}
|
||||
rest := strings.TrimPrefix(obj.Locator, "storage://")
|
||||
parts := strings.SplitN(rest, "/", 2)
|
||||
if rest == obj.Locator || len(parts) != 2 {
|
||||
return errors.New("object needs explicit backend/bucket/key")
|
||||
}
|
||||
obj.BackendID = parts[0]
|
||||
physical := strings.TrimPrefix(parts[1], obj.Provider+"://")
|
||||
location := strings.SplitN(physical, "/", 2)
|
||||
if physical == parts[1] || len(location) != 2 || location[0] == "" || location[1] == "" {
|
||||
return errors.New("invalid physical object identity")
|
||||
}
|
||||
obj.Bucket, obj.Key = location[0], location[1]
|
||||
// Backend aliases cannot make a shared physical key look independent.
|
||||
key := obj.Provider + "/" + obj.Bucket + "/" + obj.Key
|
||||
if seen[key] {
|
||||
return errors.New("duplicate physical object destination")
|
||||
}
|
||||
seen[key] = true
|
||||
token := sha256.Sum256([]byte(set.JobID + "\x00" + set.Target + "\x00" + set.BackupSnapshotID + "\x00" + set.TargetSnapshotID + "\x00" + key))
|
||||
obj.OwnerToken = hex.EncodeToString(token[:])
|
||||
observation, err := store.ObserveObject(ctx, obj.Provider, obj.Locator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
obj.Existing, obj.BeforeETag = observation.Exists, observation.ETag
|
||||
obj.BeforeVersionID = observation.VersionID
|
||||
if observation.Exists && (observation.SHA256 != obj.SHA256 || observation.Bytes != obj.Bytes) {
|
||||
return errors.New("different existing object cannot be recoverably overwritten")
|
||||
}
|
||||
set.Objects = append(set.Objects, obj)
|
||||
delete(objects, id)
|
||||
}
|
||||
}
|
||||
if len(objects) != 0 {
|
||||
return errors.New("object blob lacks resource identity")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) objectEffectPath(obj libraryrelease.ObjectWrite, phase string) string {
|
||||
sum := sha256.Sum256([]byte(obj.Provider + "\x00" + obj.Bucket + "\x00" + obj.Key))
|
||||
return filepath.Join(t.config.ArchiveRoot, "effects", t.activePlan.Digest, "objects", hex.EncodeToString(sum[:]), phase+".json")
|
||||
}
|
||||
|
||||
func effectExists(path string) (bool, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return false, errors.New("effect evidence is not a regular file")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) recordObjectEffect(obj libraryrelease.ObjectWrite, phase string, observation objectObservation) error {
|
||||
raw, err := json.Marshal(struct {
|
||||
Plan string `json:"plan"`
|
||||
Object libraryrelease.ObjectWrite `json:"object"`
|
||||
Observation objectObservation `json:"observation"`
|
||||
}{t.activePlan.Digest, obj, observation})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return persistImmutableJSON(t.objectEffectPath(obj, phase), raw)
|
||||
}
|
||||
|
||||
func matchesObject(obj libraryrelease.ObjectWrite, observed objectObservation, owned bool) bool {
|
||||
return observed.Exists && observed.Bytes == obj.Bytes && observed.SHA256 == obj.SHA256 && (!owned || (observed.Owner == obj.OwnerToken && observed.VersionID != "" && observed.VersionID != "null"))
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) applyPlannedObject(ctx context.Context, obj libraryrelease.ObjectWrite, body []byte) error {
|
||||
store, ok := t.config.Objects.(conditionalObjectStore)
|
||||
if !ok {
|
||||
return errors.New("object effects capability missing")
|
||||
}
|
||||
if obj.Existing {
|
||||
observed, err := store.ObserveObject(ctx, obj.Provider, obj.Locator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !matchesObject(obj, observed, false) || observed.ETag != obj.BeforeETag || observed.VersionID != obj.BeforeVersionID {
|
||||
return errors.New("read-only object changed since plan")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
intended, err := effectExists(t.objectEffectPath(obj, "create-intent"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !intended {
|
||||
if err := t.recordObjectEffect(obj, "create-intent", objectObservation{}); err != nil {
|
||||
return err
|
||||
}
|
||||
err = store.CreateObject(ctx, obj.Provider, obj.Locator, bytes.NewReader(body), obj.Bytes, obj.OwnerToken)
|
||||
if errors.Is(err, errObjectWriteRejected) {
|
||||
if e := t.recordObjectEffect(obj, "create-rejected", objectObservation{}); e != nil {
|
||||
return e
|
||||
}
|
||||
return err
|
||||
}
|
||||
// Even 2xx is not a receipt: observe the exact physical target independently.
|
||||
}
|
||||
observed, observeErr := store.ObserveObject(ctx, obj.Provider, obj.Locator)
|
||||
if observeErr != nil {
|
||||
return observeErr
|
||||
}
|
||||
if !matchesObject(obj, observed, true) {
|
||||
return errors.New("object create unknown or conflicting; do not replay/delete without ownership proof")
|
||||
}
|
||||
return t.recordObjectEffect(obj, "created", observed)
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) restoreCreatedObjects(ctx context.Context) error {
|
||||
if t.activePlan == nil {
|
||||
return errors.New("object restoration requires adopted plan")
|
||||
}
|
||||
if len(t.activePlan.Objects) == 0 {
|
||||
return nil
|
||||
}
|
||||
store, ok := t.config.Objects.(conditionalObjectStore)
|
||||
if !ok {
|
||||
return errors.New("object restoration capability missing")
|
||||
}
|
||||
for _, obj := range t.activePlan.Objects {
|
||||
if obj.Existing {
|
||||
continue
|
||||
}
|
||||
intent, err := effectExists(t.objectEffectPath(obj, "create-intent"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !intent {
|
||||
continue
|
||||
}
|
||||
rejected, err := effectExists(t.objectEffectPath(obj, "create-rejected"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rejected {
|
||||
continue
|
||||
}
|
||||
observed, err := store.ObserveObject(ctx, obj.Provider, obj.Locator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
created, err := effectExists(t.objectEffectPath(obj, "created"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !observed.Exists {
|
||||
if !created {
|
||||
return errors.New("unresolved create intent: absence is not proof no delayed write remains")
|
||||
}
|
||||
if err := t.recordObjectEffect(obj, "removed", objectObservation{}); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !matchesObject(obj, observed, true) {
|
||||
return errors.New("created object now differs or has another owner; cleanup refused")
|
||||
}
|
||||
if err := t.recordObjectEffect(obj, "created", observed); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.recordObjectEffect(obj, "delete-intent", observed); err != nil {
|
||||
return err
|
||||
}
|
||||
deleteErr := store.RemoveObject(ctx, obj.Provider, obj.Locator, observed)
|
||||
after, err := store.ObserveObject(ctx, obj.Provider, obj.Locator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if after.Exists {
|
||||
return fmt.Errorf("conditional object cleanup not confirmed: %v", deleteErr)
|
||||
}
|
||||
if err := t.recordObjectEffect(obj, "removed", objectObservation{}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
func validateObjectPlanBinding(set libraryrelease.WriteSet, source librarysnapshot.Manifest) error {
|
||||
blobs := map[string]librarysnapshot.Part{}
|
||||
for _, part := range source.Parts {
|
||||
if part.Kind == "resource" {
|
||||
if _, exists := blobs[part.Name]; exists {
|
||||
return errors.New("duplicate source object blob")
|
||||
}
|
||||
blobs[part.Name] = part
|
||||
}
|
||||
}
|
||||
if len(blobs) != len(set.Objects) {
|
||||
return errors.New("object plan coverage differs from source")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, obj := range set.Objects {
|
||||
part, ok := blobs[obj.ResourceID]
|
||||
if !ok || obj.Bytes != part.Bytes || obj.SHA256 != part.SHA256 {
|
||||
return errors.New("object plan bytes differ from bound source blob")
|
||||
}
|
||||
delete(blobs, obj.ResourceID)
|
||||
if obj.Provider == "" || obj.BackendID == "" || obj.Bucket == "" || obj.Key == "" || obj.Locator != "storage://"+obj.BackendID+"/"+obj.Provider+"://"+obj.Bucket+"/"+obj.Key {
|
||||
return errors.New("object plan physical identity incomplete")
|
||||
}
|
||||
key := obj.Provider + "/" + obj.Bucket + "/" + obj.Key
|
||||
if seen[key] {
|
||||
return errors.New("duplicate physical object in plan")
|
||||
}
|
||||
seen[key] = true
|
||||
token := sha256.Sum256([]byte(set.JobID + "\x00" + set.Target + "\x00" + set.BackupSnapshotID + "\x00" + set.TargetSnapshotID + "\x00" + key))
|
||||
if obj.OwnerToken != hex.EncodeToString(token[:]) {
|
||||
return errors.New("object ownership token not bound to job/target/backup/snapshot")
|
||||
}
|
||||
if obj.Existing && obj.BeforeETag == "" {
|
||||
return errors.New("existing object lacks immutable before observation")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
)
|
||||
|
||||
type objectObservation struct {
|
||||
VersionID string `json:"version_id,omitempty"`
|
||||
Exists bool `json:"exists"`
|
||||
ETag string `json:"etag,omitempty"`
|
||||
SHA256 string `json:"sha256,omitempty"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Owner string `json:"owner,omitempty"`
|
||||
}
|
||||
|
||||
// No fallback to blind Put/Delete is allowed when conditional effects are absent.
|
||||
type conditionalObjectStore interface {
|
||||
ConditionalCapability(context.Context) error
|
||||
ObserveObject(context.Context, string, string) (objectObservation, error)
|
||||
CreateObject(context.Context, string, string, io.Reader, int64, string) error
|
||||
RemoveObject(context.Context, string, string, objectObservation) error
|
||||
}
|
||||
|
||||
var errObjectWriteRejected = errors.New("object write definitively rejected before send")
|
||||
|
||||
func (s *S3ObjectStore) ConditionalCapability(ctx context.Context) error {
|
||||
if s.provider != "minio" && s.provider != "s3" {
|
||||
return errors.New("object provider has no verified conditional create/version-delete adapter")
|
||||
}
|
||||
status, err := s.client.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(s.bucket)})
|
||||
if err != nil || string(status.Status) != "Enabled" {
|
||||
return errors.New("object effects require verified bucket versioning; never enable a business bucket implicitly")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Bind the supplied logical locator to the configured physical bucket. Legacy
|
||||
// Open/Put intentionally accept bare keys; the new contract does not infer them.
|
||||
func (s *S3ObjectStore) conditionalKey(provider, locator string) (string, error) {
|
||||
if provider != s.provider || !validObjectKey(locator) {
|
||||
return "", errors.New("conditional object provider/locator mismatch")
|
||||
}
|
||||
rest := strings.TrimPrefix(locator, "storage://")
|
||||
parts := strings.SplitN(rest, "/", 2)
|
||||
if rest == locator || len(parts) != 2 || parts[0] == "" {
|
||||
return "", errors.New("conditional object requires explicit backend")
|
||||
}
|
||||
expected := provider + "://" + s.bucket + "/"
|
||||
if !strings.HasPrefix(parts[1], expected) {
|
||||
return "", errors.New("conditional object bucket/provider mismatch")
|
||||
}
|
||||
key := strings.TrimPrefix(parts[1], expected)
|
||||
if key == "" {
|
||||
return "", errors.New("empty conditional object key")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func (s *S3ObjectStore) ObserveObject(ctx context.Context, provider, locator string) (objectObservation, error) {
|
||||
key, err := s.conditionalKey(provider, locator)
|
||||
if err != nil {
|
||||
return objectObservation{}, err
|
||||
}
|
||||
obj, err := s.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)})
|
||||
if err != nil {
|
||||
var response *smithyhttp.ResponseError
|
||||
if errors.As(err, &response) && response.HTTPStatusCode() == 404 {
|
||||
return objectObservation{}, nil
|
||||
}
|
||||
return objectObservation{}, errors.New("object observation unavailable")
|
||||
}
|
||||
defer obj.Body.Close()
|
||||
if obj.ContentLength == nil || *obj.ContentLength < 0 || *obj.ContentLength > s.maxObjectBytes || obj.ETag == nil || *obj.ETag == "" {
|
||||
return objectObservation{}, errors.New("incomplete object observation")
|
||||
}
|
||||
hash := sha256.New()
|
||||
size, err := io.Copy(hash, io.LimitReader(obj.Body, s.maxObjectBytes+1))
|
||||
if err != nil || size != *obj.ContentLength {
|
||||
return objectObservation{}, errors.New("object observation body incomplete")
|
||||
}
|
||||
return objectObservation{VersionID: aws.ToString(obj.VersionId), Exists: true, ETag: *obj.ETag, SHA256: hex.EncodeToString(hash.Sum(nil)), Bytes: size, Owner: obj.Metadata["kg-release-owner"]}, nil
|
||||
}
|
||||
|
||||
func (s *S3ObjectStore) CreateObject(ctx context.Context, provider, locator string, body io.Reader, size int64, owner string) error {
|
||||
if err := s.ConditionalCapability(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := s.conditionalKey(provider, locator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size < 0 || size > s.maxObjectBytes || len(owner) != 64 {
|
||||
return errObjectWriteRejected
|
||||
}
|
||||
// A durable intent represents one network attempt. Automatic retries could
|
||||
// remain in flight after compensation, so ambiguity is reconciled by reads.
|
||||
_, err = s.client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key), Body: body, ContentLength: aws.Int64(size), IfNoneMatch: aws.String("*"), Metadata: map[string]string{"kg-release-owner": owner}}, func(o *s3.Options) { o.RetryMaxAttempts = 1 })
|
||||
if err != nil {
|
||||
return errors.New("conditional object create outcome unknown")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3ObjectStore) RemoveObject(ctx context.Context, provider, locator string, expected objectObservation) error {
|
||||
if err := s.ConditionalCapability(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := s.conditionalKey(provider, locator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if expected.ETag == "" || expected.VersionID == "" || expected.VersionID == "null" {
|
||||
return errors.New("deletion requires an immutable object version")
|
||||
}
|
||||
before, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key), VersionId: aws.String(expected.VersionID)})
|
||||
if err != nil || aws.ToString(before.ETag) != expected.ETag || before.Metadata["kg-release-owner"] != expected.Owner {
|
||||
return errors.New("exact object version no longer matches receipt")
|
||||
}
|
||||
_, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key), VersionId: aws.String(expected.VersionID)}, func(o *s3.Options) { o.RetryMaxAttempts = 1 })
|
||||
if err != nil {
|
||||
return errors.New("conditional object delete outcome unknown")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// Consumption verifies the immutable source, not the half-written target. A
|
||||
// correctly hashed sidecar alone does not prove complete mapping coverage.
|
||||
func (t *ProductionLibraryTarget) validatePlanBindings(set libraryrelease.WriteSet) error {
|
||||
if set.Version != libraryrelease.MigrationWriteSetVersion || set.ContractVersion != migrationIdentityContractVersion || len(set.SchemaDigest) != 64 {
|
||||
return errors.New("legacy/incomplete plan is diagnostic-only; execution evidence missing")
|
||||
}
|
||||
archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
source, err := archive.Load(set.TargetSnapshotID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if set.ContractVersion != 0 && (source.TenantID != set.SourceTenantID || source.KnowledgeBaseID != set.SourceKnowledgeBaseID) {
|
||||
return errors.New("plan source identity differs from bound manifest")
|
||||
}
|
||||
backup, err := archive.Load(set.BackupSnapshotID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if backup.TenantID != set.TenantID || backup.KnowledgeBaseID != set.KnowledgeBaseID {
|
||||
return errors.New("plan before-image identity differs from target")
|
||||
}
|
||||
if err := validateObjectPlanBinding(set, source); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.validateIndexPlanBinding(archive, source, backup, set); err != nil {
|
||||
return err
|
||||
}
|
||||
requests, err := t.localIDRequests(archive, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(requests) != len(set.LocalIDs) {
|
||||
return errors.New("plan local mapping coverage differs from source")
|
||||
}
|
||||
expected := map[string]bool{}
|
||||
for _, r := range requests {
|
||||
expected[r.Table+"/"+r.Column+"/"+r.Source] = true
|
||||
}
|
||||
wikiRows := map[string]bool{}
|
||||
for _, row := range set.Rows {
|
||||
if row.Table == "wiki_log_entries" {
|
||||
wikiRows[row.ID] = !row.Existing
|
||||
}
|
||||
}
|
||||
for _, m := range set.LocalIDs {
|
||||
if !expected[m.Table+"/"+m.Column+"/"+m.Source] {
|
||||
return errors.New("plan includes unknown local mapping")
|
||||
}
|
||||
if m.Table == "wiki_log_entries" {
|
||||
if !wikiRows[m.Target] {
|
||||
return errors.New("plan omits allocated Wiki write identity")
|
||||
}
|
||||
delete(wikiRows, m.Target)
|
||||
}
|
||||
}
|
||||
if len(wikiRows) > 0 {
|
||||
return errors.New("plan includes unmapped Wiki write identity")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
"knowledge-governance/internal/testbarrier"
|
||||
)
|
||||
|
||||
// 生产整库目标:真实读、真实写、真实校验、真实恢复。
|
||||
@@ -99,6 +100,8 @@ type ProductionLibraryTarget struct {
|
||||
reusedResources map[string]bool
|
||||
// 回滚必须重放目标原始序列;普通发布由目标数据库分配本地序列。
|
||||
preserveChunkSequence bool
|
||||
activePlan *libraryrelease.WriteSet
|
||||
activeSnapshot string
|
||||
}
|
||||
|
||||
// resolveStorageBackend 在目标库里找本次写入的存储后端。找不到就报错:宁可不写,
|
||||
@@ -227,7 +230,7 @@ func scopeWhere(table string) string {
|
||||
// 两种归属都要算:显式绑定(knowledge/chunk)+ 被本库 chunk 正文以
|
||||
// resource://<handle> 引用(图片/附件常见,可能没有绑定行)。
|
||||
// 与归档侧收集资源部件的规则保持一致,否则校验会把导入的资源算成"多余"。
|
||||
return `(EXISTS (
|
||||
return `resources.tenant_id=$1 AND (EXISTS (
|
||||
SELECT 1 FROM resource_bindings b
|
||||
JOIN knowledges k ON k.id=b.owner_id AND k.tenant_id=b.tenant_id
|
||||
WHERE b.resource_id=resources.id AND b.tenant_id=$1 AND b.owner_type='knowledge' AND k.knowledge_base_id=$2
|
||||
@@ -235,11 +238,7 @@ func scopeWhere(table string) string {
|
||||
SELECT 1 FROM resource_bindings b
|
||||
JOIN chunks c ON c.id=b.owner_id AND c.tenant_id=b.tenant_id
|
||||
WHERE b.resource_id=resources.id AND b.tenant_id=$1 AND b.owner_type='chunk' AND c.knowledge_base_id=$2)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM chunks c
|
||||
WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL
|
||||
AND coalesce(resources.handle,'') <> ''
|
||||
AND position('resource://'||resources.handle IN coalesce(c.content,'')) > 0))`
|
||||
OR EXISTS (` + libraryResourceBodyReferenceSQL("c.tenant_id=$1 AND c.knowledge_base_id=$2") + `))`
|
||||
default:
|
||||
return "tenant_id=$1 AND knowledge_base_id=$2"
|
||||
}
|
||||
@@ -258,7 +257,7 @@ func identityExpr(table string) string {
|
||||
|
||||
func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string) (int64, string, error) {
|
||||
rows, err := t.pool.Query(ctx, fmt.Sprintf(`SELECT %s FROM %s WHERE %s ORDER BY 1`,
|
||||
identityExpr(table), table, scopeWhere(table)), t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||||
"("+identityExpr(table)+")::text", table, scopeWhere(table)), t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("读取生产 %s 失败", table)
|
||||
}
|
||||
@@ -284,6 +283,24 @@ func digestIDs(ids []string) string {
|
||||
|
||||
// Apply 把一类数据从归档写进生产;database 与 wiki 走同一个知识域事务。
|
||||
func (t *ProductionLibraryTarget) Apply(ctx context.Context, stage libraryrelease.Stage, snapshotID string) error {
|
||||
if authorizer, ok := t.config.Objects.(interface{ EnsureObjectGrant(context.Context) error }); ok {
|
||||
if e := authorizer.EnsureObjectGrant(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if t.activePlan != nil {
|
||||
expected := t.activePlan.TargetSnapshotID
|
||||
if t.preserveChunkSequence {
|
||||
expected = t.activePlan.BackupSnapshotID
|
||||
}
|
||||
if snapshotID != expected {
|
||||
return errors.New("apply snapshot differs from frozen execution plan")
|
||||
}
|
||||
}
|
||||
if err := t.verifyPlanSchema(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
t.activeSnapshot = snapshotID
|
||||
if err := t.resolveStorageBackend(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -401,7 +418,10 @@ func (t *ProductionLibraryTarget) insertRows(ctx context.Context, tx pgx.Tx, arc
|
||||
if err := t.retargetRow(table, row); err != nil {
|
||||
return err
|
||||
}
|
||||
if table == "chunks" && !t.preserveChunkSequence {
|
||||
if _, err := t.mapLocalID(table, row); err != nil {
|
||||
return err
|
||||
}
|
||||
if table == "chunks" && !t.preserveChunkSequence && t.activePlan == nil {
|
||||
delete(row, "seq_id")
|
||||
}
|
||||
if columns == nil {
|
||||
@@ -416,7 +436,7 @@ func (t *ProductionLibraryTarget) insertRows(ctx context.Context, tx pgx.Tx, arc
|
||||
if table == "resources" {
|
||||
statement = fmt.Sprintf(`INSERT INTO %s SELECT * FROM jsonb_populate_record(NULL::%s, $1::jsonb)
|
||||
ON CONFLICT (id) DO UPDATE SET %s WHERE %s.tenant_id = $2`, table, table, updateAssignments(columns), table)
|
||||
} else if table == "chunks" && !t.preserveChunkSequence {
|
||||
} else if table == "chunks" && !t.preserveChunkSequence && t.activePlan == nil {
|
||||
// Omitting the column (not inserting NULL) invokes the target default.
|
||||
quoted := make([]string, len(columns))
|
||||
for i, column := range columns {
|
||||
@@ -479,7 +499,10 @@ func (t *ProductionLibraryTarget) rowTransform(table string) func(map[string]jso
|
||||
}
|
||||
// seq_id is destination-local, not content identity. Full-universe
|
||||
// rollback verification still compares the original value exactly.
|
||||
if table == "chunks" && !t.preserveChunkSequence {
|
||||
if _, err := t.mapLocalID(table, row); err != nil {
|
||||
return err
|
||||
}
|
||||
if table == "chunks" && !t.preserveChunkSequence && t.activePlan == nil {
|
||||
delete(row, "seq_id")
|
||||
}
|
||||
return nil
|
||||
@@ -501,7 +524,7 @@ func (t *ProductionLibraryTarget) importResources(ctx context.Context, archive *
|
||||
}
|
||||
// 复用资源的对象字节已经在计划阶段逐字节比过:不再重传(重传只会改
|
||||
// 对象的写入时间,没有任何收益)。
|
||||
if t.reusedResources[part.Name] {
|
||||
if t.reusedResources[part.Name] && t.activePlan == nil {
|
||||
continue
|
||||
}
|
||||
reader, err := archive.OpenPart(part)
|
||||
@@ -513,6 +536,42 @@ func (t *ProductionLibraryTarget) importResources(ctx context.Context, archive *
|
||||
if err != nil || int64(len(body)) != part.Bytes {
|
||||
return fmt.Errorf("资源 %s 字节与归档摘要不符", part.Name)
|
||||
}
|
||||
if t.activePlan != nil {
|
||||
if t.activeSnapshot == t.activePlan.BackupSnapshotID {
|
||||
store, ok := t.config.Objects.(conditionalObjectStore)
|
||||
if !ok {
|
||||
return errors.New("rollback lacks conditional object observation")
|
||||
}
|
||||
observed, err := store.ObserveObject(ctx, location.Provider, location.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !observed.Exists || observed.SHA256 != part.SHA256 || observed.Bytes != part.Bytes {
|
||||
return errors.New("before-image object changed; refusing blind restore overwrite")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if t.activeSnapshot != t.activePlan.TargetSnapshotID {
|
||||
return errors.New("object snapshot differs from plan")
|
||||
}
|
||||
found := false
|
||||
for _, obj := range t.activePlan.Objects {
|
||||
if obj.ResourceID == part.Name {
|
||||
if obj.Locator != location.Path || obj.Provider != location.Provider || obj.SHA256 != part.SHA256 || obj.Bytes != part.Bytes {
|
||||
return errors.New("object plan differs from resource/blob")
|
||||
}
|
||||
if err := t.applyPlannedObject(ctx, obj, body); err != nil {
|
||||
return err
|
||||
}
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return errors.New("resource omitted from immutable object plan")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := t.config.Objects.Put(ctx, location.Provider, location.Path, bytes.NewReader(body), int64(len(body))); err != nil {
|
||||
return fmt.Errorf("上传资源 %s 失败: %w", part.Name, err)
|
||||
}
|
||||
@@ -587,6 +646,12 @@ WHERE tenant_id=$1 AND id = ANY($2::text[])`, t.scope.TenantID, ids)
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error {
|
||||
if t.activePlan != nil {
|
||||
if t.preserveChunkSequence {
|
||||
return t.restorePlannedIndex(ctx)
|
||||
}
|
||||
return t.applyPlannedIndex(ctx)
|
||||
}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind != "index" {
|
||||
continue
|
||||
@@ -605,7 +670,11 @@ func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *libr
|
||||
}
|
||||
// 直接搬运原始文档与向量:不解析、不重新 Embedding。
|
||||
identity := SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}
|
||||
if err := t.search.BulkIndex(ctx, documents, identity); err != nil {
|
||||
write := t.search.BulkIndex
|
||||
if t.activePlan != nil {
|
||||
write = t.search.BulkIndexGuarded
|
||||
}
|
||||
if err := write(ctx, documents, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
// 快照里没有的文档必须从生产索引删掉,否则撤销只在数据库生效。
|
||||
@@ -622,6 +691,7 @@ func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *libr
|
||||
|
||||
// Verify 用行数 + 身份集合摘要 + 索引条数核对生产与预发布快照是否一致。
|
||||
func (t *ProductionLibraryTarget) Verify(ctx context.Context, expect libraryrelease.Expectation) error {
|
||||
t.activeSnapshot = expect.SnapshotID
|
||||
if err := t.resolveStorageBackend(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -650,6 +720,19 @@ func (t *ProductionLibraryTarget) Verify(ctx context.Context, expect libraryrele
|
||||
}
|
||||
}
|
||||
wantCount, wantDigest, err := archivedTableState(archive, part)
|
||||
if err == nil && part.Name == "wiki_log_entries" && t.activePlan != nil && t.activeSnapshot == t.activePlan.TargetSnapshotID && !t.preserveChunkSequence {
|
||||
ids := []string{}
|
||||
for _, mapping := range t.activePlan.LocalIDs {
|
||||
if mapping.Table == part.Name {
|
||||
ids = append(ids, mapping.Target)
|
||||
}
|
||||
}
|
||||
if int64(len(ids)) != wantCount {
|
||||
return errors.New("Wiki local mapping coverage mismatch")
|
||||
}
|
||||
sort.Strings(ids)
|
||||
wantDigest = digestIDs(ids)
|
||||
}
|
||||
if errors.Is(err, errMissingIdentity) {
|
||||
// 个别表(例如日志表)没有代理主键:身份集合无从比,但行数与逐行内容摘要仍然必须一致。
|
||||
wantContentCount, wantContentDigest, columns, contentErr := archivedTableContent(archive, part, t.rowTransform(part.Name))
|
||||
@@ -790,19 +873,11 @@ func archivedTableState(archive *librarysnapshot.Archive, part librarysnapshot.P
|
||||
}
|
||||
|
||||
func archiveRowIdentity(table string, row map[string]json.RawMessage) string {
|
||||
value := func(key string) string {
|
||||
var text string
|
||||
_ = json.Unmarshal(row[key], &text)
|
||||
return text
|
||||
identity, err := parseRowIdentity(table, row)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if table == "knowledge_tag_relations" {
|
||||
knowledge, tag := value("knowledge_id"), value("tag_id")
|
||||
if knowledge == "" || tag == "" {
|
||||
return ""
|
||||
}
|
||||
return knowledge + ":" + tag
|
||||
}
|
||||
return value("id")
|
||||
return identity.key()
|
||||
}
|
||||
|
||||
// AdoptWriteSet 消费已持久化的写集合(接管/恢复路径)。
|
||||
@@ -831,12 +906,30 @@ func (t *ProductionLibraryTarget) AdoptWriteSet(set libraryrelease.WriteSet) err
|
||||
}
|
||||
reused[row.ID] = true
|
||||
}
|
||||
if t.reusedResources == nil {
|
||||
t.reusedResources = map[string]bool{}
|
||||
if set.ContractVersion != 0 && set.ContractVersion != migrationIdentityContractVersion {
|
||||
return errors.New("unsupported migration identity contract")
|
||||
}
|
||||
for id := range reused {
|
||||
t.reusedResources[id] = true
|
||||
if err := t.validatePlanBindings(set); err != nil {
|
||||
return err
|
||||
}
|
||||
// Copy through JSON: the caller cannot mutate the adopted immutable plan.
|
||||
raw, err := json.Marshal(set)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var adopted libraryrelease.WriteSet
|
||||
if err := json.Unmarshal(raw, &adopted); err != nil {
|
||||
return err
|
||||
}
|
||||
if binder, ok := t.config.Objects.(interface {
|
||||
BindObjectPlan(libraryrelease.WriteSet) error
|
||||
}); ok {
|
||||
if err := binder.BindObjectPlan(adopted); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
t.activePlan = &adopted
|
||||
t.reusedResources = reused
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -862,6 +955,15 @@ func (t *ProductionLibraryTarget) Restore(ctx context.Context, backup libraryrel
|
||||
return fmt.Errorf("写集合记录绑定的是 %d/%s,与目标 %d/%s 不一致",
|
||||
backup.WriteSet.TenantID, backup.WriteSet.KnowledgeBaseID, t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||||
}
|
||||
if err := t.AdoptWriteSet(*backup.WriteSet); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureRestorableResourceReferences(ctx, t.pool, *backup.WriteSet); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureNoResourceGrants(ctx, t.pool, backup.WriteSet.CreatedIDs("resources")); err != nil {
|
||||
return err
|
||||
}
|
||||
previous := t.preserveChunkSequence
|
||||
t.preserveChunkSequence = true
|
||||
defer func() { t.preserveChunkSequence = previous }()
|
||||
@@ -869,6 +971,7 @@ func (t *ProductionLibraryTarget) Restore(ctx context.Context, backup libraryrel
|
||||
if err := t.Apply(ctx, stage, backup.SnapshotID); err != nil {
|
||||
return fmt.Errorf("恢复阶段 %s 失败: %w", stage, err)
|
||||
}
|
||||
_ = testbarrier.Wait(ctx, "restore:"+string(stage), backup.WriteSet.JobID)
|
||||
}
|
||||
// resources 是多知识库共享表,回放阶段不删它。这里只清"写前不存在 ∧ 由本次写入 ∧
|
||||
// 不在本次恢复内容里"的精确身份,历史孤儿与其它知识库的资源一律不动。
|
||||
@@ -886,6 +989,9 @@ func (t *ProductionLibraryTarget) Restore(ctx context.Context, backup libraryrel
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.restoreCreatedObjects(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.clearJobCreatedRows(ctx, *backup.WriteSet, restored); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
type libraryClosureReader interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
// Check edges before JOIN-based export can erase a scoped orphan. Either parent
|
||||
// can establish scope; an edge is not safe merely because its other parent is absent.
|
||||
func verifyLibraryRelationalClosure(ctx context.Context, db libraryClosureReader, identity PostgresIdentity, includeDeleted bool) error {
|
||||
var invalid bool
|
||||
err := db.QueryRow(ctx, `/* library-relational-closure */ SELECT
|
||||
EXISTS(SELECT 1 FROM chunks c LEFT JOIN knowledges k ON k.id=c.knowledge_id
|
||||
WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND ($3 OR c.deleted_at IS NULL)
|
||||
AND (k.id IS NULL OR k.tenant_id IS DISTINCT FROM c.tenant_id OR k.knowledge_base_id IS DISTINCT FROM c.knowledge_base_id OR (NOT $3 AND k.deleted_at IS NOT NULL)))
|
||||
OR EXISTS(SELECT 1 FROM knowledge_tag_relations r LEFT JOIN knowledges k ON k.id=r.knowledge_id LEFT JOIN knowledge_tags t ON t.id=r.tag_id
|
||||
WHERE ((k.tenant_id=$1 AND k.knowledge_base_id=$2 AND ($3 OR k.deleted_at IS NULL)) OR (t.tenant_id=$1 AND t.knowledge_base_id=$2 AND ($3 OR t.deleted_at IS NULL)))
|
||||
AND (k.id IS NULL OR t.id IS NULL OR k.tenant_id IS DISTINCT FROM t.tenant_id OR k.knowledge_base_id IS DISTINCT FROM t.knowledge_base_id OR (NOT $3 AND (k.deleted_at IS NOT NULL OR t.deleted_at IS NOT NULL))))
|
||||
OR EXISTS(SELECT 1 FROM resource_bindings b WHERE b.tenant_id=$1
|
||||
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 ($3 OR k.deleted_at IS NULL)) OR EXISTS(SELECT 1 FROM chunks c WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND ($3 OR c.deleted_at IS NULL)))
|
||||
AND (b.owner_type NOT IN ('knowledge','chunk') OR b.owner_type IS NULL))`, identity.TenantID, identity.KnowledgeBaseID, includeDeleted).Scan(&invalid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read library reference closure: %w", err)
|
||||
}
|
||||
if invalid {
|
||||
return errors.New("unresolved or cross-parent library relationship")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyLibraryResourceOwners(ctx context.Context, db libraryClosureReader, ids []string) error {
|
||||
var invalid bool
|
||||
err := db.QueryRow(ctx, `/* library-resource-owner-closure */ SELECT EXISTS(
|
||||
SELECT 1 FROM resource_bindings b JOIN resources r ON r.id=b.resource_id WHERE r.id=ANY($1::text[]) AND (
|
||||
b.tenant_id IS DISTINCT FROM r.tenant_id OR b.owner_type IS NULL OR NOT (
|
||||
(b.owner_type='knowledge' AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=b.tenant_id)) 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=b.tenant_id)))))`, ids).Scan(&invalid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read referenced resource owners: %w", err)
|
||||
}
|
||||
if invalid {
|
||||
return errors.New("referenced resource has unknown or unresolved owner")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var libraryResourceToken = regexp.MustCompile(`resource://([A-Za-z0-9_-]*)`)
|
||||
|
||||
// Decode JSON before scanning string leaves (including nested metadata). The
|
||||
// v071 reader accepts exactly 22 URL-safe characters, not URI query/path suffixes.
|
||||
// Opaque escaped/encoded representations are refused rather than silently omitted.
|
||||
func libraryResourceHandles(rows []json.RawMessage) ([]string, error) {
|
||||
seen := map[string]bool{}
|
||||
var visit func(any) error
|
||||
visit = func(value any) error {
|
||||
switch v := value.(type) {
|
||||
case map[string]any:
|
||||
for _, x := range v {
|
||||
if e := visit(x); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, x := range v {
|
||||
if e := visit(x); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
case string:
|
||||
rest := v
|
||||
for strings.Contains(rest, "resource:") {
|
||||
start := strings.Index(rest, "resource:")
|
||||
rest = rest[start:]
|
||||
match := libraryResourceToken.FindStringSubmatchIndex(rest)
|
||||
if match == nil || match[0] != 0 || match[3]-match[2] != 22 {
|
||||
return errors.New("unsupported resource reference representation")
|
||||
}
|
||||
if match[1] < len(rest) && strings.ContainsRune("/?#=%\\", rune(rest[match[1]])) {
|
||||
return errors.New("unsupported resource reference suffix")
|
||||
}
|
||||
seen[rest[match[2]:match[3]]] = true
|
||||
rest = rest[match[1]:]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, raw := range rows {
|
||||
var value any
|
||||
decoder := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
decoder.UseNumber()
|
||||
if e := decoder.Decode(&value); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e := visit(value); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
handles := make([]string, 0, len(seen))
|
||||
for handle := range seen {
|
||||
handles = append(handles, handle)
|
||||
}
|
||||
sort.Strings(handles)
|
||||
return handles, nil
|
||||
}
|
||||
|
||||
// Revalidate frozen source content at the actual planning boundary. A sealed
|
||||
// manifest proves bytes, not that every row has a parent or a supported owner.
|
||||
func validateArchivedLibraryClosure(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error {
|
||||
var pg PostgresSnapshot
|
||||
es := SearchSnapshot{MappingSHA256: manifest.Compatibility.IndexMappingSHA256}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind != "database" && part.Kind != "wiki" && part.Kind != "index" {
|
||||
continue
|
||||
}
|
||||
reader, e := archive.OpenPart(part)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if part.Kind == "index" {
|
||||
e = json.NewDecoder(reader).Decode(&es.Documents)
|
||||
} else {
|
||||
var rows []json.RawMessage
|
||||
e = json.NewDecoder(reader).Decode(&rows)
|
||||
pg.Tables = append(pg.Tables, newTableSnapshot(part.Name, rows))
|
||||
}
|
||||
reader.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
|
||||
return validateLibraryCandidate(PostgresIdentity{TenantID: manifest.TenantID, KnowledgeBaseID: manifest.KnowledgeBaseID}, pg, es)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type resourceGrantQuery interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
// Grants are an external FK, not part of the migration archive. Deleting a
|
||||
// resource would silently cascade a capability owned outside this operation.
|
||||
func ensureNoResourceGrants(ctx context.Context, q resourceGrantQuery, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
var present bool
|
||||
if err := q.QueryRow(ctx, `SELECT to_regclass('public.resource_access_grants') IS NOT NULL`).Scan(&present); err != nil {
|
||||
return err
|
||||
}
|
||||
if !present {
|
||||
return nil
|
||||
}
|
||||
var referenced bool
|
||||
if err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM public.resource_access_grants WHERE resource_id=ANY($1::text[]))`, ids).Scan(&referenced); err != nil {
|
||||
return err
|
||||
}
|
||||
if referenced {
|
||||
return errors.New("created resource has external access grants; refusing cascade and object deletion")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
// Keep capture/verification and deletion protection on the same set of bodies.
|
||||
// predicate is an internal SQL fragment, never caller-supplied content.
|
||||
func libraryResourceBodyReferenceSQL(predicate string) string {
|
||||
queries := []string{}
|
||||
for _, table := range productionLibraryTables {
|
||||
if table == "resources" || table == "resource_bindings" || table == "knowledge_tag_relations" {
|
||||
continue
|
||||
}
|
||||
queries = append(queries, fmt.Sprintf(`SELECT 1 FROM %s c WHERE (%s) AND coalesce(resources.handle,'')<>'' AND position('resource://'||resources.handle IN to_jsonb(c)::text)>0`, table, predicate))
|
||||
}
|
||||
return strings.Join(queries, " UNION ALL ")
|
||||
}
|
||||
|
||||
// This must precede *all* restore mutations, including ES and object deletes.
|
||||
// A created row is not permission to invalidate a later out-of-plan reader.
|
||||
func ensureRestorableResourceReferences(ctx context.Context, q libraryClosureReader, set libraryrelease.WriteSet) error {
|
||||
ids := set.CreatedIDs("resources")
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
if e := verifyLibraryResourceOwners(ctx, q, ids); e != nil {
|
||||
return e
|
||||
}
|
||||
bindings := []string{}
|
||||
for _, row := range set.Rows {
|
||||
if row.Table == "resource_bindings" {
|
||||
bindings = append(bindings, row.ID)
|
||||
}
|
||||
}
|
||||
var referenced bool
|
||||
err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM resource_bindings b WHERE b.resource_id=ANY($1::text[]) AND
|
||||
(NOT(b.id=ANY($2::text[])) OR b.tenant_id IS DISTINCT FROM $3 OR NOT (
|
||||
(b.owner_type='knowledge' AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$3 AND k.knowledge_base_id=$4)) OR
|
||||
(b.owner_type='chunk' AND EXISTS(SELECT 1 FROM chunks c WHERE c.id=b.owner_id AND c.tenant_id=$3 AND c.knowledge_base_id=$4)))))`, ids, bindings, set.TenantID, set.KnowledgeBaseID).Scan(&referenced)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if referenced {
|
||||
return errors.New("created resource has out-of-plan bindings; restore held before writes")
|
||||
}
|
||||
bodySQL := libraryResourceBodyReferenceSQL("c.tenant_id IS DISTINCT FROM $2 OR c.knowledge_base_id IS DISTINCT FROM $3")
|
||||
err = q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM resources WHERE id=ANY($1::text[]) AND EXISTS (`+bodySQL+`))`, ids, set.TenantID, set.KnowledgeBaseID).Scan(&referenced)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if referenced {
|
||||
return errors.New("created resource has foreign body/metadata references; restore held before writes")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Recheck under the already-held resource parent locks. This does not claim
|
||||
// cross-store isolation from uncontrolled writers; deployed exclusivity is separate.
|
||||
func ensureCreatedResourcesUnreferenced(ctx context.Context, q libraryClosureReader, ids []string) error {
|
||||
var referenced bool
|
||||
err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM resources WHERE id=ANY($1::text[]) AND
|
||||
(EXISTS(SELECT 1 FROM resource_bindings b WHERE b.resource_id=resources.id) OR EXISTS (`+libraryResourceBodyReferenceSQL("TRUE")+`)))`, ids).Scan(&referenced)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if referenced {
|
||||
return errors.New("created resource is still referenced; refusing row deletion")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -93,7 +93,7 @@ func (e *ResourceReuseEvidence) Seal() error {
|
||||
|
||||
// Verify 校验版本、必备身份与摘要;缺任何一项都不许拿它去放行覆盖。
|
||||
func (e *ResourceReuseEvidence) Verify() error {
|
||||
if e.Version != reuseEvidenceVersion {
|
||||
if e.Version != reuseEvidenceVersion && e.Version != 2 {
|
||||
return fmt.Errorf("复用证据版本 %d 不受支持(当前 %d)", e.Version, reuseEvidenceVersion)
|
||||
}
|
||||
if e.JobID == "" || e.Target == "" || e.TargetSnapshotID == "" || e.ResourceID == "" ||
|
||||
@@ -107,9 +107,12 @@ func (e *ResourceReuseEvidence) Verify() error {
|
||||
if e.RetargetedRowDigest == "" || e.TargetRowDigest != e.RetargetedRowDigest {
|
||||
return errors.New("复用证据里目标行与本次要写的行不一致")
|
||||
}
|
||||
if e.ProvenanceRowDigest != e.ArchivedRowDigest {
|
||||
if e.Version == 1 && e.ProvenanceRowDigest != e.ArchivedRowDigest {
|
||||
return errors.New("复用证据里的来源行与本次快照行不一致")
|
||||
}
|
||||
if e.Version == 2 && (e.ProvenanceKind != libraryrelease.PriorSnapshotPrebackup || e.ProvenanceRowDigest != e.RetargetedRowDigest) {
|
||||
return errors.New("prebackup reuse proof differs from target projection")
|
||||
}
|
||||
copied := *e
|
||||
copied.Digest = ""
|
||||
raw, err := json.Marshal(copied)
|
||||
@@ -133,50 +136,16 @@ func PersistReuseEvidence(archiveRoot string, evidence *ResourceReuseEvidence) (
|
||||
if evidence.Digest == "" {
|
||||
return "", errors.New("复用证据没有摘要,拒绝落盘")
|
||||
}
|
||||
directory := filepath.Join(archiveRoot, reuseDirName)
|
||||
if err := os.MkdirAll(directory, 0700); err != nil {
|
||||
return "", fmt.Errorf("创建复用证据目录失败: %w", err)
|
||||
}
|
||||
path := reusePath(archiveRoot, evidence.Digest)
|
||||
if existing, readErr := os.ReadFile(path); readErr == nil {
|
||||
var recorded ResourceReuseEvidence
|
||||
if json.Unmarshal(existing, &recorded) != nil || recorded.Verify() != nil || recorded.Digest != evidence.Digest {
|
||||
return "", errors.New("复用证据同名但内容不符,拒绝覆盖")
|
||||
}
|
||||
return path, nil
|
||||
} else if !errors.Is(readErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("读取已有复用证据失败: %w", readErr)
|
||||
if err := evidence.Verify(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw, err := json.Marshal(*evidence)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码复用证据失败: %w", err)
|
||||
return "", err
|
||||
}
|
||||
temporary := path + ".tmp"
|
||||
file, err := os.OpenFile(temporary, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("写入复用证据失败: %w", err)
|
||||
}
|
||||
if _, err := file.Write(raw); err != nil {
|
||||
file.Close()
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("写入复用证据失败: %w", err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
file.Close()
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("复用证据未落盘: %w", err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("复用证据未落盘: %w", err)
|
||||
}
|
||||
if err := os.Chmod(temporary, 0444); err != nil {
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("复用证据只读化失败: %w", err)
|
||||
}
|
||||
if err := os.Rename(temporary, path); err != nil {
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("复用证据落盘失败: %w", err)
|
||||
path := reusePath(archiveRoot, evidence.Digest)
|
||||
if err := persistImmutableJSON(path, raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
@@ -392,6 +361,39 @@ func (t *ProductionLibraryTarget) planReusableResource(ctx context.Context, arch
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSetRow{}, err
|
||||
}
|
||||
evidenceVersion := reuseEvidenceVersion
|
||||
backupIDs, backupErr := archivedSnapshotResourceIDs(archive, plan.BackupSnapshotID)
|
||||
if backupErr != nil {
|
||||
return libraryrelease.WriteSetRow{}, backupErr
|
||||
}
|
||||
if backupIDs[id] {
|
||||
baseline, err := archive.Load(plan.BackupSnapshotID)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSetRow{}, err
|
||||
}
|
||||
if baseline.TenantID != t.scope.TenantID || baseline.KnowledgeBaseID != t.scope.KnowledgeBaseID {
|
||||
return libraryrelease.WriteSetRow{}, errors.New("resource prebackup scope mismatch")
|
||||
}
|
||||
for _, p := range baseline.Parts {
|
||||
if p.Kind != "database" || p.Name != "resources" {
|
||||
continue
|
||||
}
|
||||
row, err := archivedRowByID(archive, p, id)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSetRow{}, err
|
||||
}
|
||||
digest, err := canonicalRowDigest(projectRow(row, columns))
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSetRow{}, err
|
||||
}
|
||||
if digest != retargetedDigest {
|
||||
return libraryrelease.WriteSetRow{}, errors.New("shared resource differs from immutable before-image")
|
||||
}
|
||||
provenance = libraryrelease.PriorSnapshot{JobID: plan.JobID, SnapshotID: plan.BackupSnapshotID, Kind: libraryrelease.PriorSnapshotPrebackup}
|
||||
provenanceDigest = digest
|
||||
evidenceVersion = 2
|
||||
}
|
||||
}
|
||||
if provenance.JobID == "" {
|
||||
return libraryrelease.WriteSetRow{}, fmt.Errorf(
|
||||
"资源 ID 冲突:%s 已存在于目标租户但不在预备份范围内,且没有可审计的持久来源(成功同步/预备份)证明它属于本目标,拒绝覆盖", id)
|
||||
@@ -417,7 +419,7 @@ func (t *ProductionLibraryTarget) planReusableResource(ctx context.Context, arch
|
||||
objects = append(objects, reuseObject{Name: item.Name, Path: path, Bytes: size, SHA256: digest})
|
||||
}
|
||||
evidence := &ResourceReuseEvidence{
|
||||
Version: reuseEvidenceVersion, JobID: plan.JobID, Target: plan.Target,
|
||||
Version: evidenceVersion, JobID: plan.JobID, Target: plan.Target,
|
||||
TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID,
|
||||
SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID,
|
||||
TargetSnapshotID: plan.TargetSnapshotID, ResourceID: id,
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
type migrationCatalog map[string]json.RawMessage
|
||||
|
||||
// Catalog capture is read-only. Sequence *definitions*, not mutable last_value,
|
||||
// belong in the fingerprint; allocating a number must not look like DDL drift.
|
||||
func (t *ProductionLibraryTarget) migrationCatalog(ctx context.Context) (migrationCatalog, string, error) {
|
||||
tx, err := t.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
catalog, digest, err := captureMigrationCatalog(ctx, tx)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return catalog, digest, nil
|
||||
}
|
||||
|
||||
// Source rows and their definitions must come from the same read-only transaction.
|
||||
func captureMigrationCatalog(ctx context.Context, tx pgx.Tx) (migrationCatalog, string, error) {
|
||||
queries := map[string]string{
|
||||
"columns": `SELECT c.relname AS table_name,a.attname AS column_name,format_type(a.atttypid,a.atttypmod) AS type,a.attnotnull AS not_null,a.attidentity AS identity,a.attgenerated AS generated,coalesce(pg_get_expr(d.adbin,d.adrelid),'') AS default_expr FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped ORDER BY c.relname,a.attnum`,
|
||||
"constraints": `SELECT ns.nspname AS namespace,c.relname AS table_name,x.conname AS name,x.contype AS type,pg_get_constraintdef(x.oid) AS definition,coalesce(r.relname,'') AS referenced_table,coalesce(rns.nspname,'') AS referenced_namespace FROM pg_constraint x JOIN pg_class c ON c.oid=x.conrelid JOIN pg_namespace ns ON ns.oid=c.relnamespace LEFT JOIN pg_class r ON r.oid=x.confrelid LEFT JOIN pg_namespace rns ON rns.oid=r.relnamespace WHERE (ns.nspname='public' AND c.relname=ANY($1)) OR (rns.nspname='public' AND r.relname=ANY($1)) ORDER BY ns.nspname,c.relname,x.conname`,
|
||||
"indexes": `SELECT c.relname AS table_name,ic.relname AS name,i.indisunique AS unique_index,i.indisvalid AS valid,pg_get_indexdef(i.indexrelid) AS definition,coalesce(pg_get_expr(i.indpred,i.indrelid),'') AS predicate FROM pg_index i JOIN pg_class c ON c.oid=i.indrelid JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_class ic ON ic.oid=i.indexrelid WHERE n.nspname='public' AND c.relname=ANY($1) ORDER BY c.relname,ic.relname`,
|
||||
"triggers": `SELECT c.relname AS table_name,g.tgname AS name,pg_get_triggerdef(g.oid) AS definition FROM pg_trigger g JOIN pg_class c ON c.oid=g.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=ANY($1) AND NOT g.tgisinternal ORDER BY c.relname,g.tgname`,
|
||||
"relations": `SELECT c.relname AS table_name,c.relkind::text AS kind,c.relispartition AS partition,c.relrowsecurity AS row_security,EXISTS(SELECT 1 FROM pg_inherits i WHERE i.inhrelid=c.oid OR i.inhparent=c.oid) AS inherits FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=ANY($1) ORDER BY c.relname`,
|
||||
"sequences": `SELECT c.relname AS table_name,a.attname AS column_name,coalesce(s.seqrelid::regclass::text,'') AS sequence,s.seqstart,s.seqincrement,s.seqmin,s.seqmax,s.seqcache,s.seqcycle,coalesce(own.deptype::text,'') AS ownership FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum LEFT JOIN pg_depend dep ON dep.classid='pg_attrdef'::regclass AND dep.objid=d.oid AND dep.refclassid='pg_class'::regclass AND EXISTS(SELECT 1 FROM pg_sequence sq WHERE sq.seqrelid=dep.refobjid) LEFT JOIN pg_depend own ON own.refclassid='pg_class'::regclass AND own.refobjid=c.oid AND own.refobjsubid=a.attnum AND own.classid='pg_class'::regclass AND own.deptype IN ('a','i') AND EXISTS(SELECT 1 FROM pg_sequence sq WHERE sq.seqrelid=own.objid) LEFT JOIN pg_sequence s ON s.seqrelid=coalesce(dep.refobjid,own.objid) WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped AND (s.seqrelid IS NOT NULL OR a.attname='seq_id' OR (c.relname='wiki_log_entries' AND a.attname='id')) ORDER BY c.relname,a.attname,s.seqrelid`,
|
||||
}
|
||||
catalog := migrationCatalog{}
|
||||
for key, query := range queries {
|
||||
var raw []byte
|
||||
if err := tx.QueryRow(ctx, "SELECT coalesce(jsonb_agg(to_jsonb(q)),'[]'::jsonb) FROM ("+query+") q", productionLibraryTables).Scan(&raw); err != nil {
|
||||
return nil, "", fmt.Errorf("capture migration catalog %s: %w", key, err)
|
||||
}
|
||||
catalog[key] = raw
|
||||
}
|
||||
raw, err := json.Marshal(catalog)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
hash := sha256.Sum256(raw)
|
||||
return catalog, hex.EncodeToString(hash[:]), nil
|
||||
}
|
||||
|
||||
func validateMigrationCatalog(catalog migrationCatalog) error {
|
||||
var triggers []json.RawMessage
|
||||
if err := json.Unmarshal(catalog["triggers"], &triggers); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(triggers) > 0 {
|
||||
return errors.New("unreviewed migration trigger effects")
|
||||
}
|
||||
var relations []struct {
|
||||
Table string `json:"table_name"`
|
||||
Kind string `json:"kind"`
|
||||
Partition bool `json:"partition"`
|
||||
RLS bool `json:"row_security"`
|
||||
Inherits bool `json:"inherits"`
|
||||
}
|
||||
if err := json.Unmarshal(catalog["relations"], &relations); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(relations) != len(productionLibraryTables) {
|
||||
return errors.New("incomplete migration table catalog")
|
||||
}
|
||||
for _, r := range relations {
|
||||
if r.Kind != "r" || r.Partition || r.RLS || r.Inherits {
|
||||
return fmt.Errorf("unsupported migration relation: %s", r.Table)
|
||||
}
|
||||
}
|
||||
var constraints []struct {
|
||||
Namespace string `json:"namespace"`
|
||||
Table string `json:"table_name"`
|
||||
Type string `json:"type"`
|
||||
Referenced string `json:"referenced_table"`
|
||||
ReferencedNamespace string `json:"referenced_namespace"`
|
||||
Definition string `json:"definition"`
|
||||
}
|
||||
if err := json.Unmarshal(catalog["constraints"], &constraints); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range constraints {
|
||||
if c.Type != "f" {
|
||||
continue
|
||||
}
|
||||
// Internal-table membership does not prove the referenced identity survives
|
||||
// local-number remapping. v071 has exactly these reviewed FK contracts.
|
||||
if !(c.Namespace == "public" && c.ReferencedNamespace == "public" &&
|
||||
(c.Table == "resource_bindings" || c.Table == "resource_access_grants") && c.Referenced == "resources" &&
|
||||
c.Definition == "FOREIGN KEY (resource_id) REFERENCES resources(id) ON DELETE CASCADE") {
|
||||
return fmt.Errorf("unreviewed incoming migration FK: %s.%s", c.Namespace, c.Table)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) preflightMigrationCatalog(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) (string, error) {
|
||||
catalog, digest, err := t.migrationCatalog(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := validateMigrationCatalog(catalog); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var columns []struct {
|
||||
Table string `json:"table_name"`
|
||||
Column string `json:"column_name"`
|
||||
Type string `json:"type"`
|
||||
Generated string `json:"generated"`
|
||||
Identity string `json:"identity"`
|
||||
}
|
||||
if err := json.Unmarshal(catalog["columns"], &columns); err != nil {
|
||||
return "", err
|
||||
}
|
||||
allowed := map[string]map[string]string{}
|
||||
for _, c := range columns {
|
||||
if c.Generated != "" || c.Identity != "" {
|
||||
return "", fmt.Errorf("unsupported generated/identity column: %s.%s", c.Table, c.Column)
|
||||
}
|
||||
if allowed[c.Table] == nil {
|
||||
allowed[c.Table] = map[string]string{}
|
||||
}
|
||||
allowed[c.Table][c.Column] = c.Type
|
||||
}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind == "schema" {
|
||||
if part.Name != "migration-catalog" || part.SHA256 != digest {
|
||||
return "", errors.New("captured source/target schema catalog mismatch")
|
||||
}
|
||||
reader, err := archive.OpenPart(part)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
reader.Close()
|
||||
continue
|
||||
}
|
||||
if part.Kind != "database" && part.Kind != "wiki" {
|
||||
continue
|
||||
}
|
||||
reader, err := archive.OpenPart(part)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var rows []map[string]json.RawMessage
|
||||
err = json.NewDecoder(reader).Decode(&rows)
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
contract := migrationIdentityContracts[part.Name]
|
||||
for _, row := range rows {
|
||||
for name := range row {
|
||||
if _, ok := allowed[part.Name][name]; !ok {
|
||||
return "", fmt.Errorf("source column absent from target contract: %s.%s", part.Name, name)
|
||||
}
|
||||
}
|
||||
if contract.LocalColumn != "" && allowed[part.Name][contract.LocalColumn] != "" {
|
||||
if allowed[part.Name][contract.LocalColumn] != "bigint" {
|
||||
return "", fmt.Errorf("local column type mismatch: %s.%s", part.Name, contract.LocalColumn)
|
||||
}
|
||||
if _, err := positiveBigint(row[contract.LocalColumn]); err != nil {
|
||||
return "", fmt.Errorf("missing/invalid source local number: %s.%s", part.Name, contract.LocalColumn)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(catalog)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := persistImmutableJSON(t.config.ArchiveRoot+"/catalogs/"+digest+".json", raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return digest, nil
|
||||
}
|
||||
|
||||
func (t *ProductionLibraryTarget) verifyPlanSchema(ctx context.Context) error {
|
||||
if t.activePlan == nil {
|
||||
return nil
|
||||
}
|
||||
if t.activePlan.SchemaDigest == "" {
|
||||
return errors.New("persisted execution plan lacks schema fingerprint")
|
||||
}
|
||||
_, digest, err := t.migrationCatalog(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if digest != t.activePlan.SchemaDigest {
|
||||
return errors.New("target schema changed after immutable plan")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// This is the finite v071 structured-reference contract, not a heuristic that
|
||||
// treats arbitrary text/numbers as IDs. Historical log refs are display facts.
|
||||
func validateLibraryStructuredReferences(pg PostgresSnapshot) error {
|
||||
type row map[string]json.RawMessage
|
||||
tables := map[string]map[string]row{}
|
||||
for _, table := range pg.Tables {
|
||||
tables[table.Name] = map[string]row{}
|
||||
for _, raw := range table.Rows {
|
||||
var r row
|
||||
if e := json.Unmarshal(raw, &r); e != nil {
|
||||
return e
|
||||
}
|
||||
var id string
|
||||
json.Unmarshal(r["id"], &id)
|
||||
if id == "" {
|
||||
id = string(r["id"])
|
||||
}
|
||||
tables[table.Name][id] = r
|
||||
}
|
||||
}
|
||||
text := func(r row, key string) (string, error) {
|
||||
v := bytes.TrimSpace(r[key])
|
||||
if len(v) == 0 || bytes.Equal(v, []byte("null")) {
|
||||
return "", nil
|
||||
}
|
||||
var out string
|
||||
if e := json.Unmarshal(v, &out); e != nil {
|
||||
return "", fmt.Errorf("unsupported reference %s", key)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
ref := func(r row, key, table string, sameKnowledge bool) error {
|
||||
v, e := text(r, key)
|
||||
if e != nil || v == "" {
|
||||
return e
|
||||
}
|
||||
parent, ok := tables[table][v]
|
||||
if !ok {
|
||||
return fmt.Errorf("unresolved %s reference to %s", key, table)
|
||||
}
|
||||
if sameKnowledge {
|
||||
a, _ := text(r, "knowledge_id")
|
||||
b, _ := text(parent, "knowledge_id")
|
||||
if a != b {
|
||||
return fmt.Errorf("cross-parent %s reference", key)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
refs := func(r row, key, table string, legacyTitle bool) error {
|
||||
raw := bytes.TrimSpace(r[key])
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
return nil
|
||||
}
|
||||
var ids []string
|
||||
if e := json.Unmarshal(raw, &ids); e != nil {
|
||||
return fmt.Errorf("unsupported %s reference representation", key)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if legacyTitle {
|
||||
id = strings.SplitN(id, "|", 2)[0]
|
||||
}
|
||||
if _, ok := tables[table][id]; !ok {
|
||||
return fmt.Errorf("unresolved %s reference to %s", key, table)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, r := range tables["chunks"] {
|
||||
for _, key := range []string{"pre_chunk_id", "next_chunk_id", "parent_chunk_id"} {
|
||||
if e := ref(r, key, "chunks", true); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if e := ref(r, "tag_id", "knowledge_tags", false); e != nil {
|
||||
return e
|
||||
}
|
||||
for _, key := range []string{"relation_chunks", "indirect_relation_chunks"} {
|
||||
if e := refs(r, key, "chunks", false); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, r := range tables["wiki_folders"] {
|
||||
if e := ref(r, "parent_id", "wiki_folders", false); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
// Parent edges must be acyclic; pre/next chunk adjacency is intentionally not
|
||||
// run through this check because a normal bidirectional adjacency is a cycle.
|
||||
for _, kind := range []struct{ table, key string }{{"wiki_folders", "parent_id"}, {"chunks", "parent_chunk_id"}} {
|
||||
for id := range tables[kind.table] {
|
||||
seen := map[string]bool{}
|
||||
for id != "" {
|
||||
if seen[id] {
|
||||
return fmt.Errorf("cyclic %s reference", kind.key)
|
||||
}
|
||||
seen[id] = true
|
||||
next, e := text(tables[kind.table][id], kind.key)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
id = next
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, r := range tables["wiki_pages"] {
|
||||
if e := ref(r, "folder_id", "wiki_folders", false); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := refs(r, "source_refs", "knowledges", true); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := refs(r, "chunk_refs", "chunks", false); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, r := range tables["wiki_log_entries"] {
|
||||
raw := bytes.TrimSpace(r["pages_affected"])
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
continue
|
||||
}
|
||||
var items []json.RawMessage
|
||||
if e := json.Unmarshal(raw, &items); e != nil {
|
||||
return fmt.Errorf("unsupported Wiki log pages_affected")
|
||||
}
|
||||
shape := ""
|
||||
for _, item := range items {
|
||||
var slug string
|
||||
if json.Unmarshal(item, &slug) == nil {
|
||||
if shape == "object" {
|
||||
return fmt.Errorf("mixed Wiki log reference representations")
|
||||
}
|
||||
shape = "string"
|
||||
continue
|
||||
}
|
||||
var object map[string]json.RawMessage
|
||||
if e := json.Unmarshal(item, &object); e != nil || object == nil {
|
||||
return fmt.Errorf("unsupported Wiki log page reference")
|
||||
}
|
||||
if shape == "string" {
|
||||
return fmt.Errorf("mixed Wiki log reference representations")
|
||||
}
|
||||
shape = "object"
|
||||
if e := json.Unmarshal(object["slug"], &slug); e != nil {
|
||||
return fmt.Errorf("Wiki log reference lacks string slug")
|
||||
}
|
||||
for key, value := range object {
|
||||
if key != "slug" && key != "title" {
|
||||
return fmt.Errorf("unreviewed Wiki log reference field: %s", key)
|
||||
}
|
||||
var s string
|
||||
if e := json.Unmarshal(value, &s); e != nil {
|
||||
return fmt.Errorf("unsupported Wiki log reference %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
@@ -88,7 +89,7 @@ func VerifySourceAgainstTarget(source librarysnapshot.Compatibility, live LiveTa
|
||||
return fmt.Errorf("目标 schema 版本 %d 与来源快照声明 %d 不一致:拒绝搬运",
|
||||
live.SchemaVersion, source.SchemaVersion)
|
||||
}
|
||||
if !live.ModelBound || live.EmbeddingDimension < 1 {
|
||||
if !live.ModelBound || live.EmbeddingDimension < 1 || strings.TrimSpace(live.EmbeddingModel) == "" {
|
||||
return errors.New("目标知识库没有可读的 embedding 模型绑定(模型行缺失或维度未知):" +
|
||||
"无法证明向量可迁移,先在目标上绑定模型")
|
||||
}
|
||||
|
||||
@@ -57,11 +57,17 @@ func archivedRowIdentities(archive *librarysnapshot.Archive, part librarysnapsho
|
||||
if err := decoder.Decode(&row); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
identity := archiveRowIdentity(part.Name, row)
|
||||
if identity == "" {
|
||||
continue
|
||||
identity, err := parseRowIdentity(part.Name, row)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, identity)
|
||||
key := identity.key()
|
||||
for _, previous := range ids {
|
||||
if previous == key {
|
||||
return nil, fmt.Errorf("duplicate %s identity", part.Name)
|
||||
}
|
||||
}
|
||||
ids = append(ids, key)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
@@ -109,6 +115,11 @@ func (t *ProductionLibraryTarget) assertNoSourceScopeRows(ctx context.Context, a
|
||||
if !tableHasTenant(part.Name) {
|
||||
continue
|
||||
}
|
||||
// DB-local source numbers have no target-global ownership meaning.
|
||||
// The mapped target values are checked by the typed content verifier.
|
||||
if part.Name == "wiki_log_entries" && t.activePlan != nil && t.activeSnapshot == t.activePlan.TargetSnapshotID {
|
||||
continue
|
||||
}
|
||||
ids, err := archivedRowIdentities(archive, part)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -116,9 +127,23 @@ func (t *ProductionLibraryTarget) assertNoSourceScopeRows(ctx context.Context, a
|
||||
if len(ids) == 0 {
|
||||
continue
|
||||
}
|
||||
statement := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_id=$1 AND id = ANY($2::text[])`, part.Name)
|
||||
// Shared tables have no KB column. Equal tenant identity is not
|
||||
// evidence of leakage; their ownership is checked by the plan.
|
||||
if !tablesWithKB[part.Name] && t.snapshotTenant == t.scope.TenantID {
|
||||
continue
|
||||
}
|
||||
cast := "text"
|
||||
if part.Name == "wiki_log_entries" {
|
||||
cast = "bigint"
|
||||
}
|
||||
statement := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_id=$1 AND id = ANY($2::%s[])`, part.Name, cast)
|
||||
args := []any{t.snapshotTenant, ids}
|
||||
if tablesWithKB[part.Name] {
|
||||
statement += " AND knowledge_base_id=$3"
|
||||
args = append(args, t.snapshotKB)
|
||||
}
|
||||
var count int64
|
||||
if err := t.pool.QueryRow(ctx, statement, t.snapshotTenant, ids).Scan(&count); err != nil {
|
||||
if err := t.pool.QueryRow(ctx, statement, args...).Scan(&count); err != nil {
|
||||
return fmt.Errorf("检查目标 %s 的来源范围残留失败: %w", part.Name, err)
|
||||
}
|
||||
if count > 0 {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
@@ -22,7 +23,6 @@ var contentVolatileFields = map[string]bool{
|
||||
"created_at": true,
|
||||
"updated_at": true,
|
||||
"processed_at": true,
|
||||
"expires_at": true,
|
||||
}
|
||||
|
||||
func canonicalRowDigest(raw map[string]json.RawMessage) (string, error) {
|
||||
@@ -32,7 +32,9 @@ func canonicalRowDigest(raw map[string]json.RawMessage) (string, error) {
|
||||
continue
|
||||
}
|
||||
var decoded any
|
||||
if err := json.Unmarshal(value, &decoded); err != nil {
|
||||
decoder := json.NewDecoder(bytes.NewReader(value))
|
||||
decoder.UseNumber()
|
||||
if err := decoder.Decode(&decoded); err != nil {
|
||||
return "", fmt.Errorf("decode column %s: %w", key, err)
|
||||
}
|
||||
normalized[key] = decoded
|
||||
@@ -136,26 +138,29 @@ func archivedTableContent(archive *librarysnapshot.Archive, part librarysnapshot
|
||||
}
|
||||
|
||||
// orphanIndexDocuments 找出"索引里有、生产分块里没有"的文档(按 chunk_id 关联)。
|
||||
func (t *ProductionLibraryTarget) orphanIndexDocuments(ctx context.Context, documents []SearchDocument) []string {
|
||||
func (t *ProductionLibraryTarget) orphanIndexDocuments(ctx context.Context, documents []SearchDocument) ([]string, error) {
|
||||
if len(documents) == 0 {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
// 按文档归属判断而不是按 chunk_id:真实 WeKnora 是父子分块,
|
||||
// 索引里的子块 ID 本来就不在 chunks 表里,按 chunk_id 判会误报孤儿。
|
||||
rows, err := t.pool.Query(ctx, `SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL`,
|
||||
t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
known := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
known[id] = true
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orphans := make([]string, 0, 4)
|
||||
for _, document := range documents {
|
||||
var source struct {
|
||||
@@ -163,13 +168,13 @@ func (t *ProductionLibraryTarget) orphanIndexDocuments(ctx context.Context, docu
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
}
|
||||
if json.Unmarshal(document.Source, &source) != nil || source.KnowledgeID == "" {
|
||||
continue
|
||||
return nil, errors.New("index document has invalid or missing knowledge_id")
|
||||
}
|
||||
if !known[source.KnowledgeID] {
|
||||
orphans = append(orphans, document.ID)
|
||||
}
|
||||
}
|
||||
return orphans
|
||||
return orphans, nil
|
||||
}
|
||||
|
||||
// firstIndexDifference 返回第一处不一致的文档 ID 与字段,便于定位。
|
||||
@@ -258,7 +263,11 @@ func (t *ProductionLibraryTarget) verifyIndexDigest(ctx context.Context, archive
|
||||
}
|
||||
// 孤儿向量:索引里有、数据库分块里没有的文档必须报出来。
|
||||
// 只比"归档 vs 生产"会漏掉两边一致但都错的情况。
|
||||
if orphans := t.orphanIndexDocuments(ctx, snapshot.Documents); len(orphans) > 0 {
|
||||
orphans, orphanErr := t.orphanIndexDocuments(ctx, snapshot.Documents)
|
||||
if orphanErr != nil {
|
||||
return fmt.Errorf("index ownership verification failed: %w", orphanErr)
|
||||
}
|
||||
if len(orphans) > 0 {
|
||||
return fmt.Errorf("生产索引存在 %d 条孤儿文档(所属文档已不在数据库),首个 %s", len(orphans), orphans[0])
|
||||
}
|
||||
if len(snapshot.Documents) != len(archived) || snapshot.DocumentsSHA256 != wantDigest {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
@@ -55,46 +56,9 @@ func PersistWriteSet(archiveRoot string, set *libraryrelease.WriteSet) (string,
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码写集合失败: %w", err)
|
||||
}
|
||||
directory := filepath.Join(archiveRoot, writeSetDirName)
|
||||
if err := os.MkdirAll(directory, 0700); err != nil {
|
||||
return "", fmt.Errorf("创建写集合目录失败: %w", err)
|
||||
}
|
||||
path := writeSetPath(archiveRoot, digest)
|
||||
if existing, readErr := os.ReadFile(path); readErr == nil {
|
||||
var recorded libraryrelease.WriteSet
|
||||
if json.Unmarshal(existing, &recorded) != nil || recorded.Verify() != nil || recorded.Digest != digest {
|
||||
return "", errors.New("写集合记录同名但内容不符,拒绝覆盖")
|
||||
}
|
||||
return path, nil
|
||||
} else if !errors.Is(readErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("读取已有写集合失败: %w", readErr)
|
||||
}
|
||||
temporary := path + ".tmp"
|
||||
file, err := os.OpenFile(temporary, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("写入写集合失败: %w", err)
|
||||
}
|
||||
if _, err := file.Write(raw); err != nil {
|
||||
file.Close()
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("写入写集合失败: %w", err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
file.Close()
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("写集合未落盘: %w", err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("写集合未落盘: %w", err)
|
||||
}
|
||||
if err := os.Chmod(temporary, 0444); err != nil {
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("写集合只读化失败: %w", err)
|
||||
}
|
||||
if err := os.Rename(temporary, path); err != nil {
|
||||
os.Remove(temporary)
|
||||
return "", fmt.Errorf("写集合落盘失败: %w", err)
|
||||
if err := persistImmutableJSON(path, raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
@@ -152,11 +116,34 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
if err := t.bindSnapshotScope(manifestScope{tenantID: manifest.TenantID, knowledgeBaseID: manifest.KnowledgeBaseID}); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := validateArchivedLibraryClosure(archive, manifest); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := verifyLibraryRelationalClosure(ctx, t.pool, PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, true); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
schemaDigest, err := t.preflightMigrationCatalog(ctx, archive, manifest)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
backupResources, err := archivedSnapshotResourceIDs(archive, plan.BackupSnapshotID)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: plan.JobID, Target: plan.Target,
|
||||
resourceIDs := make([]string, 0, len(backupResources))
|
||||
for id := range backupResources {
|
||||
resourceIDs = append(resourceIDs, id)
|
||||
}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind == "resource" {
|
||||
resourceIDs = append(resourceIDs, part.Name)
|
||||
}
|
||||
}
|
||||
if err := verifyLibraryResourceOwners(ctx, t.pool, resourceIDs); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
set := libraryrelease.WriteSet{SchemaDigest: schemaDigest, Version: libraryrelease.MigrationWriteSetVersion, ContractVersion: migrationIdentityContractVersion,
|
||||
SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID, JobID: plan.JobID, Target: plan.Target,
|
||||
TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID,
|
||||
BackupSnapshotID: plan.BackupSnapshotID, TargetSnapshotID: plan.TargetSnapshotID,
|
||||
CreatedAt: t.now().UTC(), Universe: plan.Universe}
|
||||
@@ -171,6 +158,9 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
if len(ids) == 0 {
|
||||
continue
|
||||
}
|
||||
if part.Name == "wiki_log_entries" {
|
||||
continue
|
||||
} // source IDs are local; target IDs are assigned below
|
||||
owners, err := t.existingRowOwners(ctx, part.Name, ids)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
@@ -181,7 +171,7 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
set.Rows = append(set.Rows, libraryrelease.WriteSetRow{Table: part.Name, ID: id})
|
||||
continue
|
||||
}
|
||||
if part.Name == resourceReuseTableName && !backupResources[id] {
|
||||
if part.Name == resourceReuseTableName {
|
||||
// 资源不在预备份范围,但可能正是这个目标上一次成功同步写进去、
|
||||
// 又被恢复保留下来的那份内容。只有"内容/字节相同 + 来源可审计"
|
||||
// 才允许复用(不重写、不清理);否则按跨范围冲突拒绝。
|
||||
@@ -201,12 +191,34 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
set.Rows = append(set.Rows, libraryrelease.WriteSetRow{Table: part.Name, ID: id, Existing: true, Owner: owner})
|
||||
}
|
||||
}
|
||||
if err := t.preflightArchiveIndex(ctx, archive, manifest); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := t.preflightNaturalKeys(ctx, archive, manifest); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := t.planIndex(ctx, archive, manifest, &set); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := t.planObjects(ctx, archive, manifest, &set); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
set.LocalIDs, err = t.localIDRequests(archive, manifest)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := t.allocateLocalIDs(ctx, &set); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := set.Seal(); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if _, err := PersistWriteSet(t.config.ArchiveRoot, &set); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := t.AdoptWriteSet(set); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
@@ -240,11 +252,23 @@ func archivedSnapshotResourceIDs(archive *librarysnapshot.Archive, snapshotID st
|
||||
// 没有 id 列的关系表按父表 knowledges 判归属。
|
||||
func (t *ProductionLibraryTarget) existingRowOwners(ctx context.Context, table string, ids []string) (map[string]string, error) {
|
||||
owners := map[string]string{}
|
||||
if _, ok := migrationIdentityContracts[table]; !ok {
|
||||
return nil, fmt.Errorf("unknown migration table %s", table)
|
||||
}
|
||||
if table == "knowledge_tag_relations" {
|
||||
knowledgeIDs, tagIDs := make([]string, 0, len(ids)), make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
parts := strings.Split(id, ":")
|
||||
if len(parts) != 2 || !validSearchIdentifier(parts[0]) || !validSearchIdentifier(parts[1]) {
|
||||
return nil, errors.New("invalid relation tuple")
|
||||
}
|
||||
knowledgeIDs = append(knowledgeIDs, parts[0])
|
||||
tagIDs = append(tagIDs, parts[1])
|
||||
}
|
||||
rows, err := t.pool.Query(ctx, `
|
||||
SELECT r.knowledge_id, coalesce(r.tag_id,''), coalesce(k.tenant_id,0), coalesce(k.knowledge_base_id,'')
|
||||
FROM knowledge_tag_relations r LEFT JOIN knowledges k ON k.id=r.knowledge_id
|
||||
WHERE r.knowledge_id = ANY($1::text[])`, ids)
|
||||
WHERE (r.knowledge_id,r.tag_id) IN (SELECT * FROM unnest($1::text[],$2::text[]))`, knowledgeIDs, tagIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取目标 %s 归属失败", table)
|
||||
}
|
||||
@@ -271,6 +295,9 @@ WHERE b.id = ANY($1::text[])`
|
||||
} else if !tablesWithKB[table] {
|
||||
statement = fmt.Sprintf(`SELECT id, tenant_id, '' FROM %s WHERE id = ANY($1::text[])`, table)
|
||||
}
|
||||
if table == "wiki_log_entries" {
|
||||
statement = `SELECT id::text, tenant_id, coalesce(knowledge_base_id,'') FROM wiki_log_entries WHERE id = ANY($1::bigint[])`
|
||||
}
|
||||
rows, err := t.pool.Query(ctx, statement, ids)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取目标 %s 归属失败", table)
|
||||
@@ -326,6 +353,12 @@ func (t *ProductionLibraryTarget) assertWriteSetOwnership(table, id, owner strin
|
||||
// 等于把刚恢复的行再删一次。
|
||||
func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set libraryrelease.WriteSet,
|
||||
restored map[string]map[string]bool) error {
|
||||
tx, err := t.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
|
||||
// 子表先删:resource_bindings → chunks/knowledges、wiki 子表 → wiki 页 → 资源。
|
||||
for _, table := range []string{"resource_bindings", "chunks", "knowledges", "knowledge_tag_relations",
|
||||
"wiki_page_issues", "wiki_log_entries", "wiki_pages", "wiki_folders", "knowledge_tags", "resources"} {
|
||||
@@ -341,13 +374,32 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
|
||||
}
|
||||
statement := fmt.Sprintf(`DELETE FROM %s WHERE (%s)::text = ANY($1::text[])`, table, identityExpr(table))
|
||||
if table == "resources" {
|
||||
statement += `
|
||||
AND NOT EXISTS (SELECT 1 FROM resource_bindings b WHERE b.resource_id=resources.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.deleted_at IS NULL
|
||||
AND coalesce(resources.handle,'') <> ''
|
||||
AND position('resource://'||resources.handle IN coalesce(c.content,'')) > 0)`
|
||||
// Lock parent keys through grant check and delete; a concurrent FK insert
|
||||
// must wait rather than race the protection query and be cascaded away.
|
||||
locked, err := tx.Query(ctx, `SELECT id FROM resources WHERE id=ANY($1::text[]) FOR UPDATE`, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for locked.Next() {
|
||||
var id string
|
||||
if err = locked.Scan(&id); err != nil {
|
||||
locked.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
locked.Close()
|
||||
if err = locked.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = ensureNoResourceGrants(ctx, tx, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := ensureCreatedResourcesUnreferenced(ctx, tx, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := t.pool.Exec(ctx, statement, ids); err != nil {
|
||||
if _, err := tx.Exec(ctx, statement, ids); err != nil {
|
||||
return fmt.Errorf("清理本次新增的 %s 失败: %w", table, err)
|
||||
}
|
||||
}
|
||||
@@ -367,7 +419,7 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
|
||||
}
|
||||
statement := fmt.Sprintf(`SELECT (%s)::text FROM %s WHERE (%s)::text = ANY($1::text[])`,
|
||||
identityExpr(table), table, identityExpr(table))
|
||||
rows, err := t.pool.Query(ctx, statement, ids)
|
||||
rows, err := tx.Query(ctx, statement, ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("复核本次新增的 %s 失败: %w", table, err)
|
||||
}
|
||||
@@ -389,7 +441,7 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
|
||||
return fmt.Errorf("恢复后仍留下本次写入的 %d 行(%v):目标未回到预备份状态,不能当作已恢复",
|
||||
len(leftovers), leftovers)
|
||||
}
|
||||
return nil
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// snapshotRowIdentities 读出"恢复要用这份快照"的全部行身份(按表)。
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
@@ -47,57 +46,19 @@ func NewObjectImporter(store ObjectStore, config TargetObjectConfig) (*ObjectImp
|
||||
return &ObjectImporter{store: store, config: config}, nil
|
||||
}
|
||||
|
||||
func (importer *ObjectImporter) Stage(ctx context.Context, releaseRevision string, snapshot ObjectSnapshot) (ObjectStage, error) {
|
||||
if !validSearchIdentifier(releaseRevision) || !validLowerSHA256(snapshot.SHA256) || snapshot.SHA256 != objectSnapshotDigest(snapshot.Objects) {
|
||||
return ObjectStage{}, errors.New("invalid object import snapshot")
|
||||
}
|
||||
var total int64
|
||||
stage := ObjectStage{ReleaseRevision: releaseRevision, Provider: importer.config.Provider, Objects: make([]StagedObject, 0, len(snapshot.Objects))}
|
||||
for _, object := range snapshot.Objects {
|
||||
if !validSearchIdentifier(object.ResourceID) || len(object.Handle) != 22 || object.Size != int64(len(object.Data)) || object.SHA256 != shaBytes(object.Data) || !validObjectKey(object.PhysicalPath) {
|
||||
return ObjectStage{}, errors.New("invalid object import entry")
|
||||
}
|
||||
providerPath, ok := providerPathFromLocator(object.PhysicalPath)
|
||||
if !ok {
|
||||
return ObjectStage{}, errors.New("invalid object import locator")
|
||||
}
|
||||
total += object.Size
|
||||
stagingPath := ".governance-release-stage/" + releaseRevision + "/" + providerPath
|
||||
if !validObjectLocator(stagingPath) {
|
||||
return ObjectStage{}, errors.New("invalid object staging locator")
|
||||
}
|
||||
if err := importer.store.Put(ctx, importer.config.Provider, stagingPath, bytes.NewReader(object.Data), object.Size); err != nil {
|
||||
return ObjectStage{}, errors.New("write staged release object")
|
||||
}
|
||||
size, digest, err := importer.store.Stat(ctx, importer.config.Provider, stagingPath)
|
||||
if err != nil || size != object.Size || digest != object.SHA256 {
|
||||
return ObjectStage{}, errors.New("verify staged release object")
|
||||
}
|
||||
stage.Objects = append(stage.Objects, StagedObject{Handle: object.Handle, StagingPath: stagingPath, FinalPath: providerPath, Size: object.Size, SHA256: object.SHA256})
|
||||
}
|
||||
if total != snapshot.TotalBytes {
|
||||
return ObjectStage{}, errors.New("object import total mismatch")
|
||||
}
|
||||
return stage, nil
|
||||
// CheckLegacyObjectWrites has no configuration bypass. Document-level staging
|
||||
// and promotion do not carry an immutable WriteSet/attempt grant, so they cannot
|
||||
// participate in the exclusive object write domain. Read-only export is intact.
|
||||
func CheckLegacyObjectWrites() error {
|
||||
return errors.New("legacy object writes disabled: use the frozen-plan library worker and object gateway")
|
||||
}
|
||||
|
||||
func (importer *ObjectImporter) Promote(ctx context.Context, stage ObjectStage) error {
|
||||
if stage.Provider != importer.config.Provider || !validSearchIdentifier(stage.ReleaseRevision) {
|
||||
return errors.New("invalid object promotion stage")
|
||||
}
|
||||
for _, object := range stage.Objects {
|
||||
if !validObjectLocator(object.StagingPath) || !validObjectLocator(object.FinalPath) || !validLowerSHA256(object.SHA256) || object.Size < 0 {
|
||||
return errors.New("invalid object promotion entry")
|
||||
}
|
||||
if err := importer.store.Copy(ctx, importer.config.Provider, object.StagingPath, object.FinalPath); err != nil {
|
||||
return errors.New("promote release object")
|
||||
}
|
||||
size, digest, err := importer.store.Stat(ctx, importer.config.Provider, object.FinalPath)
|
||||
if err != nil || size != object.Size || digest != object.SHA256 {
|
||||
return errors.New("verify promoted release object")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
func (importer *ObjectImporter) Stage(context.Context, string, ObjectSnapshot) (ObjectStage, error) {
|
||||
return ObjectStage{}, CheckLegacyObjectWrites()
|
||||
}
|
||||
|
||||
func (importer *ObjectImporter) Promote(context.Context, ObjectStage) error {
|
||||
return CheckLegacyObjectWrites()
|
||||
}
|
||||
|
||||
// rewriteLocatorBucket 把资源定位符里的桶换成目标桶,结构保持不变:
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type ossListedVersion struct {
|
||||
Key string `xml:"Key" json:"key"`
|
||||
VersionID string `xml:"VersionId" json:"version_id"`
|
||||
}
|
||||
type ossExactVersionListing struct {
|
||||
Versions []ossListedVersion `json:"versions"`
|
||||
DeleteMarkers []ossListedVersion `json:"delete_markers"`
|
||||
RequestIDs []string `json:"request_ids"`
|
||||
}
|
||||
|
||||
// Query the exact key as prefix; never scan a bucket to infer ownership. Listing
|
||||
// is only discovery: deletion still requires full exact-version readback proof.
|
||||
func (s *ossVersionStore) listExactVersions(ctx context.Context, key string) (ossExactVersionListing, error) {
|
||||
result := ossExactVersionListing{Versions: []ossListedVersion{}, DeleteMarkers: []ossListedVersion{}}
|
||||
if !validObjectKey(key) || key == "" {
|
||||
return result, errors.New("exact OSS listing key required")
|
||||
}
|
||||
q := url.Values{"versions": {""}, "prefix": {key}, "max-keys": {"100"}}
|
||||
seen := map[string]bool{}
|
||||
seenMarkers := map[string]bool{}
|
||||
for page := 0; page < 100; page++ {
|
||||
resp, err := s.request(ctx, http.MethodGet, "", q, nil, nil)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
var value struct {
|
||||
XMLName xml.Name `xml:"ListVersionsResult"`
|
||||
Name string `xml:"Name"`
|
||||
Prefix string `xml:"Prefix"`
|
||||
Truncated *bool `xml:"IsTruncated"`
|
||||
NextKey string `xml:"NextKeyMarker"`
|
||||
NextVersion string `xml:"NextVersionIdMarker"`
|
||||
Versions []ossListedVersion `xml:"Version"`
|
||||
Deletes []ossListedVersion `xml:"DeleteMarker"`
|
||||
CommonPrefixes []string `xml:"CommonPrefixes>Prefix"`
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
resp.Body.Close()
|
||||
return result, fmt.Errorf("OSS list versions status %d", resp.StatusCode)
|
||||
}
|
||||
err = xml.NewDecoder(io.LimitReader(resp.Body, 1024*1024)).Decode(&value)
|
||||
resp.Body.Close()
|
||||
if err != nil || value.Name != s.bucket || value.Prefix != key || value.Truncated == nil || len(value.CommonPrefixes) != 0 {
|
||||
return result, errors.New("OSS version listing identity/completeness not proven")
|
||||
}
|
||||
result.RequestIDs = append(result.RequestIDs, resp.Header.Get("x-oss-request-id"))
|
||||
for _, v := range append(append([]ossListedVersion{}, value.Versions...), value.Deletes...) {
|
||||
if v.Key != key || v.VersionID == "" || seen[v.VersionID] {
|
||||
return result, errors.New("OSS listing contains unexpected key or duplicate version")
|
||||
}
|
||||
seen[v.VersionID] = true
|
||||
}
|
||||
result.Versions = append(result.Versions, value.Versions...)
|
||||
result.DeleteMarkers = append(result.DeleteMarkers, value.Deletes...)
|
||||
if !*value.Truncated {
|
||||
return result, nil
|
||||
}
|
||||
marker := value.NextKey + "\x00" + value.NextVersion
|
||||
if value.NextKey != key || value.NextVersion == "" || seenMarkers[marker] {
|
||||
return result, errors.New("OSS listing pagination incomplete")
|
||||
}
|
||||
seenMarkers[marker] = true
|
||||
q.Set("key-marker", value.NextKey)
|
||||
q.Set("version-id-marker", value.NextVersion)
|
||||
}
|
||||
return result, errors.New("OSS version listing page budget exceeded")
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Native OSS version operations deliberately do NOT implement conditionalObjectStore:
|
||||
// OSS documents forbid-overwrite as ineffective on versioned buckets. Appending a
|
||||
// version is recoverable, but is not an atomic absent-key create. Keep that policy
|
||||
// decision separate from this protocol rather than silently weakening the gate.
|
||||
type ossVersionStore struct {
|
||||
endpoint *url.URL
|
||||
bucket, access, secret string
|
||||
maxBytes int64
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newOSSVersionStore(c S3ObjectStoreConfig) (*ossVersionStore, error) {
|
||||
u, err := url.Parse(c.Endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || c.Provider != "oss" || c.ForcePathStyle || c.Bucket == "" || strings.ContainsAny(c.Bucket, "/.: ") || c.AccessKeyID == "" || c.SecretAccessKey == "" {
|
||||
return nil, errors.New("invalid native OSS configuration")
|
||||
}
|
||||
if c.MaxObjectBytes == 0 {
|
||||
c.MaxObjectBytes = 100 * 1024 * 1024
|
||||
}
|
||||
if c.MaxObjectBytes < 1 {
|
||||
return nil, errors.New("invalid OSS size limit")
|
||||
}
|
||||
client := &http.Client{Timeout: 2 * time.Minute}
|
||||
if c.HTTPClient != nil {
|
||||
clone := *c.HTTPClient
|
||||
client = &clone
|
||||
}
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return errors.New("OSS redirect refused") }
|
||||
return &ossVersionStore{u, c.Bucket, c.AccessKeyID, c.SecretAccessKey, c.MaxObjectBytes, client}, nil
|
||||
}
|
||||
|
||||
func (s *ossVersionStore) request(ctx context.Context, method, key string, q url.Values, body []byte, headers http.Header) (*http.Response, error) {
|
||||
if key != "" && (!validObjectKey(key) || strings.Contains(key, "://") || strings.HasPrefix(key, "/")) {
|
||||
return nil, errors.New("invalid OSS key")
|
||||
}
|
||||
u := *s.endpoint
|
||||
u.Host = s.bucket + "." + s.endpoint.Host
|
||||
u.Path = "/" + key
|
||||
u.RawQuery = q.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid OSS request")
|
||||
}
|
||||
req.Header = headers.Clone()
|
||||
if req.Header == nil {
|
||||
req.Header = make(http.Header)
|
||||
}
|
||||
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
|
||||
resource := "/" + s.bucket + "/" + key
|
||||
keys := make([]string, 0, len(q))
|
||||
for k := range q {
|
||||
if k == "prefix" || k == "max-keys" || k == "key-marker" || k == "version-id-marker" {
|
||||
if method != http.MethodGet || key != "" || !q.Has("versions") || q.Get("prefix") == "" {
|
||||
return nil, errors.New("OSS listing must be exact-key scoped and read-only")
|
||||
}
|
||||
continue // These list filters are not OSS V1 signed subresources.
|
||||
}
|
||||
if k != "versionId" && k != "versioning" && k != "versions" {
|
||||
return nil, errors.New("unsupported OSS subresource")
|
||||
}
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for i, k := range keys {
|
||||
if i == 0 {
|
||||
resource += "?"
|
||||
} else {
|
||||
resource += "&"
|
||||
}
|
||||
resource += k
|
||||
if q.Get(k) != "" {
|
||||
resource += "=" + q.Get(k)
|
||||
}
|
||||
}
|
||||
oss := map[string]string{}
|
||||
for k, v := range req.Header {
|
||||
lower := strings.ToLower(k)
|
||||
if strings.HasPrefix(lower, "x-oss-") {
|
||||
oss[lower] = strings.TrimSpace(strings.Join(v, ","))
|
||||
}
|
||||
}
|
||||
keys = keys[:0]
|
||||
for k := range oss {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
canonical := ""
|
||||
for _, k := range keys {
|
||||
canonical += k + ":" + oss[k] + "\n"
|
||||
}
|
||||
toSign := method + "\n" + req.Header.Get("Content-MD5") + "\n" + req.Header.Get("Content-Type") + "\n" + req.Header.Get("Date") + "\n" + canonical + resource
|
||||
mac := hmac.New(sha1.New, []byte(s.secret))
|
||||
_, _ = mac.Write([]byte(toSign))
|
||||
req.Header.Set("Authorization", "OSS "+s.access+":"+base64.StdEncoding.EncodeToString(mac.Sum(nil)))
|
||||
// No retry middleware and no redirect: an ambiguous write remains one attempt.
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, errors.New("native OSS transport outcome unknown")
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
func (s *ossVersionStore) versioning(ctx context.Context) error {
|
||||
resp, err := s.request(ctx, http.MethodGet, "", url.Values{"versioning": {""}}, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var value struct {
|
||||
Status string `xml:"Status"`
|
||||
}
|
||||
if resp.StatusCode != 200 || xml.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&value) != nil || value.Status != "Enabled" {
|
||||
return errors.New("OSS versioning is not confirmed Enabled")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *ossVersionStore) observeVersion(ctx context.Context, key, version string) (objectObservation, error) {
|
||||
q := url.Values{}
|
||||
if version != "" {
|
||||
if version == "null" {
|
||||
return objectObservation{}, errors.New("null is not an immutable OSS version")
|
||||
}
|
||||
q.Set("versionId", version)
|
||||
}
|
||||
resp, err := s.request(ctx, http.MethodGet, key, q, nil, nil)
|
||||
if err != nil {
|
||||
return objectObservation{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == 404 {
|
||||
var failure struct {
|
||||
Code string `xml:"Code"`
|
||||
}
|
||||
if xml.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&failure) != nil || (failure.Code != "NoSuchKey" && failure.Code != "NoSuchVersion") {
|
||||
return objectObservation{}, errors.New("OSS 404 is not an authoritative missing object version")
|
||||
}
|
||||
return objectObservation{}, nil
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
return objectObservation{}, fmt.Errorf("OSS version read status %d", resp.StatusCode)
|
||||
}
|
||||
got := resp.Header.Get("x-oss-version-id")
|
||||
if got == "" || got == "null" || version != "" && got != version || resp.Header.Get("ETag") == "" || resp.ContentLength < 0 || resp.ContentLength > s.maxBytes {
|
||||
return objectObservation{}, errors.New("OSS version identity incomplete")
|
||||
}
|
||||
hash := sha256.New()
|
||||
size, err := io.Copy(hash, io.LimitReader(resp.Body, s.maxBytes+1))
|
||||
if err != nil || size != resp.ContentLength {
|
||||
return objectObservation{}, errors.New("OSS version body incomplete")
|
||||
}
|
||||
return objectObservation{Exists: true, VersionID: got, ETag: resp.Header.Get("ETag"), Owner: resp.Header.Get("x-oss-meta-kg-release-owner"), Bytes: size, SHA256: hex.EncodeToString(hash.Sum(nil))}, nil
|
||||
}
|
||||
|
||||
// appendVersion is explicit about its semantics. Callers need an approved version-
|
||||
// append plan and a persisted intent; this is not wired as CreateObject.
|
||||
func (s *ossVersionStore) appendVersion(ctx context.Context, key string, body []byte, owner string) (objectObservation, error) {
|
||||
if len(owner) != 64 || int64(len(body)) > s.maxBytes {
|
||||
return objectObservation{}, errObjectWriteRejected
|
||||
}
|
||||
if _, err := hex.DecodeString(owner); err != nil {
|
||||
return objectObservation{}, errObjectWriteRejected
|
||||
}
|
||||
if err := s.versioning(ctx); err != nil {
|
||||
return objectObservation{}, err
|
||||
}
|
||||
resp, err := s.request(ctx, http.MethodPut, key, nil, body, http.Header{"Content-Type": {"application/octet-stream"}, "X-Oss-Meta-Kg-Release-Owner": {owner}})
|
||||
if err != nil {
|
||||
return objectObservation{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
version := resp.Header.Get("x-oss-version-id")
|
||||
if resp.StatusCode != 200 || version == "" || version == "null" {
|
||||
return objectObservation{}, errors.New("OSS append receipt unknown")
|
||||
}
|
||||
observation, err := s.observeVersion(ctx, key, version)
|
||||
sum := sha256.Sum256(body)
|
||||
if err != nil {
|
||||
return objectObservation{}, err
|
||||
}
|
||||
if !observation.Exists || observation.Owner != owner || observation.Bytes != int64(len(body)) || observation.SHA256 != hex.EncodeToString(sum[:]) {
|
||||
return objectObservation{}, errors.New("OSS exact version readback mismatch")
|
||||
}
|
||||
return observation, nil
|
||||
}
|
||||
func (s *ossVersionStore) removeVersion(ctx context.Context, key string, want objectObservation) error {
|
||||
if !want.Exists || want.VersionID == "" || want.VersionID == "null" || want.ETag == "" || want.Owner == "" || want.SHA256 == "" {
|
||||
return errors.New("OSS deletion requires complete owned version receipt")
|
||||
}
|
||||
got, err := s.observeVersion(ctx, key, want.VersionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !got.Exists {
|
||||
return nil
|
||||
}
|
||||
if got != want {
|
||||
return errors.New("OSS exact version differs from receipt")
|
||||
}
|
||||
resp, sendErr := s.request(ctx, http.MethodDelete, key, url.Values{"versionId": {want.VersionID}}, nil, nil)
|
||||
if resp != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
after, readErr := s.observeVersion(ctx, key, want.VersionID)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
if after.Exists {
|
||||
return fmt.Errorf("OSS exact version delete unconfirmed: %v", sendErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -28,7 +28,8 @@ type TableSnapshot struct {
|
||||
}
|
||||
|
||||
type PostgresSnapshot struct {
|
||||
Tables []TableSnapshot
|
||||
Catalog migrationCatalog `json:"catalog,omitempty"`
|
||||
Tables []TableSnapshot
|
||||
}
|
||||
|
||||
func (snapshot PostgresSnapshot) Table(name string) TableSnapshot {
|
||||
|
||||
@@ -363,9 +363,14 @@ func searchDocumentsDigest(documents []SearchDocument) (string, error) {
|
||||
|
||||
func canonicalJSON(raw json.RawMessage) (json.RawMessage, error) {
|
||||
var value any
|
||||
if err := json.Unmarshal(raw, &value); err != nil {
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !json.Valid(raw) {
|
||||
return nil, errors.New("invalid JSON")
|
||||
}
|
||||
return json.Marshal(value)
|
||||
}
|
||||
|
||||
|
||||
@@ -101,7 +101,7 @@ func (exporter *SearchExporter) PruneScope(ctx context.Context, identity SearchI
|
||||
end = len(stale)
|
||||
}
|
||||
payload := map[string]any{
|
||||
"query": map[string]any{"ids": map[string]any{"values": stale[start:end]}},
|
||||
"query": map[string]any{"bool": map[string]any{"filter": append(scopeFilterFor(inspection.fields, identity), map[string]any{"ids": map[string]any{"values": stale[start:end]}})}},
|
||||
}
|
||||
var response struct {
|
||||
Deleted int `json:"deleted"`
|
||||
@@ -126,6 +126,10 @@ func scopeFilterFor(fields searchFieldNames, identity SearchIdentity) []any {
|
||||
// BulkIndex 把归档里的原始文档与向量直接写入生产索引(不解析、不重新 Embedding)。
|
||||
// 写入前补齐 tenant_id/knowledge_base_id,避免归档文档缺字段时落到别的库。
|
||||
func (exporter *SearchExporter) BulkIndex(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity) error {
|
||||
return exporter.bulkIndex(ctx, documents, identity, nil)
|
||||
}
|
||||
|
||||
func (exporter *SearchExporter) bulkIndex(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity, guards map[string]indexWriteGuard) error {
|
||||
if len(documents) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -146,9 +150,21 @@ func (exporter *SearchExporter) BulkIndex(ctx context.Context, documents []libra
|
||||
return err
|
||||
}
|
||||
payload = encoded
|
||||
action, err := json.Marshal(map[string]any{"index": map[string]string{
|
||||
"_index": exporter.index, "_id": document.ID,
|
||||
}})
|
||||
operation := "index"
|
||||
metadata := map[string]any{"_index": exporter.index, "_id": document.ID}
|
||||
if guards != nil {
|
||||
guard, ok := guards[document.ID]
|
||||
if !ok {
|
||||
return errors.New("missing index write guard")
|
||||
}
|
||||
if !guard.Found {
|
||||
operation = "create"
|
||||
} else {
|
||||
metadata["if_seq_no"] = *guard.SeqNo
|
||||
metadata["if_primary_term"] = *guard.PrimaryTerm
|
||||
}
|
||||
}
|
||||
action, err := json.Marshal(map[string]any{operation: metadata})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,6 +205,18 @@ func (exporter *SearchExporter) BulkIndex(ctx context.Context, documents []libra
|
||||
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||
return errors.New("Elasticsearch bulk response invalid")
|
||||
}
|
||||
if len(parsed.Items) == len(documents) {
|
||||
for i, item := range parsed.Items {
|
||||
if len(item) != 1 {
|
||||
return errors.New("invalid bulk item result")
|
||||
}
|
||||
for operation, result := range item {
|
||||
if (operation != "index" && operation != "create") || result.ID != documents[i].ID || result.Status < 200 || result.Status >= 300 || result.Error != nil {
|
||||
return fmt.Errorf("Elasticsearch item outcome not confirmed: %s status %d", documents[i].ID, result.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if parsed.Errors {
|
||||
for _, item := range parsed.Items {
|
||||
for _, result := range item {
|
||||
|
||||
Reference in New Issue
Block a user