Skip to content

[staging] studio.db WAL keeper (#9934) — CI only, do not merge - #9

Closed
Lyxot wants to merge 6 commits into
mainfrom
fix/9934-studio-db-wal-keeper
Closed

Lyxot wants to merge 6 commits into
mainfrom
fix/9934-studio-db-wal-keeper

Conversation

@Lyxot

@Lyxot Lyxot commented Aug 31, 2026

Copy link
Copy Markdown
Owner

Staging only — do not merge. This exists to run CI against the fork's own runners instead of waiting in the upstream queue. The real review is unslothai#9945.

Same branch and same head commit as that PR. See it for the description; the short version is that Studio holds one idle SQLite connection for the process lifetime so short-lived event writers stop checkpointing the WAL back into studio.db on close.

Diff is 4 files: studio/backend/main.py, studio/backend/storage/studio_db.py and their two test files.

Imagineer99 and others added 6 commits August 29, 2026 02:04
Resolves studio/backend/core/inference/chat_generation_runs.py: main added the lease sweeper, including a sweeper stop at the head of ChatGenerationSupervisor.stop(); this branch wrapped that method's body so the WAL keeper is released on the way out. Kept both -- the sweeper stop runs inside the try, and the keeper release stays in the finally.
get_connection now applies synchronous=NORMAL to every studio.db connection, gated on the database really being in WAL mode, and append_events reaches it through _connect. Setting the pragma again per batch is a no-op, and its comment claimed the terminal transaction in finish_run() still syncs at FULL, which is no longer true of any connection.

All synchronous policy now lives in one place.
… in WAL mode

open_wal_keeper() raised when the database reported any other journal mode, from an unguarded lifespan call, so an install whose filesystem declined WAL would not boot at all. journal_mode=WAL declines silently on filesystems without shared-memory support -- network shares, some FUSE and container mounts -- and the mode is persistent in the file, so this is reachable on a normal desktop install.

It now returns None and logs, the lifespan guards the call like every other fallible startup step, and those installs go without the saving rather than without Studio. Matches how _apply_wal_synchronous already treats the same condition.
The keeper was constructed in the lifespan, handed to ChatGenerationSupervisor, and closed in its stop(), which forced that method's whole body into a try/finally. WAL lifetime is a property of the database, not of chat generation: every short-lived writer in the backend benefits, including the mcp_servers_db, credential_secrets and providers_db factories that open the same file.

open_wal_keeper()/close_wal_keeper() now hold it as process state next to the existing schema latch, and the lifespan opens it before the first startup write and releases it after the last shutdown write. ChatGenerationSupervisor returns to what it was.
Two failures reachable when a lifespan does not release its keeper -- a shutdown that raised, or an embedded restart.

open_wal_keeper() returned the existing keeper if it found one. A second lifespan on a different database therefore reported success while holding a database the process had stopped using, so the saving was silently off for the one it was using. It now releases whatever it finds before opening its own.

That release could not happen at all when the keeper belonged to a thread that has since exited: sqlite refuses a cross-thread close, so the connection stayed an open WAL participant for the rest of the process and the WAL was never cleared. get_connection() takes a keyword-only check_same_thread, and the keeper -- which runs one statement, at open, on the opening thread, and is otherwise only closed -- opens with it off. Every other caller keeps the default.
@Lyxot

Lyxot commented Aug 31, 2026

Copy link
Copy Markdown
Owner Author

CI done: 44 pass, 4 skipped, 3 pre-existing Core failures that are red on main too. Results linked from unslothai#9945. Closing — staging only.

@Lyxot Lyxot closed this Aug 31, 2026
Lyxot pushed a commit that referenced this pull request Nov 16, 2026
…caped code stays in its code block (unslothai#17200)

Fixes unslothai#17199.

## Problem

When the model fetches a page, Studio's HTML-to-Markdown converter:

- appends a `;` to a bare `&` followed by a letter, and decodes names
that are references only with their `;`. For example, `AT&T.` becomes
`AT&T.;` and `?key=abc&format=json&lang=en` becomes
`?key=abc&format;=json⟨=en`.
- moves escaped characters out of a `<pre>` in a table cell. That is the
layout of line-numbered code from Pygments' table formatter, Rouge and
Chroma, so `if a < b and c > 0:` reads `if a b and c 0:` inside the
fence. Inside a link in a `<pre>`, it moves the escaped characters into
the link text and drops a `&nbsp;`.
- can pass the rest of the page through as raw HTML:
- on Python 3.13 and 3.14, after a decimal reference that has no `;` and
runs into a letter a–f (`&#169Copyright`);
- on 3.11 and 3.12, after a `&#` with no digits when no `;` follows it.

The issue lists live pages where this happens, such as Alpha Vantage's
API samples, Google's Maps URLs docs and RFC 6749.

## Root cause

The renderer ran `HTMLParser` with `convert_charrefs=False` and decoded
references itself in `handle_entityref` and `handle_charref`:

- `HTMLParser` reports `&name` whether or not a `;` follows, and the
handler always decoded `&name;`.
- The decoded text went through `_emit()`, which picks an open link or
table cell before an open `<pre>`, while the text around it went to the
`<pre>`.
- With `convert_charrefs=False`, `HTMLParser`'s handling of a malformed
`&#` depends on the Python version, and on each version some form of it
ends the parse early.

## Changes

- **`HTMLParser(convert_charrefs=True)`**, the stdlib default.
- References decode inside their text run with `html.unescape`, as a
browser decodes text, and the decoded run reaches `handle_data`, so it
is routed with the text around it.
- `HTMLParser` then never calls `handle_entityref` or `handle_charref`.
They, their two replay branches and the `html` import are removed.
- The `_TokenLog` docstring now names the three handlers its replay
contract covers.
- **U+00A0 is not collapsed.**
- `&nbsp;` used to bypass the whitespace collapse in `handle_data`.
Decoded inside the text run, it would be collapsed, and code indented
with `&nbsp;` (W3Schools writes its examples that way) would lose its
indentation.
- Emitted text now collapses whitespace other than U+00A0
(`_COLLAPSIBLE_RUN`), as a browser does.
- The header link-density tally still counts the text with U+00A0
collapsed, so a link header padded with `&nbsp;` is stripped as before.
- **Decimal references longer than 640 digits are shortened before
parsing.**
- `html.unescape` raises `ValueError` once a decimal reference has more
digits than `int()`'s limit. Python never sets that limit below 640, and
leading zeros count toward it.
- `html_to_markdown` drops the leading zeros of such a reference. If 8
or more digits remain, it writes `&#65533`, which is the U+FFFD that
`html.unescape` gives past U+10FFFF.
- On every version, main raised for such a reference ended by `;` or a
space, or inside an attribute. On 3.13 and 3.14 it also raised for one
followed by a hex letter or cut off at the end of the page. With
`convert_charrefs=True` alone, 3.11 and 3.12 would raise for those two
as well.

## Other behavior changes

- **Literal U+00A0:** a literal U+00A0 in flowing text is now kept, as
`&nbsp;` already was, instead of becoming a space.
- **Other whitespace references:** `&ensp;`, `&emsp;`, `&thinsp;`,
`&unslothai#8239;`, `&#9;`, `&#10;` and `&#13;` in flowing text now collapse like
the characters they decode to, as those literal characters already did.
Main emitted them as is, including a raw tab and carriage return.
- **U+00A0-only text between table elements:** this is now dropped like
other whitespace there.
  - Main put it in front of the next Markdown row (`\xa0| c | d |`).
- It also drops Javadoc 8's method-summary tab separators, which sit
inside a `<caption>`: `All Methods\xa0Static Methods` becomes `All
MethodsStatic Methods`.
- **List markers:** a list item whose first text is a reference after
source indentation now gets the two spaces after its marker that literal
text already gets (`* "Quoted" title`).
- **Legacy reference names in query parameters:** a parameter that
starts with a legacy reference name still decodes, as in a browser, but
without the stray `;`. `&param=x` was `¶m;=x` and is now `¶m=x`.

## Testing

All runs were on macOS 26 (arm64).

- **New tests:** 12 cases in `test_web_fetch_extraction.py`, which make
28 tests with the `main_content` variants.
- Against `origin/main`'s converter, 22 fail on Python 3.11.16 and
3.12.7, and 18 fail on 3.13.11 and 3.14.7, where CPython already parses
a `&#` without digits as text.
- The 6 that pass on main are guards: references still decode,
`&nbsp;`-indented text keeps its indentation, and a `&nbsp;`-padded link
header is still stripped.
  - All 28 pass on this branch on 3.11.16, 3.12.7, 3.13.11 and 3.14.7.
- **Converter test files** (`test_html_to_md_*.py` and
`test_web_fetch_extraction.py`): 1567 passed on main and 1595 (1567 +
28) on this branch, on each of 3.11.16, 3.12.7, 3.13.11 and 3.14.7.
- **Related backend tests:** 47 backend test files around web fetch and
the tool loop, on Python 3.12.7 with the backend CI dependencies.
- This branch: 8232 passed, 9 failed, 3 skipped. `origin/main`: 8204
passed, 9 failed, 3 skipped. The 28 extra passes are the new tests.
- The same 9 deferred workspace-deletion tests in
`test_sandbox_files_and_storage_roots.py` fail on both on this machine.
- The same 3 tests skip on both, because `unsloth_zoo` is not installed
and a tokenizer file was not fetched.
- **Live pages:** 155 saved responses (153 distinct URLs) from
documentation, code-heavy, prose and data sites. They are 133 pages (7
of which give empty Markdown with both converters), 17 Cloudflare
challenge pages, 4 "Access Denied" pages and 1 empty file. Converted
with `main_content=True`:
- **112 are identical**, including all 29 non-pages and empty
conversions.
- **25 differ only in whitespace.** 24 come from a literal U+00A0 that
is now kept. The other is legislation.gov.uk, where `&#xD;` no longer
emits a raw carriage return.
- **18 differ in content.** A script sorted the differing hunks on those
pages:
    - 619 drop a stray `;` or keep a bare `&` that main decoded.
    - 53 put characters back in their `<pre>`.
- 12 keep a U+00A0 from `&nbsp;` inside a link in a `<pre>`, which main
dropped (RFC section links, Cloudflare-protected email addresses in code
samples).
    - 1 is the Javadoc caption change above.
- Across these outputs, U+00A0 goes from 2,822 to 12,253 characters,
0.15% of the branch's 8.26M.
- **Robustness and speed:**
- 3,000 generated documents in both modes, on each of 3.11.16, 3.12.7,
3.13.11 and 3.14.7: 0 exceptions on this branch, 18 on main.
- CPU time over the 155 responses (49 MB) on 3.13.11, as the sum of
per-page minimums over 5 interleaved runs: 4.52 s on main and 4.44 s on
this branch. The pre-pass costs 14 ms over the whole 49 MB.
- **Lint:** `python scripts/run_ruff_format.py` (ruff-unsloth
0.6.9.post1), `ruff check` (0.17.3) and `git diff --check` pass.

## Not covered

- **`<caption>` rendering:** `<caption>` has no rendering rule. On both
main and this branch, a caption runs into its table's header row.
- **`_HTMLBodyLocator` in `tools.py`:** it also runs `HTMLParser` with
`convert_charrefs=False`. It only finds where `<body>` starts, so the
download can stop a window after it, and it produces no text, so it is
left as is.

This contribution is part of Stanford's CS146S: The Modern Software
Developer.

---------

Co-authored-by: Nilay Yadav <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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