Skip to content

Requirements from campaign-continuity: what a Workers-AI-only, governed app needs from llm-providers #136

Open

Description

@stackbilt-admin

Who is asking, and why

campaign-continuity is a Cloudflare Worker that keeps a tabletop campaign's record for a game master (GM) and their family. It pins @stackbilt/[email protected] exactly and uses Workers AI only (its ADR-0007), because campaign text is family data and shouldn't go to more vendors. Today it runs three GM-only tasks (its ADR-0011): quick help at the table, prep ideas, and setup from a description, which extracts entities, facts, links and holdings for the GM to review. Its roadmap adds live Q&A with streaming (M12), extraction from session notes (M13), and recaps (M14).

The app treats model output as untrusted: every response is checked against a per-task allowlist, validated, and reviewed by a person before anything is saved. That works, but it currently rests on workarounds for gaps in this package. This issue collects what the app needs, in priority order, so the package can serve it without them. Each need lists the gap, the app's current workaround, and acceptance criteria. Existing issues are linked rather than restated.

Measured on Workers AI (2026-11-06 unless noted)

Small samples, one call per setting unless noted, through 1.23.0:

Model Task Result
@cf/openai/gpt-oss-20b Extraction-style prompt, ~900 input tokens, temperature 0.2 and 0.6 Reasoning looped, repeating one line until max_tokens 8,000; empty message, finishReason: 'length', 85–104 s
@cf/openai/gpt-oss-20b Same, temperature 0.8 Valid JSON, 44 s, 6,103 output tokens
@cf/openai/gpt-oss-120b Same, temperature 0.8 Valid JSON; 25 s, 26 s, 40 s, 46 s, 60 s and 76 s across six calls of ~3,300–4,200 output tokens
@cf/meta/llama-3.3-70b-instruct-fp8-fast Any SchemaDriftError (#130), unusable
@cf/zai-org/glm-5.3-flash Prep ideas, 1,500-token cap (2026-11-05) Whole budget spent reasoning on both attempts, no JSON, 62 s
GLM-5.3 Flash and gpt-oss-20b Extraction on 2k-token notes (2026-10-31, n=40 each) p95 56.5 s and 50.1 s; 9 of 40 gpt-oss outputs invalid after one repair

The pattern: reasoning models spend the output budget invisibly, throughput varies 3× between identical calls, and the caller can't see or steer either.

Needs

1. Control and account for reasoning (P1)

2. Truthful model capabilities, per model (P1)

  • Gap: the catalog doesn't let the app plan a call: context window, maximum output tokens, whether reasoning counts against output, which response_format kinds really work, whether streaming reports the served model. Some catalog entries are unverified (fix(catalog): verify vendor model IDs and prices and remove fabricated defaults #112).
  • Workaround: the app hard-codes budgets, e.g. a 24,000-character packet (about 6k tokens) and per-task maxTokens, and finds limits by failing live.
  • Acceptance:
    • getModelCapabilities(model) returns contextWindow, maxOutputTokens, reasoning: 'none' | 'always' | 'controllable', reasoningCountsAgainstOutput, structuredOutput: 'none' | 'instruction' | 'json_object' | 'json_schema', streaming, and verifiedAt with a source.
    • A request whose input estimate plus maxTokens passes the window fails before the call, with a typed error.

3. Token estimates before the call (P2)

  • Gap: the app builds context packets (campaign records, then the newest events and notes first, within a fixed budget) and splits long user text into parts, but it can only count characters.
  • Acceptance: estimateTokens(model, text | messages), documented as an estimate with its error bound, so packets and splits are sized in tokens, not characters.

4. Structured output that is real or honestly degraded (P1)

  • Gap: json_schema is silently dropped on Workers AI, and the route plan reports no degradation (Workers AI silently drops json_schema while the route plan reports no degradation #127).
  • Workaround: json_object plus the schema in the prompt, Zod on every row, and one repair attempt, all in the app.
  • Acceptance:
    • Where Workers AI supports response_format: json_schema for a model, it is sent.
    • Where it isn't supported, the response says structuredOutput: 'instruction_only', so the caller knows to validate.
    • Never a silent drop.

5. A deadline the package actually enforces (P1)

  • Gap: timeout doesn't bind non-streaming Workers AI calls (Provider timeout is silently ignored on non-streaming Workers AI calls #131), and the binding can't be aborted, so a call past the app's deadline still runs and costs money.
  • Workaround: a Promise.race against the app's own deadline, while the call keeps running.
  • Acceptance:
    • timeout and an AbortSignal are honoured on every Workers AI path.
    • Where Cloudflare can't cancel the underlying run, the response or error says so (cancelled: false), and cost accounting includes the abandoned call.

6. Exactly the model asked for, and proof of it (P1)

7. Degenerate output detection (P2)

  • Gap: a looping generation burns the whole budget and deadline before the caller learns anything.
  • Acceptance: an opt-in guard, for streamed or chunked output, that stops a generation repeating the same span N times. It ends with finishReason: 'repetition' and reports the tokens used. Sampling guidance per model, such as "gpt-oss loops below temperature ~0.7 on long structured output", is recorded in the catalog.

8. Parallel calls without surprises (P2)

  • Gap: the app now reads a long description as several calls at once. Workers AI rate and concurrency limits aren't exposed, and a 429 or capacity error isn't distinguishable from a model failure.
  • Acceptance:
    • A typed error taxonomy: timeout, rate_limited with retryAfter, capacity, schema_drift, invalid_request, model_unavailable, content_filtered.
    • Messages never echo the prompt or output.
    • An optional per-client concurrency limit.

9. Telemetry the app can store without campaign text (P2)

  • Gap: the app logs task, model, outcome, attempts, ms and tokens itself, and must never log prompts or output (test(resilience): add transport fault contracts and make telemetry unable to replay requests #116).
  • Acceptance:
    • An onCallComplete hook with provider, served model, latency, time to first token, input, reasoning and output tokens, finish reason, cost and costProvenance, and retries.
    • It is structurally unable to include message content.
    • Cost covers reasoning tokens and abandoned calls.

10. Streaming fit for a Worker (P3, for M12)

Not needed

  • Multi-provider fallback: the app forbids it.
  • Response caching: the app requires it off.
  • Tool calling: not used.

Related

#95, #110, #112, #113, #116, #127, #128, #130, #131, #133, #135.

Activity

  1. stackbilt-admin commented on Nov 8, 2026

    @stackbilt-admin
    MemberAuthor

    Long-context and output limits (audit 2026-11-08)

    This expands the "Gap" item above ("the catalog doesn't let the app plan a call: context window, maximum output tokens…") with what the code does today on main (1.25.0).

    What's right. Context windows in the catalog match Cloudflare's model pages for the long-context Workers AI models: DeepSeek V4 Flash / V4 Pro and GLM-5.3 / 5.3 Flash (1,048,576), Kimi K2.6 / K2.7 Code (262,144), GLM-4.7 Flash (131,072). @cf/meta/llama-3.3-70b-instruct-fp8-fast is 24,000, per its page (not 128k). DeepSeek V4.1 Flash (1M) is being added in #144.

    Gaps

    1. The context window isn't a routing constraint. Pool eligibility (model-catalog.ts) checks vision, tools and structured output, but not estimated input tokens against maxContextLength. The only check is a warning in getGatewayRoutePlan. A 200k-token request can be routed, or fall back, to a 24k or 128k model. The overflow then comes back as InvalidRequestError / TokenLimitError, neither of which falls back, so the request fails instead of moving to a model that fits.
    2. No output-limit metadata. ModelCapabilities has no maximum-output field. When maxTokens is unset, the Cloudflare adapter sends no max_tokens, so Workers AI's per-model default applies: 256 on Llama 3.3 70B Fast, per its page. Long summaries are cut off silently; lengthCause reports it only afterwards. DeepSeek V4 / V4.1 also mark max_tokens deprecated in favour of max_completion_tokens.
    3. The token estimate is coarse. Input tokens are estimated as characters ÷ 4. That's fine for cost estimates, but too rough to enforce a window near 1M or for non-Latin text.
    4. Long-context selection. inferUseCaseFromRequest switches to LONG_CONTEXT at 20,000 characters or maxTokens >= 4000. Kimi K2.7 Code (262k) isn't tagged LONG_CONTEXT.

    Proposed scope (additive)

    • Treat estimated input + requested output as a hard requirement during selection and fallback: skip models whose maxContextLength can't fit it, and raise NoRouteError when none can. This is the "long context checked through fallback" item on fix(api): preserve canonical identity and make route planning match dispatch #113.
    • Add optional maxOutputTokens (and a documented default) to ModelCapabilities, from each model's page, so callers can plan a call and the adapter can warn when the default would truncate.
    • Let callers pass an exact input token count when they have one, instead of the estimate.

    No live or billable requests were made for this audit.

  2. stackbilt-admin commented on Nov 8, 2026

    @stackbilt-admin
    MemberAuthor

    Correction to gap 1 in the audit above. I wrote that a context overflow comes back as an error that "doesn't fall back, so the request fails". That's wrong for the default config. The built-in fallback rules end with a catch-all error rule, so an InvalidRequestError / TokenLimitError from an overflow already falls back to the next provider. The overflow only ends the request when the caller sets fallbackRules: [] (or uses allowFallback: false).

    So the real cost of routing a request to a model that's too small is one wasted call, which may be billed or rate-limited, not a failed request. Skipping that call also means the skipped provider can't absorb a transient failure of the provider that fits, so it isn't a clear win for every caller.

    Because of that, #147 makes the check opt-in: contextWindowRouting: true skips providers whose planned model can't hold the estimated input (recorded as CONTEXT_WINDOW in fallback.failedAttempts). With the option unset, dispatch is the same as before. The always-on part of #147 is a better input estimate that counts tool calls and tool results.

    The rest of the audit (output limits, the Workers AI 256-token default, max_completion_tokens) is unaffected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions