From 7b83e89ebfd8eaf26c8c5d01e7f4d7d0a5dac750 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 22:45:08 -0800 Subject: [PATCH 1/4] ADFA-7295 SQLite debugger: refuse text after the JSON body, report a failed finalize, document the connection-id name clash Three follow-ups from CodeRabbit's review of #2260 (F18, F06, F24). - McpProtocol.post: JSONTokener.nextValue() reads one value and stops, so {"jsonrpc":"2.0","id":1,"method":"ping"} garbage ran the ping. Only JSON whitespace may follow the value now; anything else is HTTP 400 with PARSE_ERROR, and nothing runs. The rest is read with next(), because Android's nextClean() also skips comments and the JVM's org.json does not. - bridge_query dropped the result of sqlite3_finalize. A page that stops before SQLITE_DONE ends the statement there, and on a writable connection an autocommit write (an INSERT with RETURNING) commits there: a failed commit rolled the write back while the call returned its first rows. That is now the call's error, unless the query had already failed. No tool opens a writable connection yet. - README: the name clash of sqlitedbg_connection_id() as a limit, and the finalize error beside the rollback backstop. Tests: McpProtocolTest.textAfterTheJsonIsAParseErrorAndRunsNothing, and a JniQueryTest case where another connection's read lock makes the commit at finalize fail. Both fail with the fix reverted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 ++-- .../src/main/cpp/sqlitedbg_jni.c | 12 +++++++++++- .../sqlitedebugger/mcp/McpProtocol.kt | 15 ++++++++++++++- .../sqlitedebugger/mcp/McpProtocolTest.kt | 17 +++++++++++++++++ .../src/test/jni/JniQueryTest.java | 17 +++++++++++++++++ 5 files changed, 61 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 236123db27..4537dce02c 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -34,7 +34,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. So is an error from `sqlite3_finalize`, where a writable connection's autocommit write commits when a page stops before its last row (an INSERT with RETURNING), unless the query had already failed. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). @@ -43,7 +43,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The time limits are best effort.** The 1.5 s limit on a database that is not in WAL mode and the 50 s limit per call are checked by the progress handler, every 1,000 SQLite VM instructions. They are not checked while a statement waits for a lock the app holds (the busy wait, up to 3 s, `SQLITEDBG_SERVER_BUSY_MS`) or inside one long VM instruction, so a result can arrive up to about 3 s after its limit (the client waits 60 s). The tool descriptions say "best effort" too. - **Column names can be stale after a schema change.** The column names are read after prepare and before the first step, so a schema change by the app between the two can return the old column set. - **Turning off bound-value recording can be late.** After the client goes idle (60 s after the last `get_events`), turning recording off takes the tools' lock, so it waits for a running query and can be up to 50 s late (more by the overrun above). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `query`, `explain_query_plan` and `integrity_check` return that list as `truncated_cell_indexes`, `[row, column]` pairs from 0 with the row relative to the rows returned, beside the count `truncated_cells`; a cut TEXT cell stays a plain string, so this list is the only mark on it, and a cut BLOB is listed too (it also has `truncated: true`). `get_schema` has no such list: each entry says whether one of its cells was cut. `get_stats` returns numbers and table names and does not report cuts (a table name over 4096 bytes would be cut there; not tested). `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. The 50 s time limit belongs to the POST: `McpProtocol` sets one deadline when it starts handling a POST and passes it to every tool call of the batch, so waits behind other calls count and a batch of slow calls ends within 50 s in all, not 50 s each (32 calls would have held the lock for about 27 minutes). A call that starts after the deadline fails at once with the time-limit error (the engine refuses to start a query past its deadline); `list_databases`, `list_connections` and `get_events` run no SQL and still answer. A single call gets the same limit as before. The server therefore gives up before the client's 60 s limit, which is taken to be per request and is unchecked for a batch, so a timed-out query does not hold the lock after the client has stopped waiting; when waiting for the lock took at least half of the limit, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. The extension keeps each connection's state as the user data of the function it registers on that connection, `sqlitedbg_connection_id()` (no arguments), and SQLite frees the state through that function's destructor. If the app registers a function with the same name and no arguments on the same connection, which replaces ours, or deletes ours, SQLite frees the state while the trace callback still uses it: a use after free in the app's process. Don't give an app function that name. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `query`, `explain_query_plan` and `integrity_check` return that list as `truncated_cell_indexes`, `[row, column]` pairs from 0 with the row relative to the rows returned, beside the count `truncated_cells`; a cut TEXT cell stays a plain string, so this list is the only mark on it, and a cut BLOB is listed too (it also has `truncated: true`). `get_schema` has no such list: each entry says whether one of its cells was cut. `get_stats` returns numbers and table names and does not report cuts (a table name over 4096 bytes would be cut there; not tested). `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. The 50 s time limit belongs to the POST: `McpProtocol` sets one deadline when it starts handling a POST and passes it to every tool call of the batch, so waits behind other calls count and a batch of slow calls ends within 50 s in all, not 50 s each (32 calls would have held the lock for about 27 minutes). A call that starts after the deadline fails at once with the time-limit error (the engine refuses to start a query past its deadline); `list_databases`, `list_connections` and `get_events` run no SQL and still answer. A single call gets the same limit as before. The server therefore gives up before the client's 60 s limit, which is taken to be per request and is unchecked for a batch, so a timed-out query does not hold the lock after the client has stopped waiting; when waiting for the lock took at least half of the limit, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). ## Testing diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 8d19317ff2..6ea0fc194a 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -497,8 +497,18 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); - sqlite3_finalize(st); + // A statement stopped before SQLITE_DONE (a page cut short) ends here: on a writable connection an + // autocommit write, such as an INSERT ... RETURNING, commits here, and a commit that fails rolls the + // write back. That is the call's error, unless the query already failed: that error is kept. + rc = sqlite3_finalize(st); free(cut_cells); + if (rc != SQLITE_OK && !(*env)->ExceptionCheck(env)) { + char msg[256]; + snprintf(msg, sizeof msg, "the statement failed as it was finished, and nothing it changed was kept: %s", + sqlite3_errmsg(db)); + throw_engine(env, rc, msg); + result = NULL; + } // Backstop: a transaction left open (a writable connection, or a way past the authorizer) // would hold a lock on the app's database until the next query. A failure is the call's error, // unless the query already failed: that error is kept. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index b0d017b73f..c22e613207 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -113,7 +113,8 @@ class McpProtocol( val deadline = postTimeLimitMs?.let { clock() + it } val parsed = try { - JSONTokener(body).nextValue() + val tokener = JSONTokener(body) + tokener.nextValue().takeIf { onlyWhitespaceLeft(tokener) } } catch (e: Exception) { null } @@ -269,6 +270,18 @@ class McpProtocol( return ok(id, result) } + /** + * Whether only JSON whitespace is left after the value: `nextValue` reads one value and stops, so + * `{"method":"ping"} garbage` would otherwise run the ping. Read with `next()`, as Android's + * `nextClean()` also skips comments and the JVM's org.json does not. + */ + private fun onlyWhitespaceLeft(tokener: JSONTokener): Boolean { + while (tokener.more()) { + if (tokener.next() !in " \t\n\r") return false + } + return true + } + private fun validId(id: Any?) = id is String || id is Number private fun text(t: String) = JSONObject().put("type", "text").put("text", t) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 34892e4efc..83612225dd 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -206,6 +206,23 @@ class McpProtocolTest { assertEquals(McpProtocol.PARSE_ERROR, JSONObject(r.body!!).getJSONObject("error").getInt("code")) } + @Test fun textAfterTheJsonIsAParseErrorAndRunsNothing() { + var calls = 0 + val counts = McpTool("counts", "Counts", "Counts its calls.") { _, _ -> JSONObject().put("n", ++calls) } + val p = McpProtocol(listOf(counts), "test", { "s${++sessionNumber}" }, 16) + val s = session(p) + val call = request(7, "tools/call", JSONObject().put("name", "counts")).toString() + val batch = JSONArray().put(JSONObject(call)).toString() + for (body in listOf("$call garbage", "$call}", "$call {}", "$call // a comment", "$batch ]", "$batch $call")) { + val r = p.post(body, s, null) + assertEquals(body, 400, r.status) + assertEquals(body, McpProtocol.PARSE_ERROR, JSONObject(r.body!!).getJSONObject("error").getInt("code")) + } + assertEquals("nothing ran", 0, calls) + assertEquals(200, p.post("$call \n\t\r ", s, null).status) + assertEquals("trailing whitespace is fine", 1, calls) + } + @Test fun batchGetsAnArrayOfReplies() { val p = protocol() val s = session(p) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 5e47180211..a5c64d6754 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -383,6 +383,23 @@ public static void main(String[] a) throws Exception { eq(Helper.denyTransactions(w, false), 0, "the authorizer cleared, again"); eq(refusal(w, "SELECT 1"), null, "the next query rolls it back, again"); eq(Helper.autocommit(w), 1, "closed"); + // a commit that fails as the statement is finished is the call's error: with RETURNING the insert + // runs at the first step, a page cut short ends the statement at sqlite3_finalize, and the commit + // waits for another connection's read lock (rollback-journal mode) until the busy timeout + long reader = Helper.open(path); + eq(Helper.exec(reader, "BEGIN; SELECT count(*) FROM t;"), 0, "another connection holds a read transaction"); + String finished = null; + try { + query(w, "INSERT INTO t(id) VALUES(4247),(4248) RETURNING id", new Object[0], 0, 1, 4096, 1024, MAX, FAR); + } catch (DebugEngineException e) { + finished = e.sqliteCode + " " + e.getMessage(); + } + eq(finished, "5 the statement failed as it was finished, and nothing it changed was kept: database is locked", + "the failed commit at finalize is reported, not the first page of rows"); + eq(Helper.exec(reader, "COMMIT"), 0, "the reader ends its transaction"); + eq(q(w, "SELECT count(*) FROM t WHERE id IN (4247, 4248)").rows.get(0)[0], 0L, "the insert was rolled back"); + eq(Helper.autocommit(w), 1, "no transaction left open after the failed commit"); + eq(Helper.close(reader), 0, "close the reader"); NativeBridge.close(w); Helper.exec(app, "DELETE FROM t WHERE id = 4245"); From 156d31509cdf147be16ff144e73af47b102e2db7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:38:14 +0000 Subject: [PATCH 2/4] ADFA-7295 SQLite debugger: the three optional items (F21, F09, F11) On #2320 (7b83e89eb), which left them out as not asked for; David asked for them. - F21: McpHttp's request-head deadline (serve, readHead) uses System.nanoTime(), as finishReply does, so a wall clock set back no longer extends it. - F09: sqlitedbg.map is a LINK_DEPENDS of libsqlitedbg, so an edit to the version script alone relinks. - F11: TimerIdleScheduler cancels its timer once the task has run, so the daemon thread no longer stays parked until the next schedule. Tests: DatabaseToolsTest, McpProtocolTest and EventDecoderTest pass (109), compiled with the Kotlin compiler outside Gradle; the existing head-deadline test (a trickling client, McpProtocolTest) passes on nanoTime. New: theIdleTimerThreadEndsOnceItsCheckHasRun; without the cancel it fails ("still parked"). F09, by a host CMake/Ninja build: touching sqlitedbg.map relinks, and without LINK_DEPENDS "no work to do". F21 has no test: there is no clock seam to step back. C sources unchanged, so test.sh is not rerun. Not run here: Gradle, spotlessCheck. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- .../sqlite-debugger/src/main/cpp/CMakeLists.txt | 2 ++ .../sqlitedebugger/mcp/DatabaseTools.kt | 13 ++++++++++--- .../org/appdevforall/sqlitedebugger/mcp/McpHttp.kt | 11 ++++++----- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 12 ++++++++++++ 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt index 779767a2bb..d766422624 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt +++ b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt @@ -15,6 +15,8 @@ target_compile_options(sqlitedbg PRIVATE -Wall -Wextra -fvisibility=hidden) # dlopen/dlsym to find sqlite3_auto_extension in requery's libsqlite3x.so target_link_libraries(sqlitedbg dl) # Only JNI_OnLoad is exported, so sqlite3_api and our other symbols cannot bind to another library's. +# A change to the version script alone must relink. +set_target_properties(sqlitedbg PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/sqlitedbg.map) target_link_options(sqlitedbg PRIVATE -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/sqlitedbg.map -Wl,-z,max-page-size=16384) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index ac343b44af..d82e0a8302 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -760,8 +760,8 @@ internal fun interface IdleScheduler { ): () -> Unit } -/** One daemon timer thread per pending check, ended by its cancel. */ -private class TimerIdleScheduler : IdleScheduler { +/** One daemon timer thread per pending check, ended by its cancel or once its task has run. */ +internal class TimerIdleScheduler : IdleScheduler { override fun schedule( delayMs: Long, task: Runnable, @@ -769,7 +769,14 @@ private class TimerIdleScheduler : IdleScheduler { val timer = Timer("sqlite-debugger-idle", true) timer.schedule( object : TimerTask() { - override fun run() = task.run() + override fun run() { + try { + task.run() + } finally { + // The thread would otherwise stay parked until the next schedule cancels it. + timer.cancel() + } + } }, delayMs, ) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index 3e2e84ff87..2ad29603f5 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -243,7 +243,8 @@ class McpHttp( c.tcpNoDelay = true val input = BufferedInputStream(c.getInputStream()) val out = c.getOutputStream() - var headStart = System.currentTimeMillis() + // nanoTime, not the wall clock: a clock set back would extend the head's deadline (as in finishReply) + var headStart = System.nanoTime() var first = true while (running) { val req = @@ -254,10 +255,10 @@ class McpHttp( input.mark(1) if (input.read() < 0) return false input.reset() - headStart = System.currentTimeMillis() + headStart = System.nanoTime() } first = false - val head = readHead(input, c, headStart + headDeadlineMs) ?: return false + val head = readHead(input, c, headStart + headDeadlineMs * 1_000_000L) ?: return false // Refuse before reading a body, so an unauthenticated client never gets that far. if (!allowed(head, out)) return true c.soTimeout = IDLE_TIMEOUT_MS @@ -382,7 +383,7 @@ class McpHttp( return MessageDigest.isEqual(h.substring(7).trim().toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8)) } - /** The head of one request (no body yet), or null if the connection closed before one began. */ + /** The head of one request (no body yet), or null if the connection closed before one began. [deadlineAt] is in nanoTime. */ private fun readHead( input: InputStream, c: Socket, @@ -393,7 +394,7 @@ class McpHttp( fun read(): Int { // Each blocking read may wait only as long as the head has left, however slowly bytes come. if (input.available() == 0) { - val left = deadlineAt - System.currentTimeMillis() + val left = (deadlineAt - System.nanoTime()) / 1_000_000L if (left <= 0) throw SocketTimeoutException("the request's head took too long") c.soTimeout = minOf(left, IDLE_TIMEOUT_MS.toLong()).toInt() } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index c804bb99c1..9e87c546d5 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -1086,6 +1086,18 @@ class DatabaseToolsTest { t.onServerStopped() } + @Test fun theIdleTimerThreadEndsOnceItsCheckHasRun() { + fun idleThreads() = Thread.getAllStackTraces().keys.filter { it.name == "sqlite-debugger-idle" && it.isAlive }.toSet() + val before = idleThreads() + val ran = CountDownLatch(1) + TimerIdleScheduler().schedule(10) { ran.countDown() } + assertTrue(ran.await(5, TimeUnit.SECONDS)) + // other tests leave their own checks pending: only this schedule's thread must end + val mine = idleThreads() - before + mine.forEach { it.join(5_000) } + assertTrue("still parked: $mine", mine.none { it.isAlive }) + } + private class FakeIdleScheduler : IdleScheduler { class Check( val task: Runnable, From ebadb2dcb76c1e32bd9a7ad8b4abb063a83de68a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:03:06 -0800 Subject: [PATCH 3/4] ADFA-7295 style: spotless reformat of the idle-timer test, no functional change spotlessKotlinCheck's one change after 156d31509: ktlint wraps the idleThreads() call chain in theIdleTimerThreadEndsOnceItsCheckHasRun. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 9e87c546d5..e87c81ad28 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -1087,7 +1087,12 @@ class DatabaseToolsTest { } @Test fun theIdleTimerThreadEndsOnceItsCheckHasRun() { - fun idleThreads() = Thread.getAllStackTraces().keys.filter { it.name == "sqlite-debugger-idle" && it.isAlive }.toSet() + fun idleThreads() = + Thread + .getAllStackTraces() + .keys + .filter { it.name == "sqlite-debugger-idle" && it.isAlive } + .toSet() val before = idleThreads() val ran = CountDownLatch(1) TimerIdleScheduler().schedule(10) { ran.countDown() } From 50a44b3c35992c5404e6c250882b864489b5ef6f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 29 Nov 2026 23:01:35 -0800 Subject: [PATCH 4/4] ADFA-7295 McpProtocolTest: a held-connection test that survives a busy runner clientsThatTrickleOrNeverAuthenticateAreDroppedAndDoNotBlockTheRealOne failed on CI (#2323 at 1133a58b4, expected 503 but was 200). With headDeadlineMs at 600, a starved accept thread could still be accepting the 8 held connections when the first one reached its deadline, so the 9th client got a free slot. This is a test bug, not a server one (David's cloud session reproduced it under CPU load: 49 of 50 runs failed at 120 busy loops on one core, 0 of 45 after this change; ADFA-7131 comment 41723). Test only: the deadline is 2_000 ms, the trickler sends 30 lines instead of 20 so it still outlasts the deadline, the elapsed bound is 4_400 ms (under the 5 s socket read timeout), and the 503 assertion's message gives the time. The test still fails if the server resets the deadline on each read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/McpProtocolTest.kt | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 83612225dd..8264b89204 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -647,7 +647,7 @@ class McpProtocolTest { } @Test fun clientsThatTrickleOrNeverAuthenticateAreDroppedAndDoNotBlockTheRealOne() { - val s = McpHttp(protocol(), { token }, port = 0, headDeadlineMs = 600) + val s = McpHttp(protocol(), { token }, port = 0, headDeadlineMs = 2_000) s.start() server = s val port = s.boundPort @@ -666,12 +666,14 @@ class McpProtocolTest { } } } - // the slots are full: a real client is refused with 503 - assertEquals(503, http(port, "POST", headers = auth, body = initBody()).status) + // the slots are full: a real client is refused with 503. The deadline is long enough that a starved + // accept thread (a busy CI runner) still has every held connection open when this client arrives. + val refusedAtMs = (System.nanoTime() - started) / 1_000_000 + assertEquals("refused at $refusedAtMs ms", 503, http(port, "POST", headers = auth, body = initBody()).status) val trickler = Thread { try { - repeat(20) { + repeat(30) { Thread.sleep(200) held[0].getOutputStream().apply { write("X-Slow: 1\r\n".toByteArray()) @@ -686,7 +688,7 @@ class McpProtocolTest { // every held connection is closed by the server within the deadline plus slack for (c in held) assertEquals(-1, c.getInputStream().read()) val elapsedMs = (System.nanoTime() - started) / 1_000_000 - assertTrue("took $elapsedMs ms", elapsedMs < 3_000) + assertTrue("took $elapsedMs ms", elapsedMs < 4_400) assertEquals(200, http(port, "POST", headers = auth, body = initBody()).status) } finally { held.forEach { it.close() }