package attachment import ( "bytes" "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "math" "strconv" "strings" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) const ( reconcilePageSize = 500 reconcileOperationTimeout = 30 * time.Second ) type Finding struct { Kind string `json:"kind"` Key string `json:"key"` Action string `json:"action"` Applied bool `json:"applied"` } // SQLQueries counts SQL statements, including transaction control and locks. // S3Calls counts calls to the Blobs port, including each list page and deep GET. type Stats struct { ElapsedMS int64 `json:"elapsed_ms"` SQLQueries int64 `json:"sql_queries"` S3Calls int64 `json:"s3_calls"` ScannedFiles int64 `json:"scanned_files"` ScannedObjects int64 `json:"scanned_objects"` Findings int64 `json:"findings"` Repaired int64 `json:"repaired"` } type Reconciler struct { db *pgxpool.Pool blobs Blobs grace time.Duration retention time.Duration } type ReconcileOptions struct { Apply bool Deep bool } func NewReconciler(db *pgxpool.Pool, blobs Blobs, grace time.Duration) (*Reconciler, error) { return NewReconcilerWithRetention(db, blobs, grace, 24*time.Hour) } func NewReconcilerWithRetention(db *pgxpool.Pool, blobs Blobs, grace, retention time.Duration) (*Reconciler, error) { if retention < time.Second { return nil, errors.New("reconcile: staging retention must be at least one second") } if db == nil || blobs == nil { return nil, errors.New("reconcile: database and blobs are required") } if grace == 0 { grace = time.Hour } if grace < 2*time.Minute { return nil, errors.New("reconcile: grace must be at least two minutes") } return &Reconciler{db: db, blobs: blobs, grace: grace, retention: retention}, nil } // Run streams findings and keeps at most one page of metadata in memory. // Dry runs only read storage. Each apply candidate is checked again under the // publisher's transaction lock; no scan snapshot authorizes a later mutation. func (r *Reconciler) Run(ctx context.Context, options ReconcileOptions, emit func(Finding)) (stats Stats, err error) { started := time.Now() defer func() { stats.ElapsedMS = time.Since(started).Milliseconds() }() run := reconcileRun{ r: r, ctx: ctx, apply: options.Apply, deep: options.Deep, emit: emit, stats: &stats, cutoff: started.Add(-r.grace), } for _, prefix := range []string{"staging/", "variants/", "blobs/"} { if err = run.objects(prefix); err != nil { return stats, err } } err = run.files() return stats, err } type reconcileRun struct { r *Reconciler ctx context.Context apply, deep bool emit func(Finding) stats *Stats cutoff time.Time } func (s *reconcileRun) note(f *Finding) { if f == nil { return } s.stats.Findings++ if f.Applied { s.stats.Repaired++ } if s.emit != nil { s.emit(*f) } } func (s *reconcileRun) old(modified time.Time) bool { // Unknown timestamps must never authorize collection. return !modified.IsZero() && modified.Before(s.cutoff) } func (s *reconcileRun) objects(prefix string) error { after := "" for { if err := s.ctx.Err(); err != nil { return err } s.stats.S3Calls++ opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout) page, err := s.r.blobs.List(opCtx, prefix, after, reconcilePageSize) cancel() if err != nil { return fmt.Errorf("reconcile list %s: %w", prefix, err) } if len(page) == 0 { return nil } var known map[string]bool if prefix == "blobs/" { known, err = s.knownFiles(page) if err != nil { return err } } for _, obj := range page { if obj.Key <= after { return errors.New("reconcile: object page did not advance") } after = obj.Key s.stats.ScannedObjects++ if !s.old(obj.Modified) { continue } var finding *Finding if prefix == "blobs/" { finding, err = s.orphan(obj, known[obj.Key]) } else { finding, err = s.jobObject(prefix, obj) } if err != nil { return fmt.Errorf("reconcile %s: %w", obj.Key, err) } s.note(finding) } } } func (s *reconcileRun) stat(key string) (Object, error) { s.stats.S3Calls++ opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout) defer cancel() return s.r.blobs.Stat(opCtx, key) } func (s *reconcileRun) delete(key string) error { s.stats.S3Calls++ opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout) defer cancel() err := s.r.blobs.Delete(opCtx, key) if errors.Is(err, ErrObjectMissing) { return nil } return err } // Failed sources remain available for operator replay until the retention period after failure elapses. // Staging shared by several pipeline versions is retained while any active job needs it. func (s *reconcileRun) jobObject(prefix string, obj Object) (*Finding, error) { parts := strings.Split(strings.TrimPrefix(obj.Key, prefix), "/") id, idErr := uuid.Parse(parts[0]) kind := "stale_staging" query := `SELECT EXISTS(SELECT 1 FROM attachment_jobs WHERE attachment_id=$1 AND source_key=$2 AND (state IN ('queued','processing') OR (state='failed' AND updated_at >= now()-$3::bigint*interval '1 second')))` args := []any{id, obj.Key, int64(s.r.retention / time.Second)} if prefix == "variants/" { if len(parts) != 4 || idErr != nil { return &Finding{Kind: "invalid_variant_key", Key: obj.Key, Action: "report"}, nil } version, err := strconv.Atoi(parts[1]) if err != nil || version < 1 || version > math.MaxInt32 { return &Finding{Kind: "invalid_variant_key", Key: obj.Key, Action: "report"}, nil } kind = "orphan_variant" query = `SELECT EXISTS(SELECT 1 FROM attachment_variants WHERE attachment_id=$1 AND pipeline_version=$3 AND object_key=$2) OR EXISTS(SELECT 1 FROM attachment_jobs WHERE attachment_id=$1 AND pipeline_version=$3 AND state IN ('queued','processing'))` args[2] = version } finding := &Finding{Kind: kind, Key: obj.Key, Action: "delete_object"} var keep bool s.stats.SQLQueries++ if err := s.r.db.QueryRow(s.ctx, query, args...).Scan(&keep); err != nil { return nil, err } if keep { return nil, nil } if !s.apply { return finding, nil } keyHash := sha256.Sum256([]byte(obj.Key)) return s.locked(keyHash[:], func(opCtx context.Context, tx pgx.Tx) (*Finding, error) { // Intake locks the staging key before inserting an attachment. Replay, // reprocess and completion lock the existing attachment before changing job state. if idErr == nil { s.stats.SQLQueries++ if _, err := tx.Exec(opCtx, `SELECT id FROM attachments WHERE id=$1 FOR UPDATE`, id); err != nil { return nil, err } } s.stats.SQLQueries++ if err := tx.QueryRow(opCtx, query, args...).Scan(&keep); err != nil { return nil, err } if keep { return nil, nil } op := *s op.ctx = opCtx current, err := op.stat(obj.Key) if errors.Is(err, ErrObjectMissing) { return nil, nil } if err != nil { return nil, err } if !s.old(current.Modified) { return nil, nil } if err := op.delete(obj.Key); err != nil { return nil, err } finding.Applied = true return finding, nil }) } func (s *reconcileRun) knownFiles(page []Object) (map[string]bool, error) { hashes := make([][]byte, 0, len(page)) for _, obj := range page { if !s.old(obj.Modified) { continue } hash, err := hex.DecodeString(obj.Key[len("blobs/"):]) if err == nil && len(hash) == sha256.Size && BlobKey(hash) == obj.Key { hashes = append(hashes, hash) } } known := make(map[string]bool, len(hashes)) if len(hashes) == 0 { return known, nil } s.stats.SQLQueries++ rows, err := s.r.db.Query(s.ctx, ` SELECT hash FROM files WHERE hash = ANY($1::bytea[])`, hashes) if err != nil { return nil, err } defer rows.Close() for rows.Next() { var hash []byte if err := rows.Scan(&hash); err != nil { return nil, err } known[BlobKey(hash)] = true } return known, rows.Err() } func (s *reconcileRun) orphan(obj Object, known bool) (*Finding, error) { hash, err := hex.DecodeString(obj.Key[len("blobs/"):]) if err != nil || len(hash) != sha256.Size || BlobKey(hash) != obj.Key { return &Finding{Kind: "invalid_blob_key", Key: obj.Key, Action: "report"}, nil } if known { return nil, nil } f := &Finding{Kind: "orphan_blob", Key: obj.Key, Action: "delete_object"} if !s.apply { return f, nil } return s.locked(hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) { op := *s op.ctx = opCtx var exists bool s.stats.SQLQueries++ if err := tx.QueryRow(opCtx, ` SELECT EXISTS (SELECT 1 FROM files WHERE hash = $1)`, hash).Scan(&exists); err != nil { return nil, err } if exists { return nil, nil } current, err := op.stat(obj.Key) if errors.Is(err, ErrObjectMissing) { return nil, nil } if err != nil { return nil, err } if !s.old(current.Modified) { return nil, nil } if err = op.delete(obj.Key); err != nil { return nil, err } f.Applied = true return f, nil }) } // locked also covers hashes without a files row: a publisher and an orphan // collector therefore cannot pass each other's existence check concurrently. func (s *reconcileRun) locked(hash []byte, fn func(context.Context, pgx.Tx) (*Finding, error)) (*Finding, error) { opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout) defer cancel() s.stats.SQLQueries++ tx, err := s.r.db.Begin(opCtx) if err != nil { return nil, err } committed := false defer func() { if !committed { cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() s.stats.SQLQueries++ _ = tx.Rollback(cleanup) } }() // Pool defaults cover ordinary requests; object I/O can outlive those // idle limits. The operation deadline bounds the entire locked candidate. s.stats.SQLQueries++ if _, err = tx.Exec(opCtx, `SET LOCAL idle_in_transaction_session_timeout='35s'`); err != nil { return nil, err } s.stats.SQLQueries++ if err = LockHash(opCtx, tx, hash); err != nil { return nil, err } f, err := fn(opCtx, tx) if err != nil { return nil, err } s.stats.SQLQueries++ err = tx.Commit(opCtx) committed = true // pgx closes the transaction even when COMMIT fails. if err != nil { return nil, err } return f, nil } type reconcileFile struct { hash []byte size int64 status FileStatus created time.Time referenced bool } func (s *reconcileRun) files() error { after := []byte{} for { if err := s.ctx.Err(); err != nil { return err } s.stats.SQLQueries++ rows, err := s.r.db.Query(s.ctx, ` SELECT f.hash, f.size_bytes, f.status, f.created_at, EXISTS (SELECT 1 FROM attachments a WHERE a.file_hash = f.hash) FROM files f WHERE f.hash > $1 ORDER BY f.hash LIMIT $2`, after, reconcilePageSize) if err != nil { return err } page := make([]reconcileFile, 0, reconcilePageSize) for rows.Next() { var f reconcileFile if err = rows.Scan(&f.hash, &f.size, &f.status, &f.created, &f.referenced); err != nil { rows.Close() return err } page = append(page, f) } err = rows.Err() rows.Close() if err != nil { return err } if len(page) == 0 { return nil } // Close the page's SQL rows before acquiring a transaction connection. for _, f := range page { after = f.hash s.stats.ScannedFiles++ if !s.candidate(f) { continue } finding, err := s.inspect(f) if err == nil && s.apply && finding != nil && finding.Action != "report" { finding, err = s.repairFile(f.hash) } if err != nil { return fmt.Errorf("reconcile file %s: %w", BlobKey(f.hash), err) } s.note(finding) } } } func (s *reconcileRun) repairFile(hash []byte) (*Finding, error) { return s.locked(hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) { op := *s op.ctx = opCtx var current reconcileFile s.stats.SQLQueries++ err := tx.QueryRow(opCtx, ` SELECT f.hash, f.size_bytes, f.status, f.created_at, EXISTS (SELECT 1 FROM attachments a WHERE a.file_hash = f.hash) FROM files f WHERE f.hash = $1 FOR UPDATE OF f`, hash). Scan(¤t.hash, ¤t.size, ¤t.status, ¤t.created, ¤t.referenced) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } if err != nil { return nil, err } if !op.candidate(current) { return nil, nil } finding, err := op.inspect(current) if err != nil || finding == nil { return finding, err } switch finding.Action { case "delete_file": // Delete bytes first. A failed SQL commit leaves an unreferenced // missing row that the next pass can safely finish collecting. if err := op.delete(finding.Key); err != nil { return nil, err } s.stats.SQLQueries++ _, err = tx.Exec(opCtx, `DELETE FROM files WHERE hash = $1`, hash) case "mark_failed": s.stats.SQLQueries++ _, err = tx.Exec(opCtx, `UPDATE files SET status = $2 WHERE hash = $1`, hash, FileFailed) default: return finding, nil } if err != nil { return nil, err } finding.Applied = true return finding, nil }) } func (s *reconcileRun) candidate(f reconcileFile) bool { if !s.old(f.created) { return false } if !f.referenced { return f.status == FilePending || f.status == FileReady } return f.status == FileReady || f.status == FileFailed } func (s *reconcileRun) inspect(f reconcileFile) (*Finding, error) { key := BlobKey(f.hash) if !f.referenced { // A publication that rolled back can leave fresh bytes behind an old // pending row. Both the metadata and the current object must be old. obj, err := s.stat(key) if err != nil && !errors.Is(err, ErrObjectMissing) { return nil, err } if err == nil && !s.old(obj.Modified) { return nil, nil } return &Finding{Kind: "unreferenced_" + string(f.status), Key: key, Action: "delete_file"}, nil } obj, err := s.stat(key) if errors.Is(err, ErrObjectMissing) { if f.status == FileFailed { return nil, nil } return &Finding{Kind: "missing_blob", Key: key, Action: "mark_failed"}, nil } if err != nil { return nil, err } if obj.Size != f.size { return &Finding{Kind: "size_mismatch", Key: key, Action: "report"}, nil } if s.deep { match, err := s.verify(f) if err != nil { return nil, err } if !match { return &Finding{Kind: "hash_mismatch", Key: key, Action: "report"}, nil } } // A failed file stays failed even when the key reappears. Recovery requires // an explicit publisher; a shallow HEAD cannot prove content integrity. if f.status == FileFailed { return &Finding{Kind: "failed_present", Key: key, Action: "report"}, nil } return nil, nil } func (s *reconcileRun) verify(f reconcileFile) (bool, error) { if f.size < 0 || f.size == math.MaxInt64 { return false, errors.New("reconcile: invalid file size") } s.stats.S3Calls++ opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout) defer cancel() body, err := s.r.blobs.Open(opCtx, BlobKey(f.hash)) if err != nil { return false, err } hash := sha256.New() n, readErr := io.Copy(hash, io.LimitReader(body, f.size+1)) closeErr := body.Close() if readErr != nil { return false, readErr } if closeErr != nil { return false, closeErr } return n == f.size && bytes.Equal(hash.Sum(nil), f.hash), nil }