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
19 changes: 18 additions & 1 deletion backend/crates/providers/openai/src/credential/selector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,15 @@ impl CodexCredentialSelector {
only_account,
)
.await?;
let image_primary = binding
.as_ref()
.filter(|_| {
matches!(model, CodexSelectionModel::Image(_))
&& affinity_mode == AccountAffinity::Strict
&& pinned_account.is_none()
})
.map(ProviderSessionBinding::account_id)
.filter(|id| accounts.iter().any(|account| account.id() == *id));
let mut model_access_rejected = 0_usize;
let accounts = accounts
.into_iter()
Expand Down Expand Up @@ -1030,6 +1039,14 @@ impl CodexCredentialSelector {
.iter()
.map(|account| account.id().clone())
.collect::<Vec<_>>();
// 主账号在授权池内,但未通过 Images 的模型、套餐或协议筛选时,只为本次图片借号
let image_primary_to_keep = image_primary.filter(|id| !account_ids.contains(id));
if image_primary_to_keep.is_some() && queued_account.is_some() {
// 排队期间主账号的资格可能变化,先恢复完整候选再找可用的生图账号
refresh_candidates = true;
continue 'capacity;
}
let follow_only = follow_only && image_primary_to_keep.is_none();
let rate_limits = if diagnostic {
HashMap::new()
} else {
Expand Down Expand Up @@ -1508,7 +1525,7 @@ impl CodexCredentialSelector {
}
ProviderLeaseAcquisition::Acquired(guard) => guard,
};
let mut binding_account = account.id();
let mut binding_account = image_primary_to_keep.unwrap_or(account.id());
if affinity_mode == AccountAffinity::Preferred
&& let Some(primary) = binding.as_ref()
&& (primary.account_id() == account.id()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,104 @@ async fn image_model_access_overrides_existing_session_affinity() {
}
}

#[tokio::test]
async fn strict_session_images_borrow_within_group_and_account_model_access() {
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};

const TEXT_ONLY: &str = "acct_text_only";
let chat = AccountGroupId::new("grp_00000000000000000000000000000001").unwrap();
let mixed = AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
let openai = ProviderKind::new("openai").unwrap();
let deny_image = policy(AccountModelAccessMode::Denylist, "gpt-image-2");
let accounts = [
(CPA_ACCOUNT, &chat, AccountModelAccess::all()),
(TEXT_ONLY, &mixed, deny_image.clone()),
(IMAGE_ACCOUNT, &mixed, AccountModelAccess::all()),
]
.map(|(id, group, access)| {
(
ProviderAccountId::new(id).unwrap(),
RuntimeAccount::new(openai.clone(), [group.clone()].into()).with_model_access(access),
)
});
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(
RuntimeAccountDirectory::new(accounts.into())
.with_group_model_access([(chat.clone(), deny_image)].into()),
),
ClientRoutingScope::restricted(
vec![
RoutingGroupSnapshot::new(chat.clone(), "Chat".into()),
RoutingGroupSnapshot::new(mixed.clone(), "Mixed".into()),
],
[chat, mixed].into(),
[openai].into(),
)
.unwrap(),
));
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/codex/responses"))
.and(header(
"chatgpt-account-id",
format!("chatgpt-{CPA_ACCOUNT}"),
))
.respond_with(
ResponseTemplate::new(200).set_body_raw(CAPTURE_COMPLETED_SSE, "text/event-stream"),
)
.expect(3)
.mount(&server)
.await;
for endpoint in ["/codex/images/generations", "/codex/images/edits"] {
Mock::given(method("POST"))
.and(path(endpoint))
.and(header(
"chatgpt-account-id",
format!("chatgpt-{IMAGE_ACCOUNT}"),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"data":[]})))
.expect(1)
.mount(&server)
.await;
}
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, CPA_ACCOUNT).await;
let provider = provider_with_base_url(&store, server.uri());
let send = async |request| {
let mut stream = provider
.clone()
.execute(
request,
attempt(
AccountAttemptContext::new(BTreeSet::new(), None, None)
.with_account_scope(scope.clone()),
),
)
.await
.unwrap();
while let Some(event) = stream.next().await {
event.unwrap();
}
};
let text = |turn| planned_request("openai", super::session_binding::turn_request("root", turn));
send(text("first")).await;
create_account(&store, TEXT_ONLY).await;
create_account(&store, IMAGE_ACCOUNT).await;
store.set_scheduling(TEXT_ONLY, None, AccountWeight::new(100).unwrap());
let generation = image_operation(
ImageRequestKind::Generation,
br#"{"session_id":"root","model":"gpt-image-2","prompt":"draw"}"#,
);
let edit = image_operation(
ImageRequestKind::Edit,
br#"{"session_id":"root","thread_id":"child","model":"gpt-image-2","prompt":"edit"}"#,
);
for (image, next_turn) in [(generation, "after-generation"), (edit, "after-edit")] {
send(planned_provider_endpoint_request("openai", image)).await;
send(text(next_turn)).await;
}
}

#[tokio::test]
async fn final_image_model_after_middleware_must_be_allowed_by_the_selected_account() {
let server = MockServer::start().await;
Expand Down
7 changes: 5 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,9 @@ Messages 费用按管理员显式配置的模型价格计算,未配置时保
Images 使用原生非流式 JSON 端点,JSON 请求与响应正文原样转发。
`/v1/images/edits` 还接受 `multipart/form-data`,将上传转换为原生 Images JSON 请求

Key 允许生图时,已绑定分组的 Key 只使用允许该图片模型的启用分组成员。账号自身的模型黑白名单进一步收窄可选范围。
采用严格或优先亲和时优先使用会话主账号。主账号在授权池内但模型权限、套餐或上游协议不支持本次生图时,可以临时借用合格账号,后续聊天仍沿用原绑定

multipart 的 `image` 和 `image[]` 上传按出现顺序组成 `images` 数组,每项为
`{"image_url":"data:image/...;base64,..."}`;`mask` 上传转换为同结构的单个对象。
图片支持 PNG、JPEG、WebP,根据内容识别格式,原始文件字节直接编码,不缩放或重新编码
Expand Down Expand Up @@ -2169,7 +2172,7 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范

严格亲和下的后代线程始终启用账号排队,沿用 `accountQueueTimeoutSeconds` 和请求截止时间;
`maxWaitingPerAccount` 为 0 时使用每队列 1,000 人上限,否则沿用配置的上限。
可识别来源的 Search、Images、Live 创建请求采用同样规则,身份与轮次关联见[会话绑定](architecture.md#6-路由账号范围与-continuation)。
可识别来源的 Search、Images、Live 创建请求共用会话绑定。主账号缺少本次生图资格时,后代可按 [Images 请求](#images-请求)规则借号。身份与轮次关联见[会话绑定](architecture.md#6-路由账号范围与-continuation)。
插件显式选号须通过账号资格与租约检查,见[调度合同](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#路由调度与观察)。普通请求关闭账号排队且没有可用容量时返回 `503` / `account_capacity_unavailable`,
与无候选账号的 `no_available_provider` 区分;排队不绕过账号范围、模型权限、RPM 或金额限额

Expand Down Expand Up @@ -2392,7 +2395,7 @@ Guardian 以 `subagent_kind` 或 `client_metadata.x-openai-subagent` 值 `guardi
主账号被删除、停用或凭据过期、失效、封禁时,在后备账号成功准入时原子迁移绑定
额度耗尽且重置时间未知或距离当前时刻超过账号排队时限时迁移,接近重置时保留主绑定,并给刚过重置时间的额度复核同长度宽限
原生续接仍固定其状态归属账号
- `strict`(严格):同一会话共用账号,后代请求等待当前账号并跟随根请求换号
- `strict`(严格):同一会话共用账号,后代请求等待当前账号并跟随根请求换号;[原生 Images](#images-请求) 可按生图资格临时借号

插件显式选号及原生续写的状态归属约束在三种模式下仍然生效

Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,7 @@ OpenAI Provider 解释官方逻辑 `session_id` 与 `thread_id`,按 Client Key
- 严格:根线程及后代共享当前账号;绑定缺失时任意会话请求均可按调度策略首次认领,
已有绑定的后代只跟随当前账号,账号不可用时排队,根迁移后重读共享绑定

可关联的 Search、Images、Live 创建请求共用会话绑定,宽松和优先模式不依赖线程身份分流;严格模式下后代请求保留跟随约束。
可关联的 Search、Images、Live 创建请求共用会话绑定。严格模式下,授权池内的主账号未通过原生 Images 的模型、套餐或协议筛选时,根线程和后代均可从合格账号中借号。取得生图账号租约后,按选号时读到的主绑定原子续期;绑定已变化则重新选号。主账号具备生图资格但繁忙时,后代仍跟随主账号排队
内置 `round_robin` 在最高可调度权重层按账号 ID 轮换。游标按 Client Key 和 Provider 隔离,在取得租约后推进;有会话绑定时,两者原子提交。并发首绑只占一个位置,亲和命中和插件显式选号不推进游标。插件委托仍走内置轮询,优先模式已有绑定时沿用会话派生的后备顺序
插件显式选号由 Core 复核账号资格并取得租约,native continuation 受独立的状态 owner 与安全重放边界约束

Expand Down