feat(library): 整库发布身份、写集合与收尾边界
build / build (push) Successful in 1m45s

执行时真实时钟与持久授权回读(撤销/过期即停并保留预备份)、写集合写前落盘、
租约与 attempt 身份、恢复队列与原发送身份分离、成功收尾必须释放维护后再登记终态。
This commit is contained in:
姚章浩
2026-11-01 11:35:10 +08:00
parent 5afd8c0140
commit 8d838d9cb4
82 changed files with 4809 additions and 551 deletions
+14
View File
@@ -0,0 +1,14 @@
package libraryrelease
import "encoding/json"
// IndexWrite freezes the exact index/ID, original bytes and CAS generation.
// After=nil is an explicit removal, never a scope-wide delete-by-query.
type IndexWrite struct {
Index string `json:"index"`
ID string `json:"id"`
Before json.RawMessage `json:"before,omitempty"`
SeqNo *int64 `json:"seq_no,omitempty"`
PrimaryTerm *int64 `json:"primary_term,omitempty"`
After json.RawMessage `json:"after,omitempty"`
}
+18
View File
@@ -0,0 +1,18 @@
package libraryrelease
// ObjectWrite identifies a physical object, not a row ID or a guessed orphan.
// Existing objects are read-only. This protocol refuses differing overwrites.
type ObjectWrite struct {
BeforeVersionID string `json:"before_version_id,omitempty"`
ResourceID string `json:"resource_id"`
Provider string `json:"provider"`
BackendID string `json:"backend_id"`
Bucket string `json:"bucket"`
Key string `json:"key"`
Locator string `json:"locator"`
SHA256 string `json:"sha256"`
Bytes int64 `json:"bytes"`
Existing bool `json:"existing"`
BeforeETag string `json:"before_etag,omitempty"`
OwnerToken string `json:"owner_token"`
}
+42
View File
@@ -115,6 +115,16 @@ type Recorder interface {
Stage(ctx context.Context, stage string, state string, detail string)
}
// GrantRevalidator 让编排在每笔副作用前按**持久授权**回读。
//
// 内存里的 Grant 只是一个快照:它既不能延长有效期,也不能掩盖中途撤销。
// 目标实现了这个接口就必须给出权威答案(读治理库的授权行);返回错误即拒绝继续。
// 未实现时行为不变(只核静态有效期),所以这不是给"忘记接线"留的后门 ——
// 生产目标的 wrapper 由 runLibraryRelease 无条件接线。
type GrantRevalidator interface {
RevalidateGrant(ctx context.Context, grant Grant) error
}
// BackupObserver 让调用方在预备份完成时立刻持久化快照身份:
// worker 被杀后重启必须能接管这份预备份,而不是重新备份覆盖它。
type BackupObserver interface {
@@ -184,6 +194,8 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor
if recorder == nil {
recorder = NoopRecorder{}
}
// Request.Now is a diagnostic input, not a clock authority for execution.
request.Now = time.Now().UTC()
if err := ValidateGrant(request); err != nil {
outcome.Error = err.Error()
recorder.Stage(ctx, "prebackup", "failed", err.Error())
@@ -217,6 +229,33 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor
}
recorder.Stage(ctx, "prebackup", "succeeded", "预备份 "+backup.ID)
// Backup may outlive the grant. Recheck before planning (which may allocate
// numbers), and again after durable plan registration before the first apply.
// With a GrantRevalidator the check is authoritative: a revoked or expired
// authorization row stops the run even though the in-memory grant still looks
// valid, and a stale in-memory expiry cannot be extended either.
checkLiveGrant := func() bool {
request.Now = time.Now().UTC()
if e := ValidateGrant(request); e != nil {
outcome.Error = e.Error()
outcome.Recovery = "预备份保留;需要有效的新授权后继续"
recorder.Stage(ctx, "prebackup", "failed", outcome.Error)
return false
}
if revalidator, ok := target.(GrantRevalidator); ok {
if e := revalidator.RevalidateGrant(ctx, request.Grant); e != nil {
outcome.Error = "持久授权已失效,未继续写入:" + e.Error()
outcome.Recovery = "预备份保留;重新签发授权后按原预备份继续"
recorder.Stage(ctx, "prebackup", "failed", outcome.Error)
return false
}
}
return true
}
if !checkLiveGrant() {
return outcome
}
// 写集合必须在第一笔写入之前落盘并登记:恢复只按"这次明确写了什么"清理,
// 不按目标现状推断残渣(那会把历史孤儿/共享资源当成本次残留删掉)。
existingPlan := backup.WriteSet != nil
@@ -265,6 +304,9 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor
}
}
if !checkLiveGrant() {
return outcome
}
for _, stage := range Stages() {
recorder.Stage(ctx, string(stage), "running", "")
if err = target.Apply(ctx, stage, request.SnapshotID); err != nil {
+58 -11
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"sort"
"strconv"
"time"
)
@@ -15,6 +16,9 @@ import (
// 宁可保持维护,也不要用一份"格式变了但看起来还能读"的记录去删目标数据。
const WriteSetVersion = 1
// MigrationWriteSetVersion rejects reinterpretation by old V1 executors.
const MigrationWriteSetVersion = 2
// WriteSetRow 是台账里的一行:本次发布明确要写的精确身份 + 写前状态。
//
// 为什么需要"写前状态":恢复不能在目标里按"没人引用"推断残渣。历史孤儿资源、
@@ -75,17 +79,33 @@ type PriorSnapshot struct {
// WriteSet 是"这一次发布的写集合 + 写前整实例内容证据",内容寻址、可校验、
// 与 job/target/backup 绑定。恢复只读它,不读目标现状去推断。
// LocalIDMapping is operation-local source lineage. Decimal strings are used
// only inside this typed sidecar; archived row values remain JSON integers.
type LocalIDMapping struct {
Table string `json:"table"`
Column string `json:"column"`
Source string `json:"source"`
Target string `json:"target"`
}
type WriteSet struct {
Version int `json:"version"`
JobID string `json:"job_id"`
Target string `json:"target"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
BackupSnapshotID string `json:"backup_snapshot_id"`
TargetSnapshotID string `json:"target_snapshot_id"`
CreatedAt time.Time `json:"created_at"`
Rows []WriteSetRow `json:"rows"`
Universe map[string]TableFingerprint `json:"universe"`
Index []IndexWrite `json:"index,omitempty"`
Objects []ObjectWrite `json:"objects,omitempty"`
SchemaDigest string `json:"schema_digest,omitempty"`
ContractVersion int `json:"contract_version,omitempty"`
SourceTenantID uint64 `json:"source_tenant_id,omitempty"`
SourceKnowledgeBaseID string `json:"source_knowledge_base_id,omitempty"`
LocalIDs []LocalIDMapping `json:"local_ids,omitempty"`
Version int `json:"version"`
JobID string `json:"job_id"`
Target string `json:"target"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
BackupSnapshotID string `json:"backup_snapshot_id"`
TargetSnapshotID string `json:"target_snapshot_id"`
CreatedAt time.Time `json:"created_at"`
Rows []WriteSetRow `json:"rows"`
Universe map[string]TableFingerprint `json:"universe"`
// Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它,
// 记录被改一个字节就对不上。
Digest string `json:"digest"`
@@ -111,6 +131,12 @@ func (w *WriteSet) Seal() error {
// CanonicalBytes 是不含摘要字段的规范字节:摘要覆盖的就是它,落盘文件另外
// 带上摘要本身(便于自描述),读回时用同一份规范字节重新推导。
func (w WriteSet) CanonicalBytes() ([]byte, error) {
if w.Version == WriteSetVersion && (w.ContractVersion != 0 || w.SourceTenantID != 0 || w.SourceKnowledgeBaseID != "" || len(w.LocalIDs) != 0 || w.SchemaDigest != "" || len(w.Objects) != 0 || len(w.Index) != 0) {
return nil, errors.New("historical V1 cannot carry migration contract fields")
}
if w.Version != WriteSetVersion && w.Version != MigrationWriteSetVersion {
return nil, errors.New("unsupported write set format")
}
copied := w
copied.Digest = ""
rows := make([]WriteSetRow, len(w.Rows))
@@ -142,7 +168,28 @@ func (w *WriteSet) computeDigest() (string, error) {
// Verify 校验摘要与必备身份。缺任一身份都必须失败:没有绑定就没有"这份记录属于
// 这个作业/目标/预备份"的证明,拿它去删目标数据无法追责。
func (w *WriteSet) Verify() error {
if w.Version != WriteSetVersion {
if w.ContractVersion != 0 && w.ContractVersion != 1 {
return errors.New("unsupported migration contract version")
}
if len(w.LocalIDs) > 0 && (w.ContractVersion != 1 || w.SourceTenantID == 0 || w.SourceKnowledgeBaseID == "") {
return errors.New("local mapping lacks source contract binding")
}
sources, targets := map[string]bool{}, map[string]bool{}
for _, m := range w.LocalIDs {
valid := (m.Table == "chunks" || m.Table == "knowledge_tags") && m.Column == "seq_id" || m.Table == "wiki_log_entries" && m.Column == "id"
a, e1 := strconv.ParseInt(m.Source, 10, 64)
b, e2 := strconv.ParseInt(m.Target, 10, 64)
if !valid || e1 != nil || e2 != nil || a <= 0 || b <= 0 || strconv.FormatInt(a, 10) != m.Source || strconv.FormatInt(b, 10) != m.Target {
return errors.New("invalid typed local mapping")
}
source, target := m.Table+"/"+m.Source, m.Table+"/"+m.Target
if sources[source] || targets[target] {
return errors.New("duplicate typed local mapping")
}
sources[source] = true
targets[target] = true
}
if w.Version != WriteSetVersion && w.Version != MigrationWriteSetVersion {
return fmt.Errorf("写集合记录版本 %d 不受支持(当前 %d)", w.Version, WriteSetVersion)
}
if w.JobID == "" || w.BackupSnapshotID == "" || w.TargetSnapshotID == "" {