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
42 changes: 37 additions & 5 deletions .github/workflows/issue711-scheduler-contention.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ on:
- 'backend/internal/repository/account_scheduler_publication_unit_test.go'
- 'backend/internal/service/openai_codex_snapshot_contract.go'
- 'backend/internal/service/scheduler_snapshot_latest_accounts_test.go'
- 'backend/internal/service/scheduler_snapshot_service.go'
- 'backend/internal/service/scheduler_snapshot_retired_group_batch_test.go'
- 'backend/internal/integration/issue711/**'
- '.github/workflows/issue711-scheduler-contention.yml'

Expand All @@ -24,7 +26,7 @@ jobs:
strategy:
fail-fast: false
matrix:
mode: [green, red-locks, red-state]
mode: [green, red-locks, red-state, red-retirement]
services:
postgres:
image: postgres:18.1-alpine3.23
Expand Down Expand Up @@ -65,7 +67,8 @@ jobs:
mkdir -p evidence
git rev-parse HEAD | tee evidence/head.txt
test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD"
sha256sum backend/internal/integration/issue711/snapshot_contention_test.go > evidence/tests.sha256
sha256sum backend/internal/integration/issue711/snapshot_contention_test.go \
backend/internal/service/scheduler_snapshot_retired_group_batch_test.go > evidence/tests.sha256
go version | tee evidence/toolchain.txt
- name: Restore exact defective production blob in isolated RED job
if: matrix.mode != 'green'
Expand All @@ -75,14 +78,18 @@ jobs:
run: |
set -euo pipefail
baseline=7eb2e271acdc4b36d62f1b542b16b5abb5b1bb09
git fetch --no-tags --depth=1 origin "$baseline"
if [ "$MODE" = red-locks ]; then
target=backend/internal/repository/account_codex_snapshot.go
expected=4b0f4c612101ef6d83080e96ae205164ab164b1c
else
elif [ "$MODE" = red-state ]; then
target=backend/internal/service/openai_codex_snapshot_contract.go
expected=8029364741588ba7263ae581f1f22b4dc4315ff2
else
baseline=b677bb176ae66e67ed09919756c10f1b0ae2ac0f
target=backend/internal/service/scheduler_snapshot_service.go
expected=20f7505e699aaf8853da320f3d11ac182e69e2a7
fi
git fetch --no-tags --depth=1 origin "$baseline"
git show "$baseline:$target" > "$target"
test "$(git hash-object "$target")" = "$expected"
printf '%s %s %s\n' "$baseline" "$target" "$expected" | tee evidence/baseline.txt
Expand All @@ -94,10 +101,35 @@ jobs:
run: |
set -euo pipefail
go test -race -tags=unit ./internal/service ./internal/repository \
-run '^(TestSchedulerPublicationLockRoundTripAndRollback|TestSchedulerPublicationDiagnostics|TestSchedulerSnapshotUsesLatestCompleteAccounts|TestSchedulerSnapshotIDRetryFiltersLatestMembership|TestSchedulerOutboxRetry)' \
-run '^(TestSchedulerPublicationLockRoundTripAndRollback|TestSchedulerPublicationDiagnostics|TestSchedulerSnapshotUsesLatestCompleteAccounts|TestSchedulerSnapshotIDRetryFiltersLatestMembership|TestSchedulerOutboxRetry|TestSchedulerRetiredGroupBatch|TestSchedulerGroupLifecycle|TestSchedulerPrepareGroupLifecycle|TestSchedulerRebuildBatch|TestSchedulerBulkAccountEvent|TestSchedulerFullRebuild|TestSchedulerRebuildRetireAfterDBLoadFencesPublish)' \
-count=1 -v -timeout=5m 2>&1 | tee ../evidence/unit-green.log
! grep -Eq 'no tests to run|--- SKIP:' ../evidence/unit-green.log
for name in ReconcilesOnce RechecksNextCall DoesNotCacheFailure CapturesConcurrentReopen; do
grep -F -- "--- PASS: TestSchedulerRetiredGroupBatch$name" ../evidence/unit-green.log
done
- name: Retired-group behavioral RED against exact baseline
if: matrix.mode == 'red-retirement'
working-directory: backend
shell: bash
run: |
set -euo pipefail
set +e
go test -race -tags=unit ./internal/service \
-run '^TestSchedulerRetiredGroupBatchReconcilesOnce$' \
-count=1 -v -timeout=5m > ../evidence/retirement-red.log 2>&1
result=$?
set -e
cat ../evidence/retirement-red.log
printf '%s\n' "$result" > ../evidence/exit.txt
if grep -Eq '\[build failed\]|\[setup failed\]|undefined:|syntax error:|no tests to run|panic:|--- SKIP:|WARNING: DATA RACE|race detected during execution' ../evidence/retirement-red.log; then
echo 'Compilation, fixture errors, missing tests and skips are not behavioral evidence'
exit 1
fi
test "$result" -ne 0
grep -F -- '--- FAIL: TestSchedulerRetiredGroupBatchReconcilesOnce' ../evidence/retirement-red.log
grep -F -- 'retired group authority must be read once per bucket preparation' ../evidence/retirement-red.log
- name: Real PostgreSQL and Redis behavioral RED or GREEN
if: matrix.mode != 'red-retirement'
env:
MODE: ${{ matrix.mode }}
working-directory: backend
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//go:build unit

package service

import (
"context"
"errors"
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/stretchr/testify/require"
)

type retiredGroupBatchCache struct {
*groupLifecycleTestCache
beforeCapture func(SchedulerBucket)
deletedIDs []int64
}

func (c *retiredGroupBatchCache) CaptureBucketWriteToken(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) {
if c.beforeCapture != nil {
c.beforeCapture(bucket)
}
return c.groupLifecycleTestCache.CaptureBucketWriteToken(ctx, bucket)
}

func (c *retiredGroupBatchCache) DeleteAccount(_ context.Context, id int64) error {
c.deletedIDs = append(c.deletedIDs, id)
return nil
}

type retiredGroupBatchAccounts struct{ *groupLifecycleTestAccountRepo }

func (r *retiredGroupBatchAccounts) GetByID(context.Context, int64) (*Account, error) {
return nil, ErrAccountNotFound
}

func newRetiredGroupBatchFixture(t *testing.T, groupID int64) (*retiredGroupBatchCache, *groupLifecycleTestGroupRepo, *retiredGroupBatchAccounts, *SchedulerSnapshotService) {
t.Helper()
historical := SchedulerBucket{GroupID: groupID, Platform: "legacy", Mode: "obsolete"}
cache := &retiredGroupBatchCache{groupLifecycleTestCache: newGroupLifecycleTestCache(historical)}
for _, bucket := range schedulerCanonicalBuckets(groupID) {
// Seed retirement without counting a lifecycle reconciliation.
require.NoError(t, cache.retirementRaceCache.RetireBucket(context.Background(), bucket))
}
groups := &groupLifecycleTestGroupRepo{}
accounts := &retiredGroupBatchAccounts{groupLifecycleTestAccountRepo: &groupLifecycleTestAccountRepo{}}
svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard)
return cache, groups, accounts, svc
}

func TestSchedulerRetiredGroupBatchReconcilesOnce(t *testing.T) {
for _, state := range []string{"missing", "inactive"} {
for _, publication := range []string{"main", "retry"} {
t.Run(state+"/"+publication, func(t *testing.T) {
const groupID int64 = 711
cache, groups, accounts, svc := newRetiredGroupBatchFixture(t, groupID)
if state == "inactive" {
groups.set(&Group{ID: groupID, Status: StatusDisabled, Hydrated: true}, nil)
}
ctx := context.WithValue(context.Background(), schedulerOutboxStrictKey{}, true)
if publication == "retry" {
ctx = context.WithValue(context.Background(), schedulerOutboxRetryPublicationKey{}, true)
}
event := SchedulerOutboxEvent{EventType: SchedulerOutboxEventAccountChanged, AccountID: ptrInt64(101),
Payload: map[string]any{"group_ids": []any{groupID}}}

require.NoError(t, svc.handleOutboxEvent(ctx, event, make(map[batchSeenKey]struct{})))

require.Equal(t, 1, groups.callCount(), "retired group authority must be read once per bucket preparation")
acquires, releases, lists := cache.lifecycleCounts()
require.Equal(t, 1, acquires)
require.Equal(t, 1, releases)
require.Equal(t, 1, lists)
want := append(schedulerCanonicalBuckets(groupID), cache.listBuckets...)
require.ElementsMatch(t, want, cache.retiredBuckets(), "retire canonical and historical buckets exactly once")
captures, reopens := cache.captureAndReopenCounts()
require.Equal(t, schedulerCanonicalBucketCount(), captures, "every bucket must still capture its current epoch")
require.Zero(t, reopens)
require.Zero(t, accounts.callCount())
require.Equal(t, []int64{101}, cache.deletedIDs)
})
}
}
}

func TestSchedulerRetiredGroupBatchRechecksNextCall(t *testing.T) {
const groupID int64 = 712
cache, groups, accounts, svc := newRetiredGroupBatchFixture(t, groupID)
ctx := context.WithValue(context.Background(), schedulerOutboxStrictKey{}, true)
buckets := schedulerCanonicalBuckets(groupID)
require.NoError(t, svc.rebuildBuckets(ctx, buckets, "inactive"))
groups.set(&Group{ID: groupID, Status: StatusActive, Hydrated: true}, nil)

require.NoError(t, svc.rebuildBuckets(ctx, buckets, "active"))

require.Equal(t, 2, groups.callCount(), "completed retirement must not be cached across calls or events")
require.Len(t, cache.tokens(), len(buckets))
require.Positive(t, accounts.callCount())
for _, bucket := range buckets {
_, published := cache.counts(bucket)
require.Equal(t, 1, published, bucket.String())
}
}

func TestSchedulerRetiredGroupBatchDoesNotCacheFailure(t *testing.T) {
const groupID int64 = 713
cache, groups, _, svc := newRetiredGroupBatchFixture(t, groupID)
wantErr := errors.New("synthetic partial retirement failure")
cache.retireErr, cache.retireErrAt = wantErr, 1
ctx := context.WithValue(context.Background(), schedulerOutboxStrictKey{}, true)
buckets := schedulerCanonicalBuckets(groupID)[:2]

tasks, err := svc.prepareBucketWriteTasks(ctx, buckets)

require.ErrorIs(t, err, wantErr, "later success must not acknowledge an earlier failed reconciliation")
require.Empty(t, tasks)
require.Equal(t, 2, groups.callCount(), "failed lifecycle work must be retried for the next retired bucket")
acquires, releases, lists := cache.lifecycleCounts()
require.Equal(t, 2, acquires)
require.Equal(t, 2, releases)
require.Equal(t, 2, lists)
}

func TestSchedulerRetiredGroupBatchCapturesConcurrentReopen(t *testing.T) {
const groupID int64 = 714
cache, groups, _, svc := newRetiredGroupBatchFixture(t, groupID)
ctx := context.WithValue(context.Background(), schedulerOutboxStrictKey{}, true)
buckets := schedulerCanonicalBuckets(groupID)[:2]
cache.beforeCapture = func(bucket SchedulerBucket) {
if bucket == buckets[1] {
// A concurrent lifecycle owner reactivates this bucket after the
// first inactive decision, before its own epoch capture.
groups.set(&Group{ID: groupID, Status: StatusActive, Hydrated: true}, nil)
_, err := cache.retirementRaceCache.ReopenBucket(ctx, bucket)
require.NoError(t, err)
}
}

tasks, err := svc.prepareBucketWriteTasks(ctx, buckets)

require.NoError(t, err)
require.Len(t, tasks, 1, "successful captures must take precedence over a previous inactive decision")
require.Equal(t, buckets[1], tasks[0].bucket)
require.NoError(t, cache.SetSnapshot(ctx, tasks[0].bucket, tasks[0].token, nil))
// Retirement/reopening after capture must still fence the prepared token.
require.NoError(t, cache.retirementRaceCache.RetireBucket(ctx, buckets[1]))
_, err = cache.retirementRaceCache.ReopenBucket(ctx, buckets[1])
require.NoError(t, err)
require.ErrorIs(t, cache.SetSnapshot(ctx, tasks[0].bucket, tasks[0].token, nil), ErrSchedulerBucketWriteFenced)
require.Equal(t, 1, groups.callCount())
}
16 changes: 16 additions & 0 deletions backend/internal/service/scheduler_snapshot_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -1046,6 +1046,10 @@ func (s *SchedulerSnapshotService) prepareBucketWriteTasks(ctx context.Context,
return nil, ErrSchedulerCacheNotReady
}
tasks := make([]schedulerBucketWriteTask, 0, len(buckets))
// A successful inactive reconciliation already retires the entire group,
// including historical buckets. Reuse only that completed decision within
// this preparation; failures and active plans still follow the fresh path.
var retiredGroups map[int64]struct{}
var firstErr error
for _, bucket := range buckets {
token, err := s.cache.CaptureBucketWriteToken(ctx, bucket)
Expand All @@ -1054,13 +1058,25 @@ func (s *SchedulerSnapshotService) prepareBucketWriteTasks(ctx context.Context,
// A delayed account event can refer to a now-deleted group. Recheck
// authority under the existing lifecycle lease; do not reopen it
// from the event payload or retain an already-retired group forever.
// Capture above always takes precedence: a concurrent reopen can
// supply a current token even after this group's inactive decision.
if _, completed := retiredGroups[bucket.GroupID]; completed {
continue
}
plan, lifecycleErr := s.prepareGroupLifecycle(ctx, bucket.GroupID, nil)
if lifecycleErr != nil {
if firstErr == nil {
firstErr = lifecycleErr
}
continue
}
if !plan.active {
if retiredGroups == nil {
retiredGroups = make(map[int64]struct{})
}
retiredGroups[bucket.GroupID] = struct{}{}
continue
}
for _, task := range plan.tasks {
if task.bucket == bucket {
tasks = append(tasks, task)
Expand Down
35 changes: 32 additions & 3 deletions docs/scheduler-publication-contention.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

关联 [#711](https://github.com/ranxi2001/sub2api/issues/711)。分析基线为
`production@dc1e1b072faa53ec2e6f0925be39d5d024ec1687`。
本文前半部分说明本次新增的日志;后半部分是尚未实现的设计与验收门槛。
本次不修改锁粒度、Redis 发布位置或请求 fallback,不能据此关闭 #711。
本文包含已落地的分阶段日志与退休分组批次优化;后半部分是尚未实现的设计与验收门槛。
这些增量不修改账号锁粒度、Redis 发布位置或请求 fallback,不能据此关闭 #711。

## 当前一致性边界

Expand Down Expand Up @@ -48,6 +48,35 @@ bucket 重建沿用现有日志维度,并补充 `load_ms`、`publish_ms`、`el

本次未增加持久化指标或 retry 深度采集器,未采集线上耗时,不声称任何生产性能改善幅度。

## 退休分组:减少一次 bucket 准备内的重复协调

在 `production@b677bb176ae66e67ed09919756c10f1b0ae2ac0f`,严格 outbox
处理延迟到达的 `account_changed` 时,已删除账号会通过旧分组 ID 重建全部平台。
若该分组已经退休,`prepareBucketWriteTasks` 为每个退休 bucket 再次调用
`prepareGroupLifecycle`。每次都获取生命周期租约、fresh 查询分组、读取 bucket 注册表,
并退休全部 canonical 与已登记历史 bucket;同组 B 个退休 bucket 重复 B 轮。

现在仅在一次 `prepareBucketWriteTasks` 内记住**已成功完成**的 inactive/missing 协调。
相同分组后续仍然退休的 bucket 不再重复整组协调;该分组的权威读取、注册表读取和租约
获取由 B 次变为 1 次,全组退休由 B 轮变为 1 轮。这是源码调用次数的变化,未测量线上收益。

每个 bucket 仍先捕获当前 epoch,成功 capture 优先于之前的 inactive 判断,
并发 reopen 后仍可生成写任务;之后的 retire/reopen 仍由原 token fencing 拒绝旧写入。
失败(包括租约释放失败)不缓存,首个错误仍向上传递;active 协调不复用。
记录不跨调用、事件或 retry,后续调用重新读取权威状态。首次 inactive 判断之后发生的
状态变化继续由既有事件与全量对账处理,不新增 revision 或事件可靠性保证。

本增量进度(勾选表示源码/接线完成,不表示测试已执行):

- [x] 生产严格 outbox 路径复用同次准备内完成的 inactive/missing 整组退休。
- [x] 确定性回归源码覆盖 missing/inactive、主事件/retry、历史 bucket、失败后重试、下一调用激活、并发 reopen 与旧 token fencing。
- [x] 专项 CI 选择新回归与生命周期守卫,并新增固定旧 blob 的 expected-RED;原真实 PG18/双 Redis adapter 集成检查继续运行。
- [ ] 当前候选 SHA 的远端 GREEN、行为 RED 与真实 adapter 集成证据(本轮禁止本地动态验证,尚未发布)。

回归位于 `backend/internal/service/scheduler_snapshot_retired_group_batch_test.go`;
远端命令为 `go test -race -tags=unit ./internal/service -run '^TestSchedulerRetiredGroupBatch' -count=1 -v`。
此优化没有减少活跃大分组的全量成员重建,也没有实现真正的增量成员更新。

## 后续方案:账号 revision 与 Redis CAS(尚未实现)

### 1. 先建立可证明的账号修订号
Expand Down Expand Up @@ -98,7 +127,7 @@ usage 已有逐字段 observation version,要保留该语义。现有请求反

## #711 关闭验收

以下均为待完成条件,不能用本次日志单测或 #712 的历史 GREEN 替代:
以下均为待完成条件,不能用日志单测、退休分组批次优化或 #712 的历史 GREEN 替代:

- [ ] 明确单账号状态修订顺序、临时请求反馈、usage 逐字段版本和删除 tombstone 的契约。
- [ ] Redis 原子 CAS 对旧 revision、同版本冲突、硬删除、Redis 重启、TTL/清理和旧 writer 均 fail closed。
Expand Down
Loading