Skip to content

fix(py): keep inline use=[...] instances, type middleware kwargs, and stop mid-stream retries - #86

Merged
huangjeff5 merged 12 commits into
mainfrom
fix/py-1.0-pr6b-middleware-instances-resilience
Nov 13, 2026
Merged

huangjeff5 merged 12 commits into
mainfrom
fix/py-1.0-pr6b-middleware-instances-resilience

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Genkit keeps caller-instantiated middleware instances instead of rebuilding them from JSON config, stops Retry and Fallback once chunks have already streamed to the client, and types middleware constructors.

# --- BEFORE ---
# 1. Instantiated middleware with custom __init__ crashed on turn 1
guard = SecretGuard(re.compile(r'SECRET_[0-9]+', re.IGNORECASE), audit_client)
await ai.generate(prompt='Show key', use=[guard])
# => TypeError: SecretGuard.__init__() missing 2 required arguments (rebuilt via cls(config=...))

# 2. Retrying after chunks already streamed yielded duplicate responses into the client stream
#    Client SSE received: "Paris is the cap" -> [error] -> "Paris is the capital of France."
#    Resulting in: "Paris is the capParis is the capital of France."

# 3. Untyped constructors allowed typos to pass type checkers and fail at runtime
Retry(max_retry=3)
# => Passed pyright/ty; failed at runtime with TypeError: unexpected keyword argument

# 4. Defining legacy 0.12 hooks was silently ignored
class LegacyGuard(Middleware):
    async def model(self, req, ctx, next_fn): ...
# => 0.13 runtime looks for wrap_model; LegacyGuard was never executed

# 5. String fallback models dropped caller's temperature and max_output_tokens
await ai.generate(prompt='hi', config={'temperature': 0.2}, use=[Fallback(models=['googleai/gemini-2.5-flash'])])
# => Fallback model ran with default config {} instead of temperature 0.2


# --- AFTER ---
# 1. Caller's instance is retained via shallow copy per generate call; regexes and clients survive
guard = SecretGuard(re.compile(r'SECRET_[0-9]+', re.IGNORECASE), audit_client)
res = await ai.generate(
    model='googleai/gemini-2.5-flash',
    prompt='Show key',
    use=[Retry(max_retries=3), guard],
)
print(res.text)
# => [blocked]

# 2. Mid-stream retries and fallbacks are halted once chunks reach the client
#    If provider drops mid-stream, the error raises immediately; duplicate partial responses are prevented

# 3. Shipped middleware constructors declare typed keyword parameters
Retry(max_retry=3)
# => Type checker error: Unexpected keyword argument "max_retry" for "Retry" (suggests max_retries)

# 4. Deprecated 0.12 hook names fail fast at class definition time
class LegacyGuard(Middleware):
    async def model(self, req, ctx, next_fn): ...
# => TypeError: LegacyGuard defines hook 'model'. In 0.13+, rename to 'wrap_model(self, params, ctx, next_fn)'.

# 5. String backups in Fallback inherit caller's portable config parameters
# => Fallback model inherits temperature=0.2 from caller's config

Main Changes

  • Retain caller-instantiated middleware instances via shallow copy: Previously, _compile_middleware discarded passed middleware instances and called cls(config=...), which crashed any custom middleware requiring __init__ arguments and dropped non-JSON state (clients, compiled regex flags). We now retain a shallow copy (copy.copy(instance)) per generate call, preserving constructor state while isolating per-call mutations.
  • Halt retry and fallback once chunks reach the client: Previously, when streaming (generate_stream), if an attempt failed after chunks had already been sent over SSE, Retry and Fallback triggered a new attempt, appending a second response to the partial first response in the client's stream. Middleware now monitors ctx.on_chunk and immediately aborts retry/failover if chunks were already emitted.
  • Typed keyword constructors on built-in middleware: Previously, built-in middleware (Retry, Fallback, Filesystem, Skills, ToolApproval) accepted raw untyped **kwargs, allowing typos to pass static type checking and fail only at runtime. All constructors now declare explicit typed keyword arguments (Retry(max_retries=3)).
  • Fast-fail on deprecated 0.12 hook definitions: Previously, custom guardrails defining legacy 0.12 hook names (async def model(...) without wrap_model) were silently skipped by the 0.13+ runtime. Defining such a class now raises TypeError immediately at class definition time with instructions to use wrap_model.

@huangjeff5
huangjeff5 added this pull request to stack #88 November 11, 2026 02:37
@huangjeff5 huangjeff5 changed the title fix(py): keep inline use=[...] instances, type middleware kwargs, and stop mid-stream retries fix(py)!: keep inline use=[...] instances, type middleware kwargs, and stop mid-stream retries Nov 11, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #88 November 11, 2026 06:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr6b-middleware-instances-resilience branch from 47719f5 to be59650 Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 added this pull request to stack #89 November 11, 2026 06:23
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr6b-middleware-instances-resilience branch from be59650 to 3a3b6df Compare November 11, 2026 16:21
@huangjeff5 huangjeff5 changed the title fix(py)!: keep inline use=[...] instances, type middleware kwargs, and stop mid-stream retries fix(py): keep inline use=[...] instances, type middleware kwargs, and stop mid-stream retries Nov 11, 2026
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr6b-middleware-instances-resilience branch from 3a3b6df to 9bd4843 Compare November 11, 2026 17:31
@huangjeff5
huangjeff5 removed this pull request from stack #89 November 11, 2026 18:06
@huangjeff5
huangjeff5 changed the base branch from fix/py-1.0-pr6-devui-middleware-mcp to fix/py-1.0-pr6-middleware-sandbox November 11, 2026 18:37
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr6b-middleware-instances-resilience branch from 9bd4843 to 06c4e79 Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #103 November 11, 2026 18:40
Base automatically changed from fix/py-1.0-pr6-middleware-sandbox to main November 11, 2026 18:40
- use=[Mw(...)] ran a fresh cls(config=...) rebuilt from serialized
  config: custom __init__ crashed, __init__ state reset, re.Pattern lost
  its flags (SECRET bypassed an IGNORECASE guard), Callable config fields
  raised PydanticSerializationError. The call's child registry now keeps
  the caller's instance and the per-call copy is a shallow copy.copy.
  MiddlewareRef serialization stays for traces and the Dev UI.
- A Middleware subclass defining 0.12 model()/generate()/tool() without
  the matching wrap_* raises TypeError at class definition instead of
  becoming a silent no-op.
…ks commit

- A string Fallback entry inherits the caller's config narrowed to keys
  the backup's config class accepts (portable generation keys when it
  has none), instead of {} wiping max_output_tokens/temperature. Matches
  JS (entry.config ?? req.config). version/extra never carry over.
- Retry and Fallback no longer retry or fail over once the failed
  attempt streamed chunks to the caller, which spliced a second answer
  onto partial JSON in ChunkAccumulator.
…ueue

The engine now shallow-copies middleware per generate(), so a reused
Filesystem instance shared one _message_queue across calls. One request's
read_file contents could be injected into a concurrent request's next turn.
…ool/generate

_reject_legacy_hooks raised on any plain method named model, generate or
tool, so a helper like def tool(self, name) broke class definition. Reject
only an async def with self plus three positional params.
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr6b-middleware-instances-resilience branch from 06c4e79 to 5957719 Compare November 11, 2026 18:40
@huangjeff5
huangjeff5 requested a review from apascal07 November 12, 2026 07:49
@huangjeff5
huangjeff5 merged commit e365812 into main Nov 13, 2026
20 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-1.0-pr6b-middleware-instances-resilience branch November 13, 2026 17:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants