Skip to content

Slow toolset Start() blocks conversation turns unboundedly; RAG file watcher's context gets cancelled by the startup probe #4001

Closed

Description

@steilerDev

Summary

Two related bugs make a slow Startable toolset (in our case, a RAG toolset doing a large incremental reindex) both (a) silently and permanently break its own background maintenance work, and (b) turn a cosmetic 30s startup warning into an unbounded hang on the very next user turn.

Bug 1 — the turn-critical path has no start timeout, unlike the startup sidebar path

EmitStartupInfo bounds each toolset's Start() call with a 30s deadline via startToolsetWithTimeout (pkg/runtime/runtime.go:1920), racing the call against the timeout in a goroutine+select. When it fires, the abandoned Start() keeps running in the background — by design, per the comment on startToolsetWithTimeout — holding StartableToolSet's single-flight lock (pkg/tools/startable.go:88, a plain sync.Mutex, not context-aware).

But Agent.Tools() (pkg/agent/agent.go:402-403), which every conversation turn calls to gather the tool list, goes through ensureToolSetsAreStarted (pkg/agent/agent.go:550) → toolSet.Start(ctx) with no timeout at all. If the toolset's original Start() is still running (because it exceeded the 30s sidebar deadline), this call blocks on the mutex until that original call finishes — which can be well past 30s, well past the deadline that was supposedly enforced. The 30s bound in startToolsetWithTimeout protects only the sidebar display; it does not protect the actual message-sending path, so a toolset that's merely slow (not stuck) still causes a real, unbounded hang on the user's next message.

Suggested fix: apply the same bounded-timeout wrapper to ensureToolSetsAreStarted's Start() calls, and when a toolset isn't ready in time, proceed with the tools available so far (skip that toolset for this turn) instead of blocking.

Bug 2 — a toolset's background watcher can inherit a context that gets cancelled out from under it

rag.ToolSet.Start() (pkg/tools/builtin/rag/rag.go:93-99) spawns its background file watcher using the same ctx passed into Start:

func (t *ToolSet) Start(ctx context.Context) error {
	...
	if err := t.manager.Initialize(ctx); err != nil { ... }
	go func() {
		if err := t.manager.StartFileWatcher(ctx); err != nil { ... }
	}()
	return nil
}

On the common startup path, that ctx is the bounded startCtx created in startToolsetWithTimeout (pkg/runtime/runtime.go:1924):

startCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

defer cancel() fires as soon as startToolsetWithTimeout returns — which is normal and expected for the one-shot Initialize() call, but the file-watcher goroutine captured the same startCtx, so its background reindexing dies the moment that deferred cancel fires, and never comes back (there's no restart/refresh of the watcher's context afterward). Since StartableToolSet.Start is single-flight and only calls the underlying Start() once per process, the watcher never gets a second chance at a longer-lived context.

Observed directly in a debug log from a real session (paths lightly genericized):

level=WARN msg="Embedding input builder failed; falling back to raw chunk content" strategy=semantic-embeddings path=~/.tampa/runtime/agent/tampa-knowledge/systems/snowflake.md chunk_index=1 error="error receiving from semantic generation stream: context canceled"
... (repeated for chunk_index 0,2,3,4,5,6)
level=ERROR msg="Failed to re-index file" path=~/.tampa/runtime/agent/tampa-knowledge/systems/snowflake.md error="failed to generate embeddings: batch 1 failed: failed to create embeddings: context canceled"
level=ERROR msg="Failed to cleanup orphaned documents" error="failed to collect files: context canceled"

This happened well into the session (long after the [RAG Manager] Initialization complete log line), triggered by a live file edit — i.e. the watcher was already dead by the time it tried to act, and every subsequent live edit to that KB silently fails to index for the rest of the process's life. The backlog only gets cleared on the next full Initialize() — i.e. the next relaunch/new session — which combined with Bug 1 means that next relaunch can block the first message for however long the accumulated backlog takes to reindex.

Suggested fix: give the file watcher (and any other long-lived background work started from inside Start()) an independent, process-scoped context — e.g. context.WithoutCancel(ctx), mirroring the pattern already used elsewhere in the codebase for MCP connectors that need to detach from a short-lived caller context.

Repro sketch

  1. Configure a rag toolset with type: semantic-embeddings (or any Startable toolset whose Initialize/Start can take >30s on a cold or large-delta index).
  2. Launch, and let the startup sidebar probe time out ("... is taking too long to start (>30s)").
  3. Edit one of the indexed files while the session is running. Observe the background reindex attempt fail with context canceled once the sidebar probe's startCtx deadline has passed.
  4. Send a message before the original Start() call has returned: the turn hangs with no user-visible indication of why, well past the 30s the sidebar implied.

Environment

  • docker-agent commit: 8003b634c0068ee95cdf599fdbada22b3e715275

Activity

  1. added theissue type on Aug 18, 2026
  2. added
    area/rag
    area/runtime
    area/tools
    on Aug 18, 2026
  3. aheritier commented on Aug 20, 2026

    @aheritier
    Collaborator

    Thanks for the detailed reproduction. A proposed fix should address the lifecycle and user-visible contract together:

    • Update stale references in the issue/implementation notes. Please anchor references to symbols such as startToolsetWithTimeout, ensureToolSetsAreStarted, StartableToolSet.Start, and rag.ToolSet.Start rather than line numbers or snippets that may drift. The relevant code should be rechecked against the current branch before implementation.
    • Define degraded behavior explicitly. A toolset that is unavailable, still starting, or whose required dependency fails must not block the turn indefinitely. The caller should receive the tools that are ready, while the unavailable toolset is omitted and a concise, actionable warning is surfaced (including the toolset and dependency/error where useful). Avoid implying that a partially available toolset provides tools it cannot reliably execute.
    • Bound startup from the caller’s perspective. Both the startup probe and turn-critical tool discovery should use a finite timeout. The timeout must return control to the caller, while caller cancellation and runtime shutdown must take precedence and propagate promptly. Do not rely on a timeout wrapper to stop an underlying non-context-aware Start(); document and contain that behavior, and ensure later calls cannot wait unboundedly on it.
    • Fix the RAG watcher lifecycle deliberately. The watcher must outlive the short-lived startup-probe context so a probe timeout does not permanently disable live indexing. It must nevertheless stop on ToolSet.Stop() and runtime shutdown. Use an explicitly owned, cancellable lifecycle context (and cancellation/Wait or equivalent shutdown coordination), rather than broadly detaching work with context.WithoutCancel and risking a goroutine that survives the runtime.
    • Keep the change scoped. Do not make broad implicit changes to all background work or alter unrelated toolset startup semantics. Apply the lifecycle and timeout contract only where the ownership and shutdown behavior are clear.

    For reproducibility, please add a deterministic test toolset whose Start() blocks past the configured timeout, plus a cancellation-aware variant and a failing-dependency variant. Also add a RAG watcher test using a controllable manager/context that verifies activity continues after the probe context expires and stops after ToolSet.Stop()/runtime shutdown.

    Acceptance criteria:

    1. A slow or stuck toolset cannot block a conversation turn beyond the documented timeout.
    2. Ready tools remain usable; unavailable tools are omitted and produce one clear warning with actionable failure information.
    3. Caller cancellation and runtime shutdown terminate startup and background work promptly.
    4. RAG live watching survives startup-probe timeout but is fully stopped during normal toolset/runtime shutdown.
    5. Tests cover timeout, cancellation, dependency failure/warnings, partial availability, watcher lifetime, and shutdown, and pass with task test, task lint, and task build.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/ragarea/runtimearea/tools

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions