Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion subprojects/sqlite-debugger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ 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 <token>`, 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 but `execute` 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. A PRAGMA with an argument (`PRAGMA x = v`, `PRAGMA x(v)`) is refused as well, unless it is `table_info`, `table_xinfo`, `table_list`, `index_info`, `index_xinfo`, `index_list`, `foreign_key_list`, `foreign_key_check`, `integrity_check` or `quick_check`: SQLite applies a flag such as `foreign_keys`, `ignore_check_constraints`, `recursive_triggers` or `cache_size` while it prepares the statement, so refusing the write afterwards would come too late, and no setting can be changed. A PRAGMA without an argument only reads, and the table-valued `pragma_*` functions are checked as the PRAGMA they run. 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 run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300).
- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only` and `writable_schema` in any form, and every PRAGMA with an argument except the reads listed above and `user_version`, so `PRAGMA user_version = n` is the one setting it can change (the read-only connection refuses that too). So `application_id = n`, `wal_checkpoint(mode)` and `incremental_vacuum(n)` are refused on the writable connection as well; the read-only connection refuses the rest of this list too. The writable connection also enforces foreign keys (`sqlite3_db_config` with `SQLITE_DBCONFIG_ENABLE_FKEY`, set when it is opened), whatever the app's own connections do, so a write cannot leave orphan rows: `ON DELETE` and `ON UPDATE` actions run for its deletes and updates (their rows are not in `changes`), and a write the app itself could make with foreign keys off may be refused. SQLite's default is off (`SQLITE_DEFAULT_FOREIGN_KEYS` is 0, which the host tests confirm on their build); the read-only connection leaves it alone. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299).
- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only` and `writable_schema` in any form, and every PRAGMA with an argument except the reads listed above and `user_version`, so `PRAGMA user_version = n` is the one setting it can change (the read-only connection refuses that too). So `application_id = n`, `wal_checkpoint(mode)` and `incremental_vacuum(n)` are refused on the writable connection as well; the read-only connection refuses the rest of this list too. The writable connection also enforces foreign keys (`sqlite3_db_config` with `SQLITE_DBCONFIG_ENABLE_FKEY`, set when it is opened), whatever the app's own connections do, so a write cannot leave orphan rows: `ON DELETE` and `ON UPDATE` actions run for its deletes and updates (their rows are not in `changes`), and a write the app itself could make with foreign keys off may be refused. SQLite's default is off (`SQLITE_DEFAULT_FOREIGN_KEYS` is 0, which the host tests confirm on their build); the read-only connection leaves it alone. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again.
- **The first write to a Room database waits for an acknowledgement (ADFA-7299, D6).** Room records changes with TEMP triggers on its own connection, which a write on the server's connection does not fire, so its observers (Flow, LiveData, Paging, `InvalidationTracker`) miss it and a screen can show stale data. The debugger does not make Room refresh, as it must not change how the app behaves. Instead, `execute` looks for `room_master_table` on the read-only connection, and on a Room database it runs nothing and returns an error that says so, until the call is repeated with `acknowledge_room: true`. The acknowledgement is kept per database path for the life of `DatabaseTools`, one per app process (`DebuggerStartup`), so later writes to that database run without asking until the app restarts, and the check is not run again. A database without `room_master_table` never asks. The app's own connections and writes are not touched.
- **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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,23 @@ class DatabaseTools internal constructor(
"A statement is stopped and rolled back after 1.5 s (best effort: it can run up to about 3 s longer), in every " +
"journal mode, so a long write does not make the app's own writes fail; change fewer rows per call."

/** Said by execute's description: the first write to a Room database is refused until acknowledged (ADFA-7299). */
const val ROOM_DESCRIPTION =
"The first write to a Room database (one with room_master_table) is refused with a warning until it is sent again " +
"with acknowledge_room true; later writes to it run without asking until the app restarts."

/**
* Why a write to a Room database waits for acknowledge_room. Room records changes with TEMP triggers on its own
* connection, which a write on the server's connection does not fire, and the debugger must not change how the app
* behaves, so it does not make Room refresh (ADFA-7131, D6).
*/
const val ROOM_WARNING =
"Nothing was run: this is a Room database. Room learns about changes through triggers on its own connection, so it " +
"will not see a write from the debugger. Screens that observe this data (Flow, LiveData, Paging, " +
"InvalidationTracker) can show stale data, and the app's caches can keep old values, until the app queries again " +
"or restarts. Tell the user this; to write anyway, call execute again with acknowledge_room true. Later writes to " +
"this database then run without asking until the app restarts."

private const val READ_PRAGMAS_NOTE =
"table_info, table_xinfo, table_list, index_info, index_xinfo, index_list, foreign_key_list, " +
"foreign_key_check, integrity_check or quick_check (no setting can be changed)"
Expand Down Expand Up @@ -165,6 +182,12 @@ class DatabaseTools internal constructor(

/** execute's connections, apart from the read-only ones, so a read never runs where writes are allowed. */
private val writableConnections = HashMap<String, CachedConnection>()

/**
* Room databases execute may write to without asking again (ADFA-7299): acknowledged once with
* `acknowledge_room` in this server process. Guarded by [lock].
*/
private val roomAcknowledged = HashSet<String>()
private var clientConnected = false
private var lastEventsCallMs = 0L
private var cancelIdleCheck: (() -> Unit)? = null
Expand Down Expand Up @@ -303,10 +326,15 @@ class DatabaseTools internal constructor(
"changed), and PRAGMA locking_mode, busy_timeout, query_only, writable_schema, the heap limits and " +
"temp_store_directory in any form, as they would reach the app's own connections. $WRITE_NOTE " +
"The app is not told about the change: a screen showing this data may stay " +
"stale until it reads it again. $APP_FUNCTIONS_NOTE.",
"stale until it reads it again. $ROOM_DESCRIPTION $APP_FUNCTIONS_NOTE.",
databaseSchema(
"sql" to prop("string", "The SQL statement."),
"args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."),
"acknowledge_room" to
prop(
"boolean",
"Set to true, after telling the user, to write to a Room database: Room's observers will not see the change.",
),
required = listOf("sql"),
),
readOnly = false,
Expand Down Expand Up @@ -485,12 +513,39 @@ class DatabaseTools internal constructor(
): JSONObject {
val sql = stringArg(args, "sql")
val bind = bindArgs(args)
val result = withConnection(call, checkedPath(call, args), writable = true) { it.execute(sql, bind, call.deadline) }
val acknowledge =
when (val v = args.opt("acknowledge_room")) {
null, JSONObject.NULL -> false
is Boolean -> v
else -> throw McpToolError("acknowledge_room must be true or false.")
}
val path = checkedPath(call, args)
if (!call.locked { path in roomAcknowledged } && isRoomDatabase(call, path)) {
if (!acknowledge) {
throw McpToolError(ROOM_WARNING, JSONObject().put("room", true).put("acknowledge_with", "acknowledge_room"))
}
call.locked { roomAcknowledged += path }
}
val result = withConnection(call, path, writable = true) { it.execute(sql, bind, call.deadline) }
return JSONObject()
.put("changes", encodeLong(result.changes))
.put("last_insert_rowid", result.lastInsertRowid?.let { encodeLong(it) } ?: JSONObject.NULL)
}

/** Room creates room_master_table in every database it opens; read on the read-only connection. */
private fun isRoomDatabase(
call: Call,
path: String,
): Boolean =
runChecked(
call,
path,
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'room_master_table'",
emptyList(),
0,
QueryLimits(1, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES),
).rows.isNotEmpty()

private fun explain(
call: Call,
args: JSONObject,
Expand Down
Loading
Loading