unsloth/studio/backend/storage/research_runs_db.py
alkinun 502730bbba
Studio: add Deep Research (#7219)
* Studio: add durable Deep Research workflows

* Studio: preserve research integration after upstream updates

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: keep research worker compatible with Python 3.11

* Studio: address Deep Research lifecycle review

* Studio: preserve durable research recovery

* Studio: preserve research stream and context

* Studio: harden research sources and limits

* Studio: align research with shared chats

* Studio: guard durable research actions

* Studio: protect durable research turns

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: deepen durable research decisions

* Studio: protect research prompts and queries

* Studio: slim research stream deltas

* Studio: preserve research evidence and citations

* Studio: harden Deep Research (CI, prompt injection, query PII, config, citations)

- Fix backend CI: add research_runs_router to the synthetic routes stub in
  test_desktop_auth so studio.backend.main imports under the health-check test.
- Escape prompt-delimiter tags in the decision and synthesis prompts so gathered
  web/document content cannot close an <untrusted_...> wrapper and inject
  instructions into the local planner/decision/synthesis model.
- Extend the public-query sanitizer to redact Luhn-valid payment cards, phone
  numbers, non-global IPs, and labeled private identifiers before a query can
  reach web search.
- Reject nested credential keys in inferenceRequest and ragScope, not just
  top-level keys, when persisting a durable run config.
- Treat maxSources as one budget shared across web and document sources
  (collection and resume paths) instead of per type, which allowed up to 2x the
  configured cap.
- Preserve document citations whose filename contains a closing bracket by
  tokenizing valid citations before stripping invalid ones.
- Persist Deep Research off when switching to an external model and when enabling
  Web Fetch so a refresh cannot rehydrate a mutually-exclusive state.
- Add regression tests for the query, prompt, citation, and config hardening.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: make the research claims table migration atomic

The owner-scoped to global claims migration ran its RENAME, CREATE, INSERT and DROP in autocommit, so an interruption after CREATE left the new table empty, orphaned the rows in the legacy table, and never re-triggered. Wrap the rebuild in an explicit transaction so a crash rolls back cleanly and the migration re-runs on the next boot.

* Studio: block message edits and regeneration during an active research run

After a reload a durable research run is followed by the research store rather than an assistant-ui run, so thread.isRunning is false while research is still active. Message edit, refresh and the edit composer previously gated only on isRunning, which let a normal generation start alongside the running research run. Gate them on the active thread's research state as well.

* Studio: keep the plan review mounted through approval

Keying PlanReview on planRevision remounted it mid-approve when updateResearchPlan bumped the revision, resetting the local pending flag and re-enabling Start research while the approve was still in flight, which allowed a duplicate approve. Key on runId only.

* Studio: drop the redundant deep-research persistence change

setCheckpoint already persists Deep Research off for external models at the top of the function, so the added saveBool was a duplicate, and clearing Deep Research from setWebFetchToolsEnabled guarded a state that is not reachable (Deep Research is local-model only while the Web Fetch pill is external-provider only). Revert both to the pre-hardening version.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: harden Deep Research citations, query privacy, and message protection

Address review findings in the Deep Research backend:

- Escape an unbalanced ")" in citation destinations so a source URL cannot
  close the markdown link early and inject a second link, keeping balanced
  parentheses literal.
- Match raw-URL citations on whole tokens so a URL sharing another URL's
  prefix is no longer partially rewritten.
- Redact non-global IPv6 addresses in public search queries, matching the
  existing IPv4 handling.
- Detect credential key names after normalizing case and separators so nested
  openaiApiKey, accessToken, and clientSecret values cannot be persisted.
- Reject client edits to server-managed research prompts and reports at the
  storage layer; only the internal writers pass allow_research_update.
- Scope research searches to the first allowed domains instead of dropping
  site scoping for large allow lists.
- Persist the same fetch evidence bound used during live synthesis so a
  resumed run is not shortened.
- Scope run completion so it only replaces this run's message parts.

Add regression tests for the above.

* Studio: fix Deep Research SSE framing, source counts, and favicon privacy

- Normalize the whole SSE buffer so a CRLF split across transport chunks
  still frames events.
- Count web and document sources together in the activity header so a
  RAG-only run is not shown as zero sources.
- Cap the plan editor at the run's configured maxSteps instead of a
  hard-coded 30.
- Add an allowRemoteIcons opt-out to the sources components and disable
  third-party favicon requests for research sources so visited domains are
  not leaked.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: address final Deep Research review findings

* Studio: fit Deep Research synthesis evidence to loaded context, add opt-in web grounding

Size the synthesis evidence budget to the loaded model context so the prompt is not
silently truncated on small contexts. When the evidence overflowed the window the report
degenerated (it echoed the evidence tail instead of writing); the budget now reserves tokens
for the prompt scaffolding and converts the remainder to chars, keeping the full cap when the
context is unknown.

Add opt-in web grounding for auto-read: read the top search results, ingest them into an
ephemeral RAG scope, hybrid-retrieve the passages most relevant to the question with the
existing knowledge-base retriever, and fold those chunks into the step evidence. The scope is
per call and deleted afterwards, so a user's knowledge base is never touched.

Off by default; enable with UNSLOTH_RESEARCH_AUTO_SCRAPE=1. Gated per run by
budgets["maxAutoScrape"], so runs created without it keep legacy snippet-only behavior, and
grounding is skipped when the loaded context is too small for the prompt.

Add tests for the adaptive evidence budget, scraped-text cleaning, the ephemeral web-RAG
retrieval and scope cleanup, and the auto-read evidence path.

* Studio: read Deep Research synthesis context from the inference orchestrator

Make the adaptive synthesis-evidence budget actually engage in the normal Studio
architecture. _loaded_context_length read core.inference.inference, the low-level backend that
lives in the model subprocess and stays unpopulated in the main web process where the research
supervisor runs, so it returned None and the budget silently fell back to the 32000 character
cap (leaving the report exposed to the truncation this was meant to fix). Read the inference
orchestrator instead, and the llama.cpp backend for GGUF, mirroring
routes.inference._monitor_context_length so the budget sizes to the context the API layer
serves. Verified on a running server: at a 12288 token load the probe now reports 12288 and the
budget adapts to 24576 characters instead of the 32000 fallback.

Also:
- Reserve context for the generated report as well as the prompt scaffolding (raise the reserve
  to 4096 tokens) so evidence does not crowd out the output on a small window.
- Honor a numeric UNSLOTH_RESEARCH_AUTO_SCRAPE by passing the per-run maxAutoScrape as the page
  cap to the scraper, instead of always reading the maximum.
- Guard the web-RAG connection acquisition so a get_connection failure returns the documented
  empty result rather than propagating.
- Add a synthesis-context test that patches the real backend accessor (not the probe itself) so
  the production wiring is exercised, plus a scrape page-cap test.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: harden Deep Research query redaction and research autosave

- research_runs: extend the opaque-token allowlist so unlabeled Hugging
  Face (hf_) and GitLab (glpat-) tokens are redacted before a query can
  reach web search, without over-redacting public model or version ids.
- runtime-provider: for a server-managed research message, echo the
  backend-stored metadata verbatim on autosave. Merging the client
  metadata re-added client-only fields the server never persisted, so the
  server-side guard saw a diff and rejected every streamed or snapshot
  update with 409.

* Studio: keep composer tool pills always accessible after merge

The merge left the composer line marked always-expanded (data-expanded
"true") while the inner pill row was still gated behind composerExpanded,
so the Search and Code toggles disappeared once the permission mode was
"off" with no other toggle set. Render the primary tool pills
unconditionally, matching the always-expanded layout, and drop the now
unused composerExpanded and permissionMode locals. Fixes the Chat UI
Playwright check that asserts the Search and Code pills stay visible.

* Studio: update Deep Research composer contract to always-expanded layout

The always-expanded composer no longer routes effectiveDeepResearchEnabled
through a composerExpanded expression, so the frontend contract now checks
that it gates the Deep Research composer button render instead.

* Studio: do not bind a research run to a populated assistant reply

create_run adopted any assistant message under the user turn whose
researchRunId was unset, including a prior answer reused by a retry. On
completion _update_assistant drops the untagged text and source parts, so
that answer was silently overwritten. Only bind to an empty placeholder or
this run's own message, and reject a reply that already carries content.

* Studio: harden Deep Research synthesis budget, prompt shielding, and message protection

- research_runs: split the synthesis evidence budget evenly across notes so a
  small context still keeps a slice of every research step instead of dropping
  the later steps after the earliest ones fill the budget.
- research_runs: shield the research question and approved plan before placing
  them in the decision and synthesis prompts, so a closing delimiter in either
  cannot escape its block and inject sibling sections.
- research_runs: redact bearer authorization tokens from public search queries.
- studio_db: include attachments in the research-message change check and guard
  direct attachment deletion, so server-managed research prompts and responses
  cannot be mutated through the attachment paths.
- chat_history: map the protected-message conflict on attachment deletion to 409.

* Studio: strip invalid document citations that contain brackets

The invalid-citation regex stopped at the first closing bracket, so a
citation whose filename contained brackets left its tail (".pdf, p. 9]") in
the report. Match a balanced bracketed span so the whole invalid citation is
removed; valid citations stay protected by the earlier tokenization pass.

* Studio: free the RAG search slot when a lookup times out or is cancelled

The bounded knowledge-base search held the sole admission slot in a detached
worker until the search returned, so a lookup that outlived its timeout (a
stalled embedding or blocked vector call) kept the slot forever and starved
every later lookup, disabling knowledge-base retrieval globally. Release the
slot from the caller when it stops waiting, exactly once, so a detached worker
finishes without re-holding it.

* Studio: remove Websites label from research composer

* Studio: fix Deep Research review findings (RAG slot bound, orphaned workers, hardening)

- Bound the shared RAG search slot to one running worker. The search that is
  doing the embedding/index/GPU work now owns the admission slot until it
  finishes, instead of freeing it on caller timeout while the detached worker
  keeps running, which let a second search enter and stack concurrent work
  behind the capacity-of-one semaphore.
- Cancel active research runs before deleting their thread, project, or all
  history. Deleting cascade-drops the run row, but the worker only notices at
  its next lease check, so it could keep doing model/web/RAG work for a run
  that no longer exists; signalling cancel first shortens that window.
- Shield the planner prompt's conversation and question with _shield_untrusted,
  matching the decision and synthesis prompts, so untrusted text cannot forge
  planner delimiters.
- Do not let a research key-revocation failure replace a successful
  non-streaming completion; log it like the streaming path does.
- Include created_at in the protected research-message guard so a client cannot
  reorder server-managed prompt/response messages while leaving the body intact.
- Reject non-scalar ragScope values; a nested container evades the
  sensitive-key scan when its inner keys are unlisted and would reach retrieval
  code that expects a scalar scope id.

Adds regression tests for each.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: remove research composer globe icon

* Studio: use Hugeicons telescope in research composer

* Studio: use Telescope02 icon in research composer

* Studio: standardize Deep Research telescope icons

* Studio: move Deep Research below web and code tools

* Studio: merge grounded page excerpts with search snippets instead of replacing

When auto-scrape grounding retrieved page-body chunks, it replaced the raw
search-result text for that step. If the retrieved chunk was a distractor or
dropped the key fact, the answer-bearing search snippet was lost and grounded
runs regressed below snippet-only accuracy on factual questions (e.g. returning
Apache 2.0 instead of the Qwen License, 403 instead of 404, or a single mirror
diameter instead of the sum).

Keep the search snippets and append the grounded excerpts as supplementary
evidence via a small _merge_scraped_evidence helper. Grounding stays opt-in and
off by default, so legacy runs are unchanged. Adds regression tests.

* Studio: fix stale website access assertion in Deep Research contract test

The dialog heading was renamed to a DialogTitle, so the contract test still
asserted a <span>Websites</span> that no longer exists and failed on every
branch built on this one. Assert the current heading instead.

* Add AGPL-3.0 SPDX header to the two new test files for PR #7219

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix citation loss, effort clamping and nested inferenceRequest for PR #7219

Three review findings, each with a regression test that fails without the fix.

Citation dropped for a bare URL in prose parentheses. _RAW_URL swallows the
closing paren and the old trim set only stripped ".,;:!?", so the catalog
lookup missed and the validator deleted the whole citation, leaving an
unbalanced "(" in the report. New _trim_url_tail follows GFM extended autolink
path validation: one right-to-left pass that interleaves punctuation and
unmatched-")" trimming. Both rules must run in the same loop, else
"https://x/y.)" keeps a stray dot. Balanced parens inside a URL
(Wikipedia-style) still survive. Output verified against cmark-gfm on nine
cases, including "https://x/foo)bar)" which must keep ")bar".

Research runs forwarded reasoningEffort unclamped. The local chat path clamps
to the loaded model's advertised levels; the research branch did not, and the
backend only validates enum membership, so llama.cpp dropped a level the model
lacks and the whole durable run silently fell back to the template default.
Now uses the same helper and the same levels as normal chat. Note this makes
"max" on a gpt-oss low|medium|high model resolve to "low" rather than falling
through to the template default, matching normal chat exactly; the divergence
between the two paths was the bug.

Nested inferenceRequest values were persisted. Every allowed field is a scalar
and the numeric/bool/enum ones reject a container while coercing, but "model"
is stringified with str(), which never raises, so {"auth": "sk-..."} slipped
past the sensitive-key scan ("auth" is not on the list) into the durable run
config as the model id. Mirrors the ragScope guard already in this PR.

Verified: 542 passed across the research/web/sandbox/chat-history backend
suites, frontend contract 10 passed, tsc --noEmit clean.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix report-stalling regex, uncataloged KB evidence and bracketed titles for PR #7219

Catastrophic backtracking in _DOCUMENT_CITATION. The alternation
(?:[^\[\]]+|\[[^\[\]]*\])* backtracks exponentially on an unterminated
"[Document:" with no later bare "]", which is ordinary malformed model output
and exactly what this sanitizer exists to handle. Runtime quadrupled every two
characters; one realistic 76-char line did not finish in 90s. It runs
synchronously inside async _research (the line below it uses asyncio.to_thread),
so a single bad report pins the event loop and stalls all of Studio, not just
the run. Replaced with the language-equivalent unrolled form, verified identical
on well-formed inputs including bracketed filenames, and linear: a 20,000-char
tail now takes 0.4ms. Not using possessive quantifiers or atomic groups, which
need Python 3.11 while this package declares >=3.9.

Uncataloged knowledge base evidence reached synthesis. When maxSources is
already full, every returned chunk hits the continue, so accepted_rag_sources
stays empty, the "if accepted_rag_sources" rebuild no-ops and rag_result keeps
the raw KB text. That text has no document_source_catalog entry, so the
validator strips any citation to it and synthesis is left building claims on
private KB chunks it cannot attribute. Cleared, gated on rag_sources so a
text-only KB reply is still passed through. The resume branch built rag_evidence
from all restored sources with the same hole, so it now mirrors the live loop.

Bracketed source titles destroyed their own citation. The catalog gave the model
the raw title while the citation writer stripped brackets. Search titles
routinely carry one ("[PDF] Annual Report"), and the prompt tells the model to
copy the title verbatim, producing a label the validator cannot match. Both
sides now share _citation_title.

Verified: 756 passed across the research/web/sandbox/chat-history/rag backend
suites. Each fix has a regression test that fails without it.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep a durable run alive when no model is loaded for PR #7219

A durable run is claimable within the supervisor's poll interval of startup
(main.py starts it in the lifespan, and claim_next takes any 'running' run whose
lease expired), Studio has no startup model auto-load, and the browser is not
connected yet. So restarting Studio mid-run reliably lands the next model call
on the local endpoint's HTTP 400 "No model loaded". That 400 is not retryable:
_completion retries only >= 500, and _stream_completion, which serves both
planning and synthesis, has no retry at all. The run is marked failed, and the
only recovery is retry, which sets report_text NULL and deletes every
research_plan_step, research_source and research_document_source. Up to an hour
of scraping and synthesis is lost on a plain restart, on the feature whose whole
point is surviving one.

Treat only that refusal as transient: wait up to the run's own
modelTimeoutSeconds for a model to come back, then re-send. Any other 400 still
fails immediately, so no behaviour changes on the happy path. The wait polls
_check_active, so cancellation and lease loss are still honoured, and the model
probe fails open, so a probe error can only send a request, never withhold one.
Each wait is bounded by the run timeout and the number of waits per call is
capped, so a model that keeps disappearing cannot re-send forever.

Deliberately not pinning or restoring the model, which the review comment also
suggested. Auto-switch is opt-in, default off, and GGUF-only, so restoring
would silently evict the model the user just loaded from a background worker,
and comparing the configured name to the loaded id is fragile across variant
suffixes and advertised aliases, so it would break working runs.

Verified: 853 passed across the research/web/sandbox/chat-history/rag/inference
backend suites. Eight of the nine new tests fail without the fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make website-policy search reach the whole allowlist and refill past blocks for PR #7219

Two review findings on the website access policy.

Domains past the site: filter cap were undiscoverable. The policy accepts up to
100 allowed domains and the prompt tells the model all of them are searchable,
but scope_search_query always scoped to allowed[:8], so a source in the ninth or
later domain could never be found, and an undiscovered URL cannot be fetched
either. The cap itself is right, search engines stop honouring long OR chains,
so the window now rotates by a hash of the query instead of being a fixed head.
Every allowed domain is reachable across a multi-step run, the same query is
always scoped the same way, and lists at or under the cap are unchanged.

A page of blocked results returned nothing. The policy filters after the search
while DDGS was asked for exactly max_results candidates, so if those happened to
be disallowed the tool reported no results even when valid ones ranked just
below, wasting a research step. Ask for a deeper pool when a policy is set and
stop at max_results allowed entries. No policy means no over-fetch, so ordinary
searches are unchanged.

Verified: 2324 passed across the research/web/sandbox/chat-history/rag/tool
backend suites. The 8 test_studio_api.py failures are pre-existing and need live
OpenAI/Anthropic credentials; they fail identically with these changes stashed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only overfetch search results when the website policy restricts for PR #7219

Follow-up to 8be0b3699. Every run stores normalize_website_policy(...), which
returns {"allowedDomains": [], "blockedDomains": []} and is truthy even when
nothing is restricted, so the default unrestricted path asked DDGS for four
times as many results on every step. That is pure added latency and timeout
risk, since the filter passes everything and only max_results entries are
returned either way. Test the domain lists rather than the dict.

* Budget the whole research prompt against the loaded context for PR #7219

Only the synthesis evidence was budgeted, so the budget could not prevent the
overflow it existed to prevent.

Measured at head with a realistic prompt (40-source catalog, 12-step plan): the
untrimmable scaffolding is about 7,900 chars and the conversation context adds
up to 12,000 more. On a 4096-token context, which is the GGUF auto-fit floor and
the transformers default, the synthesis request came to about 1.7x the window.
Worse, _synthesis_evidence_budget computed usable_tokens = 0 at or below the
4,096-token reserve and then returned the 1,500-char floor anyway, so it added
evidence to a prompt that already did not fit. The decision prompt had no
context awareness at all: a fixed evidence[-60000:], roughly ten times a small
window, on every step rather than once at the end.

Overflow is not cosmetic here. It either silently truncates and degenerates the
report, as the comment above these constants already warned, or fails the run,
and a failed run is only recoverable via retry, which deletes every plan step,
source and document source and nulls the report.

Both paths now share _prompt_char_budget plus _trimmable_budget: each trimmable
section is measured against what the rest of the prompt leaves, and can reach 0
instead of a floor, because a shorter report beats a destroyed run. Evidence is
budgeted before the chat history, since the evidence is the report. Unknown
context still keeps the full cap.

At 4096 tokens the synthesis prompt now fits (0.6x). Below that it is still
over, since a 40-source catalog alone exceeds the window; that needs a smaller
maxSources, and the context box does accept values down to 128.

test_synthesis_evidence_budget_tracks_loaded_context asserted the old floor at
2048 tokens, which is the bug, so it now asserts 0 and that the rest of the
prompt counts against the same budget.

Verified: 2325 passed across the research/web/sandbox/chat-history/rag/tool
suites. The test_mcp_stdio_sessions failure is pre-existing and fails
identically with these changes stashed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scope replayed research history to its own attempt for PR #7219

A retry deletes the previous attempt's research_plan_steps, research_sources
and research_document_sources rows but keeps its events, and the SSE route
attaches one live run snapshot to every event it emits, replayed history
included. The step.completed payload carries only position, title, action,
input and sourceCount, so that snapshot is the sole source of the excerpt and
evidence.

On any refresh after a retry, a replayed attempt-0 step was therefore matched
against attempt-1's step row by position alone, and start_position resets to 0
after the delete, so the positions line up exactly. The preserved attempt-0
activity then showed attempt-1's excerpt and evidence, or lost them entirely
when attempt 1 had not yet reached that position, under a banner that says
previous activity is preserved. The run.started resumed branch read the same
cross-attempt snapshot and spliced those activities out.

Both are gated on the event's attempt matching the snapshot's retryCount, which
is the same attempt scoping get_reasoning_text already applies server-side. The
excerpt and evidence fall back to what the activity already holds, so a mismatch
is non-destructive rather than blanking it.

Verified: frontend contract 11 passed, tsc -b exit 0, and the new test fails
without the store change.

* Retry pre-stream failures in the research stream for PR #7219

_stream_completion serves planning, every decision step and synthesis, and it
had no transport retry: a connection error or a 5xx raised before any response
byte failed the durable run, and retry then deletes every gathered source,
document source and plan step. _completion already treats the identical
failures on the identical endpoint as retryable, so the two paths disagreed.

This is partly a hole my own 689b06535 opened. After the no-model 400 the body
is read, the connection returns to the pool, and _wait_for_local_model then
sleeps for up to modelTimeoutSeconds before re-sending on the same client.
Uvicorn's keep-alive is 5s, so that pooled connection is essentially always
server-closed by then, and losing the has_expired race raises
RemoteProtocolError, killing the run the wait existed to save. Also reachable
via a read timeout waiting for headers under prompt-eval load.

Retrying is safe only because nothing has been consumed at that point, and that
is structural rather than a convention: with stream=True httpx returns on the
response headers without calling aread(), and raise_for_status() reads no body,
both verified against the installed 0.28.1. The handler is scoped to the inner
try that ends at break, and _iter_stream_lines sits outside the loop with no
path back to send, so a re-send cannot duplicate report text.

Bounded and mirrors _completion: same >= 500 predicate, same 3 attempts, same
2**attempt backoff, lease and cancellation re-checked before re-sending. The
transport counter and the model-wait counter are independent, so they cannot
multiply. The response is closed before every re-send, as manual stream mode
requires.

Note HTTPStatusError is not a TransportError in httpx, so both are caught
explicitly.

Verified: 2330 passed. Five of the new tests fail without the fix; the three
that pass either way are the invariants that must not change (fail fast on a
real 400, never retry once the report has streamed, existing model-wait path).

* Bound the planning prompt to the loaded context for PR #7219

Completes dc16598a4, which budgeted the decision and synthesis prompts but left
planning unbounded. The question reaches the planner verbatim (a pasted document
arrives here as-is) and the history is capped only at the fixed 12,000 chars,
so on a small context planning could overflow before any plan was persisted,
failing the run without doing any research at all.

Same helpers as the other two paths. The question is budgeted before the
history, since the question is the request.

A test now asserts all three prompt paths hold their own context budget, so a
fourth path cannot be added later without one.

Verified: 2331 passed; the new test fails without the change.

* Keep prompt inputs non-empty and fit the source catalog for PR #7219

Two follow-ups to the prompt budgeting, the first a regression I introduced in
dc16598a4.

The output reserve was a flat 4096 tokens, so on any context at or below that,
including the documented 4096-token GGUF floor, the whole prompt budget came out
as 0. Every trimmable section then sliced to nothing: planning_question became
the empty string, so the planner never saw the request at all, and synthesis
dropped all its evidence. Removing the old floor outright went too far; an empty
prompt is worse than the overflow it was avoiding. The reserve is now capped at
half the window, and the question and the evidence each keep a floor, since one
carries the request and the other carries the answer. A truncated completion is
recoverable, a confidently empty report is not.

The source catalog was the one section still inserted whole. It holds up to
maxSources entries with snippets persisted at up to 4000 chars each, so on a
smaller context it alone could exceed the budget while the code responded only
by zeroing the evidence and history. It is now fitted first, dropping whole
entries from the tail rather than slicing mid-entry, because a half-truncated
URL is worse than an absent one: the validator would strip it and the claim
would be left uncited.

Verified: 2333 passed. All three new tests fail without the change; the question
now keeps 1072 chars at a 2048-token context and 4144 at 4096, where both were
previously 0.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten Deep Research comments for PR #7219

Post-convergence comment pass over the 40 source files in the PR diff, limited
to lines the PR itself adds so untouched upstream code in the same files is left
alone. 15 files, 110 insertions, 141 deletions.

The reduction is deliberately small. Almost every comment here records why
something non-obvious is done, a measured result, a spec rule, or the exact bug
it prevents, and those are worth more than the lines they cost, so nearly every
edit is a same-meaning compression rather than a deletion. Kept in full: the GFM
autolink citation for the URL trim, the catastrophic-backtracking note on
_DOCUMENT_CITATION, the prompt-budget notes recording that a reserve at or above
the context leaves nothing, the two measured site: filter findings, and the
remount note on the activity panel key.

Verified comment-only three ways: comment_tools.py reports 15/15 code-unchanged,
and an independent ast.dump comparison with docstrings stripped shows zero of the
12 Python files differing. 421 backend tests and the 11 frontend contract tests
pass, and the phrase the contract test asserts on is still present on one line.

* Harden Deep Research model streams

* Fit Deep Research decision prompts

* Preserve Deep Research follow-up context

* Redact composite credentials from research queries

* Scale Deep Research UI typography

* Address Deep Research refinement review

* Harden Deep Research refinement edge cases

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <unslothai@gmail.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
2026-07-26 23:36:02 -07:00

1228 lines
42 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Transactional durable state for inline Deep Research runs."""
from __future__ import annotations
import hashlib
import json
import sqlite3
import threading
import time
from typing import Any
from core.inference.web_access_policy import check_url_access
from storage.studio_db import get_connection
ACTIVE_STATUSES = frozenset(
{"planning", "awaiting_approval", "queued", "running", "paused", "cancelling"}
)
TERMINAL_STATUSES = frozenset({"cancelled", "completed", "failed"})
ALL_STATUSES = ACTIVE_STATUSES | TERMINAL_STATUSES
_EVENTS_CHANGED = threading.Condition()
class ResearchConflictError(RuntimeError):
pass
def now_ms() -> int:
return int(time.time() * 1000)
def canonical_plan(plan: dict[str, Any]) -> tuple[str, str]:
raw = json.dumps(plan, sort_keys = True, separators = (",", ":"), ensure_ascii = False)
return raw, hashlib.sha256(raw.encode("utf-8")).hexdigest()
def _loads(value: str | None, fallback: Any) -> Any:
if value is None:
return fallback
try:
return json.loads(value)
except (TypeError, ValueError):
return fallback
def _event_locked(conn: sqlite3.Connection, run_id: str, event_type: str, data: dict) -> int:
row = conn.execute(
"SELECT next_event_seq, retry_count FROM research_runs WHERE id = ?", (run_id,)
).fetchone()
if row is None:
raise KeyError(run_id)
seq = int(row["next_event_seq"])
created = now_ms()
event_data = dict(data)
event_data.setdefault("attempt", int(row["retry_count"]))
conn.execute(
"INSERT INTO research_events (run_id, seq, event_type, data_json, created_at) "
"VALUES (?, ?, ?, ?, ?)",
(run_id, seq, event_type, json.dumps(event_data, ensure_ascii = False), created),
)
conn.execute(
"UPDATE research_runs SET next_event_seq = ?, updated_at = ? WHERE id = ?",
(seq + 1, created, run_id),
)
return seq
def _commit_event(conn: sqlite3.Connection) -> None:
conn.commit()
with _EVENTS_CHANGED:
_EVENTS_CHANGED.notify_all()
def _worker_can_write_locked(
conn: sqlite3.Connection, run_id: str, worker_id: str, statuses: set[str]
) -> bool:
row = conn.execute(
"SELECT status, lease_owner, lease_expires_at, cancel_requested "
"FROM research_runs WHERE id = ?",
(run_id,),
).fetchone()
return bool(
row is not None
and row["lease_owner"] == worker_id
and row["status"] in statuses
and not bool(row["cancel_requested"])
and row["lease_expires_at"] is not None
and int(row["lease_expires_at"]) >= now_ms()
)
def append_event(run_id: str, event_type: str, data: dict[str, Any]) -> int:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
seq = _event_locked(conn, run_id, event_type, data)
_commit_event(conn)
return seq
except Exception:
conn.rollback()
raise
finally:
conn.close()
def append_worker_event(
run_id: str, worker_id: str, event_type: str, data: dict[str, Any]
) -> int | None:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
if not _worker_can_write_locked(
conn,
run_id,
worker_id,
{"planning", "running"},
):
conn.commit()
return None
seq = _event_locked(conn, run_id, event_type, data)
_commit_event(conn)
return seq
except Exception:
conn.rollback()
raise
finally:
conn.close()
def create_run(
*,
run_id: str,
owner_subject: str,
thread_id: str,
user_message_id: str,
assistant_message_id: str | None,
config: dict[str, Any],
created_at: int | None = None,
) -> dict:
created = created_at or now_ms()
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
try:
conn.execute(
"INSERT INTO research_thread_claims (owner_subject, thread_id, created_at) "
"VALUES (?, ?, ?)",
(owner_subject, thread_id, created),
)
except sqlite3.IntegrityError as exc:
claim = conn.execute(
"SELECT 1 FROM research_thread_claims WHERE thread_id=?",
(thread_id,),
).fetchone()
if claim is not None:
raise ResearchConflictError("This thread already has a Deep Research run") from exc
raise
if assistant_message_id:
message = conn.execute(
"SELECT * FROM chat_messages WHERE id=?", (assistant_message_id,)
).fetchone()
metadata = {
"researchRunId": run_id,
"researchStatus": "planning",
"researchPlanRevision": 0,
"serverManaged": True,
}
if message is None:
conn.execute(
"""INSERT INTO chat_messages
(id, thread_id, parent_id, role, content_json, metadata_json, created_at)
VALUES (?, ?, ?, 'assistant', '[]', ?, ?)""",
(
assistant_message_id,
thread_id,
user_message_id,
json.dumps(metadata, ensure_ascii = False),
created,
),
)
conn.execute(
"UPDATE chat_threads SET updated_at=MAX(COALESCE(updated_at, created_at), ?) "
"WHERE id=?",
(created, thread_id),
)
else:
existing_metadata = _loads(message["metadata_json"], {})
existing_run_id = (
existing_metadata.get("researchRunId")
if isinstance(existing_metadata, dict)
else None
)
# Only bind to an empty placeholder or this run's own message: an untagged
# reply carries text/source parts that _update_assistant drops on completion,
# so binding one silently overwrites an existing answer.
existing_answer = any(
isinstance(part, dict)
and (
(part.get("type") == "text" and (part.get("text") or "").strip())
or part.get("type") == "source"
)
and part.get("researchRunId") is None
for part in _loads(message["content_json"], [])
)
if (
message["thread_id"] != thread_id
or message["role"] != "assistant"
or message["parent_id"] != user_message_id
or existing_run_id not in (None, run_id)
or (existing_run_id is None and existing_answer)
):
raise ResearchConflictError(
"Assistant message does not match this research run"
)
merged_metadata = (
dict(existing_metadata) if isinstance(existing_metadata, dict) else {}
)
merged_metadata.update(metadata)
conn.execute(
"UPDATE chat_messages SET metadata_json=? WHERE id=?",
(json.dumps(merged_metadata, ensure_ascii = False), assistant_message_id),
)
conn.execute(
"""
INSERT INTO research_runs
(id, owner_subject, thread_id, user_message_id, assistant_message_id,
status, config_json, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 'planning', ?, ?, ?)
""",
(
run_id,
owner_subject,
thread_id,
user_message_id,
assistant_message_id,
json.dumps(config, ensure_ascii = False),
created,
created,
),
)
_event_locked(conn, run_id, "run.created", {"status": "planning"})
_commit_event(conn)
except Exception:
conn.rollback()
raise
finally:
conn.close()
return get_run(run_id, owner_subject)
def _row_to_run(row: sqlite3.Row) -> dict[str, Any]:
data = dict(row)
return {
"id": data["id"],
"ownerSubject": data["owner_subject"],
"threadId": data["thread_id"],
"userMessageId": data["user_message_id"],
"assistantMessageId": data["assistant_message_id"],
"status": data["status"],
"plan": _loads(data["plan_json"], None),
"planRevision": data["plan_revision"],
"planHash": data["plan_hash"],
"config": _loads(data["config_json"], {}),
"cancelRequested": bool(data["cancel_requested"]),
"retryCount": data["retry_count"],
"error": data["error_message"],
"report": data.get("report_text"),
"createdAt": data["created_at"],
"updatedAt": data["updated_at"],
"startedAt": data["started_at"],
"completedAt": data["completed_at"],
"heartbeatAt": data["heartbeat_at"],
"lastEventSeq": int(data["next_event_seq"]) - 1,
}
def get_run(run_id: str, owner_subject: str | None = None) -> dict | None:
conn = get_connection()
try:
sql = "SELECT * FROM research_runs WHERE id = ?"
args: tuple = (run_id,)
if owner_subject is not None:
sql += " AND owner_subject = ?"
args += (owner_subject,)
row = conn.execute(sql, args).fetchone()
if row is None:
return None
result = _row_to_run(row)
result["steps"] = [
dict(r)
for r in conn.execute(
"SELECT position, title, query, status, result_json AS resultJson, "
"started_at AS startedAt, completed_at AS completedAt FROM research_plan_steps "
"WHERE run_id = ? ORDER BY position",
(run_id,),
).fetchall()
]
for step in result["steps"]:
step["result"] = _loads(step.pop("resultJson"), None)
step["input"] = step["query"]
result["sources"] = [
dict(r)
for r in conn.execute(
"SELECT id, step_position AS stepPosition, url, title, snippet, "
"fetched_at AS fetchedAt FROM research_sources WHERE run_id = ? ORDER BY id",
(run_id,),
).fetchall()
]
result["documentSources"] = [
dict(r)
for r in conn.execute(
"SELECT id, step_position AS stepPosition, document_id AS documentId, "
"chunk_id AS chunkId, filename, page, score, snippet, "
"fetched_at AS fetchedAt FROM research_document_sources "
"WHERE run_id = ? ORDER BY id",
(run_id,),
).fetchall()
]
return result
finally:
conn.close()
def list_active(thread_id: str) -> list[dict]:
conn = get_connection()
try:
placeholders = ",".join("?" for _ in ACTIVE_STATUSES)
rows = conn.execute(
f"SELECT id FROM research_runs WHERE thread_id = ? "
f"AND status IN ({placeholders}) ORDER BY created_at",
(thread_id, *sorted(ACTIVE_STATUSES)),
).fetchall()
finally:
conn.close()
return [run for row in rows if (run := get_run(row["id"])) is not None]
def has_thread_claim(thread_id: str) -> bool:
conn = get_connection()
try:
return (
conn.execute(
"SELECT 1 FROM research_thread_claims WHERE thread_id=?",
(thread_id,),
).fetchone()
is not None
)
finally:
conn.close()
def _discover_assistant_locked(conn: sqlite3.Connection, run: sqlite3.Row) -> str | None:
bound_id = run["assistant_message_id"]
if bound_id:
bound = conn.execute(
"SELECT id FROM chat_messages WHERE id=? AND thread_id=? AND role='assistant'",
(bound_id, run["thread_id"]),
).fetchone()
if bound is not None:
return str(bound["id"])
rows = conn.execute(
"""SELECT id, metadata_json FROM chat_messages
WHERE thread_id=? AND parent_id=? AND role='assistant' ORDER BY created_at, id""",
(run["thread_id"], run["user_message_id"]),
).fetchall()
for message in rows:
metadata = _loads(message["metadata_json"], {})
if isinstance(metadata, dict) and metadata.get("researchRunId") == run["id"]:
message_id = str(message["id"])
conn.execute(
"UPDATE research_runs SET assistant_message_id=?, updated_at=? WHERE id=?",
(message_id, now_ms(), run["id"]),
)
return message_id
return None
def discover_and_bind_assistant_message(run_id: str) -> str | None:
"""Atomically bind the assistant-ui child carrying this run's metadata."""
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
run = conn.execute("SELECT * FROM research_runs WHERE id=?", (run_id,)).fetchone()
if run is None:
raise KeyError(run_id)
message_id = _discover_assistant_locked(conn, run)
_commit_event(conn)
return message_id
except Exception:
conn.rollback()
raise
finally:
conn.close()
def create_and_bind_terminal_fallback(
run_id: str,
*,
text: str,
status: str,
sources: list[dict] | None = None,
completion_worker_id: str | None = None,
) -> tuple[str, bool]:
"""Discover a frontend message or atomically create exactly one fallback."""
if status not in TERMINAL_STATUSES:
raise ValueError(status)
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
run = conn.execute("SELECT * FROM research_runs WHERE id=?", (run_id,)).fetchone()
if run is None:
raise KeyError(run_id)
can_prepare_completion = (
completion_worker_id is not None
and status == "completed"
and run["status"] == "running"
and run["lease_owner"] == completion_worker_id
and run["lease_expires_at"] is not None
and int(run["lease_expires_at"]) >= now_ms()
and not bool(run["cancel_requested"])
)
if run["status"] != status and not can_prepare_completion:
raise ResearchConflictError(
f"Cannot create a {status} fallback for a {run['status']} run"
)
message_id = _discover_assistant_locked(conn, run)
if message_id is not None:
conn.commit()
return message_id, False
message_id = f"research-{run_id}"
parts: list[dict[str, Any]] = [{"type": "text", "text": text, "researchRunId": run_id}]
for source in sources or []:
parts.append(
{
"type": "source",
"sourceType": "url",
"id": source["url"],
"url": source["url"],
"title": source.get("title") or source["url"],
"metadata": {"description": source.get("snippet") or ""},
"researchRunId": run_id,
}
)
metadata = {
"researchRunId": run_id,
"researchStatus": status,
"researchPlanRevision": int(run["plan_revision"]),
"serverManaged": True,
}
created = now_ms()
conn.execute(
"""INSERT INTO chat_messages
(id, thread_id, parent_id, role, content_json, metadata_json, created_at)
VALUES (?, ?, ?, 'assistant', ?, ?, ?)""",
(
message_id,
run["thread_id"],
run["user_message_id"],
json.dumps(parts, ensure_ascii = False),
json.dumps(metadata, ensure_ascii = False),
created,
),
)
conn.execute(
"UPDATE research_runs SET assistant_message_id=?, updated_at=? WHERE id=?",
(message_id, created, run_id),
)
conn.execute(
"UPDATE chat_threads SET updated_at=MAX(COALESCE(updated_at, created_at), ?) WHERE id=?",
(created, run["thread_id"]),
)
_commit_event(conn)
return message_id, True
except sqlite3.IntegrityError:
conn.rollback()
# A concurrent terminal path may have inserted the deterministic fallback.
message_id = discover_and_bind_assistant_message(run_id)
if message_id is None:
raise
return message_id, False
except Exception:
conn.rollback()
raise
finally:
conn.close()
def set_plan(
run_id: str,
plan: dict,
expected_revision: int | None = None,
worker_id: str | None = None,
) -> dict:
raw, digest = canonical_plan(plan)
steps = plan.get("steps") or []
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
"SELECT status, plan_revision, lease_owner, lease_expires_at, cancel_requested "
"FROM research_runs WHERE id = ?",
(run_id,),
).fetchone()
if row is None:
raise KeyError(run_id)
if worker_id is not None and (
row["status"] != "planning"
or row["lease_owner"] != worker_id
or row["lease_expires_at"] is None
or int(row["lease_expires_at"]) < now_ms()
or bool(row["cancel_requested"])
):
raise ResearchConflictError("Planner no longer owns this research run")
if worker_id is None and row["status"] not in {"planning", "awaiting_approval"}:
raise ResearchConflictError("Plan can only be changed before approval")
revision = int(row["plan_revision"])
if expected_revision is not None and revision != expected_revision:
raise ResearchConflictError(f"Plan revision is {revision}, not {expected_revision}")
revision += 1
conn.execute(
"UPDATE research_runs SET plan_json = ?, plan_revision = ?, plan_hash = ?, "
"status = 'awaiting_approval', error_message = NULL, lease_owner = NULL, "
"lease_expires_at = NULL, updated_at = ? WHERE id = ?",
(raw, revision, digest, now_ms(), run_id),
)
conn.execute("DELETE FROM research_plan_steps WHERE run_id = ?", (run_id,))
conn.executemany(
"INSERT INTO research_plan_steps (run_id, position, title, query) VALUES (?, ?, ?, ?)",
[
(run_id, i, str(s["title"]), str(s.get("query") or s["title"]))
for i, s in enumerate(steps)
],
)
_event_locked(
conn,
run_id,
"plan.ready",
{
"status": "awaiting_approval",
"plan": plan,
"planRevision": revision,
"planHash": digest,
},
)
_commit_event(conn)
return {"plan": plan, "planRevision": revision, "planHash": digest}
except Exception:
conn.rollback()
raise
finally:
conn.close()
def approve(run_id: str, revision: int, plan_hash: str) -> str:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
"SELECT status, plan_revision, plan_hash FROM research_runs WHERE id = ?", (run_id,)
).fetchone()
if row is None:
raise KeyError(run_id)
if int(row["plan_revision"]) != revision or row["plan_hash"] != plan_hash:
raise ResearchConflictError("Plan revision or hash no longer matches")
if row["status"] in {"queued", "running", "completed"}:
conn.commit()
return row["status"]
if row["status"] != "awaiting_approval":
raise ResearchConflictError(f"Cannot approve a {row['status']} run")
conn.execute(
"UPDATE research_runs SET status = 'queued', updated_at = ? WHERE id = ?",
(now_ms(), run_id),
)
_event_locked(conn, run_id, "run.approved", {"status": "queued"})
_commit_event(conn)
return "queued"
except Exception:
conn.rollback()
raise
finally:
conn.close()
def request_cancel(run_id: str) -> str:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute("SELECT status FROM research_runs WHERE id = ?", (run_id,)).fetchone()
if row is None:
raise KeyError(run_id)
status = row["status"]
if status in TERMINAL_STATUSES or status == "cancelling":
conn.commit()
return status
new_status = (
"cancelled" if status in {"awaiting_approval", "queued", "paused"} else "cancelling"
)
completed = now_ms() if new_status == "cancelled" else None
conn.execute(
"UPDATE research_runs SET cancel_requested = 1, status = ?, completed_at = ?, "
"updated_at = ? WHERE id = ?",
(new_status, completed, now_ms(), run_id),
)
event_type = "run.cancelled" if new_status == "cancelled" else "run.cancelRequested"
_event_locked(conn, run_id, event_type, {"status": new_status})
_commit_event(conn)
return new_status
except Exception:
conn.rollback()
raise
finally:
conn.close()
def retry(run_id: str, max_retries: int = 3) -> str:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
"SELECT status, retry_count, plan_json, owner_subject, thread_id "
"FROM research_runs WHERE id = ?",
(run_id,),
).fetchone()
if row is None:
raise KeyError(run_id)
if row["status"] not in {"failed", "cancelled"}:
raise ResearchConflictError("Only failed or cancelled runs can be retried")
if int(row["retry_count"]) >= max_retries:
raise ResearchConflictError("Retry budget exhausted")
claim = conn.execute(
"SELECT owner_subject FROM research_thread_claims WHERE thread_id=?",
(row["thread_id"],),
).fetchone()
if claim is None or claim["owner_subject"] != row["owner_subject"]:
raise ResearchConflictError("This run does not own the thread research claim")
placeholders = ",".join("?" for _ in ACTIVE_STATUSES)
active = conn.execute(
f"SELECT id FROM research_runs WHERE owner_subject=? AND thread_id=? AND id<>? "
f"AND status IN ({placeholders}) LIMIT 1",
(row["owner_subject"], row["thread_id"], run_id, *sorted(ACTIVE_STATUSES)),
).fetchone()
if active is not None:
raise ResearchConflictError("This thread already has an active research run")
plan_was_approved = False
if row["plan_json"]:
plan_was_approved = (
conn.execute(
"SELECT 1 FROM research_events WHERE run_id=? AND event_type='run.approved' LIMIT 1",
(run_id,),
).fetchone()
is not None
)
status = (
"queued"
if plan_was_approved
else "awaiting_approval"
if row["plan_json"]
else "planning"
)
conn.execute(
"UPDATE research_runs SET status = ?, cancel_requested = 0, retry_count = retry_count + 1, "
"error_message = NULL, report_text = NULL, completed_at = NULL, lease_owner = NULL, "
"lease_expires_at = NULL, updated_at = ? WHERE id = ?",
(status, now_ms(), run_id),
)
if status != "awaiting_approval":
conn.execute("DELETE FROM research_plan_steps WHERE run_id = ?", (run_id,))
conn.execute("DELETE FROM research_sources WHERE run_id = ?", (run_id,))
conn.execute("DELETE FROM research_document_sources WHERE run_id = ?", (run_id,))
_event_locked(conn, run_id, "run.retried", {"status": status})
_commit_event(conn)
return status
except Exception:
conn.rollback()
raise
finally:
conn.close()
def claim_next(worker_id: str, lease_ms: int = 120_000) -> dict | None:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
now = now_ms()
row = conn.execute(
"""SELECT r.* FROM research_runs r
JOIN research_thread_claims c ON c.thread_id=r.thread_id
WHERE r.owner_subject=c.owner_subject
AND r.status IN ('planning','queued','running','cancelling')
AND (r.lease_owner IS NULL OR r.lease_expires_at < ?)
ORDER BY r.created_at LIMIT 1""",
(now,),
).fetchone()
if row is None:
conn.commit()
return None
status = row["status"]
next_status = (
"running"
if status in {"queued", "running"}
else "cancelling"
if status == "cancelling"
else "planning"
)
conn.execute(
"UPDATE research_runs SET status=?, lease_owner=?, lease_expires_at=?, heartbeat_at=?, "
"started_at=COALESCE(started_at, ?), updated_at=? WHERE id=?",
(next_status, worker_id, now + lease_ms, now, now, now, row["id"]),
)
resumed = status == "running"
_event_locked(
conn,
row["id"],
"run.started",
{"status": next_status, "resumed": resumed},
)
_commit_event(conn)
claimed = get_run(row["id"])
if claimed is not None:
claimed["claimedFromStatus"] = status
return claimed
except Exception:
conn.rollback()
raise
finally:
conn.close()
def heartbeat(
run_id: str,
worker_id: str,
lease_ms: int = 120_000,
) -> bool:
conn = get_connection()
try:
now = now_ms()
cur = conn.execute(
"UPDATE research_runs SET heartbeat_at=?, lease_expires_at=? "
"WHERE id=? AND lease_owner=? AND lease_expires_at>=?",
(now, now + lease_ms, run_id, worker_id, now),
)
conn.commit()
return cur.rowcount == 1
finally:
conn.close()
def is_cancel_requested(run_id: str) -> bool:
conn = get_connection()
try:
row = conn.execute(
"SELECT cancel_requested FROM research_runs WHERE id = ?", (run_id,)
).fetchone()
return row is None or bool(row[0])
finally:
conn.close()
def finish(
run_id: str,
worker_id: str,
status: str,
error: str | None = None,
event_payload: dict[str, Any] | None = None,
allow_expired: bool = False,
) -> str | None:
if status not in TERMINAL_STATUSES:
raise ValueError(status)
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
now = now_ms()
row = conn.execute(
"SELECT status, cancel_requested, lease_expires_at "
"FROM research_runs WHERE id=? AND lease_owner=?",
(run_id, worker_id),
).fetchone()
if row is None:
conn.commit()
return None
if (
not allow_expired
and not bool(row["cancel_requested"])
and (row["lease_expires_at"] is None or int(row["lease_expires_at"]) < now)
):
conn.commit()
return None
actual_status = (
"cancelled"
if bool(row["cancel_requested"]) or row["status"] == "cancelling"
else status
)
actual_error = None if actual_status == "cancelled" else error
report_text = None
if actual_status == "completed" and event_payload:
candidate = event_payload.get("report")
if isinstance(candidate, str):
report_text = candidate
conn.execute(
"UPDATE research_runs SET status=?, error_message=?, report_text=?, completed_at=?, updated_at=?, "
"lease_owner=NULL, lease_expires_at=NULL WHERE id=? AND lease_owner=?",
(actual_status, actual_error, report_text, now, now, run_id, worker_id),
)
payload = {"status": actual_status, "error": actual_error}
if event_payload and actual_status == status:
payload.update(event_payload)
_event_locked(conn, run_id, f"run.{actual_status}", payload)
_commit_event(conn)
return actual_status
except Exception:
conn.rollback()
raise
finally:
conn.close()
def set_report_progress(
run_id: str,
report: str,
delta: str | None = None,
worker_id: str | None = None,
) -> bool:
"""Persist partial report text and notify followers while synthesis runs."""
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
"SELECT status, lease_owner, lease_expires_at, cancel_requested "
"FROM research_runs WHERE id = ?",
(run_id,),
).fetchone()
if (
row is None
or row["status"] != "running"
or worker_id is not None
and (
row["lease_owner"] != worker_id
or bool(row["cancel_requested"])
or row["lease_expires_at"] is None
or int(row["lease_expires_at"]) < now_ms()
)
):
conn.commit()
return False
now = now_ms()
conn.execute(
"UPDATE research_runs SET report_text = ?, updated_at = ? WHERE id = ?",
(report, now, run_id),
)
event_data: dict[str, Any] = {"length": len(report)}
if delta:
event_data.update({"delta": delta, "offset": len(report) - len(delta)})
_event_locked(conn, run_id, "report.updated", event_data)
_commit_event(conn)
return True
except Exception:
conn.rollback()
raise
finally:
conn.close()
def update_step(
run_id: str,
position: int,
status: str,
result: Any = None,
) -> None:
conn = get_connection()
try:
now = now_ms()
conn.execute(
"UPDATE research_plan_steps SET status=?, result_json=?, "
"started_at=CASE WHEN ?='running' THEN COALESCE(started_at, ?) ELSE started_at END, "
"completed_at=CASE WHEN ? IN ('completed','failed') THEN ? ELSE completed_at END "
"WHERE run_id=? AND position=?",
(
status,
json.dumps(result, ensure_ascii = False) if result is not None else None,
status,
now,
status,
now,
run_id,
position,
),
)
conn.commit()
finally:
conn.close()
def reset_execution_steps(run_id: str, worker_id: str | None = None) -> bool:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
if worker_id is not None and not _worker_can_write_locked(
conn,
run_id,
worker_id,
{"running"},
):
conn.commit()
return False
conn.execute("DELETE FROM research_plan_steps WHERE run_id = ?", (run_id,))
conn.execute("DELETE FROM research_sources WHERE run_id = ?", (run_id,))
conn.execute("DELETE FROM research_document_sources WHERE run_id = ?", (run_id,))
conn.commit()
return True
except Exception:
conn.rollback()
raise
finally:
conn.close()
def prepare_execution_resume(run_id: str, worker_id: str) -> bool:
"""Keep completed evidence while discarding the interrupted step."""
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
if not _worker_can_write_locked(conn, run_id, worker_id, {"running"}):
conn.commit()
return False
interrupted = conn.execute(
"SELECT position FROM research_plan_steps WHERE run_id = ? "
"AND status NOT IN ('completed','failed')",
(run_id,),
).fetchall()
conn.executemany(
"DELETE FROM research_sources WHERE run_id = ? AND step_position = ?",
[(run_id, int(row["position"])) for row in interrupted],
)
conn.executemany(
"DELETE FROM research_document_sources WHERE run_id = ? AND step_position = ?",
[(run_id, int(row["position"])) for row in interrupted],
)
conn.execute(
"DELETE FROM research_plan_steps WHERE run_id = ? "
"AND status NOT IN ('completed','failed')",
(run_id,),
)
conn.commit()
return True
except Exception:
conn.rollback()
raise
finally:
conn.close()
def upsert_execution_step(
run_id: str,
position: int,
title: str,
query: str,
status: str,
result: Any = None,
worker_id: str | None = None,
) -> bool:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
if worker_id is not None and not _worker_can_write_locked(
conn,
run_id,
worker_id,
{"running"},
):
conn.commit()
return False
now = now_ms()
conn.execute(
"""INSERT INTO research_plan_steps
(run_id, position, title, query, status, result_json, started_at, completed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(run_id, position) DO UPDATE SET
title=excluded.title, query=excluded.query, status=excluded.status,
result_json=excluded.result_json,
started_at=COALESCE(research_plan_steps.started_at, excluded.started_at),
completed_at=excluded.completed_at""",
(
run_id,
position,
title[:200],
query[:500],
status,
json.dumps(result, ensure_ascii = False) if result is not None else None,
now,
now if status in {"completed", "failed"} else None,
),
)
conn.commit()
return True
except Exception:
conn.rollback()
raise
finally:
conn.close()
def get_reasoning_text(run_id: str) -> str:
conn = get_connection()
try:
run = conn.execute("SELECT retry_count FROM research_runs WHERE id=?", (run_id,)).fetchone()
if run is None:
return ""
attempt = int(run["retry_count"])
rows = conn.execute(
"SELECT data_json FROM research_events WHERE run_id=? "
"AND event_type='reasoning.updated' ORDER BY seq",
(run_id,),
).fetchall()
return "".join(
str(data.get("reasoningDelta") or "")
for row in rows
if int((data := _loads(row["data_json"], {})).get("attempt", 0)) == attempt
)
finally:
conn.close()
def upsert_source(
run_id: str,
position: int,
url: str,
title: str,
snippet: str,
worker_id: str | None = None,
) -> bool:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
if worker_id is not None and not _worker_can_write_locked(
conn,
run_id,
worker_id,
{"running"},
):
conn.commit()
return False
run = conn.execute(
"SELECT config_json FROM research_runs WHERE id=?",
(run_id,),
).fetchone()
if run is None:
conn.commit()
return False
config = _loads(run["config_json"], {})
allowed, reason, _hostname = check_url_access(
url,
config.get("websitePolicy") if isinstance(config, dict) else None,
)
if not allowed:
raise ValueError(reason)
fetched_at = now_ms()
conn.execute(
"""INSERT INTO research_sources (run_id, step_position, url, title, snippet, fetched_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(run_id, url) DO UPDATE SET step_position=excluded.step_position,
title=excluded.title,
snippet=excluded.snippet, fetched_at=excluded.fetched_at""",
(run_id, position, url, title[:500], snippet[:4000], fetched_at),
)
_event_locked(
conn,
run_id,
"source.added",
{
"position": position,
"stepPosition": position,
"url": url,
"title": title[:500],
"snippet": snippet[:4000],
"fetchedAt": fetched_at,
},
)
_commit_event(conn)
return True
except Exception:
conn.rollback()
raise
finally:
conn.close()
def upsert_document_source(
run_id: str,
position: int,
source: dict[str, Any],
worker_id: str | None = None,
) -> bool:
filename = str(source.get("filename") or "Document")[:500]
document_id = source.get("documentId")
chunk_id = source.get("chunkId")
page = source.get("page")
source_key = str(chunk_id or f"{document_id or filename}:{page or ''}")[:1000]
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
if worker_id is not None and not _worker_can_write_locked(
conn,
run_id,
worker_id,
{"running"},
):
conn.commit()
return False
fetched_at = now_ms()
conn.execute(
"""INSERT INTO research_document_sources
(run_id, step_position, source_key, document_id, chunk_id, filename,
page, score, snippet, fetched_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(run_id, source_key) DO UPDATE SET
step_position=excluded.step_position, document_id=excluded.document_id,
chunk_id=excluded.chunk_id, filename=excluded.filename, page=excluded.page,
score=excluded.score, snippet=excluded.snippet, fetched_at=excluded.fetched_at""",
(
run_id,
position,
source_key,
str(document_id)[:500] if document_id is not None else None,
str(chunk_id)[:500] if chunk_id is not None else None,
filename,
int(page) if isinstance(page, (int, float)) else None,
float(source["score"]) if isinstance(source.get("score"), (int, float)) else None,
str(source.get("text") or source.get("snippet") or "")[:4000],
fetched_at,
),
)
conn.commit()
return True
except Exception:
conn.rollback()
raise
finally:
conn.close()
def list_events(
run_id: str,
after: int = 0,
limit: int = 1000,
) -> list[dict]:
conn = get_connection()
try:
rows = conn.execute(
"""SELECT seq, event_type, data_json, created_at
FROM research_events
WHERE run_id=? AND seq>? ORDER BY seq LIMIT ?""",
(run_id, after, limit),
).fetchall()
return [
{
"seq": r["seq"],
"type": r["event_type"],
"data": _loads(r["data_json"], {}),
"createdAt": r["created_at"],
}
for r in rows
]
finally:
conn.close()
def wait_for_events(
run_id: str,
after: int = 0,
timeout: float = 15,
) -> list[dict]:
"""Block until committed events are available or the keep-alive timeout expires."""
events = list_events(run_id, after)
if events:
return events
with _EVENTS_CHANGED:
# Recheck under the condition lock so a commit cannot be missed between
# the initial query and waiting for its notification.
events = list_events(run_id, after)
if events:
return events
_EVENTS_CHANGED.wait(timeout)
return list_events(run_id, after)
def recover_expired(now: int | None = None) -> int:
conn = get_connection()
try:
now = now or now_ms()
cur = conn.execute(
"""UPDATE research_runs SET lease_owner=NULL, lease_expires_at=NULL, updated_at=?
WHERE status IN ('planning','queued','running','cancelling')
AND lease_owner IS NOT NULL AND lease_expires_at < ?""",
(now, now),
)
conn.commit()
return cur.rowcount
finally:
conn.close()
def owns_lease(run_id: str, worker_id: str) -> bool:
conn = get_connection()
try:
row = conn.execute(
"SELECT 1 FROM research_runs WHERE id=? AND lease_owner=? AND lease_expires_at>=?",
(run_id, worker_id, now_ms()),
).fetchone()
return row is not None
finally:
conn.close()
def release_worker_leases(worker_id: str) -> int:
conn = get_connection()
try:
cur = conn.execute(
"""UPDATE research_runs SET lease_owner=NULL, lease_expires_at=NULL, updated_at=?
WHERE lease_owner=? AND status IN ('planning','queued','running','cancelling')""",
(now_ms(), worker_id),
)
conn.commit()
return cur.rowcount
finally:
conn.close()