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 .github/workflows/issue711-scheduler-contention.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ jobs:
run: |
set -euo pipefail
go test -race -tags=unit ./internal/service ./internal/repository \
-run '^(TestSchedulerPublicationLockRoundTripAndRollback|TestSchedulerSnapshotUsesLatestCompleteAccounts|TestSchedulerSnapshotIDRetryFiltersLatestMembership|TestSchedulerOutboxRetry)' \
-run '^(TestSchedulerPublicationLockRoundTripAndRollback|TestSchedulerPublicationDiagnostics|TestSchedulerSnapshotUsesLatestCompleteAccounts|TestSchedulerSnapshotIDRetryFiltersLatestMembership|TestSchedulerOutboxRetry)' \
-count=1 -v -timeout=5m 2>&1 | tee ../evidence/unit-green.log
! grep -Eq 'no tests to run|--- SKIP:' ../evidence/unit-green.log
- name: Real PostgreSQL and Redis behavioral RED or GREEN
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ docs/*
!docs/codex-credits.md
!docs/account-token-guard.md
!docs/priority-scheduling.md
!docs/scheduler-publication-contention.md
!docs/astra-account-scheduling.md
!docs/legal/
!docs/legal/*.md
Expand Down
67 changes: 64 additions & 3 deletions backend/internal/repository/account_codex_snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"slices"
"strconv"
"time"
Expand Down Expand Up @@ -174,16 +175,52 @@ func (r *accountRepository) UpdateCodexUsageSnapshot(ctx context.Context, id int
// delayed generic updates/rebuilds. The fresh read and Redis write are inside
// the lock; database CAS writes can proceed, but their publication waits and
// republishes the newest committed row before reporting success.
func (r *accountRepository) WithLatestSchedulerAccounts(ctx context.Context, ids []int64, publish func([]service.Account) error) error {
func (r *accountRepository) WithLatestSchedulerAccounts(ctx context.Context, ids []int64, publish func([]service.Account) error) (retErr error) {
if len(ids) == 0 {
return publish(nil)
}
started := time.Now()
phase := "begin"
var lockSQLDuration, readDuration, publishDuration time.Duration
var lockCompletedAt time.Time
var lockSQLAttempted, readAttempted, publishAttempted, ownsTransaction bool
lockCount := 0
defer func() {
elapsed := time.Since(started)
var postLockDuration time.Duration
if !lockCompletedAt.IsZero() {
postLockDuration = time.Since(lockCompletedAt)
}
level := slog.LevelDebug
if retErr != nil || elapsed >= time.Second {
level = slog.LevelWarn
}
failureKind := "none"
if retErr != nil {
failureKind = "error"
if errors.Is(retErr, context.DeadlineExceeded) {
failureKind = "deadline"
} else if errors.Is(retErr, context.Canceled) {
failureKind = "canceled"
}
}
// Durations include driver/network work; lock SQL time is not a direct
// measurement of PostgreSQL lock wait. Never log IDs, rows or raw errors.
slog.Log(ctx, level, "[Scheduler] account publication timing",
"phase", phase, "failure_kind", failureKind, "requested_count", len(ids), "lock_count", lockCount,
"owns_transaction", ownsTransaction, "elapsed_ms", elapsed.Milliseconds(),
"lock_sql_attempted", lockSQLAttempted, "lock_sql_ms", lockSQLDuration.Milliseconds(),
"lock_acquired", !lockCompletedAt.IsZero(), "post_lock_ms", postLockDuration.Milliseconds(),
"read_attempted", readAttempted, "read_ms", readDuration.Milliseconds(),
"publish_attempted", publishAttempted, "publish_ms", publishDuration.Milliseconds())
}()
tx, err := r.client.Tx(ctx)
if err != nil && !errors.Is(err, dbent.ErrTxStarted) {
return err
}
client := r.client
if tx != nil {
ownsTransaction = true
defer func() { _ = tx.Rollback() }()
client = tx.Client()
}
Expand All @@ -195,38 +232,62 @@ func (r *accountRepository) WithLatestSchedulerAccounts(ctx context.Context, ids
}
slices.Sort(keys)
keys = slices.Compact(keys)
lockCount = len(keys)
phase = "lock"
lockStarted := time.Now()
if len(keys) == 1 {
lockSQLAttempted = true
if _, err := client.ExecContext(ctx, "SELECT pg_advisory_xact_lock($1)", keys[0]); err != nil {
lockSQLDuration = time.Since(lockStarted)
return err
}
} else if len(keys) > 1 {
lockSQLAttempted = true
// Keep the account-level publication fence shared with single-account
// feedback, but acquire it in one database round trip. The ordered
// subquery feeds the volatile lock function in the same global order as
// before, including when two buckets overlap on only some accounts.
if _, err := client.ExecContext(ctx, `SELECT pg_advisory_xact_lock(lock_key)
FROM (SELECT unnest($1::bigint[]) AS lock_key ORDER BY lock_key) AS ordered_locks`, pq.Array(keys)); err != nil {
lockSQLDuration = time.Since(lockStarted)
return err
}
}
if lockSQLAttempted {
lockSQLDuration = time.Since(lockStarted)
lockCompletedAt = time.Now()
}
scoped := *r
scoped.client = client
scoped.sql = client
scoped.schedulerCache = nil
phase = "read"
readAttempted = true
readStarted := time.Now()
accounts, err := scoped.GetByIDs(ctx, ids)
readDuration = time.Since(readStarted)
if err != nil {
return err
}
values := make([]service.Account, 0, len(accounts))
for _, a := range accounts {
values = append(values, *a)
}
if err := publish(values); err != nil {
phase = "publish"
publishAttempted = true
publishStarted := time.Now()
err = publish(values)
publishDuration = time.Since(publishStarted)
if err != nil {
return err
}
if tx != nil {
return tx.Commit()
phase = "commit"
if err := tx.Commit(); err != nil {
return err
}
}
phase = "complete"
return nil
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
package repository

import (
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"testing"

"entgo.io/ent/dialect"
Expand All @@ -16,6 +19,88 @@ import (
"github.com/stretchr/testify/require"
)

// A failed publication must identify the stalled stage without exposing the
// account IDs or a driver/callback error that may contain sensitive row data.
func TestSchedulerPublicationDiagnostics(t *testing.T) {
for _, failure := range []string{"begin", "lock", "read", "publish", "complete"} {
t.Run(failure, func(t *testing.T) {
var output bytes.Buffer
previous := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(&output, &slog.HandlerOptions{Level: slog.LevelDebug})))
t.Cleanup(func() { slog.SetDefault(previous) })

db, mock, err := sqlmock.New()
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
repo := newAccountRepositoryWithSQL(client, db, nil)
privateError := errors.New("synthetic-private-token-and-driver-detail")
begin := mock.ExpectBegin()
if failure == "begin" {
begin.WillReturnError(privateError)
} else {
lock := mock.ExpectExec("SELECT pg_advisory_xact_lock\\(lock_key\\)")
if failure == "lock" {
lock.WillReturnError(context.DeadlineExceeded)
} else {
lock.WillReturnResult(sqlmock.NewResult(0, 2))
read := mock.ExpectQuery("SELECT .* FROM .*accounts")
if failure == "read" {
read.WillReturnError(privateError)
} else {
read.WillReturnRows(sqlmock.NewRows([]string{"id"}))
}
}
if failure == "complete" {
mock.ExpectCommit()
} else {
mock.ExpectRollback()
}
}
called := false
err = repo.WithLatestSchedulerAccounts(context.Background(), []int64{987654321012345, 876543210123456, 987654321012345}, func([]service.Account) error {
called = true
if failure == "publish" {
return privateError
}
return nil
})
if failure == "complete" {
require.NoError(t, err)
} else if failure == "lock" {
require.ErrorIs(t, err, context.DeadlineExceeded)
} else {
require.ErrorIs(t, err, privateError)
}
require.Equal(t, failure == "publish" || failure == "complete", called)
require.NoError(t, mock.ExpectationsWereMet())

var record map[string]any
require.NoError(t, json.Unmarshal(bytes.TrimSpace(output.Bytes()), &record))
require.Equal(t, "[Scheduler] account publication timing", record["msg"])
require.Equal(t, failure, record["phase"])
require.Equal(t, float64(3), record["requested_count"])
require.Equal(t, failure != "begin", record["owns_transaction"])
require.Equal(t, failure != "begin", record["lock_sql_attempted"])
require.Equal(t, failure != "begin" && failure != "lock", record["lock_acquired"])
require.Equal(t, failure == "publish" || failure == "complete", record["publish_attempted"])
if failure != "begin" {
require.Equal(t, float64(2), record["lock_count"], "counts must describe deduplicated lock keys")
}
if failure == "lock" {
require.Equal(t, "deadline", record["failure_kind"])
} else if failure == "complete" {
require.Equal(t, "none", record["failure_kind"])
} else {
require.Equal(t, "error", record["failure_kind"])
}
for _, secret := range []string{"987654321012345", "876543210123456", privateError.Error()} {
require.NotContains(t, output.String(), secret)
}
})
}
}

func TestSchedulerPublicationLockRoundTripAndRollback(t *testing.T) {
for _, failLock := range []bool{false, true} {
t.Run(map[bool]string{false: "publish", true: "lock_failure"}[failLock], func(t *testing.T) {
Expand Down
9 changes: 6 additions & 3 deletions backend/internal/service/scheduler_snapshot_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -1132,11 +1132,14 @@ func (s *SchedulerSnapshotService) rebuildBucketWithTokenPolicyAndQueryCache(
rebuildCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()

rebuildStarted := time.Now()
accounts, err := s.loadAccountsForRebuild(rebuildCtx, bucket, queries)
loadDuration := time.Since(rebuildStarted)
if err != nil {
logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] rebuild failed: bucket=%s reason=%s err=%v", bucket.String(), reason, err)
logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] rebuild failed: bucket=%s reason=%s load_ms=%d err=%v", bucket.String(), reason, loadDuration.Milliseconds(), err)
return err
}
publicationStarted := time.Now()
if err := s.setRebuildSnapshot(rebuildCtx, task, accounts, queries); err != nil {
if errors.Is(err, ErrSchedulerBucketRetired) || errors.Is(err, ErrSchedulerBucketWriteFenced) {
slog.Debug("[Scheduler] rebuild fenced", "bucket", bucket.String(), "reason", reason)
Expand All @@ -1145,10 +1148,10 @@ func (s *SchedulerSnapshotService) rebuildBucketWithTokenPolicyAndQueryCache(
}
return nil
}
logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] rebuild cache failed: bucket=%s reason=%s err=%v", bucket.String(), reason, err)
logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] rebuild cache failed: bucket=%s reason=%s size=%d load_ms=%d publish_ms=%d elapsed_ms=%d err=%v", bucket.String(), reason, len(accounts), loadDuration.Milliseconds(), time.Since(publicationStarted).Milliseconds(), time.Since(rebuildStarted).Milliseconds(), err)
return err
}
slog.Debug("[Scheduler] rebuild ok", "bucket", bucket.String(), "reason", reason, "size", len(accounts))
slog.Debug("[Scheduler] rebuild ok", "bucket", bucket.String(), "reason", reason, "size", len(accounts), "load_ms", loadDuration.Milliseconds(), "publish_ms", time.Since(publicationStarted).Milliseconds(), "elapsed_ms", time.Since(rebuildStarted).Milliseconds())
return nil
}

Expand Down
Loading
Loading