Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/storage/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Follow these rules when adding or modifying code under `internal/storage/`:
- **Multi-Page Pagination Test Coverage**: Unit and integration test suites for `List*` repositories MUST test pagination traversal across multiple pages (`N > page_size`) and verify that default sorting (empty `orderBy`) returns the view's declared default order (newest-first for feeds) consistently across page boundaries.

## 5. PostgreSQL Row Locking in Transactions
`pgdb.RunInTx` ([`postgres/pgdb/`](postgres/pgdb/)) runs `postgres.Storage.RunInTransaction` callbacks—and any repository-owned read-write transactions (such as [`postgres/operation/`](postgres/operation/))—at PostgreSQL's default `READ COMMITTED` isolation and retries `40001`/`40P01` up to `pgdb.DefaultMaxTxAttempts` times. A plain `SELECT` takes no row lock at this level, so concurrent read-modify-write transactions silently overwrite each other unless the read locks its rows. [`postgres/pausestate/`](postgres/pausestate/) and [`postgres/operation/`](postgres/operation/) are the reference implementations.
`pgdb.RunInTx` ([`postgres/pgdb/`](postgres/pgdb/)) runs `postgres.Storage.RunInTransaction` callbacks—and any repository-owned read-write transactions (such as [`postgres/operation/`](postgres/operation/))—at PostgreSQL's default `READ COMMITTED` isolation and retries `40001`/`40P01` up to `pgdb.DefaultMaxTxAttempts` times. A plain `SELECT` takes no row lock at this level, so concurrent read-modify-write transactions silently overwrite each other unless the read locks its rows. [`postgres/pausestate/`](postgres/pausestate/) and [`postgres/operation/`](postgres/operation/) are the reference implementations. `READ COMMITTED` with the explicit row locks below is the default; domains whose invariants span many rows, such as the component catalog (dependency cycles, active dependents, the ownership fence), instead call `TransactionRunner.RunInSerializableTransaction` (backed by `pgdb.RunInSerializableTx` at `SERIALIZABLE` isolation), and their repositories need no row locks.
- **Make `pgdb.RunInTx` callbacks safe to re-run**: Because `pgdb.RunInTx` retries the callback on serialization failures (`40001`) and deadlocks (`40P01`), reset any outer state modified by the callback at the start of each attempt and keep side effects (such as logging diffs or external calls) outside the callback until `pgdb.RunInTx` succeeds.
- **Lock read-modify-write reads with `FOR NO KEY UPDATE`**: Any `*TxRepository` read whose result the same transaction writes back (such as `FetchExperiment`, `FetchWorkUnit`, `FetchUpdatingWorkUnits`, `FetchXidEntry`, and `PauseStateTxRepository.Get`) must end with `FOR NO KEY UPDATE`. Never use `FOR UPDATE`: it conflicts with the `FOR KEY SHARE` lock that foreign-key checks take on a parent row when child rows are inserted, which deadlocks concurrent writers.
- **Lock batches in primary-key order**: Multi-row locking reads must `ORDER BY` the primary key so concurrent transactions acquire row locks in the same order.
Expand Down
16 changes: 10 additions & 6 deletions internal/storage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ Multi-step writes that touch multiple tables (for example, `restartWorkUnitExecu
```go
type TransactionRunner interface {
RunInTransaction(ctx context.Context, fn func(ctx context.Context, tx *Transaction) error) error
RunInTransactionWithCommitTime(ctx context.Context, fn func(ctx context.Context, tx *Transaction) error) (time.Time, error)
RunInSerializableTransaction(ctx context.Context, fn func(ctx context.Context, tx *Transaction) error) (time.Time, error)
}
```

`RunInTransactionWithCommitTime` follows the same callback and retry rules as `RunInTransaction` and also returns the backend's commit timestamp (the value written to commit-time columns such as `UpdateTime`), so callers can populate timestamps without reading rows back. The PostgreSQL backend returns `codes.Unimplemented` until the PostgreSQL serializable-transaction follow-up (#1416) lands. For reads that must come from one consistent snapshot without a write lock, `ComponentRepository.WithReadOnlySnapshot` passes `fn` a read-only `ComponentTxRepository`; writes through it fail with `codes.FailedPrecondition`.
`RunInSerializableTransaction` runs `fn` in a serializable read-write transaction with the same callback and retry rules as `RunInTransaction`, and returns the backend's commit timestamp (the value written to commit-time columns such as `UpdateTime`) so callers can populate timestamps without reading rows back. For reads that must come from one consistent snapshot without a write lock, `ComponentRepository.WithReadOnlySnapshot` passes `fn` a read-only `ComponentTxRepository`; writes through it fail with `codes.FailedPrecondition`.

Inside `RunInTransaction` (and `RunInTransactionWithCommitTime`), the callback receives a `*storage.Transaction` holding repositories bound to the active read-write transaction:
Inside `RunInTransaction` (and `RunInSerializableTransaction`), the callback receives a `*storage.Transaction` holding repositories bound to the active read-write transaction:

```go
type Transaction struct {
Expand Down Expand Up @@ -116,15 +116,19 @@ Methods that only buffer mutations into an active read-write transaction (such a

### Writing `RunInTransaction` Callbacks

Cloud Spanner may abort and re-run the `RunInTransaction` or `RunInTransactionWithCommitTime` callback when a transaction encounters lock contention (the PostgreSQL backend likewise re-runs it on serialization failures and deadlocks):
Cloud Spanner may abort and re-run the `RunInTransaction` or `RunInSerializableTransaction` callback when a transaction encounters lock contention (the PostgreSQL backend likewise re-runs it on serialization failures and deadlocks):

1. **Reset state on each attempt**: Initialize or clear any slices, maps, or counters modified by `fn` at the start of the callback, not outside it.
2. **Avoid external side effects**: Do not enqueue tasks or make external RPCs inside `fn`. Perform those after `RunInTransaction` / `RunInTransactionWithCommitTime` succeeds.
2. **Avoid external side effects**: Do not enqueue tasks or make external RPCs inside `fn`. Perform those after `RunInTransaction` / `RunInSerializableTransaction` succeeds.
3. **Read through `tx`**: Use `tx.WorkUnits` / `tx.Experiments` for reads inside the callback rather than the non-transactional `Storage`, so reads participate in the read-write transaction.

### Isolation

Spanner read-write transactions are always serializable. PostgreSQL runs `RunInTransaction` at `READ COMMITTED` by default, and repositories lock the rows they read and write back (see rule 5 of [`AGENTS.md`](AGENTS.md)). Callers whose invariants span many rows, such as the component store in [`pkg/components/store/dbstore/`](../../pkg/components/store/dbstore/), call `RunInSerializableTransaction` (backed by `pgdb.RunInSerializableTx` at `SERIALIZABLE` isolation) instead; PostgreSQL then aborts conflicting transactions with `40001`, and the callback is retried.

## Testing

- **Service unit tests**: Use `storage.MockStorage` ([`test_utils.go`](test_utils.go)) to test handler logic in memory. Set `MockStorage.RunInTransactionAttempts = 2` to verify that a transaction callback behaves properly when retried. Set `MockStorage.CommitTime` to pin the timestamp returned by `RunInTransactionWithCommitTime`; when it is zero, the mock returns `time.Now()`.
- **Service unit tests**: Use `storage.MockStorage` ([`test_utils.go`](test_utils.go)) to test handler logic in memory. Set `MockStorage.RunInTransactionAttempts = 2` to verify that a transaction callback behaves properly when retried. Set `MockStorage.CommitTime` to pin the timestamp returned by `RunInSerializableTransaction`; when it is zero, the mock returns `time.Now()`.
- **Spanner integration tests**: Tests under `internal/storage/spanner/...` run against the Spanner emulator to test SQL queries, mutations, and schema constraints.
- **PostgreSQL integration tests**: Tests under `internal/storage/postgres/...` call `postgrestest.Setup(ctx, t)` ([`postgres/testing/`](postgres/testing/)) to get isolated databases with the canonical schema on a shared `postgres:16-alpine` container; their `go_test` targets need `tags = ["local"]` for Docker access. [`postgres/operation/`](postgres/operation/) and [`postgres/pausestate/`](postgres/pausestate/) hold the reference repository tests, including the concurrency test required by [`AGENTS.md`](AGENTS.md).

Expand Down
5 changes: 3 additions & 2 deletions internal/storage/postgres/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ go_library(
visibility = ["//:__subpackages__"],
deps = [
"//internal/grpcerr",
"//internal/safesql",
"//internal/storage",
"//internal/storage/postgres/artifact",
"//internal/storage/postgres/clilogincode",
Expand All @@ -40,8 +41,6 @@ go_library(
"//internal/storage/postgres/xid",
"@com_github_jackc_pgx_v5//:pgx",
"@com_github_jackc_pgx_v5//pgxpool",
"@org_golang_google_grpc//codes",
"@org_golang_google_grpc//status",
],
)

Expand All @@ -52,9 +51,11 @@ go_test(
"storage_test.go",
],
embed = [":postgres"],
tags = ["local"],
deps = [
"//internal/grpcerr",
"//internal/storage",
"//internal/storage/postgres/testing",
"@com_github_jackc_pgx_v5//pgxpool",
"@org_golang_google_grpc//codes",
"@org_golang_google_grpc//status",
Expand Down
23 changes: 19 additions & 4 deletions internal/storage/postgres/pgdb/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ const (
)

type txBeginner interface {
Begin(ctx context.Context) (pgx.Tx, error)
BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)
}

type txRetryConfig struct {
txOptions pgx.TxOptions
maxAttempts int
initialBackoff time.Duration
maxBackoff time.Duration
Expand All @@ -60,6 +60,15 @@ func RunInTx(ctx context.Context, pool *pgxpool.Pool, fn func(ctx context.Contex
return runInTx(ctx, pool, defaultTxRetryConfig, fn)
}

// RunInSerializableTx executes fn inside a SERIALIZABLE read-write PostgreSQL transaction with the
// same commit, rollback, and retry semantics as RunInTx.
func RunInSerializableTx(ctx context.Context, pool *pgxpool.Pool, fn func(ctx context.Context, tx pgx.Tx) error) error {
if pool == nil {
return WrapStatusError("postgres pool must not be nil", grpcerr.ErrFailedPrecondition, nil)
}
return runInSerializableTx(ctx, pool, fn)
}

// RunInReadOnlyTx executes fn inside a REPEATABLE READ READ ONLY PostgreSQL transaction,
// releasing the snapshot via a detached-context Rollback when fn returns or panics.
func RunInReadOnlyTx(ctx context.Context, pool *pgxpool.Pool, fn func(ctx context.Context, tx pgx.Tx) error) error {
Expand All @@ -69,6 +78,12 @@ func RunInReadOnlyTx(ctx context.Context, pool *pgxpool.Pool, fn func(ctx contex
return runInReadOnlyTx(ctx, pool, fn)
}

func runInSerializableTx(ctx context.Context, beginner txBeginner, fn func(ctx context.Context, tx pgx.Tx) error) error {
cfg := defaultTxRetryConfig
cfg.txOptions = pgx.TxOptions{IsoLevel: pgx.Serializable}
return runInTx(ctx, beginner, cfg, fn)
}

func runInTx(ctx context.Context, beginner txBeginner, cfg txRetryConfig, fn func(ctx context.Context, tx pgx.Tx) error) error {
if fn == nil {
return WrapStatusError("transaction callback must not be nil", grpcerr.ErrInvalidArgument, nil)
Expand All @@ -79,7 +94,7 @@ func runInTx(ctx context.Context, beginner txBeginner, cfg txRetryConfig, fn fun
if err := ctx.Err(); err != nil {
return err
}
lastErr = runTxAttempt(ctx, beginner, fn)
lastErr = runTxAttempt(ctx, beginner, cfg.txOptions, fn)
if lastErr == nil || !IsRetryableTxError(lastErr) {
return lastErr
}
Expand All @@ -93,8 +108,8 @@ func runInTx(ctx context.Context, beginner txBeginner, cfg txRetryConfig, fn fun
return TranslateError(lastErr, "transaction")
}

func runTxAttempt(ctx context.Context, beginner txBeginner, fn func(ctx context.Context, tx pgx.Tx) error) error {
tx, err := beginner.Begin(ctx)
func runTxAttempt(ctx context.Context, beginner txBeginner, opts pgx.TxOptions, fn func(ctx context.Context, tx pgx.Tx) error) error {
tx, err := beginner.BeginTx(ctx, opts)
if err != nil {
return fmt.Errorf("failed to begin postgres transaction: %w", err)
}
Expand Down
36 changes: 36 additions & 0 deletions internal/storage/postgres/pgdb/tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,42 @@ func TestRunInTxExecutionAndRetries(t *testing.T) {
})
}

func TestRunInSerializableTx(t *testing.T) {
if err := RunInSerializableTx(context.Background(), nil, func(context.Context, pgx.Tx) error { return nil }); !errors.Is(err, grpcerr.ErrFailedPrecondition) {
t.Errorf("RunInSerializableTx(nil pool) = %v, want %v", err, grpcerr.ErrFailedPrecondition)
}

tests := []struct {
name string
run func(ctx context.Context, beginner txBeginner, fn func(context.Context, pgx.Tx) error) error
want []pgx.TxOptions
}{
{
name: "runInTx uses server default isolation",
run: func(ctx context.Context, beginner txBeginner, fn func(context.Context, pgx.Tx) error) error {
return runInTx(ctx, beginner, fastRetryConfig(), fn)
},
want: []pgx.TxOptions{{}},
},
{
name: "runInSerializableTx uses serializable isolation",
run: runInSerializableTx,
want: []pgx.TxOptions{{IsoLevel: pgx.Serializable}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
beginner := &fakeBeginner{}
if err := tt.run(context.Background(), beginner, func(context.Context, pgx.Tx) error { return nil }); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if diff := cmp.Diff(tt.want, beginner.txOpts); diff != "" {
t.Errorf("BeginTx options mismatch (-want +got):\n%s", diff)
}
})
}
}

func TestRunInTxContextAndPanicHandling(t *testing.T) {
serializationErr := &pgconn.PgError{Code: SQLStateSerializationFailure, Message: "could not serialize"}

Expand Down
38 changes: 31 additions & 7 deletions internal/storage/postgres/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@ import (

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"xmanager_cloud/internal/grpcerr"
"xmanager_cloud/internal/safesql"
"xmanager_cloud/internal/storage"
"xmanager_cloud/internal/storage/postgres/artifact"
"xmanager_cloud/internal/storage/postgres/clilogincode"
Expand Down Expand Up @@ -52,7 +51,10 @@ type pauseStateRepository = pausestate.Repository
type pausedTaskRepository = pausedtask.Repository
type cliLoginCodeRepository = clilogincode.Repository

var _ storage.Storage = (*Storage)(nil)
var (
_ storage.Storage = (*Storage)(nil)
selectNowSQL = safesql.New("SELECT now()")
)

// Storage implements the storage.Storage interface using PostgreSQL.
type Storage struct {
Expand Down Expand Up @@ -107,10 +109,32 @@ func (s *Storage) RunInTransaction(ctx context.Context, fn func(ctx context.Cont
})
}

// RunInTransactionWithCommitTime returns codes.Unimplemented on PostgreSQL.
// TODO(#1416): implement with the PostgreSQL serializable-transaction follow-up.
func (s *Storage) RunInTransactionWithCommitTime(context.Context, func(ctx context.Context, tx *storage.Transaction) error) (time.Time, error) {
return time.Time{}, status.Error(codes.Unimplemented, "postgres storage: RunInTransactionWithCommitTime is not implemented")
// RunInSerializableTransaction executes fn in a PostgreSQL SERIALIZABLE read-write transaction and
// returns the transaction's now() timestamp in UTC, matching the timestamp stored by SQL writes
// using now() in that transaction.
func (s *Storage) RunInSerializableTransaction(ctx context.Context, fn func(ctx context.Context, tx *storage.Transaction) error) (time.Time, error) {
if s == nil || s.pool == nil {
return time.Time{}, pgdb.WrapStatusError("postgres pool must not be nil", grpcerr.ErrFailedPrecondition, nil)
}
if fn == nil {
return time.Time{}, pgdb.WrapStatusError("transaction callback must not be nil", grpcerr.ErrInvalidArgument, nil)
}
var commitTime time.Time
err := pgdb.RunInSerializableTx(ctx, s.pool, func(txCtx context.Context, pgTx pgx.Tx) error {
commitTime = time.Time{}
if err := fn(txCtx, s.newTransaction(pgTx)); err != nil {
return err
}
if err := pgTx.QueryRow(txCtx, selectNowSQL.String()).Scan(&commitTime); err != nil {
return pgdb.TranslateError(err, "transaction")
}
commitTime = commitTime.UTC()
return nil
})
if err != nil {
return time.Time{}, err
}
return commitTime, nil
}

func (s *Storage) newTransaction(tx pgdb.DBTX) *storage.Transaction {
Expand Down
70 changes: 65 additions & 5 deletions internal/storage/postgres/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ import (
"context"
"errors"
"testing"
"time"

"github.com/jackc/pgx/v5/pgxpool"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"xmanager_cloud/internal/grpcerr"
"xmanager_cloud/internal/storage"
postgrestest "xmanager_cloud/internal/storage/postgres/testing"
)

func newLazyTestPool(t *testing.T) *pgxpool.Pool {
Expand Down Expand Up @@ -144,16 +146,28 @@ func TestStorage(t *testing.T) {
},
},
{
name: "RunInTransactionWithCommitTime unimplemented",
name: "RunInSerializableTransaction nil pool",
check: func(t *testing.T) {
ts, err := s.RunInTransactionWithCommitTime(ctx, func(ctx context.Context, tx *storage.Transaction) error {
ts, err := (&Storage{}).RunInSerializableTransaction(ctx, func(ctx context.Context, tx *storage.Transaction) error {
return nil
})
if got := status.Code(err); got != codes.Unimplemented {
t.Errorf("RunInTransactionWithCommitTime() code = %v, want %v (err: %v)", got, codes.Unimplemented, err)
if got := status.Code(err); got != codes.FailedPrecondition {
t.Errorf("RunInSerializableTransaction() code = %v, want %v (err: %v)", got, codes.FailedPrecondition, err)
}
if !ts.IsZero() {
t.Errorf("RunInTransactionWithCommitTime() timestamp = %v, want zero", ts)
t.Errorf("RunInSerializableTransaction() timestamp = %v, want zero", ts)
}
},
},
{
name: "RunInSerializableTransaction nil callback",
check: func(t *testing.T) {
ts, err := s.RunInSerializableTransaction(ctx, nil)
if got := status.Code(err); got != codes.InvalidArgument {
t.Errorf("RunInSerializableTransaction(nil) code = %v, want %v (err: %v)", got, codes.InvalidArgument, err)
}
if !ts.IsZero() {
t.Errorf("RunInSerializableTransaction(nil) timestamp = %v, want zero", ts)
}
},
},
Expand All @@ -165,3 +179,49 @@ func TestStorage(t *testing.T) {
})
}
}

func TestStorage_RunInSerializableTransaction(t *testing.T) {
ctx := context.Background()
_, pool := postgrestest.Setup(ctx, t)
s, err := NewStorage(pool)
if err != nil {
t.Fatalf("NewStorage() failed: %v", err)
}

commitTime, err := s.RunInSerializableTransaction(ctx, func(txCtx context.Context, tx *storage.Transaction) error {
return tx.PauseState.Set(txCtx, &storage.PauseSchedulingState{SchedulingPaused: true})
})
if err != nil {
t.Fatalf("RunInSerializableTransaction() failed: %v", err)
}
if commitTime.IsZero() || commitTime.Location() != time.UTC {
t.Errorf("commitTime = %v (%v), want non-zero UTC timestamp", commitTime, commitTime.Location())
}

stored, err := s.PauseState().Get(ctx)
if err != nil {
t.Fatalf("PauseState().Get() failed: %v", err)
}
if !stored.SchedulingPaused || !commitTime.Equal(stored.UpdatedAt) {
t.Errorf("stored = (%v, %v), want (true, %v)", stored.SchedulingPaused, stored.UpdatedAt, commitTime)
}

callbackErr := errors.New("callback failed")
got, err := s.RunInSerializableTransaction(ctx, func(txCtx context.Context, tx *storage.Transaction) error {
if err := tx.PauseState.Set(txCtx, &storage.PauseSchedulingState{SchedulingPaused: false}); err != nil {
return err
}
return callbackErr
})
if !errors.Is(err, callbackErr) || !got.IsZero() {
t.Errorf("RunInSerializableTransaction(callbackErr) = (%v, %v), want (zero, %v)", got, err, callbackErr)
}

afterRollback, err := s.PauseState().Get(ctx)
if err != nil {
t.Fatalf("PauseState().Get() after rollback failed: %v", err)
}
if !afterRollback.SchedulingPaused {
t.Error("PauseState().SchedulingPaused = false after rollback, want true")
}
}
Loading
Loading