Spaces:
Paused
Paused
fix: align protected seat rotation semantics
Browse filesFiles changed (6)
56 unmodified lines575859606162636451 unmodified lines11611711811912012112251 unmodified lines17417517617717817918018118250 unmodified lines23323423523623723823924056 unmodified lines- `cmd_check(include_standby=False, *, force_auth_repair=False, preserve_low_active=False, preserved_low_accounts=None) -> list`- `_historical_low_quota_info(acc, threshold, now=None) -> dict | None`- `_record_auth_repair_failure(email, error_type=None, error_detail=None, *, chatgpt_api=None) -> dict`- `_can_replace_protected_managed_auth_failure(acc, *, error_type=None, reason=None, missing_auth=False) -> bool`- `_should_aggressively_release_auth_failure(error_type, *, discard_failed_repair) -> bool`- `_discard_auth_repair_failed_account_record(email, reason, *, status=STATUS_STANDBY, now=None) -> None`- `cmd_rotate(target_seats=3, force_auth_repair=False, background_post_sync=False)`- `IPv6Pool.start(active_emails: Iterable[str] | None = None) -> None`51 unmodified lines- `_record_auth_repair_failure()` must preserve current state-machine semantics: final auth-pending state is persisted as `STATUS_AUTH_INVALID`, and status writes may include `_reason` for transition logging.- `_record_auth_repair_failure()` may release a Team blocker after repeated `email_verification` exhausts the retry budget, and may release missing-auth `login_state_lost` / organization-selection blockers when they occupy a Team seat.- Protected local credential seats (`protect_team_seat=True` or a non-provider local auth file) must not be released by `login_state_lost`; they should pause repair and stay in the current auth-pending state.- Protected AutoTeam-managed child seats with a mail binding (`mail_account_id` or `cloudmail_account_id`) are different from manual/local credential seats. If concrete auth-failure evidence exists (`auth_error_discard`, `missing_auth_file`, `auth_retry_paused`, `auth_retry_after`, `non_team_plan`, `oauth_timeout`, `login_failed`, etc.), `_can_replace_protected_managed_auth_failure()` may override stale protection flags so rotation can release/retire the child and restore capacity.- When an auth-repair failure successfully releases a Team seat and `ROTATE_SKIP_REUSE=true`, the local row should be retained for evidence but marked `disabled=True`, `reuse_disabled=True`, and `retired_reason="auth_repair_failed:<type>"` so automated standby reuse cannot select it.- When add-phone soft retry is disabled, current capacity-first behavior treats `add_phone` as a hard managed-child blocker that may release the Team seat. Do not migrate target's pause-without-release behavior unless the operator policy is explicitly changed.- Target assertions that require persisted `"auth_pending"` or exact `update_account(email, {"status": ...})` calls are incompatible with the current account-state lifecycle and are not migration requirements.51 unmodified lines| repeated `email_verification` exhausts auth-repair retry budget | Pause repair, release the Team seat when present, and retire/disable the released local row under skip-reuse mode || `login_state_lost` has no usable local auth file and blocks Team capacity | Pause repair, release the Team seat when present, and retire/disable the released local row under skip-reuse mode || `login_state_lost` has a protected local credential auth file | Pause repair without releasing the Team seat or disabling the row || `auth_error_discard` or another concrete auth failure hits a protected AutoTeam-managed child with a mail binding | Allow the protected replacement override, release the Team seat when present, and retire/disable the row under skip-reuse mode || `auth_retry_paused` / `auth_retry_after` is present on a protected AutoTeam-managed child | Treat it as a replaceable pool blocker; do not let stale `protect_team_seat` block rotation || the same auth-failure signal hits a protected manual/local credential row without mail binding | Preserve the seat; do not release or retire the row automatically || `collect_runtime_resource_snapshot()` unexpectedly raises inside `/api/status` | Return a status response with a diagnostic `runtime_resources.error`; do not raise a 500 || `/api/status?fast=true` is called while rotate/fill is running | Return account/resource snapshot without live quota probes and with bounded CLIProxy health metadata || background task calls `bump_task_progress("stage")` repeatedly | Update task heartbeat and append/refresh a bounded stage history |50 unmodified lines - selected target `test_signup_flow_profiles.py` assertions may be used for lightweight OAuth helper parity, split-code target waits, session-bundle extraction, and explicit browser-login result wrapping. Full-file target parity is not required when the only failures are the rejected old positional `SignupProfile` constructor shape. - selected target `test_manager_auth_repair.py` assertions may be used for `_login_codex_with_result()` result-wrapper parity, `cmd_check(...force_auth_repair...)`, historical-low-quota network-error handling, and protected/released Team blocker behavior. Full-file target parity is not required while remaining failures describe target-only `"auth_pending"` persisted literals, exact `update_account()` call shape, or the rejected add-phone retry-disabled no-release policy. - current `tests/unit/test_round12_s3_cherry_pick.py::TestCmdCheckAuthRepairEntry` and `::TestRecordAuthRepairFailure` must cover the adapted current behavior. - `tests/unit/test_round12_s3_cherry_pick.py::TestRecordAuthRepairFailure` must cover protected managed-child release and manual protected credential preservation. - `tests/unit/test_manager_rotate.py::test_replaceable_pool_blocker_reason_reports_concrete_evidence` must cover protected managed-child blocker classification and manual protected credential exclusion.- Status endpoint integration: `tests/unit/test_api_status.py` - fast status skips live quota probes and uses bounded CLIProxy health reads. - active tasks record progress history from `bump_task_progress()`.3449 unmodified lines345034513452345334533454345534563457345834593460346154 unmodified lines3516351735183519352035213522352335243525352635273528351735293530353135323449 unmodified lines 则直接返回 409,不启动后台任务(队列化拒绝,Solution C)。本地状态足够用,无需启动 Playwright 远程查询,避免给前端按错按钮带来额外开销。 """ from autoteam.manager import TEAM_SUB_ACCOUNT_HARD_CAP, _count_local_team_seat_accounts, cmd_fill from autoteam.manager import ( TEAM_SUB_ACCOUNT_HARD_CAP, _count_local_team_seat_accounts, _schedule_post_task_sync, cmd_fill, )
if params.leave_workspace: from autoteam.accounts import load_accounts54 unmodified lines # probe 异常按 spec §6.1 不阻塞 — M-T1 / M-T2 在 _run_post_register_oauth 兜底 pass
def _cmd_fill_api_task(target: int, *, leave_workspace: bool = False): if leave_workspace: return cmd_fill(target, leave_workspace=True) result = cmd_fill(target, leave_workspace=False, post_sync=False, print_status=False) _schedule_post_task_sync("[填充]") return result
command = "fill-personal" if params.leave_workspace else "fill" task = _start_task( command, cmd_fill, _cmd_fill_api_task, {"target": params.target, "leave_workspace": params.leave_workspace}, params.target, leave_workspace=params.leave_workspace,264 unmodified lines265266267268269270271272273274275276277278279280281282283284285286287288289290291155 unmodified lines447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492169 unmodified lines662663664604665666667668669670671265 unmodified lines93793893994094194294394494594694794894995095195228 unmodified lines98198298398498598698798898999099199299399491099599699799860 unmodified lines1059106010611062977106310641065106615 unmodified lines1082108310849991085108610871088108910908 unmodified lines1099110011011102110311041105264 unmodified lines "auth_error_discard", })AUTH_REPAIR_AGGRESSIVE_RELEASE_TYPES = frozenset( { "add_phone", "human_verification", "email_verification", "workspace_selection", "account_selection", "login_state_lost", "no_valid_organizations", "missing_auth_file", "auth_error_discard", "unsupported_region", "oauth_timeout", "site_unavailable", "token_exchange_failed", "non_team_plan", "auth_code_missing", "login_failed", "exception", })
def _chatgpt_session_ready(chatgpt_api) -> bool:155 unmodified lines return not _has_account_mail_binding(acc)
def _can_replace_protected_managed_auth_failure( acc: dict | None, *, error_type: str | None = None, reason: str | None = None, missing_auth: bool = False,) -> bool: """Allow AutoTeam-managed child seats to be evicted despite stale protection flags.""" acc = acc or {} if _is_main_account_email(acc.get("email")) or not _has_account_mail_binding(acc): return False signals = { str(value or "").strip() for value in ( error_type, reason, acc.get("auth_last_error"), "missing_auth_file" if missing_auth else None, ) if str(value or "").strip() } if acc.get("auth_retry_paused"): signals.add("auth_retry_paused") if acc.get("auth_retry_after"): signals.add("auth_retry_after") return bool( signals & ( AUTH_REPAIR_AGGRESSIVE_RELEASE_TYPES | AUTH_REPAIR_RELEASE_TEAM_BLOCKER_TYPES | { "auth_error", "auth_retry_paused", "auth_retry_after", "auth_retry_after_invalid", } ) )
def _is_auth_repair_pending_status(status: str | None) -> bool: """Accept current persisted auth-invalid alias and legacy target auth_pending literal.""" return status in {STATUS_AUTH_PENDING, "auth_pending"}169 unmodified lines acc = acc or {} if _is_main_account_email(acc.get("email")) or is_account_disabled(acc): return None if _is_protected_local_credential_seat(acc): if _is_protected_local_credential_seat(acc) and not _can_replace_protected_managed_auth_failure( acc, missing_auth=missing_auth, ): return None status = acc.get("status") if status == STATUS_EXHAUSTED:265 unmodified lines return None
def _should_aggressively_release_auth_failure(error_type: str | None, *, discard_failed_repair: bool) -> bool: """Return whether one-shot rotation should release a child seat for this login/link failure.""" if not discard_failed_repair: return False normalized = str(error_type or "").strip() if not normalized: normalized = "login_failed" return normalized in AUTH_REPAIR_AGGRESSIVE_RELEASE_TYPES
def _record_auth_repair_failure( email: str, error_type: str | None = None,28 unmodified lines except Exception: discard_failed_repair = True
if _should_aggressively_release_auth_failure(error_type, discard_failed_repair=discard_failed_repair): prev_count = int(acc.get("auth_retry_count") or 0) state = { "auth_retry_count": prev_count + 1, "auth_last_error": error_type, "auth_last_error_detail": error_detail, "auth_last_failed_at": now, "auth_retry_after": None, "auth_retry_paused": True, } release_team_seat = True if error_type == "add_phone" and _auth_repair_retry_add_phone_enabled(): elif error_type == "add_phone" and _auth_repair_retry_add_phone_enabled(): prev_count = int(acc.get("auth_retry_count") or 0) if acc.get("auth_last_error") == "add_phone" else 0 next_count = prev_count + 1 max_retries = _auth_repair_add_phone_max_retries()60 unmodified lines state["auth_retry_paused"] = True release_team_seat = True
protected_replacement_override = _can_replace_protected_managed_auth_failure(acc, error_type=error_type) if release_team_seat and protected_local_credential: if release_team_seat and protected_local_credential and not protected_replacement_override: logger.warning("[认证修复] 保留受保护的本地凭证席位: %s", email) release_team_seat = False
15 unmodified lines # 走 default_machine.transition 时映射到 AccountState.AUTH_PENDING. final_status = STATUS_STANDBY if seat_released or not is_team_member else STATUS_AUTH_INVALID update_account(email, status=final_status, _reason=f"auth_repair:{error_type}") if discard_failed_repair and seat_released and not protected_local_credential: if discard_failed_repair and final_status == STATUS_STANDBY and ( not protected_local_credential or protected_replacement_override ): _discard_auth_repair_failed_account_record( email, f"auth_repair_failed:{error_type}",8 unmodified lines "release_attempted": release_attempted, "remove_status": remove_status, "protected_local_credential": protected_local_credential, "protected_replacement_override": protected_replacement_override, }
766 unmodified lines767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809766 unmodified lines assert rotate_calls == [((3,), {"force_auth_repair": True, "background_post_sync": True})]
def test_post_fill_defers_sync_and_status_to_background(monkeypatch): started = [] fill_calls = [] sync_calls = []
def fake_start_task(command, func, params, *args, **kwargs): started.append((command, func, params, args, kwargs)) return {"task_id": "fill-task", "command": command, "params": params}
monkeypatch.setattr(api, "_start_task", fake_start_task) monkeypatch.setattr(api._pw_executor, "run", lambda fn: (True, "ok", {})) monkeypatch.setattr( "autoteam.manager.cmd_fill", lambda *args, **kwargs: fill_calls.append((args, kwargs)) or {"filled": True}, ) monkeypatch.setattr( "autoteam.manager._schedule_post_task_sync", lambda stage_label: sync_calls.append(stage_label), )
result = api.post_fill(api.TaskParams(target=3))
assert result["task_id"] == "fill-task" assert len(started) == 1 command, func, params, args, kwargs = started[0] assert command == "fill" assert params == {"target": 3, "leave_workspace": False} assert args == (3,) assert kwargs == {"leave_workspace": False}
assert func(3, leave_workspace=False) == {"filled": True} assert fill_calls == [ ((3,), {"leave_workspace": False, "post_sync": False, "print_status": False}) ] assert sync_calls == ["[填充]"]
def test_disable_and_enable_account_toggle_local_flag(tmp_path, monkeypatch): accounts_file = tmp_path / "accounts.json" monkeypatch.setattr(accounts, "ACCOUNTS_FILE", accounts_file)102 unmodified lines10310410510610610710810911011112 unmodified lines124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154102 unmodified lines ]
def test_replaceable_pool_blocker_reason_reports_concrete_evidence():def test_replaceable_pool_blocker_reason_reports_concrete_evidence(tmp_path): auth_file = tmp_path / "codex-auth.json" auth_file.write_text("{}", encoding="utf-8") assert ( manager._replaceable_pool_blocker_reason( {"email": "missing@example.com", "status": manager.STATUS_ACTIVE, "auth_file": ""}12 unmodified lines ) == "quota_exhausted" ) assert ( manager._replaceable_pool_blocker_reason( { "email": "managed-protected@example.com", "status": manager.STATUS_ACTIVE, "auth_file": str(auth_file), "mail_account_id": 1, "auth_retry_paused": True, "protect_team_seat": True, } ) == "auth_retry_paused" ) assert ( manager._replaceable_pool_blocker_reason( { "email": "manual-protected@example.com", "status": manager.STATUS_ACTIVE, "auth_file": str(auth_file), "auth_retry_paused": True, "protect_team_seat": True, } ) is None )
def test_create_new_account_uses_domain_auto_join_before_invite(monkeypatch):587 unmodified lines58858959059159259359442 unmodified lines63763863964064164264397 unmodified lines74174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978031 unmodified lines812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859587 unmodified lines ): """普通错误 → 衰退式 retry_after, paused=False, status=AUTH_INVALID(留 team)。""" # Account is in team → final_status should be AUTH_INVALID monkeypatch.setattr("autoteam.config.ROTATE_SKIP_REUSE", False) monkeypatch.setattr(manager_mod, "_is_email_in_team", lambda email: True)
result = manager_mod._record_auth_repair_failure(42 unmodified lines self, seeded_account, monkeypatch ): """add_phone (软重试开 + 未超限) → paused=False + retry_after.""" monkeypatch.setattr("autoteam.config.ROTATE_SKIP_REUSE", False) monkeypatch.setattr(manager_mod, "_is_email_in_team", lambda email: True) monkeypatch.setenv("AUTO_CHECK_RETRY_ADD_PHONE", "1") monkeypatch.setenv("AUTO_CHECK_ADD_PHONE_MAX_RETRIES", "3")97 unmodified lines assert acc["disabled"] is True assert acc["retired_reason"] == "auth_repair_failed:login_state_lost"
@pytest.mark.parametrize( "error_type", ["non_team_plan", "oauth_timeout", "auth_code_missing"], ) def test_aggressive_login_link_failures_release_child( self, seeded_account, monkeypatch, error_type ): """One-shot login/link failures should release managed child capacity under skip-reuse.""" monkeypatch.setattr("autoteam.config.ROTATE_SKIP_REUSE", True) monkeypatch.setattr(manager_mod, "_is_email_in_team", lambda email: True) monkeypatch.setattr(manager_mod.time, "time", lambda: 1_700_000_000) monkeypatch.setattr( manager_mod, "_release_auth_repair_team_seat", lambda email, **kw: "removed", )
result = manager_mod._record_auth_repair_failure( seeded_account, error_type=error_type, error_detail="login/link failure", )
assert result["auth_retry_count"] == 1 assert result["auth_retry_paused"] is True assert result["auth_retry_after"] is None assert result["release_attempted"] is True assert result["seat_released"] is True assert result["status"] == accounts_mod.STATUS_STANDBY acc = accounts_mod.find_account(accounts_mod.load_accounts(), seeded_account) assert acc["disabled"] is True assert acc["reuse_disabled"] is True assert acc["retired_reason"] == f"auth_repair_failed:{error_type}"
def test_login_state_lost_preserves_protected_local_credential( self, isolated_accounts, tmp_path, monkeypatch ):31 unmodified lines assert acc["disabled"] is False assert acc.get("retired_reason") is None
def test_auth_error_releases_protected_managed_child( self, isolated_accounts, tmp_path, monkeypatch ): """Managed child seats may be released even when stale protection flags remain.""" auth_file = tmp_path / "managed-seat.json" auth_file.write_text("{}", encoding="utf-8") accounts_mod.add_account("managed@example.com", "pwd") accounts_mod.update_account( "managed@example.com", status=accounts_mod.STATUS_ACTIVE, auth_file=str(auth_file), mail_account_id=123, protect_team_seat=True, ) monkeypatch.setattr("autoteam.config.ROTATE_SKIP_REUSE", True) monkeypatch.setattr(manager_mod, "_is_email_in_team", lambda email: True) monkeypatch.setattr(manager_mod.time, "time", lambda: 1_700_000_000) monkeypatch.setattr( manager_mod, "_release_auth_repair_team_seat", lambda email, **kw: "removed", )
result = manager_mod._record_auth_repair_failure( "managed@example.com", error_type="auth_error_discard", error_detail="token invalid", )
assert result["auth_retry_paused"] is True assert result["protected_local_credential"] is True assert result["protected_replacement_override"] is True assert result["release_attempted"] is True assert result["seat_released"] is True assert result["status"] == accounts_mod.STATUS_STANDBY acc = accounts_mod.find_account(accounts_mod.load_accounts(), "managed@example.com") assert acc["status"] == accounts_mod.STATUS_STANDBY assert acc["disabled"] is True assert acc["reuse_disabled"] is True assert acc["retired_at"] == 1_700_000_000 assert acc["retired_reason"] == "auth_repair_failed:auth_error_discard"
def test_failure_when_not_in_team_lands_standby( self, seeded_account, monkeypatch ):.trellis/spec/backend/runtime-docker-hardening.md+8
src/autoteam/api.py+14-2
src/autoteam/manager.py+93-4
tests/unit/test_api_status.py+37
tests/unit/test_manager_rotate.py+28-1
tests/unit/test_round12_s3_cherry_pick.py+78