Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): offer the open-weights models to everyone (#100970)

Alessandro Pogliaghib67221912ad9
diff --git a/.claude/rules/task-model-catalog.md b/.claude/rules/task-model-catalog.md
index d96b99922f9d..3a8ff7ad2b22 100644
--- a/.claude/rules/task-model-catalog.md
+++ b/.claude/rules/task-model-catalog.md
@@ -17,5 +17,7 @@ A test re-renders both and compares them byte for byte, so an edit that the gene
Adding a model means one row in `MODELS`. Two things do not follow from that row and are worth checking:
-- A model gated behind a feature flag also needs an entry in `MODEL_ACCESS_FLAGS` (`products/tasks/backend/constants.py`), which is where the server re-checks entitlement. A picker hiding a model is a convenience, not a gate.
+- A model gated behind a feature flag carries the flag in its `access_flag`, which every picker and the server's entitlement check read.
+ The LLM gateway keeps its own copy in `MODEL_ACCESS_FLAGS` (`services/llm-gateway/src/llm_gateway/products/config.py`), because it also serves callers outside this repo.
+ Clear both when the rollout reaches everyone: each gate fails closed, so a flag left behind hides the model from anyone the flag service cannot answer for.
- The catalog names the harness that drives a model. The LLM gateway reports `owned_by`, which names whoever serves it — `cloudflare` and `baseten` for the vendor-served models — so routing a model by its owner puts it on the wrong adapter or drops it entirely.
diff --git a/products/desktop/apps/mobile/src/app/task/[id].tsx b/products/desktop/apps/mobile/src/app/task/[id].tsx
index b49876bc4386..623b02536d1d 100644
--- a/products/desktop/apps/mobile/src/app/task/[id].tsx
+++ b/products/desktop/apps/mobile/src/app/task/[id].tsx
@@ -13,9 +13,7 @@ import {
DEFAULT_GATEWAY_MODEL,
DEFAULT_REASONING_EFFORT,
type ExecutionMode,
- isModalModelId,
isSupportedReasoningEffort,
- KIMI_MODEL_FLAG,
readPrUrls,
type SupportedReasoningEffort,
serializeCloudPrompt,
@@ -25,7 +23,6 @@ import { useQueryClient } from "@tanstack/react-query";
import * as Haptics from "expo-haptics";
import { useLocalSearchParams, useRouter } from "expo-router";
import { UserSwitch } from "phosphor-react-native";
-import { useFeatureFlag } from "posthog-react-native";
import { useCallback, useEffect, useRef, useState } from "react";
import {
ActivityIndicator,
@@ -194,18 +191,11 @@ export default function TaskDetailScreen() {
const composerMode: ExecutionMode =
(composerConfigMatchesAdapter ? composerConfig?.mode : undefined) ??
getDefaultExecutionModeForAdapter(composerAdapter);
- const kimiEnabled = !!useFeatureFlag(KIMI_MODEL_FLAG);
- const persistedComposerModel =
+ // The composer independently re-resolves this against the live config once mounted.
+ const composerModel =
(composerConfigMatchesAdapter ? composerConfig?.model : undefined) ??
task?.latest_run?.model ??
(composerAdapter === "codex" ? DEFAULT_CODEX_MODEL : DEFAULT_GATEWAY_MODEL);
- // Fall a persisted Kimi selection back to the default when the flag is off so
- // a hidden model never gets sent on the retry-after-terminal path. The
- // composer independently re-resolves against the live config once mounted.
- const composerModel =
- !kimiEnabled && isModalModelId(persistedComposerModel)
- ? DEFAULT_GATEWAY_MODEL
- : persistedComposerModel;
const requestedComposerReasoning = composerConfigMatchesAdapter
? composerConfig?.reasoning
: undefined;
diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.test.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.test.ts
index 1f702398b55c..82b02ac41710 100644
--- a/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.test.ts
+++ b/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.test.ts
@@ -1,24 +1,12 @@
-import {
- DEFAULT_GATEWAY_MODEL,
- type GatewayModel,
- GLM53_FLASH_MODEL_FLAG,
- GLM53_MODEL_FLAG,
- KIMI_MODEL_FLAG,
-} from "@posthog/shared";
+import { DEFAULT_GATEWAY_MODEL, type GatewayModel } from "@posthog/shared";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createElement, type PropsWithChildren } from "react";
import { act, create } from "react-test-renderer";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const { mockGetCloudTaskGatewayModels, mockUseAuthStore, mockUseFeatureFlag } =
- vi.hoisted(() => ({
- mockGetCloudTaskGatewayModels: vi.fn(),
- mockUseAuthStore: vi.fn(),
- mockUseFeatureFlag: vi.fn(),
- }));
-
-vi.mock("posthog-react-native", () => ({
- useFeatureFlag: mockUseFeatureFlag,
+const { mockGetCloudTaskGatewayModels, mockUseAuthStore } = vi.hoisted(() => ({
+ mockGetCloudTaskGatewayModels: vi.fn(),
+ mockUseAuthStore: vi.fn(),
}));
vi.mock("@/features/auth", () => ({
@@ -111,8 +99,6 @@ function gatewayModel(
describe("useCloudTaskConfigOptions", () => {
beforeEach(() => {
mockGetCloudTaskGatewayModels.mockReset();
- mockUseFeatureFlag.mockReset();
- mockUseFeatureFlag.mockReturnValue(false);
mockUseAuthStore.mockImplementation((selector) =>
selector({ oauthAccessToken: "token" }),
);
@@ -153,43 +139,23 @@ describe("useCloudTaskConfigOptions", () => {
});
});
- it("replaces a hidden GLM current model with a visible model", async () => {
- mockGetCloudTaskGatewayModels.mockResolvedValue([
- gatewayModel("zai-org/glm-5.3"),
- gatewayModel("claude-sonnet-5"),
- ]);
-
- const result = await renderHook("claude");
- await waitForAssertion(() => {
- const modelOption = getModelConfigOption(result.current.configOptions);
- expect(modelOption.options.map((option) => option.value)).toEqual([
- "claude-sonnet-5",
- ]);
- // Cross-harness groups drop the empty Z.ai group along with its heading.
- expect(result.current.modelGroups.map((g) => g.group)).not.toContain(
- "zai-org",
- );
- });
- });
-
+ // The gateway serves these to everyone, and a second gate in this app used to hide them.
it.each([
- { enabledFlag: GLM53_MODEL_FLAG, model: "zai-org/glm-5.3" },
- { enabledFlag: GLM53_FLASH_MODEL_FLAG, model: "zai-org/glm-5.3-flash" },
- ])("gates $model independently", async ({ enabledFlag, model }) => {
- mockUseFeatureFlag.mockImplementation(
- (flag: string) => flag === enabledFlag,
- );
+ { model: "zai-org/glm-5.3" },
+ { model: "zai-org/glm-5.3-flash" },
+ { model: "deepseek-ai/deepseek-v4-flash-0731" },
+ ])("offers a served $model", async ({ model }) => {
mockGetCloudTaskGatewayModels.mockResolvedValue([
- gatewayModel("zai-org/glm-5.3"),
- gatewayModel("zai-org/glm-5.3-flash"),
+ gatewayModel(model),
+ gatewayModel("claude-sonnet-5"),
]);
const result = await renderHook("claude");
await waitForAssertion(() => {
const modelOption = getModelConfigOption(result.current.configOptions);
- expect(modelOption.options.map((option) => option.value)).toEqual([
+ expect(modelOption.options.map((option) => option.value)).toContain(
model,
- ]);
+ );
});
});
@@ -226,31 +192,17 @@ describe("useCloudTaskConfigOptions", () => {
});
});
- it("hides Kimi K3 when its flag is off and keeps it when on", async () => {
+ it("offers a served Kimi K3", async () => {
mockGetCloudTaskGatewayModels.mockResolvedValue([
gatewayModel("moonshotai/kimi-k3", { owned_by: "modal" }),
gatewayModel("claude-sonnet-5"),
]);
- let flagOn = false;
- mockUseFeatureFlag.mockImplementation(
- (flag: string) => flag === KIMI_MODEL_FLAG && flagOn,
- );
-
- const off = await renderHook("claude");
+ const result = await renderHook("claude");
await waitForAssertion(() => {
const values = getModelConfigOption(
- off.current.configOptions,
+ result.current.configOptions,
).options.map((option) => option.value);
- expect(values).not.toContain("moonshotai/kimi-k3");
- });
-
- flagOn = true;
- const on = await renderHook("claude");
- await waitForAssertion(() => {
- const values = getModelConfigOption(on.current.configOptions).options.map(
- (option) => option.value,
- );
expect(values).toContain("moonshotai/kimi-k3");
});
});
diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.ts
index 3b8d6767bb9e..c9a3eb75cc60 100644
--- a/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.ts
+++ b/products/desktop/apps/mobile/src/features/tasks/hooks/useCloudTaskConfigOptions.ts
@@ -4,21 +4,10 @@ import {
buildProviderModelGroups,
type CloudTaskConfigOption,
type CloudTaskConfigSelectGroup,
- DEEPSEEK_MODEL_FLAG,
type GatewayModel,
- GLM_MODEL_FLAG,
- GLM53_FLASH_MODEL_FLAG,
- GLM53_MODEL_FLAG,
- isDeepseekModelId,
- isGlm53FlashModelId,
- isGlm53ModelId,
- isGlmModelId,
- isModalModelId,
isRestrictedModelOption,
- KIMI_MODEL_FLAG,
} from "@posthog/shared";
import { useQuery } from "@tanstack/react-query";
-import { useFeatureFlag } from "posthog-react-native";
import { useMemo } from "react";
import { useAuthStore } from "@/features/auth";
import { getPostHogApiClient } from "@/lib/posthogApiClient";
@@ -35,11 +24,6 @@ export function useCloudTaskConfigOptions(
currentValue?: string,
) {
const oauthAccessToken = useAuthStore((state) => state.oauthAccessToken);
- const glmEnabled = useFeatureFlag(GLM_MODEL_FLAG);
- const glm53Enabled = useFeatureFlag(GLM53_MODEL_FLAG);
- const glm53FlashEnabled = useFeatureFlag(GLM53_FLASH_MODEL_FLAG);
- const deepseekEnabled = useFeatureFlag(DEEPSEEK_MODEL_FLAG);
- const kimiEnabled = useFeatureFlag(KIMI_MODEL_FLAG);
const query = useQuery({
queryKey: cloudTaskConfigOptionKeys.models(),
queryFn: () => getPostHogApiClient().getCloudTaskGatewayModels(),
@@ -49,30 +33,10 @@ export function useCloudTaskConfigOptions(
const models = query.data ?? emptyModels;
const hasLiveConfig = query.data !== undefined;
- const visibleModels = useMemo(
- () =>
- models.filter(
- (model) =>
- !(!glm53Enabled && isGlm53ModelId(model.id)) &&
- !(!glm53FlashEnabled && isGlm53FlashModelId(model.id)) &&
- !(
- !glmEnabled &&
- isGlmModelId(model.id) &&
- !isGlm53ModelId(model.id) &&
- !isGlm53FlashModelId(model.id)
- ) &&
- !(!deepseekEnabled && isDeepseekModelId(model.id)) &&
- !(!kimiEnabled && isModalModelId(model.id)),
- ),
- [
- models,
- glmEnabled,
- glm53Enabled,
- glm53FlashEnabled,
- deepseekEnabled,
- kimiEnabled,
- ],
- );
+ // The gateway listing is already scoped to the caller: it drops a model behind a rollout
+ // flag the caller does not hold. A second gate here reads flags this app cannot see the
+ // catalog for, which is how it hid models the gateway was serving.
+ const visibleModels = models;
const configOptions = useMemo(
() =>
diff --git a/products/desktop/packages/shared/src/cloud-task-models.ts b/products/desktop/packages/shared/src/cloud-task-models.ts
index e8ccc46d4c19..390bc4839ac1 100644
--- a/products/desktop/packages/shared/src/cloud-task-models.ts
+++ b/products/desktop/packages/shared/src/cloud-task-models.ts
@@ -198,18 +198,6 @@ export function isCloudflareModelId(modelId: string): boolean {
return modelId.startsWith("@cf/");
}
-export function isGlmModelId(modelId: string): boolean {
- return modelId.toLowerCase().includes("glm");
-}
-
-export function isGlm53ModelId(modelId: string): boolean {
- return modelId.toLowerCase() === "zai-org/glm-5.3";
-}
-
-export function isGlm53FlashModelId(modelId: string): boolean {
- return modelId.toLowerCase() === "zai-org/glm-5.3-flash";
-}
-
export function isCloudflareModel(model: GatewayModel): boolean {
return isCloudflareModelId(model.id) || model.owned_by === "cloudflare";
}
diff --git a/products/desktop/packages/shared/src/feature-flag-keys.json b/products/desktop/packages/shared/src/feature-flag-keys.json
index 65925382b48b..266871d0192e 100644
--- a/products/desktop/packages/shared/src/feature-flag-keys.json
+++ b/products/desktop/packages/shared/src/feature-flag-keys.json
@@ -12,15 +12,10 @@
"CODEX_OWN_SUBSCRIPTION_FLAG": "posthog-code-codex-own-subscription",
"CONTEXT_LAYER_FLAG": "context-layer",
"CUSTOM_IMAGES_FEATURE_FLAG": "tasks-modal-vm-sandbox",
- "DEEPSEEK_MODEL_FLAG": "posthog-code-deepseek-model",
"DESKTOP_HOME_FLAG": "desktop-home-flag",
"DISCOVERY_RUN_FLAG": "posthog-code-discovery-run",
"EXPERIMENT_SUGGESTIONS_FLAG": "posthog-code-experiment-suggestions",
"FAST_MODE_FLAG": "posthog-desktop-fast-mode",
- "GLM53_FLASH_MODEL_FLAG": "posthog-code-glm-53-flash-model",
- "GLM53_MODEL_FLAG": "posthog-code-glm-53-model",
- "GLM_MODEL_FLAG": "posthog-code-glm-model",
- "KIMI_MODEL_FLAG": "tasks-kimi-k3",
"LOCAL_MCP_IMPORT_FLAG": "posthog-code-local-mcp-import",
"LOOPS_FLAG": "loops",
"LOOPS_HOG_FLOWS_FLAG": "loops-hog-flows",
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 84d9074a333b..6db22630078d 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -28,14 +28,8 @@ export const SAVED_SEARCHES_RAIL_FLAG =
featureFlagKeys.SAVED_SEARCHES_RAIL_FLAG;
export const TASKS_PREWARM_SANDBOX_FLAG =
featureFlagKeys.TASKS_PREWARM_SANDBOX_FLAG;
-export const GLM_MODEL_FLAG = featureFlagKeys.GLM_MODEL_FLAG;
-export const GLM53_MODEL_FLAG = featureFlagKeys.GLM53_MODEL_FLAG;
-export const GLM53_FLASH_MODEL_FLAG = featureFlagKeys.GLM53_FLASH_MODEL_FLAG;
-/** PostHog Desktop: show DeepSeek V4 Flash in the model picker. Off = hidden. */
-export const DEEPSEEK_MODEL_FLAG = featureFlagKeys.DEEPSEEK_MODEL_FLAG;
export const TASK_ANALYSIS_FLAG = featureFlagKeys.TASK_ANALYSIS_FLAG;
-export const KIMI_MODEL_FLAG = featureFlagKeys.KIMI_MODEL_FLAG;
/** Gates the Fast Mode section of the reasoning dropdown. */
export const FAST_MODE_FLAG = featureFlagKeys.FAST_MODE_FLAG;
/** Spoken narration (agent speaks via the `speak` tool). Gated for a staged rollout. */
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 4d65252cd841..9695ef6a6aa7 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -98,9 +98,6 @@ export {
isCloudflareModel,
isCloudflareModelId,
isDeepseekModelId,
- isGlm53FlashModelId,
- isGlm53ModelId,
- isGlmModelId,
isModalModel,
isModalModelId,
isOpenAIModel,
diff --git a/products/desktop/packages/shared/src/model-catalog.generated.ts b/products/desktop/packages/shared/src/model-catalog.generated.ts
index bfbdb95a3621..6303cc40e042 100644
--- a/products/desktop/packages/shared/src/model-catalog.generated.ts
+++ b/products/desktop/packages/shared/src/model-catalog.generated.ts
@@ -81,7 +81,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: "claude",
reasoningEfforts: ["high", "max"],
label: "GLM-5.2",
- accessFlag: "posthog-code-glm-model",
cost: {
inputPerMtok: 1.4,
outputPerMtok: 4.4,
@@ -94,7 +93,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: "claude",
reasoningEfforts: ["high", "max"],
label: "GLM-5.3",
- accessFlag: "posthog-code-glm-53-model",
cost: {
inputPerMtok: 1.4,
outputPerMtok: 4.4,
@@ -107,7 +105,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: "claude",
reasoningEfforts: ["high", "max"],
label: "GLM-5.3 Flash",
- accessFlag: "posthog-code-glm-53-flash-model",
cost: {
inputPerMtok: 0.15,
outputPerMtok: 0.5,
@@ -120,7 +117,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: "claude",
reasoningEfforts: [],
label: "Kimi K3",
- accessFlag: "tasks-kimi-k3",
cost: {
inputPerMtok: 3,
outputPerMtok: 15,
@@ -133,7 +129,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: "claude",
reasoningEfforts: [],
label: "DeepSeek V4 Flash",
- accessFlag: "posthog-code-deepseek-model",
cost: {
inputPerMtok: 0.13,
outputPerMtok: 0.26,
diff --git a/products/desktop/packages/shared/src/model-catalog.ts b/products/desktop/packages/shared/src/model-catalog.ts
index c05e6675dc4b..d742203d6a41 100644
--- a/products/desktop/packages/shared/src/model-catalog.ts
+++ b/products/desktop/packages/shared/src/model-catalog.ts
@@ -71,6 +71,21 @@ export function reasoningEffortsForModel(
* for everything else. Mirrors `label_for_model` in
* products/tasks/backend/model_catalog.py, so both surfaces name a model identically.
*/
+/**
+ * Every access flag the catalog gates a model behind, without duplicates.
+ *
+ * A picker resolves these and hands the answers back to the filter, so gating a model is
+ * done by giving it an `access_flag` in products/tasks/backend/model_catalog.py and no
+ * picker has to learn the flag's name. Empty while no model is behind a rollout.
+ */
+export const MODEL_ACCESS_FLAGS: readonly string[] = [
+ ...new Set(
+ MODELS.map((model) => model.accessFlag).filter(
+ (flag): flag is string => flag !== undefined,
+ ),
+ ),
+];
+
/**
* The feature flag a person needs before a picker offers this model, or `undefined` when
* it is generally available.
diff --git a/products/desktop/packages/ui/src/features/loops/loopModels.test.ts b/products/desktop/packages/ui/src/features/loops/loopModels.test.ts
index 530d0b095e66..c2b7985f7d31 100644
--- a/products/desktop/packages/ui/src/features/loops/loopModels.test.ts
+++ b/products/desktop/packages/ui/src/features/loops/loopModels.test.ts
@@ -3,14 +3,7 @@ import type {
SessionConfigSelectOptions,
} from "@agentclientprotocol/sdk";
import type { LoopSchemas } from "@posthog/api-client/loops";
-import {
- DEEPSEEK_MODEL_FLAG,
- GLM_MODEL_FLAG,
- GLM53_FLASH_MODEL_FLAG,
- GLM53_MODEL_FLAG,
- KIMI_MODEL_FLAG,
- restrictedModelMeta,
-} from "@posthog/shared";
+import { restrictedModelMeta } from "@posthog/shared";
import { MODELS } from "@posthog/shared/model-catalog";
import { describe, expect, it } from "vitest";
import type { ModelRolloutFlags } from "../sessions/modelOptionFilters";
@@ -36,22 +29,8 @@ function modelConfigOption(
];
}
-/** The flag record the picker reads, from the friendlier names these cases are written in. */
-function rolloutFlags(on: {
- glm?: boolean;
- glm53?: boolean;
- glm53Flash?: boolean;
- kimi?: boolean;
- deepseek?: boolean;
-}): ModelRolloutFlags {
- return {
- [GLM_MODEL_FLAG]: on.glm ?? false,
- [GLM53_MODEL_FLAG]: on.glm53 ?? false,
- [GLM53_FLASH_MODEL_FLAG]: on.glm53Flash ?? false,
- [KIMI_MODEL_FLAG]: on.kimi ?? false,
- [DEEPSEEK_MODEL_FLAG]: on.deepseek ?? false,
- };
-}
+/** What the picker reads while the catalog gates no model. */
+const noFlags: ModelRolloutFlags = {};
const claudeOptions = modelConfigOption([
{ value: "claude-sonnet-5", name: "Claude Sonnet 5" },
@@ -62,7 +41,7 @@ describe("loopModelOptions", () => {
it("includes GPT-6 Astra in the offline Codex fallback", () => {
expect(
loopModelOptions("codex", [], {
- flags: rolloutFlags({ glm: false }),
+ flags: noFlags,
pinnedModel: "",
}),
).toContainEqual({ value: "gpt-6-astra", label: "GPT-6 Astra" });
@@ -71,7 +50,7 @@ describe("loopModelOptions", () => {
it("maps served model options to value/label pairs", () => {
expect(
loopModelOptions("claude", claudeOptions, {
- flags: rolloutFlags({ glm: true }),
+ flags: noFlags,
pinnedModel: "",
}),
).toEqual([
@@ -90,7 +69,7 @@ describe("loopModelOptions", () => {
]);
expect(
loopModelOptions("claude", grouped, {
- flags: rolloutFlags({ glm: true }),
+ flags: noFlags,
pinnedModel: "",
}),
).toEqual([{ value: "claude-sonnet-5", label: "Claude Sonnet 5" }]);
@@ -107,108 +86,45 @@ describe("loopModelOptions", () => {
]);
expect(
loopModelOptions("claude", withRestricted, {
- flags: rolloutFlags({ glm: true }),
+ flags: noFlags,
pinnedModel: "",
}),
).toEqual([{ value: "claude-sonnet-5", label: "Claude Sonnet 5" }]);
});
+ // The open-weights models ran on the claude harness while their rollout flags were
+ // already on for everyone, and the pickers kept hiding them, so each id is named here.
it.each([
- {
- name: "hides GLM when the flag is off",
- glmEnabled: false,
- pinnedModel: "",
- expectedValues: ["claude-sonnet-5"],
- },
- {
- name: "shows GLM when the flag is on",
- glmEnabled: true,
+ { name: "GLM-5.2", id: "@cf/zai-org/glm-5.2" },
+ { name: "GLM-5.3", id: "zai-org/glm-5.3" },
+ { name: "GLM-5.3 Flash", id: "zai-org/glm-5.3-flash" },
+ { name: "DeepSeek V4 Flash", id: "deepseek-ai/deepseek-v4-flash-0731" },
+ { name: "Kimi K3", id: "moonshotai/kimi-k3" },
+ ])("offers a served $name to everyone", ({ name, id }) => {
+ const options = modelConfigOption([
+ { value: "claude-sonnet-5", name: "Claude Sonnet 5" },
+ { value: id, name },
+ ]);
+
+ const values = loopModelOptions("claude", options, {
+ flags: noFlags,
pinnedModel: "",
- expectedValues: ["claude-sonnet-5", "@cf/zai-org/glm-5.2"],
- },
- {
- name: "keeps a pinned GLM model visible with the flag off",
- glmEnabled: false,
- pinnedModel: "@cf/zai-org/glm-5.2",
- expectedValues: ["claude-sonnet-5", "@cf/zai-org/glm-5.2"],
- },
- ])("$name", ({ glmEnabled, pinnedModel, expectedValues }) => {
- const values = loopModelOptions("claude", claudeOptions, {
- flags: rolloutFlags({ glm: glmEnabled }),
- pinnedModel,
}).map((option) => option.value);
- expect(values).toEqual(expectedValues);
+ expect(values).toEqual(["claude-sonnet-5", id]);
});
it("keeps a pinned model that the catalog no longer serves", () => {
expect(
loopModelOptions("claude", claudeOptions, {
- flags: rolloutFlags({ glm: true }),
+ flags: noFlags,
pinnedModel: "claude-opus-4-1",
}),
).toContainEqual({ value: "claude-opus-4-1", label: "Claude Opus 4.1" });
});
- it.each([
- {
- flags: rolloutFlags({ glm53: true }),
- expected: [{ value: "zai-org/glm-5.3", label: "GLM-5.3" }],
- },
- {
- flags: rolloutFlags({ glm53Flash: true }),
- expected: [{ value: "zai-org/glm-5.3-flash", label: "GLM-5.3 Flash" }],
- },
- ])("gates each GLM 5.3 variant independently", ({ flags, expected }) => {
- const options = modelConfigOption([
- { value: "@cf/zai-org/glm-5.2", name: "GLM-5.2" },
- { value: "zai-org/glm-5.3", name: "GLM-5.3" },
- { value: "zai-org/glm-5.3-flash", name: "GLM-5.3 Flash" },
- ]);
-
- expect(
- loopModelOptions("claude", options, { flags, pinnedModel: "" }),
- ).toEqual(expected);
- });
-
- it.each([
- {
- name: "hides a served DeepSeek model when the flag is off",
- deepseekEnabled: false,
- pinnedModel: "",
- expectedValues: ["claude-sonnet-5"],
- },
- {
- name: "shows a served DeepSeek model when the flag is on",
- deepseekEnabled: true,
- pinnedModel: "",
- expectedValues: ["claude-sonnet-5", "deepseek-ai/deepseek-v4-flash-0731"],
- },
- {
- name: "keeps a pinned DeepSeek model visible with the flag off",
- deepseekEnabled: false,
- pinnedModel: "deepseek-ai/deepseek-v4-flash-0731",
- expectedValues: ["claude-sonnet-5", "deepseek-ai/deepseek-v4-flash-0731"],
- },
- ])("$name", ({ deepseekEnabled, pinnedModel, expectedValues }) => {
- const options = modelConfigOption([
- { value: "claude-sonnet-5", name: "Claude Sonnet 5" },
- {
- value: "deepseek-ai/deepseek-v4-flash-0731",
- name: "DeepSeek V4 Flash",
- },
- ]);
-
- const values = loopModelOptions("claude", options, {
- flags: rolloutFlags({ glm: true, deepseek: deepseekEnabled }),
- pinnedModel,
- }).map((option) => option.value);
- expect(values).toEqual(expectedValues);
- });
-
it.each<{
name: string;
adapter: LoopSchemas.LoopRuntimeAdapterEnum;
- glm53Enabled?: boolean;
expectedValues: string[];
}>([
{
@@ -220,6 +136,9 @@ describe("loopModelOptions", () => {
"claude-sonnet-5",
"claude-fable-5",
"claude-fable-5-1",
+ "zai-org/glm-5.3",
+ "zai-org/glm-5.3-flash",
+ "moonshotai/kimi-k3",
],
},
{
@@ -234,22 +153,9 @@ describe("loopModelOptions", () => {
"gpt-6-astra",
],
},
- {
- name: "applies the GLM 5.3 flag to the fallback list",
- adapter: "claude",
- glm53Enabled: true,
- expectedValues: [
- "claude-opus-4-8",
- "claude-opus-5",
- "claude-sonnet-5",
- "claude-fable-5",
- "claude-fable-5-1",
- "zai-org/glm-5.3",
- ],
- },
- ])("$name", ({ adapter, glm53Enabled, expectedValues }) => {
+ ])("$name", ({ adapter, expectedValues }) => {
const values = loopModelOptions(adapter, [], {
- flags: rolloutFlags({ glm: true, glm53: glm53Enabled }),
+ flags: noFlags,
pinnedModel: "",
}).map((option) => option.value);
expect(values).toEqual(expectedValues);
@@ -264,13 +170,7 @@ describe("loopModelOptions", () => {
(m) => m.id,
);
const fallback = loopModelOptions(adapter, [], {
- flags: rolloutFlags({
- glm: true,
- glm53: true,
- glm53Flash: true,
- kimi: true,
- deepseek: true,
- }),
+ flags: noFlags,
pinnedModel: "",
})
.map((o) => o.value)
diff --git a/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts b/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts
index 8e295e512931..4e7d9d3f9d7c 100644
--- a/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts
@@ -1,48 +1,41 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
-import {
- DEEPSEEK_MODEL_FLAG,
- GLM_MODEL_FLAG,
- GLM53_FLASH_MODEL_FLAG,
- GLM53_MODEL_FLAG,
- KIMI_MODEL_FLAG,
-} from "@posthog/shared";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import {
type ModelRolloutFlags,
stripDisabledModelOption,
stripDisabledModels,
} from "./modelOptionFilters";
+const GATED_MODEL = "acme/gated-model";
+const GATED_FLAG = "acme-gated-model";
+
+// The catalog gates no model at the moment, so the strip paths need a stand-in to be
+// exercised at all. Naming a real model here would instead tie these cases to a rollout
+// that ends, which is how the open-weights models stayed hidden after their flags were
+// fully rolled out.
+vi.mock("@posthog/shared/model-catalog", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@posthog/shared/model-catalog")>();
+ return {
+ ...actual,
+ accessFlagForModel: (modelId: string): string | undefined =>
+ modelId === GATED_MODEL ? GATED_FLAG : actual.accessFlagForModel(modelId),
+ };
+});
+
describe("modelOptionFilters", () => {
- // The flag beside each id is the one the catalog records for it, so a case fails if the
- // two ever disagree about which flag gates the model.
- const rolloutModels: { flag: string; id: string; name: string }[] = [
- {
- flag: DEEPSEEK_MODEL_FLAG,
- id: "deepseek-ai/deepseek-v4-flash-0731",
- name: "DeepSeek V4 Flash",
- },
- { flag: GLM_MODEL_FLAG, id: "@cf/zai-org/glm-5.2", name: "GLM-5.2" },
- { flag: GLM53_MODEL_FLAG, id: "zai-org/glm-5.3", name: "GLM-5.3" },
- {
- flag: GLM53_FLASH_MODEL_FLAG,
- id: "zai-org/glm-5.3-flash",
- name: "GLM-5.3 Flash",
- },
- { flag: KIMI_MODEL_FLAG, id: "moonshotai/kimi-k3", name: "Kimi K3" },
+ const openWeightsModels = [
+ { id: "deepseek-ai/deepseek-v4-flash-0731", name: "DeepSeek V4 Flash" },
+ { id: "@cf/zai-org/glm-5.2", name: "GLM-5.2" },
+ { id: "zai-org/glm-5.3", name: "GLM-5.3" },
+ { id: "zai-org/glm-5.3-flash", name: "GLM-5.3 Flash" },
+ { id: "moonshotai/kimi-k3", name: "Kimi K3" },
];
- const enabledFlags: ModelRolloutFlags = {
- [DEEPSEEK_MODEL_FLAG]: true,
- [GLM_MODEL_FLAG]: true,
- [GLM53_MODEL_FLAG]: true,
- [GLM53_FLASH_MODEL_FLAG]: true,
- [KIMI_MODEL_FLAG]: true,
- };
+ const noFlags: ModelRolloutFlags = {};
- it.each(rolloutModels)(
- "selects an available model when $flag is disabled",
- ({ flag, id, name }) => {
- const flags = { ...enabledFlags, [flag]: false };
+ it.each(openWeightsModels)(
+ "offers $name, which the catalog does not gate",
+ ({ id, name }) => {
const option: SessionConfigOption = {
type: "select",
id: "model",
@@ -54,13 +47,31 @@ describe("modelOptionFilters", () => {
],
};
- expect(stripDisabledModelOption(option, flags)).toMatchObject({
- currentValue: "claude-opus-4-8",
- options: [{ value: "claude-opus-4-8" }],
- });
+ expect(stripDisabledModelOption(option, noFlags)).toEqual(option);
+ expect(stripDisabledModels([{ id }], noFlags)).toEqual([{ id }]);
},
);
+ it("selects an available model when the gated one is not reachable", () => {
+ const option: SessionConfigOption = {
+ type: "select",
+ id: "model",
+ name: "Model",
+ currentValue: GATED_MODEL,
+ options: [
+ { value: GATED_MODEL, name: "Gated model" },
+ { value: "claude-opus-4-8", name: "Claude Opus 4.8" },
+ ],
+ };
+
+ expect(
+ stripDisabledModelOption(option, { [GATED_FLAG]: false }),
+ ).toMatchObject({
+ currentValue: "claude-opus-4-8",
+ options: [{ value: "claude-opus-4-8" }],
+ });
+ });
+
it("drops a group emptied by a disabled flag, heading and all", () => {
const option: SessionConfigOption = {
type: "select",
@@ -74,36 +85,30 @@ describe("modelOptionFilters", () => {
options: [{ value: "claude-opus-5", name: "Claude Opus 5" }],
},
{
- group: "moonshotai",
- name: "Moonshot AI",
- options: [{ value: "moonshotai/kimi-k3", name: "Kimi K3" }],
+ group: "acme",
+ name: "Acme",
+ options: [{ value: GATED_MODEL, name: "Gated model" }],
},
],
};
expect(
- stripDisabledModelOption(option, {
- ...enabledFlags,
- [KIMI_MODEL_FLAG]: false,
- }),
+ stripDisabledModelOption(option, { [GATED_FLAG]: false }),
).toMatchObject({
currentValue: "claude-opus-5",
options: [{ group: "anthropic" }],
});
});
- it.each(rolloutModels)(
- "removes only $flag models when its flag is disabled",
- ({ flag, id }) => {
- const flags = { ...enabledFlags, [flag]: false };
- const models = [
- ...rolloutModels.map(({ id, name }) => ({ id, name })),
- { id: "gpt-5.6-terra", name: "GPT-5.6 Terra" },
- ];
+ it("removes only the models whose flag is off", () => {
+ const models = [
+ ...openWeightsModels.map(({ id }) => ({ id })),
+ { id: GATED_MODEL },
+ { id: "gpt-5.6-terra" },
+ ];
- expect(stripDisabledModels(models, flags)).toEqual(
- models.filter((model) => model.id !== id),
- );
- },
- );
+ expect(stripDisabledModels(models, { [GATED_FLAG]: false })).toEqual(
+ models.filter((model) => model.id !== GATED_MODEL),
+ );
+ });
});
diff --git a/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts b/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts
index 3595d6a531e4..dbb4411c3a36 100644
--- a/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts
+++ b/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts
@@ -1,36 +1,45 @@
+import { useService } from "@posthog/di/react";
+import { MODEL_ACCESS_FLAGS } from "@posthog/shared/model-catalog";
+import { isFlagForcedOff } from "@posthog/ui/features/feature-flags/devFlagOverrides";
import {
- DEEPSEEK_MODEL_FLAG,
- GLM_MODEL_FLAG,
- GLM53_FLASH_MODEL_FLAG,
- GLM53_MODEL_FLAG,
- KIMI_MODEL_FLAG,
-} from "@posthog/shared";
-import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
-import { useMemo } from "react";
+ FEATURE_FLAGS,
+ type FeatureFlags,
+} from "@posthog/ui/features/feature-flags/identifiers";
+import { useCallback, useEffect, useState } from "react";
import type { ModelRolloutFlags } from "./modelOptionFilters";
/**
- * The rollout flags gating individual models, read in one place. Dev builds
- * default them on, like pi-harness, so the full catalog shows without a
- * posthog override. Memoized so the object can sit in dependency arrays.
+ * The rollout flags gating individual models, read in one place.
+ *
+ * Which flags to read comes from the catalog rather than from a list kept here, so a model
+ * the catalog stops gating is offered to everyone, and a model it starts gating is read
+ * rather than silently treated as unreachable. Dev builds default them on, like pi-harness,
+ * so the full catalog shows without a posthog override.
+ *
+ * Read the same way as `useFeatureFlag`, including the re-read once the flags arrive, so a
+ * gated model appears as soon as the answers land instead of on the next mount.
*/
export function useModelRolloutFlags(): ModelRolloutFlags {
+ const flags = useService<FeatureFlags>(FEATURE_FLAGS);
const dev = import.meta.env.DEV;
- const deepseek = useFeatureFlag(DEEPSEEK_MODEL_FLAG, dev);
- const glm = useFeatureFlag(GLM_MODEL_FLAG, dev);
- const glm53 = useFeatureFlag(GLM53_MODEL_FLAG, dev);
- const glm53Flash = useFeatureFlag(GLM53_FLASH_MODEL_FLAG, dev);
- const kimi = useFeatureFlag(KIMI_MODEL_FLAG, dev);
// Keyed by flag, so a model's `accessFlag` from the catalog reads straight off this
// rather than each caller knowing which named boolean belongs to which model.
- return useMemo(
- () => ({
- [DEEPSEEK_MODEL_FLAG]: deepseek,
- [GLM_MODEL_FLAG]: glm,
- [GLM53_MODEL_FLAG]: glm53,
- [GLM53_FLASH_MODEL_FLAG]: glm53Flash,
- [KIMI_MODEL_FLAG]: kimi,
- }),
- [deepseek, glm, glm53, glm53Flash, kimi],
+ const read = useCallback(
+ (): ModelRolloutFlags =>
+ Object.fromEntries(
+ MODEL_ACCESS_FLAGS.map((flag) => [
+ flag,
+ !isFlagForcedOff(flag) && (flags.isEnabled(flag) || dev),
+ ]),
+ ),
+ [flags],
);
+ const [rollout, setRollout] = useState(read);
+
+ useEffect(() => {
+ setRollout(read());
+ return flags.onFlagsLoaded(() => setRollout(read()));
+ }, [flags, read]);
+
+ return rollout;
}
diff --git a/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts b/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts
index 2cd9882559e4..c2a87557b6de 100644
--- a/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts
@@ -6,6 +6,37 @@ import { MODELS } from 'products/tasks/frontend/modelCatalog.generated'
import { modelCatalogueLogic } from './modelCatalogueLogic'
+const GATED_ONE = { id: 'acme/gated-one', flag: 'acme-gated-one' }
+const GATED_TWO = { id: 'acme/gated-two', flag: 'acme-gated-two' }
+
+// The catalog gates no model at the moment, so the gate needs stand-ins to be exercised at
+// all. Two of them, because one cannot show that a flag reveals its own model and no other.
+// Naming real models here instead is what tied these cases to a rollout that ends: the
+// open-weights models stayed hidden after their flags had reached everyone.
+jest.mock('products/tasks/frontend/modelCatalog.generated', () => {
+ const actual = jest.requireActual('products/tasks/frontend/modelCatalog.generated')
+ return {
+ ...actual,
+ MODELS: [
+ ...actual.MODELS,
+ {
+ id: 'acme/gated-one',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: [],
+ label: 'Gated one',
+ accessFlag: 'acme-gated-one',
+ },
+ {
+ id: 'acme/gated-two',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: [],
+ label: 'Gated two',
+ accessFlag: 'acme-gated-two',
+ },
+ ],
+ }
+})
+
describe('modelCatalogueLogic', () => {
let logic: ReturnType<typeof modelCatalogueLogic.build>
@@ -46,14 +77,26 @@ describe('modelCatalogueLogic', () => {
})
it('reveals only the gated model whose flag is on', () => {
- const [first] = GATED
- mountWithFlags([first.accessFlag as string])
+ mountWithFlags([GATED_ONE.flag])
const offered = logic.values.catalogue.map((choice) => choice.model)
- expect(offered).toContain(first.id)
- for (const model of GATED.filter((candidate) => candidate.id !== first.id)) {
- expect(offered).not.toContain(model.id)
- }
+ expect(offered).toContain(GATED_ONE.id)
+ expect(offered).not.toContain(GATED_TWO.id)
+ })
+
+ // These run on the claude harness and are offered to everyone. Every gate that reads an
+ // access flag fails closed, so a flag left on the catalog row after its rollout finished
+ // took them off the composer for anyone the flag service could not answer for.
+ it.each([
+ 'deepseek-ai/deepseek-v4-flash-0731',
+ '@cf/zai-org/glm-5.2',
+ 'zai-org/glm-5.3',
+ 'zai-org/glm-5.3-flash',
+ 'moonshotai/kimi-k3',
+ ])('offers %s without a flag', (model: string) => {
+ mountWithFlags([])
+
+ expect(logic.values.catalogue.map((choice) => choice.model)).toContain(model)
})
// An empty effort list is an answer, not missing metadata: the picker renders such a model with no
diff --git a/products/tasks/backend/model_catalog.py b/products/tasks/backend/model_catalog.py
index f24ea84eade1..cf70c1ed56fd 100644
--- a/products/tasks/backend/model_catalog.py
+++ b/products/tasks/backend/model_catalog.py
@@ -87,6 +87,10 @@ class CatalogModel:
``cost`` is ``None`` where no public price list covers the model, and a picker then shows
it with no cost rather than a guessed one.
+
+ Both gates fail closed, so clear ``access_flag`` when the rollout reaches everyone. A flag
+ left behind keeps the model away from every caller the flag service cannot answer for, and
+ from every surface that reads flags before they load.
"""
id: str
@@ -118,39 +122,15 @@ MODELS: tuple[CatalogModel, ...] = (
# GLM 5.2 is Cloudflare-served and driven through the `claude` adapter: the LLM gateway
# exposes it over its Anthropic-Messages surface and translates the `@cf/` id upstream,
# so the `anthropic` provider is the intended routing rather than a direct Anthropic call.
- CatalogModel(
- "@cf/zai-org/glm-5.2",
- CLAUDE,
- _GLM,
- label="GLM-5.2",
- access_flag="posthog-code-glm-model",
- cost=_GLM_COST,
- ),
- CatalogModel(
- "zai-org/glm-5.3",
- CLAUDE,
- _GLM,
- label="GLM-5.3",
- access_flag="posthog-code-glm-53-model",
- cost=_GLM_COST,
- ),
- CatalogModel(
- "zai-org/glm-5.3-flash",
- CLAUDE,
- _GLM,
- label="GLM-5.3 Flash",
- access_flag="posthog-code-glm-53-flash-model",
- cost=_GLM_FLASH_COST,
- ),
- CatalogModel(
- "moonshotai/kimi-k3", CLAUDE, _NO_EFFORT, label="Kimi K3", access_flag="tasks-kimi-k3", cost=_KIMI_COST
- ),
+ CatalogModel("@cf/zai-org/glm-5.2", CLAUDE, _GLM, label="GLM-5.2", cost=_GLM_COST),
+ CatalogModel("zai-org/glm-5.3", CLAUDE, _GLM, label="GLM-5.3", cost=_GLM_COST),
+ CatalogModel("zai-org/glm-5.3-flash", CLAUDE, _GLM, label="GLM-5.3 Flash", cost=_GLM_FLASH_COST),
+ CatalogModel("moonshotai/kimi-k3", CLAUDE, _NO_EFFORT, label="Kimi K3", cost=_KIMI_COST),
CatalogModel(
"deepseek-ai/deepseek-v4-flash-0731",
CLAUDE,
_NO_EFFORT,
label="DeepSeek V4 Flash",
- access_flag="posthog-code-deepseek-model",
cost=_DEEPSEEK_COST,
),
CatalogModel("claude-opus-4-5", CLAUDE, _STANDARD, cost=_OPUS_COST),
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index c33ab5495a2a..78a5a6fed802 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -100,6 +100,10 @@ from products.tasks.backend.presentation.serializers import (
from products.tasks.backend.presentation.views import api as views_api
from products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token
+# The catalog gates no model behind a rollout flag now, so the write paths that re-check
+# entitlement are exercised with a stand-in rather than with whichever model is mid-rollout.
+GATED_MODEL_FLAG = "tasks-test-model-gate"
+
def _grant_user_github_access(user: User, *, refresh_ttl_seconds: int = 15897600) -> UserIntegration:
now = int(time.time())
@@ -4346,8 +4350,11 @@ class TestTaskAPI(BaseTaskAPITest):
@override_settings(DEBUG=False)
@patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)
+ @patch("products.tasks.backend.feature_flags.get_required_model_flag", return_value=GATED_MODEL_FLAG)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- def test_run_endpoint_rejects_a_gated_model_the_caller_cannot_access(self, mock_workflow, mock_feature_enabled):
+ def test_run_endpoint_rejects_a_gated_model_the_caller_cannot_access(
+ self, mock_workflow, _mock_required_flag, mock_feature_enabled
+ ):
# The Desktop picker hides gated models, but a stored preference or a direct API
# call reaches this endpoint without one, so the entitlement is re-checked here.
task = self.create_task()
@@ -4364,7 +4371,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "model"
- assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"
+ assert mock_feature_enabled.call_args.args[0] == GATED_MODEL_FLAG
mock_workflow.assert_not_called()
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
@@ -5015,8 +5022,12 @@ class TestTaskAPI(BaseTaskAPITest):
"products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
side_effect=lambda flag, *_args, **_kwargs: flag == "tasks",
)
+ @patch("products.tasks.backend.feature_flags.get_required_model_flag", return_value=GATED_MODEL_FLAG)
+ @patch("products.tasks.backend.facade.api.get_required_model_flag", return_value=GATED_MODEL_FLAG)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- def test_run_endpoint_resume_rejects_inherited_gated_model(self, mock_workflow, mock_feature_enabled):
+ def test_run_endpoint_resume_rejects_inherited_gated_model(
+ self, mock_workflow, _mock_facade_required_flag, _mock_required_flag, mock_feature_enabled
+ ):
# A resume omits `model`, so the serializer sees None and passes. The inherited
# model is the one that actually runs, so entitlement is re-checked after it lands.
task = self.create_task()
@@ -5035,7 +5046,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "model"
- assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"
+ assert mock_feature_enabled.call_args.args[0] == GATED_MODEL_FLAG
mock_workflow.assert_not_called()
def test_run_endpoint_rejects_invalid_sandbox_environment_id(self):
@@ -14258,8 +14269,9 @@ class TestCloudUsageGate(BaseTaskAPITest):
@patch("products.tasks.backend.facade.api.warm_task_sandbox")
@patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)
@patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)
+ @patch("products.tasks.backend.feature_flags.get_required_model_flag", return_value=GATED_MODEL_FLAG)
def test_warm_rejects_a_gated_model_the_caller_cannot_access(
- self, mock_feature_enabled, _mock_warm_enabled, mock_warm
+ self, _mock_required_flag, mock_feature_enabled, _mock_warm_enabled, mock_warm
):
# Warming boots a sandbox and starts the agent on this model, so it bills like a run.
response = self.client.post(
@@ -14270,12 +14282,13 @@ class TestCloudUsageGate(BaseTaskAPITest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "model"
- assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"
+ assert mock_feature_enabled.call_args.args[0] == GATED_MODEL_FLAG
mock_warm.assert_not_called()
@override_settings(DEBUG=False)
@patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)
- def test_create_rejects_a_gated_model_hint(self, mock_feature_enabled):
+ @patch("products.tasks.backend.feature_flags.get_required_model_flag", return_value=GATED_MODEL_FLAG)
+ def test_create_rejects_a_gated_model_hint(self, _mock_required_flag, mock_feature_enabled):
# The create hint is write-only, but it is what selects a warm Run to activate,
# so a gated value here would run the gated model without ever reaching run_task.
response = self.client.post(
@@ -14291,7 +14304,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "model"
- assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"
+ assert mock_feature_enabled.call_args.args[0] == GATED_MODEL_FLAG
assert not Task.objects.filter(title="Gated").exists()
def _inbox_task(self, origin: Task.OriginProduct) -> Task:
diff --git a/products/tasks/backend/tests/test_feature_flags.py b/products/tasks/backend/tests/test_feature_flags.py
index e2fb05f2f3e6..9f14b9d46c20 100644
--- a/products/tasks/backend/tests/test_feature_flags.py
+++ b/products/tasks/backend/tests/test_feature_flags.py
@@ -57,10 +57,26 @@ class TestIsDevStackImageBakeEnabled:
feature_enabled_mock.assert_not_called()
+GATED_MODEL_FLAG = "tasks-test-model-gate"
+
+
class TestGetModelAccessError:
+ # The open-weights models run on the claude harness and are offered to everyone. They
+ # were gated while their rollout ran, and a caller whose flags could not be evaluated
+ # lost them, so each id is named here.
@pytest.mark.parametrize(
"model",
- ["claude-sonnet-5", "gpt-5.6-luna", "", None],
+ [
+ "claude-sonnet-5",
+ "gpt-5.6-luna",
+ "deepseek-ai/deepseek-v4-flash-0731",
+ "moonshotai/kimi-k3",
+ "zai-org/glm-5.3",
+ "zai-org/glm-5.3-flash",
+ "@cf/zai-org/glm-5.2",
+ "",
+ None,
+ ],
)
def test_ungated_model_is_allowed_without_consulting_the_flag(self, model):
with (
@@ -74,30 +90,23 @@ class TestGetModelAccessError:
feature_enabled_mock.assert_not_called()
- @pytest.mark.parametrize(
- "model, flag_key",
- [
- ("moonshotai/kimi-k3", "tasks-kimi-k3"),
- (" MoonshotAI/Kimi-K3 ", "tasks-kimi-k3"),
- ("deepseek-ai/deepseek-v4-flash-0731", "posthog-code-deepseek-model"),
- # Gated on the desktop app before this was one definition, and ungated on the
- # server, so the same model was reachable through the web composer and the API.
- ("@cf/zai-org/glm-5.2", "posthog-code-glm-model"),
- ("zai-org/glm-5.3", "posthog-code-glm-53-model"),
- ("zai-org/glm-5.3-flash", "posthog-code-glm-53-flash-model"),
- ],
- )
- def test_gated_model_is_allowed_when_the_flag_is_on(self, model, flag_key):
+ # No catalog model is behind a rollout right now, so the gate itself is exercised with a
+ # stand-in flag instead of with whichever model happens to be mid-rollout.
+ def test_gated_model_is_allowed_when_the_flag_is_on(self):
with (
override_settings(DEBUG=False),
+ patch(
+ "products.tasks.backend.feature_flags.get_required_model_flag",
+ return_value=GATED_MODEL_FLAG,
+ ),
patch(
"products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
return_value=True,
) as feature_enabled_mock,
):
- assert get_model_access_error(model, distinct_id="d-1") is None
+ assert get_model_access_error("moonshotai/kimi-k3", distinct_id="d-1") is None
- assert feature_enabled_mock.call_args.args[0] == flag_key
+ assert feature_enabled_mock.call_args.args[0] == GATED_MODEL_FLAG
assert feature_enabled_mock.call_args.kwargs["distinct_id"] == "d-1"
@pytest.mark.parametrize(
@@ -107,6 +116,10 @@ class TestGetModelAccessError:
def test_gated_model_is_rejected_without_entitlement(self, flag_value, distinct_id):
with (
override_settings(DEBUG=False),
+ patch(
+ "products.tasks.backend.feature_flags.get_required_model_flag",
+ return_value=GATED_MODEL_FLAG,
+ ),
patch(
"products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
return_value=flag_value,
@@ -121,6 +134,10 @@ class TestGetModelAccessError:
# rather than opening it to every caller.
with (
override_settings(DEBUG=False),
+ patch(
+ "products.tasks.backend.feature_flags.get_required_model_flag",
+ return_value=GATED_MODEL_FLAG,
+ ),
patch(
"products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
side_effect=RuntimeError("flag service failed"),
diff --git a/products/tasks/backend/tests/test_model_catalog.py b/products/tasks/backend/tests/test_model_catalog.py
index 9545d7b9bd55..1dd0b6f9b38d 100644
--- a/products/tasks/backend/tests/test_model_catalog.py
+++ b/products/tasks/backend/tests/test_model_catalog.py
@@ -208,16 +208,9 @@ class TestAvailableModelChoices:
assert [c.label for c in choices] == ["DeepSeek V4 Flash", "GLM-5.3 Flash", "Kimi K3"]
-def test_every_gated_model_resolves_to_its_catalog_flag() -> None:
+def test_every_model_resolves_to_its_catalog_flag() -> None:
# The gate and the pickers read one field now, so this fails if a row gains an
# access_flag the entitlement check cannot see, whichever spelling the caller sends.
- gated = [model for model in model_catalog.MODELS if model.access_flag]
- assert gated, "the catalog gates no model, so this guard proves nothing"
-
- for model in gated:
+ for model in model_catalog.MODELS:
assert get_required_model_flag(model.id) == model.access_flag
assert get_required_model_flag(f"anthropic/{model.id}") == model.access_flag
-
- for model in model_catalog.MODELS:
- if model.access_flag is None:
- assert get_required_model_flag(model.id) is None
diff --git a/products/tasks/backend/tests/test_model_selection.py b/products/tasks/backend/tests/test_model_selection.py
index 73cc22ec8857..cfa13010fd63 100644
--- a/products/tasks/backend/tests/test_model_selection.py
+++ b/products/tasks/backend/tests/test_model_selection.py
@@ -2,6 +2,7 @@ import pytest
from django.core.exceptions import ValidationError
+from products.tasks.backend import model_catalog
from products.tasks.backend.constants import get_required_model_flag
from products.tasks.backend.temporal.process_task.utils import (
RuntimeAdapter,
@@ -62,20 +63,43 @@ def test_invalid_selections_raise(runtime_adapter, model, reasoning_effort, expe
@pytest.mark.parametrize(
- "model,expected_flag",
+ "model",
[
- ("zai-org/glm-5.3", "posthog-code-glm-53-model"),
- ("anthropic/zai-org/glm-5.3", "posthog-code-glm-53-model"),
- ("ANTHROPIC/ZAI-ORG/GLM-5.3", "posthog-code-glm-53-model"),
- ("claude-opus-5", None),
+ "zai-org/glm-5.3",
+ "anthropic/zai-org/glm-5.3",
+ "ANTHROPIC/ZAI-ORG/GLM-5.3",
+ "deepseek-ai/deepseek-v4-flash-0731",
+ "moonshotai/kimi-k3",
+ "claude-opus-5",
],
- ids=["canonical", "provider_qualified", "mixed_case", "ungated"],
+ ids=["canonical", "provider_qualified", "mixed_case", "deepseek", "kimi", "anthropic"],
)
-def test_gated_model_is_gated_in_every_spelling(model: str, expected_flag: str | None) -> None:
- # Every resolver folds a provider-qualified id onto the model it names, so a gate that
- # missed that spelling would skip the entitlement check on an id the rest of the stack
- # already treats as the gated one.
- assert get_required_model_flag(model) == expected_flag
+def test_open_weights_models_need_no_entitlement(model: str) -> None:
+ # These run on the claude harness and are offered to everyone. Every resolver folds a
+ # provider-qualified id onto the model it names, so a spelling that resolved to a gate
+ # would reject a selection every other surface accepts.
+ assert get_required_model_flag(model) is None
+
+
+ "model",
+ [
+ "gated-test-model",
+ "anthropic/gated-test-model",
+ "ANTHROPIC/GATED-TEST-MODEL",
+ " gated-test-model ",
+ ],
+ ids=["canonical", "provider_qualified", "mixed_case", "padded"],
+)
+def test_get_required_model_flag_resolves_a_real_gate(model: str, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The test above only proves every open-weights spelling resolves to None. Without a
+ # gated catalog entry, a resolver that always returned None would pass it too, leaving
+ # the retained rollout mechanism untested until another model is gated. This adds one.
+ gated = model_catalog.CatalogModel(
+ "gated-test-model", model_catalog.CLAUDE, ("low",), access_flag="tasks-gated-test-model"
+ )
+ monkeypatch.setitem(model_catalog._MODEL_BY_ID, gated.id, gated)
+ assert get_required_model_flag(model) == gated.access_flag
@pytest.mark.parametrize(
diff --git a/products/tasks/frontend/modelCatalog.generated.ts b/products/tasks/frontend/modelCatalog.generated.ts
index 883edca47a9c..ee09dc2bd676 100644
--- a/products/tasks/frontend/modelCatalog.generated.ts
+++ b/products/tasks/frontend/modelCatalog.generated.ts
@@ -68,7 +68,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: 'claude',
reasoningEfforts: ['high', 'max'],
label: 'GLM-5.2',
- accessFlag: 'posthog-code-glm-model',
cost: {
inputPerMtok: 1.4,
outputPerMtok: 4.4,
@@ -81,7 +80,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: 'claude',
reasoningEfforts: ['high', 'max'],
label: 'GLM-5.3',
- accessFlag: 'posthog-code-glm-53-model',
cost: {
inputPerMtok: 1.4,
outputPerMtok: 4.4,
@@ -94,7 +92,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: 'claude',
reasoningEfforts: ['high', 'max'],
label: 'GLM-5.3 Flash',
- accessFlag: 'posthog-code-glm-53-flash-model',
cost: {
inputPerMtok: 0.15,
outputPerMtok: 0.5,
@@ -107,7 +104,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: 'claude',
reasoningEfforts: [],
label: 'Kimi K3',
- accessFlag: 'tasks-kimi-k3',
cost: {
inputPerMtok: 3,
outputPerMtok: 15,
@@ -120,7 +116,6 @@ export const MODELS: readonly CatalogModel[] = [
runtimeAdapter: 'claude',
reasoningEfforts: [],
label: 'DeepSeek V4 Flash',
- accessFlag: 'posthog-code-deepseek-model',
cost: {
inputPerMtok: 0.13,
outputPerMtok: 0.26,
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index 6604efeed7a5..affc81962634 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -48,9 +48,10 @@ Existing Django callers should use `build_openai_client`, `build_async_openai_cl
For PostHog Desktop, the Python gateway maps Django credential rejections to generic access denials. Transport, server, and malformed-response failures remain retryable service errors.
-Flag-gated open-weight models added to the Python gateway under the freeze stay there for the same reason.
-`zai-org/glm-5.3-flash` is Baseten-exclusive, gated by the `posthog-code-glm-53-flash-model` flag, and reachable only by the `posthog_code` and `review_hog` products.
-Its callers are PostHog Desktop and PostHog Code, so the model depends on the OAuth application allowlists, the request-selected project validated against OAuth scope and live organization membership, the billing policy, and the per-model access flags named in the first row above.
+Open-weight models added to the Python gateway under the freeze stay there for the same reason.
+`zai-org/glm-5.3-flash` is Baseten-exclusive and reachable only by the `posthog_code` and `review_hog` products.
+Its callers are PostHog Desktop and PostHog Code, so the model depends on the OAuth application allowlists, the request-selected project validated against OAuth scope and live organization membership, and the billing policy.
+No open-weight model is behind a per-model access flag now; the mechanism stays for the next rollout.
The Go catalog serves GLM 5.2 only, and Baseten on Go still depends on the provider deployment check below.
`gpt-6-astra` is also Python-only because the Go catalog does not serve it, while Desktop, Code, and cloud agents require the Python product policy above.
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index c570ddaf02a8..fed33a882aae 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -215,12 +215,14 @@ Use your runtime's standard AWS authentication mechanism (e.g. IAM role, IRSA, E
The gateway exposes models consistently across Anthropic Messages, chat/completions, and Responses while choosing their inference provider internally in `src/llm_gateway/inference_routing.py`.
- **GLM 5.2** (`@cf/zai-org/glm-5.2`) can run on Cloudflare Workers AI, Modal, or Baseten.
-- **GLM 5.3** (`zai-org/glm-5.3`) runs only on Baseten and is available to ReviewHog and PostHog Desktop behind its own `posthog-code-glm-53-model` flag.
- GLM 5.3 has no open weights released yet, so the flag is not created: the access gate fails closed, keeping the model blocked server-side and hidden in every picker.
- Do not create the flag until Baseten lists the model and the deployment slug, context window, and contract rate in `model_cost_overrides.py` / `model_registry.py` are confirmed against `inference.baseten.co/v1/models`: the rate is pinned, so a wrong placeholder bills at the wrong price with no automatic correction.
-- **GLM 5.3 Flash** (`zai-org/glm-5.3-flash`) runs only on Baseten and is available to ReviewHog and PostHog Desktop behind its own `posthog-code-glm-53-flash-model` flag.
+- **GLM 5.3** (`zai-org/glm-5.3`) runs only on Baseten and is available to ReviewHog and PostHog Desktop.
+ The deployment slug, context window, and contract rate in `model_cost_overrides.py` / `model_registry.py` are confirmed against `inference.baseten.co/v1/models`: the rate is pinned, so a wrong placeholder bills at the wrong price with no automatic correction.
+- **GLM 5.3 Flash** (`zai-org/glm-5.3-flash`) runs only on Baseten and is available to ReviewHog and PostHog Desktop.
Contract rate and 1M context window come from the Baseten listing and are pinned in `model_cost_overrides.py` / `model_registry.py`.
-- **DeepSeek V4 Flash** (`deepseek-ai/deepseek-v4-flash-0731`) runs only on Baseten and is available to ReviewHog and PostHog Desktop (client-gated by the `posthog-code-deepseek-model` flag).
+- **DeepSeek V4 Flash** (`deepseek-ai/deepseek-v4-flash-0731`) runs only on Baseten and is available to ReviewHog and PostHog Desktop.
+
+A model still in rollout is named in `MODEL_ACCESS_FLAGS` (`src/llm_gateway/products/config.py`), which both blocks selection and drops the model from the listing while the flag is off for the caller.
+That gate fails closed, so remove the entry once the flag reaches everyone: a caller whose flags cannot be evaluated loses the model otherwise.
Provider configuration:
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index ed2b9f4f2329..e9e361cab01f 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -114,7 +114,7 @@ _POSTHOG_CODE_AGENT_MODELS: Final[frozenset[str]] = frozenset(
# model-registry advertising filter; the registry also derives its advertising from it so the two
# can't drift. Keys must be lowercase.
RESTRICTED_MODEL_PRODUCTS: Final[dict[str, frozenset[str]]] = {
- # Evaluated by ReviewHog; exposed in PostHog Code behind the posthog-code-deepseek-model flag.
+ # Evaluated by ReviewHog and offered in PostHog Code; no other product may select it.
BASETEN_DEEPSEEK_PUBLIC_MODEL: frozenset({"posthog_code", "review_hog"}),
BASETEN_GLM53_PUBLIC_MODEL: frozenset({"posthog_code", "review_hog"}),
BASETEN_GLM53_FLASH_PUBLIC_MODEL: frozenset({"posthog_code", "review_hog"}),
@@ -474,16 +474,15 @@ def check_free_tier_model_access(
)
-# Models a caller may only select while the paired flag is enabled for them, mirroring
-# products/tasks MODEL_ACCESS_FLAGS. Each model maps to its own access flag — the same flag the
-# Desktop picker gates it behind — so an entitlement can't be widened for one model by proxy of
-# another. Keys are the model ids callers send.
-MODEL_ACCESS_FLAGS: Final[dict[str, str]] = {
- "moonshotai/kimi-k3": "tasks-kimi-k3",
- "deepseek-ai/deepseek-v4-flash-0731": "posthog-code-deepseek-model",
- "zai-org/glm-5.3": "posthog-code-glm-53-model",
- "zai-org/glm-5.3-flash": "posthog-code-glm-53-flash-model",
-}
+# Models a caller may only select while the paired flag is enabled for them, mirroring the
+# `access_flag` column of products/tasks/backend/model_catalog.py. Each model maps to its own
+# access flag, the same flag the Desktop picker gates it behind, so an entitlement can't be
+# widened for one model by proxy of another. Keys are the model ids callers send.
+#
+# Empty because no model is behind a rollout right now. Every gate here fails closed, so a model
+# stays listed here only while its rollout is live: an entry left behind after the flag reaches
+# everyone hides the model from any caller the flag service cannot answer for.
+MODEL_ACCESS_FLAGS: Final[dict[str, str]] = {}
def get_required_model_flag(model: str | None) -> str | None:
diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.py
index 192c718b66d8..d562556f15e4 100644
--- a/services/llm-gateway/tests/test_dependencies.py
+++ b/services/llm-gateway/tests/test_dependencies.py
@@ -406,7 +406,12 @@ class TestFreeTierModelGateWiring:
get_settings.cache_clear()
-class TestPreviewModelGateWiring:
+class TestModelAccessGateWiring:
+ # No model is behind a rollout flag now, so the gate is wired with a stand-in. Naming a
+ # real model here would tie these cases to a rollout that ends.
+ GATED_MODEL = "acme/gated-model"
+ GATED_FLAG = "acme-gated-model"
+
@pytest.fixture(autouse=True)
def billed_org(self):
with patch(
@@ -415,19 +420,30 @@ class TestPreviewModelGateWiring:
):
yield
- @pytest.mark.asyncio
- @pytest.mark.parametrize("flag_result", [False, None])
- async def test_preview_model_blocked_when_flag_off_or_unavailable(self, flag_result: bool | None) -> None:
- # flag_result=None is the eval-outage case: must fail closed (403), not fail open.
- request = _make_request({"model": "moonshotai/kimi-k3", "messages": []}, path="/posthog_code/v1/messages")
- user = _make_user(auth_method="oauth_access_token", user_id=7)
+ @pytest.fixture
+ def gate(self):
+ with patch(
+ "llm_gateway.dependencies.get_required_model_flag",
+ side_effect=lambda model: self.GATED_FLAG if model == self.GATED_MODEL else None,
+ ):
+ yield
+ def _gate_call(self, model: str):
+ request = _make_request({"model": model, "messages": []}, path="/posthog_code/v1/messages")
+ user = _make_user(auth_method="oauth_access_token", user_id=7)
runner = MagicMock()
runner.check = AsyncMock(return_value=ThrottleResult.allow())
+ return request, user, runner
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("flag_result", [False, None])
+ async def test_gated_model_blocked_when_flag_off_or_unavailable(self, gate, flag_result: bool | None) -> None:
+ # flag_result=None is the eval-outage case: must fail closed (403), not fail open.
+ request, user, runner = self._gate_call(self.GATED_MODEL)
with (
patch("llm_gateway.dependencies.ensure_costs_fresh"),
- patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=flag_result)),
+ patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=flag_result)) as flag,
):
with pytest.raises(HTTPException) as exc_info:
await enforce_throttles(request=request, user=user, runner=runner)
@@ -435,17 +451,17 @@ class TestPreviewModelGateWiring:
assert exc_info.value.status_code == 403
error = exc_info.value.detail["error"]
assert error["code"] == "model_gate"
- assert "moonshotai/kimi-k3" in error["message"]
+ assert self.GATED_MODEL in error["message"]
+ # Legacy PostHog Desktop clients route errors by substring; the "(rate_limit)" suffix
+ # sends this 403 to their usage-limit modal instead of their fatal-session teardown path.
assert error["message"].endswith("(rate_limit)")
assert error["reason"] == "model_not_available"
+ assert flag.await_args is not None
+ assert flag.await_args.args[0] == self.GATED_FLAG
@pytest.mark.asyncio
- async def test_preview_model_allowed_when_flag_enabled(self) -> None:
- request = _make_request({"model": "moonshotai/kimi-k3", "messages": []}, path="/posthog_code/v1/messages")
- user = _make_user(auth_method="oauth_access_token", user_id=7)
-
- runner = MagicMock()
- runner.check = AsyncMock(return_value=ThrottleResult.allow())
+ async def test_gated_model_allowed_when_flag_enabled(self, gate) -> None:
+ request, user, runner = self._gate_call(self.GATED_MODEL)
with (
patch("llm_gateway.dependencies.ensure_costs_fresh"),
@@ -455,90 +471,53 @@ class TestPreviewModelGateWiring:
flag.assert_awaited_once()
assert flag.await_args is not None
- assert flag.await_args.args[0] == "tasks-kimi-k3"
-
+ assert flag.await_args.args[0] == self.GATED_FLAG
-class TestBasetenExclusiveModelGateWiring:
- @pytest.fixture(autouse=True)
- def billed_org(self):
- with patch(
- "llm_gateway.dependencies.resolve_quota",
- AsyncMock(return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=True)),
- ):
- yield
-
- # Baseten-only models with no fallback aren't cleared for external rollout, so each is blocked
- # behind its own access flag (not the GLM Baseten routing flag).
@pytest.mark.asyncio
- @pytest.mark.parametrize(
- ("model", "access_flag", "path"),
- [
- (BASETEN_DEEPSEEK_PUBLIC_MODEL, "posthog-code-deepseek-model", "/posthog_code/v1/messages"),
- (BASETEN_GLM53_PUBLIC_MODEL, "posthog-code-glm-53-model", "/posthog_code/v1/messages"),
- (BASETEN_GLM53_FLASH_PUBLIC_MODEL, "posthog-code-glm-53-flash-model", "/posthog_code/v1/messages"),
- ],
- )
@pytest.mark.parametrize("flag_result", [False, None])
- async def test_baseten_exclusive_model_blocked_when_flag_off_or_unavailable(
- self, flag_result: bool | None, model: str, access_flag: str, path: str
+ async def test_unbilled_gated_model_gets_rollout_denial_before_billing_denial(
+ self, gate, flag_result: bool | None
) -> None:
- request = _make_request({"model": model, "messages": []}, path=path)
- user = _make_user(auth_method="oauth_access_token", user_id=7)
-
- runner = MagicMock()
- runner.check = AsyncMock(return_value=ThrottleResult.allow())
+ request, user, runner = self._gate_call(self.GATED_MODEL)
with (
+ patch(
+ "llm_gateway.dependencies.resolve_quota",
+ AsyncMock(return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=False)),
+ ),
patch("llm_gateway.dependencies.ensure_costs_fresh"),
- patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=flag_result)) as flag,
+ patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=flag_result)),
):
with pytest.raises(HTTPException) as exc_info:
await enforce_throttles(request=request, user=user, runner=runner)
- assert exc_info.value.status_code == 403
- assert exc_info.value.detail["error"]["code"] == "model_gate"
- assert flag.await_args is not None
- assert flag.await_args.args[0] == access_flag
+ error = exc_info.value.detail["error"]
+ assert error["reason"] == "model_not_available"
+ assert "payment method" not in error["message"].lower()
+ # The open-weights models run on the claude and pi harnesses and are offered to everyone.
+ # A gate left behind after a rollout finished rejected any caller the flag service could
+ # not answer for, which is what took these models away from non-staff accounts.
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "model", [BASETEN_DEEPSEEK_PUBLIC_MODEL, BASETEN_GLM53_PUBLIC_MODEL, BASETEN_GLM53_FLASH_PUBLIC_MODEL]
+ "model",
+ [
+ BASETEN_DEEPSEEK_PUBLIC_MODEL,
+ BASETEN_GLM53_PUBLIC_MODEL,
+ BASETEN_GLM53_FLASH_PUBLIC_MODEL,
+ "moonshotai/kimi-k3",
+ ],
)
- async def test_baseten_exclusive_model_allowed_when_flag_enabled(self, model: str) -> None:
- request = _make_request({"model": model, "messages": []}, path="/posthog_code/v1/messages")
- user = _make_user(auth_method="oauth_access_token", user_id=7)
-
- runner = MagicMock()
- runner.check = AsyncMock(return_value=ThrottleResult.allow())
+ async def test_open_weights_model_needs_no_flag_evaluation(self, model: str) -> None:
+ request, user, runner = self._gate_call(model)
with (
patch("llm_gateway.dependencies.ensure_costs_fresh"),
- patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=True)),
+ patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=False)) as flag,
):
await enforce_throttles(request=request, user=user, runner=runner)
- @pytest.mark.asyncio
- @pytest.mark.parametrize("flag_result", [False, None])
- async def test_unbilled_glm_gets_rollout_denial_before_billing_denial(self, flag_result: bool | None) -> None:
- request = _make_request({"model": BASETEN_GLM53_PUBLIC_MODEL, "messages": []}, path="/posthog_code/v1/messages")
- user = _make_user(auth_method="oauth_access_token", user_id=7)
- runner = MagicMock()
- runner.check = AsyncMock(return_value=ThrottleResult.allow())
-
- with (
- patch(
- "llm_gateway.dependencies.resolve_quota",
- AsyncMock(return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=False)),
- ),
- patch("llm_gateway.dependencies.ensure_costs_fresh"),
- patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=flag_result)),
- ):
- with pytest.raises(HTTPException) as exc_info:
- await enforce_throttles(request=request, user=user, runner=runner)
-
- error = exc_info.value.detail["error"]
- assert error["reason"] == "model_not_available"
- assert "payment method" not in error["message"].lower()
+ flag.assert_not_awaited()
class TestServerCredentialRequirementWiring:
diff --git a/services/llm-gateway/tests/test_models_api.py b/services/llm-gateway/tests/test_models_api.py
index 97107a0a6421..535caa3b4ce3 100644
--- a/services/llm-gateway/tests/test_models_api.py
+++ b/services/llm-gateway/tests/test_models_api.py
@@ -384,8 +384,11 @@ class TestFreeTierModelListing:
premium = by_id["claude-opus-4-5"]
assert premium["allowed"] is False
assert premium["restriction_reason"] == "paid_plan_required"
- # exact, not subset: the default free model must survive the allowlist
- assert {m["id"] for m in body["data"] if m["allowed"]} == {"@cf/zai-org/glm-5.2"}
+ # exact, not subset: every free-tier model must survive the allowlist
+ assert {m["id"] for m in body["data"] if m["allowed"]} == {
+ "@cf/zai-org/glm-5.2",
+ "deepseek-ai/deepseek-v4-flash-0731",
+ }
# codex reads the `models` mirror; the marks must be there too
assert body["models"] == body["data"]
@@ -397,10 +400,16 @@ class TestFreeTierModelListing:
def test_flag_gated_model_is_listed_only_when_its_flag_clears(
self, app, mock_db_pool, flag_enabled: bool | None, listed: bool
):
+ # No model is behind a rollout flag now, so one is gated here for the listing to have
+ # something to drop.
_wire_authenticated_user(mock_db_pool, "gated-user")
evaluate = AsyncMock(side_effect=lambda flag_keys, _: dict.fromkeys(flag_keys, flag_enabled))
with (
+ patch(
+ "llm_gateway.api.models.get_required_model_flag",
+ side_effect=lambda model: "acme-gated-model" if model == "claude-opus-4-5" else None,
+ ),
patch("llm_gateway.api.models.evaluate_flags", evaluate),
TestClient(app) as c,
):
@@ -409,9 +418,32 @@ class TestFreeTierModelListing:
assert response.status_code == 200
evaluate.assert_awaited_once()
body = response.json()
- assert ("deepseek-ai/deepseek-v4-flash-0731" in {m["id"] for m in body["data"]}) is listed
+ assert ("claude-opus-4-5" in {m["id"] for m in body["data"]}) is listed
assert body["models"] == body["data"]
+ # The listing drops a model whose flag cannot be evaluated, so a flag left behind after a
+ # rollout finished is what took the open-weights models off non-staff pickers.
+ def test_open_weights_models_are_listed_without_a_flag_evaluation(self, app, mock_db_pool):
+ _wire_authenticated_user(mock_db_pool, "open-weights-user")
+
+ evaluate = AsyncMock(side_effect=lambda flag_keys, _: dict.fromkeys(flag_keys, False))
+ with (
+ patch("llm_gateway.api.models.evaluate_flags", evaluate),
+ TestClient(app) as c,
+ ):
+ response = c.get("/posthog_code/v1/models", headers={"Authorization": "Bearer phx_open_weights_models"})
+
+ assert response.status_code == 200
+ evaluate.assert_not_awaited()
+ listed = {m["id"] for m in response.json()["data"]}
+ # Kimi K3 is Modal-served, and Modal is unconfigured here, so it is out of scope for
+ # a listing test.
+ assert {
+ "deepseek-ai/deepseek-v4-flash-0731",
+ "zai-org/glm-5.3",
+ "zai-org/glm-5.3-flash",
+ } <= listed
+
def test_billed_org_sees_full_list(self, app, mock_db_pool):
from unittest.mock import AsyncMock
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index 7150ec6931f5..91de1b3f6e2a 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -742,51 +742,56 @@ class TestServerCredentialConfigInvariant:
class TestModelAccessFlag:
+ # The open-weights models run on the claude and pi harnesses and are offered to every
+ # caller. Their rollout flags outlived the rollout, and the gate fails closed, so a
+ # caller the flag service could not answer for lost them.
@pytest.mark.parametrize(
- "model,gated",
+ "model",
[
- ("moonshotai/kimi-k3", "moonshotai/kimi-k3"),
- ("MoonshotAI/Kimi-K3", "moonshotai/kimi-k3"),
- (" moonshotai/kimi-k3 ", "moonshotai/kimi-k3"),
- ("deepseek-ai/deepseek-v4-flash-0731", "deepseek-ai/deepseek-v4-flash-0731"),
- ("DeepSeek-AI/DeepSeek-V4-Flash-0731", "deepseek-ai/deepseek-v4-flash-0731"),
- ("zai-org/glm-5.3", "zai-org/glm-5.3"),
- ("ZAI-Org/GLM-5.3", "zai-org/glm-5.3"),
- ("zai-org/glm-5.3-flash", "zai-org/glm-5.3-flash"),
- ("ZAI-Org/GLM-5.3-Flash", "zai-org/glm-5.3-flash"),
+ None,
+ "",
+ "gpt-5.2",
+ "claude-opus-5",
+ "@cf/zai-org/glm-5.2",
+ "moonshotai/kimi-k3",
+ "MoonshotAI/Kimi-K3",
+ " moonshotai/kimi-k3 ",
+ "deepseek-ai/deepseek-v4-flash-0731",
+ "DeepSeek-AI/DeepSeek-V4-Flash-0731",
+ "zai-org/glm-5.3",
+ "ZAI-Org/GLM-5.3",
+ "zai-org/glm-5.3-flash",
+ "ZAI-Org/GLM-5.3-Flash",
],
)
- def test_gated_model_requires_its_own_flag(self, model: str, gated: str):
- # each model resolves to its own dedicated access flag, not a shared one
- assert get_required_model_flag(model) == MODEL_ACCESS_FLAGS[gated]
+ def test_ungated_models_need_no_flag(self, model: str | None):
+ assert get_required_model_flag(model) is None
def test_every_gated_model_has_its_own_flag(self):
+ # An entitlement must not be widened for one model by proxy of another, and the GLM
+ # Baseten routing flag is not an entitlement at all.
flags = list(MODEL_ACCESS_FLAGS.values())
assert len(flags) == len(set(flags))
assert GLM_MODAL_FLAG not in flags
- @pytest.mark.parametrize("model", [None, "", "gpt-5.2", "claude-opus-5", "@cf/zai-org/glm-5.2"])
- def test_ungated_models_need_no_flag(self, model: str | None):
- assert get_required_model_flag(model) is None
-
- def test_suffixed_gated_model_ids_reach_no_backend(self):
- # Product allowlists prefix-match while the access-flag gate matches exactly, so a
- # suffixed id (e.g. zai-org/glm-5.3x) can pass the allowlist without a flag
- # evaluation. Routing exactness is the backstop that keeps such ids unserved; this
- # pins that invariant for every gated model. Literal vocabulary so a new gated
- # model is added here consciously.
- assert set(MODEL_ACCESS_FLAGS) == {
+ @pytest.mark.parametrize(
+ "model",
+ [
"moonshotai/kimi-k3",
"deepseek-ai/deepseek-v4-flash-0731",
"zai-org/glm-5.3",
"zai-org/glm-5.3-flash",
- }
- for gated_model in MODEL_ACCESS_FLAGS:
- suffixed = f"{gated_model}x"
- assert not is_inference_routed_model(suffixed)
- assert suffixed not in BASETEN_MODELS
- assert not is_modal_served_model(suffixed)
- assert suffixed not in CLOUDFLARE_ALLOWED_MODELS
+ ],
+ )
+ def test_suffixed_vendor_model_ids_reach_no_backend(self, model: str):
+ # Product allowlists prefix-match, so a suffixed id (e.g. zai-org/glm-5.3x) passes the
+ # allowlist while naming a model nobody serves. Routing exactness is what keeps such
+ # an id unserved.
+ suffixed = f"{model}x"
+ assert not is_inference_routed_model(suffixed)
+ assert suffixed not in BASETEN_MODELS
+ assert not is_modal_served_model(suffixed)
+ assert suffixed not in CLOUDFLARE_ALLOWED_MODELS
class TestSignalsApplicationIsolation: