DeepTutor icon indicating copy to clipboard operation
DeepTutor copied to clipboard

[Feature Request]: Detect lack of effective progress and recover a known provider response before recreating it

Open Scarffe opened this issue 3 weeks ago • 6 comments

Do you need to file a feature request?

  • [x] I have searched the existing feature request and this feature request is not already filed.
  • [x] I believe this is a legitimate feature request, not just a question or bug.

Feature Request Description

Problem

A provider connection can remain alive while no new answer, reasoning, tool arguments or state transition arrives. Transport heartbeats alone should not make a turn appear productive indefinitely. Where a provider can retrieve the original operation, a bounded same-operation lookup could obtain its completed result without creating another generation.

This is a request for progress semantics and provider-capability-based recovery, not a claim that every long silent reasoning call has stalled or that all compatible gateways support retrieval.

Existing behavior inspected

At dev@60fb3bdfddb30b7740c7ce3bd9b28d908f2af6db:

  • Python OpenAICompatProvider.chat_stream wraps each Responses iterator read in a 90-second timeout. Each returned event starts another read deadline.
  • The TypeScript sse parser similarly bounds each byte read; SSE comments are ignored after the read succeeds. This is useful transport protection but does not measure meaningful generation progress.
  • Worker restart recovery in #2035 and browser reconnect work such as #1668 address different ownership/transport boundaries. This proposal should reuse their durable-turn owner rather than create a second turn store. Reasoning-output-budget recovery in #2384 is also separate.

Synthetic reproduction

Run the existing TypeScript sse function against an in-memory stream emitting only : synthetic keepalive\n\n every 5 ms. Set its read-idle timeout to 20 ms and observe for 100 ms. The iterator remains waiting despite yielding zero semantic events. Abort it afterward.

Tested with Node.js 24.15.0. Save the following as reproduce_sse.mjs and run node --experimental-strip-types reproduce_sse.mjs /path/to/DeepTutor against the recorded upstream checkout. It uses an in-memory stream and compressed test timeouts, with zero network/model requests. This proves the read-idle contract only, not live-provider or full application recovery.

/* Synthetic transport-only repro. No network, model request or account data. */
import assert from 'node:assert/strict';
import { setTimeout as sleep } from 'node:timers/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const checkout = process.argv[2];
assert(checkout, 'Pass the path to a clean DeepTutor checkout');
const { sse } = await import(pathToFileURL(path.resolve(checkout, 'packages/chat-engine/src/providers/sse.ts')));

let timer;
let heartbeats = 0;
const abort = new AbortController();
const body = new ReadableStream({
  start(controller) {
    timer = setInterval(() => {
      heartbeats++;
      controller.enqueue(new TextEncoder().encode(': synthetic keepalive\n\n'));
    }, 5);
  },
  cancel() { clearInterval(timer); },
});
const pending = sse(body, abort.signal, 20).next();
try {
  const result = await Promise.race([
    pending.then(() => 'ended', () => 'failed'),
    sleep(100).then(() => 'still_waiting'),
  ]);
  assert.equal(result, 'still_waiting');
  assert(heartbeats >= 5);
  console.log(JSON.stringify({ transport_only: true, read_idle_ms: 20,
    observation_ms: 100, heartbeats, semantic_events: 0, result,
    network_requests: 0, model_requests: 0 }));
} finally {
  abort.abort(new Error('Synthetic observation complete'));
  clearInterval(timer);
  await pending.catch(() => {});
}

Proposed bounded scope

  1. Track transport liveness separately from effective progress. Only newly observed native content, reasoning/tool-argument bytes or meaningful operation-state changes reset progress. Comments, keepalives, duplicate events and repeated sequence numbers do not advance the content cursor.
  2. At an agreed progress deadline, use a bounded status/result lookup only when the adapter supports it and a confirmed operation ID is bound to the current account, provider configuration and turn. Keep local limits on reading, querying, closing and cancellation. Do not increase model/context/output budgets.
  3. If the original operation completed, reconcile missing output and usage with the existing turn. Preserve tool-call identity and saved write receipts; do not replay successful grading or other tool writes. If it remains pending, wait within the shared recovery allowance and then publish an explicit recoverable pause.
  4. An unknown create outcome without an ID must not trigger a blind replacement. Cancellation, changed provider/account settings, inaccessible/expired results and uncertain writes need explicit handling. Retain cancellation intent if remote cancellation cannot be confirmed; do not claim the remote job stopped.
  5. A paused summary or grading call must not continue into a fresh teaching step or become a learner error. The existing retry owner should decide the next action. Providers without same-operation retrieval keep an honest unsupported/uncertain state.

Store only the necessary private recovery state under existing ownership and retention rules, recheck permissions on reopen, and keep credentials/raw payloads out of the browser, issues and Git. Lookup costs and retention windows are provider-specific; this proposal does not promise free queries or permanent recovery.

Related broader tracking: #1940. This request is limited to provider-stream progress and same-operation recovery.

Suggested implementation order and acceptance

  • First agree on the shared effective-progress signal and pause outcome for both engines.
  • Then add one explicitly supported same-operation adapter, with synthetic tests for comments/duplicate events, completed/pending/failed/unknown results, read/query/close timeouts, cancellation, changed configuration and late events.
  • Verify a completed known response is reused without another create, duplicate retry cannot repeat a write, and unsupported adapters cannot silently resubmit. Use synthetic workspaces; real-provider acceptance, if performed later, should report create/retrieve counts and its exact provider scope.

Would maintainers support this separation and a small provider-specific first slice, or prefer a different owner/API boundary?

Related Module

API/Backend

Use Case

A tutoring or grading turn should not appear to progress indefinitely merely because a gateway keeps sending heartbeats. If the provider supports retrieval of a confirmed operation, reuse its completed result before considering replacement, while preserving saved tool writes and learner evidence.

Additional Context

Prepared with AI assistance and reviewed against the recorded upstream source. The included reproduction uses only synthetic in-memory data, with zero network/model requests or learner data. This proposes a bounded first slice for maintainer discussion.

Scarffe avatar Nov 09 '26 05:11 Scarffe

I'd like to take a minimal slice of this: the SSE parser ignores comments (keepalives) after each successful read, so a stream that emits only : keepalive resets the read deadline forever while producing zero semantic events — the turn looks productive without being one. I'll add a semantic-progress signal (track the last meaningful event, not the last byte) with a warning when only keepalives arrive for a sustained window, plus regression tests using the issue's synthetic repro. The 90s transport deadline itself is left alone; provider-side retrieval/recovery stays out of scope for this slice.

ZQR1101 avatar Nov 09 '26 08:11 ZQR1101

Withdrawing my claim after a closer look: the TypeScript sse.ts referenced here lives in packages/chat-engine/, which is not part of this repository, and on the Python side the OpenAI SDK's stream iterator already drops SSE comment lines (keepalives) before yielding events — so the "pure keepalives reset the deadline forever" failure mode doesn't exist in this repo's code path. The remaining progress-semantics + provider-retrieval recovery is a cross-repo design proposal, not a bounded fix I should silently land. Better discussed with maintainers first.

ZQR1101 avatar Nov 09 '26 08:11 ZQR1101

Thanks for checking this and for clarifying the Python SDK behavior. You are right that, in the tested Python Responses path, SSE comment-only keepalives are filtered by the SDK before they become events. In my synthetic test with openai-python 2.8.1, repeated comments did not renew DeepTutor’s next-event deadline, and the stream eventually timed out.

I also checked the repository at the commit referenced in this issue. The TypeScript package is present there: sse.ts and package.json. Its TypeScript-native path is experimental and opt-in, so this result should not be generalized to the default Python path.

For that TypeScript parser, a synthetic stream of comment-only heartbeats kept the per-read deadline from expiring while yielding no data events. As a control, the parser timed out when bytes stopped arriving.

Separately, I tested the Python Responses path with repeated synthetic response.in_progress events. Each event renewed the next-event deadline, while no content, reasoning, or tool callbacks were produced. This demonstrates a distinction between receiving an SDK event and making semantic progress, but I have not established that a real provider sends this sequence or that a production deployment stalls in this way.

All of these were synthetic tests with shortened timeouts and no external model requests. I have not tested the proposed warning implementation or full application recovery. A small semantic-progress signal or warning could be discussed separately from retrieval and recovery behavior.

Scarffe avatar Nov 09 '26 10:11 Scarffe

Correcting my withdrawal above: packages/chat-engine/ is in this repository at 60fb3bd — both sse.ts and package.json exist. I checked the contents API at that commit; @Scarffe's links are right and my claim was wrong.

That makes my second claim too broad as well. Reading sse.ts at that commit: each loop iteration races reader.read() against a fresh idleMs timer, and a : keepalive line is neither blank nor data:, so it is dropped without yielding — but the read already resolved, so the next iteration arms a new timer. Comment-only heartbeats do hold that per-read deadline open, as Scarffe reported. What survives from my withdrawal is narrower: on the default Python path the OpenAI SDK filters comment lines before they become events, so keepalives alone don't reproduce there.

Re-claiming a bounded slice on the Python Responses path, using Scarffe's response.in_progress reproduction instead of keepalives. chat_stream wraps every stream_iter.__anext__() in asyncio.wait_for(..., timeout=90), so any SDK event restarts the deadline. I reproduced it locally against the 1.7.2 wheel matching tip 60fb3bd: lifecycle-only frames followed by a normal answer complete with the answer intact and nothing logged — the turn looked productive for the whole silent stretch.

The slice only makes that distinction visible:

  • semantic progress = content / reasoning / tool-argument deltas and provider output items, taken from the callbacks consume_sdk_stream already dispatches, so there is no second event-type list to drift
  • one warning per silent stretch, naming elapsed seconds and the last event type, re-armed by real output
  • reporting only: the 90s transport deadline, the stream stalled error path, retries and the terminal result are untouched. Shortening a deadline or recovering a provider response is a product decision, not something I should land quietly.

Scope: the Responses branch of OpenAICompatProvider.chat_stream only. The chat/completions loop and the experimental TypeScript parser are left alone.

Per Scarffe's own caveats, this is synthetic evidence: neither of us has shown a real provider emitting that sequence, and a warning does not recover a stalled turn — it stops the silence from being invisible.

PR incoming with red/green tests.

ZQR1101 avatar Nov 11 '26 05:11 ZQR1101

Thanks for revisiting this and putting together the PR! I appreciate you taking the time to reproduce the issue and clarify the two paths.

Scarffe avatar Nov 11 '26 06:11 Scarffe

Fixed on local dev (3166cda2061a2157abfb819dd575b71cfb417d0c). fix(llm): bound effective progress and recover known responses. Synthetic acceptance: one create/one retrieve, prefix reconciliation, duplicate sequence and tool identity, pending/failed/unknown outcomes, bounded read/query/close, ownership changes and cancellation. Official stored OpenAI Responses only; default store=false is unchanged. No automatic replacement; active-call recovery only, not reopening after restart. 76 native engine tests passed; Python LLM/workspace/book combined suite 1477 passed/1 skipped and final boundary recheck 55 passed. No paid/live model requests.

will be fixed in the next releases!

pancacake avatar Nov 14 '26 17:11 pancacake