Repository navigation
feat(ladder): per-config persist lock and PlanAndSaveLadderRun #845
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| package config | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "log" | ||
| "time" | ||
|
|
||
| "github.com/google/uuid" | ||
| "github.com/jackc/pgx/v5" | ||
|
|
||
| "github.com/LeanerCloud/cloud-commitments-go/pkg/ladder" | ||
| ) | ||
|
|
||
| // ladderConfigLockPrefix namespaces the per-config ladder advisory lock. It is | ||
| // a distinct text input to the same hashtextextended(text, 0) bigint key space | ||
| // as planStepProviderLockPrefix and the purchase-submit lock; a 64-bit hash | ||
| // collision could only cause a spurious wait, never a correctness break. | ||
| const ladderConfigLockPrefix = "cudly:ladder-config:" | ||
|
|
||
| // ladderLockTimeout bounds only the advisory-lock wait so a stuck holder fails | ||
| // loudly instead of queueing every later run. Package var so a test can shrink it. | ||
| var ladderLockTimeout = 30 * time.Second | ||
|
|
||
| // LadderPlanBuilder computes a run and its new tranches from the config's | ||
| // in-flight commitment. It runs while the per-config lock is held inside the | ||
| // persist transaction: it must be pure compute (no provider or network I/O). | ||
| type LadderPlanBuilder func(inFlightUSDHr float64) (*LadderRunDB, []LadderTrancheDB, error) | ||
|
|
||
| func ladderConfigLockKey(configID string) string { return ladderConfigLockPrefix + configID } | ||
|
|
||
| // withLadderConfigLock runs fn in a READ COMMITTED transaction that holds the | ||
| // config's ladder lock. It is the only way planning (PlanAndSaveLadderRun) and | ||
| // claiming (ClaimDueLadderTranches) serialize on one config. | ||
| // | ||
| // Lock order: this lock is taken FIRST. Whatever fn takes afterwards (provider | ||
| // plan-step locks, LockPurchasePlanTx, row locks) comes after it; code holding | ||
| // an execution or tranche row lock must never take this lock. | ||
| // | ||
| // Isolation is set explicitly: under REPEATABLE READ the snapshot is fixed at | ||
| // the first statement, before the wait, so the in-flight read would be stale. | ||
| func (s *PostgresStore) withLadderConfigLock(ctx context.Context, configID string, fn func(tx pgx.Tx) error) error { | ||
| if configID == "" { | ||
| return errors.New("ladder config lock: empty config id") | ||
| } | ||
| tx, err := s.db.Begin(ctx) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to begin transaction: %w", err) | ||
| } | ||
| defer func() { | ||
| // ErrTxClosed after Commit is expected; the deferred call also covers a panic in fn. | ||
| if rbErr := tx.Rollback(ctx); rbErr != nil && !errors.Is(rbErr, pgx.ErrTxClosed) { | ||
| log.Printf("ladder config lock %s: rollback: %v", configID, rbErr) | ||
| } | ||
| }() | ||
|
|
||
| if err := acquireLadderConfigLock(ctx, tx, configID); err != nil { | ||
| return err | ||
| } | ||
| if err := fn(tx); err != nil { | ||
| return err | ||
| } | ||
| if err := tx.Commit(ctx); err != nil { | ||
| return fmt.Errorf("failed to commit transaction: %w", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // acquireLadderConfigLock must be the first thing run in tx: the isolation | ||
| // level can only be set before any query. | ||
| func acquireLadderConfigLock(ctx context.Context, tx pgx.Tx, configID string) error { | ||
| if _, err := tx.Exec(ctx, "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); err != nil { | ||
| return fmt.Errorf("ladder config lock %s: set isolation: %w", configID, err) | ||
| } | ||
| if _, err := tx.Exec(ctx, fmt.Sprintf("SET LOCAL lock_timeout = %d", ladderLockTimeout.Milliseconds())); err != nil { | ||
| return fmt.Errorf("ladder config lock %s: set lock_timeout: %w", configID, err) | ||
| } | ||
| if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", ladderConfigLockKey(configID)); err != nil { | ||
| return fmt.Errorf("ladder config lock %s: %w", configID, err) | ||
| } | ||
| // The timeout was for the advisory wait only; do not leak it into fn's statements. | ||
| if _, err := tx.Exec(ctx, "SET LOCAL lock_timeout TO DEFAULT"); err != nil { | ||
| return fmt.Errorf("ladder config lock %s: reset lock_timeout: %w", configID, err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // PlanAndSaveLadderRun reads the config's in-flight commitment, lets build turn | ||
| // it into a run plus tranches, and persists both, all in ONE transaction under | ||
| // the config's ladder lock. Two overlapping runs for one config therefore | ||
| // cannot both plan the same gap: the second waits, then reads the first's | ||
| // committed tranches as in-flight. build must be pure compute. The run's | ||
| // ConfigID must equal configID and its StartedAt must equal asOf, which bounds | ||
| // both the netting read and the overdue sweep. | ||
| func (s *PostgresStore) PlanAndSaveLadderRun(ctx context.Context, configID string, asOf time.Time, build LadderPlanBuilder) (*LadderRunDB, error) { | ||
| var result LadderRunDB | ||
| err := s.withLadderConfigLock(ctx, configID, func(tx pgx.Tx) error { | ||
| inFlight, err := inFlightLadderCommit(ctx, tx, configID, asOf) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| run, tranches, err := build(inFlight) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if run == nil { | ||
| return errors.New("ladder plan builder returned a nil run") | ||
| } | ||
| if run.ConfigID == nil || *run.ConfigID != configID { | ||
| return fmt.Errorf("ladder run config_id does not match locked config %s", configID) | ||
| } | ||
| // The netting read above and the overdue sweep in the insert must use | ||
| // the same grace cutoff, or a row could be counted and canceled (or neither). | ||
| if !run.StartedAt.Equal(asOf) { | ||
| return fmt.Errorf("ladder run started_at %s does not match asOf %s", run.StartedAt, asOf) | ||
| } | ||
| if run.ID == "" { | ||
| run.ID = uuid.New().String() | ||
| } | ||
| saved, err := insertLadderRunWithTranchesTx(ctx, tx, run, tranches) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| result = *saved | ||
| return nil | ||
| }) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return &result, nil | ||
| } | ||
|
|
||
| // queryRower is satisfied by pgx.Tx and the pool connection. | ||
| type queryRower interface { | ||
| QueryRow(ctx context.Context, sql string, args ...any) pgx.Row | ||
| } | ||
|
|
||
| // inFlightLadderCommit sums the config's in-flight commitment; see | ||
| // GetInFlightLadderCommitUSDHr for the row classes counted and excluded. | ||
| func inFlightLadderCommit(ctx context.Context, q queryRower, configID string, asOf time.Time) (float64, error) { | ||
| var total float64 | ||
| err := q.QueryRow(ctx, ` | ||
| SELECT COALESCE(SUM(amount_usd_hr), 0) | ||
| FROM ladder_tranches | ||
| WHERE config_id = $1 | ||
| AND (status = $2 OR (status = $3 AND scheduled_date > $4)) | ||
| `, configID, string(ladder.TrancheStatusFired), string(ladder.TrancheStatusScheduled), ladderGraceCutoff(asOf)).Scan(&total) | ||
| if err != nil { | ||
| return 0, fmt.Errorf("in-flight ladder commit config_id=%s: %w", configID, err) | ||
| } | ||
| return total, nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Validate each tranche's
ConfigIDandRunIDagainst the locked config and the run.The code checks
run.ConfigIDagainstconfigIDbut does not check the tranches.insertLadderTranchesTxwritestr.ConfigIDexactly as the builder sets it. A builder bug can therefore insert tranches for a different config while only this config's ladder lock is held. That other config's planner and claim paths are then not serialized against this write, which bypasses the netting guarantee this PR adds. Reject any tranche whoseConfigIDis nil or differs fromconfigID. Also reject any tranche whose non-nilRunIDdiffers from the run ID.🛡️ Proposed guard
if run.ID == "" { run.ID = uuid.New().String() } + for i := range tranches { + if tranches[i].ConfigID == nil || *tranches[i].ConfigID != configID { + return fmt.Errorf("ladder tranche %d config_id does not match locked config %s", i, configID) + } + if tranches[i].RunID != nil && *tranches[i].RunID != run.ID { + return fmt.Errorf("ladder tranche %d run_id does not match run %s", i, run.ID) + } + } saved, err := insertLadderRunWithTranchesTx(ctx, tx, run, tranches)🤖 Prompt for AI Agents