Skip to content

bug: ctx.run() silently allows double-invocation #54

Open

Description

@shloimy-wiesel

Summary

Calling ctx.run(work) twice on the same context schedules two _safe tasks. The first runs and finishes the stream; the second hits _finished=True inside write_text, has the resulting exception swallowed by _safe's except branch (because self.is_finished is already true, the error event is suppressed), and exits silently — no error event, no exception, no warning.

Repro

import asyncio
from ai_sdk_stream_python import StreamContext

async def main():
    ctx = StreamContext()
    async def work(c):
        await c.write_text("A")
        await c.finish()
    await ctx.run(work)
    await ctx.run(work)        # silently does nothing useful
    async for chunk in ctx.stream():
        print(repr(chunk))

asyncio.run(main())

Only one stream's worth of events appears. The second run() call's failure is invisible.

Why this matters

A handler that calls ctx.run twice (retry path, refactor mistake) sees no error — work just doesn't happen, and the user can't tell why their second piece of work was lost. Loud failure here would prevent a class of confusing bugs.

Related to #45, which is about the misleading run() return type — same family of "API surface should make misuse impossible" concerns, but a distinct fix.

Proposed fix

Track _run_called: bool on StreamContext (in addition to the existing _task ref). In run(), raise RuntimeError("ctx.run() has already been called on this StreamContext; create a new StreamContext per request") on the second invocation.

Workflow (required for fix)

Per repo convention:

  1. Add a failing test that calls ctx.run() twice and asserts the second raises (must fail on main).
  2. Apply the fix.
  3. Verify the new test passes; full suite + pyright stay green.

Acceptance

  • Failing repro test added.
  • Second run() call raises RuntimeError with a message that names the cause.
  • Existing test_run_* tests still pass unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugSomething isn't working

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions