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
133 changes: 133 additions & 0 deletions .github/scripts/moderation-scope-preview.mjs

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions .github/workflows/issue805-owner-policy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,25 @@ jobs:
test ! -e "$omission_test"
echo "$omission_test test=candidate-only candidate=$candidate actual=absent reason=unavailable-unit-helpers" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
fi
# Account-scope tests require production symbols introduced after
# this baseline. Keep them in GREEN and their dedicated acceptance;
# omit only this unrelated feature from the disposable old-source RED.
while IFS= read -r target; do
candidate=$(git rev-parse "$EXPECTED_HEAD_SHA:$target")
rm -- "$target"
test ! -e "$target"
echo "$target test=candidate-only candidate=$candidate actual=absent reason=moderation-scope-not-in-baseline" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
done < <(git ls-files 'backend/internal/handler/moderation_upstream*_test.go')
# The shared WS fixture gained an optional moderation repository only
# in PR848; its pre-feature version preserves the Issue805 contract.
target=backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go
fixture_base=4189ed821d6e4308b2f5fc3791b73d2eb53cda8a
git fetch --no-tags --depth=1 origin "$fixture_base"
git show "$fixture_base:$target" > "$target"
expected=$(git rev-parse "$fixture_base:$target")
actual=$(git hash-object "$target")
test "$expected" = "$actual"
echo "$target test=pre-moderation-scope expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
# The selected regression and its shared harness must remain exact
# candidate blobs. The clean GREEN checkout retains all new tests.
for target in backend/internal/handler/openai_issue805_delivery_test.go backend/internal/handler/openai_issue805_owner_policy_test.go backend/internal/handler/openai_issue805_ws_test.go backend/internal/handler/openai_issue715_recovery_test.go; do
Expand Down
126 changes: 126 additions & 0 deletions .github/workflows/moderation-upstream-scope.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
name: Moderation upstream scope acceptance
on:
push:
branches: [feat/moderation-upstream-account-scope]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: moderation-upstream-scope-${{ github.ref }}
cancel-in-progress: false
jobs:
behavioral-red:
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Pinned original implementation with candidate regression
run: |
mkdir -p "$RUNNER_TEMP/moderation-scope"
git rev-parse HEAD > "$RUNNER_TEMP/moderation-scope/head.txt"
cp backend/internal/handler/moderation_upstream_scope_test.go "$RUNNER_TEMP/scope_test.go"
git checkout --detach 4189ed821
cp "$RUNNER_TEMP/scope_test.go" backend/internal/handler/moderation_upstream_scope_test.go
cd backend
set +e
go test ./internal/handler -run '^TestModerationUpstreamScopeUnselectedDoesNotAudit$' -count=1 -v > "$RUNNER_TEMP/moderation-scope/red.log" 2>&1
result=$?
set -e
cat "$RUNNER_TEMP/moderation-scope/red.log"
test "$result" -ne 0
if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|fatal error:|DATA RACE|signal:|segmentation fault' "$RUNNER_TEMP/moderation-scope/red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestModerationUpstreamScopeUnselectedDoesNotAudit' "$RUNNER_TEMP/moderation-scope/red.log"
grep -q 'unselected upstream account must make zero audit calls' "$RUNNER_TEMP/moderation-scope/red.log"
- uses: actions/upload-artifact@v7
if: always()
with:
name: moderation-scope-red-${{ github.sha }}
path: ${{ runner.temp }}/moderation-scope
ui-evidence:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: pnpm/action-setup@v6
with:
version: 9
- uses: actions/setup-node@v6
with:
node-version: '22'
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- run: pnpm --dir frontend install --frozen-lockfile
- name: Frontend integration and existing selector regressions
run: |
pnpm --dir frontend exec vitest run src/components/admin/moderation/__tests__/ModerationUpstreamAccountSelector.spec.ts src/components/admin/operations/__tests__/QualityAccountSelector.spec.ts src/views/admin/__tests__/RiskControlView.spec.ts src/components/common/__tests__/NewFeatureBadge.spec.ts
pnpm --dir frontend run build
- name: Isolated browser
run: |
npm install --prefix "$RUNNER_TEMP/scope-browser" --no-save --ignore-scripts playwright@1.56.1
node "$RUNNER_TEMP/scope-browser/node_modules/playwright/cli.js" install --with-deps chromium
- name: Render actual baseline settings
env:
EVIDENCE_DIR: ${{ runner.temp }}/moderation-scope-ui
SUB2API_PLAYWRIGHT_MODULE: ${{ runner.temp }}/scope-browser/node_modules/playwright/index.mjs
run: node .github/scripts/moderation-scope-preview.mjs
- uses: actions/upload-artifact@v7
if: always()
with:
name: moderation-scope-ui-${{ github.sha }}
path: ${{ runner.temp }}/moderation-scope-ui
backend-green:
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Selected upstream execution and admission regressions
run: |
mkdir -p "$RUNNER_TEMP/moderation-scope-green"
git rev-parse HEAD > "$RUNNER_TEMP/moderation-scope-green/head.txt"
set -o pipefail
cd backend
go test -race -tags=unit ./internal/handler ./internal/handler/admin ./internal/service ./internal/securityaudit -run 'TestModerationUpstream|TestOpenAIResponsesWebSocket_ContentModeration|Test.*SecurityAudit|Test.*Queue.*Auth|Test.*Turn.*Admission|TestCoordinator|TestAPIKeyAdmissionRealForwardingHandlersRejectBeforeUpstream|TestOpenAIWSRevalidationFollowup|TestOpenAIWSRevalidationNativeImagePermissionTiming' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/moderation-scope-green/green.log"
if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|fatal error:|DATA RACE|signal:|segmentation fault' "$RUNNER_TEMP/moderation-scope-green/green.log"; then exit 1; fi
for name in TestModerationUpstreamScopeUnselectedDoesNotAudit TestModerationUpstreamHTTPSelectionAndFailover TestModerationUpstreamWebSocketModesAndTurns TestModerationUpstreamPersistenceAndValidation TestModerationUpstreamAdminSaveReloadAndAuthorization TestModerationUpstreamWebSocketTurnIdentityAfterFailover TestModerationUpstreamImagesJSONKeepaliveAndAsync TestModerationUpstreamSystemOneLocalDenial TestModerationUpstreamHTTPDispatchFamilies TestModerationUpstreamWebSocketCurrentAliasControlsScope TestModerationUpstreamEligibility TestModerationUpstreamAccountCatalogEligibility; do
grep -q -- "--- PASS: $name" "$RUNNER_TEMP/moderation-scope-green/green.log"
done
- uses: actions/upload-artifact@v7
if: always()
with:
name: moderation-scope-green-${{ github.sha }}
path: ${{ runner.temp }}/moderation-scope-green
postgres-persistence:
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Authenticated handler and real PostgreSQL persistence
run: |
mkdir -p "$RUNNER_TEMP/moderation-scope-postgres"
git rev-parse HEAD > "$RUNNER_TEMP/moderation-scope-postgres/head.txt"
set -o pipefail
cd backend
go test -tags=integration ./internal/repository -run '^TestModerationUpstreamPostgresAdminRoundTrip$' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/moderation-scope-postgres/postgres.log"
if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|fatal error:|DATA RACE|signal:|segmentation fault' "$RUNNER_TEMP/moderation-scope-postgres/postgres.log"; then exit 1; fi
grep -q -- '--- PASS: TestModerationUpstreamPostgresAdminRoundTrip' "$RUNNER_TEMP/moderation-scope-postgres/postgres.log"
- uses: actions/upload-artifact@v7
if: always()
with:
name: moderation-scope-postgres-${{ github.sha }}
path: ${{ runner.temp }}/moderation-scope-postgres
2 changes: 1 addition & 1 deletion backend/cmd/server/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 22 additions & 17 deletions backend/internal/handler/admin/account_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ type CheckMixedChannelRequest struct {

// AccountWithConcurrency extends Account with real-time concurrency info
type AccountWithConcurrency struct {
ModerationScopeEligible bool `json:"moderation_scope_eligible"`
*dto.Account
simpleMode bool `json:"-"`
CurrentConcurrency int `json:"current_concurrency"`
Expand All @@ -242,6 +243,7 @@ type AccountWithConcurrency struct {
// for lite=1. It embeds dto.AccountListItem instead of the full dto.Account,
// so groups/account_groups never appear in the list payload.
type AccountListItemWithConcurrency struct {
ModerationScopeEligible bool `json:"moderation_scope_eligible"`
*dto.AccountListItem
CurrentConcurrency int `json:"current_concurrency"`
SchedulerScore *AccountSchedulerScore `json:"scheduler_score,omitempty"`
Expand Down Expand Up @@ -412,9 +414,10 @@ func (h *AccountHandler) isSimpleMode() bool {

func (h *AccountHandler) buildAccountResponseWithRuntime(ctx context.Context, account *service.Account) AccountWithConcurrency {
item := AccountWithConcurrency{
Account: dto.AccountForObserver(ctx, h.accountResponseFromService(account)),
simpleMode: h.isSimpleMode(),
CurrentConcurrency: 0,
Account: dto.AccountForObserver(ctx, h.accountResponseFromService(account)),
ModerationScopeEligible: service.ModerationUpstreamAccountEligible(account),
simpleMode: h.isSimpleMode(),
CurrentConcurrency: 0,
}
if account == nil {
return item
Expand Down Expand Up @@ -878,11 +881,12 @@ func (h *AccountHandler) List(c *gin.Context) {
}
}
item := AccountWithConcurrency{
Account: accountResponse,
simpleMode: h.isSimpleMode(),
CurrentConcurrency: concurrencyCounts[acc.ID],
SchedulerScore: schedulerScores[acc.ID],
SchedulerScores: schedulerGroupScores[acc.ID],
Account: accountResponse,
ModerationScopeEligible: service.ModerationUpstreamAccountEligible(acc),
simpleMode: h.isSimpleMode(),
CurrentConcurrency: concurrencyCounts[acc.ID],
SchedulerScore: schedulerScores[acc.ID],
SchedulerScores: schedulerGroupScores[acc.ID],
}

// 添加窗口费用(仅当启用时)
Expand Down Expand Up @@ -929,15 +933,16 @@ func (h *AccountHandler) List(c *gin.Context) {
for i := range result {
item := result[i]
compact[i] = AccountListItemWithConcurrency{
AccountListItem: dto.AccountListItemFromAccount(item.Account),
CurrentConcurrency: item.CurrentConcurrency,
SchedulerScore: item.SchedulerScore,
SchedulerScores: item.SchedulerScores,
CurrentWindowCost: item.CurrentWindowCost,
ActiveSessions: item.ActiveSessions,
CurrentRPM: item.CurrentRPM,
RPMPaused: item.RPMPaused,
RPMResetAt: item.RPMResetAt,
AccountListItem: dto.AccountListItemFromAccount(item.Account),
ModerationScopeEligible: item.ModerationScopeEligible,
CurrentConcurrency: item.CurrentConcurrency,
SchedulerScore: item.SchedulerScore,
SchedulerScores: item.SchedulerScores,
CurrentWindowCost: item.CurrentWindowCost,
ActiveSessions: item.ActiveSessions,
CurrentRPM: item.CurrentRPM,
RPMPaused: item.RPMPaused,
RPMResetAt: item.RPMResetAt,
}
}
etag := buildAccountsListETag(compact, total, page, pageSize, platform, accountType, status, search, true)
Expand Down
23 changes: 23 additions & 0 deletions backend/internal/handler/admin/account_handler_list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,26 @@ func TestAccountHandlerListSchedulerScoreIgnoresPagination(t *testing.T) {
require.Less(t, payload.Data.Items[0].SchedulerScore.BaseScore, 3.75)
require.Empty(t, payload.Data.Items[0].SchedulerScores)
}

func TestModerationUpstreamAccountCatalogEligibility(t *testing.T) {
router, adminSvc := setupAccountListRouter()
adminSvc.accounts = []service.Account{
{ID: 801, Name: "Vertex fixture", Platform: service.PlatformAnthropic, Type: service.AccountTypeServiceAccount, Credentials: map[string]any{}},
{ID: 802, Name: "Unsupported fixture", Platform: service.PlatformTypeSafe, Type: service.AccountTypeOAuth, Credentials: map[string]any{}},
}
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?lite=1", nil))
require.Equal(t, 200, w.Code)
var got struct {
Data struct {
Items []struct {
ID int64 `json:"id"`
Eligible bool `json:"moderation_scope_eligible"`
} `json:"items"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &got))
require.Len(t, got.Data.Items, 2)
require.True(t, got.Data.Items[0].Eligible)
require.False(t, got.Data.Items[1].Eligible)
}
15 changes: 9 additions & 6 deletions backend/internal/handler/admin/content_moderation_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@ func NewContentModerationHandlerWithSafetyPrompt(svc *service.ContentModerationS
}

type contentModerationConfigRequest struct {
Engine *string `json:"engine"`
EngineConfigs map[string]service.UpdateContentModerationEngineInput `json:"engine_configs"`
Enabled *bool `json:"enabled"`
Mode *string `json:"mode"`
BaseURL *string `json:"base_url"`
Model *string `json:"model"`
UpstreamAccountScope *string `json:"upstream_account_scope"`
UpstreamAccountIDs *[]int64 `json:"upstream_account_ids"`
Engine *string `json:"engine"`
EngineConfigs map[string]service.UpdateContentModerationEngineInput `json:"engine_configs"`
Enabled *bool `json:"enabled"`
Mode *string `json:"mode"`
BaseURL *string `json:"base_url"`
Model *string `json:"model"`
// 审计请求使用的代理服务器:null 不修改;0 清除(直连);>0 指定代理。
ProxyID *int64 `json:"proxy_id"`
APIKey *string `json:"api_key"`
Expand Down Expand Up @@ -102,6 +104,7 @@ func (h *ContentModerationHandler) UpdateConfig(c *gin.Context) {
}
cfg, err := h.service.UpdateConfig(c.Request.Context(), service.UpdateContentModerationConfigInput{
Engine: req.Engine, EngineConfigs: req.EngineConfigs,
UpstreamAccountScope: req.UpstreamAccountScope, UpstreamAccountIDs: req.UpstreamAccountIDs,
Enabled: req.Enabled,
Mode: req.Mode,
BaseURL: req.BaseURL,
Expand Down
Loading
Loading