From 67355bdbdfad3e3d311a060b4258ee122b43fd47 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 03:22:17 +0000 Subject: [PATCH 01/45] ADFA-7296 SQLite debugger: record row and change events in the extension Phase 2, P2-1 (ADFA-7131 comments 41476, 41477, 41489). - The record header grows from 56 to 72 bytes with rows and changes; every earlier field keeps its offset. SQLITEDBG_INTERFACE_VERSION 3. - PROFILE events carry the rows the statement returned and, for a statement that may write, its own change count (sqlite3_changes64, or 0 when sqlite3_total_changes64 did not move, so a CREATE TABLE does not report the previous write's count). -1 for a read. - New SQLITEDBG_EVENT_ROW: the first N rows of each statement, while a client is connected and sqlitedbg_set_row_capture is on. Off by default; nothing turns it on yet (the server will, ADFA-7297). - Each value is read with the accessor of its own type. Reading every column with sqlite3_column_text turns a BLOB into TEXT for the app. - Up to 16 statements per connection are followed from start to PROFILE. Rows of a statement not seen start are dropped, which drops SQLite's own nested statements (a CREATE TABLE's schema read). - EventDecoder.kt decodes the new header and row data; Event gains rows, changes, rowsCut and row, with defaults. - Fixture regenerated; README documents the layout and the limits. Tests: test.sh passes (ASan+UBSan, TSan, JNI 205). EventDecoderTest, DatabaseToolsTest and McpProtocolTest pass (108), compiled with the Kotlin compiler outside Gradle. Revert proofs: reading every column as text fails test_rows (BLOB read back as TEXT); recording rows with no slot fails test_internal_rows; plain sqlite3_changes64 fails test_changes. Not run here: Gradle, spotlessCheck, the Robolectric tests, and overhead on a phone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 7 + .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 183 ++++++- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 69 ++- .../sqlitedebugger/engine/DebugEngine.kt | 35 +- .../sqlitedebugger/engine/EventDecoder.kt | 83 +++- .../src/test/c/sqlitedbg_test.c | 467 +++++++++++++++++- .../sqlitedebugger/engine/EventDecoderTest.kt | 82 ++- .../sqlitedebugger/engine/events.bin | Bin 1792 -> 2760 bytes .../sqlitedebugger/engine/events.tsv | 47 +- 9 files changed, 893 insertions(+), 80 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 236123db27..979c0608bb 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -30,6 +30,13 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer hands the bytes to Kotlin unchanged, so `EventDecoder.kt` mirrors the layout, field offsets included: change both together. A committed fixture pins them (see Testing). +**Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). +- A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and a statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). +- `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). +- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit; both are marked. +- The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. +- Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. It has not been measured on a phone yet. + ## Decisions that shape it - **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. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index d55c47afac..ab6451bc94 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -22,14 +22,31 @@ SQLITE_EXTENSION_INIT1 #define DEFAULT_BUFFER_BYTES ((size_t)4 << 20) #define DEFAULT_MAX_SQL_BYTES 4096u -#define RECORD_HEADER_BYTES 56u +#define DEFAULT_MAX_VALUE_BYTES 256u +#define DEFAULT_MAX_ROW_BYTES 4096u +#define RECORD_HEADER_BYTES 72u +#define ROW_HEADER_BYTES 8u +#define ROW_VALUE_BYTES 12u _Static_assert(sizeof(sqlitedbg_event_record) == RECORD_HEADER_BYTES, "event record layout"); +_Static_assert(sizeof(sqlitedbg_row_header) == ROW_HEADER_BYTES, "row header layout"); +_Static_assert(sizeof(sqlitedbg_row_value) == ROW_VALUE_BYTES, "row value layout"); // Padding record written where the next record would not fit before the end of the ring, so a // record is always contiguous. kind 0 is never a real event. #define KIND_PAD 0u +// A statement the extension saw start on a connection (a TRACE_STMT that is not a trigger's or a +// nested statement's), until its PROFILE event. +typedef struct stmt_slot { + sqlite3_stmt *stmt; // NULL: free + int64_t rows; // TRACE_ROW events so far + int64_t recorded; // of those, recorded as SQLITEDBG_EVENT_ROW + int rows_cut; // a row went unrecorded because of the per-statement limit + sqlite3_int64 total_changes; // sqlite3_total_changes64 when it started + uint64_t last_use; // for evicting the least recently used slot +} stmt_slot; + typedef struct conn_state { struct conn_state *prev, *next; uint64_t id; @@ -38,6 +55,10 @@ typedef struct conn_state { int closing; // atomic: set by the close event, cleared by a later statement event int64_t opened_at_ns; int64_t open_thread_id; + // Used only from the trace callback, which runs on the thread using the connection: requery's + // SQLITE_THREADSAFE=2 means one thread at a time, so these need no lock. + stmt_slot slots[SQLITEDBG_STATEMENT_SLOTS]; + uint64_t use_clock; } conn_state; // Taken only for the fields below; never while SQLite runs. @@ -49,6 +70,10 @@ static int g_installed; // g_install_lock static int g_api_ready; // g_lock: sqlite3_api has been saved static uint32_t g_max_sql; // set before g_installed, then read-only static int g_client_connected; // atomic +// Row recording (sqlitedbg_set_row_capture); each read on its own, so a change mid-row is harmless. +static uint32_t g_max_rows; // atomic; 0: off +static uint32_t g_max_value = DEFAULT_MAX_VALUE_BYTES; // atomic +static uint32_t g_max_row = DEFAULT_MAX_ROW_BYTES; // atomic static conn_state *g_first, *g_last; static uint64_t g_next_conn_id = 1; @@ -129,13 +154,12 @@ static size_t utf8_cut(const char *sql, size_t len, size_t max) { return max; } -static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns, uint32_t flags, - const char *sql, size_t sql_len) { +// Adds one record with `len` bytes of data, already within the limits. +static void add_record(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, + uint32_t flags, const void *data, size_t len) { int64_t time = now_ns(); int64_t tid = this_thread_id(); - size_t kept = utf8_cut(sql, sql_len, g_max_sql); - if (kept < sql_len) flags |= SQLITEDBG_EVENT_TRUNCATED; - size_t need = (RECORD_HEADER_BYTES + kept + 7) & ~(size_t)7; + size_t need = (RECORD_HEADER_BYTES + len + 7) & ~(size_t)7; pthread_mutex_lock(&g_lock); uint64_t seq = g_next_seq++; @@ -150,9 +174,11 @@ static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns r->time_ns = time; r->duration_ns = duration_ns; r->flags = flags; - r->sql_bytes = (uint32_t)kept; - memcpy((unsigned char *)r + RECORD_HEADER_BYTES, sql, kept); - memset((unsigned char *)r + RECORD_HEADER_BYTES + kept, 0, need - RECORD_HEADER_BYTES - kept); + r->data_bytes = (uint32_t)len; + r->rows = rows; + r->changes = changes; + memcpy((unsigned char *)r + RECORD_HEADER_BYTES, data, len); + memset((unsigned char *)r + RECORD_HEADER_BYTES + len, 0, need - RECORD_HEADER_BYTES - len); g_head += need; g_used += need; if (g_head >= g_cap) g_head = 0; @@ -160,6 +186,94 @@ static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns pthread_mutex_unlock(&g_lock); } +static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, + uint32_t flags, const char *sql, size_t sql_len) { + size_t kept = utf8_cut(sql, sql_len, g_max_sql); + if (kept < sql_len) flags |= SQLITEDBG_EVENT_TRUNCATED; + add_record(kind, connection_id, duration_ns, rows, changes, flags, sql, kept); +} + +static stmt_slot *find_slot(conn_state *cs, sqlite3_stmt *stmt) { + for (int i = 0; i < SQLITEDBG_STATEMENT_SLOTS; i++) + if (cs->slots[i].stmt == stmt) return &cs->slots[i]; + return NULL; +} + +// The slot for a statement that starts: its old one if it is restarting, else a free one, else the +// least recently used. +static stmt_slot *claim_slot(conn_state *cs, sqlite3_stmt *stmt) { + stmt_slot *slot = find_slot(cs, stmt); + if (!slot) slot = find_slot(cs, NULL); + if (!slot) { + slot = &cs->slots[0]; + for (int i = 1; i < SQLITEDBG_STATEMENT_SLOTS; i++) + if (cs->slots[i].last_use < slot->last_use) slot = &cs->slots[i]; + } + memset(slot, 0, sizeof *slot); + slot->stmt = stmt; + slot->last_use = ++cs->use_clock; + return slot; +} + +static size_t put_value(unsigned char *out, uint8_t type, uint8_t cut, uint32_t stored, uint32_t full) { + sqlitedbg_row_value v = {type, cut, 0, stored, full}; + memcpy(out, &v, sizeof v); + return sizeof v; +} + +// Records the row the statement is on. Each column is read with the accessor of its own type, so +// nothing is converted and the app's later sqlite3_column_type and values are unchanged. +static void record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { + uint32_t max_value = __atomic_load_n(&g_max_value, __ATOMIC_RELAXED); + size_t budget = __atomic_load_n(&g_max_row, __ATOMIC_RELAXED); + // A record must fit beside a pad in the ring (see sqlitedbg_install). + size_t ring_max = g_cap / 2 > RECORD_HEADER_BYTES ? g_cap / 2 - RECORD_HEADER_BYTES : 0; + if (budget > ring_max) budget = ring_max; + if (budget < ROW_HEADER_BYTES) return; + unsigned char *data = (unsigned char *)malloc(budget); + if (!data) return; + int columns = sqlite3_column_count(stmt); + size_t len = ROW_HEADER_BYTES; + uint32_t kept = 0; + uint32_t flags = 0; + for (int i = 0; i < columns; i++) { + if (budget - len < ROW_VALUE_BYTES) break; + size_t room = budget - len - ROW_VALUE_BYTES; + int type = sqlite3_column_type(stmt, i); + unsigned char *v = data + len; + if (type == SQLITE_INTEGER || type == SQLITE_FLOAT) { + if (room < 8) break; + if (type == SQLITE_INTEGER) { + sqlite3_int64 n = sqlite3_column_int64(stmt, i); + memcpy(v + ROW_VALUE_BYTES, &n, 8); + } else { + double d = sqlite3_column_double(stmt, i); + memcpy(v + ROW_VALUE_BYTES, &d, 8); + } + len += put_value(v, (uint8_t)type, 0, 8, 8) + 8; + } else if (type == SQLITE_TEXT || type == SQLITE_BLOB) { + // For TEXT, sqlite3_column_text first and then sqlite3_column_bytes, as SQLite advises. + const void *p = type == SQLITE_TEXT ? (const void *)sqlite3_column_text(stmt, i) : sqlite3_column_blob(stmt, i); + size_t full = (size_t)sqlite3_column_bytes(stmt, i); + size_t limit = room < max_value ? room : max_value; + size_t stored = type == SQLITE_TEXT ? utf8_cut((const char *)p, full, limit) : (full < limit ? full : limit); + if (!p) stored = 0; + uint8_t cut = stored < full; + if (cut) flags |= SQLITEDBG_EVENT_TRUNCATED; + if (stored) memcpy(v + ROW_VALUE_BYTES, p, stored); + len += put_value(v, (uint8_t)type, cut, (uint32_t)stored, (uint32_t)full) + stored; + } else { + len += put_value(v, SQLITE_NULL, 0, 0, 0); + } + kept++; + } + if (kept < (uint32_t)columns) flags |= SQLITEDBG_EVENT_TRUNCATED; + sqlitedbg_row_header h = {(uint32_t)columns, kept}; + memcpy(data, &h, sizeof h); + add_record(SQLITEDBG_EVENT_ROW, cs->id, -1, number, -1, flags, data, len); + free(data); +} + // sqlite3_trace_v2 callback. C is the connection's conn_state, which lives until SQLite frees the // connection, so it outlives every callback. static int trace_cb(unsigned type, void *c, void *p, void *x) { @@ -194,15 +308,51 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { } } int64_t duration = is_stmt ? -1 : *(sqlite3_int64 *)x; - add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, flags, sql, - strlen(sql)); + int64_t rows = -1, changes = -1; + if (is_stmt) { + // SQLite's own nested statements (the schema read a CREATE TABLE runs, for one) are traced + // with "--" text like a trigger, so they get no slot and their rows are never recorded. + if (!is_trigger) claim_slot(cs, stmt)->total_changes = sqlite3_total_changes64(sqlite3_db_handle(stmt)); + } else { + stmt_slot *slot = find_slot(cs, stmt); + if (slot) { + rows = slot->rows; + if (slot->rows_cut) flags |= SQLITEDBG_EVENT_ROWS_CUT; + if (!sqlite3_stmt_readonly(stmt)) { + // sqlite3_changes64 is this statement's count once it has run, but only INSERT, UPDATE + // and DELETE set it: after a CREATE TABLE it still holds the last write's. A total that + // did not move means the statement changed nothing. + sqlite3 *db = sqlite3_db_handle(stmt); + changes = sqlite3_total_changes64(db) == slot->total_changes ? 0 : sqlite3_changes64(db); + } + memset(slot, 0, sizeof *slot); + } + } + add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, rows, changes, + flags, sql, strlen(sql)); if (expanded) sqlite3_free(expanded); break; } + case SQLITE_TRACE_ROW: { + sqlite3_stmt *stmt = (sqlite3_stmt *)p; + stmt_slot *slot = find_slot(cs, stmt); + if (!slot) break; + slot->rows++; + slot->last_use = ++cs->use_clock; + uint32_t max_rows = __atomic_load_n(&g_max_rows, __ATOMIC_RELAXED); + if (!max_rows || !__atomic_load_n(&g_client_connected, __ATOMIC_RELAXED)) break; + if (slot->recorded >= max_rows) { + slot->rows_cut = 1; + break; + } + slot->recorded++; + record_row(cs, stmt, slot->rows); + break; + } case SQLITE_TRACE_CLOSE: // The close can still fail or leave a zombie, so only mark it: xDestroy frees. __atomic_store_n(&cs->closing, 1, __ATOMIC_RELAXED); - add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, 0, "", 0); + add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, -1, -1, 0, "", 0); break; } return 0; @@ -287,7 +437,8 @@ static int init_connection(sqlite3 *db, const sqlite3_api_routines *api) { int rc = sqlite3_create_function_v2(db, fn_name, 0, SQLITE_UTF8 | SQLITE_INNOCUOUS, cs, connection_id_fn, NULL, NULL, conn_destroy); if (rc != SQLITE_OK) return rc; - return sqlite3_trace_v2(db, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE | SQLITE_TRACE_CLOSE, trace_cb, cs); + return sqlite3_trace_v2(db, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE | SQLITE_TRACE_ROW | SQLITE_TRACE_CLOSE, + trace_cb, cs); } int sqlitedbg_install(sqlitedbg_auto_extension_fn auto_extension, const sqlitedbg_config *config) { @@ -391,6 +542,12 @@ void sqlitedbg_set_client_connected(int connected) { __atomic_store_n(&g_client_connected, connected ? 1 : 0, __ATOMIC_RELAXED); } +void sqlitedbg_set_row_capture(uint32_t max_rows_per_statement, uint32_t max_value_bytes, uint32_t max_row_bytes) { + __atomic_store_n(&g_max_value, max_value_bytes ? max_value_bytes : DEFAULT_MAX_VALUE_BYTES, __ATOMIC_RELAXED); + __atomic_store_n(&g_max_row, max_row_bytes ? max_row_bytes : DEFAULT_MAX_ROW_BYTES, __ATOMIC_RELAXED); + __atomic_store_n(&g_max_rows, max_rows_per_statement, __ATOMIC_RELAXED); +} + static int server_authorizer(void *unused, int action, const char *a1, const char *a2, const char *db, const char *trigger) { (void)unused; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 4b342ce878..9e74b1aa6b 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -23,7 +23,7 @@ extern "C" { #endif // The interface version. Raise it when anything below changes shape. -#define SQLITEDBG_INTERFACE_VERSION 2 +#define SQLITEDBG_INTERFACE_VERSION 3 // sqlite3_auto_extension's type. On a device the JNI layer looks it up in libsqlite3x.so with // dlsym (requery exports every sqlite3_ function); host tests pass SQLite's own. @@ -85,31 +85,70 @@ enum { SQLITEDBG_EVENT_PROFILE = 2, // The app asked SQLite to close the connection (SQLITE_TRACE_CLOSE); sql is empty. SQLITEDBG_EVENT_CLOSE = 3, + // A statement returned a row (SQLITE_TRACE_ROW). Recorded only while a client is connected and + // row recording is on (sqlitedbg_set_row_capture); the data is the row's values, in the row + // layout below, not SQL. rows is the row's number in its statement, from 1. + SQLITEDBG_EVENT_ROW = 4, }; enum { - // sql was cut at max_sql_bytes. + // The data was cut: SQL at max_sql_bytes, or a row's values at the row limits. SQLITEDBG_EVENT_TRUNCATED = 1u << 0, // sql has its bound values written in (sqlite3_expanded_sql). Only while a client is // connected (sqlitedbg_set_client_connected): expanding a 1 MB value costs 2 MB on every run. SQLITEDBG_EVENT_EXPANDED = 1u << 1, + // SQLITEDBG_EVENT_PROFILE only: rows were left unrecorded because the statement returned more than + // the per-statement limit while row recording was on. + SQLITEDBG_EVENT_ROWS_CUT = 1u << 2, }; -// One event as sqlitedbg_read_events copies it out: this header, then sql_bytes of UTF-8 (no -// terminating NUL), then zero padding to a multiple of 8 bytes. Fields are in the CPU's byte order +// One event as sqlitedbg_read_events copies it out: this header, then data_bytes of data, then zero +// padding to a multiple of 8 bytes. The data is UTF-8 SQL (no terminating NUL) for every kind but +// SQLITEDBG_EVENT_ROW, whose data is its values (below). Fields are in the CPU's byte order // (little-endian on every ABI we build). The JNI layer hands the bytes to Kotlin unchanged, so // EventDecoder.kt mirrors this layout; change both together. typedef struct sqlitedbg_event_record { uint32_t record_bytes; // the whole record, padding included - uint32_t kind; // SQLITEDBG_EVENT_STATEMENT, _PROFILE or _CLOSE + uint32_t kind; // SQLITEDBG_EVENT_STATEMENT, _PROFILE, _CLOSE or _ROW uint64_t seq; // 1, 2, 3...: every event made, dropped or not, gets the next one uint64_t connection_id; // sqlitedbg_connection.id int64_t thread_id; // gettid() of the thread running the statement int64_t time_ns; // CLOCK_REALTIME when the event happened int64_t duration_ns; // SQLITEDBG_EVENT_PROFILE only; -1 for the others - uint32_t flags; // SQLITEDBG_EVENT_TRUNCATED, SQLITEDBG_EVENT_EXPANDED - uint32_t sql_bytes; -} sqlitedbg_event_record; // 56 bytes; the SQL text follows + uint32_t flags; // SQLITEDBG_EVENT_TRUNCATED, _EXPANDED, _ROWS_CUT + uint32_t data_bytes; + // SQLITEDBG_EVENT_PROFILE: the rows the statement returned, whether or not they were recorded. + // SQLITEDBG_EVENT_ROW: this row's number, from 1. -1 otherwise, and -1 for a statement the + // extension did not see start (SQLite's own nested statements, or more than + // SQLITEDBG_STATEMENT_SLOTS statements stepped in turn on one connection). + int64_t rows; + // SQLITEDBG_EVENT_PROFILE of a statement that may write (sqlite3_stmt_readonly false): the rows + // it changed itself, as sqlite3_changes64 counts them (not those changed by triggers or foreign + // key actions); 0 when it changed none, as a CREATE TABLE. -1 for a read-only statement, for the + // other kinds, and when rows is -1. + int64_t changes; +} sqlitedbg_event_record; // 72 bytes; the data follows + +// How many statements per connection the extension follows at once, to number their rows and count +// their changes. A connection that steps more statements in turn than this loses the oldest: +// its rows are not recorded and its PROFILE event has rows and changes -1. +#define SQLITEDBG_STATEMENT_SLOTS 16 + +// The data of an SQLITEDBG_EVENT_ROW: this header, then `kept` values, each a sqlitedbg_row_value +// followed by stored_bytes of value. Nothing is aligned: read each field with memcpy. +typedef struct sqlitedbg_row_header { + uint32_t columns; // sqlite3_column_count of the statement + uint32_t kept; // values that follow; fewer than columns when the row limit was reached +} sqlitedbg_row_header; // 8 bytes + +typedef struct sqlitedbg_row_value { + uint8_t type; // SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB or SQLITE_NULL + uint8_t cut; // 1 if fewer than full_bytes were stored + uint16_t reserved; // 0 + uint32_t stored_bytes; // bytes that follow: 8 for INTEGER (int64) and FLOAT (IEEE double), + // 0 for NULL, UTF-8 for TEXT (cut at a character boundary), BLOB bytes + uint32_t full_bytes; // the value's whole size (sqlite3_column_bytes for TEXT and BLOB) +} sqlitedbg_row_value; // 12 bytes typedef struct sqlitedbg_read_result { // The seq of the last event copied out, or if none was, `after` moved past any dropped events @@ -137,9 +176,21 @@ typedef struct sqlitedbg_read_result { void sqlitedbg_read_events(uint64_t after, void *out, size_t out_bytes, sqlitedbg_read_result *result); // Whether a client is connected. While it is, statements are recorded with their bound values -// written in. Off at install. +// written in, and rows if row recording is on. Off at install. void sqlitedbg_set_client_connected(int connected); +// Turns row recording on (max_rows_per_statement > 0) or off (0, as at install). While it is on and +// a client is connected, the first max_rows_per_statement rows of each statement become +// SQLITEDBG_EVENT_ROW events. TEXT and BLOB values longer than max_value_bytes are cut (0: 256), and +// a row's data stops at max_row_bytes (0: 4 KiB; never more than half the buffer less one header). +// Each value is read with the accessor of its own type (sqlite3_column_type first), so the app sees +// the same values and types afterwards: sqlite3_column_text converts a value in place, and on a BLOB +// it makes the app's own sqlite3_column_type return SQLITE_TEXT (SQLite 3.49.1, sqlitedbg_test.c). Rows of statements the extension did +// not see start are never recorded: that drops the rows of SQLite's own nested statements, such as +// the schema read a CREATE TABLE runs. PROFILE events count rows whether or not this is on. +void sqlitedbg_set_row_capture(uint32_t max_rows_per_statement, uint32_t max_value_bytes, + uint32_t max_row_bytes); + // Server connections #define SQLITEDBG_SERVER_BUSY_MS 3000 diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 0225492399..0c3fa07de0 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -91,6 +91,12 @@ enum class EventKind( /** The app asked SQLite to close the connection; [Event.sql] is empty. */ CLOSE(3), + + /** + * A statement returned a row, recorded only while a client is connected and row recording is on. + * [Event.row] holds its values, [Event.rows] its number in the statement; [Event.sql] is empty. + */ + ROW(4), } data class Event( @@ -103,10 +109,37 @@ data class Event( /** Set for [EventKind.PROFILE] only. */ val durationNanos: Long?, val sql: String, - /** [sql] was cut at the extension's limit. */ + /** [sql] was cut at the extension's limit, or for [EventKind.ROW], [row] was (see [RowValues]). */ val truncated: Boolean, /** [sql] has its bound values written in. */ val expanded: Boolean, + /** + * [EventKind.PROFILE]: the rows the statement returned, recorded or not. [EventKind.ROW]: the row's + * number in its statement, from 1. Null otherwise, and for a statement the extension did not see start. + */ + val rows: Long? = null, + /** + * [EventKind.PROFILE] of a statement that may write: the rows it changed itself, as + * `sqlite3_changes64` counts them (not those changed by triggers); 0 when it changed none. Null for a + * read-only statement and for the other kinds. + */ + val changes: Long? = null, + /** [EventKind.PROFILE]: rows went unrecorded because the statement returned more than the per-statement limit. */ + val rowsCut: Boolean = false, + /** [EventKind.ROW] only: the row's values. */ + val row: RowValues? = null, +) + +data class RowValues( + /** The statement's column count. */ + val columnCount: Int, + /** + * The values kept, in column order: null, [Long], [Double], [String] or [ByteArray]. Fewer than + * [columnCount] when the row's data reached its limit. + */ + val values: List, + /** Indexes into [values] of TEXT and BLOB values that were cut at the value limit. */ + val cutIndexes: Set, ) data class EventBatch( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt index 73af648598..0124530255 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -4,12 +4,13 @@ import java.nio.ByteBuffer import java.nio.ByteOrder /** - * Decodes the records `sqlitedbg_read_events` copies out. Mirrors `sqlitedbg_event_record` in - * `sqlitedbg.h`: change both together. Little-endian, because the CPU is on every ABI we build. + * Decodes the records `sqlitedbg_read_events` copies out. Mirrors `sqlitedbg_event_record` and the + * row layout (`sqlitedbg_row_header`, `sqlitedbg_row_value`) in `sqlitedbg.h`: change both together. + * Little-endian, because the CPU is on every ABI we build. */ internal object EventDecoder { /** `sizeof(sqlitedbg_event_record)`. */ - const val HEADER_BYTES = 56 + const val HEADER_BYTES = 72 private const val OFFSET_RECORD_BYTES = 0 private const val OFFSET_KIND = 4 @@ -19,10 +20,23 @@ internal object EventDecoder { private const val OFFSET_TIME_NS = 32 private const val OFFSET_DURATION_NS = 40 private const val OFFSET_FLAGS = 48 - private const val OFFSET_SQL_BYTES = 52 + private const val OFFSET_DATA_BYTES = 52 + private const val OFFSET_ROWS = 56 + private const val OFFSET_CHANGES = 64 private const val FLAG_TRUNCATED = 1 private const val FLAG_EXPANDED = 2 + private const val FLAG_ROWS_CUT = 4 + + private const val ROW_HEADER_BYTES = 8 + private const val ROW_VALUE_BYTES = 12 + + // SQLite's fundamental types, as sqlite3_column_type returns them. + private const val SQLITE_INTEGER = 1 + private const val SQLITE_FLOAT = 2 + private const val SQLITE_TEXT = 3 + private const val SQLITE_BLOB = 4 + private const val SQLITE_NULL = 5 /** * The records in the first [length] bytes of [bytes]. @@ -40,9 +54,9 @@ internal object EventDecoder { while (offset < length) { require(length - offset >= HEADER_BYTES) { "record at $offset is cut off by the end of the data" } val recordBytes = buffer.getInt(offset + OFFSET_RECORD_BYTES) - val sqlBytes = buffer.getInt(offset + OFFSET_SQL_BYTES) - require(sqlBytes >= 0 && recordBytes >= 0 && recordBytes % 8 == 0 && sqlBytes <= recordBytes - HEADER_BYTES) { - "record at $offset has record_bytes=$recordBytes sql_bytes=$sqlBytes" + val dataBytes = buffer.getInt(offset + OFFSET_DATA_BYTES) + require(dataBytes >= 0 && recordBytes >= 0 && recordBytes % 8 == 0 && dataBytes <= recordBytes - HEADER_BYTES) { + "record at $offset has record_bytes=$recordBytes data_bytes=$dataBytes" } require(recordBytes <= length - offset) { "record at $offset runs past the end of the data" } val kindValue = buffer.getInt(offset + OFFSET_KIND) @@ -50,6 +64,10 @@ internal object EventDecoder { EventKind.values().firstOrNull { it.nativeValue == kindValue } ?: throw IllegalArgumentException("record at $offset has unknown kind $kindValue") val flags = buffer.getInt(offset + OFFSET_FLAGS) + val dataStart = offset + HEADER_BYTES + // -1 in the record: does not apply, or the extension did not see the statement start + val rows = buffer.getLong(offset + OFFSET_ROWS).takeIf { it >= 0 && (kind == EventKind.PROFILE || kind == EventKind.ROW) } + val changes = buffer.getLong(offset + OFFSET_CHANGES).takeIf { it >= 0 && kind == EventKind.PROFILE } events += Event( seq = buffer.getLong(offset + OFFSET_SEQ), @@ -58,12 +76,61 @@ internal object EventDecoder { threadId = buffer.getLong(offset + OFFSET_THREAD_ID), timeEpochNanos = buffer.getLong(offset + OFFSET_TIME_NS), durationNanos = if (kind == EventKind.PROFILE) buffer.getLong(offset + OFFSET_DURATION_NS) else null, - sql = String(bytes, offset + HEADER_BYTES, sqlBytes, Charsets.UTF_8), + sql = if (kind == EventKind.ROW) "" else String(bytes, dataStart, dataBytes, Charsets.UTF_8), truncated = flags and FLAG_TRUNCATED != 0, expanded = flags and FLAG_EXPANDED != 0, + rows = rows, + changes = changes, + rowsCut = kind == EventKind.PROFILE && flags and FLAG_ROWS_CUT != 0, + row = if (kind == EventKind.ROW) decodeRow(bytes, buffer, dataStart, dataBytes) else null, ) offset += recordBytes } return events } + + private fun decodeRow( + bytes: ByteArray, + buffer: ByteBuffer, + start: Int, + length: Int, + ): RowValues { + require(length >= ROW_HEADER_BYTES) { "row at $start is shorter than its header" } + val end = start + length + val columns = buffer.getInt(start) + val kept = buffer.getInt(start + 4) + require(columns >= 0 && kept in 0..columns) { "row at $start has columns=$columns kept=$kept" } + val values = ArrayList(kept) + val cut = HashSet() + var pos = start + ROW_HEADER_BYTES + repeat(kept) { i -> + require(end - pos >= ROW_VALUE_BYTES) { "row at $start: value $i is cut off" } + val type = buffer.get(pos).toInt() and 0xff + val isCut = buffer.get(pos + 1).toInt() != 0 + val stored = buffer.getInt(pos + 4) + val full = buffer.getInt(pos + 8) + pos += ROW_VALUE_BYTES + require(stored in 0..(end - pos) && full >= stored && isCut == (stored < full)) { + "row at $start: value $i has stored_bytes=$stored full_bytes=$full cut=$isCut" + } + values += + when (type) { + SQLITE_INTEGER, SQLITE_FLOAT -> { + require(stored == 8) { "row at $start: number $i is $stored bytes" } + if (type == SQLITE_INTEGER) buffer.getLong(pos) else buffer.getDouble(pos) + } + SQLITE_TEXT -> String(bytes, pos, stored, Charsets.UTF_8) + SQLITE_BLOB -> bytes.copyOfRange(pos, pos + stored) + SQLITE_NULL -> { + require(stored == 0) { "row at $start: null $i has $stored bytes" } + null + } + else -> throw IllegalArgumentException("row at $start: value $i has unknown type $type") + } + if (isCut) cut += i + pos += stored + } + require(pos == end) { "row at $start has ${end - pos} bytes after its last value" } + return RowValues(columns, values, cut) + } } diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 5f3d6c637d..266666e229 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -66,12 +66,15 @@ static sqlite3 *open_app(const char *path) { // Events +// The largest row data a test records (sqlitedbg_set_row_capture's max_row_bytes in the row tests). +#define MAX_ROW_DATA 1024 + typedef struct ev { uint32_t kind, flags; uint64_t seq, conn; - int64_t tid, time_ns, duration_ns; - char sql[MAX_SQL * 4 + 8]; - uint32_t sql_bytes; + int64_t tid, time_ns, duration_ns, rows, changes; + char sql[MAX_ROW_DATA + 8]; // SQL text, or a row's data for SQLITEDBG_EVENT_ROW + uint32_t data_bytes; } ev; typedef struct batch { @@ -101,9 +104,12 @@ static void read_all(uint64_t after, batch *b) { const sqlitedbg_event_record *rec = (const sqlitedbg_event_record *)(void *)(buf + off); CHECK(rec->record_bytes >= sizeof *rec); CHECK_EQ(rec->record_bytes % 8, 0); - CHECK(rec->sql_bytes <= MAX_SQL); - CHECK(rec->record_bytes >= sizeof *rec + rec->sql_bytes); + CHECK(rec->data_bytes <= (rec->kind == SQLITEDBG_EVENT_ROW ? MAX_ROW_DATA : MAX_SQL)); + CHECK(rec->record_bytes >= sizeof *rec + rec->data_bytes); CHECK(rec->seq > prev); + // rows and changes are -1 where they do not apply + if (rec->kind != SQLITEDBG_EVENT_PROFILE && rec->kind != SQLITEDBG_EVENT_ROW) CHECK_EQ(rec->rows, -1); + if (rec->kind != SQLITEDBG_EVENT_PROFILE) CHECK_EQ(rec->changes, -1); prev = rec->seq; ev *e = &b->events[i]; e->kind = rec->kind; @@ -113,9 +119,11 @@ static void read_all(uint64_t after, batch *b) { e->tid = rec->thread_id; e->time_ns = rec->time_ns; e->duration_ns = rec->duration_ns; - e->sql_bytes = rec->sql_bytes; - memcpy(e->sql, (const char *)buf + off + sizeof *rec, rec->sql_bytes); - e->sql[rec->sql_bytes] = 0; + e->rows = rec->rows; + e->changes = rec->changes; + e->data_bytes = rec->data_bytes; + memcpy(e->sql, (const char *)buf + off + sizeof *rec, rec->data_bytes); + e->sql[rec->data_bytes] = 0; off += rec->record_bytes; } CHECK_EQ(off, r.bytes); @@ -220,7 +228,7 @@ static void test_install(void) { read_all(cur, &b); CHECK_EQ(b.count, 2); CHECK(b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED); - CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + CHECK_EQ(b.events[0].data_bytes, MAX_SQL); batch_free(&b); } @@ -251,6 +259,9 @@ static void test_events(void) { CHECK_EQ(b.events[3].kind, SQLITEDBG_EVENT_PROFILE); CHECK(strcmp(b.events[3].sql, "INSERT INTO t VALUES(?)") == 0); CHECK(b.events[3].duration_ns >= 0); + // no rows; one row changed by the insert itself, not counting the trigger's + CHECK_EQ(b.events[3].rows, 0); + CHECK_EQ(b.events[3].changes, 1); for (size_t i = 0; i < b.count; i++) { CHECK_EQ(b.events[i].conn, 1); CHECK_EQ(b.events[i].tid, tid()); @@ -338,7 +349,7 @@ static void test_expanded(void) { read_all(cur, &b); CHECK(b.events[0].flags & SQLITEDBG_EVENT_EXPANDED); CHECK(b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED); - CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + CHECK_EQ(b.events[0].data_bytes, MAX_SQL); batch_free(&b); } @@ -357,9 +368,9 @@ static void test_truncation(void) { read_all(cur, &b); CHECK_EQ(b.count, 2); for (int i = 0; i < 2; i++) { - CHECK_EQ(b.events[i].sql_bytes, 62); + CHECK_EQ(b.events[i].data_bytes, 62); CHECK(b.events[i].flags & SQLITEDBG_EVENT_TRUNCATED); - CHECK(utf8_valid(b.events[i].sql, b.events[i].sql_bytes)); + CHECK(utf8_valid(b.events[i].sql, b.events[i].data_bytes)); } batch_free(&b); @@ -372,8 +383,8 @@ static void test_truncation(void) { exec_ok(g_main, sql); read_all(cur, &b); CHECK_EQ(b.count, 2); - CHECK_EQ(b.events[0].sql_bytes, 63); - CHECK(utf8_valid(b.events[0].sql, b.events[0].sql_bytes)); + CHECK_EQ(b.events[0].data_bytes, 63); + CHECK(utf8_valid(b.events[0].sql, b.events[0].data_bytes)); batch_free(&b); // exactly at the limit is whole, one byte over is cut @@ -388,12 +399,348 @@ static void test_truncation(void) { cur = cursor_now(); exec_ok(g_main, sql); read_all(cur, &b); - CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + CHECK_EQ(b.events[0].data_bytes, MAX_SQL); CHECK_EQ((b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED) != 0, over); batch_free(&b); } } +// Rows and changes (ADFA-7296) + +typedef struct rv { + int type, cut; + uint32_t stored, full; + const unsigned char *p; +} rv; + +// Parses a ROW event's data into at most max values; checks it is exactly as long as data_bytes. +// Returns the values kept, or -1 if the data is malformed. +static int parse_row(const ev *e, uint32_t *columns, rv *vals, int max) { + const unsigned char *d = (const unsigned char *)e->sql; + size_t n = e->data_bytes, off = sizeof(sqlitedbg_row_header); + if (n < off) return -1; + sqlitedbg_row_header h; + memcpy(&h, d, sizeof h); + *columns = h.columns; + if (h.kept > h.columns || (int)h.kept > max) return -1; + for (uint32_t i = 0; i < h.kept; i++) { + sqlitedbg_row_value v; + if (n - off < sizeof v) return -1; + memcpy(&v, d + off, sizeof v); + off += sizeof v; + if (v.stored_bytes > n - off || v.stored_bytes > v.full_bytes || v.reserved != 0 || v.cut != (v.stored_bytes < v.full_bytes)) return -1; + vals[i] = (rv){v.type, v.cut, v.stored_bytes, v.full_bytes, d + off}; + off += v.stored_bytes; + } + return off == n ? (int)h.kept : -1; +} + +static int64_t rv_int(const rv *v) { + int64_t x = 0; + if (v->stored == 8) memcpy(&x, v->p, 8); + return x; +} + +static double rv_double(const rv *v) { + double x = 0; + if (v->stored == 8) memcpy(&x, v->p, 8); + return x; +} + +// The last event of `kind` whose SQL is `sql`, or NULL. +static const ev *find_event(const batch *b, uint32_t kind, const char *sql) { + for (size_t i = b->count; i-- > 0;) + if (b->events[i].kind == kind && strcmp(b->events[i].sql, sql) == 0) return &b->events[i]; + return NULL; +} + +static size_t count_kind(const batch *b, uint32_t kind) { + size_t n = 0; + for (size_t i = 0; i < b->count; i++) n += b->events[i].kind == kind; + return n; +} + +static void test_rows(void) { + exec_ok(g_main, "CREATE TABLE r(i INTEGER, f REAL, s TEXT, b BLOB, n)"); + // row 2's text is 20 two-byte characters (40 bytes) and its blob 40 bytes, both over the 15-byte + // value limit below; 15 falls inside a character, so the text is cut to 14 + char long_text[64] = ""; + for (int k = 0; k < 20; k++) strcat(long_text, "\xC3\xA9"); + char sql[256]; + exec_ok(g_main, "INSERT INTO r VALUES(1, 1.5, 'one', x'0102', NULL)"); + snprintf(sql, sizeof sql, "INSERT INTO r VALUES(2, 2.5, '%s', zeroblob(40), NULL)", long_text); + exec_ok(g_main, sql); + exec_ok(g_main, "INSERT INTO r VALUES(3, 3.5, 'three', x'03', NULL)"); + exec_ok(g_main, "INSERT INTO r VALUES(4, 4.5, 'four', x'04', NULL)"); + exec_ok(g_main, "INSERT INTO r VALUES(5, 5.5, 'five', x'05', NULL)"); + + sqlitedbg_set_row_capture(3, 15, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT i, f, s, b, n FROM r ORDER BY i", -1, &st, NULL), SQLITE_OK); + int steps = 0; + while (sqlite3_step(st) == SQLITE_ROW) { + steps++; + // the app sees its own types and values: the extension read each column with its own accessor + CHECK_EQ(sqlite3_column_type(st, 0), SQLITE_INTEGER); + CHECK_EQ(sqlite3_column_type(st, 1), SQLITE_FLOAT); + CHECK_EQ(sqlite3_column_type(st, 2), SQLITE_TEXT); + CHECK_EQ(sqlite3_column_type(st, 3), SQLITE_BLOB); + CHECK_EQ(sqlite3_column_type(st, 4), SQLITE_NULL); + CHECK_EQ(sqlite3_column_int64(st, 0), steps); + CHECK(sqlite3_column_double(st, 1) == steps + 0.5); + } + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + CHECK_EQ(steps, 5); + + batch b; + read_all(cur, &b); + // the statement, its first three rows, its profile + CHECK_EQ(b.count, 5); + CHECK_EQ(b.events[0].kind, SQLITEDBG_EVENT_STATEMENT); + for (int k = 1; k <= 3; k++) { + const ev *e = &b.events[k]; + CHECK_EQ(e->kind, SQLITEDBG_EVENT_ROW); + CHECK_EQ(e->rows, k); + CHECK_EQ(e->changes, -1); + CHECK_EQ(e->duration_ns, -1); + CHECK_EQ(e->conn, 1); + CHECK_EQ(e->tid, tid()); + uint32_t columns = 0; + rv v[5]; + CHECK_EQ(parse_row(e, &columns, v, 5), 5); + CHECK_EQ(columns, 5); + CHECK_EQ(v[0].type, SQLITE_INTEGER); + CHECK_EQ(rv_int(&v[0]), k); + CHECK_EQ(v[1].type, SQLITE_FLOAT); + CHECK(rv_double(&v[1]) == k + 0.5); + CHECK_EQ(v[2].type, SQLITE_TEXT); + CHECK_EQ(v[3].type, SQLITE_BLOB); + CHECK_EQ(v[4].type, SQLITE_NULL); + CHECK_EQ(v[4].stored, 0); + if (k == 2) { + CHECK(e->flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK_EQ(v[2].full, 40); + CHECK_EQ(v[2].stored, 14); + CHECK_EQ(v[2].cut, 1); + CHECK(utf8_valid((const char *)v[2].p, v[2].stored)); + CHECK(memcmp(v[2].p, long_text, 14) == 0); + CHECK_EQ(v[3].full, 40); + CHECK_EQ(v[3].stored, 15); + CHECK_EQ(v[3].cut, 1); + } else { + CHECK_EQ(e->flags, 0); + const char *want = k == 1 ? "one" : "three"; + CHECK_EQ(v[2].stored, strlen(want)); + CHECK(memcmp(v[2].p, want, strlen(want)) == 0); + CHECK_EQ(v[3].cut, 0); + } + } + CHECK(memcmp(b.events[1].sql + 8 + 12 + 8 + 12 + 8 + 12 + 3 + 12, "\x01\x02", 2) == 0); + const ev *prof = &b.events[4]; + CHECK_EQ(prof->kind, SQLITEDBG_EVENT_PROFILE); + // all five rows counted, two left unrecorded by the limit; a read changes nothing + CHECK_EQ(prof->rows, 5); + CHECK(prof->flags & SQLITEDBG_EVENT_ROWS_CUT); + CHECK_EQ(prof->changes, -1); + batch_free(&b); + + // with no client, or with recording off, rows are counted but not recorded + cur = cursor_now(); + exec_ok(g_main, "SELECT i FROM r"); + sqlitedbg_set_row_capture(0, 0, 0); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "SELECT i FROM r WHERE i < 3"); + sqlitedbg_set_client_connected(0); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r")->rows, 5); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r")->flags, 0); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r WHERE i < 3")->rows, 2); + batch_free(&b); +} + +static void test_internal_rows(void) { + // a CREATE TABLE runs SQLite's own nested statement that returns a row (the schema read); with + // recording on, it is not recorded + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + exec_ok(g_main, "CREATE TABLE ri(a)"); + exec_ok(g_main, "CREATE INDEX rii ON ri(a)"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + batch b; + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + const ev *e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "CREATE TABLE ri(a)"); + CHECK(e != NULL); + if (e) CHECK_EQ(e->rows, 0); + batch_free(&b); +} + +static void test_changes(void) { + exec_ok(g_main, "CREATE TABLE c(a)"); + uint64_t cur = cursor_now(); + exec_ok(g_main, "INSERT INTO c SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3"); + exec_ok(g_main, "UPDATE c SET a = a + 1 WHERE a > 1"); + exec_ok(g_main, "DELETE FROM c WHERE a = 1"); + exec_ok(g_main, "SELECT a FROM c"); + // after the DELETE, sqlite3_changes64 still says 1: a CREATE TABLE does not set it + exec_ok(g_main, "CREATE TABLE c2(a)"); + exec_ok(g_main, "UPDATE c SET a = a WHERE 0"); + // t's trigger inserts into log too: only the insert's own row counts + exec_ok(g_main, "INSERT INTO t VALUES(5)"); + batch b; + read_all(cur, &b); + struct { + const char *sql; + int64_t changes, rows; + } want[] = { + {"INSERT INTO c SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3", 3, 0}, + {"UPDATE c SET a = a + 1 WHERE a > 1", 2, 0}, + {"DELETE FROM c WHERE a = 1", 1, 0}, + {"SELECT a FROM c", -1, 2}, + {"CREATE TABLE c2(a)", 0, 0}, + {"UPDATE c SET a = a WHERE 0", 0, 0}, + {"INSERT INTO t VALUES(5)", 1, 0}, + }; + for (size_t i = 0; i < sizeof want / sizeof want[0]; i++) { + const ev *e = find_event(&b, SQLITEDBG_EVENT_PROFILE, want[i].sql); + CHECK(e != NULL); + if (!e) continue; + if (e->changes != want[i].changes) fprintf(stderr, " changes of %s\n", want[i].sql); + CHECK_EQ(e->changes, want[i].changes); + CHECK_EQ(e->rows, want[i].rows); + } + batch_free(&b); +} + +// The first value of a ROW event, as an int (INTEGER) or its first byte (TEXT). +static int64_t first_value(const ev *e, int *type) { + uint32_t columns; + rv v[2]; + *type = 0; + if (parse_row(e, &columns, v, 2) < 1) return -1; + *type = v[0].type; + return v[0].type == SQLITE_INTEGER ? rv_int(&v[0]) : v[0].stored ? v[0].p[0] : -1; +} + +static void test_interleaved_rows(void) { + // two statements stepped in turn on one connection keep their own row numbers + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + sqlite3_stmt *a, *s; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 10 UNION ALL SELECT 20", -1, &a, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'", -1, &s, NULL), + SQLITE_OK); + CHECK_EQ(sqlite3_step(a), SQLITE_ROW); + CHECK_EQ(sqlite3_step(s), SQLITE_ROW); + CHECK_EQ(sqlite3_step(a), SQLITE_ROW); + CHECK_EQ(sqlite3_step(s), SQLITE_ROW); + CHECK_EQ(sqlite3_step(s), SQLITE_ROW); + sqlite3_finalize(a); + sqlite3_finalize(s); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + batch b; + read_all(cur, &b); + int64_t want_rows[] = {1, 1, 2, 2, 3}; + int64_t want_first[] = {10, 'x', 20, 'y', 'z'}; + size_t k = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + int type; + int64_t first = first_value(&b.events[i], &type); + if (k < 5) { + CHECK_EQ(b.events[i].rows, want_rows[k]); + CHECK_EQ(first, want_first[k]); + CHECK_EQ(type, k == 0 || k == 2 ? SQLITE_INTEGER : SQLITE_TEXT); + } + k++; + } + CHECK_EQ(k, 5); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 10 UNION ALL SELECT 20")->rows, 2); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'")->rows, 3); + batch_free(&b); + + // one statement more than there are slots, each started in turn: the oldest loses its slot, so its + // later rows go unrecorded and its profile has no counts + enum { N = SQLITEDBG_STATEMENT_SLOTS + 1 }; + sqlite3_stmt *st[N]; + char sql[64]; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + for (int i = 0; i < N; i++) { + snprintf(sql, sizeof sql, "SELECT %d UNION ALL SELECT %d", i, i); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st[i], NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st[i]), SQLITE_ROW); + } + CHECK_EQ(sqlite3_step(st[0]), SQLITE_ROW); + CHECK_EQ(sqlite3_step(st[1]), SQLITE_ROW); + for (int i = 0; i < N; i++) sqlite3_finalize(st[i]); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + // one row each, plus statement 1's second row; statement 0's second row had no slot + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), N + 1); + const ev *p0 = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 0 UNION ALL SELECT 0"); + const ev *p1 = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 1 UNION ALL SELECT 1"); + CHECK(p0 && p1); + if (p0) CHECK_EQ(p0->rows, -1); + if (p0) CHECK_EQ(p0->changes, -1); + if (p1) CHECK_EQ(p1->rows, 2); + batch_free(&b); +} + +static void test_row_limits(void) { + // the row's data stops at max_row_bytes: the header (8) and one INTEGER (12 + 8) fit in 40, a + // second INTEGER does not + sqlitedbg_set_row_capture(10, 0, 40); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + exec_ok(g_main, "SELECT 1, 2"); + // a value limit of 1 cuts a two-byte character to nothing, which is still a whole value + sqlitedbg_set_row_capture(10, 1, MAX_ROW_DATA); + exec_ok(g_main, "SELECT '\xC3\xA9', x'0a0b'"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + batch b; + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 2); + const ev *wide = NULL, *cut = NULL; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + if (!wide) wide = &b.events[i]; + else cut = &b.events[i]; + } + uint32_t columns; + rv v[2]; + if (wide) { + CHECK_EQ(parse_row(wide, &columns, v, 2), 1); + CHECK_EQ(columns, 2); + CHECK_EQ(rv_int(&v[0]), 1); + CHECK(wide->flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK(wide->data_bytes <= 40); + } + if (cut) { + CHECK_EQ(parse_row(cut, &columns, v, 2), 2); + CHECK_EQ(v[0].type, SQLITE_TEXT); + CHECK_EQ(v[0].stored, 0); + CHECK_EQ(v[0].full, 2); + CHECK_EQ(v[1].type, SQLITE_BLOB); + CHECK_EQ(v[1].stored, 1); + CHECK_EQ(v[1].p[0], 0x0a); + CHECK(cut->flags & SQLITEDBG_EVENT_TRUNCATED); + } + CHECK(wide && cut); + batch_free(&b); +} + static void test_burst(void) { uint64_t cur = cursor_now(); const int stmts = 2000; @@ -513,7 +860,7 @@ static void test_close_and_list(void) { CHECK_EQ(b.count, 1); CHECK_EQ(b.events[0].kind, SQLITEDBG_EVENT_CLOSE); CHECK_EQ(b.events[0].conn, id); - CHECK_EQ(b.events[0].sql_bytes, 0); + CHECK_EQ(b.events[0].data_bytes, 0); batch_free(&b); // the failed close left the connection open: a statement on it clears closing, a second failed close sets it @@ -816,6 +1163,7 @@ typedef struct worker { int index; atomic_int *stop; long long stmts, closes; + long long row_stmts; // statements that return one row: each adds at most one row event int failed; } worker; @@ -843,6 +1191,7 @@ static void *worker_main(void *arg) { if (n % 7 == 0) { if (sqlite3_exec(db, "SELECT count(*) FROM w", NULL, NULL, NULL) != SQLITE_OK) w->failed = 1; w->stmts++; + w->row_stmts++; } if (n % 50 == 0) { // connection churn beside the other threads' statements @@ -853,6 +1202,7 @@ static void *worker_main(void *arg) { } if (sqlite3_exec(extra, "SELECT 1", NULL, NULL, NULL) != SQLITE_OK) w->failed = 1; w->stmts++; + w->row_stmts++; if (sqlite3_close(extra) != SQLITE_OK) w->failed = 1; w->closes++; } @@ -885,8 +1235,8 @@ static void *reader_main(void *arg) { uint64_t prev = after; for (size_t i = 0; i < res.count; i++) { const sqlitedbg_event_record *rec = (const sqlitedbg_event_record *)(void *)(buf + off); - if (rec->seq <= prev || rec->record_bytes % 8 || rec->kind < 1 || rec->kind > 3 || - rec->record_bytes < sizeof *rec + rec->sql_bytes) + if (rec->seq <= prev || rec->record_bytes % 8 || rec->kind < 1 || rec->kind > 4 || + rec->record_bytes < sizeof *rec + rec->data_bytes) r->failed = 1; prev = rec->seq; off += rec->record_bytes; @@ -896,9 +1246,12 @@ static void *reader_main(void *arg) { int bad = 0; sqlitedbg_each_connection(list_noop, &bad); if (bad) r->failed = 1; + // row recording switched on and off while the workers' statements return rows + sqlitedbg_set_row_capture(r->reads % 2 ? 4 : 0, 0, 0); sqlitedbg_set_client_connected(r->reads++ % 3 == 0); } sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); return NULL; } @@ -926,11 +1279,12 @@ static void test_threads(void) { for (int i = 0; i < N; i++) pthread_join(th[i], NULL); pthread_join(rt, NULL); - long long stmts = 0, closes = 0; + long long stmts = 0, closes = 0, row_stmts = 0; for (int i = 0; i < N; i++) { CHECK_EQ(w[i].failed, 0); stmts += w[i].stmts; closes += w[i].closes; + row_stmts += w[i].row_stmts; } CHECK_EQ(rd.failed, 0); CHECK(stmts > 1000); @@ -938,17 +1292,63 @@ static void test_threads(void) { CHECK_EQ(list_conns(&l), before); batch b; read_all(0, &b); - CHECK_EQ(b.next - cur, 2 * (uint64_t)stmts + (uint64_t)closes); + // two events per statement, one per close, and one per recorded row: at most one per row statement + uint64_t made = b.next - cur, base = 2 * (uint64_t)stmts + (uint64_t)closes; + CHECK(made >= base); + CHECK(made <= base + (uint64_t)row_stmts); batch_free(&b); printf(" threads: %lld statements, %lld closes, %lld reads\n", stmts, closes, rd.reads); } // Fixture for EventDecoder's JVM test: a known run, as bytes plus a table of what they hold. -static void write_tsv_row(FILE *f, const sqlitedbg_event_record *r, const char *sql) { - fprintf(f, "%llu\t%u\t%llu\t%lld\t%lld\t%lld\t%u\t%.*s\n", (unsigned long long)r->seq, r->kind, +// A ROW event's data as text: "/|" and then each value, comma-separated, as a type +// letter (i, f, t, b, n), "*" if it was cut, ":" and the value: an integer in decimal, a float with +// %.17g, text as is, a blob in lowercase hex, nothing for NULL. Returns 0 if the data is malformed. +static int write_row_data(FILE *f, const unsigned char *d, size_t n) { + sqlitedbg_row_header h; + if (n < sizeof h) return 0; + memcpy(&h, d, sizeof h); + fprintf(f, "%u/%u|", h.columns, h.kept); + size_t off = sizeof h; + for (uint32_t i = 0; i < h.kept; i++) { + sqlitedbg_row_value v; + if (n - off < sizeof v) return 0; + memcpy(&v, d + off, sizeof v); + off += sizeof v; + if (v.stored_bytes > n - off) return 0; + const unsigned char *p = d + off; + const char *letter = v.type == SQLITE_INTEGER ? "i" : v.type == SQLITE_FLOAT ? "f" : v.type == SQLITE_TEXT ? "t" + : v.type == SQLITE_BLOB ? "b" : "n"; + fprintf(f, "%s%s%s:", i ? "," : "", letter, v.cut ? "*" : ""); + if (v.type == SQLITE_INTEGER || v.type == SQLITE_FLOAT) { + if (v.stored_bytes != 8) return 0; + long long x; + double y; + memcpy(&x, p, 8); + memcpy(&y, p, 8); + if (v.type == SQLITE_INTEGER) fprintf(f, "%lld", x); + else fprintf(f, "%.17g", y); + } else if (v.type == SQLITE_TEXT) { + fprintf(f, "%.*s", (int)v.stored_bytes, (const char *)p); + } else if (v.type == SQLITE_BLOB) { + for (uint32_t k = 0; k < v.stored_bytes; k++) fprintf(f, "%02x", p[k]); + } + off += v.stored_bytes; + } + return off == n; +} + +// seq, kind, connection, thread, time, duration, flags, rows, changes, then the SQL or the row data. +static int write_tsv_row(FILE *f, const sqlitedbg_event_record *r, const char *data) { + fprintf(f, "%llu\t%u\t%llu\t%lld\t%lld\t%lld\t%u\t%lld\t%lld\t", (unsigned long long)r->seq, r->kind, (unsigned long long)r->connection_id, (long long)r->thread_id, (long long)r->time_ns, - (long long)r->duration_ns, r->flags, (int)r->sql_bytes, sql); + (long long)r->duration_ns, r->flags, (long long)r->rows, (long long)r->changes); + int ok = 1; + if (r->kind == SQLITEDBG_EVENT_ROW) ok = write_row_data(f, (const unsigned char *)data, r->data_bytes); + else fprintf(f, "%.*s", (int)r->data_bytes, data); + fputc('\n', f); + return ok; } static void run_fixture_scenario(void) { @@ -975,6 +1375,14 @@ static void run_fixture_scenario(void) { sqlite3 *c = open_app(":memory:"); exec_ok(c, "SELECT 1"); CHECK_EQ(sqlite3_close(c), SQLITE_OK); + // recorded rows (ADFA-7296): every type, a text and a blob cut at 4 bytes, and a profile with its + // counts and ROWS_CUT; then a write's change count + sqlitedbg_set_row_capture(1, 4, 1024); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "SELECT 7, 2.5, 'h\xC3\xA9llo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9, -0.125, 'ab', x'', NULL"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + exec_ok(g_main, "DELETE FROM fxlog"); } static unsigned char *slurp(const char *path, size_t *n) { @@ -1004,11 +1412,14 @@ static int bin_to_tsv(const unsigned char *bin, size_t n, char **out) { while (off < n) { const sqlitedbg_event_record *r = (const sqlitedbg_event_record *)(const void *)(bin + off); if (off + sizeof *r > n || r->record_bytes % 8 || off + r->record_bytes > n || - r->record_bytes < sizeof *r + r->sql_bytes) { + r->record_bytes < sizeof *r + r->data_bytes) { + ok = 0; + break; + } + if (!write_tsv_row(f, r, (const char *)bin + off + sizeof *r)) { ok = 0; break; } - write_tsv_row(f, r, (const char *)bin + off + sizeof *r); off += r->record_bytes; } fclose(f); @@ -1076,6 +1487,12 @@ int main(int argc, char **argv) { test_expanded(); printf("# truncation\n"); test_truncation(); + printf("# rows and changes\n"); + test_rows(); + test_internal_rows(); + test_changes(); + test_interleaved_rows(); + test_row_limits(); printf("# burst\n"); test_burst(); printf("# cursor reset\n"); diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index 555e566544..e38d99ebc0 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -9,13 +9,13 @@ import java.nio.ByteOrder class EventDecoderTest { // events.bin is what sqlitedbg_read_events copied out in sqlitedbg_test.c (test.sh --update-fixture); // events.tsv is the same records as the C struct reads them: seq, kind, connection, thread, time, - // duration, flags, sql. + // duration, flags, rows, changes, then the SQL or, for a row, its values (see write_row_data there). private val bytes = resource("events.bin") private val table = String(resource("events.tsv"), Charsets.UTF_8) .trimEnd('\n') .split('\n') - .map { it.split('\t', limit = 8) } + .map { it.split('\t', limit = 10) } private fun resource(name: String): ByteArray = checkNotNull(javaClass.getResourceAsStream(name)) { "missing fixture $name" }.use { it.readBytes() } @@ -34,7 +34,42 @@ class EventDecoderTest { assertThat(event.durationNanos).isEqualTo(if (event.kind == EventKind.PROFILE) row[5].toLong() else null) assertThat(event.truncated).isEqualTo(row[6].toInt() and 1 != 0) assertThat(event.expanded).isEqualTo(row[6].toInt() and 2 != 0) - assertThat(event.sql).isEqualTo(row[7]) + assertThat(event.rowsCut).isEqualTo(row[6].toInt() and 4 != 0) + assertThat(event.rows).isEqualTo(row[7].toLong().takeIf { it >= 0 }) + assertThat(event.changes).isEqualTo(row[8].toLong().takeIf { it >= 0 }) + if (event.kind == EventKind.ROW) { + assertThat(event.sql).isEmpty() + assertRow(event.row, row[9]) + } else { + assertThat(event.row).isNull() + assertThat(event.sql).isEqualTo(row[9]) + } + } + } + + // row is "/|" and then each value: a type letter (i, f, t, b, n), "*" if cut, ":" and + // the value (decimal, %.17g, text, lowercase hex, nothing for NULL). + private fun assertRow( + actual: RowValues?, + row: String, + ) { + checkNotNull(actual) + val (counts, values) = row.split('|', limit = 2) + val (columns, kept) = counts.split('/').map { it.toInt() } + assertThat(actual.columnCount).isEqualTo(columns) + assertThat(actual.values).hasSize(kept) + values.split(',').forEachIndexed { i, token -> + val (type, text) = token.split(':', limit = 2) + assertThat(i in actual.cutIndexes).isEqualTo(type.endsWith("*")) + val value = actual.values[i] + when (type.trimEnd('*')) { + "i" -> assertThat(value).isEqualTo(text.toLong()) + "f" -> assertThat(value).isEqualTo(text.toDouble()) + "t" -> assertThat(value).isEqualTo(text) + "b" -> assertThat((value as ByteArray).joinToString("") { "%02x".format(it) }).isEqualTo(text) + "n" -> assertThat(value).isNull() + else -> error("unknown type $type") + } } } @@ -45,6 +80,18 @@ class EventDecoderTest { assertThat(events.map { it.kind }.toSet()).containsExactlyElementsIn(EventKind.values().toList()) assertThat(events.any { it.truncated }).isTrue() assertThat(events.any { it.expanded }).isTrue() + assertThat(events.any { it.rowsCut }).isTrue() + assertThat(events.any { (it.changes ?: 0) > 0 }).isTrue() + // a row with every type, and a cut TEXT and BLOB + val row = checkNotNull(events.single { it.kind == EventKind.ROW }.row) + assertThat(row.values.map { it?.javaClass }).containsExactly( + Long::class.javaObjectType, + Double::class.javaObjectType, + String::class.java, + ByteArray::class.java, + null, + ).inOrder() + assertThat(row.cutIndexes).containsExactly(2, 3) assertThat(events.any { it.sql.startsWith("--") }).isTrue() // multi-byte text survives, including a character outside the BMP assertThat(events.any { it.sql.contains("héllo € 😀") }).isTrue() @@ -89,4 +136,33 @@ class EventDecoderTest { val negative = patched(52, -1) assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(negative, negative.size) } } + + @Test + fun `a malformed row is refused`() { + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + var offset = 0 + while (buffer.getInt(offset + 4) != EventKind.ROW.nativeValue) offset += buffer.getInt(offset) + val data = offset + EventDecoder.HEADER_BYTES + + fun patched( + at: Int, + value: Int, + ): ByteArray { + val copy = bytes.copyOf() + ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN).putInt(at, value) + return copy + } + + // kept above columns; the first value (an integer) not 8 bytes; its stored bytes past the row; + // an unknown type in the first value's type byte (and its neighbours left alone) + val first = data + 8 + for (broken in listOf( + patched(data + 4, 99), + patched(first + 4, 4), + patched(first + 4, 100000), + patched(first, 9), + )) { + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(broken, broken.size) } + } + } } diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin index 0441b915006ad5921acdf11c603ea101862533ed..a1b0e7d07a40a05b0deebfba529d9a5f5d716bce 100644 GIT binary patch literal 2760 zcmb`JOK1~O6ozkYec%%Xq3#A3Cc&m8f{GiPv`%XvO(dO&V1=o*Di}>r!7fz9f)u-O zTWnF>wIbpsg4l(i_yAXeprBx@)<>;veO4Fh`7?8(H^~X2J>=xf+&S~z|DL(`&e%$+ z3i4-9=Fq=$jCiOD|4I#Yts1QboYBpGgXYb9yR4Q$ZoV;XAp6@;3u_+&#UJ3lCeGZ>e z@&-QZ=I2|EkKES+zv9vUBK^xLpSc_h=4UFs$5{e4Rqfq&|3k5+H+7n5^; z9Q}U7`dw?KGA{SMz|Hg*b61w;>e8LZliSS>bR4NI+?OYW{=TPswdX}$f!8%utPfz; z#S!&JAD@MKZ|~{X#)&>d&A(xQnD~VGBIwAT({(^|D|umkW>Xs+?WiAoE;$VK=eAsfstQ$7BKpPG z6y9Z3?l~Cq7c5+a_@{N#2{>N`owo)YoqP}a4w2&?*i6;SCKkpxE$C>!tJjNC)lzcq ppW`NakJEQxV|tT3Cpsjg5_kjkUhFvlFvfUKDZ2n=CVLzW2|Yx3gi!SRPm+SqQy+#($Rsd&Wxd zHD_w&wfxg;#u#+oh;ZwI>uyg_@WF(m*NHQXg~9T{W(eMXu*2YKo)UC7S}F9oc&Kld z;EkjtFH>JR_yziKwI5sr1beypOg%o4%iTsBfO&U5-hf(ucXB zd39-h3j}ZIb;6?WH$2q0NbtseleY6keNhn9?&n{<+$y+CQjqS&l{2{Lxtfq$R-??L~2gXp>2EiHcv~wyX$9fgW z^cuIp=)iPs_Pw=9@T6W>^0Y(eJ N_K5YKM|*q(eF53lvcUiV diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv index 4405849603..94a033c800 100644 --- a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv +++ b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv @@ -1,21 +1,26 @@ -426616 1 1 10289 1794545527187098386 -1 0 CREATE TABLE fx(a) -426617 2 1 10289 1794545527188573325 1000000 0 CREATE TABLE fx(a) -426618 1 1 10289 1794545527188596333 -1 0 INSERT INTO fx VALUES(?) -426619 2 1 10289 1794545527189296629 1000000 0 INSERT INTO fx VALUES(?) -426620 1 1 10289 1794545527189303467 -1 2 INSERT INTO fx VALUES(6) -426621 2 1 10289 1794545527190447975 1000000 2 INSERT INTO fx VALUES(6) -426622 1 1 10289 1794545527190472305 -1 0 SELECT 'héllo € 😀' -426623 2 1 10289 1794545527190474851 0 0 SELECT 'héllo € 😀' -426624 1 1 10289 1794545527190557276 -1 0 CREATE TABLE fxlog(a) -426625 2 1 10289 1794545527191607925 1000000 0 CREATE TABLE fxlog(a) -426626 1 1 10289 1794545527191694489 -1 1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA -426627 2 1 10289 1794545527192759261 1000000 1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA -426628 1 1 10289 1794545527192791863 -1 0 INSERT INTO fx VALUES(1) -426629 1 1 10289 1794545527192835643 -1 0 -- TRIGGER fxt -426630 1 1 10289 1794545527192836209 -1 0 -- INSERT INTO fxlog VALUES(new.a) -426631 2 1 10289 1794545527193623084 1000000 0 INSERT INTO fx VALUES(1) -426632 1 1 10289 1794545527193646993 -1 1 SELECT '€€€€€€€€€€€€€€€€€€ -426633 2 1 10289 1794545527193649365 0 1 SELECT '€€€€€€€€€€€€€€€€€€ -426634 1 3616 10289 1794545527193782816 -1 0 SELECT 1 -426635 2 3616 10289 1794545527193784200 0 0 SELECT 1 -426636 3 3616 10289 1794545527193785154 -1 0 +449760 1 1 1139 1795576849764877244 -1 0 -1 -1 CREATE TABLE fx(a) +449761 2 1 1139 1795576849767385554 3000000 0 0 0 CREATE TABLE fx(a) +449762 1 1 1139 1795576849767428350 -1 0 -1 -1 INSERT INTO fx VALUES(?) +449763 2 1 1139 1795576849768441548 1000000 0 0 1 INSERT INTO fx VALUES(?) +449764 1 1 1139 1795576849768454479 -1 2 -1 -1 INSERT INTO fx VALUES(6) +449765 2 1 1139 1795576849769429166 1000000 2 0 1 INSERT INTO fx VALUES(6) +449766 1 1 1139 1795576849769467830 -1 0 -1 -1 SELECT 'héllo € 😀' +449767 2 1 1139 1795576849769470941 0 0 1 -1 SELECT 'héllo € 😀' +449768 1 1 1139 1795576849769551873 -1 0 -1 -1 CREATE TABLE fxlog(a) +449769 2 1 1139 1795576849770495943 1000000 0 0 0 CREATE TABLE fxlog(a) +449770 1 1 1139 1795576849770577649 -1 1 -1 -1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +449771 2 1 1139 1795576849771426369 1000000 1 0 0 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +449772 1 1 1139 1795576849771458485 -1 0 -1 -1 INSERT INTO fx VALUES(1) +449773 1 1 1139 1795576849771502214 -1 0 -1 -1 -- TRIGGER fxt +449774 1 1 1139 1795576849771502704 -1 0 -1 -1 -- INSERT INTO fxlog VALUES(new.a) +449775 2 1 1139 1795576849772343290 1000000 0 0 1 INSERT INTO fx VALUES(1) +449776 1 1 1139 1795576849772372693 -1 1 -1 -1 SELECT '€€€€€€€€€€€€€€€€€€ +449777 2 1 1139 1795576849772375404 0 1 1 -1 SELECT '€€€€€€€€€€€€€€€€€€ +449778 1 3765 1139 1795576849772556358 -1 0 -1 -1 SELECT 1 +449779 2 3765 1139 1795576849772558632 0 0 1 -1 SELECT 1 +449780 3 3765 1139 1795576849772559491 -1 0 -1 -1 +449781 1 1 1139 1795576849772612443 -1 3 -1 -1 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +449782 4 1 1139 1795576849772617397 -1 1 1 -1 5/5|i:7,f:2.5,t*:hél,b*:0a0b0c0d,n: +449783 2 1 1139 1795576849772619972 0 7 2 -1 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +449784 1 1 1139 1795576849772628067 -1 0 -1 -1 DELETE FROM fxlog +449785 2 1 1139 1795576849773550011 1000000 0 0 1 DELETE FROM fxlog From 02c384fcd201977fe7dd7783294747176f45e609 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 22:47:43 -0800 Subject: [PATCH 02/45] ADFA-7296 Apply spotless formatting to EventDecoder and its test spotlessKotlinCheck failed on 67355bdbd (the hand-off expected ktlint to reflow): braces around the multi-line `when` branches in EventDecoder.kt and a chained `containsExactly` in EventDecoderTest.kt. Formatting only, from `spotlessApply`; `git diff -w` changes no tokens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/engine/EventDecoder.kt | 16 +++++++++++++--- .../sqlitedebugger/engine/EventDecoderTest.kt | 15 ++++++++------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt index 0124530255..e49421a8c8 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -119,13 +119,23 @@ internal object EventDecoder { require(stored == 8) { "row at $start: number $i is $stored bytes" } if (type == SQLITE_INTEGER) buffer.getLong(pos) else buffer.getDouble(pos) } - SQLITE_TEXT -> String(bytes, pos, stored, Charsets.UTF_8) - SQLITE_BLOB -> bytes.copyOfRange(pos, pos + stored) + + SQLITE_TEXT -> { + String(bytes, pos, stored, Charsets.UTF_8) + } + + SQLITE_BLOB -> { + bytes.copyOfRange(pos, pos + stored) + } + SQLITE_NULL -> { require(stored == 0) { "row at $start: null $i has $stored bytes" } null } - else -> throw IllegalArgumentException("row at $start: value $i has unknown type $type") + + else -> { + throw IllegalArgumentException("row at $start: value $i has unknown type $type") + } } if (isCut) cut += i pos += stored diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index e38d99ebc0..9c5c789616 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -84,13 +84,14 @@ class EventDecoderTest { assertThat(events.any { (it.changes ?: 0) > 0 }).isTrue() // a row with every type, and a cut TEXT and BLOB val row = checkNotNull(events.single { it.kind == EventKind.ROW }.row) - assertThat(row.values.map { it?.javaClass }).containsExactly( - Long::class.javaObjectType, - Double::class.javaObjectType, - String::class.java, - ByteArray::class.java, - null, - ).inOrder() + assertThat(row.values.map { it?.javaClass }) + .containsExactly( + Long::class.javaObjectType, + Double::class.javaObjectType, + String::class.java, + ByteArray::class.java, + null, + ).inOrder() assertThat(row.cutIndexes).containsExactly(2, 3) assertThat(events.any { it.sql.startsWith("--") }).isTrue() // multi-byte text survives, including a character outside the BMP From ce76bcb4ea3962a0c599f1d2fb9e534def6ddbec Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 23:20:59 -0800 Subject: [PATCH 03/45] ADFA-7296 Don't read row text through a NULL pointer when SQLite is out of memory record_row passed p to utf8_cut before its `if (!p)` guard. sqlite3_column_text returns NULL when SQLite runs out of memory (for example when it cannot add the NUL terminator), while sqlite3_column_bytes can still return the value's length; for a TEXT value longer than the limit, utf8_cut then read through the NULL pointer, inside the app's own sqlite3_step, and the app crashed. Before ADFA-7296 the extension never read column values, so the path was new. stored is now 0 whenever p is NULL, for TEXT and BLOB. No test: it needs SQLite to fail an allocation at that exact point, which the host tests cannot arrange. test.sh passes (with the next commit): ASan+UBSan 20745 checks, TSan 20726, JNI 205, 0 failures (system JDK). CodeRabbit thread 4691490650. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index ab6451bc94..abe0aa8c7a 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -256,8 +256,8 @@ static void record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { const void *p = type == SQLITE_TEXT ? (const void *)sqlite3_column_text(stmt, i) : sqlite3_column_blob(stmt, i); size_t full = (size_t)sqlite3_column_bytes(stmt, i); size_t limit = room < max_value ? room : max_value; - size_t stored = type == SQLITE_TEXT ? utf8_cut((const char *)p, full, limit) : (full < limit ? full : limit); - if (!p) stored = 0; + // p is NULL when SQLite is out of memory; utf8_cut would read through it. + size_t stored = !p ? 0 : type == SQLITE_TEXT ? utf8_cut((const char *)p, full, limit) : (full < limit ? full : limit); uint8_t cut = stored < full; if (cut) flags |= SQLITEDBG_EVENT_TRUNCATED; if (stored) memcpy(v + ROW_VALUE_BYTES, p, stored); From 76be5b01a7d6f4efbe1e784f316e4b8a7cd01faf Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 23:21:14 -0800 Subject: [PATCH 04/45] ADFA-7296 Cap max_row_bytes at 64 KiB so a row record always fits a reader's batch sqlitedbg_read_events stops at the first record that doesn't fit its buffer, and the server reads 256 KiB at a time (DatabaseTools. EVENT_BATCH_BYTES). sqlitedbg_set_row_capture accepted any max_row_bytes, and a row record was bounded only by half the ring (2 MiB by default), so a large setting could make one record no reader can receive, and every event after it would wait until the ring evicted it. Nothing sets the limit yet (default 4 KiB), so this guards a future setting. SQLITEDBG_MAX_ROW_BYTES (64 KiB) in sqlitedbg.h caps it; a larger value is lowered to it. The tests' ring is 8 KiB, which caps a row first, so a test-only getter (SQLITEDBG_TEST, like sqlitedbg_test_fail_init) shows the limit in force: UINT32_MAX becomes 64 KiB, 1000 stays, 0 is 4 KiB. Revert proof: with the cap removed, test_row_limits fails with "sqlitedbg_test_max_row_bytes() == SQLITEDBG_MAX_ROW_BYTES (4294967295 vs 65536)"; restored, test.sh passes: ASan+UBSan 20745 checks, TSan 20726, JNI 205, 0 failures (system JDK). CodeRabbit thread 4691490645. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c | 5 ++++- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h | 8 +++++++- subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c | 8 ++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index abe0aa8c7a..cf60e234d8 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -380,6 +380,8 @@ static void connection_id_fn(sqlite3_context *ctx, int argc, sqlite3_value **arg #ifdef SQLITEDBG_TEST // Host tests: 1 fails the allocation, 2 makes registering the function fail. int sqlitedbg_test_fail_init; +// Host tests: the row limit in force, since the tests' 8 KiB buffer caps a row before it would. +uint32_t sqlitedbg_test_max_row_bytes(void) { return __atomic_load_n(&g_max_row, __ATOMIC_RELAXED); } #endif static int init_connection(sqlite3 *db, const sqlite3_api_routines *api); @@ -544,7 +546,8 @@ void sqlitedbg_set_client_connected(int connected) { void sqlitedbg_set_row_capture(uint32_t max_rows_per_statement, uint32_t max_value_bytes, uint32_t max_row_bytes) { __atomic_store_n(&g_max_value, max_value_bytes ? max_value_bytes : DEFAULT_MAX_VALUE_BYTES, __ATOMIC_RELAXED); - __atomic_store_n(&g_max_row, max_row_bytes ? max_row_bytes : DEFAULT_MAX_ROW_BYTES, __ATOMIC_RELAXED); + uint32_t row = max_row_bytes ? max_row_bytes : DEFAULT_MAX_ROW_BYTES; + __atomic_store_n(&g_max_row, row < SQLITEDBG_MAX_ROW_BYTES ? row : SQLITEDBG_MAX_ROW_BYTES, __ATOMIC_RELAXED); __atomic_store_n(&g_max_rows, max_rows_per_statement, __ATOMIC_RELAXED); } diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 9e74b1aa6b..71c2b23d0f 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -182,7 +182,8 @@ void sqlitedbg_set_client_connected(int connected); // Turns row recording on (max_rows_per_statement > 0) or off (0, as at install). While it is on and // a client is connected, the first max_rows_per_statement rows of each statement become // SQLITEDBG_EVENT_ROW events. TEXT and BLOB values longer than max_value_bytes are cut (0: 256), and -// a row's data stops at max_row_bytes (0: 4 KiB; never more than half the buffer less one header). +// a row's data stops at max_row_bytes (0: 4 KiB; at most SQLITEDBG_MAX_ROW_BYTES; never more than +// half the buffer less one header). // Each value is read with the accessor of its own type (sqlite3_column_type first), so the app sees // the same values and types afterwards: sqlite3_column_text converts a value in place, and on a BLOB // it makes the app's own sqlite3_column_type return SQLITE_TEXT (SQLite 3.49.1, sqlitedbg_test.c). Rows of statements the extension did @@ -191,6 +192,11 @@ void sqlitedbg_set_client_connected(int connected); void sqlitedbg_set_row_capture(uint32_t max_rows_per_statement, uint32_t max_value_bytes, uint32_t max_row_bytes); +// The largest max_row_bytes that sqlitedbg_set_row_capture keeps; a larger one is lowered to it. +// sqlitedbg_read_events stops at the first record that does not fit its buffer, so a row record must +// stay well below the 256 KiB the server reads at a time (DatabaseTools.EVENT_BATCH_BYTES). +#define SQLITEDBG_MAX_ROW_BYTES (64u * 1024u) + // Server connections #define SQLITEDBG_SERVER_BUSY_MS 3000 diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 266666e229..a6300732b8 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -192,6 +192,7 @@ static uint64_t conn_id_of(sqlite3 *db) { // Tests extern int sqlitedbg_test_fail_init; // sqlitedbg.c, built with SQLITEDBG_TEST +extern uint32_t sqlitedbg_test_max_row_bytes(void); // likewise static sqlitedbg_config g_config = {BUFFER_BYTES, MAX_SQL}; static sqlite3 *g_main; @@ -739,6 +740,13 @@ static void test_row_limits(void) { } CHECK(wide && cut); batch_free(&b); + // a row limit above SQLITEDBG_MAX_ROW_BYTES is lowered to it, so no row record outgrows a reader's batch + sqlitedbg_set_row_capture(1, 0, UINT32_MAX); + CHECK_EQ(sqlitedbg_test_max_row_bytes(), SQLITEDBG_MAX_ROW_BYTES); + sqlitedbg_set_row_capture(1, 0, 1000); + CHECK_EQ(sqlitedbg_test_max_row_bytes(), 1000); + sqlitedbg_set_row_capture(0, 0, 0); + CHECK_EQ(sqlitedbg_test_max_row_bytes(), 4096); } static void test_burst(void) { From 8592704d1892a018bda64307413d9f5c61bd2193 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 23:21:37 -0800 Subject: [PATCH 05/45] ADFA-7296 README: the row limit's cap and the measured cost of counting rows The README said the per-row cost "has not been measured on a phone yet". It now gives the Galaxy J7 numbers from the native benchmark in #2311's description (no client: +1.1 us for a 20-row SELECT, +0.6 us for a one-row SELECT over ade5cc2fb; about 2.9 us per recorded row), and the 64 KiB cap on a row's data from the previous commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 979c0608bb..6e66528d34 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -33,9 +33,9 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). - A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and a statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). - `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). -- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit; both are marked. +- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. - The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. -- Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. It has not been measured on a phone yet. +- Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). ## Decisions that shape it From 490feb0d024b31d28fe856712330f84b9397b6b6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 09:58:34 -0800 Subject: [PATCH 06/45] ADFA-7296 README: the row event kind and interface version 3 The README still listed the ring buffer's trace events as statement, profile and close, and said SQLITEDBG_INTERFACE_VERSION is 2. This change added row events and raised the version to 3 (sqlitedbg.h). Both lines now say so; the version line keeps why it became 2. Checked against sqlitedbg.h (SQLITEDBG_INTERFACE_VERSION 3, SQLITEDBG_EVENT_ROW). No code change. CodeRabbit review 6053222300, outside-diff comment (README.md:20, 49) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 6e66528d34..c8371a91d7 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -17,7 +17,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug ``` - `src/main/cpp/sqlitedbg.h` is the contract between the extension, its JNI layer and its host tests, with the semantics of each call. `SQLITEDBG_INTERFACE_VERSION` is raised when anything in it changes shape. -- `sqlitedbg.c` is a SQLite extension. `sqlitedbg_install` registers it with `sqlite3_auto_extension`, so it runs on every connection the app opens afterwards. It keeps the list of app connections and a ring buffer of statement events (trace: statement, profile, close), and opens connections for the server (`sqlitedbg_open_server`). +- `sqlitedbg.c` is a SQLite extension. `sqlitedbg_install` registers it with `sqlite3_auto_extension`, so it runs on every connection the app opens afterwards. It keeps the list of app connections and a ring buffer of statement events (trace: statement, profile, row, close), and opens connections for the server (`sqlitedbg_open_server`). - `sqlitedbg_jni.c` finds `sqlite3_auto_extension` in requery's `libsqlite3x.so` with `dlopen(RTLD_NOLOAD)` and `dlsym`, so no SQLite is compiled or linked here (CMake takes only the headers from `../sqlite-js/upstream/libs`). Its version script exports only `JNI_OnLoad`; the functions of `NativeBridge` are registered there by name, and `consumer-rules.pro` keeps them. - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. @@ -46,7 +46,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **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). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` is 2 for the changed struct), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. +- **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` became 2 for the changed struct, and is 3 since the row and change fields, ADFA-7296), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. - **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). From 4f971a83d3ee3490c28e87c977e76ece97845cb0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 09:58:34 -0800 Subject: [PATCH 07/45] ADFA-7296 EventDecoderTest: make the 4-byte number case reach the width check The malformed-row test patched an integer's stored_bytes to 4 but left full_bytes at 8, so decodeRow refused it at the cut check (stored < full with cut 0) and never reached the 8-byte width check for numbers. The test passed with the width check removed. The case now sets both stored_bytes and full_bytes to 4 and asserts the width check's message ("number 0 is 4 bytes"), so only that check can refuse it. Revert proof: with the width check removed, "a malformed row is refused" fails; restored, it passes. testDebugUnitTest and spotlessCheck pass. CodeRabbit review 6053222300, nitpick (EventDecoderTest.kt:162) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../appdevforall/sqlitedebugger/engine/EventDecoderTest.kt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index 9c5c789616..1b47cf84ef 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -154,16 +154,19 @@ class EventDecoderTest { return copy } - // kept above columns; the first value (an integer) not 8 bytes; its stored bytes past the row; + // kept above columns; its stored bytes past the row; // an unknown type in the first value's type byte (and its neighbours left alone) val first = data + 8 for (broken in listOf( patched(data + 4, 99), - patched(first + 4, 4), patched(first + 4, 100000), patched(first, 9), )) { assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(broken, broken.size) } } + // stored and full both 4: the value is not cut, so it is the width check that refuses it + val narrow = patched(first + 4, 4).also { ByteBuffer.wrap(it).order(ByteOrder.LITTLE_ENDIAN).putInt(first + 8, 4) } + val e = assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(narrow, narrow.size) } + assertThat(e.message).contains("number 0 is 4 bytes") } } From 99007a7a0915d9df61c3d030a7f4204574393a74 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:02:42 +0000 Subject: [PATCH 08/45] ADFA-7297 SQLite debugger: rows, change counts, named parameters and column types Phase 2, P2-2 (ADFA-7131 comments 41476, 41477). On P2-1 (#2311, at e16ea4587). - get_events: a profile event carries rows, changes (null for a read) and rows_cut; a row event carries row_number, column_count, values, storage_classes and cut_values. get_events turns row recording on (new DebugEngine.setRowCapture, JNI setRowCapture): 10 rows per statement, values cut at 256 bytes, a row at 4 KiB. include_rows false turns it off and leaves row events out; it also goes off with the idle client and when the server stops. - query and explain_query_plan: args as an object binds by name (:name, @name, $name, ?NNN; a key with or without its prefix). Names go to JNI as UTF-8 and are matched against sqlite3_bind_parameter_name: every parameter needs a value and every key a parameter. The array form is unchanged. - query returns column_types (sqlite3_column_decltype, null for an expression) and storage_classes, a letter per cell (i r t b n): JSON writes REAL 2.0 as 2, and big integers as strings. - BLOBs are {hex, bytes, truncated}; they were base64. No client reads the old key (AI-Agent-MCP passes results through). - Tool descriptions say what is capped; README updated. Limit: execute (P2-3, #2312) still binds positional args only; the second of the two PRs to merge wires its names. Tests: test.sh passes (ASan+UBSan, TSan, JNI 279 checks: each name form, the five refusals, declared types, the row-recording switch). DatabaseToolsTest, McpProtocolTest and EventDecoderTest pass (118), compiled with the Kotlin compiler outside Gradle, including an encoding of every event in P2-1's fixture. Revert proofs: no unused-name check fails "named: a misspelt name"; no decltype fails "declared types"; no idle switch-off fails rowRecordingStopsWithTheIdleClient; no row filter fails getEventsTurnsRowRecordingOnUnlessToldNotTo. Not run here: Gradle, spotlessCheck, a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 14 +- .../src/main/cpp/sqlitedbg_jni.c | 220 +++++++++++++----- .../sqlitedebugger/engine/DebugEngine.kt | 22 +- .../sqlitedebugger/engine/NativeBridge.kt | 19 +- .../engine/NativeDebugEngine.kt | 20 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 199 +++++++++++++--- .../sqlitedebugger/engine/FakeDebugEngine.kt | 23 ++ .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 217 ++++++++++++++++- .../src/test/jni/JniQueryTest.java | 82 ++++++- .../sqlitedebugger/engine/NativeBridge.java | 4 +- 10 files changed, 721 insertions(+), 99 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index c8371a91d7..a3970161f3 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -32,11 +32,21 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). - A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and a statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). -- `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). +- `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default; `get_events` turns it on (see "Results and bound parameters"). - Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. - The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. - Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). +### Results and bound parameters (ADFA-7297) + +What the server gives a client so it can format results as the sqlite3 shell would (`.mode`, `.nullvalue` and the rest stay client-side): +- **Values.** A NULL is JSON `null`. A BLOB is `{hex, bytes, truncated}`, lowercase hex (base64 before). An integer beyond 2^53 is a decimal string, and a NaN or infinite REAL is `"NaN"`, `"Infinity"` or `"-Infinity"`, as before. +- **Storage classes.** JSON alone cannot tell a REAL 2.0 from an INTEGER 2 (org.json writes both as `2`), or a big integer from TEXT, so `query` returns `storage_classes`, one string per row with a letter per column: `i` INTEGER, `r` REAL, `t` TEXT, `b` BLOB, `n` NULL. Row events carry the same string. +- **Declared types.** `query` returns `column_types`, each column's `sqlite3_column_decltype`, `null` for an expression. +- **Bound parameters (`.parameter`).** `query` and `explain_query_plan` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. +- **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. +- **Limits.** `execute` (ADFA-7298, a separate PR) binds positional `args` only until the two PRs meet. Row recording is one switch for the process: the last `get_events` call decides it. + ## Decisions that shape it - **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. @@ -56,7 +66,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 8d19317ff2..bd7e613e07 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -166,6 +166,13 @@ static void bridge_set_client_connected(JNIEnv *env, jclass cls, jboolean connec sqlitedbg_set_client_connected(connected ? 1 : 0); } +static void bridge_set_row_capture(JNIEnv *env, jclass cls, jint max_rows, jint max_value_bytes, jint max_row_bytes) { + (void)env; + (void)cls; + sqlitedbg_set_row_capture(max_rows > 0 ? (uint32_t)max_rows : 0, max_value_bytes > 0 ? (uint32_t)max_value_bytes : 0, + max_row_bytes > 0 ? (uint32_t)max_row_bytes : 0); +} + // server connections static jlong bridge_open_server(JNIEnv *env, jclass cls, jbyteArray path, jboolean writable) { @@ -221,48 +228,154 @@ static int progress_cb(void *p) { } // Binds args[i] to parameter i + 1. Returns SQLITE_OK or a code with *message set. -static int bind_args(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, const char **message) { +// Binds v (null, Long, Double, String or byte[]) to parameter idx (from 1). +static int bind_value(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, int idx, jobject v, const char **message) { + int rc; + if (!v) { + rc = sqlite3_bind_null(st, idx); + } else if ((*env)->IsInstanceOf(env, v, g_long)) { + jmethodID m = (*env)->GetMethodID(env, g_long, "longValue", "()J"); + rc = sqlite3_bind_int64(st, idx, (sqlite3_int64)(*env)->CallLongMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_double)) { + jmethodID m = (*env)->GetMethodID(env, g_double, "doubleValue", "()D"); + rc = sqlite3_bind_double(st, idx, (*env)->CallDoubleMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_string)) { + jsize len = (*env)->GetStringLength(env, (jstring)v); + const jchar *chars = (*env)->GetStringChars(env, (jstring)v, NULL); + if (!chars) return SQLITE_NOMEM; + rc = sqlite3_bind_text16(st, idx, chars, len * 2, SQLITE_TRANSIENT); + (*env)->ReleaseStringChars(env, (jstring)v, chars); + } else { + jclass bytes_class = (*env)->FindClass(env, "[B"); + int is_bytes = bytes_class && (*env)->IsInstanceOf(env, v, bytes_class); + if (bytes_class) (*env)->DeleteLocalRef(env, bytes_class); + if (!is_bytes) { + *message = "unsupported argument type"; + return SQLITE_MISUSE; + } + jsize len = (*env)->GetArrayLength(env, (jbyteArray)v); + void *copy = malloc(len ? (size_t)len : 1); + if (!copy) return SQLITE_NOMEM; + (*env)->GetByteArrayRegion(env, (jbyteArray)v, 0, len, (jbyte *)copy); + rc = sqlite3_bind_blob64(st, idx, copy, (sqlite3_uint64)len, SQLITE_TRANSIENT); + free(copy); + } + if (rc != SQLITE_OK) { + *message = sqlite3_errmsg(db); + return rc; + } + return (*env)->ExceptionCheck(env) ? SQLITE_ERROR : SQLITE_OK; +} + +// Binds args by position, ? and ?NNN alike: args[i] to parameter i + 1. Their number must be the +// statement's parameter count: a missing one would be bound as NULL and the query would run, +// returning a plausible empty result. +static int bind_positional(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, const char **message) { + int wanted = sqlite3_bind_parameter_count(st); jsize count = (*env)->GetArrayLength(env, args); + if (count != wanted) { + char msg[96]; + snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)count); + throw_engine(env, SQLITE_RANGE, msg); + return SQLITE_RANGE; + } for (jsize i = 0; i < count; i++) { jobject v = (*env)->GetObjectArrayElement(env, args, i); - int rc; - if (!v) { - rc = sqlite3_bind_null(st, i + 1); - } else if ((*env)->IsInstanceOf(env, v, g_long)) { - jmethodID m = (*env)->GetMethodID(env, g_long, "longValue", "()J"); - rc = sqlite3_bind_int64(st, i + 1, (sqlite3_int64)(*env)->CallLongMethod(env, v, m)); - } else if ((*env)->IsInstanceOf(env, v, g_double)) { - jmethodID m = (*env)->GetMethodID(env, g_double, "doubleValue", "()D"); - rc = sqlite3_bind_double(st, i + 1, (*env)->CallDoubleMethod(env, v, m)); - } else if ((*env)->IsInstanceOf(env, v, g_string)) { - jsize len = (*env)->GetStringLength(env, (jstring)v); - const jchar *chars = (*env)->GetStringChars(env, (jstring)v, NULL); - if (!chars) return SQLITE_NOMEM; - rc = sqlite3_bind_text16(st, i + 1, chars, len * 2, SQLITE_TRANSIENT); - (*env)->ReleaseStringChars(env, (jstring)v, chars); - } else { - jclass bytes_class = (*env)->FindClass(env, "[B"); - int is_bytes = bytes_class && (*env)->IsInstanceOf(env, v, bytes_class); - if (bytes_class) (*env)->DeleteLocalRef(env, bytes_class); - if (!is_bytes) { - *message = "unsupported argument type"; - return SQLITE_MISUSE; + int rc = bind_value(env, db, st, i + 1, v, message); + if (v) (*env)->DeleteLocalRef(env, v); + if (rc != SQLITE_OK) return rc; + } + return SQLITE_OK; +} + +typedef struct { + char *name; // UTF-8, not terminated + size_t len; + int used; +} bind_key; + +// Whether SQLite's parameter name (":id", "@id", "$id" or "?3") is key: written the same, or key +// without the prefix (":", "@" or "$"). +static int key_matches(const char *param, const bind_key *key) { + size_t plen = strlen(param); + if (plen == key->len && memcmp(param, key->name, plen) == 0) return 1; + if (key->len == 0 || strchr(":@$?", key->name[0])) return 0; + return strchr(":@$", param[0]) && plen - 1 == key->len && memcmp(param + 1, key->name, key->len) == 0; +} + +// Binds args by name: names[i] (UTF-8) names the parameter args[i] goes to. Every parameter must +// get exactly one value and every name must be used, so a misspelt name fails instead of leaving a +// NULL. +static int bind_named(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, jobjectArray names, + const char **message) { + jsize n = (*env)->GetArrayLength(env, names); + if ((*env)->GetArrayLength(env, args) != n) { + *message = "names and args differ in length"; + return SQLITE_MISUSE; + } + bind_key *keys = calloc(n ? (size_t)n : 1, sizeof *keys); + if (!keys) return SQLITE_NOMEM; + int rc = SQLITE_OK; + char msg[256]; + for (jsize i = 0; i < n && rc == SQLITE_OK; i++) { + jbyteArray b = (jbyteArray)(*env)->GetObjectArrayElement(env, names, i); + if (!b) { + *message = "a parameter name is null"; + rc = SQLITE_MISUSE; + break; + } + jsize len = (*env)->GetArrayLength(env, b); + keys[i].name = malloc(len ? (size_t)len : 1); + if (!keys[i].name) rc = SQLITE_NOMEM; + else { + (*env)->GetByteArrayRegion(env, b, 0, len, (jbyte *)keys[i].name); + keys[i].len = (size_t)len; + } + (*env)->DeleteLocalRef(env, b); + } + int count = sqlite3_bind_parameter_count(st); + for (int p = 1; p <= count && rc == SQLITE_OK; p++) { + const char *param = sqlite3_bind_parameter_name(st, p); + if (!param) { + snprintf(msg, sizeof msg, + "parameter %d has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", p); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + break; + } + jsize found = -1; + for (jsize i = 0; i < n; i++) { + if (!key_matches(param, &keys[i])) continue; + if (found >= 0) { + snprintf(msg, sizeof msg, "parameter %.100s is given more than once", param); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + break; } - jsize len = (*env)->GetArrayLength(env, (jbyteArray)v); - void *copy = malloc(len ? (size_t)len : 1); - if (!copy) return SQLITE_NOMEM; - (*env)->GetByteArrayRegion(env, (jbyteArray)v, 0, len, (jbyte *)copy); - rc = sqlite3_bind_blob64(st, i + 1, copy, (sqlite3_uint64)len, SQLITE_TRANSIENT); - free(copy); + found = i; } - if (v) (*env)->DeleteLocalRef(env, v); - if (rc != SQLITE_OK) { - *message = sqlite3_errmsg(db); - return rc; + if (rc != SQLITE_OK) break; + if (found < 0) { + snprintf(msg, sizeof msg, "no value was given for parameter %.100s", param); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + break; } - if ((*env)->ExceptionCheck(env)) return SQLITE_ERROR; + keys[found].used = 1; + jobject v = (*env)->GetObjectArrayElement(env, args, found); + rc = bind_value(env, db, st, p, v, message); + if (v) (*env)->DeleteLocalRef(env, v); } - return SQLITE_OK; + for (jsize i = 0; i < n && rc == SQLITE_OK; i++) { + if (keys[i].used) continue; + int shown = keys[i].len > 100 ? 100 : (int)keys[i].len; + snprintf(msg, sizeof msg, "the statement has no parameter named %.*s", shown, keys[i].name); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + } + for (jsize i = 0; i < n; i++) free(keys[i].name); + free(keys); + return rc; } // A UTF-8 prefix of at most max bytes ending on a character boundary. @@ -348,7 +461,8 @@ static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, } } -static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong offset, +static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, + jobjectArray names, jlong offset, jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; @@ -392,31 +506,31 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sqlite3_progress_handler(db, 1000, progress_cb, &dl); handler_set = 1; - // A missing argument would be bound as NULL and the query would run, returning a plausible empty result. - int wanted = sqlite3_bind_parameter_count(st); - jsize given = (*env)->GetArrayLength(env, args); - if (given != wanted) { - char msg[96]; - snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)given); - throw_engine(env, SQLITE_RANGE, msg); - goto done; - } - rc = bind_args(env, db, st, args, &message); + rc = names ? bind_named(env, db, st, args, names, &message) : bind_positional(env, db, st, args, &message); if (rc != SQLITE_OK) { if (!(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); goto done; } int ncols = sqlite3_column_count(st); - jobjectArray names = (*env)->NewObjectArray(env, ncols, g_string, NULL); - jobject rows = names ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; + jobjectArray columns = (*env)->NewObjectArray(env, ncols, g_string, NULL); + // The declared type of each column, null for an expression (sqlite3_column_decltype) + jobjectArray decltypes = columns ? (*env)->NewObjectArray(env, ncols, g_string, NULL) : NULL; + jobject rows = decltypes ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; if (!rows) goto done; for (int c = 0; c < ncols; c++) { const char *name = sqlite3_column_name(st, c); jstring s = utf8_string(env, name ? name : "", name ? (int)strlen(name) : 0); if (!s) goto done; - (*env)->SetObjectArrayElement(env, names, c, s); + (*env)->SetObjectArrayElement(env, columns, c, s); (*env)->DeleteLocalRef(env, s); + const char *decl = sqlite3_column_decltype(st, c); + if (decl) { + jstring d = utf8_string(env, decl, (int)strlen(decl)); + if (!d) goto done; + (*env)->SetObjectArrayElement(env, decltypes, c, d); + (*env)->DeleteLocalRef(env, d); + } } int has_more = 0, row_count = 0; @@ -486,14 +600,15 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring // {cut cell count, hasMore, then the index of each cut cell} jlongArray counts = (*env)->NewLongArray(env, (jsize)(2 + cut_n)); - result = counts ? (*env)->NewObjectArray(env, 3, g_object, NULL) : NULL; + result = counts ? (*env)->NewObjectArray(env, 4, g_object, NULL) : NULL; if (!result) goto done; jlong head[2] = {(jlong)cut_n, has_more}; (*env)->SetLongArrayRegion(env, counts, 0, 2, head); if (cut_n) (*env)->SetLongArrayRegion(env, counts, 2, (jsize)cut_n, cut_cells); - (*env)->SetObjectArrayElement(env, result, 0, names); + (*env)->SetObjectArrayElement(env, result, 0, columns); (*env)->SetObjectArrayElement(env, result, 1, rows); (*env)->SetObjectArrayElement(env, result, 2, counts); + (*env)->SetObjectArrayElement(env, result, 3, decltypes); done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); @@ -550,7 +665,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"readEvents", "(J[B[J)V", (void *)bridge_read_events}, {"setClientConnected", "(Z)V", (void *)bridge_set_client_connected}, {"openServer", "([BZ)J", (void *)bridge_open_server}, - {"query", "(JLjava/lang/String;[Ljava/lang/Object;JIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, + {"setRowCapture", "(III)V", (void *)bridge_set_row_capture}, + {"query", "(JLjava/lang/String;[Ljava/lang/Object;[[BJIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 0c3fa07de0..1c5cb10701 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -29,9 +29,20 @@ interface DebugEngine { maxBytes: Int, ): EventBatch - /** While true, statements are recorded with their bound values written in. */ + /** While true, statements are recorded with their bound values written in, and rows if [setRowCapture] is on. */ fun setClientConnected(connected: Boolean) + /** + * Records the first [maxRowsPerStatement] rows of each statement as [EventKind.ROW] events while a + * client is connected; 0 turns it off, as at install. TEXT and BLOB values are cut at [maxValueBytes] + * and a row's data at [maxRowBytes] (`sqlitedbg_set_row_capture`). + */ + fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) + /** * Opens [path] for the server: read-only (with an authorizer refusing writes) unless * [writable]. Only a path one of [connections] has open may be passed: opening a database that @@ -55,12 +66,17 @@ interface ServerConnection : Closeable { * progress handler on this server connection) once [deadlineMillis] (System.currentTimeMillis * clock) has passed. * + * [argNames] null binds [args] by position, `?NNN` by its number; otherwise `argNames[i]` names the + * parameter `args[i]` goes to, written as in the SQL (`:id`, `@id`, `$id`, `?3`) or bare (`id`, for + * any of `:`, `@` and `$`). Every parameter must get exactly one value and every name must be used. + * * @throws DebugEngineException for SQLite errors, SQL with no statement or more than one, a - * refused write, or the deadline. + * refused write, the deadline, or arguments that do not match the parameters (SQLITE_RANGE). */ fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -178,6 +194,8 @@ data class QueryResult( * is whole and not listed, one byte more is. [truncatedCells] is its size. */ val truncatedCellIndexes: Set = emptySet(), + /** Each column's declared type, as `sqlite3_column_decltype` gives it; null for an expression. */ + val declaredTypes: List = List(columns.size) { null }, ) { fun isTruncated( row: Int, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 2aee5d390a..6450b1c403 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -24,6 +24,17 @@ internal object NativeBridge { @JvmStatic external fun setClientConnected(connected: Boolean) + /** + * Turns row recording on (`maxRowsPerStatement` > 0) or off (0): `sqlitedbg_set_row_capture`. A value + * or row limit of 0 takes the extension's default. + */ + @JvmStatic + external fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) + /** A handle for [query] and [close]. Throws [DebugEngineException]. */ @JvmStatic external fun openServer( @@ -32,15 +43,17 @@ internal object NativeBridge { ): Long /** - * `[Array, ArrayList>, LongArray]`: the column names, the rows, and - * `{truncatedCells, hasMore, then the index of each cut cell}` (row * columns + column). - * Throws [DebugEngineException]. + * `[Array, ArrayList>, LongArray, Array]`: the column names, the rows, + * `{truncatedCells, hasMore, then the index of each cut cell}` (row * columns + column), and each + * column's declared type. [names] null binds [args] by position; otherwise `names[i]` (UTF-8) names + * the parameter `args[i]` goes to. Throws [DebugEngineException]. */ @JvmStatic external fun query( handle: Long, sql: String, args: Array, + names: Array?, offset: Long, maxRows: Int, maxTextBytes: Int, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index de4217fb02..9b4130b98d 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -70,6 +70,12 @@ class NativeDebugEngine : DebugEngine { override fun setClientConnected(connected: Boolean) = NativeBridge.setClientConnected(connected) + override fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) = NativeBridge.setRowCapture(maxRowsPerStatement, maxValueBytes, maxRowBytes) + override fun openServerConnection( path: String, writable: Boolean, @@ -81,12 +87,14 @@ class NativeDebugEngine : DebugEngine { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, ): QueryResult { check(handle != 0L) { "the connection is closed" } require(offset >= 0) { "offset $offset is negative" } + require(argNames == null || argNames.size == args.size) { "${argNames?.size} names for ${args.size} args" } require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0 && limits.maxTotalBytes > 0) { "bad limits $limits" } @@ -95,6 +103,7 @@ class NativeDebugEngine : DebugEngine { handle, sql, Array(args.size) { bindable(args[it]) }, + argNames?.map { it.toByteArray(Charsets.UTF_8) }?.toTypedArray(), offset, limits.maxRows, limits.maxTextBytes, @@ -111,7 +120,16 @@ class NativeDebugEngine : DebugEngine { val counts = result[2] as LongArray val cut = HashSet() for (i in 2 until counts.size) cut += counts[i] - return QueryResult(columns, rows, truncatedCells = counts[0].toInt(), hasMore = counts[1] != 0L, truncatedCellIndexes = cut) + @Suppress("UNCHECKED_CAST") + val declaredTypes = (result[3] as Array).asList() + return QueryResult( + columns, + rows, + truncatedCells = counts[0].toInt(), + hasMore = counts[1] != 0L, + truncatedCellIndexes = cut, + declaredTypes = declaredTypes, + ) } override fun close() { 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..59551f962c 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 @@ -3,6 +3,8 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.Event +import org.appdevforall.sqlitedebugger.engine.EventKind import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult import org.appdevforall.sqlitedebugger.engine.ServerConnection @@ -70,11 +72,23 @@ class DatabaseTools internal constructor( /** Bound values stop being recorded this long after the last get_events call. */ const val EVENTS_IDLE_MS = 60_000L + /** get_events' row recording: rows per statement, bytes per TEXT or BLOB value, and bytes per row. */ + const val EVENT_ROWS_PER_STATEMENT = 10 + const val EVENT_VALUE_BYTES = 256 + const val EVENT_ROW_BYTES = 4096 + private const val MAX_SAFE_INTEGER = 9007199254740992L // 2^53 private val SIDE_FILE_SUFFIXES = listOf("-wal", "-shm", "-journal") const val PAGING_NOTE = "Paging re-runs the query for each page, so a later page can differ if the data changed." + /** How a cell is written, said by every tool that returns cells. */ + const val VALUES_NOTE = + "A NULL is JSON null; a BLOB is {hex, bytes, truncated}; an integer beyond 2^53 is a decimal string, and a " + + "NaN or infinite REAL is the string \"NaN\", \"Infinity\" or \"-Infinity\". storage_classes gives each row's " + + "SQLite storage classes, one letter per column: i INTEGER, r REAL, t TEXT, b BLOB, n NULL (JSON writes a REAL " + + "such as 2.0 as 2)." + /** Said by the tools that return cells whose TEXT and BLOB values the server can cut. */ private const val CUT_CELLS_NOTE = "truncated_cells counts the cut cells and truncated_cell_indexes lists each as [row, column], both from 0 and " + @@ -128,7 +142,7 @@ class DatabaseTools internal constructor( is ByteArray -> { JSONObject() - .put("base64", McpHttp.base64(value, urlSafe = false, pad = true)) + .put("hex", hex(value)) .put("bytes", value.size) .put("truncated", truncated) } @@ -138,6 +152,29 @@ class DatabaseTools internal constructor( } } + private val HEX_DIGITS = "0123456789abcdef".toCharArray() + + fun hex(bytes: ByteArray): String { + val out = CharArray(bytes.size * 2) + bytes.forEachIndexed { i, b -> + out[i * 2] = HEX_DIGITS[(b.toInt() shr 4) and 0xf] + out[i * 2 + 1] = HEX_DIGITS[b.toInt() and 0xf] + } + return String(out) + } + + /** One letter per value: i INTEGER, r REAL, t TEXT, b BLOB, n NULL (see [VALUES_NOTE]). */ + fun storageClasses(values: List): String = + values.joinToString("") { + when (it) { + null -> "n" + is Long, is Int -> "i" + is Double -> "r" + is ByteArray -> "b" + else -> "t" + } + } + fun encodeLong(value: Long): Any = if (value > MAX_SAFE_INTEGER || value < -MAX_SAFE_INTEGER) value.toString() else value fun quoteIdentifier(name: String) = "\"" + name.replace("\"", "\"\"") + "\"" @@ -146,6 +183,7 @@ class DatabaseTools internal constructor( private val lock = Any() private val serverConnections = HashMap() private var clientConnected = false + private var rowCapture = false private var lastEventsCallMs = 0L private var cancelIdleCheck: (() -> Unit)? = null private var idleCheckGeneration = 0 @@ -182,9 +220,17 @@ class DatabaseTools internal constructor( clientConnected = false engine.setClientConnected(false) } + setRowCaptureLocked(false) } } + /** Row recording costs the app time on every row it reads, so it is on only while a get_events client asks for rows. [lock] held. */ + private fun setRowCaptureLocked(on: Boolean) { + if (on == rowCapture) return + rowCapture = on + if (on) engine.setRowCapture(EVENT_ROWS_PER_STATEMENT, EVENT_VALUE_BYTES, EVENT_ROW_BYTES) else engine.setRowCapture(0, 0, 0) + } + /** * Stops recording bound values once [EVENTS_IDLE_MS] have passed since the last get_events call: * expanding every statement costs memory, and nobody is reading. Checked on every tool call and @@ -196,6 +242,7 @@ class DatabaseTools internal constructor( if (clientConnected && clock() - lastEventsCallMs >= EVENTS_IDLE_MS) { clientConnected = false engine.setClientConnected(false) + setRowCaptureLocked(false) } } @@ -249,7 +296,8 @@ class DatabaseTools internal constructor( tool( "query", "Run a query", - "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + + "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS), " + + "with each column's declared_type in column_types (null for an expression). $VALUES_NOTE " + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES: $CUT_CELLS_NOTE " + "A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + @@ -257,7 +305,7 @@ class DatabaseTools internal constructor( "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), - "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), + "args" to argsSchema(), "offset" to prop("integer", "Rows to skip. Default 0."), "max_rows" to prop("integer", "Rows to return. Default $DEFAULT_MAX_ROWS, at most $MAX_ROWS."), required = listOf("sql"), @@ -270,7 +318,7 @@ class DatabaseTools internal constructor( "A cell cut at $MAX_TEXT_BYTES bytes is listed as in query: $CUT_CELLS_NOTE $APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), - "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), + "args" to argsSchema(), required = listOf("sql"), ), ) { call, args -> explain(call, args) }, @@ -302,7 +350,17 @@ class DatabaseTools internal constructor( "as run to continue; dropped counts events that left the buffer unread. reset true means the app restarted " + "(run differs, or after is past the newest event), and events are read from the start. " + "The first call starts recording bound values into the SQL; " + - "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while watching.", + "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while " + + "watching. " + + "kind is statement (one starts; a trigger's SQL starts with --), profile (one finished: duration_nanos; rows, the " + + "rows it returned; changes, the rows it changed itself, not through triggers, null for a read; null when the " + + "statement's start was not seen), close, or row. With include_rows true (the default), the app's statements " + + "after the call also record their first $EVENT_ROWS_PER_STATEMENT rows as row events: row_number (from 1), " + + "column_count, values, storage_classes and cut_values (indexes of TEXT and BLOB values cut at " + + "$EVENT_VALUE_BYTES bytes); a row's data stops at ${EVENT_ROW_BYTES / 1024} KiB, and then values holds fewer " + + "than column_count and truncated is true. A profile's rows_cut says rows went unrecorded past the limit. " + + "$VALUES_NOTE Recording rows costs the app a few microseconds a row, so pass include_rows false when you need " + + "only the SQL; it then stops, and row events are left out.", JSONObject() .put("type", "object") .put("additionalProperties", false) @@ -313,7 +371,7 @@ class DatabaseTools internal constructor( .put( "run", prop("string", "The run from the last call. If it differs from the current, the read starts from 0."), - ), + ).put("include_rows", prop("boolean", "Record and return rows the app's statements return. Default true.")), ).put("required", JSONArray()), ) { _, args -> getEvents(args) }, ) @@ -335,6 +393,16 @@ class DatabaseTools internal constructor( description: String, ) = JSONObject().put("type", type).put("description", description) + private fun argsSchema() = + JSONObject() + .put("type", JSONArray(listOf("array", "object"))) + .put( + "description", + "Values to bind: null, numbers or strings. An array binds by position (? and ?NNN, by number); an object binds " + + "by name (:name, @name, \$name, ?NNN), with keys written as in the SQL or without the prefix. Every " + + "parameter needs a value, and every key a parameter.", + ) + private fun databaseSchema( vararg extra: Pair, required: List = emptyList(), @@ -394,7 +462,7 @@ class DatabaseTools internal constructor( call, args, "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name", - emptyList(), + Bind.NONE, 0, QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ) @@ -456,7 +524,7 @@ class DatabaseTools internal constructor( val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) val path = checkedPath(call, args) - fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", emptyList(), 0, limits).rows.firstOrNull()?.firstOrNull() + fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", Bind.NONE, 0, limits).rows.firstOrNull()?.firstOrNull() val pageCount = pragma("page_count") as? Long val pageSize = pragma("page_size") as? Long val out = @@ -470,7 +538,7 @@ class DatabaseTools internal constructor( call, path, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name", - emptyList(), + Bind.NONE, 0, limits, ).rows @@ -484,7 +552,7 @@ class DatabaseTools internal constructor( call, path, "SELECT COUNT(*) FROM ${quoteIdentifier(t)}", - emptyList(), + Bind.NONE, 0, limits, ).rows.firstOrNull()?.firstOrNull() @@ -513,7 +581,7 @@ class DatabaseTools internal constructor( else -> throw McpToolError("full must be true or false.") } val pragma = if (full) "PRAGMA integrity_check" else "PRAGMA quick_check" - val result = run(call, args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) + val result = run(call, args, pragma, Bind.NONE, 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) val messages = result.rows.map { it.firstOrNull()?.toString() ?: "" } return JSONObject() .put("check", if (full) "integrity_check" else "quick_check") @@ -531,9 +599,16 @@ class DatabaseTools internal constructor( is String -> v else -> throw McpToolError("run must be a string.") } + val includeRows = + when (val v = args.opt("include_rows")) { + null, JSONObject.NULL -> true + is Boolean -> v + else -> throw McpToolError("include_rows must be true or false.") + } val otherRun = run != null && run != engine.runId synchronized(lock) { lastEventsCallMs = clock() + setRowCaptureLocked(includeRows) if (!clientConnected) { engine.setClientConnected(true) clientConnected = true @@ -548,18 +623,8 @@ class DatabaseTools internal constructor( } val events = JSONArray() for (e in batch.events) { - events.put( - JSONObject() - .put("seq", encodeLong(e.seq)) - .put("kind", e.kind.name.lowercase()) - .put("connection_id", encodeLong(e.connectionId)) - .put("thread_id", encodeLong(e.threadId)) - .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) - .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) - .put("sql", e.sql) - .put("truncated", e.truncated) - .put("expanded", e.expanded), - ) + if (e.kind == EventKind.ROW && !includeRows) continue + events.put(encodeEvent(e)) } return JSONObject() .put("run", engine.runId) @@ -569,6 +634,43 @@ class DatabaseTools internal constructor( .put("events", events) } + private fun encodeEvent(e: Event): JSONObject { + val out = + JSONObject() + .put("seq", encodeLong(e.seq)) + .put("kind", e.kind.name.lowercase()) + .put("connection_id", encodeLong(e.connectionId)) + .put("thread_id", encodeLong(e.threadId)) + .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) + .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("sql", e.sql) + .put("truncated", e.truncated) + .put("expanded", e.expanded) + when (e.kind) { + EventKind.PROFILE -> { + out + .put("rows", e.rows?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("changes", e.changes?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("rows_cut", e.rowsCut) + } + + EventKind.ROW -> { + val row = e.row + out.put("row_number", e.rows?.let { encodeLong(it) } ?: JSONObject.NULL) + if (row != null) { + out + .put("column_count", row.columnCount) + .put("values", JSONArray(row.values.mapIndexed { i, v -> encodeValue(v, i in row.cutIndexes) })) + .put("storage_classes", storageClasses(row.values)) + .put("cut_values", JSONArray(row.cutIndexes.sorted())) + } + } + + else -> {} + } + return out + } + private fun encodeResult( result: QueryResult, offset: Long, @@ -580,7 +682,9 @@ class DatabaseTools internal constructor( val out = JSONObject() .put("columns", JSONArray(result.columns)) + .put("column_types", JSONArray().also { a -> result.declaredTypes.forEach { a.put(it ?: JSONObject.NULL) } }) .put("rows", rows) + .put("storage_classes", JSONArray(result.rows.map { storageClasses(it) })) .put("row_count", result.rows.size) .put("offset", encodeLong(offset)) .put("has_more", result.hasMore) @@ -639,7 +743,7 @@ class DatabaseTools internal constructor( call: Call, args: JSONObject, sql: String, - bind: List, + bind: Bind, offset: Long, limits: QueryLimits, ): QueryResult = runChecked(call, checkedPath(call, args), sql, bind, offset, limits) @@ -648,7 +752,7 @@ class DatabaseTools internal constructor( call: Call, path: String, sql: String, - bind: List, + bind: Bind, offset: Long, limits: QueryLimits, ): QueryResult = @@ -666,7 +770,7 @@ class DatabaseTools internal constructor( if (ids.isEmpty()) throw unknownDatabase(path, knownPaths(live)) CachedConnection(engine.openServerConnection(path, writable = false), ids) }.connection - conn.query(sql, bind, offset, limits, call.deadline) + conn.query(sql, bind.values, bind.names, offset, limits, call.deadline) } catch (e: DebugEngineException) { val error = engineError(e) // The time limit counts the call's waits for the lock, so a quick query can run out of time @@ -734,23 +838,52 @@ class DatabaseTools internal constructor( return l } - private fun bindArgs(args: JSONObject): List { - val raw = args.opt("args") - if (raw == null || raw == JSONObject.NULL) return emptyList() - val arr = raw as? JSONArray ?: throw McpToolError("args must be an array.") - return (0 until arr.length()).map { i -> - when (val v = arr.opt(i)) { + /** Values to bind: by position when [names] is null, else `names[i]` names the parameter of `values[i]`. */ + private class Bind( + val values: List, + val names: List?, + ) { + companion object { + val NONE = Bind(emptyList(), null) + } + } + + private fun bindArgs(args: JSONObject): Bind { + fun value( + v: Any?, + what: String, + ): Any? = + when (v) { null, JSONObject.NULL -> null is Int, is Long, is Short -> (v as Number).toLong() is Number -> v.toDouble() is String -> v is Boolean -> if (v) 1L else 0L - else -> throw McpToolError("args[$i] must be null, a number or a string.") + else -> throw McpToolError("$what must be null, a number or a string.") + } + return when (val raw = args.opt("args")) { + null, JSONObject.NULL -> { + Bind.NONE + } + + is JSONArray -> { + Bind((0 until raw.length()).map { i -> value(raw.opt(i), "args[$i]") }, null) + } + + is JSONObject -> { + val names = raw.keys().asSequence().sorted().toList() + names.forEach { if (it.isEmpty()) throw McpToolError("args has an empty name.") } + Bind(names.map { value(raw.opt(it), "args.$it") }, names) + } + + else -> { + throw McpToolError("args must be an array or an object.") } } } } + /** Runs the idle check later; a test seam, the real one is [TimerIdleScheduler]. */ internal fun interface IdleScheduler { /** Runs [task] once after [delayMs]; the result cancels it. */ diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index f889ba3684..727f47d991 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -29,6 +29,13 @@ class FakeDebugEngine( var clientConnected = false private set + /** Each setRowCapture call, in order: rows per statement, value bytes, row bytes. */ + val rowCaptureCalls = mutableListOf>() + + /** The argNames of the last query: null when its args were bound by position. */ + var lastArgNames: List? = null + private set + val openedServerConnections = mutableListOf>() /** How many times the server asked to open one, counted before any refusal: [openedServerConnections] holds only successes. */ @@ -49,6 +56,12 @@ class FakeDebugEngine( buffered.addLast(Event(lastSeq, kind, connectionId, 1, lastSeq, durationNanos, sql, false, clientConnected)) } + /** Adds the event [make] builds for the next number, for the kinds and fields [addEvent] does not set. */ + fun addEvent(make: (seq: Long) -> Event) { + lastSeq++ + buffered.addLast(make(lastSeq)) + } + /** Drops the [count] oldest buffered events, as a full native buffer would. */ fun dropOldest(count: Int) = repeat(count) { buffered.removeFirstOrNull() } @@ -87,6 +100,14 @@ class FakeDebugEngine( clientConnected = connected } + override fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) { + rowCaptureCalls += Triple(maxRowsPerStatement, maxValueBytes, maxRowBytes) + } + override fun openServerConnection( path: String, writable: Boolean, @@ -105,11 +126,13 @@ class FakeDebugEngine( override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, ): QueryResult { check(!closed) { "closed" } + lastArgNames = argNames val all = answer(path, writable, sql, args) val skip = offset.toInt().coerceAtMost(all.rows.size) val rest = all.rows.drop(skip) 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..9a96068be4 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 @@ -3,10 +3,13 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.Event +import org.appdevforall.sqlitedebugger.engine.EventDecoder import org.appdevforall.sqlitedebugger.engine.EventKind import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.appdevforall.sqlitedebugger.engine.RowValues import org.appdevforall.sqlitedebugger.engine.ServerConnection import org.json.JSONArray import org.json.JSONObject @@ -359,6 +362,8 @@ class DatabaseToolsTest { bad("sql" to "x", "max_rows" to 1.5) bad("sql" to "x", "args" to "nope") bad("sql" to "x", "args" to JSONArray().put(JSONObject())) + bad("sql" to "x", "args" to JSONObject().put("a", JSONArray())) + bad("sql" to "x", "args" to JSONObject().put("", 1)) assertTrue(engine.openedServerConnections.isEmpty()) assertEquals(0, engine.openAttempts) } @@ -383,6 +388,7 @@ class DatabaseToolsTest { ), ) assertEquals(listOf(null, 3L, 2.5, "s", 1L), got) + assertEquals("an array binds by position", null, engine.lastArgNames) } @Test fun queryErrorsCarryTheSqliteCode() { @@ -409,12 +415,13 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: org.appdevforall.sqlitedebugger.engine.QueryLimits, deadlineMillis: Long, ): QueryResult { deadline = deadlineMillis - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -434,6 +441,7 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -444,7 +452,7 @@ class DatabaseToolsTest { "the time limit passed before the query started", ) } - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -514,6 +522,7 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -527,7 +536,7 @@ class DatabaseToolsTest { throw DebugEngineException(DebugEngineException.SQLITE_INTERRUPT, "the query ran past its time limit") } now += runMs - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -672,7 +681,7 @@ class DatabaseToolsTest { assertEquals("-9007199254740993", row.get(4)) assertEquals(9_007_199_254_740_992L, row.getLong(5)) val blob = row.getJSONObject(6) - assertEquals("AQID", blob.getString("base64")) + assertEquals("010203", blob.getString("hex")) assertEquals(3, blob.getInt("bytes")) assertFalse(blob.getBoolean("truncated")) assertTrue(row.isNull(7)) @@ -1086,6 +1095,206 @@ class DatabaseToolsTest { t.onServerStopped() } + @Test fun queryBindsAnObjectByName() { + engine.appConnections += conn(1, "/data/a.db") + var got: List = emptyList() + engine.answer = { _, _, _, a -> + got = a + QueryResult(emptyList(), emptyList(), 0, false) + } + ok("query", db().put("sql", "x").put("args", JSONObject().put(":b", "s").put("a", 1).put("\$c", JSONObject.NULL).put("?2", 2.5))) + val byName = engine.lastArgNames!!.zip(got).toMap() + assertEquals(mapOf("a" to 1L, ":b" to "s", "\$c" to null, "?2" to 2.5), byName) + ok("explain_query_plan", db().put("sql", "x").put("args", JSONObject().put("id", 7))) + assertEquals(listOf("id"), engine.lastArgNames) + assertEquals(listOf(7L), got) + ok("query", db().put("sql", "x").put("args", JSONObject())) + assertEquals("an empty object still binds by name: a parameter left out is an error", emptyList(), engine.lastArgNames) + ok("query", db().put("sql", "x")) + assertEquals("no args", null, engine.lastArgNames) + } + + @Test fun queryDescribesBothArgForms() { + val query = tools.tools().single { it.name == "query" } + val args = query.inputSchema.getJSONObject("properties").getJSONObject("args") + assertEquals(listOf("array", "object"), args.getJSONArray("type").let { a -> (0 until a.length()).map { a.getString(it) } }) + for (form in listOf(":name", "@name", "\$name", "?NNN")) assertTrue(form, args.getString("description").contains(form)) + } + + @Test fun queryReturnsDeclaredTypesAndStorageClasses() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> + QueryResult( + listOf("id", "r", "s", "b", "e"), + listOf(listOf(1L, 2.0, "x", byteArrayOf(0x0f, -1), null), listOf("t", null, 3L, 1.5, byteArrayOf())), + 0, + false, + declaredTypes = listOf("INTEGER", "REAL", "TEXT", "BLOB", null), + ) + } + val r = ok("query", db().put("sql", "x")) + val types = r.getJSONArray("column_types") + val declared = (0 until types.length()).map { if (types.isNull(it)) null else types.get(it) } + assertEquals(listOf("INTEGER", "REAL", "TEXT", "BLOB", null), declared) + assertEquals(listOf("irtbn", "tnirb"), r.getJSONArray("storage_classes").let { a -> (0 until a.length()).map { a.getString(it) } }) + assertTrue("a REAL 2.0 reads as 2 in JSON, so only the storage class tells it from an INTEGER", r.toString().contains("[1,2,\"x\"")) + assertEquals("0fff", r.getJSONArray("rows").getJSONArray(0).getJSONObject(3).getString("hex")) + assertTrue(r.getJSONArray("rows").getJSONArray(0).isNull(4)) + val description = tools.tools().single { it.name == "query" }.description + assertTrue(description.contains("storage_classes") && description.contains("column_types") && description.contains("hex")) + } + + @Test fun queryResultWithoutDeclaredTypesGivesNullForEachColumn() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> QueryResult(listOf("a", "b"), listOf(listOf(1L, 2L)), 0, false) } + val types = ok("query", db().put("sql", "x")).getJSONArray("column_types") + assertEquals(2, types.length()) + assertTrue(types.isNull(0) && types.isNull(1)) + } + + private fun rowEvent( + seq: Long, + number: Long, + values: List, + cut: Set = emptySet(), + columns: Int = values.size, + ) = Event(seq, EventKind.ROW, 1, 1, seq, null, "", values.size < columns, true, rows = number, row = RowValues(columns, values, cut)) + + @Test fun getEventsReturnsRowsAndChangeCounts() { + engine.addEvent(EventKind.STATEMENT, "SELECT id, b FROM t") + engine.addEvent { rowEvent(it, 1, listOf(1L, byteArrayOf(1, 2)), cut = setOf(1)) } + engine.addEvent { rowEvent(it, 2, listOf("x"), columns = 2) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "SELECT id, b FROM t", false, true, rows = 12, rowsCut = true) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "DELETE FROM t", false, true, rows = 0, changes = 3) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "SELECT 1", false, true) } + val events = ok("get_events").getJSONArray("events") + assertEquals(6, events.length()) + val row1 = events.getJSONObject(1) + assertEquals("row", row1.getString("kind")) + assertEquals(1, row1.getInt("row_number")) + assertEquals(2, row1.getInt("column_count")) + assertEquals(1L, row1.getJSONArray("values").getLong(0)) + assertEquals("0102", row1.getJSONArray("values").getJSONObject(1).getString("hex")) + assertTrue(row1.getJSONArray("values").getJSONObject(1).getBoolean("truncated")) + assertEquals("ib", row1.getString("storage_classes")) + assertEquals(1, row1.getJSONArray("cut_values").getInt(0)) + assertFalse(row1.getBoolean("truncated")) + val row2 = events.getJSONObject(2) + assertEquals("a row whose data reached its limit keeps fewer values", 1, row2.getJSONArray("values").length()) + assertEquals(2, row2.getInt("column_count")) + assertTrue(row2.getBoolean("truncated")) + val select = events.getJSONObject(3) + assertEquals(12, select.getInt("rows")) + assertTrue("a read has no change count", select.isNull("changes")) + assertTrue(select.getBoolean("rows_cut")) + val delete = events.getJSONObject(4) + assertEquals(3, delete.getInt("changes")) + assertEquals(0, delete.getInt("rows")) + assertFalse(delete.getBoolean("rows_cut")) + val unseen = events.getJSONObject(5) + assertTrue("a statement whose start was not seen", unseen.isNull("rows") && unseen.isNull("changes")) + val statement = events.getJSONObject(0) + assertFalse("only a profile carries counts", statement.has("rows") || statement.has("changes") || statement.has("values")) + } + + @Test fun getEventsTurnsRowRecordingOnUnlessToldNotTo() { + val t = tools + ok("get_events", t = t) + assertEquals( + listOf(Triple(DatabaseTools.EVENT_ROWS_PER_STATEMENT, DatabaseTools.EVENT_VALUE_BYTES, DatabaseTools.EVENT_ROW_BYTES)), + engine.rowCaptureCalls, + ) + ok("get_events", t = t) + assertEquals("already on: no second call", 1, engine.rowCaptureCalls.size) + engine.addEvent(EventKind.STATEMENT, "SELECT 1") + engine.addEvent { rowEvent(it, 1, listOf(1L)) } + val r = ok("get_events", JSONObject().put("include_rows", false), t) + assertEquals(Triple(0, 0, 0), engine.rowCaptureCalls.last()) + assertEquals("row events are left out", listOf("statement"), kinds(r)) + assertEquals("the cursor still passes them", 2, r.getInt("next")) + ok("get_events", JSONObject().put("include_rows", true), t) + assertEquals(DatabaseTools.EVENT_ROWS_PER_STATEMENT, engine.rowCaptureCalls.last().first) + t.onServerStopped() + assertEquals("the server stopping turns it off", Triple(0, 0, 0), engine.rowCaptureCalls.last()) + assertTrue(runTool(tools, "get_events", JSONObject().put("include_rows", "yes")).getBoolean("isError")) + } + + @Test fun rowRecordingStopsWithTheIdleClient() { + val t = tools + ok("get_events", t = t) + now += DatabaseTools.EVENTS_IDLE_MS + t.expireIdleClient() + assertFalse(engine.clientConnected) + assertEquals(Triple(0, 0, 0), engine.rowCaptureCalls.last()) + ok("get_events", t = t) + assertEquals("the next get_events turns it on again", DatabaseTools.EVENT_ROWS_PER_STATEMENT, engine.rowCaptureCalls.last().first) + t.onServerStopped() + } + + @Test fun getEventsDescribesWhatIsCapped() { + val description = tools.tools().single { it.name == "get_events" }.description + for (text in listOf( + "first ${DatabaseTools.EVENT_ROWS_PER_STATEMENT} rows", + "${DatabaseTools.EVENT_VALUE_BYTES} bytes", + "${DatabaseTools.EVENT_ROW_BYTES / 1024} KiB", + "include_rows false", + "changes", + )) { + assertTrue(text, description.contains(text)) + } + } + + @Test fun getEventsEncodesTheEventsDecodedFromTheFixture() { + val bytes = checkNotNull(EventDecoder::class.java.getResourceAsStream("events.bin")).use { it.readBytes() } + val decoded = EventDecoder.decode(bytes, bytes.size) + assertTrue("the fixture has row events", decoded.any { it.kind == EventKind.ROW }) + assertTrue("and a change count", decoded.any { it.changes != null }) + decoded.forEach { e -> engine.addEvent { e.copy(seq = it) } } + val events = ok("get_events").getJSONArray("events") + assertEquals(decoded.size, events.length()) + decoded.forEachIndexed { i, e -> + val json = events.getJSONObject(i) + assertEquals(e.kind.name.lowercase(), json.getString("kind")) + when (e.kind) { + EventKind.ROW -> { + val row = e.row!! + assertEquals(row.columnCount, json.getInt("column_count")) + assertEquals(DatabaseTools.storageClasses(row.values), json.getString("storage_classes")) + val values = json.getJSONArray("values") + assertEquals(row.values.size, values.length()) + row.values.forEachIndexed { c, v -> + when (v) { + null -> assertTrue(values.isNull(c)) + is ByteArray -> assertEquals(DatabaseTools.hex(v), values.getJSONObject(c).getString("hex")) + is Double -> assertEquals(DatabaseTools.encodeValue(v), (values.get(c) as? Number)?.toDouble() ?: values.get(c)) + else -> assertEquals(DatabaseTools.encodeValue(v), values.get(c).let { if (it is Int) it.toLong() else it }) + } + } + val cut = json.getJSONArray("cut_values") + assertEquals(row.cutIndexes.sorted(), (0 until cut.length()).map { cut.getInt(it) }) + } + + EventKind.PROFILE -> { + assertEquals(e.rows, if (json.isNull("rows")) null else json.getLong("rows")) + assertEquals(e.changes, if (json.isNull("changes")) null else json.getLong("changes")) + assertEquals(e.rowsCut, json.getBoolean("rows_cut")) + } + + else -> { + assertEquals(e.sql, json.getString("sql")) + } + } + } + } + + @Test fun hexIsLowercaseAndCoversEveryByte() { + assertEquals("00017f80ff", DatabaseTools.hex(byteArrayOf(0, 1, 127, -128, -1))) + assertEquals("", DatabaseTools.hex(ByteArray(0))) + } + + private fun kinds(r: JSONObject) = + r.getJSONArray("events").let { a -> (0 until a.length()).map { a.getJSONObject(it).getString("kind") } } + private class FakeIdleScheduler : IdleScheduler { class Check( val task: Runnable, diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 5e47180211..f2cf88d016 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -44,12 +44,25 @@ static class Result { long truncated; boolean hasMore; Set cut = new HashSet<>(); + String[] declaredTypes; } @SuppressWarnings("unchecked") static Result query(long h, String sql, Object[] args, long offset, int maxRows, int maxText, int maxBlob, int maxTotal, long deadline) throws DebugEngineException { - Object[] r = NativeBridge.query(h, sql, args, offset, maxRows, maxText, maxBlob, maxTotal, deadline); + return named(h, sql, args, null, offset, maxRows, maxText, maxBlob, maxTotal, deadline); + } + + /** As query, with args bound by name when names is not null. */ + @SuppressWarnings("unchecked") + static Result named(long h, String sql, Object[] args, String[] names, long offset, int maxRows, int maxText, int maxBlob, + int maxTotal, long deadline) throws DebugEngineException { + byte[][] nameBytes = null; + if (names != null) { + nameBytes = new byte[names.length][]; + for (int i = 0; i < names.length; i++) nameBytes[i] = names[i].getBytes(StandardCharsets.UTF_8); + } + Object[] r = NativeBridge.query(h, sql, args, nameBytes, offset, maxRows, maxText, maxBlob, maxTotal, deadline); Result out = new Result(); out.columns = (String[]) r[0]; out.rows = (List) r[1]; @@ -58,6 +71,8 @@ static Result query(long h, String sql, Object[] args, long offset, int maxRows, out.hasMore = counts[1] != 0; eq(counts.length, 2 + (int) counts[0], "one index per cut cell"); for (int i = 2; i < counts.length; i++) out.cut.add(counts[i]); + out.declaredTypes = (String[]) r[3]; + eq(out.declaredTypes.length, out.columns.length, "one declared type per column"); return out; } @@ -74,6 +89,29 @@ static int codeOf(long h, String sql, Object[] args, long deadline) { } } + /** The row events (kind 4) in the buffer, read from the start; the records' layout is in sqlitedbg.h. */ + static long rowEvents() { + byte[] buf = new byte[1 << 20]; + long[] out = new long[4]; + NativeBridge.readEvents(0, buf, out); + java.nio.ByteBuffer b = java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + long rows = 0; + for (int at = 0; at < out[2]; at += b.getInt(at)) { + if (b.getInt(at + 4) == 4) rows++; + } + return rows; + } + + /** "code message" of a refused query with args bound by name, or null when it ran. */ + static String namedRefusal(long h, String sql, Object[] args, String[] names) { + try { + named(h, sql, args, names, 0, 100, 4096, 1024, MAX, FAR); + return null; + } catch (DebugEngineException e) { + return e.sqliteCode + " " + e.getMessage(); + } + } + /** "code message" of the refusal, or null when the query ran. */ static String refusal(long h, String sql) { try { @@ -195,6 +233,19 @@ public static void main(String[] a) throws Exception { eq(((String[]) conns[1]).length, 1, "one app connection"); eq(((String[]) conns[1])[0], path, "its path"); + // setRowCapture reaches the extension: rows are recorded only while it is on (and a client is connected) + NativeBridge.setClientConnected(true); + long rowsBefore = rowEvents(); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off"); + eq(rowEvents(), rowsBefore, "no row events while row recording is off"); + NativeBridge.setRowCapture(1, 0, 0); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording on"); + eq(rowEvents(), rowsBefore + 1, "one row event: one row per statement"); + NativeBridge.setRowCapture(0, 0, 0); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off again"); + eq(rowEvents(), rowsBefore + 1, "off again"); + NativeBridge.setClientConnected(false); + byte[] bytes = path.getBytes(StandardCharsets.UTF_8); long srv = NativeBridge.openServer(bytes, false); check(srv != 0, "server handle"); @@ -297,6 +348,35 @@ public static void main(String[] a) throws Exception { } eq(codeOf(srv, "SELECT ?", new Object[] {1L, 2L}, FAR), 25, "too many args: SQLITE_RANGE"); eq(codeOf(srv, "SELECT ?", new Object[] {new Object()}, FAR), 21, "unsupported arg type: SQLITE_MISUSE"); + r = query(srv, "SELECT ?2, ?1", new Object[] {"one", "two"}, 0, 10, 4096, 1024, MAX, FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList("two", "one"), "?NNN in an array binds by number"); + + // by name: each prefix, written with it or bare + r = named(srv, "SELECT :a, @b, $c, :a", new Object[] {1L, "x", null}, new String[] {":a", "b", "$c"}, 0, 10, 4096, 1024, MAX, + FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList(1L, "x", null, 1L), "named: :a, @b, $c, and :a again"); + r = named(srv, "SELECT ?2, ?1", new Object[] {"one", "two"}, new String[] {"?1", "?2"}, 0, 10, 4096, 1024, MAX, FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList("two", "one"), "named: ?NNN by its own name"); + r = named(srv, "SELECT :€", new Object[] {9L}, new String[] {"€"}, 0, 10, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 9L, "named: a non-ASCII name"); + r = named(srv, "SELECT 1", new Object[0], new String[0], 0, 10, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 1L, "named: no parameters, no names"); + eq(namedRefusal(srv, "SELECT :a, :b", new Object[] {1L}, new String[] {"a"}), "25 no value was given for parameter :b", + "named: a parameter left out"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L, 2L}, new String[] {"a", "zz"}), + "25 the statement has no parameter named zz", "named: a misspelt name"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L, 2L}, new String[] {"a", ":a"}), "25 parameter :a is given more than once", + "named: bare and prefixed"); + eq(namedRefusal(srv, "SELECT :a, ?", new Object[] {1L}, new String[] {"a"}), + "25 parameter 2 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: an anonymous ?"); + eq(namedRefusal(srv, "SELECT ?2", new Object[] {1L}, new String[] {"?2"}), + "25 parameter 1 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: a gap in ?NNN"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L}, new String[] {":b"}), "25 no value was given for parameter :a", + "named: a prefixed key matches only that prefix"); + + // declared types: the column's, or null for an expression + r = q(srv, "SELECT id, r, s, b, id + 1, NULL FROM t LIMIT 1"); + eq(Arrays.asList(r.declaredTypes), Arrays.asList("INTEGER", "REAL", "TEXT", "BLOB", null, null), "declared types"); eq(codeOf(srv, "SELEKT 1", new Object[0], FAR), 1, "syntax error: SQLITE_ERROR"); // one statement per call: SQLite compiles only the first, so a second is refused, not dropped diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java index bc4ee25852..7e3e3dcd42 100644 --- a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -16,9 +16,11 @@ private NativeBridge() {} public static native void setClientConnected(boolean connected); + public static native void setRowCapture(int maxRowsPerStatement, int maxValueBytes, int maxRowBytes); + public static native long openServer(byte[] path, boolean writable) throws DebugEngineException; - public static native Object[] query(long handle, String sql, Object[] args, long offset, int maxRows, int maxTextBytes, + public static native Object[] query(long handle, String sql, Object[] args, byte[][] names, long offset, int maxRows, int maxTextBytes, int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; From e73b3488860faae4f8b878dea194fd2fd003c7a1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 22:40:11 -0800 Subject: [PATCH 09/45] ADFA-7297 style: spotless reformat, no functional change spotlessKotlinCheck's two changes to DatabaseTools.kt: the named-args key chain on one call per line, and one blank line dropped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) 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 59551f962c..48061ecc78 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 @@ -871,7 +871,12 @@ class DatabaseTools internal constructor( } is JSONObject -> { - val names = raw.keys().asSequence().sorted().toList() + val names = + raw + .keys() + .asSequence() + .sorted() + .toList() names.forEach { if (it.isEmpty()) throw McpToolError("args has an empty name.") } Bind(names.map { value(raw.opt(it), "args.$it") }, names) } @@ -883,7 +888,6 @@ class DatabaseTools internal constructor( } } - /** Runs the idle check later; a test seam, the real one is [TimerIdleScheduler]. */ internal fun interface IdleScheduler { /** Runs [task] once after [delayMs]; the result cancels it. */ From e4501226ca4713354c38f8017eb81b9e2985b077 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 22:40:35 -0800 Subject: [PATCH 10/45] ADFA-7297 SQLite debugger: say which args keys may drop their prefix The args description said every key could be written without its prefix, but only :name, @name and $name match a bare name (key_matches): {"1": 5} for ?1 fails with "no value was given for parameter ?1". The text now says a ?NNN key keeps its ?, as the README already does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 48061ecc78..8bf356c1f2 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 @@ -399,8 +399,8 @@ class DatabaseTools internal constructor( .put( "description", "Values to bind: null, numbers or strings. An array binds by position (? and ?NNN, by number); an object binds " + - "by name (:name, @name, \$name, ?NNN), with keys written as in the SQL or without the prefix. Every " + - "parameter needs a value, and every key a parameter.", + "by name (:name, @name, \$name, ?NNN), with keys written as in the SQL. A key without a prefix, such as id, " + + "matches :id, @id and \$id; a ?NNN key keeps its ?. Every parameter needs a value, and every key a parameter.", ) private fun databaseSchema( From ffb3f184204c7f84583a36e27eea45a8baf8a61c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:50:49 +0000 Subject: [PATCH 11/45] ADFA-7297 sqlitedbg_jni.c: drop a stale comment above bind_value It described bind_args, which bind_positional and bind_value replaced. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c | 1 - 1 file changed, 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index bd7e613e07..9bcb98b117 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -227,7 +227,6 @@ static int progress_cb(void *p) { return 1; } -// Binds args[i] to parameter i + 1. Returns SQLITE_OK or a code with *message set. // Binds v (null, Long, Double, String or byte[]) to parameter idx (from 1). static int bind_value(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, int idx, jobject v, const char **message) { int rc; From e6485013cd01e06209cc5745a59dada0bbb28ace Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 23:14:51 -0800 Subject: [PATCH 12/45] ADFA-7297 style: test lines ktlint can format, no functional change spotlessKotlinCheck failed on DatabaseToolsTest.kt with one max-line-length error, reported at L1. ktlint joins kinds()'s expression body onto its signature line, and the joined line is 142 columns. Its other changes were then not applied either, so the file also needed ktlint's wrapping of the named-args call and of a four-call chain. kinds() now has a block body. Two long assertions are wrapped, and the row-values check reads values.get(c) once, before its when, so each branch stays on one line. Production code is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) 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 9a96068be4..d5b0f25511 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 @@ -1102,7 +1102,17 @@ class DatabaseToolsTest { got = a QueryResult(emptyList(), emptyList(), 0, false) } - ok("query", db().put("sql", "x").put("args", JSONObject().put(":b", "s").put("a", 1).put("\$c", JSONObject.NULL).put("?2", 2.5))) + ok( + "query", + db().put("sql", "x").put( + "args", + JSONObject() + .put(":b", "s") + .put("a", 1) + .put("\$c", JSONObject.NULL) + .put("?2", 2.5), + ), + ) val byName = engine.lastArgNames!!.zip(got).toMap() assertEquals(mapOf("a" to 1L, ":b" to "s", "\$c" to null, "?2" to 2.5), byName) ok("explain_query_plan", db().put("sql", "x").put("args", JSONObject().put("id", 7))) @@ -1136,9 +1146,20 @@ class DatabaseToolsTest { val types = r.getJSONArray("column_types") val declared = (0 until types.length()).map { if (types.isNull(it)) null else types.get(it) } assertEquals(listOf("INTEGER", "REAL", "TEXT", "BLOB", null), declared) - assertEquals(listOf("irtbn", "tnirb"), r.getJSONArray("storage_classes").let { a -> (0 until a.length()).map { a.getString(it) } }) - assertTrue("a REAL 2.0 reads as 2 in JSON, so only the storage class tells it from an INTEGER", r.toString().contains("[1,2,\"x\"")) - assertEquals("0fff", r.getJSONArray("rows").getJSONArray(0).getJSONObject(3).getString("hex")) + val classes = r.getJSONArray("storage_classes").let { a -> (0 until a.length()).map { a.getString(it) } } + assertEquals(listOf("irtbn", "tnirb"), classes) + assertTrue( + "a REAL 2.0 reads as 2 in JSON, so only the storage class tells it from an INTEGER", + r.toString().contains("[1,2,\"x\""), + ) + assertEquals( + "0fff", + r + .getJSONArray("rows") + .getJSONArray(0) + .getJSONObject(3) + .getString("hex"), + ) assertTrue(r.getJSONArray("rows").getJSONArray(0).isNull(4)) val description = tools.tools().single { it.name == "query" }.description assertTrue(description.contains("storage_classes") && description.contains("column_types") && description.contains("hex")) @@ -1263,11 +1284,12 @@ class DatabaseToolsTest { val values = json.getJSONArray("values") assertEquals(row.values.size, values.length()) row.values.forEachIndexed { c, v -> + val got = values.get(c) when (v) { null -> assertTrue(values.isNull(c)) is ByteArray -> assertEquals(DatabaseTools.hex(v), values.getJSONObject(c).getString("hex")) - is Double -> assertEquals(DatabaseTools.encodeValue(v), (values.get(c) as? Number)?.toDouble() ?: values.get(c)) - else -> assertEquals(DatabaseTools.encodeValue(v), values.get(c).let { if (it is Int) it.toLong() else it }) + is Double -> assertEquals(DatabaseTools.encodeValue(v), (got as? Number)?.toDouble() ?: got) + else -> assertEquals(DatabaseTools.encodeValue(v), if (got is Int) got.toLong() else got) } } val cut = json.getJSONArray("cut_values") @@ -1292,8 +1314,10 @@ class DatabaseToolsTest { assertEquals("", DatabaseTools.hex(ByteArray(0))) } - private fun kinds(r: JSONObject) = - r.getJSONArray("events").let { a -> (0 until a.length()).map { a.getJSONObject(it).getString("kind") } } + private fun kinds(r: JSONObject): List { + val events = r.getJSONArray("events") + return (0 until events.length()).map { events.getJSONObject(it).getString("kind") } + } private class FakeIdleScheduler : IdleScheduler { class Check( From f0c931f63f677f566f09e9660548ed566647259e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 10:16:54 -0800 Subject: [PATCH 13/45] ADFA-7323 SQLite debugger: name a misspelt named-args key in the error bind_named stopped at the first parameter with no value, before it looked for keys that matched no parameter. So args {"idx": 1} against "WHERE id = :id" failed with "no value was given for parameter :id", and the misspelt key was never named (seen on the J7, ADFA-7297 comment 41611). It now binds every parameter that has a value, then reports a key that matched nothing first, together with the parameter left without a value: "the statement has no parameter named idx, and no value was given for parameter :id". A parameter left out with no stray key, and a stray key with every parameter bound, keep their messages. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../src/main/cpp/sqlitedbg_jni.c | 32 +++++++++++++------ .../src/test/jni/JniQueryTest.java | 6 +++- 3 files changed, 28 insertions(+), 12 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index a3970161f3..bba23b9920 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -43,7 +43,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Values.** A NULL is JSON `null`. A BLOB is `{hex, bytes, truncated}`, lowercase hex (base64 before). An integer beyond 2^53 is a decimal string, and a NaN or infinite REAL is `"NaN"`, `"Infinity"` or `"-Infinity"`, as before. - **Storage classes.** JSON alone cannot tell a REAL 2.0 from an INTEGER 2 (org.json writes both as `2`), or a big integer from TEXT, so `query` returns `storage_classes`, one string per row with a letter per column: `i` INTEGER, `r` REAL, `t` TEXT, `b` BLOB, `n` NULL. Row events carry the same string. - **Declared types.** `query` returns `column_types`, each column's `sqlite3_column_decltype`, `null` for an expression. -- **Bound parameters (`.parameter`).** `query` and `explain_query_plan` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. +- **Bound parameters (`.parameter`).** `query` and `explain_query_plan` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL, and the error names the key even when a parameter is also left without a value; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. - **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. - **Limits.** `execute` (ADFA-7298, a separate PR) binds positional `args` only until the two PRs meet. Row recording is one switch for the process: the last `get_events` call decides it. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 9bcb98b117..b8ae3dec8f 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -304,7 +304,8 @@ static int key_matches(const char *param, const bind_key *key) { // Binds args by name: names[i] (UTF-8) names the parameter args[i] goes to. Every parameter must // get exactly one value and every name must be used, so a misspelt name fails instead of leaving a -// NULL. +// NULL. The error names a name that matches no parameter even when a parameter also has no value, +// since that name is most likely the parameter's, misspelt. static int bind_named(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, jobjectArray names, const char **message) { jsize n = (*env)->GetArrayLength(env, names); @@ -315,7 +316,8 @@ static int bind_named(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray a bind_key *keys = calloc(n ? (size_t)n : 1, sizeof *keys); if (!keys) return SQLITE_NOMEM; int rc = SQLITE_OK; - char msg[256]; + char msg[320]; + const char *missing = NULL; // the first parameter with no value; SQLite owns the string for (jsize i = 0; i < n && rc == SQLITE_OK; i++) { jbyteArray b = (jbyteArray)(*env)->GetObjectArrayElement(env, names, i); if (!b) { @@ -355,20 +357,30 @@ static int bind_named(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray a } if (rc != SQLITE_OK) break; if (found < 0) { - snprintf(msg, sizeof msg, "no value was given for parameter %.100s", param); - throw_engine(env, SQLITE_RANGE, msg); - rc = SQLITE_RANGE; - break; + if (!missing) missing = param; + continue; } keys[found].used = 1; jobject v = (*env)->GetObjectArrayElement(env, args, found); rc = bind_value(env, db, st, p, v, message); if (v) (*env)->DeleteLocalRef(env, v); } - for (jsize i = 0; i < n && rc == SQLITE_OK; i++) { - if (keys[i].used) continue; - int shown = keys[i].len > 100 ? 100 : (int)keys[i].len; - snprintf(msg, sizeof msg, "the statement has no parameter named %.*s", shown, keys[i].name); + jsize unused = -1; + for (jsize i = 0; i < n && unused < 0; i++) { + if (!keys[i].used) unused = i; + } + if (rc == SQLITE_OK && unused >= 0) { + int shown = keys[unused].len > 100 ? 100 : (int)keys[unused].len; + if (missing) { + snprintf(msg, sizeof msg, "the statement has no parameter named %.*s, and no value was given for parameter %.100s", + shown, keys[unused].name, missing); + } else { + snprintf(msg, sizeof msg, "the statement has no parameter named %.*s", shown, keys[unused].name); + } + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + } else if (rc == SQLITE_OK && missing) { + snprintf(msg, sizeof msg, "no value was given for parameter %.100s", missing); throw_engine(env, SQLITE_RANGE, msg); rc = SQLITE_RANGE; } diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index f2cf88d016..5bb75028fd 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -371,8 +371,12 @@ public static void main(String[] a) throws Exception { "25 parameter 2 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: an anonymous ?"); eq(namedRefusal(srv, "SELECT ?2", new Object[] {1L}, new String[] {"?2"}), "25 parameter 1 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: a gap in ?NNN"); - eq(namedRefusal(srv, "SELECT :a", new Object[] {1L}, new String[] {":b"}), "25 no value was given for parameter :a", + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L}, new String[] {":b"}), + "25 the statement has no parameter named :b, and no value was given for parameter :a", "named: a prefixed key matches only that prefix"); + eq(namedRefusal(srv, "SELECT id FROM t WHERE id = :id", new Object[] {1L}, new String[] {"idx"}), + "25 the statement has no parameter named idx, and no value was given for parameter :id", + "named: a misspelt key is named although a parameter also has no value"); // declared types: the column's, or null for an expression r = q(srv, "SELECT id, r, s, b, id + 1, NULL FROM t LIMIT 1"); From 346cd6c25aa60ecb8b84fe1c2a463940f098f5cf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:32:41 +0000 Subject: [PATCH 14/45] ADFA-7304 SQLite debugger: execute binds named args, as query does The item left for whichever of #2312 and #2319 merged second (41592): execute takes args as an array or an object, through the same prepare_bound, bind_named and argsSchema as query. - JNI execute gains names ([[B); bridge_execute passes them to prepare_bound. ServerConnection.execute gains argNames. - The execute tool's args schema is argsSchema(), and the merge's refusal of an object is gone. README updated. Tests: JNI binds INSERT ... VALUES(:id, @s) by name and refuses a misspelt key with SQLITE_RANGE, writing nothing; executeBindsAnObjectByName. test.sh 0 failures (JNI 488); JVM 132. Revert proof: execute ignoring names fails "each value went to its own parameter", "execute ran with a misspelt name" and "and the row is still there". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 4 ++-- .../src/main/cpp/sqlitedbg_jni.c | 7 +++--- .../sqlitedebugger/engine/DebugEngine.kt | 4 +++- .../sqlitedebugger/engine/NativeBridge.kt | 5 ++-- .../engine/NativeDebugEngine.kt | 11 ++++++++- .../sqlitedebugger/mcp/DatabaseTools.kt | 5 ++-- .../sqlitedebugger/engine/FakeDebugEngine.kt | 2 ++ .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 15 ++++++++++++ .../src/test/jni/JniQueryTest.java | 24 +++++++++++++++---- .../sqlitedebugger/engine/NativeBridge.java | 2 +- 10 files changed, 61 insertions(+), 18 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index fc941fc8cd..6600bf7d5a 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -43,9 +43,9 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Values.** A NULL is JSON `null`. A BLOB is `{hex, bytes, truncated}`, lowercase hex (base64 before). An integer beyond 2^53 is a decimal string, and a NaN or infinite REAL is `"NaN"`, `"Infinity"` or `"-Infinity"`, as before. - **Storage classes.** JSON alone cannot tell a REAL 2.0 from an INTEGER 2 (org.json writes both as `2`), or a big integer from TEXT, so `query` returns `storage_classes`, one string per row with a letter per column: `i` INTEGER, `r` REAL, `t` TEXT, `b` BLOB, `n` NULL. Row events carry the same string. - **Declared types.** `query` returns `column_types`, each column's `sqlite3_column_decltype`, `null` for an expression. -- **Bound parameters (`.parameter`).** `query` and `explain_query_plan` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL, and the error names the key even when a parameter is also left without a value; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. +- **Bound parameters (`.parameter`).** `query`, `explain_query_plan` and `execute` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL, and the error names the key even when a parameter is also left without a value; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. - **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. -- **Limits.** `execute` (ADFA-7298, a separate PR) binds positional `args` only until the two PRs meet. Row recording is one switch for the process: the last `get_events` call decides it. +- **Limits.** Row recording is one switch for the process: the last `get_events` call decides it. ## Decisions that shape it diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 10a45f6720..f6506a9ffc 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -662,7 +662,8 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring // when it inserted none: SQLite never assigns that rowid itself, so only a row inserted explicitly with // it reads as none (accepted), while 0 and other negative rowids are reported as they are. Inserts made // by a trigger do not count: SQLite restores the value when the trigger ends. -static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong deadline_ms) { +static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, + jobjectArray names, jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; sqlite3_stmt *st = NULL; @@ -675,7 +676,7 @@ static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the statement started"); goto done; } - if (!prepare_bound(env, db, sql, args, NULL, &st)) goto done; + if (!prepare_bound(env, db, sql, args, names, &st)) goto done; // query is the tool for a read; a statement that changes nothing here would only cost an approval. if (sqlite3_stmt_readonly(st)) { throw_engine(env, SQLITE_ERROR, "the statement does not write; run it with query"); @@ -762,7 +763,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"openServer", "([BZ)J", (void *)bridge_open_server}, {"setRowCapture", "(III)V", (void *)bridge_set_row_capture}, {"query", "(JLjava/lang/String;[Ljava/lang/Object;[[BJIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, - {"execute", "(JLjava/lang/String;[Ljava/lang/Object;J)[J", (void *)bridge_execute}, + {"execute", "(JLjava/lang/String;[Ljava/lang/Object;[[BJ)[J", (void *)bridge_execute}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index a4371541c1..4a06fa956c 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -85,7 +85,8 @@ interface ServerConnection : Closeable { ): QueryResult /** - * Runs [sql], one statement that writes, to its end in autocommit, with [args] bound as in [query]; rows it + * Runs [sql], one statement that writes, to its end in autocommit, with [args] bound as in [query] (by name when + * [argNames] is not null); rows it * returns (RETURNING) are dropped. Needs a connection opened with `writable = true`. The statement is * stopped and rolled back once [deadlineMillis] has passed, or after SQLITEDBG_SERVER_NON_WAL_MS * (1.5 s) whichever is first: it holds the write lock, which the app's own writes wait for. @@ -96,6 +97,7 @@ interface ServerConnection : Closeable { fun execute( sql: String, args: List, + argNames: List?, deadlineMillis: Long, ): ExecuteResult } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 6abed45642..be6ce5fd32 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -64,14 +64,15 @@ internal object NativeBridge { /** * `{changes, last_insert_rowid}` of one statement that writes (see [ServerConnection.execute]); the - * rowid is [Long.MIN_VALUE] when the statement inserted no row into a rowid table. Throws - * [DebugEngineException]. + * rowid is [Long.MIN_VALUE] when the statement inserted no row into a rowid table. [names] binds + * [args] as in [query]. Throws [DebugEngineException]. */ @JvmStatic external fun execute( handle: Long, sql: String, args: Array, + names: Array?, deadlineMillis: Long, ): LongArray diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index ab26ba7013..24d861db4a 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -135,10 +135,19 @@ class NativeDebugEngine : DebugEngine { override fun execute( sql: String, args: List, + argNames: List?, deadlineMillis: Long, ): ExecuteResult { check(handle != 0L) { "the connection is closed" } - val result = NativeBridge.execute(handle, sql, Array(args.size) { bindable(args[it]) }, deadlineMillis) + require(argNames == null || argNames.size == args.size) { "${argNames?.size} names for ${args.size} args" } + val result = + NativeBridge.execute( + handle, + sql, + Array(args.size) { bindable(args[it]) }, + argNames?.map { it.toByteArray(Charsets.UTF_8) }?.toTypedArray(), + deadlineMillis, + ) return ExecuteResult(changes = result[0], lastInsertRowid = result[1].takeIf { it != Long.MIN_VALUE }) } 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 dcb1595854..fef9d8e2e2 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 @@ -377,7 +377,7 @@ class DatabaseTools internal constructor( "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."), + "args" to argsSchema(), "acknowledge_room" to prop( "boolean", @@ -581,7 +581,6 @@ class DatabaseTools internal constructor( ): JSONObject { val sql = stringArg(args, "sql") val bind = bindArgs(args) - if (bind.names != null) throw McpToolError("args must be an array.") val acknowledge = when (val v = args.opt("acknowledge_room")) { null, JSONObject.NULL -> false @@ -595,7 +594,7 @@ class DatabaseTools internal constructor( } call.locked { roomAcknowledged += path } } - val result = withConnection(call, path, writable = true) { it.execute(sql, bind.values, call.deadline) } + val result = withConnection(call, path, writable = true) { it.execute(sql, bind.values, bind.names, call.deadline) } return JSONObject() .put("changes", encodeLong(result.changes)) .put("last_insert_rowid", result.lastInsertRowid?.let { encodeLong(it) } ?: JSONObject.NULL) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index a783fafe7a..34a11f07d2 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -165,9 +165,11 @@ class FakeDebugEngine( override fun execute( sql: String, args: List, + argNames: List?, deadlineMillis: Long, ): ExecuteResult { check(!closed) { "closed" } + lastArgNames = argNames if (!writable) throw DebugEngineException(DebugEngineException.SQLITE_AUTH, "not authorized") return executeAnswer(path, sql, args) } 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 778b673c25..2668d0f362 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 @@ -1409,6 +1409,21 @@ class DatabaseToolsTest { assertEquals(listOf("/data/a.db" to false, "/data/a.db" to true), engine.openedServerConnections) } + @Test fun executeBindsAnObjectByName() { + engine.appConnections += conn(1, "/data/a.db") + var got: List = emptyList() + engine.executeAnswer = { _, _, args -> + got = args + ExecuteResult(changes = 1, lastInsertRowid = null) + } + ok("execute", db().put("sql", "update t set a = :a where b = @b").put("args", JSONObject().put("a", "x").put("@b", 2))) + assertEquals(mapOf("a" to "x", "@b" to 2L), engine.lastArgNames!!.zip(got).toMap()) + ok("execute", db().put("sql", "update t set a = ?").put("args", JSONArray().put(1))) + assertEquals("an array binds by position", null, engine.lastArgNames) + val schema = tools.tools().single { it.name == "execute" }.inputSchema.getJSONObject("properties").getJSONObject("args") + assertEquals(listOf("array", "object"), schema.getJSONArray("type").let { a -> (0 until a.length()).map { a.getString(it) } }) + } + @Test fun executeReportsChangesPastTwoToTheFiftyThirdAsAString() { engine.appConnections += conn(1, "/data/a.db") engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1L shl 60, lastInsertRowid = null) } diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 4534d33ed9..87cdba0a94 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -127,20 +127,20 @@ static Set set(Long... v) { } static long exec(long h, String sql, Object... args) throws DebugEngineException { - long[] r = NativeBridge.execute(h, sql, args, FAR); + long[] r = NativeBridge.execute(h, sql, args, null, FAR); eq(r.length, 2, "execute returns {changes, last_insert_rowid}"); return r[0]; } /** The rowid execute reports, or null (Long.MIN_VALUE on the wire) when the statement inserted no row. */ static Long rowid(long h, String sql, Object... args) throws DebugEngineException { - long r = NativeBridge.execute(h, sql, args, FAR)[1]; + long r = NativeBridge.execute(h, sql, args, null, FAR)[1]; return r == Long.MIN_VALUE ? null : r; } static int execCode(long h, String sql, Object[] args, long deadline) { try { - NativeBridge.execute(h, sql, args, deadline); + NativeBridge.execute(h, sql, args, null, deadline); return 0; } catch (DebugEngineException e) { return e.sqliteCode; @@ -150,7 +150,7 @@ static int execCode(long h, String sql, Object[] args, long deadline) { /** "code message" of the refusal, or null when the statement ran. */ static String execRefusal(long h, String sql) { try { - NativeBridge.execute(h, sql, new Object[0], FAR); + NativeBridge.execute(h, sql, new Object[0], null, FAR); return null; } catch (DebugEngineException e) { return e.sqliteCode + " " + e.getMessage(); @@ -167,6 +167,20 @@ static void execute(Path dir, String path, long app) throws Exception { eq(exec(w, "UPDATE t SET s = ? WHERE id >= ?", "z", 6001L), 2L, "update 2: changes 2"); eq(exec(w, "DELETE FROM t WHERE id = :id", 6001L), 1L, "delete 1, named parameter: changes 1"); eq(exec(w, "DELETE FROM t WHERE id = -1"), 0L, "delete none: changes 0"); + // by name, as query binds (ADFA-7304: P2-2 and P2-3 met) + byte[][] names = {"s".getBytes(StandardCharsets.UTF_8), ":id".getBytes(StandardCharsets.UTF_8)}; + eq(NativeBridge.execute(w, "INSERT INTO t(id, s) VALUES(:id, @s)", new Object[] {"n", 6004L}, names, FAR)[0], 1L, + "execute binds by name: changes 1"); + eq(q(r, "SELECT count(*) FROM t WHERE id = 6004 AND s = 'n'").rows.get(0)[0], 1L, "each value went to its own parameter"); + try { + NativeBridge.execute(w, "DELETE FROM t WHERE id = :id", new Object[] {6004L}, new byte[][] {"idd".getBytes(StandardCharsets.UTF_8)}, + FAR); + check(false, "execute ran with a misspelt name"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 25, "execute: a misspelt name is SQLITE_RANGE, nothing run"); + } + eq(q(r, "SELECT count(*) FROM t WHERE id = 6004").rows.get(0)[0], 1L, "and the row is still there"); + Helper.exec(app, "DELETE FROM t WHERE id = 6004 OR s = '6004'"); // a statement that changes no row reports 0, not the previous write's count (sqlite3_changes64 keeps it) eq(exec(w, "UPDATE t SET s = 'y' WHERE id = 6002"), 1L, "update 1"); eq(exec(w, "CREATE TABLE ex(a)"), 0L, "CREATE TABLE: changes 0, not the update's 1"); @@ -275,7 +289,7 @@ static void execute(Path dir, String path, long app) throws Exception { try { // far more work than 1.5 s: a cross join of t four times over, inserted NativeBridge.execute(sw, "INSERT INTO t SELECT a.id FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0 " - + "UNION ALL SELECT -1", new Object[0], System.currentTimeMillis() + 8000); + + "UNION ALL SELECT -1", new Object[0], null, System.currentTimeMillis() + 8000); } catch (DebugEngineException e) { ran.code = e.sqliteCode; ran.message = e.getMessage(); diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java index c17d8a2331..fdfdc35a2d 100644 --- a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -24,7 +24,7 @@ public static native Object[] query(long handle, String sql, Object[] args, byte int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; - public static native long[] execute(long handle, String sql, Object[] args, long deadlineMillis) throws DebugEngineException; + public static native long[] execute(long handle, String sql, Object[] args, byte[][] names, long deadlineMillis) throws DebugEngineException; public static native void close(long handle); } From 6f5a8a4da75a11451fcaa695743f13b7f6e14abc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:47:21 +0000 Subject: [PATCH 15/45] ADFA-7304 SQLite debugger: execute returns RETURNING rows within query's limits execute ran a statement's RETURNING rows to the end and dropped them. Now they come back in query's format (P2-2's: column types, storage classes, hex BLOBs) within the same limits: max_rows (default 100, at most 1000), the 4 MiB budget with the first row whole, cut cells listed, has_more. No offset: paging would run the write again. From the experiments (41621): SQLite makes every change and buffers every returned row in the first sqlite3_step, so - a statement stopped at a limit is reset, which commits all of it, and changes counts every row written; a failed commit at the reset is the call's error ("could not be committed, and nothing it changed was kept"; the rollback backstop ends the open transaction); - a statement that fails at any step, even while its rows come back, is rolled back whole, so execute returns the error and no rows. - C: bridge_query's row loop moves into read_rows, which both use. bridge_execute takes query's limits and returns [columns, rows, counts, decltypes, {changes, last_insert_rowid}]. - Kotlin: ServerConnection.execute takes QueryLimits; ExecuteResult has rows. The tool gains max_rows and returns the rows only for a statement with RETURNING. Description and README updated. Limit (README): if the JVM fails to allocate a row mid-read, the unfinished statement is finalized, which commits it while the call reports the error. Tests: JNI returningCaps: - INSERT RETURNING id; - UPDATE past a 3-row cap (3 rows, has_more, changes 50, all 50 updated); - the byte budget (first row only); - a wide row cut; - DELETE RETURNING cut short (all deleted); - a failed commit at the reset (SQLITE_BUSY, nothing kept); - the 1.5 s limit striking while 400,000 rows come back (first step about 0.5 s; SQLITE_INTERRUPT, nothing kept). DatabaseToolsTest executeReturnsReturningRowsAsQueryDoes. test.sh 0 failures (JNI 564); JVM 133. Revert proofs: - returning rows on error fails "every row of a write past the time limit came back"; - ignoring the reset's rc fails "a write whose commit failed returned rows". Not run here: Gradle, spotlessCheck, a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 4 +- .../src/main/cpp/sqlitedbg_jni.c | 180 +++++++++++------- .../sqlitedebugger/engine/DebugEngine.kt | 17 +- .../sqlitedebugger/engine/NativeBridge.kt | 12 +- .../engine/NativeDebugEngine.kt | 56 ++++-- .../sqlitedebugger/mcp/DatabaseTools.kt | 25 ++- .../sqlitedebugger/engine/FakeDebugEngine.kt | 6 + .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 43 ++++- .../src/test/jni/JniQueryTest.java | 128 ++++++++++++- .../sqlitedebugger/engine/NativeBridge.java | 3 +- 10 files changed, 359 insertions(+), 115 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 6600bf7d5a..6a58518ef6 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -52,7 +52,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **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 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. +- **`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` come back as `query`'s do, within the same limits (ADFA-7304): at most `max_rows`, the 4 MiB budget with the first row whole, cut cells listed, and `has_more`. There is no `offset`, since paging would run the write again. SQLite makes every change, and buffers every returned row, in the first `sqlite3_step` (ADFA-7304 comment 41621). So a statement stopped at a limit is reset, which commits all of it, `changes` counts every row written, and a failed commit at the reset is the call's error. A statement that fails at any step, even while its rows come back, is rolled back whole by SQLite, so `execute` returns only the error and no rows. Limit: if the JVM fails to allocate a row mid-read, the statement is finalized unfinished, which commits it while the call reports the error. 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. @@ -68,7 +68,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, and the 1.5 s cap on a write in DELETE and WAL mode while the app writes. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, the 1.5 s cap on a write in DELETE and WAL mode while the app writes, binding by name, and RETURNING rows within the limits, including a failed commit at the reset and the time limit striking while rows come back. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index f6506a9ffc..3da39a9e5d 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -512,41 +512,19 @@ static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, } } -static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, - jobjectArray names, jlong offset, - jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { - (void)cls; - sqlite3 *db = (sqlite3 *)(intptr_t)handle; - sqlite3_stmt *st = NULL; +// Steps st, skipping offset rows, and collects at most max_rows rows within max_total bytes of cells (the +// first row always goes in, so a page makes progress), each TEXT and BLOB cut at max_text and max_blob. +// Returns [columns, rows, counts, decltypes] as NativeBridge.query describes, with *rc the last +// sqlite3_step result and *has_more set when rows were left unread. When *has_more is 0 and *rc is not +// SQLITE_DONE the statement failed: the caller reports it and drops the result. NULL with an exception +// pending when a JNI allocation failed. +static jobjectArray read_rows(JNIEnv *env, sqlite3_stmt *st, jlong offset, jint max_rows, jint max_text, jint max_blob, + jint max_total, int *rc, int *has_more) { jobjectArray result = NULL; jlong *cut_cells = NULL; // row * columns + column of each cut cell size_t cut_n = 0, cut_cap = 0; - deadline dl = {(int64_t)deadline_ms, 0, 0}; - int handler_set = 0; - int rc; - - if (now_ms() >= dl.at_ms) { - throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the query started"); - goto done; - } - if (!prepare_bound(env, db, sql, args, names, &st)) goto done; - - // Every server tool runs its statements here, so this is the one place that bounds a read on a database - // that is not in WAL mode: it holds a SHARED lock until the statement ends, and the app's commit gives - // up after requery's 2500 ms busy timeout (see SQLITEDBG_SERVER_NON_WAL_MS). The mode is read per call. - if (now_ms() + SQLITEDBG_SERVER_NON_WAL_MS < dl.at_ms && !is_wal_mode(db)) { - // counted from here, after the mode check, which can wait on the app's lock - int64_t cap_at = now_ms() + SQLITEDBG_SERVER_NON_WAL_MS; - if (cap_at < dl.at_ms) { - dl.at_ms = cap_at; - dl.capped = 1; - } - } - - // SQLite checks the handler every 1000 virtual machine steps and stops the statement when it - // returns non-zero; it is cleared before this returns, so it never outlives `dl`. - sqlite3_progress_handler(db, 1000, progress_cb, &dl); - handler_set = 1; + *rc = SQLITE_OK; + *has_more = 0; int ncols = sqlite3_column_count(st); jobjectArray columns = (*env)->NewObjectArray(env, ncols, g_string, NULL); @@ -569,16 +547,16 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring } } - int has_more = 0, row_count = 0; + int row_count = 0; int64_t total = 0; jlong skipped = 0; - while ((rc = sqlite3_step(st)) == SQLITE_ROW) { + while ((*rc = sqlite3_step(st)) == SQLITE_ROW) { if (skipped < offset) { skipped++; continue; } if (row_count >= max_rows) { - has_more = 1; + *has_more = 1; break; } jobjectArray row = (*env)->NewObjectArray(env, ncols, g_object, NULL); @@ -607,12 +585,11 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring (*env)->DeleteLocalRef(env, cell); } } - // The total bounds the host app's heap. The first row always goes in, so a page makes - // progress; one row is bounded by the per-cell limits. + // The total bounds the host app's heap. One row is bounded by the per-cell limits. if (row_count > 0 && total + row_bytes > max_total) { (*env)->DeleteLocalRef(env, row); cut_n = cut_before; - has_more = 1; + *has_more = 1; break; } total += row_bytes; @@ -621,24 +598,12 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring if ((*env)->ExceptionCheck(env)) goto done; row_count++; } - if (!has_more && rc != SQLITE_DONE) { - if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { - char msg[256]; - snprintf(msg, sizeof msg, - "the statement was stopped after %.1f s: this database is not in WAL mode, so a longer read would " - "block the app's own writes. Use a narrower query or a LIMIT; a database in WAL mode has no such limit", - SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); - throw_engine(env, SQLITE_INTERRUPT, msg); - } else if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the query ran past its time limit"); - else throw_engine(env, rc, sqlite3_errmsg(db)); - goto done; - } // {cut cell count, hasMore, then the index of each cut cell} jlongArray counts = (*env)->NewLongArray(env, (jsize)(2 + cut_n)); result = counts ? (*env)->NewObjectArray(env, 4, g_object, NULL) : NULL; if (!result) goto done; - jlong head[2] = {(jlong)cut_n, has_more}; + jlong head[2] = {(jlong)cut_n, *has_more}; (*env)->SetLongArrayRegion(env, counts, 0, 2, head); if (cut_n) (*env)->SetLongArrayRegion(env, counts, 2, (jsize)cut_n, cut_cells); (*env)->SetObjectArrayElement(env, result, 0, columns); @@ -646,31 +611,89 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring (*env)->SetObjectArrayElement(env, result, 2, counts); (*env)->SetObjectArrayElement(env, result, 3, decltypes); +done: + free(cut_cells); + return result; +} + +static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, + jobjectArray names, jlong offset, + jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { + (void)cls; + sqlite3 *db = (sqlite3 *)(intptr_t)handle; + sqlite3_stmt *st = NULL; + jobjectArray result = NULL; + deadline dl = {(int64_t)deadline_ms, 0, 0}; + int handler_set = 0; + int rc, has_more; + + if (now_ms() >= dl.at_ms) { + throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the query started"); + goto done; + } + if (!prepare_bound(env, db, sql, args, names, &st)) goto done; + + // Every server tool runs its statements here, so this is the one place that bounds a read on a database + // that is not in WAL mode: it holds a SHARED lock until the statement ends, and the app's commit gives + // up after requery's 2500 ms busy timeout (see SQLITEDBG_SERVER_NON_WAL_MS). The mode is read per call. + if (now_ms() + SQLITEDBG_SERVER_NON_WAL_MS < dl.at_ms && !is_wal_mode(db)) { + // counted from here, after the mode check, which can wait on the app's lock + int64_t cap_at = now_ms() + SQLITEDBG_SERVER_NON_WAL_MS; + if (cap_at < dl.at_ms) { + dl.at_ms = cap_at; + dl.capped = 1; + } + } + + // SQLite checks the handler every 1000 virtual machine steps and stops the statement when it + // returns non-zero; it is cleared before this returns, so it never outlives `dl`. + sqlite3_progress_handler(db, 1000, progress_cb, &dl); + handler_set = 1; + + result = read_rows(env, st, offset, max_rows, max_text, max_blob, max_total, &rc, &has_more); + if (result && !has_more && rc != SQLITE_DONE) { + result = NULL; + if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { + char msg[256]; + snprintf(msg, sizeof msg, + "the statement was stopped after %.1f s: this database is not in WAL mode, so a longer read would " + "block the app's own writes. Use a narrower query or a LIMIT; a database in WAL mode has no such limit", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the query ran past its time limit"); + else throw_engine(env, rc, sqlite3_errmsg(db)); + } + done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); sqlite3_finalize(st); - free(cut_cells); if (!end_transaction_backstop(env, db)) result = NULL; return result; } -// Runs one statement that writes, to its end, on a writable server connection (ADFA-7298). Rows it -// returns (RETURNING) are read and dropped. Returns {changes, last_insert_rowid}: changes is the rows the -// statement itself inserted, updated or deleted (sqlite3_changes64), or 0 when it changed none, such as -// CREATE TABLE, which leaves sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). -// last_insert_rowid is the rowid of the last row the statement inserted into a rowid table, and INT64_MIN -// when it inserted none: SQLite never assigns that rowid itself, so only a row inserted explicitly with -// it reads as none (accepted), while 0 and other negative rowids are reported as they are. Inserts made -// by a trigger do not count: SQLite restores the value when the trigger ends. -static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, - jobjectArray names, jlong deadline_ms) { +// Runs one statement that writes on a writable server connection (ADFA-7298), and returns the rows it +// returns (RETURNING) as read_rows does, within the same limits (ADFA-7304): [columns, rows, counts, +// decltypes, {changes, last_insert_rowid}]. changes is the rows the statement itself inserted, updated or +// deleted (sqlite3_changes64), or 0 when it changed none, such as CREATE TABLE, which leaves +// sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). last_insert_rowid is the rowid +// of the last row the statement inserted into a rowid table, and INT64_MIN when it inserted none: SQLite +// never assigns that rowid itself, so only a row inserted explicitly with it reads as none (accepted), while +// 0 and other negative rowids are reported as they are. Inserts made by a trigger do not count: SQLite +// restores the value when the trigger ends. +// SQLite makes every change, and buffers every RETURNING row, in the first sqlite3_step (ADFA-7304 comment +// 41621). So a statement stopped at the row limit is reset, which commits all its changes and leaves +// changes counting every row written. A statement that fails at any step, even after rows came back, is +// rolled back whole, so its rows are dropped and only the error is returned. +static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, + jobjectArray names, jint max_rows, jint max_text, jint max_blob, jint max_total, + jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; sqlite3_stmt *st = NULL; - jlongArray result = NULL; + jobjectArray result = NULL; deadline dl = {(int64_t)deadline_ms, 0, 0}; int handler_set = 0; - int rc; + int rc, has_more; if (now_ms() >= dl.at_ms) { throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the statement started"); @@ -697,8 +720,19 @@ static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring // the connection is cached and keeps its value across statements: without this an UPDATE would // report the rowid of an earlier execute's INSERT. Not 0, SQLite's own "none": 0 is a valid rowid. sqlite3_set_last_insert_rowid(db, INT64_MIN); - while ((rc = sqlite3_step(st)) == SQLITE_ROW) {} - if (rc != SQLITE_DONE) { + jobjectArray rows = read_rows(env, st, 0, max_rows, max_text, max_blob, max_total, &rc, &has_more); + if (!rows) goto done; + if (has_more) { + // Commits every change, not only those of the rows read; the commit itself can fail. + rc = sqlite3_reset(st); + if (rc != SQLITE_OK) { + char msg[256]; + snprintf(msg, sizeof msg, "the statement could not be committed, and nothing it changed was kept: %s", + sqlite3_errmsg(db)); + throw_engine(env, rc, msg); + goto done; + } + } else if (rc != SQLITE_DONE) { if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { char msg[256]; snprintf(msg, sizeof msg, @@ -713,8 +747,16 @@ static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring jlong out[2]; out[0] = sqlite3_total_changes64(db) == total_before ? 0 : (jlong)sqlite3_changes64(db); out[1] = (jlong)sqlite3_last_insert_rowid(db); - result = (*env)->NewLongArray(env, 2); - if (result) (*env)->SetLongArrayRegion(env, result, 0, 2, out); + jlongArray counts = (*env)->NewLongArray(env, 2); + result = counts ? (*env)->NewObjectArray(env, 5, g_object, NULL) : NULL; + if (!result) goto done; + (*env)->SetLongArrayRegion(env, counts, 0, 2, out); + for (int i = 0; i < 4; i++) { + jobject part = (*env)->GetObjectArrayElement(env, rows, i); + (*env)->SetObjectArrayElement(env, result, i, part); + (*env)->DeleteLocalRef(env, part); + } + (*env)->SetObjectArrayElement(env, result, 4, counts); done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); @@ -763,7 +805,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"openServer", "([BZ)J", (void *)bridge_open_server}, {"setRowCapture", "(III)V", (void *)bridge_set_row_capture}, {"query", "(JLjava/lang/String;[Ljava/lang/Object;[[BJIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, - {"execute", "(JLjava/lang/String;[Ljava/lang/Object;[[BJ)[J", (void *)bridge_execute}, + {"execute", "(JLjava/lang/String;[Ljava/lang/Object;[[BIIIIJ)[Ljava/lang/Object;", (void *)bridge_execute}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 4a06fa956c..774e5d1d1f 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -85,19 +85,22 @@ interface ServerConnection : Closeable { ): QueryResult /** - * Runs [sql], one statement that writes, to its end in autocommit, with [args] bound as in [query] (by name when - * [argNames] is not null); rows it - * returns (RETURNING) are dropped. Needs a connection opened with `writable = true`. The statement is - * stopped and rolled back once [deadlineMillis] has passed, or after SQLITEDBG_SERVER_NON_WAL_MS - * (1.5 s) whichever is first: it holds the write lock, which the app's own writes wait for. + * Runs [sql], one statement that writes, in autocommit, with [args] bound as in [query] (by name when + * [argNames] is not null), and returns the rows it returns (RETURNING) within [limits] as [query] does, + * from the first row, with no offset: paging would run the write again. Every change is committed + * however many rows are returned ([ExecuteResult.rows] has hasMore). Needs a connection opened with + * `writable = true`. The statement is stopped and rolled back once [deadlineMillis] has passed, or after + * SQLITEDBG_SERVER_NON_WAL_MS (1.5 s) whichever is first: it holds the write lock, which the app's own + * writes wait for. A statement that fails, even after rows came back, keeps nothing and returns no rows. * * @throws DebugEngineException as [query] does, and for a statement that does not write - * (`sqlite3_stmt_readonly`), a transaction statement, or a refused PRAGMA. + * (`sqlite3_stmt_readonly`), a transaction statement, a refused PRAGMA, or a failed commit. */ fun execute( sql: String, args: List, argNames: List?, + limits: QueryLimits, deadlineMillis: Long, ): ExecuteResult } @@ -115,6 +118,8 @@ data class ExecuteResult( * assigns itself, reads as null; 0 and other negative rowids are reported. */ val lastInsertRowid: Long?, + /** The rows from RETURNING, as [ServerConnection.query] returns rows; no columns without RETURNING. */ + val rows: QueryResult = QueryResult(emptyList(), emptyList(), 0, false), ) data class AppConnection( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index be6ce5fd32..1ea538bb4b 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -63,9 +63,9 @@ internal object NativeBridge { ): Array /** - * `{changes, last_insert_rowid}` of one statement that writes (see [ServerConnection.execute]); the - * rowid is [Long.MIN_VALUE] when the statement inserted no row into a rowid table. [names] binds - * [args] as in [query]. Throws [DebugEngineException]. + * One statement that writes (see [ServerConnection.execute]): its RETURNING rows as [query] returns + * them, then `{changes, last_insert_rowid}`; the rowid is [Long.MIN_VALUE] when the statement inserted + * no row into a rowid table. [names] binds [args] as in [query]. Throws [DebugEngineException]. */ @JvmStatic external fun execute( @@ -73,8 +73,12 @@ internal object NativeBridge { sql: String, args: Array, names: Array?, + maxRows: Int, + maxTextBytes: Int, + maxBlobBytes: Int, + maxTotalBytes: Int, deadlineMillis: Long, - ): LongArray + ): Array @JvmStatic external fun close(handle: Long) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index 24d861db4a..df346eb2a4 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -112,43 +112,61 @@ class NativeDebugEngine : DebugEngine { deadlineMillis, ) - @Suppress("UNCHECKED_CAST") - val columns = (result[0] as Array).asList() - - @Suppress("UNCHECKED_CAST") - val rows = (result[1] as List>).map { it.asList() } - val counts = result[2] as LongArray - val cut = HashSet() - for (i in 2 until counts.size) cut += counts[i] - @Suppress("UNCHECKED_CAST") - val declaredTypes = (result[3] as Array).asList() - return QueryResult( - columns, - rows, - truncatedCells = counts[0].toInt(), - hasMore = counts[1] != 0L, - truncatedCellIndexes = cut, - declaredTypes = declaredTypes, - ) + return rowsOf(result) } override fun execute( sql: String, args: List, argNames: List?, + limits: QueryLimits, deadlineMillis: Long, ): ExecuteResult { check(handle != 0L) { "the connection is closed" } require(argNames == null || argNames.size == args.size) { "${argNames?.size} names for ${args.size} args" } + require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0 && limits.maxTotalBytes > 0) { + "bad limits $limits" + } val result = NativeBridge.execute( handle, sql, Array(args.size) { bindable(args[it]) }, argNames?.map { it.toByteArray(Charsets.UTF_8) }?.toTypedArray(), + limits.maxRows, + limits.maxTextBytes, + limits.maxBlobBytes, + limits.maxTotalBytes, deadlineMillis, ) - return ExecuteResult(changes = result[0], lastInsertRowid = result[1].takeIf { it != Long.MIN_VALUE }) + val counts = result[4] as LongArray + return ExecuteResult( + changes = counts[0], + lastInsertRowid = counts[1].takeIf { it != Long.MIN_VALUE }, + rows = rowsOf(result), + ) + } + + /** The first four elements of what [NativeBridge.query] and [NativeBridge.execute] return. */ + private fun rowsOf(result: Array): QueryResult { + @Suppress("UNCHECKED_CAST") + val columns = (result[0] as Array).asList() + + @Suppress("UNCHECKED_CAST") + val rows = (result[1] as List>).map { it.asList() } + val counts = result[2] as LongArray + val cut = HashSet() + for (i in 2 until counts.size) cut += counts[i] + @Suppress("UNCHECKED_CAST") + val declaredTypes = (result[3] as Array).asList() + return QueryResult( + columns, + rows, + truncatedCells = counts[0].toInt(), + hasMore = counts[1] != 0L, + truncatedCellIndexes = cut, + declaredTypes = declaredTypes, + ) } override fun close() { 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 fef9d8e2e2..a5971b2c6a 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 @@ -367,7 +367,13 @@ class DatabaseTools internal constructor( "the rowid of the last row it inserted into a rowid table, or null when it inserted none (an UPDATE, " + "a WITHOUT ROWID table, an ignored row; rows inserted by triggers do not count). One statement per call; " + "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused, so several statements cannot be made atomic. " + - "A statement that does not write is refused: use query. Rows from RETURNING are not returned. " + + "A statement that does not write is refused: use query. Rows from RETURNING come back as query returns " + + "them (columns, column_types, rows, storage_classes, has_more, truncated_cells, truncated_cell_indexes), at " + + "most max_rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS) and about " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cells. Every change is committed whatever is returned: " + + "has_more true means RETURNING produced more rows than came back, and they cannot be paged (that " + + "would write again); read them with query. SQLite makes every change before the first row comes back, " + + "so the time limit covers the whole write. A statement that fails returns no rows and keeps nothing. " + "Foreign keys are enforced here whatever the app's own connections do: ON DELETE and ON UPDATE actions " + "run, and a write the app could make with foreign keys off may be refused. " + "Also refused: ATTACH, every PRAGMA that takes a value except user_version (no setting can be " + @@ -378,6 +384,7 @@ class DatabaseTools internal constructor( databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to argsSchema(), + "max_rows" to prop("integer", "RETURNING rows to return. Default $DEFAULT_MAX_ROWS, at most $MAX_ROWS."), "acknowledge_room" to prop( "boolean", @@ -581,6 +588,7 @@ class DatabaseTools internal constructor( ): JSONObject { val sql = stringArg(args, "sql") val bind = bindArgs(args) + val maxRows = intArg(args, "max_rows", DEFAULT_MAX_ROWS.toLong(), 1, MAX_ROWS.toLong()).toInt() val acknowledge = when (val v = args.opt("acknowledge_room")) { null, JSONObject.NULL -> false @@ -594,8 +602,19 @@ class DatabaseTools internal constructor( } call.locked { roomAcknowledged += path } } - val result = withConnection(call, path, writable = true) { it.execute(sql, bind.values, bind.names, call.deadline) } - return JSONObject() + val limits = QueryLimits(maxRows, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) + val result = withConnection(call, path, writable = true) { it.execute(sql, bind.values, bind.names, limits, call.deadline) } + // Rows only for a statement with RETURNING; there is no offset to page with. + val out = + if (result.rows.columns.isEmpty()) { + JSONObject() + } else { + encodeResult(result.rows, 0).also { + it.remove("offset") + it.remove("next_offset") + } + } + return out .put("changes", encodeLong(result.changes)) .put("last_insert_rowid", result.lastInsertRowid?.let { encodeLong(it) } ?: JSONObject.NULL) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index 34a11f07d2..0cf3aa8ca3 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -34,6 +34,10 @@ class FakeDebugEngine( /** Each setRowCapture call, in order: rows per statement, value bytes, row bytes. */ val rowCaptureCalls = mutableListOf>() + /** The limits of the last execute. */ + var lastExecuteLimits: QueryLimits? = null + private set + /** The argNames of the last query: null when its args were bound by position. */ var lastArgNames: List? = null private set @@ -166,10 +170,12 @@ class FakeDebugEngine( sql: String, args: List, argNames: List?, + limits: QueryLimits, deadlineMillis: Long, ): ExecuteResult { check(!closed) { "closed" } lastArgNames = argNames + lastExecuteLimits = limits if (!writable) throw DebugEngineException(DebugEngineException.SQLITE_AUTH, "not authorized") return executeAnswer(path, sql, args) } 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 2668d0f362..13447642b8 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 @@ -1424,6 +1424,45 @@ class DatabaseToolsTest { assertEquals(listOf("array", "object"), schema.getJSONArray("type").let { a -> (0 until a.length()).map { a.getString(it) } }) } + @Test fun executeReturnsReturningRowsAsQueryDoes() { + engine.appConnections += conn(1, "/data/a.db") + engine.executeAnswer = { _, _, _ -> + ExecuteResult( + changes = 50, + lastInsertRowid = null, + rows = + QueryResult( + listOf("id", "b"), + listOf(listOf(1L, byteArrayOf(1)), listOf(2L, null)), + 1, + true, + setOf(1L), + listOf("INTEGER", "BLOB"), + ), + ) + } + val r = ok("execute", db().put("sql", "update t set v = 1 returning id, b").put("max_rows", 2)) + assertEquals(50, r.getInt("changes")) + assertEquals(listOf("id", "b"), r.getJSONArray("columns").let { a -> (0 until a.length()).map { a.getString(it) } }) + assertEquals("INTEGER", r.getJSONArray("column_types").getString(0)) + assertEquals(2, r.getInt("row_count")) + assertEquals("01", r.getJSONArray("rows").getJSONArray(0).getJSONObject(1).getString("hex")) + assertEquals("ib", r.getJSONArray("storage_classes").getString(0)) + assertTrue(r.getBoolean("has_more")) + assertEquals(1, r.getInt("truncated_cells")) + assertEquals(0, r.getJSONArray("truncated_cell_indexes").getJSONArray(0).getInt(0)) + assertFalse("no paging: running the write again would write again", r.has("offset") || r.has("next_offset")) + assertEquals(2, engine.lastExecuteLimits!!.maxRows) + assertEquals(DatabaseTools.MAX_TOTAL_BYTES, engine.lastExecuteLimits!!.maxTotalBytes) + + engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1, lastInsertRowid = 9) } + val plain = ok("execute", db().put("sql", "insert into t values (1)")) + assertFalse("no RETURNING: no rows", plain.has("rows") || plain.has("columns")) + assertEquals(DatabaseTools.DEFAULT_MAX_ROWS, engine.lastExecuteLimits!!.maxRows) + assertTrue(runTool(tools, "execute", db().put("sql", "x").put("max_rows", 0)).getBoolean("isError")) + assertTrue(runTool(tools, "execute", db().put("sql", "x").put("max_rows", DatabaseTools.MAX_ROWS + 1)).getBoolean("isError")) + } + @Test fun executeReportsChangesPastTwoToTheFiftyThirdAsAString() { engine.appConnections += conn(1, "/data/a.db") engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1L shl 60, lastInsertRowid = null) } @@ -1479,7 +1518,9 @@ class DatabaseToolsTest { "committed at once and cannot be undone", "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused", "does not write is refused: use query", - "RETURNING are not returned", + "Rows from RETURNING come back as query returns them", + "cannot be paged", + "returns no rows and keeps nothing", "stopped and rolled back after 1.5 s", "in every journal mode", "may stay stale", diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 87cdba0a94..4b03408c19 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -126,21 +126,45 @@ static Set set(Long... v) { return new HashSet<>(Arrays.asList(v)); } + /** execute with query's limits and no names: [columns, rows, counts, decltypes, {changes, last_insert_rowid}]. */ + static Object[] run(long h, String sql, byte[][] names, int maxRows, int maxText, int maxBlob, int maxTotal, long deadline, + Object... args) throws DebugEngineException { + Object[] r = NativeBridge.execute(h, sql, args, names, maxRows, maxText, maxBlob, maxTotal, deadline); + eq(r.length, 5, "execute returns the rows, then {changes, last_insert_rowid}"); + return r; + } + + static long[] counts(Object[] r) { + return (long[]) r[4]; + } + + /** What execute returned as rows, unpacked as query's are. */ + @SuppressWarnings("unchecked") + static Result rowsOf(Object[] r) { + Result out = new Result(); + out.columns = (String[]) r[0]; + out.rows = (List) r[1]; + long[] c = (long[]) r[2]; + out.truncated = c[0]; + out.hasMore = c[1] != 0; + for (int i = 2; i < c.length; i++) out.cut.add(c[i]); + out.declaredTypes = (String[]) r[3]; + return out; + } + static long exec(long h, String sql, Object... args) throws DebugEngineException { - long[] r = NativeBridge.execute(h, sql, args, null, FAR); - eq(r.length, 2, "execute returns {changes, last_insert_rowid}"); - return r[0]; + return counts(run(h, sql, null, 1000, 4096, 1024, MAX, FAR, args))[0]; } /** The rowid execute reports, or null (Long.MIN_VALUE on the wire) when the statement inserted no row. */ static Long rowid(long h, String sql, Object... args) throws DebugEngineException { - long r = NativeBridge.execute(h, sql, args, null, FAR)[1]; + long r = counts(run(h, sql, null, 1000, 4096, 1024, MAX, FAR, args))[1]; return r == Long.MIN_VALUE ? null : r; } static int execCode(long h, String sql, Object[] args, long deadline) { try { - NativeBridge.execute(h, sql, args, null, deadline); + NativeBridge.execute(h, sql, args, null, 1000, 4096, 1024, MAX, deadline); return 0; } catch (DebugEngineException e) { return e.sqliteCode; @@ -150,13 +174,87 @@ static int execCode(long h, String sql, Object[] args, long deadline) { /** "code message" of the refusal, or null when the statement ran. */ static String execRefusal(long h, String sql) { try { - NativeBridge.execute(h, sql, new Object[0], null, FAR); + NativeBridge.execute(h, sql, new Object[0], null, 1000, 4096, 1024, MAX, FAR); return null; } catch (DebugEngineException e) { return e.sqliteCode + " " + e.getMessage(); } } + /** + * ADFA-7304: RETURNING rows within query's limits. SQLite makes every change in the first step, so a + * statement stopped at a limit is reset, which commits all of it (comment 41621). + */ + static void returningCaps(long w, long r, long app) throws Exception { + eq(exec(w, "CREATE TABLE rt(id INTEGER PRIMARY KEY, v INTEGER, s TEXT, b BLOB)"), 0L, "create rt"); + eq(exec(w, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 50) " + + "INSERT INTO rt SELECT x, 0, printf('%.20c', 'x'), x'0102030405' FROM c"), 50L, "50 rows"); + + // past the row cap: the capped rows, has_more, every change made and counted + Object[] ret = run(w, "UPDATE rt SET v = v + 1 RETURNING *", null, 3, 4096, 1024, MAX, FAR); + Result rows = rowsOf(ret); + eq(rows.rows.size(), 3, "3 rows, the cap"); + check(rows.hasMore, "has_more past the cap"); + eq(counts(ret)[0], 50L, "changes counts every row written, not only those returned"); + eq(q(r, "SELECT count(*) FROM rt WHERE v = 1").rows.get(0)[0], 50L, "and every row was updated, and committed"); + eq(Arrays.asList(rows.columns), Arrays.asList("id", "v", "s", "b"), "RETURNING * columns"); + eq(Arrays.asList(rows.declaredTypes), Arrays.asList("INTEGER", "INTEGER", "TEXT", "BLOB"), "declared types, as query's"); + + // the byte budget: the first row always comes back, the rest is has_more + ret = run(w, "UPDATE rt SET v = v + 1 RETURNING s", null, 1000, 4096, 1024, 10, FAR); + eq(rowsOf(ret).rows.size(), 1, "the budget keeps the first row only"); + check(rowsOf(ret).hasMore, "and says there is more"); + eq(counts(ret)[0], 50L, "every row still counted"); + eq(q(r, "SELECT count(*) FROM rt WHERE v = 2").rows.get(0)[0], 50L, "and updated"); + + // a wide row is cut as in query + ret = run(w, "UPDATE rt SET v = v + 1 WHERE id = 1 RETURNING s, b", null, 1000, 4, 2, MAX, FAR); + rows = rowsOf(ret); + eq(rows.rows.get(0)[0], "xxxx", "TEXT cut at its limit"); + eq(((byte[]) rows.rows.get(0)[1]).length, 2, "BLOB cut at its limit"); + eq(rows.cut, set(0L, 1L), "both listed as cut"); + + // DELETE ... RETURNING cut short deletes every row + ret = run(w, "DELETE FROM rt WHERE id > 40 RETURNING id", null, 2, 4096, 1024, MAX, FAR); + eq(rowsOf(ret).rows.size(), 2, "2 rows back"); + eq(counts(ret)[0], 10L, "10 deleted"); + eq(q(r, "SELECT count(*) FROM rt WHERE id > 40").rows.get(0)[0], 0L, "all 10 gone"); + + // the commit at the reset can fail: the app holds a read transaction, so the write cannot take the lock + eq(Helper.exec(app, "BEGIN; SELECT count(*) FROM rt"), 0, "the app opens a read transaction"); + try { + NativeBridge.execute(w, "UPDATE rt SET v = 100 RETURNING id", new Object[0], null, 1, 4096, 1024, MAX, FAR); + check(false, "a write whose commit failed returned rows"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 5, "the failed commit is the call's error: SQLITE_BUSY"); + check(e.getMessage().contains("could not be committed"), "and says so: " + e.getMessage()); + } + eq(Helper.exec(app, "COMMIT"), 0, "the app ends its transaction"); + eq(Helper.autocommit(app), 1, "the app's connection is in autocommit"); + eq(q(r, "SELECT count(*) FROM rt WHERE v = 100").rows.get(0)[0], 0L, "and nothing of the failed write was kept"); + eq(exec(w, "UPDATE rt SET v = 7 WHERE id = 1"), 1L, "the writable connection still writes"); + eq(exec(w, "DROP TABLE rt"), 0L, "drop rt"); + + // The time limit after rows came back: the first step (every change) takes about 0.5 s on a computer, + // copying 400,000 rows out runs past 1.5 s, and SQLite rolls back the whole statement (41621). + exec(w, "CREATE TABLE big(id INTEGER PRIMARY KEY, v, a, b, c, d, e, f, g, h)"); + exec(w, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 400000) " + + "INSERT INTO big SELECT x, 0, 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh' FROM c"); + long t = System.currentTimeMillis(); + eq(counts(run(w, "UPDATE big SET v = 1 RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], 400000L, "one row back: every row changed"); + long firstStep = System.currentTimeMillis() - t; + try { + run(w, "UPDATE big SET v = 2 RETURNING *", null, 1 << 30, 4096, 1024, 1 << 30, FAR); + check(false, "every row of a write past the time limit came back"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 9, "stopped while its rows came back: SQLITE_INTERRUPT"); + check(e.getMessage().contains("rolled back"), "the message says it was rolled back: " + e.getMessage()); + } + eq(q(r, "SELECT count(*) FROM big WHERE v = 2").rows.get(0)[0], 0L, "and nothing was kept, though rows had come back"); + if (firstStep >= 1000) System.out.println(" note: the first step took " + firstStep + " ms, so the stop may have come before any row"); + exec(w, "DROP TABLE big"); + } + /** ADFA-7298: execute on a writable server connection. */ static void execute(Path dir, String path, long app) throws Exception { long w = NativeBridge.openServer(path.getBytes(StandardCharsets.UTF_8), true); @@ -169,12 +267,12 @@ static void execute(Path dir, String path, long app) throws Exception { eq(exec(w, "DELETE FROM t WHERE id = -1"), 0L, "delete none: changes 0"); // by name, as query binds (ADFA-7304: P2-2 and P2-3 met) byte[][] names = {"s".getBytes(StandardCharsets.UTF_8), ":id".getBytes(StandardCharsets.UTF_8)}; - eq(NativeBridge.execute(w, "INSERT INTO t(id, s) VALUES(:id, @s)", new Object[] {"n", 6004L}, names, FAR)[0], 1L, + eq(counts(run(w, "INSERT INTO t(id, s) VALUES(:id, @s)", names, 1000, 4096, 1024, MAX, FAR, "n", 6004L))[0], 1L, "execute binds by name: changes 1"); eq(q(r, "SELECT count(*) FROM t WHERE id = 6004 AND s = 'n'").rows.get(0)[0], 1L, "each value went to its own parameter"); try { NativeBridge.execute(w, "DELETE FROM t WHERE id = :id", new Object[] {6004L}, new byte[][] {"idd".getBytes(StandardCharsets.UTF_8)}, - FAR); + 1000, 4096, 1024, MAX, FAR); check(false, "execute ran with a misspelt name"); } catch (DebugEngineException e) { eq(e.sqliteCode, 25, "execute: a misspelt name is SQLITE_RANGE, nothing run"); @@ -188,7 +286,17 @@ static void execute(Path dir, String path, long app) throws Exception { eq(q(r, "PRAGMA user_version").rows.get(0)[0], 7L, "and is stored"); eq(exec(w, "PRAGMA user_version = 0"), 0L, "user_version back"); eq(exec(w, "DROP TABLE ex"), 0L, "DROP TABLE: changes 0"); - eq(exec(w, "INSERT INTO t(id) VALUES(6003) RETURNING id"), 1L, "RETURNING rows are read and dropped: changes 1"); + // RETURNING rows come back as query's do (ADFA-7304) + Object[] ret = run(w, "INSERT INTO t(id) VALUES(6003) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + eq(counts(ret)[0], 1L, "INSERT ... RETURNING: changes 1"); + eq(Arrays.asList(rowsOf(ret).columns), Arrays.asList("id"), "its RETURNING column"); + eq(rowsOf(ret).rows.size(), 1, "one row"); + eq(rowsOf(ret).rows.get(0)[0], 6003L, "the id it inserted"); + eq(counts(ret)[1], q(r, "SELECT rowid FROM t WHERE id = 6003").rows.get(0)[0], "and last_insert_rowid, its rowid"); + ret = run(w, "UPDATE t SET s = 'q' WHERE id = 6003", null, 1000, 4096, 1024, MAX, FAR); + eq(rowsOf(ret).columns.length, 0, "without RETURNING: no columns"); + eq(rowsOf(ret).rows.size(), 0, "and no rows"); + returningCaps(w, r, app); eq(q(r, "SELECT count(*) FROM t WHERE id IN (6002, 6003)").rows.get(0)[0], 2L, "the writes are visible to a reader"); eq(Helper.exec(app, "DELETE FROM t WHERE id IN (6002, 6003)"), 0, "the app's own connection writes after them"); eq(Helper.autocommit(app), 1, "and the app's connection is in autocommit"); @@ -289,7 +397,7 @@ static void execute(Path dir, String path, long app) throws Exception { try { // far more work than 1.5 s: a cross join of t four times over, inserted NativeBridge.execute(sw, "INSERT INTO t SELECT a.id FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0 " - + "UNION ALL SELECT -1", new Object[0], null, System.currentTimeMillis() + 8000); + + "UNION ALL SELECT -1", new Object[0], null, 1000, 4096, 1024, MAX, System.currentTimeMillis() + 8000); } catch (DebugEngineException e) { ran.code = e.sqliteCode; ran.message = e.getMessage(); diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java index fdfdc35a2d..e8c1bdc18a 100644 --- a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -24,7 +24,8 @@ public static native Object[] query(long handle, String sql, Object[] args, byte int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; - public static native long[] execute(long handle, String sql, Object[] args, byte[][] names, long deadlineMillis) throws DebugEngineException; + public static native Object[] execute(long handle, String sql, Object[] args, byte[][] names, int maxRows, int maxTextBytes, + int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; public static native void close(long handle); } From 64c3ce551bcf465a92b60e8db81741fe246cb403 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 12:27:45 -0800 Subject: [PATCH 16/45] ADFA-7304 style: spotlessApply on DatabaseToolsTest.kt, no functional change ktlint wraps two long call chains in the new execute tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) 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 13447642b8..0d943578ab 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 @@ -1420,7 +1420,13 @@ class DatabaseToolsTest { assertEquals(mapOf("a" to "x", "@b" to 2L), engine.lastArgNames!!.zip(got).toMap()) ok("execute", db().put("sql", "update t set a = ?").put("args", JSONArray().put(1))) assertEquals("an array binds by position", null, engine.lastArgNames) - val schema = tools.tools().single { it.name == "execute" }.inputSchema.getJSONObject("properties").getJSONObject("args") + val schema = + tools + .tools() + .single { it.name == "execute" } + .inputSchema + .getJSONObject("properties") + .getJSONObject("args") assertEquals(listOf("array", "object"), schema.getJSONArray("type").let { a -> (0 until a.length()).map { a.getString(it) } }) } @@ -1446,7 +1452,14 @@ class DatabaseToolsTest { assertEquals(listOf("id", "b"), r.getJSONArray("columns").let { a -> (0 until a.length()).map { a.getString(it) } }) assertEquals("INTEGER", r.getJSONArray("column_types").getString(0)) assertEquals(2, r.getInt("row_count")) - assertEquals("01", r.getJSONArray("rows").getJSONArray(0).getJSONObject(1).getString("hex")) + assertEquals( + "01", + r + .getJSONArray("rows") + .getJSONArray(0) + .getJSONObject(1) + .getString("hex"), + ) assertEquals("ib", r.getJSONArray("storage_classes").getString(0)) assertTrue(r.getBoolean("has_more")) assertEquals(1, r.getInt("truncated_cells")) From a8bb4e3aae7ccbec3a80bc691595fc143cb1d421 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 13:21:06 -0800 Subject: [PATCH 17/45] ADFA-7304 JniQueryTest: the time-limit case survives a busy machine The case filled its 400,000-row table and ran its timing call through execute, which stops any write after 1.5 s. With Gradle building alongside, the setup UPDATE's first step passed 1.5 s and the JNI suite aborted (review F02). The table is now filled on the app's connection, which has no time limit. If the timing call is itself stopped, the case prints a note and skips the stop-after-rows check instead of aborting. Checked both ways: on a quiet machine the stop-after-rows check runs (JNI 578 checks, no note); with the table made ten times bigger, the first step passes 1.5 s and the case takes the note path and passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../src/test/jni/JniQueryTest.java | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 4b03408c19..cf2758edc4 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -236,12 +236,22 @@ static void returningCaps(long w, long r, long app) throws Exception { eq(exec(w, "DROP TABLE rt"), 0L, "drop rt"); // The time limit after rows came back: the first step (every change) takes about 0.5 s on a computer, - // copying 400,000 rows out runs past 1.5 s, and SQLite rolls back the whole statement (41621). - exec(w, "CREATE TABLE big(id INTEGER PRIMARY KEY, v, a, b, c, d, e, f, g, h)"); - exec(w, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 400000) " - + "INSERT INTO big SELECT x, 0, 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh' FROM c"); + // copying 400,000 rows out runs past 1.5 s, and SQLite rolls back the whole statement (41621). The table + // is filled on the app's connection, which has no time limit. On a slow or busy machine the first step + // alone can pass 1.5 s; the case after rows came back is then skipped with a note instead of failing. + eq(Helper.exec(app, "CREATE TABLE big(id INTEGER PRIMARY KEY, v, a, b, c, d, e, f, g, h)"), 0, "the app creates big"); + eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 400000) " + + "INSERT INTO big SELECT x, 0, 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh' FROM c"), 0, + "the app fills big"); long t = System.currentTimeMillis(); - eq(counts(run(w, "UPDATE big SET v = 1 RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], 400000L, "one row back: every row changed"); + boolean firstStepFits = true; + try { + eq(counts(run(w, "UPDATE big SET v = 1 RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], 400000L, "one row back: every row changed"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 9, "only the time limit stops the first step: SQLITE_INTERRUPT"); + firstStepFits = false; + System.out.println(" note: the first step alone passed 1.5 s on this machine, so the stop after rows came back was not tested"); + } long firstStep = System.currentTimeMillis() - t; try { run(w, "UPDATE big SET v = 2 RETURNING *", null, 1 << 30, 4096, 1024, 1 << 30, FAR); @@ -251,8 +261,9 @@ static void returningCaps(long w, long r, long app) throws Exception { check(e.getMessage().contains("rolled back"), "the message says it was rolled back: " + e.getMessage()); } eq(q(r, "SELECT count(*) FROM big WHERE v = 2").rows.get(0)[0], 0L, "and nothing was kept, though rows had come back"); - if (firstStep >= 1000) System.out.println(" note: the first step took " + firstStep + " ms, so the stop may have come before any row"); - exec(w, "DROP TABLE big"); + if (firstStepFits && firstStep >= 1000) + System.out.println(" note: the first step took " + firstStep + " ms, so the stop may have come before any row"); + eq(Helper.exec(app, "DROP TABLE big"), 0, "the app drops big"); } /** ADFA-7298: execute on a writable server connection. */ From c2fae14c2bc0c8295eee93d5872c1e039caac9cd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 13:21:06 -0800 Subject: [PATCH 18/45] ADFA-7304 execute: say how many rows a failed FAIL statement kept The tool text, DebugEngine, the README and a C comment said a statement that fails "returns no rows and keeps nothing". Under FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) SQLite keeps, and in autocommit commits, the rows changed before the failing one (review F01; checked on 3.49.1: ABORT, ROLLBACK and their RAISE forms keep none and leave sqlite3_total_changes64 where it was; FAIL moves it, and sqlite3_changes64 is the number kept). bridge_execute now adds "The N rows it changed before the failure were kept: FAIL conflict resolution keeps them" to the error when the total moved, and the texts say so. The README's accepted limit now covers any allocation failure during or after the read, not only a row's (F03). Tests: a JNI case with INSERT OR FAIL ... RETURNING (code 19, 2 rows kept and counted) and a default ABORT one (nothing kept, nothing claimed); DatabaseToolsTest checks the new tool text. Revert proofs: with the old C, the JNI case fails on the kept-rows message; with the old tool text, DatabaseToolsTest fails on the missing sentence. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../src/main/cpp/sqlitedbg_jni.c | 16 +++++++++++--- .../sqlitedebugger/engine/DebugEngine.kt | 3 ++- .../sqlitedebugger/mcp/DatabaseTools.kt | 4 +++- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 3 ++- .../src/test/jni/JniQueryTest.java | 22 +++++++++++++++++++ 6 files changed, 43 insertions(+), 7 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 6a58518ef6..a3ca300b52 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -52,7 +52,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **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 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` come back as `query`'s do, within the same limits (ADFA-7304): at most `max_rows`, the 4 MiB budget with the first row whole, cut cells listed, and `has_more`. There is no `offset`, since paging would run the write again. SQLite makes every change, and buffers every returned row, in the first `sqlite3_step` (ADFA-7304 comment 41621). So a statement stopped at a limit is reset, which commits all of it, `changes` counts every row written, and a failed commit at the reset is the call's error. A statement that fails at any step, even while its rows come back, is rolled back whole by SQLite, so `execute` returns only the error and no rows. Limit: if the JVM fails to allocate a row mid-read, the statement is finalized unfinished, which commits it while the call reports the error. 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. +- **`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` come back as `query`'s do, within the same limits (ADFA-7304): at most `max_rows`, the 4 MiB budget with the first row whole, cut cells listed, and `has_more`. There is no `offset`, since paging would run the write again. SQLite makes every change, and buffers every returned row, in the first `sqlite3_step` (ADFA-7304 comment 41621). So a statement stopped at a limit is reset, which commits all of it, `changes` counts every row written, and a failed commit at the reset is the call's error. A statement that fails at any step, even while its rows come back, returns only the error and no rows. SQLite rolls it back whole, except that FAIL conflict resolution (`OR FAIL`, `ON CONFLICT FAIL`, `RAISE(FAIL)`) keeps, and in autocommit commits, the rows changed before the failing one; the error then says how many (`sqlite3_changes64`, counted when `sqlite3_total_changes64` moved). Limit: if an allocation fails during or after the read (the JVM's for a row or the result, or SQLite's for a cell), the statement is finalized unfinished, which commits it while the call reports the error. 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. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 3da39a9e5d..ea06f4363b 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -682,8 +682,9 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring // restores the value when the trigger ends. // SQLite makes every change, and buffers every RETURNING row, in the first sqlite3_step (ADFA-7304 comment // 41621). So a statement stopped at the row limit is reset, which commits all its changes and leaves -// changes counting every row written. A statement that fails at any step, even after rows came back, is -// rolled back whole, so its rows are dropped and only the error is returned. +// changes counting every row written. A statement that fails at any step, even after rows came back, returns +// only the error. SQLite rolls it back whole, except that FAIL conflict resolution keeps the rows changed +// before the failing one, which the error then counts. static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jobjectArray names, jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { @@ -741,7 +742,16 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); throw_engine(env, SQLITE_INTERRUPT, msg); } else if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the statement ran past its time limit"); - else throw_engine(env, rc, sqlite3_errmsg(db)); + else if (sqlite3_total_changes64(db) != total_before) { + // FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps, and in autocommit + // commits, the rows changed before the failing one; ABORT and ROLLBACK keep none, and leave the + // total where it was. + sqlite3_int64 kept = sqlite3_changes64(db); + char msg[512]; + snprintf(msg, sizeof msg, "%.300s. The %lld %s it changed before the failure %s kept: FAIL conflict resolution keeps them", + sqlite3_errmsg(db), (long long)kept, kept == 1 ? "row" : "rows", kept == 1 ? "was" : "were"); + throw_engine(env, rc, msg); + } else throw_engine(env, rc, sqlite3_errmsg(db)); goto done; } jlong out[2]; diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 774e5d1d1f..eaba6b62ac 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -91,7 +91,8 @@ interface ServerConnection : Closeable { * however many rows are returned ([ExecuteResult.rows] has hasMore). Needs a connection opened with * `writable = true`. The statement is stopped and rolled back once [deadlineMillis] has passed, or after * SQLITEDBG_SERVER_NON_WAL_MS (1.5 s) whichever is first: it holds the write lock, which the app's own - * writes wait for. A statement that fails, even after rows came back, keeps nothing and returns no rows. + * writes wait for. A statement that fails, even after rows came back, returns no rows and is rolled back, + * except that FAIL conflict resolution keeps the rows changed before the failing one; the error counts them. * * @throws DebugEngineException as [query] does, and for a statement that does not write * (`sqlite3_stmt_readonly`), a transaction statement, a refused PRAGMA, or a failed commit. 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 a5971b2c6a..46fabe3708 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 @@ -373,7 +373,9 @@ class DatabaseTools internal constructor( "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cells. Every change is committed whatever is returned: " + "has_more true means RETURNING produced more rows than came back, and they cannot be paged (that " + "would write again); read them with query. SQLite makes every change before the first row comes back, " + - "so the time limit covers the whole write. A statement that fails returns no rows and keeps nothing. " + + "so the time limit covers the whole write. A statement that fails returns no rows, and SQLite rolls back " + + "its changes, except that FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows " + + "changed before the failing one; the error then says how many were kept. " + "Foreign keys are enforced here whatever the app's own connections do: ON DELETE and ON UPDATE actions " + "run, and a write the app could make with foreign keys off may be refused. " + "Also refused: ATTACH, every PRAGMA that takes a value except user_version (no setting can be " + 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 0d943578ab..e655cc1dd2 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 @@ -1533,7 +1533,8 @@ class DatabaseToolsTest { "does not write is refused: use query", "Rows from RETURNING come back as query returns them", "cannot be paged", - "returns no rows and keeps nothing", + "A statement that fails returns no rows", + "FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows", "stopped and rolled back after 1.5 s", "in every journal mode", "may stay stale", diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index cf2758edc4..8468426b7a 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -235,6 +235,28 @@ static void returningCaps(long w, long r, long app) throws Exception { eq(exec(w, "UPDATE rt SET v = 7 WHERE id = 1"), 1L, "the writable connection still writes"); eq(exec(w, "DROP TABLE rt"), 0L, "drop rt"); + // FAIL conflict resolution keeps the rows changed before the failing one, and the error counts them; + // ABORT, the default, keeps none. + exec(w, "CREATE TABLE fr(id INTEGER PRIMARY KEY, u UNIQUE)"); + exec(w, "INSERT INTO fr VALUES(1, 10)"); + try { + run(w, "INSERT OR FAIL INTO fr(id, u) VALUES(2, 20), (3, 30), (4, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + check(false, "an OR FAIL write that failed returned rows"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 19, "OR FAIL on a duplicate: SQLITE_CONSTRAINT"); + check(e.getMessage().contains("The 2 rows it changed before the failure were kept"), "the error counts what was kept: " + e.getMessage()); + } + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 3L, "and those 2 rows are committed"); + try { + run(w, "INSERT INTO fr(id, u) VALUES(5, 50), (6, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + check(false, "an ABORT write that failed returned rows"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 19, "ABORT on a duplicate: SQLITE_CONSTRAINT"); + check(!e.getMessage().contains("kept"), "ABORT keeps nothing, and the error claims nothing was kept: " + e.getMessage()); + } + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 3L, "and nothing of the ABORT write was kept"); + eq(exec(w, "DROP TABLE fr"), 0L, "drop fr"); + // The time limit after rows came back: the first step (every change) takes about 0.5 s on a computer, // copying 400,000 rows out runs past 1.5 s, and SQLite rolls back the whole statement (41621). The table // is filled on the app's connection, which has no time limit. On a slow or busy machine the first step From 0c9a19ea37b5fa712f40717a0135835b05294cd1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 15:21:05 -0800 Subject: [PATCH 19/45] ADFA-7296 test: size the fake engine's records as the native ones FakeDebugEngine.readEvents still counted a 56-byte header, but this PR grew the record header to 72 bytes (EventDecoder.HEADER_BYTES), and it counted a ROW event's SQL, which is empty, instead of its values (#2311 review, 2026-11-26). No test failed, as none sized a batch to the byte. The fake now uses EventDecoder's header and row sizes, made internal for it, and a new test checks that its batches end where the C layer's records in events.bin do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/engine/EventDecoder.kt | 4 +-- .../sqlitedebugger/engine/FakeDebugEngine.kt | 16 +++++++-- .../engine/FakeDebugEngineTest.kt | 36 +++++++++++++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) create mode 100644 subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt index e49421a8c8..d183bff78c 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -28,8 +28,8 @@ internal object EventDecoder { private const val FLAG_EXPANDED = 2 private const val FLAG_ROWS_CUT = 4 - private const val ROW_HEADER_BYTES = 8 - private const val ROW_VALUE_BYTES = 12 + internal const val ROW_HEADER_BYTES = 8 + internal const val ROW_VALUE_BYTES = 12 // SQLite's fundamental types, as sqlite3_column_type returns them. private const val SQLITE_INTEGER = 1 diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index f889ba3684..e984b7b418 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -49,9 +49,21 @@ class FakeDebugEngine( buffered.addLast(Event(lastSeq, kind, connectionId, 1, lastSeq, durationNanos, sql, false, clientConnected)) } + /** Adds [event] as the next one, numbered after the events before it whatever its own [Event.seq]. */ + fun addEvent(event: Event) { + lastSeq++ + buffered.addLast(event.copy(seq = lastSeq)) + } + /** Drops the [count] oldest buffered events, as a full native buffer would. */ fun dropOldest(count: Int) = repeat(count) { buffered.removeFirstOrNull() } + /** A record's data as [EventDecoder] reads it: the SQL, or a ROW event's values, each with its header. */ + private fun dataBytes(event: Event): Int { + val row = event.row ?: return event.sql.toByteArray().size + return EventDecoder.ROW_HEADER_BYTES + row.values.sumOf { EventDecoder.ROW_VALUE_BYTES + cellBytes(it).toInt() } + } + private fun cellBytes(value: Any?): Long = when (value) { is String -> value.toByteArray().size.toLong() @@ -74,8 +86,8 @@ class FakeDebugEngine( var bytes = 0 for (event in buffered) { if (event.seq <= after) continue - // the native record: a 56-byte header, then the SQL padded to 8 bytes - val size = 56 + (event.sql.toByteArray().size + 7) / 8 * 8 + // the native record: the header, then its data padded to 8 bytes + val size = EventDecoder.HEADER_BYTES + (dataBytes(event) + 7) / 8 * 8 if (bytes + size > maxBytes) break bytes += size events += event diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt new file mode 100644 index 0000000000..806e788c60 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt @@ -0,0 +1,36 @@ +package org.appdevforall.sqlitedebugger.engine + +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class FakeDebugEngineTest { + /** + * The fake fills a batch up to maxBytes as the native buffer does, so a test that sizes a batch to the + * byte gets the real cut. events.bin holds records the C layer wrote, a ROW event among them. + */ + @Test + fun `a batch ends where the native records would`() { + val bytes = checkNotNull(javaClass.getResourceAsStream("events.bin")).use { it.readBytes() } + val events = EventDecoder.decode(bytes, bytes.size) + assertThat(events.map { it.kind }).contains(EventKind.ROW) + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val recordBytes = mutableListOf() + var offset = 0 + while (offset < bytes.size) { + recordBytes += buffer.getInt(offset) + offset += recordBytes.last() + } + assertThat(recordBytes).hasSize(events.size) + + val engine = FakeDebugEngine() + events.forEach { engine.addEvent(it) } + var upTo = 0 + recordBytes.forEachIndexed { i, size -> + upTo += size + assertThat(engine.readEvents(0, upTo).events).hasSize(i + 1) + assertThat(engine.readEvents(0, upTo - 1).events).hasSize(i) + } + } +} From 2d674ecfc4ab9b4f177dec16987daced58d90d77 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 21:50:36 -0800 Subject: [PATCH 20/45] ADFA-7296 EventDecoder: refuse a row count its bytes cannot hold A ROW record with columns = kept = Int.MAX_VALUE passed the kept <= columns check, and ArrayList(kept) then threw OutOfMemoryError before the first value's check could refuse the row, instead of the documented IllegalArgumentException (CodeRabbit, #2311, 2026-11-26). Each kept value takes at least ROW_VALUE_BYTES, so kept is now checked against the row's length before the list is sized. Rows the C layer writes always pass. Without the check, the new test's row throws "OutOfMemoryError: Requested array size exceeds VM limit", and the build's -XX:+ExitOnOutOfMemoryError ends the test JVM (exit 3). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/engine/EventDecoder.kt | 5 +++++ .../sqlitedebugger/engine/EventDecoderTest.kt | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt index d183bff78c..2e8c51132e 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -100,6 +100,11 @@ internal object EventDecoder { val columns = buffer.getInt(start) val kept = buffer.getInt(start + 4) require(columns >= 0 && kept in 0..columns) { "row at $start has columns=$columns kept=$kept" } + // Each value takes at least ROW_VALUE_BYTES. Checked before ArrayList(kept) allocates: a count near + // Int.MAX_VALUE throws OutOfMemoryError there, before any value's own check runs. + require(kept <= (length - ROW_HEADER_BYTES) / ROW_VALUE_BYTES) { + "row at $start has kept=$kept, more values than its $length bytes hold" + } val values = ArrayList(kept) val cut = HashSet() var pos = start + ROW_HEADER_BYTES diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index 1b47cf84ef..50e584a018 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -169,4 +169,23 @@ class EventDecoderTest { val e = assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(narrow, narrow.size) } assertThat(e.message).contains("number 0 is 4 bytes") } + + @Test + fun `a row with more values than its bytes hold is refused before they are read`() { + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + var offset = 0 + while (buffer.getInt(offset + 4) != EventKind.ROW.nativeValue) offset += buffer.getInt(offset) + val data = offset + EventDecoder.HEADER_BYTES + val huge = bytes.copyOf() + ByteBuffer + .wrap(huge) + .order(ByteOrder.LITTLE_ENDIAN) + .putInt(data, Int.MAX_VALUE) + .putInt(data + 4, Int.MAX_VALUE) + + // columns = kept = Int.MAX_VALUE passes the kept <= columns check; sizing the value list from it threw + // OutOfMemoryError before the first value's check could refuse the row + val e = assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(huge, huge.size) } + assertThat(e.message).contains("kept=${Int.MAX_VALUE}") + } } From 571cc3ff64745455bcfeb122fea2a55e9697125c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 29 Nov 2026 22:06:45 -0800 Subject: [PATCH 21/45] ADFA-7304 execute: classify a commit stopped at the cap like a stalled step A statement cut at a row limit is reset to commit it. When the commit waited on an app reader until the cap, the call got SQLITE_BUSY and no advice, while the same stall in a step reported SQLITE_INTERRUPT with 'Try it again'. The reset path now uses the same classification (throw_if_stopped), and still reports 'nothing it changed was kept' for other failures. The done: path now finalizes before restoring busy_timeout, so the commit an unfinished statement makes in finalize (after an allocation failure) is bounded by busy_cb. The README says so. This path cannot be tested: it needs a JNI or SQLite allocation failure. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../src/main/cpp/sqlitedbg_jni.c | 55 +++++++++++-------- 2 files changed, 34 insertions(+), 23 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index ada663e81e..22135bd1b0 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -52,7 +52,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **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 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 once it has held its lock for 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`; a wait for the app's lock before that is not counted), 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` come back as `query`'s do, within the same limits (ADFA-7304): at most `max_rows`, the 4 MiB budget with the first row whole, cut cells listed, and `has_more`. There is no `offset`, since paging would run the write again. SQLite makes every change, and buffers every returned row, in the first `sqlite3_step` (ADFA-7304 comment 41621). So a statement stopped at a limit is reset, which commits all of it, `changes` counts every row written, and a failed commit at the reset is the call's error. A statement that fails at any step, even while its rows come back, returns only the error and no rows. SQLite rolls it back whole, except that FAIL conflict resolution (`OR FAIL`, `ON CONFLICT FAIL`, `RAISE(FAIL)`) keeps, and in autocommit commits, the rows changed before the failing one; the error then says how many (`sqlite3_changes64`, counted when `sqlite3_total_changes64` moved). Limit: if an allocation fails during or after the read (the JVM's for a row or the result, or SQLite's for a cell), the statement is finalized unfinished, which commits it while the call reports the error. 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 once it has held the write lock for 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. A wait for the app's lock before the statement holds its own is not counted. A wait to commit is: in rollback-journal mode the commit waits for other connections' reads to end, and `execute` replaces the connection's busy timeout with a busy handler that stops at the limit too, so the write lock is not held up to 3 s past it; that error says to try again. A deadline that passes while the statement is prepared (preparing can wait on the app's lock to read the schema) stops it before it starts. 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. +- **`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` come back as `query`'s do, within the same limits (ADFA-7304): at most `max_rows`, the 4 MiB budget with the first row whole, cut cells listed, and `has_more`. There is no `offset`, since paging would run the write again. SQLite makes every change, and buffers every returned row, in the first `sqlite3_step` (ADFA-7304 comment 41621). So a statement stopped at a limit is reset, which commits all of it, `changes` counts every row written, and a failed commit at the reset is the call's error (one that stalled to the cap waiting for another connection's read is reported as a stalled step is: SQLITE_INTERRUPT, "Try it again"). A statement that fails at any step, even while its rows come back, returns only the error and no rows. SQLite rolls it back whole, except that FAIL conflict resolution (`OR FAIL`, `ON CONFLICT FAIL`, `RAISE(FAIL)`) keeps, and in autocommit commits, the rows changed before the failing one; the error then says how many (`sqlite3_changes64`, counted when `sqlite3_total_changes64` moved). Limit: if an allocation fails during or after the read (the JVM's for a row or the result, or SQLite's for a cell), the statement is finalized unfinished, which commits it while the call reports the error; that commit waits for a lock only as long as the step's limit allows, as the busy handler stays set until the finalize. 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 once it has held the write lock for 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. A wait for the app's lock before the statement holds its own is not counted. A wait to commit is: in rollback-journal mode the commit waits for other connections' reads to end, and `execute` replaces the connection's busy timeout with a busy handler that stops at the limit too, so the write lock is not held up to 3 s past it; that error says to try again. A deadline that passes while the statement is prepared (preparing can wait on the app's lock to read the schema) stops it before it starts. 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. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index df370c2160..c0d71ecc41 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -710,6 +710,31 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring return result; } +// Reports a statement that the time limit or the cap stopped, as execute's error, and returns 1; returns 0 +// when rc is not that, for the caller to report. Used for a failed step and for a failed commit at reset. +static int throw_if_stopped(JNIEnv *env, const deadline *dl, int rc) { + // busy_cb giving up makes the step or the commit fail with SQLITE_BUSY; SQLite then rolls back + if (dl->busy_hit && rc == SQLITE_BUSY && dl->capped) { + char msg[320]; + snprintf(msg, sizeof msg, + "the statement was stopped after %.1f s and rolled back: it was waiting for another connection to finish " + "reading the database, and a write holds the database's write lock, so waiting longer would make the " + "app's own writes fail. Try it again", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl->hit && rc == SQLITE_INTERRUPT && dl->capped) { + char msg[256]; + snprintf(msg, sizeof msg, + "the statement was stopped after %.1f s and rolled back: a write holds the database's write lock, so a " + "longer one would make the app's own writes fail. Change fewer rows per call", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl->hit && (rc == SQLITE_INTERRUPT || rc == SQLITE_BUSY)) { + throw_engine(env, SQLITE_INTERRUPT, "the statement ran past its time limit"); + } else return 0; + return 1; +} + // Runs one statement that writes on a writable server connection (ADFA-7298), and returns the rows it // returns (RETURNING) as read_rows does, within the same limits (ADFA-7304): [columns, rows, counts, // decltypes, {changes, last_insert_rowid}]. changes is the rows the statement itself inserted, updated or @@ -770,6 +795,7 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin // Commits every change, not only those of the rows read; the commit itself can fail. rc = sqlite3_reset(st); if (rc != SQLITE_OK) { + if (throw_if_stopped(env, &dl, rc)) goto done; char msg[256]; snprintf(msg, sizeof msg, "the statement could not be committed, and nothing it changed was kept: %s", sqlite3_errmsg(db)); @@ -777,24 +803,8 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin goto done; } } else if (rc != SQLITE_DONE) { - // busy_cb giving up makes the step fail with SQLITE_BUSY; at the commit SQLite then rolls back - if (dl.busy_hit && rc == SQLITE_BUSY && dl.capped) { - char msg[320]; - snprintf(msg, sizeof msg, - "the statement was stopped after %.1f s and rolled back: it was waiting for another connection to finish " - "reading the database, and a write holds the database's write lock, so waiting longer would make the " - "app's own writes fail. Try it again", - SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); - throw_engine(env, SQLITE_INTERRUPT, msg); - } else if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { - char msg[256]; - snprintf(msg, sizeof msg, - "the statement was stopped after %.1f s and rolled back: a write holds the database's write lock, so a " - "longer one would make the app's own writes fail. Change fewer rows per call", - SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); - throw_engine(env, SQLITE_INTERRUPT, msg); - } else if (dl.hit && (rc == SQLITE_INTERRUPT || rc == SQLITE_BUSY)) { - throw_engine(env, SQLITE_INTERRUPT, "the statement ran past its time limit"); + if (throw_if_stopped(env, &dl, rc)) { + // reported } else if (sqlite3_total_changes64(db) != total_before) { // FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps, and in autocommit // commits, the rows changed before the failing one; ABORT and ROLLBACK keep none, and leave the @@ -822,11 +832,12 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin (*env)->SetObjectArrayElement(env, result, 4, counts); done: - if (handler_set) { - sqlite3_progress_handler(db, 0, NULL, NULL); - sqlite3_busy_timeout(db, SQLITEDBG_SERVER_BUSY_MS); // as sqlitedbg_open_server set it; dl is gone - } + // The progress handler goes first, as it can no longer matter. Finalizing commits a statement that is + // unfinished (a JNI or SQLite allocation failed while rows were read), and busy_cb, still set, bounds + // that commit's wait; only then is the connection's busy timeout restored, as sqlitedbg_open_server set it. + if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); sqlite3_finalize(st); + if (handler_set) sqlite3_busy_timeout(db, SQLITEDBG_SERVER_BUSY_MS); if (!end_transaction_backstop(env, db)) result = NULL; return result; } From f7e7b55ba2182e81218c10cf2e5ba8d49435f2e7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 29 Nov 2026 22:06:45 -0800 Subject: [PATCH 22/45] ADFA-7304 tests: reset-commit stall, conflict modes with RETURNING, a time limit that must strike The commit stopped at the cap is checked for SQLITE_INTERRUPT and the advice (fails without the previous commit: 5 vs 9). RETURNING with OR ROLLBACK, OR IGNORE and OR REPLACE is covered. The time-limit-after-rows case times its first step, halves the table while that takes over 1 s, and fails instead of passing when it cannot reach the path. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../src/test/jni/JniQueryTest.java | 77 ++++++++++++++----- 1 file changed, 58 insertions(+), 19 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 89e202aab2..6b8517b4aa 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -220,14 +220,20 @@ static void returningCaps(long w, long r, long app) throws Exception { eq(counts(ret)[0], 10L, "10 deleted"); eq(q(r, "SELECT count(*) FROM rt WHERE id > 40").rows.get(0)[0], 0L, "all 10 gone"); - // the commit at the reset can fail: the app holds a read transaction, so the write cannot take the lock + // The commit at the reset can fail: the app holds a read transaction (SHARED, rollback journal), so the + // write waits to commit until busy_cb gives up at the 1.5 s cap. That is classified as a stalled step is + // (SQLITE_INTERRUPT, "Try it again"), and still says that nothing was kept. eq(Helper.exec(app, "BEGIN; SELECT count(*) FROM rt"), 0, "the app opens a read transaction"); + long stalled = System.currentTimeMillis(); try { NativeBridge.execute(w, "UPDATE rt SET v = 100 RETURNING id", new Object[0], null, 1, 4096, 1024, MAX, FAR); check(false, "a write whose commit failed returned rows"); } catch (DebugEngineException e) { - eq(e.sqliteCode, 5, "the failed commit is the call's error: SQLITE_BUSY"); - check(e.getMessage().contains("could not be committed"), "and says so: " + e.getMessage()); + long ms = System.currentTimeMillis() - stalled; + eq(e.sqliteCode, 9, "the failed commit stopped at the cap: SQLITE_INTERRUPT, as a stalled step is"); + check(e.getMessage().contains("rolled back") && e.getMessage().contains("Try it again"), + "and gives the advice: " + e.getMessage()); + check(ms >= 1400 && ms < 2400, "after " + ms + " ms, near the 1500 ms cap"); } eq(Helper.exec(app, "COMMIT"), 0, "the app ends its transaction"); eq(Helper.autocommit(app), 1, "the app's connection is in autocommit"); @@ -255,36 +261,69 @@ static void returningCaps(long w, long r, long app) throws Exception { check(!e.getMessage().contains("kept"), "ABORT keeps nothing, and the error claims nothing was kept: " + e.getMessage()); } eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 3L, "and nothing of the ABORT write was kept"); + + // ROLLBACK resolution fails the statement and keeps nothing (no claim of kept rows, unlike FAIL) + try { + run(w, "INSERT OR ROLLBACK INTO fr(id, u) VALUES(7, 70), (8, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + check(false, "an OR ROLLBACK write that failed returned rows"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 19, "OR ROLLBACK on a duplicate: SQLITE_CONSTRAINT"); + check(!e.getMessage().contains("kept"), "OR ROLLBACK keeps nothing, and the error claims nothing was kept: " + e.getMessage()); + } + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 3L, "and nothing of the OR ROLLBACK write was kept"); + eq(Helper.autocommit(app), 1, "the app's connection is in autocommit"); + eq(exec(w, "UPDATE fr SET u = u WHERE id = 1"), 1L, "the writable connection still writes"); + + // IGNORE skips the duplicate: the other rows come back and are counted + Object[] ign = run(w, "INSERT OR IGNORE INTO fr(id, u) VALUES(9, 90), (10, 10), (11, 110) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + eq(rowsOf(ign).rows.size(), 2, "OR IGNORE returns the 2 rows it inserted"); + eq(rowsOf(ign).rows.get(0)[0], 9L, "the first"); + eq(rowsOf(ign).rows.get(1)[0], 11L, "and the last, the duplicate skipped"); + eq(counts(ign)[0], 2L, "changes counts the 2 inserted"); + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 5L, "and the table has them"); + + // REPLACE deletes the conflicting row and inserts the new one + Object[] rep = run(w, "INSERT OR REPLACE INTO fr(id, u) VALUES(12, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + eq(rowsOf(rep).rows.size(), 1, "OR REPLACE returns its row"); + eq(rowsOf(rep).rows.get(0)[0], 12L, "the new row"); + eq(counts(rep)[0], 1L, "changes counts the insert, not the replaced row"); + eq(q(r, "SELECT count(*) FROM fr WHERE id = 1").rows.get(0)[0], 0L, "the conflicting row is gone"); + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 5L, "one in, one out"); eq(exec(w, "DROP TABLE fr"), 0L, "drop fr"); - // The time limit after rows came back: the first step (every change) takes about 0.5 s on a computer, - // copying 400,000 rows out runs past 1.5 s, and SQLite rolls back the whole statement (41621). The table - // is filled on the app's connection, which has no time limit. On a slow or busy machine the first step - // alone can pass 1.5 s; the case after rows came back is then skipped with a note instead of failing. + // The time limit after rows came back: the first step (every change) must finish within 1.5 s, and + // copying every row out must run past it, and SQLite rolls back the whole statement (41621). The table + // is filled on the app's connection, which has no time limit. The first step is timed first, with a + // statement that stops after one row, and the table is halved while that takes over 1 s, so a slow + // machine still gets a first step that fits; if it cannot, or the copy then finishes in time, the test + // fails rather than pass without reaching the path. eq(Helper.exec(app, "CREATE TABLE big(id INTEGER PRIMARY KEY, v, a, b, c, d, e, f, g, h)"), 0, "the app creates big"); eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 400000) " + "INSERT INTO big SELECT x, 0, 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh' FROM c"), 0, "the app fills big"); - long t = System.currentTimeMillis(); - boolean firstStepFits = true; - try { - eq(counts(run(w, "UPDATE big SET v = 1 RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], 400000L, "one row back: every row changed"); - } catch (DebugEngineException e) { - eq(e.sqliteCode, 9, "only the time limit stops the first step: SQLITE_INTERRUPT"); - firstStepFits = false; - System.out.println(" note: the first step alone passed 1.5 s on this machine, so the stop after rows came back was not tested"); + long bigRows = 400000; + long firstStep = Long.MAX_VALUE; + for (;; bigRows /= 2) { + long t = System.currentTimeMillis(); + try { + eq(counts(run(w, "UPDATE big SET v = 1 RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], bigRows, "one row back: every row changed"); + } catch (DebugEngineException e) { + check(false, "the first step alone passed the time limit: " + e.getMessage()); + break; + } + firstStep = System.currentTimeMillis() - t; + if (firstStep <= 1000 || bigRows < 25000) break; + eq(Helper.exec(app, "DELETE FROM big WHERE id > " + (bigRows / 2)), 0, "halve big"); } - long firstStep = System.currentTimeMillis() - t; + check(firstStep <= 1000, "the first step took " + firstStep + " ms for " + bigRows + " rows: it fits within the limit, so rows come back before it strikes"); try { run(w, "UPDATE big SET v = 2 RETURNING *", null, 1 << 30, 4096, 1024, 1 << 30, FAR); - check(false, "every row of a write past the time limit came back"); + check(false, "copying " + bigRows + " rows out finished within the time limit: the case was not reached"); } catch (DebugEngineException e) { eq(e.sqliteCode, 9, "stopped while its rows came back: SQLITE_INTERRUPT"); check(e.getMessage().contains("rolled back"), "the message says it was rolled back: " + e.getMessage()); } eq(q(r, "SELECT count(*) FROM big WHERE v = 2").rows.get(0)[0], 0L, "and nothing was kept, though rows had come back"); - if (firstStepFits && firstStep >= 1000) - System.out.println(" note: the first step took " + firstStep + " ms, so the stop may have come before any row"); eq(Helper.exec(app, "DROP TABLE big"), 0, "the app drops big"); } From 0d5dbb9ad5a337a5328997158f83c9e42490d459 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 29 Nov 2026 22:06:45 -0800 Subject: [PATCH 23/45] ADFA-7304 execute: describe truncated_cell_indexes as query does The execute description lacked CUT_CELLS_NOTE, which query and explain_query_plan include, though execute returns the same fields. The description test checks it (fails without), and the RETURNING test also checks the column of truncated_cell_indexes. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 2 +- .../org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) 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 675de4f5b6..c7232799d6 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 @@ -372,7 +372,7 @@ class DatabaseTools internal constructor( "A statement that does not write is refused: use query. Rows from RETURNING come back as query returns " + "them (columns, column_types, rows, storage_classes, has_more, truncated_cells, truncated_cell_indexes), at " + "most max_rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS) and about " + - "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cells. Every change is committed whatever is returned: " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cells; $CUT_CELLS_NOTE Every change is committed whatever is returned: " + "has_more true means RETURNING produced more rows than came back, and they cannot be paged (that " + "would write again); read them with query. SQLite makes every change before the first row comes back, " + "so the time limit covers the whole write. A statement that fails returns no rows, and SQLite rolls back " + 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 be4d7be4d2..1c0defb119 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 @@ -1464,6 +1464,7 @@ class DatabaseToolsTest { assertTrue(r.getBoolean("has_more")) assertEquals(1, r.getInt("truncated_cells")) assertEquals(0, r.getJSONArray("truncated_cell_indexes").getJSONArray(0).getInt(0)) + assertEquals(1, r.getJSONArray("truncated_cell_indexes").getJSONArray(0).getInt(1)) assertFalse("no paging: running the write again would write again", r.has("offset") || r.has("next_offset")) assertEquals(2, engine.lastExecuteLimits!!.maxRows) assertEquals(DatabaseTools.MAX_TOTAL_BYTES, engine.lastExecuteLimits!!.maxTotalBytes) @@ -1532,6 +1533,7 @@ class DatabaseToolsTest { "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused", "does not write is refused: use query", "Rows from RETURNING come back as query returns them", + "truncated_cell_indexes lists each as [row, column]", "cannot be paged", "A statement that fails returns no rows", "FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows", From 5ee892b76b8ac08e0eb50efb645d410cd567fdd6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 29 Nov 2026 22:16:15 -0800 Subject: [PATCH 24/45] ADFA-7304 tests: halve the table when the first step passes the limit on a busy machine The time-limit-after-rows case failed in a run alongside a Gradle build, because its first step passed 1.5 s and the probe stopped instead of halving the table. A stopped probe now counts as too slow and the table is halved, as for a slow one; the case still fails if no size fits. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 6b8517b4aa..f5c2601f18 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -307,11 +307,12 @@ static void returningCaps(long w, long r, long app) throws Exception { long t = System.currentTimeMillis(); try { eq(counts(run(w, "UPDATE big SET v = 1 RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], bigRows, "one row back: every row changed"); + firstStep = System.currentTimeMillis() - t; } catch (DebugEngineException e) { - check(false, "the first step alone passed the time limit: " + e.getMessage()); - break; + // the first step alone passed the limit (a busy machine): too slow, so halve the table + eq(e.sqliteCode, 9, "only the time limit stops the first step: SQLITE_INTERRUPT"); + firstStep = Long.MAX_VALUE; } - firstStep = System.currentTimeMillis() - t; if (firstStep <= 1000 || bigRows < 25000) break; eq(Helper.exec(app, "DELETE FROM big WHERE id > " + (bigRows / 2)), 0, "halve big"); } From b9ccfc76d37b53be2b148b91ee9b163e1887e19f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 08:39:47 -0800 Subject: [PATCH 25/45] ADFA-7304 tests: size the RETURNING time-limit table both ways, so a fast machine reaches the case The case where the time limit strikes while RETURNING rows are copied only halved its 400,000-row table when the first step was slow. On a fast machine every row was copied within the 1.5 s limit, the write committed, and two checks failed ("the case was not reached", "nothing was kept ... 400000 vs 0"); test-sqlite-debugger failed in CI at 5ee892b76 and 9cb70b890 (review on #2332, ADFA-7131 comment 41745). The table is now also doubled (up to 3.2 million rows) while copying every row out finishes within the limit. Each try writes its own value, and the kept-rows check counts only the value of the try the limit stopped. The case still fails, with the sizes and times, if no size fits: a first step over 1 s at a size whose copy still finishes in time. Checked: with the table started at 25,000 rows to stand in for a fast machine, the old test fails both checks and the new one grows to 200,000 rows and passes; from 400,000 rows it passes here at 400,000. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../src/test/jni/JniQueryTest.java | 68 +++++++++++++------ 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index f5c2601f18..54797ed8a3 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -293,38 +293,62 @@ static void returningCaps(long w, long r, long app) throws Exception { // The time limit after rows came back: the first step (every change) must finish within 1.5 s, and // copying every row out must run past it, and SQLite rolls back the whole statement (41621). The table - // is filled on the app's connection, which has no time limit. The first step is timed first, with a - // statement that stops after one row, and the table is halved while that takes over 1 s, so a slow - // machine still gets a first step that fits; if it cannot, or the copy then finishes in time, the test - // fails rather than pass without reaching the path. + // is filled on the app's connection, which has no time limit, and sized to this machine: halved while + // the first step (timed with a statement that stops after one row) takes over 1 s, and doubled while + // copying every row out finishes within the limit. Each try that finishes commits, so every try writes + // a value of its own and the final check counts only that value. If no size fits, the test fails + // rather than pass without reaching the path. eq(Helper.exec(app, "CREATE TABLE big(id INTEGER PRIMARY KEY, v, a, b, c, d, e, f, g, h)"), 0, "the app creates big"); - eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 400000) " - + "INSERT INTO big SELECT x, 0, 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh' FROM c"), 0, - "the app fills big"); - long bigRows = 400000; - long firstStep = Long.MAX_VALUE; - for (;; bigRows /= 2) { + long bigRows = 0; + long target = 400000; + long value = 0; + long firstStep = -1; + long fastCopy = -1; + boolean shrunk = false; + boolean reached = false; + for (int tries = 0; tries < 12 && !reached; tries++) { + if (target > bigRows) { + eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT " + (bigRows + 1) + " UNION ALL SELECT x + 1 FROM c WHERE x < " + target + ") " + + "INSERT INTO big SELECT x, 0, 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh' FROM c"), 0, + "the app fills big to " + target + " rows"); + } else if (target < bigRows) { + eq(Helper.exec(app, "DELETE FROM big WHERE id > " + target), 0, "the app shrinks big to " + target + " rows"); + } + bigRows = target; long t = System.currentTimeMillis(); try { - eq(counts(run(w, "UPDATE big SET v = 1 RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], bigRows, "one row back: every row changed"); + eq(counts(run(w, "UPDATE big SET v = " + (++value) + " RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], bigRows, "one row back: every row changed"); firstStep = System.currentTimeMillis() - t; } catch (DebugEngineException e) { // the first step alone passed the limit (a busy machine): too slow, so halve the table eq(e.sqliteCode, 9, "only the time limit stops the first step: SQLITE_INTERRUPT"); firstStep = Long.MAX_VALUE; } - if (firstStep <= 1000 || bigRows < 25000) break; - eq(Helper.exec(app, "DELETE FROM big WHERE id > " + (bigRows / 2)), 0, "halve big"); - } - check(firstStep <= 1000, "the first step took " + firstStep + " ms for " + bigRows + " rows: it fits within the limit, so rows come back before it strikes"); - try { - run(w, "UPDATE big SET v = 2 RETURNING *", null, 1 << 30, 4096, 1024, 1 << 30, FAR); - check(false, "copying " + bigRows + " rows out finished within the time limit: the case was not reached"); - } catch (DebugEngineException e) { - eq(e.sqliteCode, 9, "stopped while its rows came back: SQLITE_INTERRUPT"); - check(e.getMessage().contains("rolled back"), "the message says it was rolled back: " + e.getMessage()); + if (firstStep > 1000) { + if (bigRows < 25000) break; + target = bigRows / 2; + shrunk = true; + continue; + } + long copyValue = ++value; + t = System.currentTimeMillis(); + try { + run(w, "UPDATE big SET v = " + copyValue + " RETURNING *", null, 1 << 30, 4096, 1024, 1 << 30, FAR); + // copying finished within the limit (a fast machine): double the table, unless that size was + // already too slow for the first step + fastCopy = System.currentTimeMillis() - t; + if (shrunk || bigRows >= 3200000) break; + target = bigRows * 2; + } catch (DebugEngineException e) { + eq(e.sqliteCode, 9, "stopped while its rows came back: SQLITE_INTERRUPT"); + check(e.getMessage().contains("rolled back"), "the message says it was rolled back: " + e.getMessage()); + eq(q(r, "SELECT count(*) FROM big WHERE v = " + copyValue).rows.get(0)[0], 0L, "and nothing was kept, though rows had come back"); + reached = true; + } } - eq(q(r, "SELECT count(*) FROM big WHERE v = 2").rows.get(0)[0], 0L, "and nothing was kept, though rows had come back"); + check(reached, "the time limit struck while rows came back: big has " + bigRows + " rows, the first step took " + firstStep + + " ms, and copying every row out last finished in " + fastCopy + " ms"); + System.out.println("RETURNING time limit: " + bigRows + " rows, first step " + firstStep + " ms"); eq(Helper.exec(app, "DROP TABLE big"), 0, "the app drops big"); } From 95301616007659acd6b41fe3302924ed7b3e3f0d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 15:43:29 -0800 Subject: [PATCH 26/45] ADFA-7304 execute: say whether the write committed when building the result fails Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../src/main/cpp/sqlitedbg_jni.c | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index c0d71ecc41..ab83d02aec 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -735,6 +735,26 @@ static int throw_if_stopped(JNIEnv *env, const deadline *dl, int rc) { return 1; } +// Replaces the exception pending from a failed allocation while execute built its result, for one that also +// says what became of the write, so a caller can tell whether a retry repeats it. The statement had run, and +// finalize (finalize_rc) commits what an unfinished one changed. The pending exception is kept when the +// replacement cannot be built. +static void report_unfinished_write(JNIEnv *env, int finalize_rc) { + char msg[256]; + if (finalize_rc == SQLITE_OK) + snprintf(msg, sizeof msg, + "out of memory while reading the rows the statement returned; the write was committed, so do not repeat it"); + else + snprintf(msg, sizeof msg, + "out of memory while reading the rows the statement returned; finishing the write failed (%.100s), " + "so it may not have been committed", + sqlite3_errstr(finalize_rc)); + jthrowable pending = (*env)->ExceptionOccurred(env); + (*env)->ExceptionClear(env); + throw_engine(env, finalize_rc == SQLITE_OK ? SQLITE_NOMEM : finalize_rc, msg); + if (pending && !(*env)->ExceptionCheck(env)) (*env)->Throw(env, pending); +} + // Runs one statement that writes on a writable server connection (ADFA-7298), and returns the rows it // returns (RETURNING) as read_rows does, within the same limits (ADFA-7304): [columns, rows, counts, // decltypes, {changes, last_insert_rowid}]. changes is the rows the statement itself inserted, updated or @@ -758,6 +778,7 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin jobjectArray result = NULL; deadline dl = {.db = db, .at_ms = (int64_t)deadline_ms}; int handler_set = 0; + int report_write_outcome = 0; // building the result failed with an exception pending: say what became of the write int rc, has_more; if (now_ms() >= dl.at_ms) { @@ -790,7 +811,10 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin // report the rowid of an earlier execute's INSERT. Not 0, SQLite's own "none": 0 is a valid rowid. sqlite3_set_last_insert_rowid(db, INT64_MIN); jobjectArray rows = read_rows(env, st, 0, max_rows, max_text, max_blob, max_total, &rc, &has_more); - if (!rows) goto done; + if (!rows) { + report_write_outcome = 1; + goto done; + } if (has_more) { // Commits every change, not only those of the rows read; the commit itself can fail. rc = sqlite3_reset(st); @@ -822,7 +846,10 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin out[1] = (jlong)sqlite3_last_insert_rowid(db); jlongArray counts = (*env)->NewLongArray(env, 2); result = counts ? (*env)->NewObjectArray(env, 5, g_object, NULL) : NULL; - if (!result) goto done; + if (!result) { + report_write_outcome = 1; + goto done; + } (*env)->SetLongArrayRegion(env, counts, 0, 2, out); for (int i = 0; i < 4; i++) { jobject part = (*env)->GetObjectArrayElement(env, rows, i); @@ -836,8 +863,11 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin // unfinished (a JNI or SQLite allocation failed while rows were read), and busy_cb, still set, bounds // that commit's wait; only then is the connection's busy timeout restored, as sqlitedbg_open_server set it. if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); - sqlite3_finalize(st); + // A statement that ran and was left unfinished is committed by finalize, whose result says whether it was. + int ran = st && sqlite3_stmt_status(st, SQLITE_STMTSTATUS_RUN, 0) > 0; + int finalize_rc = sqlite3_finalize(st); if (handler_set) sqlite3_busy_timeout(db, SQLITEDBG_SERVER_BUSY_MS); + if (report_write_outcome && ran) report_unfinished_write(env, finalize_rc); if (!end_transaction_backstop(env, db)) result = NULL; return result; } From 4d02e99c9f929f1480f38a3336d8a150840b9fa3 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 15:43:29 -0800 Subject: [PATCH 27/45] ADFA-7304 Align execute docs and tool text with best-effort limits and unrecoverable RETURNING rows Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/engine/DebugEngine.kt | 13 ++++++++----- .../sqlitedebugger/mcp/DatabaseTools.kt | 16 +++++++++++++--- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 5 +++++ 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index d69680a6a7..8b4281532a 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -89,11 +89,14 @@ interface ServerConnection : Closeable { * [argNames] is not null), and returns the rows it returns (RETURNING) within [limits] as [query] does, * from the first row, with no offset: paging would run the write again. Every change is committed * however many rows are returned ([ExecuteResult.rows] has hasMore). Needs a connection opened with - * `writable = true`. The statement is stopped and rolled back once [deadlineMillis] has passed, or once it - * has held the write lock for SQLITEDBG_SERVER_NON_WAL_MS (1.5 s), waiting to commit included, whichever - * is first: the app's own writes wait for that lock. A deadline that passes while the statement is prepared - * stops it before it starts. A statement that fails, even after rows came back, returns no rows and is rolled back, - * except that FAIL conflict resolution keeps the rows changed before the failing one; the error counts them. + * `writable = true`. The statement is stopped, and SQLite rolls it back, once [deadlineMillis] has passed, + * or once it has held the write lock for SQLITEDBG_SERVER_NON_WAL_MS (1.5 s), waiting to commit included, + * whichever is first: the app's own writes wait for that lock. The limits are best effort, though: a write + * cut at the row or size limit is committed in full. A deadline that passes while the statement is prepared + * stops it before it starts. A statement that fails, even after rows came back, returns no rows and SQLite + * rolls it back, except that FAIL conflict resolution keeps the rows changed before the failing one; the + * error counts them. A failure building the result after the write finished (an allocation failure) can leave + * the write committed, so a failed call is not always safe to retry; that error says the write was committed. * * @throws DebugEngineException as [query] does, and for a statement that does not write * (`sqlite3_stmt_readonly`), a transaction statement, a refused PRAGMA, or a failed commit. 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 c7232799d6..de025bae6c 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 @@ -119,6 +119,15 @@ class DatabaseTools internal constructor( "included (best effort; a wait of up to 3 s for the app's lock before that is not counted), 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: the rollbacks above are SQLite's and the limits are best effort, so an error is not always a + * proof that nothing changed. + */ + const val COMMIT_UNCERTAIN_NOTE = + "Limits are best effort: a write cut at the row or size limit is committed in full, and an out-of-memory " + + "failure while building the result after the write finished can leave it committed, in which case the error " + + "says so; if an error does not say the write was rolled back, check the data before repeating it." + /** 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 " + @@ -373,11 +382,12 @@ class DatabaseTools internal constructor( "them (columns, column_types, rows, storage_classes, has_more, truncated_cells, truncated_cell_indexes), at " + "most max_rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS) and about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cells; $CUT_CELLS_NOTE Every change is committed whatever is returned: " + - "has_more true means RETURNING produced more rows than came back, and they cannot be paged (that " + - "would write again); read them with query. SQLite makes every change before the first row comes back, " + + "has_more true means RETURNING produced more rows than came back, and the omitted rows cannot be " + + "recovered from this result or paged (that would write again); a follow-up query returns them only if the " + + "data still exists, which it does not after a DELETE. SQLite makes every change before the first row comes back, " + "so the time limit covers the whole write. A statement that fails returns no rows, and SQLite rolls back " + "its changes, except that FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows " + - "changed before the failing one; the error then says how many were kept. " + + "changed before the failing one; the error then says how many were kept. $COMMIT_UNCERTAIN_NOTE " + "Foreign keys are enforced here whatever the app's own connections do: ON DELETE and ON UPDATE actions " + "run, and a write the app could make with foreign keys off may be refused. " + "Also refused: ATTACH, every PRAGMA that takes a value except user_version (no setting can be " + 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 1c0defb119..eb169c07ae 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 @@ -322,6 +322,7 @@ class DatabaseToolsTest { assertTrue(r.getBoolean("has_more")) assertEquals(3, r.getInt("next_offset")) assertTrue(r.getString("note").contains("re-runs")) + assertFalse("omitted rows are not recoverable with query: $d", d.contains("read them with query")) assertTrue( tools .tools() @@ -1538,6 +1539,10 @@ class DatabaseToolsTest { "A statement that fails returns no rows", "FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows", "stopped and rolled back after 1.5 s", + "the omitted rows cannot be recovered from this result", + "which it does not after a DELETE", + "Limits are best effort: a write cut at the row or size limit is committed in full", + "can leave it committed", "in every journal mode", "may stay stale", "Functions the app adds to its own connections", From b1c4e5400dc783dd8365c583fb0022d4e568b825 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 15:43:29 -0800 Subject: [PATCH 28/45] ADFA-7304 JNI test: require rows copied when the RETURNING time limit strikes; bisect the table size Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlite-debugger/src/test/jni/Helper.java | 4 ++ .../src/test/jni/JniQueryTest.java | 51 ++++++++++++++----- .../sqlite-debugger/src/test/jni/helper.c | 28 ++++++++++ 3 files changed, 69 insertions(+), 14 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/jni/Helper.java b/subprojects/sqlite-debugger/src/test/jni/Helper.java index 5c89abc374..994729c024 100644 --- a/subprojects/sqlite-debugger/src/test/jni/Helper.java +++ b/subprojects/sqlite-debugger/src/test/jni/Helper.java @@ -16,5 +16,9 @@ static long open(String path) { static native int busyTimeout(long db, int ms); + static native int traceRows(long db, boolean on); + + static native long tracedRows(); + static native int denyTransactions(long db, boolean deny); } diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 54797ed8a3..8364413cff 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -293,19 +293,24 @@ static void returningCaps(long w, long r, long app) throws Exception { // The time limit after rows came back: the first step (every change) must finish within 1.5 s, and // copying every row out must run past it, and SQLite rolls back the whole statement (41621). The table - // is filled on the app's connection, which has no time limit, and sized to this machine: halved while - // the first step (timed with a statement that stops after one row) takes over 1 s, and doubled while - // copying every row out finishes within the limit. Each try that finishes commits, so every try writes - // a value of its own and the final check counts only that value. If no size fits, the test fails - // rather than pass without reaching the path. + // is filled on the app's connection, which has no time limit, and sized to this machine by bisection + // between lo, the largest size whose copy finished within the limit, and hi, the smallest size whose + // first step was too slow: halved while the first step (timed with a statement that stops after one row) + // takes over 1 s, doubled while copying every row out finishes within the limit, and the middle once both + // bounds are known. Each try that finishes commits, so every try writes a value of its own and the final + // check counts only that value. The limit must strike while rows are being copied: a trace on the server connection + // (Helper.traceRows) counts the rows SQLite handed out, and 0 means the first step was cut instead (too + // slow: that size is a new hi). If no size fits, the test fails rather than pass without reaching the path. eq(Helper.exec(app, "CREATE TABLE big(id INTEGER PRIMARY KEY, v, a, b, c, d, e, f, g, h)"), 0, "the app creates big"); long bigRows = 0; long target = 400000; long value = 0; long firstStep = -1; long fastCopy = -1; - boolean shrunk = false; + long lo = 0; + long hi = Long.MAX_VALUE; boolean reached = false; + StringBuilder sizes = new StringBuilder(); for (int tries = 0; tries < 12 && !reached; tries++) { if (target > bigRows) { eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT " + (bigRows + 1) + " UNION ALL SELECT x + 1 FROM c WHERE x < " + target + ") " @@ -324,30 +329,48 @@ static void returningCaps(long w, long r, long app) throws Exception { eq(e.sqliteCode, 9, "only the time limit stops the first step: SQLITE_INTERRUPT"); firstStep = Long.MAX_VALUE; } + sizes.append(bigRows).append(" rows: first step ").append(firstStep == Long.MAX_VALUE ? "cut" : firstStep + " ms"); if (firstStep > 1000) { + hi = bigRows; if (bigRows < 25000) break; - target = bigRows / 2; - shrunk = true; + target = lo > 0 ? (lo + hi) / 2 : bigRows / 2; + if (target <= lo) break; // lo and hi are next to each other: no size between them + sizes.append("; "); continue; } long copyValue = ++value; t = System.currentTimeMillis(); + Helper.traceRows(w, true); try { run(w, "UPDATE big SET v = " + copyValue + " RETURNING *", null, 1 << 30, 4096, 1024, 1 << 30, FAR); - // copying finished within the limit (a fast machine): double the table, unless that size was + // copying finished within the limit (a fast machine): grow the table, up to a size that was // already too slow for the first step fastCopy = System.currentTimeMillis() - t; - if (shrunk || bigRows >= 3200000) break; - target = bigRows * 2; + sizes.append(", copy ").append(fastCopy).append(" ms; "); + lo = bigRows; + if (bigRows >= 3200000) break; + target = hi == Long.MAX_VALUE ? bigRows * 2 : (lo + hi) / 2; + if (target <= lo) break; } catch (DebugEngineException e) { eq(e.sqliteCode, 9, "stopped while its rows came back: SQLITE_INTERRUPT"); check(e.getMessage().contains("rolled back"), "the message says it was rolled back: " + e.getMessage()); eq(q(r, "SELECT count(*) FROM big WHERE v = " + copyValue).rows.get(0)[0], 0L, "and nothing was kept, though rows had come back"); - reached = true; + long copied = Helper.tracedRows(); + if (copied > 0) { + check(copied < bigRows, "the limit struck before every row came back: " + copied + " of " + bigRows); + reached = true; + } else { + // no row came back: the first step was cut, so this size is too slow for it + sizes.append(", cut in its first step; "); + hi = bigRows; + if (bigRows < 25000) break; + target = lo > 0 ? (lo + hi) / 2 : bigRows / 2; + if (target <= lo) break; + } } } - check(reached, "the time limit struck while rows came back: big has " + bigRows + " rows, the first step took " + firstStep - + " ms, and copying every row out last finished in " + fastCopy + " ms"); + check(reached, "the time limit struck while rows came back: tried " + sizes + " (lo " + lo + ", hi " + (hi == Long.MAX_VALUE ? "none" : hi) + + "); copying every row out last finished in " + fastCopy + " ms"); System.out.println("RETURNING time limit: " + bigRows + " rows, first step " + firstStep + " ms"); eq(Helper.exec(app, "DROP TABLE big"), 0, "the app drops big"); } diff --git a/subprojects/sqlite-debugger/src/test/jni/helper.c b/subprojects/sqlite-debugger/src/test/jni/helper.c index d42983c3cd..acd5419d82 100644 --- a/subprojects/sqlite-debugger/src/test/jni/helper.c +++ b/subprojects/sqlite-debugger/src/test/jni/helper.c @@ -67,3 +67,31 @@ JNIEXPORT jint JNICALL Java_Helper_autocommit(JNIEnv *e, jclass c, jlong db) { (void)c; return sqlite3_get_autocommit((sqlite3 *)(intptr_t)db); } + +static volatile long traced_rows; + +static int count_rows(unsigned type, void *c, void *p, void *x) { + (void)c; + (void)p; + (void)x; + if (type == SQLITE_TRACE_ROW) traced_rows++; + return 0; +} + +// Counts the rows sqlite3_step hands out on db from now on (SQLITE_TRACE_ROW), starting at 0, or stops counting (on +// false). Only for a server connection, which the extension does not trace; an app connection's own trace would be +// replaced. +JNIEXPORT jint JNICALL Java_Helper_traceRows(JNIEnv *e, jclass c, jlong db, jboolean on) { + (void)e; + (void)c; + traced_rows = 0; + return sqlite3_trace_v2((sqlite3 *)(intptr_t)db, on ? SQLITE_TRACE_ROW : 0, on ? count_rows : 0, 0); +} + +// The rows counted since traceRows(db, true): rows SQLite returned, so 0 means the statement never got past its +// first step. +JNIEXPORT jlong JNICALL Java_Helper_tracedRows(JNIEnv *e, jclass c) { + (void)e; + (void)c; + return traced_rows; +} From 5d8acf62d8211922906e33e2f999f6493c1df2b9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 16:20:35 -0800 Subject: [PATCH 29/45] ADFA-7296 Fix CodeRabbit findings: no big-blob reads, unknown changes, BUSY resume, cut rows - F02: read sqlite3_column_bytes first; a TEXT/BLOB over 1 MiB that does not fit the limits is recorded by size only (cut), never read, so a zeroblob is not materialized on the app's statement. - F04: PROFILE of a statement that had not finished (sqlite3_stmt_busy) reports changes -1. - F05: keep the slot after a SQLITE_BUSY first step so the resumed execution's rows are recorded. - F06: count a row as recorded only if a ROW event was added; otherwise set ROWS_CUT. - F09: NULL-check find_event results in the host tests. - F03: README note that row events do not identify their statement. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 7 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 45 +++-- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 7 +- .../sqlitedebugger/engine/DebugEngine.kt | 3 +- .../src/test/c/sqlitedbg_test.c | 159 +++++++++++++++++- 5 files changed, 198 insertions(+), 23 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index c8371a91d7..5701c3f0ba 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -31,10 +31,11 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer hands the bytes to Kotlin unchanged, so `EventDecoder.kt` mirrors the layout, field offsets included: change both together. A committed fixture pins them (see Testing). **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). -- A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and a statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). +- A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). - `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). -- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. -- The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. +- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. +- The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. +- Row events do not identify the statement they belong to. Rows of statements stepped interleaved on one connection cannot be attributed to one statement; a later change (an execution id) is planned. - Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). ## Decisions that shape it diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index cf60e234d8..698c6c03e3 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -27,6 +27,10 @@ SQLITE_EXTENSION_INIT1 #define RECORD_HEADER_BYTES 72u #define ROW_HEADER_BYTES 8u #define ROW_VALUE_BYTES 12u +// A TEXT or BLOB value larger than this, and larger than what the row can keep, is not read at all: +// sqlite3_column_blob/text can materialize it (a zeroblob is virtual until read) on the app's own +// statement, with a copy of its size and an allocation that could fail there. +#define ROW_READ_MAX_BYTES ((size_t)1 << 20) _Static_assert(sizeof(sqlitedbg_event_record) == RECORD_HEADER_BYTES, "event record layout"); _Static_assert(sizeof(sqlitedbg_row_header) == ROW_HEADER_BYTES, "row header layout"); @@ -221,17 +225,18 @@ static size_t put_value(unsigned char *out, uint8_t type, uint8_t cut, uint32_t return sizeof v; } -// Records the row the statement is on. Each column is read with the accessor of its own type, so -// nothing is converted and the app's later sqlite3_column_type and values are unchanged. -static void record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { +// Records the row the statement is on; returns 1 if a ROW event was added, 0 if not (the byte limit +// is below a row header, or an allocation failed). Each column is read with the accessor of its own +// type, so nothing is converted and the app's later sqlite3_column_type and values are unchanged. +static int record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { uint32_t max_value = __atomic_load_n(&g_max_value, __ATOMIC_RELAXED); size_t budget = __atomic_load_n(&g_max_row, __ATOMIC_RELAXED); // A record must fit beside a pad in the ring (see sqlitedbg_install). size_t ring_max = g_cap / 2 > RECORD_HEADER_BYTES ? g_cap / 2 - RECORD_HEADER_BYTES : 0; if (budget > ring_max) budget = ring_max; - if (budget < ROW_HEADER_BYTES) return; + if (budget < ROW_HEADER_BYTES) return 0; unsigned char *data = (unsigned char *)malloc(budget); - if (!data) return; + if (!data) return 0; int columns = sqlite3_column_count(stmt); size_t len = ROW_HEADER_BYTES; uint32_t kept = 0; @@ -252,11 +257,15 @@ static void record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { } len += put_value(v, (uint8_t)type, 0, 8, 8) + 8; } else if (type == SQLITE_TEXT || type == SQLITE_BLOB) { - // For TEXT, sqlite3_column_text first and then sqlite3_column_bytes, as SQLite advises. - const void *p = type == SQLITE_TEXT ? (const void *)sqlite3_column_text(stmt, i) : sqlite3_column_blob(stmt, i); + // The size first: sqlite3_column_bytes does not copy a stored value, and it is how a huge + // one is recognised before anything reads it (see ROW_READ_MAX_BYTES). The pointer + // accessor then asks for the type the value already has, so nothing is converted. size_t full = (size_t)sqlite3_column_bytes(stmt, i); size_t limit = room < max_value ? room : max_value; - // p is NULL when SQLite is out of memory; utf8_cut would read through it. + const void *p = NULL; + if (full <= limit || full <= ROW_READ_MAX_BYTES) + p = type == SQLITE_TEXT ? (const void *)sqlite3_column_text(stmt, i) : sqlite3_column_blob(stmt, i); + // p is NULL for a value left unread and when SQLite is out of memory; utf8_cut would read through it. size_t stored = !p ? 0 : type == SQLITE_TEXT ? utf8_cut((const char *)p, full, limit) : (full < limit ? full : limit); uint8_t cut = stored < full; if (cut) flags |= SQLITEDBG_EVENT_TRUNCATED; @@ -272,6 +281,7 @@ static void record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { memcpy(data, &h, sizeof h); add_record(SQLITEDBG_EVENT_ROW, cs->id, -1, number, -1, flags, data, len); free(data); + return 1; } // sqlite3_trace_v2 callback. C is the connection's conn_state, which lives until SQLite frees the @@ -315,6 +325,9 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { if (!is_trigger) claim_slot(cs, stmt)->total_changes = sqlite3_total_changes64(sqlite3_db_handle(stmt)); } else { stmt_slot *slot = find_slot(cs, stmt); + // Still busy: the statement did not finish, because it was reset or finalized before its + // last step, or its step returned SQLITE_BUSY. + int unfinished = sqlite3_stmt_busy(stmt); if (slot) { rows = slot->rows; if (slot->rows_cut) flags |= SQLITEDBG_EVENT_ROWS_CUT; @@ -323,9 +336,16 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { // and DELETE set it: after a CREATE TABLE it still holds the last write's. A total that // did not move means the statement changed nothing. sqlite3 *db = sqlite3_db_handle(stmt); - changes = sqlite3_total_changes64(db) == slot->total_changes ? 0 : sqlite3_changes64(db); + // A statement stopped part way (an INSERT ... RETURNING stepped once) has made only part + // of its changes, or all of them without sqlite3_changes64 knowing: unknown. + if (unfinished) changes = -1; + else changes = sqlite3_total_changes64(db) == slot->total_changes ? 0 : sqlite3_changes64(db); } - memset(slot, 0, sizeof *slot); + // A step that returned SQLITE_BUSY before any row also ends in this event, and SQLite + // fires no other for the execution that resumes when the lock is free: keep the slot, so + // its rows are still counted and recorded. A statement that went on to finish leaves it + // until the statement starts again (claim_slot reuses it) or is evicted. + if (!(unfinished && slot->rows == 0)) memset(slot, 0, sizeof *slot); } } add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, rows, changes, @@ -345,8 +365,9 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { slot->rows_cut = 1; break; } - slot->recorded++; - record_row(cs, stmt, slot->rows); + // Counted only if a ROW event was added; otherwise the cut is flagged, as for the limit. + if (record_row(cs, stmt, slot->rows)) slot->recorded++; + else slot->rows_cut = 1; break; } case SQLITE_TRACE_CLOSE: diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 71c2b23d0f..de9195eb28 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -124,8 +124,10 @@ typedef struct sqlitedbg_event_record { int64_t rows; // SQLITEDBG_EVENT_PROFILE of a statement that may write (sqlite3_stmt_readonly false): the rows // it changed itself, as sqlite3_changes64 counts them (not those changed by triggers or foreign - // key actions); 0 when it changed none, as a CREATE TABLE. -1 for a read-only statement, for the - // other kinds, and when rows is -1. + // key actions); 0 when it changed none, as a CREATE TABLE. -1 (unknown) for a read-only + // statement, for the other kinds, when rows is -1, and when the statement had not finished when + // the event fired (reset or finalized part way, as an INSERT ... RETURNING stepped once, or a step + // that returned SQLITE_BUSY): its count is then partial or not yet set. int64_t changes; } sqlitedbg_event_record; // 72 bytes; the data follows @@ -148,6 +150,7 @@ typedef struct sqlitedbg_row_value { uint32_t stored_bytes; // bytes that follow: 8 for INTEGER (int64) and FLOAT (IEEE double), // 0 for NULL, UTF-8 for TEXT (cut at a character boundary), BLOB bytes uint32_t full_bytes; // the value's whole size (sqlite3_column_bytes for TEXT and BLOB) + // A value over 1 MiB that does not fit the limits is not read: stored_bytes 0, cut 1. } sqlitedbg_row_value; // 12 bytes typedef struct sqlitedbg_read_result { diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 0c3fa07de0..5503a88b27 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -121,7 +121,8 @@ data class Event( /** * [EventKind.PROFILE] of a statement that may write: the rows it changed itself, as * `sqlite3_changes64` counts them (not those changed by triggers); 0 when it changed none. Null for a - * read-only statement and for the other kinds. + * read-only statement, for the other kinds, and when the statement had not finished (reset or finalized + * part way, or its step returned `SQLITE_BUSY`), as the count is then unknown. */ val changes: Long? = null, /** [EventKind.PROFILE]: rows went unrecorded because the statement returned more than the per-statement limit. */ diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index a6300732b8..5a178fb88d 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -557,9 +558,15 @@ static void test_rows(void) { sqlitedbg_set_client_connected(0); read_all(cur, &b); CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); - CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r")->rows, 5); - CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r")->flags, 0); - CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r WHERE i < 3")->rows, 2); + const ev *all = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r"); + const ev *some = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r WHERE i < 3"); + CHECK(all != NULL); + CHECK(some != NULL); + if (all) { + CHECK_EQ(all->rows, 5); + CHECK_EQ(all->flags, 0); + } + if (some) CHECK_EQ(some->rows, 2); batch_free(&b); } @@ -664,8 +671,12 @@ static void test_interleaved_rows(void) { k++; } CHECK_EQ(k, 5); - CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 10 UNION ALL SELECT 20")->rows, 2); - CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'")->rows, 3); + const ev *pa = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 10 UNION ALL SELECT 20"); + const ev *ps = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'"); + CHECK(pa != NULL); + CHECK(ps != NULL); + if (pa) CHECK_EQ(pa->rows, 2); + if (ps) CHECK_EQ(ps->rows, 3); batch_free(&b); // one statement more than there are slots, each started in turn: the oldest loses its slot, so its @@ -749,6 +760,143 @@ static void test_row_limits(void) { CHECK_EQ(sqlitedbg_test_max_row_bytes(), 4096); } +// Peak resident set size in KiB. +static long peak_rss_kb(void) { + struct rusage u; + getrusage(RUSAGE_SELF, &u); + return u.ru_maxrss; +} + +// The CodeRabbit findings on #2332 (ADFA-7296) +static void test_review_fixes(void) { + batch b; + uint64_t cur; + const ev *e; + uint32_t columns; + rv v[2]; + + // F02: a BLOB too big to keep is not read, so the app's statement does not materialize it. A bound + // zeroblob is virtual until sqlite3_column_blob; the app only asks for the size. + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT ?1 /* big blob */", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_bind_zeroblob64(st, 1, 200u << 20), SQLITE_OK); + long before = peak_rss_kb(); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_type(st, 0), SQLITE_BLOB); + CHECK_EQ(sqlite3_column_bytes(st, 0), 200 << 20); + long grew = peak_rss_kb() - before; + if (grew > 50 * 1024) fprintf(stderr, " peak RSS grew %ld KiB\n", grew); + CHECK(grew < 50 * 1024); + sqlite3_finalize(st); + // the same size as TEXT + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT CAST(zeroblob(2000000) AS TEXT) /* big text */", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + sqlite3_finalize(st); + // and a value of exactly 1 MiB is still read, for its prefix up to the 256-byte default limit + exec_ok(g_main, "SELECT zeroblob(1048576) /* 1 MiB blob */"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 3); + size_t k = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + CHECK_EQ(parse_row(&b.events[i], &columns, v, 2), 1); + CHECK(b.events[i].flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK_EQ(v[0].type, k == 1 ? SQLITE_TEXT : SQLITE_BLOB); + CHECK_EQ(v[0].cut, 1); + CHECK_EQ(v[0].full, k == 0 ? 200u << 20 : k == 1 ? 2000000u : 1048576u); + CHECK_EQ(v[0].stored, k == 2 ? 256 : 0); + k++; + } + batch_free(&b); + + // F04: an INSERT ... RETURNING stepped once and reset has inserted both rows, but its count is + // not known yet; run to the end it is exact + exec_ok(g_main, "CREATE TABLE rt(a)"); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO rt VALUES(1),(2) RETURNING a", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_reset(st), SQLITE_OK); + CHECK_EQ(sqlite3_finalize(st), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO rt VALUES(3),(4) RETURNING a", -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + exec_ok(g_main, "SELECT count(*) FROM rt /* four */"); + read_all(cur, &b); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "INSERT INTO rt VALUES(1),(2) RETURNING a"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->changes, -1); + CHECK_EQ(e->rows, 1); + } + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "INSERT INTO rt VALUES(3),(4) RETURNING a"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->changes, 2); + CHECK_EQ(e->rows, 2); + } + batch_free(&b); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT count(*) FROM rt", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 4); + sqlite3_finalize(st); + + // F05: a first step that returns SQLITE_BUSY ends in a PROFILE event; when the lock is gone the + // same execution goes on, and its rows are still numbered and recorded + exec_ok(g_main, "CREATE TABLE bq(a); INSERT INTO bq VALUES(1),(2),(3)"); + sqlite3 *other = open_app(g_db_path); + exec_ok(other, "BEGIN EXCLUSIVE"); + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM bq", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_BUSY); + exec_ok(other, "COMMIT"); + int n = 0; + while (sqlite3_step(st) == SQLITE_ROW) n++; + CHECK_EQ(n, 3); + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + sqlite3_close(other); + read_all(cur, &b); + size_t rows_seen = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + rows_seen++; + CHECK_EQ(b.events[i].rows, (int64_t)rows_seen); + CHECK_EQ(parse_row(&b.events[i], &columns, v, 2), 1); + CHECK_EQ(rv_int(&v[0]), (int64_t)rows_seen); + } + CHECK_EQ(rows_seen, 3); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT a FROM bq"); + CHECK(e != NULL); + if (e) CHECK_EQ(e->rows, 0); + batch_free(&b); + + // F06: a row limit below a row header records nothing, and the profile says rows were left out + sqlitedbg_set_row_capture(1, 0, 7); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + exec_ok(g_main, "SELECT 1 /* no room */"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 1 /* no room */"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->rows, 1); + CHECK(e->flags & SQLITEDBG_EVENT_ROWS_CUT); + } + batch_free(&b); +} + static void test_burst(void) { uint64_t cur = cursor_now(); const int stmts = 2000; @@ -1501,6 +1649,7 @@ int main(int argc, char **argv) { test_changes(); test_interleaved_rows(); test_row_limits(); + test_review_fixes(); printf("# burst\n"); test_burst(); printf("# cursor reset\n"); From 67e301782c5e6d9170d6730f2152dea0281c20dd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 18:02:51 -0800 Subject: [PATCH 30/45] ADFA-7304 DatabaseToolsTest: check the reworded execute text in the execute test 4d02e99c9 put its "read them with query" check in the query test, where `d` doesn't exist, so the test source didn't compile; it belongs beside the execute description's other checks. The pinned "cannot be paged" becomes "or paged (that would write again)", as F08's rewording reads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 eb169c07ae..9f24e3af04 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 @@ -322,7 +322,6 @@ class DatabaseToolsTest { assertTrue(r.getBoolean("has_more")) assertEquals(3, r.getInt("next_offset")) assertTrue(r.getString("note").contains("re-runs")) - assertFalse("omitted rows are not recoverable with query: $d", d.contains("read them with query")) assertTrue( tools .tools() @@ -1535,7 +1534,7 @@ class DatabaseToolsTest { "does not write is refused: use query", "Rows from RETURNING come back as query returns them", "truncated_cell_indexes lists each as [row, column]", - "cannot be paged", + "or paged (that would write again)", "A statement that fails returns no rows", "FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows", "stopped and rolled back after 1.5 s", @@ -1549,6 +1548,7 @@ class DatabaseToolsTest { )) { assertTrue("$text: $d", d.contains(text)) } + assertFalse("omitted rows are not recoverable with query: $d", d.contains("read them with query")) assertTrue( tools .tools() From acd87a1f2642dfc2f8e16d4080528f591e28c0f5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 23:09:07 -0800 Subject: [PATCH 31/45] ADFA-7304 execute: say truly what became of a write whose call failed From a fresh review of the write-outcome reporting (#2332 review R01-R06): - A transaction left open on the server connection (a way past the authorizer, then a refused rollback) is rolled back before execute runs its statement. Before, the write ran inside it, the call reported it written, and the backstop after it rolled it back. - The out-of-memory outcome error is always SQLITE_NOMEM. With finalize's code (an interrupt, say), the tool appended "retry it" to an error that says the write may not have been committed. - A statement that failed before its result could be built reports its own error (a constraint, say), not the allocation failure. - A commit that fails at the row-limit reset says nothing was kept only for a lock, a constraint, a full disk or an interrupt; after an I/O error or corruption it says the change may not have been kept. - The KDoc and the tool note say the error tells whether the write was committed or may not have been. Tests: a seam in the JNI test build (SQLITEDBG_TEST, never in the app's build) fails read_rows as a JNI allocation would, on a column named sqlitedbg_test_oom_names, _row or _result. JniQueryTest covers a write committed at a row and after the last step, nothing claimed before the first step, a failed statement's own error, a failed commit at finalize (an app reader holds SHARED past the cap; SQLite rolls the write back), and a write after a transaction left open. Each fails without its fix: reverting the first three fixes fails 3 checks, and dropping the outcome report fails 3 others. The I/O-error wording has no test. 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 | 63 ++++++++++++++++--- .../sqlitedebugger/engine/DebugEngine.kt | 3 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 2 +- .../src/test/jni/JniQueryTest.java | 57 +++++++++++++++++ subprojects/sqlite-debugger/test.sh | 2 +- 6 files changed, 119 insertions(+), 12 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 8e038cd001..bf31b1cfe8 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -52,7 +52,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **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 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 once it has held its lock for 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`; a wait for the app's lock before that is not counted), 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). +- **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. `execute` also rolls one back before its statement runs, so a write is never left inside a transaction that would roll it back after the call reported it. 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 once it has held its lock for 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`; a wait for the app's lock before that is not counted), 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` come back as `query`'s do, within the same limits (ADFA-7304): at most `max_rows`, the 4 MiB budget with the first row whole, cut cells listed, and `has_more`. There is no `offset`, since paging would run the write again. SQLite makes every change, and buffers every returned row, in the first `sqlite3_step` (ADFA-7304 comment 41621). So a statement stopped at a limit is reset, which commits all of it, `changes` counts every row written, and a failed commit at the reset is the call's error (one that stalled to the cap waiting for another connection's read is reported as a stalled step is: SQLITE_INTERRUPT, "Try it again"). A statement that fails at any step, even while its rows come back, returns only the error and no rows. SQLite rolls it back whole, except that FAIL conflict resolution (`OR FAIL`, `ON CONFLICT FAIL`, `RAISE(FAIL)`) keeps, and in autocommit commits, the rows changed before the failing one; the error then says how many (`sqlite3_changes64`, counted when `sqlite3_total_changes64` moved). Limit: if an allocation fails during or after the read (the JVM's for a row or the result, or SQLite's for a cell), the statement is finalized unfinished, which commits it while the call reports the error; that commit waits for a lock only as long as the step's limit allows, as the busy handler stays set until the finalize. 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 once it has held the write lock for 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. A wait for the app's lock before the statement holds its own is not counted. A wait to commit is: in rollback-journal mode the commit waits for other connections' reads to end, and `execute` replaces the connection's busy timeout with a busy handler that stops at the limit too, so the write lock is not held up to 3 s past it; that error says to try again. A deadline that passes while the statement is prepared (preparing can wait on the app's lock to read the schema) stops it before it starts. 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. @@ -69,7 +69,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, the 1.5 s cap on a write in DELETE and WAL mode while the app writes, binding by name, and RETURNING rows within the limits, including a failed commit at the reset and the time limit striking while rows come back. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, the 1.5 s cap on a write in DELETE and WAL mode while the app writes, binding by name, and RETURNING rows within the limits, including a failed commit at the reset and the time limit striking while rows come back, and what it says of a write when building its result fails (a seam in the test build, `SQLITEDBG_TEST`, fails it as a JNI allocation would). It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index ab83d02aec..444aa443cc 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -563,6 +563,25 @@ static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, // sqlite3_step result and *has_more set when rows were left unread. When *has_more is 0 and *rc is not // SQLITE_DONE the statement failed: the caller reports it and drops the result. NULL with an exception // pending when a JNI allocation failed. +#ifdef SQLITEDBG_TEST +enum { TEST_FAIL_NONE, TEST_FAIL_NAMES, TEST_FAIL_ROW, TEST_FAIL_RESULT }; +// Host tests: a column named sqlitedbg_test_oom_names, _row or _result makes read_rows fail as a JNI +// allocation would: before the first step, at the first row it keeps, or after the last step. +static int test_fail_point(sqlite3_stmt *st) { + static const char *const names[] = {"sqlitedbg_test_oom_names", "sqlitedbg_test_oom_row", + "sqlitedbg_test_oom_result"}; + for (int c = 0; c < sqlite3_column_count(st); c++) { + const char *name = sqlite3_column_name(st, c); + for (int i = 0; name && i < 3; i++) + if (strcmp(name, names[i]) == 0) return i + 1; + } + return TEST_FAIL_NONE; +} +#define TEST_FAILS_AT(point) (fail_at == (point)) +#else +#define TEST_FAILS_AT(point) 0 +#endif + static jobjectArray read_rows(JNIEnv *env, sqlite3_stmt *st, jlong offset, jint max_rows, jint max_text, jint max_blob, jint max_total, int *rc, int *has_more) { jobjectArray result = NULL; @@ -570,6 +589,13 @@ static jobjectArray read_rows(JNIEnv *env, sqlite3_stmt *st, jlong offset, jint size_t cut_n = 0, cut_cap = 0; *rc = SQLITE_OK; *has_more = 0; +#ifdef SQLITEDBG_TEST + int fail_at = test_fail_point(st); + if (TEST_FAILS_AT(TEST_FAIL_NAMES)) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + return NULL; + } +#endif int ncols = sqlite3_column_count(st); jobjectArray columns = (*env)->NewObjectArray(env, ncols, g_string, NULL); @@ -604,6 +630,10 @@ static jobjectArray read_rows(JNIEnv *env, sqlite3_stmt *st, jlong offset, jint *has_more = 1; break; } + if (TEST_FAILS_AT(TEST_FAIL_ROW)) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + goto done; + } jobjectArray row = (*env)->NewObjectArray(env, ncols, g_object, NULL); if (!row) goto done; int64_t row_bytes = 0; @@ -644,6 +674,10 @@ static jobjectArray read_rows(JNIEnv *env, sqlite3_stmt *st, jlong offset, jint row_count++; } + if (TEST_FAILS_AT(TEST_FAIL_RESULT)) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + goto done; + } // {cut cell count, hasMore, then the index of each cut cell} jlongArray counts = (*env)->NewLongArray(env, (jsize)(2 + cut_n)); result = counts ? (*env)->NewObjectArray(env, 4, g_object, NULL) : NULL; @@ -737,8 +771,9 @@ static int throw_if_stopped(JNIEnv *env, const deadline *dl, int rc) { // Replaces the exception pending from a failed allocation while execute built its result, for one that also // says what became of the write, so a caller can tell whether a retry repeats it. The statement had run, and -// finalize (finalize_rc) commits what an unfinished one changed. The pending exception is kept when the -// replacement cannot be built. +// finalize (finalize_rc) commits what an unfinished one changed: execute runs only in autocommit, so a +// finalize that succeeds has committed it. The code stays SQLITE_NOMEM, so no caller takes finalize_rc (an +// interrupt, say) for the cause. The pending exception is kept when the replacement cannot be built. static void report_unfinished_write(JNIEnv *env, int finalize_rc) { char msg[256]; if (finalize_rc == SQLITE_OK) @@ -751,7 +786,7 @@ static void report_unfinished_write(JNIEnv *env, int finalize_rc) { sqlite3_errstr(finalize_rc)); jthrowable pending = (*env)->ExceptionOccurred(env); (*env)->ExceptionClear(env); - throw_engine(env, finalize_rc == SQLITE_OK ? SQLITE_NOMEM : finalize_rc, msg); + throw_engine(env, SQLITE_NOMEM, msg); if (pending && !(*env)->ExceptionCheck(env)) (*env)->Throw(env, pending); } @@ -785,6 +820,9 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the statement started"); goto done; } + // A transaction left open (a way past the authorizer, then a refused rollback) would hold this write + // uncommitted until the backstop below rolled it back, after the call reported it as written. + if (!end_transaction_backstop(env, db)) goto done; if (!prepare_bound(env, db, sql, args, names, &st)) goto done; // Preparing can wait on the app's lock to read the schema. A short write would then run to its // commit before the progress handler's first callback, so check again before it starts. @@ -812,16 +850,27 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin sqlite3_set_last_insert_rowid(db, INT64_MIN); jobjectArray rows = read_rows(env, st, 0, max_rows, max_text, max_blob, max_total, &rc, &has_more); if (!rows) { - report_write_outcome = 1; - goto done; + if (rc == SQLITE_OK || rc == SQLITE_ROW || rc == SQLITE_DONE) { + report_write_outcome = 1; + goto done; + } + // The statement failed before its result was built: that failure, and what SQLite kept of the + // write, are the outcome, not the allocation. + (*env)->ExceptionClear(env); } - if (has_more) { + if (rows && has_more) { // Commits every change, not only those of the rows read; the commit itself can fail. rc = sqlite3_reset(st); if (rc != SQLITE_OK) { if (throw_if_stopped(env, &dl, rc)) goto done; + // SQLite rolls back a commit that fails for a lock, a constraint, a full disk or an interrupt; + // after an I/O error or corruption it cannot say what reached the file. + int primary = rc & 0xff; + int rolled_back = primary == SQLITE_BUSY || primary == SQLITE_LOCKED || primary == SQLITE_CONSTRAINT || + primary == SQLITE_FULL || primary == SQLITE_INTERRUPT; char msg[256]; - snprintf(msg, sizeof msg, "the statement could not be committed, and nothing it changed was kept: %s", + snprintf(msg, sizeof msg, "the statement could not be committed, and %s: %s", + rolled_back ? "nothing it changed was kept" : "what it changed may not have been kept", sqlite3_errmsg(db)); throw_engine(env, rc, msg); goto done; diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index b2e5d8da15..287cc59fac 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -96,7 +96,8 @@ interface ServerConnection : Closeable { * stops it before it starts. A statement that fails, even after rows came back, returns no rows and SQLite * rolls it back, except that FAIL conflict resolution keeps the rows changed before the failing one; the * error counts them. A failure building the result after the write finished (an allocation failure) can leave - * the write committed, so a failed call is not always safe to retry; that error says the write was committed. + * the write committed, so a failed call is not always safe to retry; that error says whether the write was + * committed or may not have been. A transaction left open on the connection is rolled back before the statement runs. * * @throws DebugEngineException as [query] does, and for a statement that does not write * (`sqlite3_stmt_readonly`), a transaction statement, a refused PRAGMA, or a failed commit. 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 de025bae6c..2298038c46 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 @@ -126,7 +126,7 @@ class DatabaseTools internal constructor( const val COMMIT_UNCERTAIN_NOTE = "Limits are best effort: a write cut at the row or size limit is committed in full, and an out-of-memory " + "failure while building the result after the write finished can leave it committed, in which case the error " + - "says so; if an error does not say the write was rolled back, check the data before repeating it." + "says whether it was; if an error does not say the write was rolled back, check the data before repeating it." /** Said by execute's description: the first write to a Room database is refused until acknowledged (ADFA-7299). */ const val ROOM_DESCRIPTION = diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 8364413cff..bbdb12b8bb 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -681,6 +681,53 @@ static void lockWaits(Path dir) throws Exception { eq(Helper.close(a), 0, "waits: close the app connection"); } + static final String COMMITTED = "7 out of memory while reading the rows the statement returned; the write was committed, so do " + + "not repeat it"; + + /** + * #2332 review: what execute says of a write when building its result fails as a JNI allocation would. + * The test build's seam (SQLITEDBG_TEST) fails it on a column named sqlitedbg_test_oom_names, _row or _result. + */ + static void unfinishedWrites(Path dir) throws Exception { + String p = dir.resolve("unfinished.db").toString(); + byte[] bytes = p.getBytes(StandardCharsets.UTF_8); + long a = Helper.open(p); + eq(Helper.exec(a, "CREATE TABLE u(id INTEGER PRIMARY KEY)"), 0, "unfinished: create"); + long w = NativeBridge.openServer(bytes, true); + long r = NativeBridge.openServer(bytes, false); + + // at a row: finalize commits the write, and the error says so + eq(execRefusal(w, "INSERT INTO u(id) VALUES(1), (2) RETURNING id, 0 AS sqlitedbg_test_oom_row"), COMMITTED, + "unfinished: failing at a row, the write was committed"); + eq(q(r, "SELECT count(*) FROM u").rows.get(0)[0], 2L, "unfinished: and both rows are there"); + // after the last step + eq(execRefusal(w, "INSERT INTO u(id) VALUES(3) RETURNING 0 AS sqlitedbg_test_oom_result"), COMMITTED, + "unfinished: failing after the last step, the write was committed"); + eq(q(r, "SELECT count(*) FROM u").rows.get(0)[0], 3L, "unfinished: and its row is there"); + // before the first step the statement had not run: no claim about a write + eq(execRefusal(w, "INSERT INTO u(id) VALUES(4) RETURNING 0 AS sqlitedbg_test_oom_names"), "7 out of memory", + "unfinished: failing before the first step, nothing is claimed"); + eq(q(r, "SELECT count(*) FROM u WHERE id = 4").rows.get(0)[0], 0L, "unfinished: and nothing was written"); + // the statement failed, then its result could not be built: the statement's error is the outcome + String failed = execRefusal(w, "INSERT INTO u(id) VALUES(3) RETURNING 0 AS sqlitedbg_test_oom_result"); + check(failed != null && failed.startsWith("19 ") && failed.contains("UNIQUE constraint failed") && !failed.contains("memory"), + "unfinished: a failed statement reports its own error: " + failed); + + // the commit at finalize fails: an app reader holds SHARED past the 1.5 s cap + eq(Helper.exec(a, "BEGIN"), 0, "unfinished: the app opens a read"); + eq(Helper.exec(a, "SELECT count(*) FROM u"), 0, "unfinished: and holds SHARED"); + String locked = execRefusal(w, "INSERT INTO u(id) VALUES(5) RETURNING id, 0 AS sqlitedbg_test_oom_row"); + eq(Helper.exec(a, "COMMIT"), 0, "unfinished: the app ends its read"); + check(locked != null && locked.startsWith("7 ") && locked.contains("may not have been committed") + && locked.contains("database is locked"), "unfinished: a failed commit says the write may not be committed: " + locked); + eq(Helper.autocommit(w), 1, "unfinished: no transaction is left open"); + eq(q(r, "SELECT count(*) FROM u WHERE id = 5").rows.get(0)[0], 0L, "unfinished: SQLite rolled that write back"); + eq(exec(w, "INSERT INTO u(id) VALUES(6)"), 1L, "unfinished: the next execute writes"); + NativeBridge.close(r); + NativeBridge.close(w); + eq(Helper.close(a), 0, "unfinished: close the app connection"); + } + /** Reads t four times over: far longer than the cap, and it holds the lock from its first step. */ static final String LONG_READ = "SELECT count(*) FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0"; @@ -1031,6 +1078,15 @@ public static void main(String[] a) throws Exception { eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path"); eq(execCode(w, "UPDATE t SET id = id WHERE id = -1; SELECT 1", new Object[0], FAR), 1, "execute's own error is kept"); eq(Helper.autocommit(w), 1, "rolled back after a failed execute"); + // #2332 review: a write is not run inside a transaction left open, which the backstop after it would + // roll back once the call had reported the write; that transaction is rolled back first + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path, before a write"); + eq(execRefusal(w, "INSERT INTO t(id) VALUES(4247)"), null, "execute writes"); + eq(Helper.autocommit(w), 1, "closed after the write"); + long seen = NativeBridge.openServer(bytes, false); + eq(q(seen, "SELECT count(*) FROM t WHERE id = 4247").rows.get(0)[0], 1L, "and the write was committed, as reported"); + NativeBridge.close(seen); + Helper.exec(app, "DELETE FROM t WHERE id = 4247"); eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path, rollback to be refused"); eq(Helper.denyTransactions(w, true), 0, "an authorizer that refuses ROLLBACK, for execute"); eq(execRefusal(w, "DELETE FROM t WHERE id = -1"), "23 a transaction was left open and rolling it back failed: not authorized", @@ -1044,6 +1100,7 @@ public static void main(String[] a) throws Exception { execute(dir, path, app); lockWaits(dir); + unfinishedWrites(dir); nonWalCap(dir, path); diff --git a/subprojects/sqlite-debugger/test.sh b/subprojects/sqlite-debugger/test.sh index ce80e1702a..279bfd1506 100755 --- a/subprojects/sqlite-debugger/test.sh +++ b/subprojects/sqlite-debugger/test.sh @@ -86,7 +86,7 @@ run_jni () { # as requery builds it: everything exported, so dlsym finds sqlite3_auto_extension build gcc -O1 -w -shared -fPIC -DSQLITE_THREADSAFE=2 -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -I"$AMAL" \ "$AMAL/sqlite3.c" -o "$out/lib/libsqlite3x.so" -lpthread -ldl -lm - build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -fvisibility=hidden -I"$AMAL" -I"$CPP" "${jinc[@]}" \ + build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -fvisibility=hidden -DSQLITEDBG_TEST -I"$AMAL" -I"$CPP" "${jinc[@]}" \ "$CPP/sqlitedbg.c" "$CPP/sqlitedbg_jni.c" -Wl,--version-script="$CPP/sqlitedbg.map" \ -o "$out/lib/libsqlitedbg.so" -lpthread -ldl build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -I"$AMAL" "${jinc[@]}" "$jni/helper.c" \ From dd7ee1953149bed5fe5ad3e30acc3b33db0ed836 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 23:49:28 -0800 Subject: [PATCH 32/45] ADFA-7296 README: a query inside a leftover transaction can read stale The backstop rolls back a transaction left open after each query, not before it. So a query that starts inside one (a way past the authorizer, then a refused ROLLBACK) reads in that transaction's snapshot, which in WAL mode can be stale, for that one call. Documented as accepted: queries run on the read-only connection, so the transaction holds no uncommitted writes. execute rolls one back first (#2332, acd87a1f2), where a write was at stake. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 5701c3f0ba..53b9bbd8fa 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -42,7 +42,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. The rollback comes after the statement, so a query that starts inside a transaction left open by a refused rollback reads in that transaction's snapshot, which in WAL mode can be stale, for that one call. This is accepted: it needs a way past the authorizer and then a refused ROLLBACK, and queries run on the read-only connection, so the transaction holds no uncommitted writes. 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). From 559fb199fb94298f0eeb69f229e073cbc95d85e0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 00:11:43 -0800 Subject: [PATCH 33/45] ADFA-7304 execute: a commit that SQLite rolled back says so at finalize too From the cloud session's review of acd87a1f2 (optional nits): - When reading RETURNING rows ran out of memory and the commit at finalize then failed, the error always said the write "may not have been committed". For a lock, a constraint, a full disk or an interrupt SQLite rolls the statement back (sqlite3VdbeHalt calls sqlite3RollbackAll), so it now says nothing was kept, as the row-limit reset already did, and a retry is safe. Both paths share commit_failure_rolled_back(). The I/O-error branch keeps the hedge (not testable here). - README: test.sh builds libsqlitedbg.so as it ships plus the SQLITEDBG_TEST seam. The failed-commit JNI check now expects "nothing it changed was kept"; acd87a1f2's text fails it. test.sh 0 failures (23,037 / 23,036, JNI 690). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../src/main/cpp/sqlitedbg_jni.c | 19 ++++++++++++++----- .../src/test/jni/JniQueryTest.java | 4 ++-- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 0ddadfc6e9..5cb799ff57 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -69,7 +69,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, the 1.5 s cap on a write in DELETE and WAL mode while the app writes, binding by name, and RETURNING rows within the limits, including a failed commit at the reset and the time limit striking while rows come back, and what it says of a write when building its result fails (a seam in the test build, `SQLITEDBG_TEST`, fails it as a JNI allocation would). It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`), plus the `SQLITEDBG_TEST` seam, against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, the 1.5 s cap on a write in DELETE and WAL mode while the app writes, binding by name, and RETURNING rows within the limits, including a failed commit at the reset and the time limit striking while rows come back, and what it says of a write when building its result fails (a seam in the test build, `SQLITEDBG_TEST`, fails it as a JNI allocation would). It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 444aa443cc..e5ab68d7bf 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -769,6 +769,14 @@ static int throw_if_stopped(JNIEnv *env, const deadline *dl, int rc) { return 1; } +// Whether SQLite rolled back a writing statement whose commit failed with rc: it does for a lock, a +// constraint, a full disk or an interrupt; after an I/O error or corruption it cannot say what reached the file. +static int commit_failure_rolled_back(int rc) { + int primary = rc & 0xff; + return primary == SQLITE_BUSY || primary == SQLITE_LOCKED || primary == SQLITE_CONSTRAINT || primary == SQLITE_FULL || + primary == SQLITE_INTERRUPT; +} + // Replaces the exception pending from a failed allocation while execute built its result, for one that also // says what became of the write, so a caller can tell whether a retry repeats it. The statement had run, and // finalize (finalize_rc) commits what an unfinished one changed: execute runs only in autocommit, so a @@ -779,6 +787,11 @@ static void report_unfinished_write(JNIEnv *env, int finalize_rc) { if (finalize_rc == SQLITE_OK) snprintf(msg, sizeof msg, "out of memory while reading the rows the statement returned; the write was committed, so do not repeat it"); + else if (commit_failure_rolled_back(finalize_rc)) + snprintf(msg, sizeof msg, + "out of memory while reading the rows the statement returned; committing the write failed (%.100s), " + "and nothing it changed was kept", + sqlite3_errstr(finalize_rc)); else snprintf(msg, sizeof msg, "out of memory while reading the rows the statement returned; finishing the write failed (%.100s), " @@ -863,11 +876,7 @@ static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstrin rc = sqlite3_reset(st); if (rc != SQLITE_OK) { if (throw_if_stopped(env, &dl, rc)) goto done; - // SQLite rolls back a commit that fails for a lock, a constraint, a full disk or an interrupt; - // after an I/O error or corruption it cannot say what reached the file. - int primary = rc & 0xff; - int rolled_back = primary == SQLITE_BUSY || primary == SQLITE_LOCKED || primary == SQLITE_CONSTRAINT || - primary == SQLITE_FULL || primary == SQLITE_INTERRUPT; + int rolled_back = commit_failure_rolled_back(rc); char msg[256]; snprintf(msg, sizeof msg, "the statement could not be committed, and %s: %s", rolled_back ? "nothing it changed was kept" : "what it changed may not have been kept", diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index bbdb12b8bb..21c927f012 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -718,8 +718,8 @@ static void unfinishedWrites(Path dir) throws Exception { eq(Helper.exec(a, "SELECT count(*) FROM u"), 0, "unfinished: and holds SHARED"); String locked = execRefusal(w, "INSERT INTO u(id) VALUES(5) RETURNING id, 0 AS sqlitedbg_test_oom_row"); eq(Helper.exec(a, "COMMIT"), 0, "unfinished: the app ends its read"); - check(locked != null && locked.startsWith("7 ") && locked.contains("may not have been committed") - && locked.contains("database is locked"), "unfinished: a failed commit says the write may not be committed: " + locked); + check(locked != null && locked.startsWith("7 ") && locked.contains("nothing it changed was kept") + && locked.contains("database is locked"), "unfinished: a commit failed for a lock says nothing was kept: " + locked); eq(Helper.autocommit(w), 1, "unfinished: no transaction is left open"); eq(q(r, "SELECT count(*) FROM u WHERE id = 5").rows.get(0)[0], 0L, "unfinished: SQLite rolled that write back"); eq(exec(w, "INSERT INTO u(id) VALUES(6)"), 1L, "unfinished: the next execute writes"); From f4c3722c377ee7acf4ff0e1616e972e541e1bd80 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 00:48:28 -0800 Subject: [PATCH 34/45] ADFA-7379 SQLite debugger: an 80-byte event record with an execution_id field Layout only. The record header grows from 72 to 80 bytes: execution_id, a uint64_t at offset 72. Interface version 3 to 4. add_record and add_event take the id and return the record's seq; every caller passes 0 here, so EventDecoder reads Event.executionId as null for now. EventDecoder.HEADER_BYTES is 80 and the fixture is regenerated with an 11th column. Tests: offsetof and sizeof asserts in the C test, the decoder reads offset 72, and a record with a 72-byte header is refused. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 + .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 25 +++++---- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 7 ++- .../sqlitedebugger/engine/DebugEngine.kt | 6 ++ .../sqlitedebugger/engine/EventDecoder.kt | 6 +- .../src/test/c/sqlitedbg_test.c | 12 +++- .../sqlitedebugger/engine/EventDecoderTest.kt | 27 +++++++-- .../sqlitedebugger/engine/FakeDebugEngine.kt | 5 +- .../sqlitedebugger/engine/events.bin | Bin 2760 -> 2968 bytes .../sqlitedebugger/engine/events.tsv | 52 +++++++++--------- 10 files changed, 94 insertions(+), 48 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 53b9bbd8fa..6574c2002e 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -30,6 +30,8 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer hands the bytes to Kotlin unchanged, so `EventDecoder.kt` mirrors the layout, field offsets included: change both together. A committed fixture pins them (see Testing). +**Execution id (ADFA-7379, interface version 4).** The header grew from 72 to 80 bytes: `execution_id` is a `uint64_t` at offset 72, after `changes`; the earlier fields kept their offsets. A 72-byte producer read by the 80-byte `EventDecoder` throws `IllegalArgumentException`: both ship in one AAR, so that pairing does not occur. The field is 0 (none or unknown) until a later change fills it. + **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). - A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). - `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 698c6c03e3..b1394c2927 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -24,7 +24,7 @@ SQLITE_EXTENSION_INIT1 #define DEFAULT_MAX_SQL_BYTES 4096u #define DEFAULT_MAX_VALUE_BYTES 256u #define DEFAULT_MAX_ROW_BYTES 4096u -#define RECORD_HEADER_BYTES 72u +#define RECORD_HEADER_BYTES 80u #define ROW_HEADER_BYTES 8u #define ROW_VALUE_BYTES 12u // A TEXT or BLOB value larger than this, and larger than what the row can keep, is not read at all: @@ -33,6 +33,7 @@ SQLITE_EXTENSION_INIT1 #define ROW_READ_MAX_BYTES ((size_t)1 << 20) _Static_assert(sizeof(sqlitedbg_event_record) == RECORD_HEADER_BYTES, "event record layout"); +_Static_assert(offsetof(sqlitedbg_event_record, execution_id) == 72, "execution_id offset"); _Static_assert(sizeof(sqlitedbg_row_header) == ROW_HEADER_BYTES, "row header layout"); _Static_assert(sizeof(sqlitedbg_row_value) == ROW_VALUE_BYTES, "row value layout"); @@ -159,8 +160,8 @@ static size_t utf8_cut(const char *sql, size_t len, size_t max) { } // Adds one record with `len` bytes of data, already within the limits. -static void add_record(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, - uint32_t flags, const void *data, size_t len) { +static uint64_t add_record(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, + uint32_t flags, const void *data, size_t len, uint64_t exec_id) { int64_t time = now_ns(); int64_t tid = this_thread_id(); size_t need = (RECORD_HEADER_BYTES + len + 7) & ~(size_t)7; @@ -181,6 +182,7 @@ static void add_record(uint32_t kind, uint64_t connection_id, int64_t duration_n r->data_bytes = (uint32_t)len; r->rows = rows; r->changes = changes; + r->execution_id = exec_id; memcpy((unsigned char *)r + RECORD_HEADER_BYTES, data, len); memset((unsigned char *)r + RECORD_HEADER_BYTES + len, 0, need - RECORD_HEADER_BYTES - len); g_head += need; @@ -188,13 +190,14 @@ static void add_record(uint32_t kind, uint64_t connection_id, int64_t duration_n if (g_head >= g_cap) g_head = 0; } pthread_mutex_unlock(&g_lock); + return seq; } -static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, - uint32_t flags, const char *sql, size_t sql_len) { +static uint64_t add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, + uint32_t flags, const char *sql, size_t sql_len, uint64_t exec_id) { size_t kept = utf8_cut(sql, sql_len, g_max_sql); if (kept < sql_len) flags |= SQLITEDBG_EVENT_TRUNCATED; - add_record(kind, connection_id, duration_ns, rows, changes, flags, sql, kept); + return add_record(kind, connection_id, duration_ns, rows, changes, flags, sql, kept, exec_id); } static stmt_slot *find_slot(conn_state *cs, sqlite3_stmt *stmt) { @@ -228,7 +231,7 @@ static size_t put_value(unsigned char *out, uint8_t type, uint8_t cut, uint32_t // Records the row the statement is on; returns 1 if a ROW event was added, 0 if not (the byte limit // is below a row header, or an allocation failed). Each column is read with the accessor of its own // type, so nothing is converted and the app's later sqlite3_column_type and values are unchanged. -static int record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { +static int record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number, uint64_t exec_id) { uint32_t max_value = __atomic_load_n(&g_max_value, __ATOMIC_RELAXED); size_t budget = __atomic_load_n(&g_max_row, __ATOMIC_RELAXED); // A record must fit beside a pad in the ring (see sqlitedbg_install). @@ -279,7 +282,7 @@ static int record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { if (kept < (uint32_t)columns) flags |= SQLITEDBG_EVENT_TRUNCATED; sqlitedbg_row_header h = {(uint32_t)columns, kept}; memcpy(data, &h, sizeof h); - add_record(SQLITEDBG_EVENT_ROW, cs->id, -1, number, -1, flags, data, len); + add_record(SQLITEDBG_EVENT_ROW, cs->id, -1, number, -1, flags, data, len, exec_id); free(data); return 1; } @@ -349,7 +352,7 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { } } add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, rows, changes, - flags, sql, strlen(sql)); + flags, sql, strlen(sql), 0); if (expanded) sqlite3_free(expanded); break; } @@ -366,14 +369,14 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { break; } // Counted only if a ROW event was added; otherwise the cut is flagged, as for the limit. - if (record_row(cs, stmt, slot->rows)) slot->recorded++; + if (record_row(cs, stmt, slot->rows, 0)) slot->recorded++; else slot->rows_cut = 1; break; } case SQLITE_TRACE_CLOSE: // The close can still fail or leave a zombie, so only mark it: xDestroy frees. __atomic_store_n(&cs->closing, 1, __ATOMIC_RELAXED); - add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, -1, -1, 0, "", 0); + add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, -1, -1, 0, "", 0, 0); break; } return 0; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index de9195eb28..3242bbab74 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -23,7 +23,8 @@ extern "C" { #endif // The interface version. Raise it when anything below changes shape. -#define SQLITEDBG_INTERFACE_VERSION 3 +// 4: the event record has execution_id (72 to 80 bytes). +#define SQLITEDBG_INTERFACE_VERSION 4 // sqlite3_auto_extension's type. On a device the JNI layer looks it up in libsqlite3x.so with // dlsym (requery exports every sqlite3_ function); host tests pass SQLite's own. @@ -129,7 +130,9 @@ typedef struct sqlitedbg_event_record { // the event fired (reset or finalized part way, as an INSERT ... RETURNING stepped once, or a step // that returned SQLITE_BUSY): its count is then partial or not yet set. int64_t changes; -} sqlitedbg_event_record; // 72 bytes; the data follows + // The run of a statement this event belongs to (see the README); 0: none or unknown. + uint64_t execution_id; +} sqlitedbg_event_record; // 80 bytes; the data follows // How many statements per connection the extension follows at once, to number their rows and count // their changes. A connection that steps more statements in turn than this loses the oldest: diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 5503a88b27..0ed4b115f3 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -129,6 +129,12 @@ data class Event( val rowsCut: Boolean = false, /** [EventKind.ROW] only: the row's values. */ val row: RowValues? = null, + /** + * The run of a statement this event belongs to: the [seq] of its [EventKind.STATEMENT] event, on that + * event and on the [EventKind.PROFILE] and [EventKind.ROW] events of the run. Null when there is none or + * it is unknown, and for [EventKind.CLOSE]. + */ + val executionId: Long? = null, ) data class RowValues( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt index 2e8c51132e..cff1a45cb2 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -10,7 +10,7 @@ import java.nio.ByteOrder */ internal object EventDecoder { /** `sizeof(sqlitedbg_event_record)`. */ - const val HEADER_BYTES = 72 + const val HEADER_BYTES = 80 private const val OFFSET_RECORD_BYTES = 0 private const val OFFSET_KIND = 4 @@ -23,6 +23,7 @@ internal object EventDecoder { private const val OFFSET_DATA_BYTES = 52 private const val OFFSET_ROWS = 56 private const val OFFSET_CHANGES = 64 + private const val OFFSET_EXECUTION_ID = 72 private const val FLAG_TRUNCATED = 1 private const val FLAG_EXPANDED = 2 @@ -68,6 +69,8 @@ internal object EventDecoder { // -1 in the record: does not apply, or the extension did not see the statement start val rows = buffer.getLong(offset + OFFSET_ROWS).takeIf { it >= 0 && (kind == EventKind.PROFILE || kind == EventKind.ROW) } val changes = buffer.getLong(offset + OFFSET_CHANGES).takeIf { it >= 0 && kind == EventKind.PROFILE } + // 0 in the record: none or unknown; CLOSE never has one + val executionId = buffer.getLong(offset + OFFSET_EXECUTION_ID).takeIf { it != 0L && kind != EventKind.CLOSE } events += Event( seq = buffer.getLong(offset + OFFSET_SEQ), @@ -83,6 +86,7 @@ internal object EventDecoder { changes = changes, rowsCut = kind == EventKind.PROFILE && flags and FLAG_ROWS_CUT != 0, row = if (kind == EventKind.ROW) decodeRow(bytes, buffer, dataStart, dataBytes) else null, + executionId = executionId, ) offset += recordBytes } diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 5a178fb88d..45074fa90a 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -19,6 +19,9 @@ #include "sqlite3.h" #include "sqlitedbg.h" +_Static_assert(offsetof(sqlitedbg_event_record, execution_id) == 72, "execution_id offset"); +_Static_assert(sizeof(sqlitedbg_event_record) == 80, "event record size"); + static int g_failures; static int g_checks; @@ -74,6 +77,7 @@ typedef struct ev { uint32_t kind, flags; uint64_t seq, conn; int64_t tid, time_ns, duration_ns, rows, changes; + uint64_t exec_id; char sql[MAX_ROW_DATA + 8]; // SQL text, or a row's data for SQLITEDBG_EVENT_ROW uint32_t data_bytes; } ev; @@ -122,6 +126,7 @@ static void read_all(uint64_t after, batch *b) { e->duration_ns = rec->duration_ns; e->rows = rec->rows; e->changes = rec->changes; + e->exec_id = rec->execution_id; e->data_bytes = rec->data_bytes; memcpy(e->sql, (const char *)buf + off + sizeof *rec, rec->data_bytes); e->sql[rec->data_bytes] = 0; @@ -1495,11 +1500,12 @@ static int write_row_data(FILE *f, const unsigned char *d, size_t n) { return off == n; } -// seq, kind, connection, thread, time, duration, flags, rows, changes, then the SQL or the row data. +// seq, kind, connection, thread, time, duration, flags, rows, changes, execution id, then the SQL or the row data. static int write_tsv_row(FILE *f, const sqlitedbg_event_record *r, const char *data) { - fprintf(f, "%llu\t%u\t%llu\t%lld\t%lld\t%lld\t%u\t%lld\t%lld\t", (unsigned long long)r->seq, r->kind, + fprintf(f, "%llu\t%u\t%llu\t%lld\t%lld\t%lld\t%u\t%lld\t%lld\t%llu\t", (unsigned long long)r->seq, r->kind, (unsigned long long)r->connection_id, (long long)r->thread_id, (long long)r->time_ns, - (long long)r->duration_ns, r->flags, (long long)r->rows, (long long)r->changes); + (long long)r->duration_ns, r->flags, (long long)r->rows, (long long)r->changes, + (unsigned long long)r->execution_id); int ok = 1; if (r->kind == SQLITEDBG_EVENT_ROW) ok = write_row_data(f, (const unsigned char *)data, r->data_bytes); else fprintf(f, "%.*s", (int)r->data_bytes, data); diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index 50e584a018..d3b50278ae 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -9,13 +9,13 @@ import java.nio.ByteOrder class EventDecoderTest { // events.bin is what sqlitedbg_read_events copied out in sqlitedbg_test.c (test.sh --update-fixture); // events.tsv is the same records as the C struct reads them: seq, kind, connection, thread, time, - // duration, flags, rows, changes, then the SQL or, for a row, its values (see write_row_data there). + // duration, flags, rows, changes, execution id, then the SQL or, for a row, its values (see write_row_data there). private val bytes = resource("events.bin") private val table = String(resource("events.tsv"), Charsets.UTF_8) .trimEnd('\n') .split('\n') - .map { it.split('\t', limit = 10) } + .map { it.split('\t', limit = 11) } private fun resource(name: String): ByteArray = checkNotNull(javaClass.getResourceAsStream(name)) { "missing fixture $name" }.use { it.readBytes() } @@ -37,12 +37,13 @@ class EventDecoderTest { assertThat(event.rowsCut).isEqualTo(row[6].toInt() and 4 != 0) assertThat(event.rows).isEqualTo(row[7].toLong().takeIf { it >= 0 }) assertThat(event.changes).isEqualTo(row[8].toLong().takeIf { it >= 0 }) + assertThat(event.executionId).isEqualTo(row[9].toLong().takeIf { it != 0L && event.kind != EventKind.CLOSE }) if (event.kind == EventKind.ROW) { assertThat(event.sql).isEmpty() - assertRow(event.row, row[9]) + assertRow(event.row, row[10]) } else { assertThat(event.row).isNull() - assertThat(event.sql).isEqualTo(row[9]) + assertThat(event.sql).isEqualTo(row[10]) } } } @@ -99,6 +100,24 @@ class EventDecoderTest { assertThat(events.map { it.seq }).isInOrder() } + @Test + fun `the header is 80 bytes and the execution id sits at offset 72`() { + assertThat(EventDecoder.HEADER_BYTES).isEqualTo(80) + val copy = bytes.copyOf() + ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN).putLong(72, 77) + assertThat(EventDecoder.decode(copy, copy.size).first().executionId).isEqualTo(77) + } + + @Test + fun `a record with a 72-byte header is refused`() { + // a producer built before interface version 4: header 72 bytes, no data + val old = ByteBuffer.allocate(72).order(ByteOrder.LITTLE_ENDIAN) + old.putInt(0, 72) + old.putInt(4, EventKind.CLOSE.nativeValue) + + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(old.array(), 72) } + } + @Test fun `a prefix ending on a record boundary decodes to those records`() { val firstRecordBytes = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(0) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index e984b7b418..003408819f 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -44,9 +44,12 @@ class FakeDebugEngine( sql: String, connectionId: Long = 1, durationNanos: Long? = null, + executionId: Long? = null, ) { lastSeq++ - buffered.addLast(Event(lastSeq, kind, connectionId, 1, lastSeq, durationNanos, sql, false, clientConnected)) + buffered.addLast( + Event(lastSeq, kind, connectionId, 1, lastSeq, durationNanos, sql, false, clientConnected, executionId = executionId), + ) } /** Adds [event] as the next one, numbered after the events before it whatever its own [Event.seq]. */ diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin index a1b0e7d07a40a05b0deebfba529d9a5f5d716bce..43e63094262f16d193ee0aeb3581261b5f9e8fc8 100644 GIT binary patch literal 2968 zcmb_eOK1~O6di5-)GvyKZYqPDB#@LusNzPG)M*XIM3RY!xUjV~SyZ#pHmIN$mkNTv zR{J$I+FC!juq(l~u0#;Qjaxx+BXr?X)O+U5)l9}4wR*{&n|brzJ?Gr_naOFIwut=N z(OSBy|A@mMy$D)I_;KT`0v`&4_5!ea94 z0#5U}%N9;Jx>gOKD{v&Mh66qQ0#1JBic3!e^=BO%88?NVHw2vV`T>U?)cEi9Z26(*rhqeA8nkejGvo06pXpIJ z=sPIjP3iL^{bxNqKSKge>9fLN{*1#qD%U|Z z9E=$ja8kR+TzcxMKj-JjJSx_8cRs7O5bGHcaHg}97Eby80ghx6&LtWEJ);87*T%;V zJ?I-IXB`}=$uh=C#oF486m6m7dZg8)fA)e;Ca|rdMq4bwP4-?R>9pOz2WxFi;M2G3 znL{`8QRwdLzw*I60OOXx=Y4j@Q6DgF?q$bM( z0p0vL2bxx(R^%TS^7lS<=ifyAIWI>mIbA5fQ;M2C>$E)9)!S709=I*wHqOskx;QT) z>cmzC^Eu?>bzBl~>Smui>W94B$ypai#^U`?2h0L~n#Sw+j=-n*M)6@h=EHjb zH=q3kgxq&+KBwvwGQambPrq=~2TzxiGY^hxl&0DB2_Y}`>x7WE=Yq=1;}DVeH#$Rm zsZS00q>#6G)yi+p)~+!N+wWBjEg`t{9C&3=9#dHj086KoH51P=#0 zgI#o+$i(A%CK01^FGBz9VS#OrC^x>qrUX6*PB{6XUI)pgx-Fq+a6CtS;mgQjm>+Jl z8noJQ4Rr+mQgXaYYwdgFSg~@|YQ%Em^?YC8d*-6z%VU5YCI>c5SU(G{UygD@>jQyL z&s%5xz+oLZ^Wcbf*iQPcpzqk$RB{i!py)7D%^Gl^;h}(&O}=uSU%+7l$8wW!z5{*K BN`?Rc literal 2760 zcmb`JOK1~O6ozkYec%%Xq3#A3Cc&m8f{GiPv`%XvO(dO&V1=o*Di}>r!7fz9f)u-O zTWnF>wIbpsg4l(i_yAXeprBx@)<>;veO4Fh`7?8(H^~X2J>=xf+&S~z|DL(`&e%$+ z3i4-9=Fq=$jCiOD|4I#Yts1QboYBpGgXYb9yR4Q$ZoV;XAp6@;3u_+&#UJ3lCeGZ>e z@&-QZ=I2|EkKES+zv9vUBK^xLpSc_h=4UFs$5{e4Rqfq&|3k5+H+7n5^; z9Q}U7`dw?KGA{SMz|Hg*b61w;>e8LZliSS>bR4NI+?OYW{=TPswdX}$f!8%utPfz; z#S!&JAD@MKZ|~{X#)&>d&A(xQnD~VGBIwAT({(^|D|umkW>Xs+?WiAoE;$VK=eAsfstQ$7BKpPG z6y9Z3?l~Cq7c5+a_@{N#2{>N`owo)YoqP}a4w2&?*i6;SCKkpxE$C>!tJjNC)lzcq ppW`NakJEQxV Date: Tue, 1 Dec 2026 00:55:06 -0800 Subject: [PATCH 35/45] ADFA-7379 SQLite debugger: an execution id on STATEMENT, ROW and PROFILE events Rows of statements stepped interleaved on one connection could not be told apart. A STATEMENT's execution_id is its own seq; the slot keeps it, and the ROW and PROFILE events of the run carry it. 0 means none or unknown. Three guards keep a slot left behind at an address from being taken for another statement's: - a PROFILE for an EXPLAIN (traced with no STATEMENT) releases the slot and gets id 0 and rows -1; - a ROW whose sqlite3_sql is NULL (a schema read) is ignored; - a statement an app function runs inside a callback (traced as "-- " plus its own text) releases the slot at its address and gets id 0. Trigger STATEMENTs carry 0. Tests cover interleaved rows, re-runs, triggers, RETURNING, nested statements, EXPLAIN, BUSY resume, a client connecting mid-run, CLOSE, slot eviction and threads. README: the id's meaning, the PROFILE caveats (EXPLAIN, BUSY: more than one PROFILE per id), the eviction gap and the record size. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 9 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 40 ++- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 6 +- .../src/test/c/sqlitedbg_test.c | 308 +++++++++++++++++- .../sqlitedebugger/engine/EventDecoderTest.kt | 41 +++ .../sqlitedebugger/engine/events.bin | Bin 2968 -> 2968 bytes .../sqlitedebugger/engine/events.tsv | 52 +-- 7 files changed, 418 insertions(+), 38 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 6574c2002e..9c15e55366 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -30,14 +30,17 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer hands the bytes to Kotlin unchanged, so `EventDecoder.kt` mirrors the layout, field offsets included: change both together. A committed fixture pins them (see Testing). -**Execution id (ADFA-7379, interface version 4).** The header grew from 72 to 80 bytes: `execution_id` is a `uint64_t` at offset 72, after `changes`; the earlier fields kept their offsets. A 72-byte producer read by the 80-byte `EventDecoder` throws `IllegalArgumentException`: both ship in one AAR, so that pairing does not occur. The field is 0 (none or unknown) until a later change fills it. +**Execution id (ADFA-7379, interface version 4).** The header grew from 72 to 80 bytes: `execution_id` is a `uint64_t` at offset 72, after `changes`; the earlier fields kept their offsets. A 72-byte producer read by the 80-byte `EventDecoder` throws `IllegalArgumentException`: both ship in one AAR, so that pairing does not occur. +- `execution_id` tells which run of a statement an event belongs to, so rows of statements stepped interleaved on one connection can be told apart. A STATEMENT's id is its own `seq`. The PROFILE and ROW events of that run carry the same id, not their own `seq`, so ids are not contiguous. 0 means none or unknown (Kotlin: `executionId` null; CLOSE never has one). Ids are unique within a process and restart with it, like `seq`. A run that is stepped, reset and stepped again gets a new STATEMENT and a new id each time, and so does a statement prepared again at the same address. +- Events with id 0: a trigger's STATEMENT (its text starts with `-- `, and a STATEMENT whose id equals its `seq` is always the start of a run), a statement an app function runs inside a callback (its STATEMENT and PROFILE; no rows are recorded), an EXPLAIN's PROFILE, and the PROFILE and ROW events of a statement the extension did not see start. A statement evicted from its slot (more than 16 stepped in turn) keeps its id on its STATEMENT, but its later PROFILE and ROW events say 0, so a STATEMENT can have no PROFILE with its id. +- A PROFILE is not a reliable "the run ended" event. An EXPLAIN fires a PROFILE with no STATEMENT. A step that returns `SQLITE_BUSY` fires a PROFILE (rows 0) before any row, and the run that resumes may fire no closing PROFILE; it does fire one if the resumed step hits `SQLITE_SCHEMA`. So one `execution_id` can have more than one PROFILE, and a client must not key on one PROFILE per id. +- Size: records grew from 72 to 80 bytes, about 10% more for an event with little data. The per-row path with no client connected is unchanged (see the benchmark below). **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). - A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). - `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). - Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. -- The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. -- Row events do not identify the statement they belong to. Rows of statements stepped interleaved on one connection cannot be attributed to one statement; a later change (an execution id) is planned. +- The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one; those reads are traced as ROW only and are ignored). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. - Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). ## Decisions that shape it diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index b1394c2927..2abffab775 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -25,6 +25,8 @@ SQLITE_EXTENSION_INIT1 #define DEFAULT_MAX_VALUE_BYTES 256u #define DEFAULT_MAX_ROW_BYTES 4096u #define RECORD_HEADER_BYTES 80u +// add_record: the record's own seq is its execution id. +#define EXEC_SELF UINT64_MAX #define ROW_HEADER_BYTES 8u #define ROW_VALUE_BYTES 12u // A TEXT or BLOB value larger than this, and larger than what the row can keep, is not read at all: @@ -50,6 +52,7 @@ typedef struct stmt_slot { int rows_cut; // a row went unrecorded because of the per-statement limit sqlite3_int64 total_changes; // sqlite3_total_changes64 when it started uint64_t last_use; // for evicting the least recently used slot + uint64_t exec_id; // seq of the STATEMENT record that started this run } stmt_slot; typedef struct conn_state { @@ -182,7 +185,7 @@ static uint64_t add_record(uint32_t kind, uint64_t connection_id, int64_t durati r->data_bytes = (uint32_t)len; r->rows = rows; r->changes = changes; - r->execution_id = exec_id; + r->execution_id = exec_id == EXEC_SELF ? seq : exec_id; memcpy((unsigned char *)r + RECORD_HEADER_BYTES, data, len); memset((unsigned char *)r + RECORD_HEADER_BYTES + len, 0, need - RECORD_HEADER_BYTES - len); g_head += need; @@ -322,17 +325,36 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { } int64_t duration = is_stmt ? -1 : *(sqlite3_int64 *)x; int64_t rows = -1, changes = -1; + uint64_t exec_id = 0; + stmt_slot *claimed = NULL; if (is_stmt) { - // SQLite's own nested statements (the schema read a CREATE TABLE runs, for one) are traced - // with "--" text like a trigger, so they get no slot and their rows are never recorded. - if (!is_trigger) claim_slot(cs, stmt)->total_changes = sqlite3_total_changes64(sqlite3_db_handle(stmt)); + // A trigger's statements are traced with "-- " text and P the outer statement, so they get no + // slot. A schema read sends no STATEMENT at all, and an app statement run inside a callback is + // handled below. + const char *own = sqlite3_sql(stmt); + // A statement the app runs inside a callback is traced as "-- " + its own text, with P the + // statement itself: it claims no slot, and one left at this address is not its. + if (own && !strncmp(sql, "-- ", 3) && !strcmp(sql + 3, own)) { + stmt_slot *old = find_slot(cs, stmt); + if (old) memset(old, 0, sizeof *old); + } + if (!is_trigger) { + claimed = claim_slot(cs, stmt); + claimed->total_changes = sqlite3_total_changes64(sqlite3_db_handle(stmt)); + } } else { stmt_slot *slot = find_slot(cs, stmt); + // An EXPLAIN is traced with no STATEMENT: a slot at its address is another statement's. + if (slot && sqlite3_stmt_isexplain(stmt)) { + memset(slot, 0, sizeof *slot); + slot = NULL; + } // Still busy: the statement did not finish, because it was reset or finalized before its // last step, or its step returned SQLITE_BUSY. int unfinished = sqlite3_stmt_busy(stmt); if (slot) { rows = slot->rows; + exec_id = slot->exec_id; if (slot->rows_cut) flags |= SQLITEDBG_EVENT_ROWS_CUT; if (!sqlite3_stmt_readonly(stmt)) { // sqlite3_changes64 is this statement's count once it has run, but only INSERT, UPDATE @@ -351,13 +373,17 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { if (!(unfinished && slot->rows == 0)) memset(slot, 0, sizeof *slot); } } - add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, rows, changes, - flags, sql, strlen(sql), 0); + uint32_t kind = is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE; + uint64_t seq = add_event(kind, cs->id, duration, rows, changes, flags, sql, strlen(sql), + claimed ? EXEC_SELF : exec_id); + if (claimed) claimed->exec_id = seq; if (expanded) sqlite3_free(expanded); break; } case SQLITE_TRACE_ROW: { sqlite3_stmt *stmt = (sqlite3_stmt *)p; + // A schema read (sqlite3_sql NULL) sends only ROW traces: no slot is theirs. + if (!sqlite3_sql(stmt)) break; stmt_slot *slot = find_slot(cs, stmt); if (!slot) break; slot->rows++; @@ -369,7 +395,7 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { break; } // Counted only if a ROW event was added; otherwise the cut is flagged, as for the limit. - if (record_row(cs, stmt, slot->rows, 0)) slot->recorded++; + if (record_row(cs, stmt, slot->rows, slot->exec_id)) slot->recorded++; else slot->rows_cut = 1; break; } diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 3242bbab74..43f001d478 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -130,7 +130,11 @@ typedef struct sqlitedbg_event_record { // the event fired (reset or finalized part way, as an INSERT ... RETURNING stepped once, or a step // that returned SQLITE_BUSY): its count is then partial or not yet set. int64_t changes; - // The run of a statement this event belongs to (see the README); 0: none or unknown. + // The run of a statement this event belongs to: the seq of its STATEMENT record, on that record + // and on the PROFILE and ROW records of the run. 0: none or unknown (a trigger's STATEMENT, a + // statement nested in a callback, an EXPLAIN, a CLOSE, or a statement the extension did not see + // start). A statement evicted from its slot keeps its id on the STATEMENT only. Not contiguous, + // and restarting with the process like seq. uint64_t execution_id; } sqlitedbg_event_record; // 80 bytes; the data follows diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 45074fa90a..22ac697674 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -467,6 +467,32 @@ static size_t count_kind(const batch *b, uint32_t kind) { return n; } +// The n-th (from 0) event of `kind` whose SQL is `sql`, or NULL. +static const ev *nth_event(const batch *b, uint32_t kind, const char *sql, size_t n) { + for (size_t i = 0; i < b->count; i++) + if (b->events[i].kind == kind && strcmp(b->events[i].sql, sql) == 0 && n-- == 0) return &b->events[i]; + return NULL; +} + +// For statements that ran one after another (no nesting, no trigger): each STATEMENT's execution id +// is its own seq, and each PROFILE and ROW carries that of the STATEMENT before it. Returns the +// number of STATEMENTs. +static size_t check_runs(const batch *b) { + uint64_t run = 0; + size_t n = 0; + for (size_t i = 0; i < b->count; i++) { + const ev *e = &b->events[i]; + if (e->kind == SQLITEDBG_EVENT_STATEMENT) { + CHECK_EQ(e->exec_id, e->seq); + run = e->seq; + n++; + } else if (e->kind == SQLITEDBG_EVENT_PROFILE || e->kind == SQLITEDBG_EVENT_ROW) { + CHECK_EQ(e->exec_id, run); + } + } + return n; +} + static void test_rows(void) { exec_ok(g_main, "CREATE TABLE r(i INTEGER, f REAL, s TEXT, b BLOB, n)"); // row 2's text is 20 two-byte characters (40 bytes) and its blob 40 bytes, both over the 15-byte @@ -663,6 +689,12 @@ static void test_interleaved_rows(void) { read_all(cur, &b); int64_t want_rows[] = {1, 1, 2, 2, 3}; int64_t want_first[] = {10, 'x', 20, 'y', 'z'}; + // the execution id tells which statement a row belongs to: a, s, a, s, s + const ev *sa = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 10 UNION ALL SELECT 20"); + const ev *ss = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'"); + CHECK(sa != NULL && ss != NULL); + CHECK_EQ(b.dropped, 0); + if (sa && ss) CHECK(sa->seq != ss->seq); size_t k = 0; for (size_t i = 0; i < b.count; i++) { if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; @@ -672,6 +704,7 @@ static void test_interleaved_rows(void) { CHECK_EQ(b.events[i].rows, want_rows[k]); CHECK_EQ(first, want_first[k]); CHECK_EQ(type, k == 0 || k == 2 ? SQLITE_INTEGER : SQLITE_TEXT); + if (sa && ss) CHECK_EQ(b.events[i].exec_id, (k == 0 || k == 2 ? sa : ss)->seq); } k++; } @@ -682,6 +715,8 @@ static void test_interleaved_rows(void) { CHECK(ps != NULL); if (pa) CHECK_EQ(pa->rows, 2); if (ps) CHECK_EQ(ps->rows, 3); + if (pa && sa) CHECK_EQ(pa->exec_id, sa->seq); + if (ps && ss) CHECK_EQ(ps->exec_id, ss->seq); batch_free(&b); // one statement more than there are slots, each started in turn: the oldest loses its slot, so its @@ -711,6 +746,14 @@ static void test_interleaved_rows(void) { if (p0) CHECK_EQ(p0->rows, -1); if (p0) CHECK_EQ(p0->changes, -1); if (p1) CHECK_EQ(p1->rows, 2); + // the evicted statement keeps its id on its STATEMENT only; its PROFILE says none + const ev *s0 = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 0 UNION ALL SELECT 0"); + const ev *s1 = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 1 UNION ALL SELECT 1"); + CHECK(s0 && s1); + CHECK_EQ(b.dropped, 0); + if (s0) CHECK_EQ(s0->exec_id, s0->seq); + if (p0) CHECK_EQ(p0->exec_id, 0); + if (s1 && p1) CHECK_EQ(p1->exec_id, s1->seq); batch_free(&b); } @@ -882,6 +925,12 @@ static void test_review_fixes(void) { e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT a FROM bq"); CHECK(e != NULL); if (e) CHECK_EQ(e->rows, 0); + // the rows after the BUSY profile keep the execution id + const ev *bs = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT a FROM bq"); + CHECK(bs != NULL); + if (e && bs) CHECK_EQ(e->exec_id, bs->seq); + for (size_t i = 0; bs && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW) CHECK_EQ(b.events[i].exec_id, bs->seq); batch_free(&b); // F06: a row limit below a row header records nothing, and the profile says rows were left out @@ -902,6 +951,236 @@ static void test_review_fixes(void) { batch_free(&b); } +// A statement run by an app function, on the connection that called it. +static sqlite3_stmt *g_inner; + +static void nested_fn(sqlite3_context *ctx, int argc, sqlite3_value **argv) { + (void)argc; + (void)argv; + int n = 0; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 100 UNION ALL SELECT 200 /* nested */", -1, &g_inner, NULL), SQLITE_OK); + while (sqlite3_step(g_inner) == SQLITE_ROW) n++; + sqlite3_finalize(g_inner); + sqlite3_result_int(ctx, n); +} + +// Leaves a slot behind at the address of a finalized statement: a first step that returns SQLITE_BUSY +// (rows 0, so the slot is kept) and a resumed run to the end, which fires no PROFILE. The address is +// returned so a test can make another statement land on it. +static sqlite3_stmt *leave_stale_slot(sqlite3 *other, const char *sql) { + sqlite3_stmt *st; + exec_ok(other, "BEGIN EXCLUSIVE"); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_BUSY); + exec_ok(other, "COMMIT"); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + return st; +} + +static void test_execution_id(void) { + batch b; + uint64_t cur; + sqlite3_stmt *st; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "CREATE TABLE xe(a); INSERT INTO xe VALUES(1),(2)"); + + // the STATEMENT's execution id is its own seq, and its PROFILE carries it + cur = cursor_now(); + exec_ok(g_main, "SELECT 1 /* own id */"); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(b.count, 3); + CHECK_EQ(check_runs(&b), 1); + const ev *e = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 1 /* own id */"); + if (e) CHECK(e->exec_id != 0); + batch_free(&b); + + // runs of one statement get their own ids: after reset, after stepping past DONE, and after a + // finalize and a prepare of the same text (often at the same address) + cur = cursor_now(); + const char *again = "SELECT a FROM xe /* again */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, again, -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); // a new run, started by stepping past DONE + CHECK_EQ(sqlite3_reset(st), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + CHECK_EQ(sqlite3_prepare_v2(g_main, again, -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(check_runs(&b), 4); + for (size_t i = 0; i < 4; i++) + for (size_t j = i + 1; j < 4; j++) { + const ev *x = nth_event(&b, SQLITEDBG_EVENT_STATEMENT, again, i); + const ev *y = nth_event(&b, SQLITEDBG_EVENT_STATEMENT, again, j); + CHECK(x && y && x->exec_id != y->exec_id); + } + batch_free(&b); + + // a trigger's statements carry no id; a statement an app function runs carries none either, and its + // rows are not recorded (a slot left at its address is not its) + exec_ok(g_main, "CREATE TABLE xt(a); CREATE TABLE xlog(a)"); + exec_ok(g_main, "CREATE TRIGGER xtrg AFTER INSERT ON xt BEGIN INSERT INTO xlog VALUES(new.a); END"); + cur = cursor_now(); + exec_ok(g_main, "INSERT INTO xt VALUES(1)"); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + size_t outer = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_STATEMENT) continue; + if (!strncmp(b.events[i].sql, "-- ", 3)) CHECK_EQ(b.events[i].exec_id, 0); + else { + CHECK_EQ(b.events[i].exec_id, b.events[i].seq); + outer++; + } + } + CHECK_EQ(outer, 1); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "INSERT INTO xt VALUES(1)"); + const ev *os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "INSERT INTO xt VALUES(1)"); + CHECK(e && os); + if (e && os) CHECK_EQ(e->exec_id, os->seq); + batch_free(&b); + + // RETURNING from a statement that fires a trigger: the row keeps the outer id + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO xt VALUES(2) RETURNING a", -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "INSERT INTO xt VALUES(2) RETURNING a"); + CHECK(os != NULL); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 1); + for (size_t i = 0; os && i < b.count; i++) { + if (b.events[i].kind == SQLITEDBG_EVENT_ROW) CHECK_EQ(b.events[i].exec_id, os->seq); + if (b.events[i].kind == SQLITEDBG_EVENT_STATEMENT && !strncmp(b.events[i].sql, "-- ", 3)) + CHECK_EQ(b.events[i].exec_id, 0); + } + batch_free(&b); + + exec_ok(g_main, "CREATE TABLE xb(a); INSERT INTO xb VALUES(1),(2),(3)"); + sqlite3 *other = open_app(g_db_path); + sqlite3_create_function(g_main, "nested_fn", 0, SQLITE_UTF8, NULL, nested_fn, NULL, NULL); + + // a statement run inside an app function, at the address of a stale slot + cur = cursor_now(); + sqlite3_stmt *stale = leave_stale_slot(other, "SELECT a FROM xb /* stale 1 */"); + sqlite3_stmt *filler, *outerst; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 0 /* filler */", -1, &filler, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT nested_fn()", -1, &outerst, NULL), SQLITE_OK); + sqlite3_finalize(filler); // the stale address is free again, for the statement the function prepares + while (sqlite3_step(outerst) == SQLITE_ROW) { + } + sqlite3_finalize(outerst); + CHECK(g_inner == stale); // else this checks nothing + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT nested_fn()"); + CHECK(os != NULL); + e = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "-- SELECT 100 UNION ALL SELECT 200 /* nested */"); + CHECK(e != NULL); + if (e) CHECK_EQ(e->exec_id, 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 100 UNION ALL SELECT 200 /* nested */"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT nested_fn()"); + CHECK(e != NULL); + if (e && os) CHECK_EQ(e->exec_id, os->seq); + // the three rows of the stale statement, one of the outer statement, none of the nested one + size_t outer_rows = 0; + for (size_t i = 0; os && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW && b.events[i].exec_id == os->seq) outer_rows++; + CHECK_EQ(outer_rows, 1); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 4); + batch_free(&b); + + // an EXPLAIN is traced with no STATEMENT: at the address of a stale slot it is not that statement + cur = cursor_now(); + stale = leave_stale_slot(other, "SELECT a FROM xb /* stale 2 */"); + CHECK_EQ(sqlite3_prepare_v2(g_main, "EXPLAIN SELECT 1", -1, &st, NULL), SQLITE_OK); + CHECK(st == stale); // else this checks nothing + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "EXPLAIN SELECT 1"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + batch_free(&b); + + // a schema read (traced as ROW only, sqlite3_sql NULL) after another connection's DDL, with a + // stale slot about: the stale statement keeps just its own three rows. Not known to fail without + // the guard; kept as a regression test. + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM xb WHERE a = 2 /* kept */", -1, &st, NULL), SQLITE_OK); + stale = leave_stale_slot(other, "SELECT a FROM xb /* stale 3 */"); + exec_ok(other, "CREATE TABLE xother(y)"); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT a FROM xb /* stale 3 */"); + CHECK(os != NULL); + size_t stale_rows = 0; + for (size_t i = 0; os && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW && b.events[i].exec_id == os->seq) stale_rows++; + CHECK_EQ(stale_rows, 3); + batch_free(&b); + sqlite3_close(other); + + // a client that connects mid-run: the row recorded after it keeps the STATEMENT's id, though the + // STATEMENT was recorded with no client + sqlitedbg_set_client_connected(0); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM xe /* late client */", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + sqlitedbg_set_client_connected(1); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 1); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT a FROM xe /* late client */"); + CHECK(os != NULL); + for (size_t i = 0; os && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW) { + CHECK_EQ(b.events[i].rows, 2); + CHECK_EQ(b.events[i].exec_id, os->seq); + } + batch_free(&b); + + // CLOSE has no id + cur = cursor_now(); + sqlite3 *c = open_app(":memory:"); + exec_ok(c, "SELECT 1"); + CHECK_EQ(sqlite3_close(c), SQLITE_OK); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_CLOSE), 1); + for (size_t i = 0; i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_CLOSE) CHECK_EQ(b.events[i].exec_id, 0); + batch_free(&b); + + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); +} + static void test_burst(void) { uint64_t cur = cursor_now(); const int stmts = 2000; @@ -1376,6 +1655,7 @@ static void *worker_main(void *arg) { typedef struct reader { atomic_int *stop; + uint64_t first; // read from here: the earlier tests' events have triggers and nested statements int failed; long long reads; } reader; @@ -1385,13 +1665,23 @@ static void list_noop(void *context, const sqlitedbg_connection *c) { if (c->id == 0 || !c->path) *(int *)context = 1; } +// The last STATEMENT's execution id seen on each connection (by id modulo the table size), to check +// that every ROW and PROFILE carries its connection's current one. +#define RUNS 256 +typedef struct run_table { + uint64_t conn[RUNS], run[RUNS]; +} run_table; + static void *reader_main(void *arg) { reader *r = arg; static unsigned char buf[2048]; - uint64_t after = 0; + uint64_t after = r->first; + run_table runs; + memset(&runs, 0, sizeof runs); while (!atomic_load(r->stop)) { sqlitedbg_read_result res; sqlitedbg_read_events(after, buf, sizeof buf, &res); + if (res.dropped) memset(&runs, 0, sizeof runs); size_t off = 0; uint64_t prev = after; for (size_t i = 0; i < res.count; i++) { @@ -1399,6 +1689,20 @@ static void *reader_main(void *arg) { if (rec->seq <= prev || rec->record_bytes % 8 || rec->kind < 1 || rec->kind > 4 || rec->record_bytes < sizeof *rec + rec->data_bytes) r->failed = 1; + // The workers run statements one at a time on each connection, so a STATEMENT's id is its + // seq, later than the connection's last, and its ROWs and PROFILE carry it. Events dropped + // before this read can have taken the STATEMENT, so the table is only trusted after it. + uint64_t slot = rec->connection_id % RUNS; + if (rec->kind == SQLITEDBG_EVENT_STATEMENT) { + if (rec->execution_id != rec->seq) r->failed = 1; + if (runs.conn[slot] == rec->connection_id && runs.run[slot] >= rec->execution_id) r->failed = 1; + runs.conn[slot] = rec->connection_id; + runs.run[slot] = rec->execution_id; + } else if (rec->kind == SQLITEDBG_EVENT_CLOSE) { + if (rec->execution_id != 0) r->failed = 1; + } else if (runs.conn[slot] == rec->connection_id && rec->execution_id != runs.run[slot]) { + r->failed = 1; + } prev = rec->seq; off += rec->record_bytes; } @@ -1428,6 +1732,7 @@ static void test_threads(void) { memset(w, 0, sizeof w); memset(&rd, 0, sizeof rd); rd.stop = &stop; + rd.first = cur; pthread_create(&rt, NULL, reader_main, &rd); for (int i = 0; i < N; i++) { w[i].index = i; @@ -1656,6 +1961,7 @@ int main(int argc, char **argv) { test_interleaved_rows(); test_row_limits(); test_review_fixes(); + test_execution_id(); printf("# burst\n"); test_burst(); printf("# cursor reset\n"); diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index d3b50278ae..28264ea588 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -108,6 +108,47 @@ class EventDecoderTest { assertThat(EventDecoder.decode(copy, copy.size).first().executionId).isEqualTo(77) } + @Test + fun `the fixture's ROW and PROFILE events carry their STATEMENT's id`() { + val events = EventDecoder.decode(bytes, bytes.size) + + var run: Long? = null + for (event in events) { + when { + event.kind == EventKind.STATEMENT && event.sql.startsWith("-- ") -> assertThat(event.executionId).isNull() + event.kind == EventKind.STATEMENT -> { + assertThat(event.executionId).isEqualTo(event.seq) + run = event.seq + } + event.kind == EventKind.CLOSE -> assertThat(event.executionId).isNull() + else -> assertThat(event.executionId).isEqualTo(run) + } + } + assertThat(events.single { it.kind == EventKind.ROW }.executionId).isNotNull() + } + + @Test + fun `ROW records decode their own execution ids`() { + fun rowRecord( + seq: Long, + executionId: Long, + ): ByteArray { + // the header, then an empty row: columns 0, kept 0 + val record = ByteBuffer.allocate(EventDecoder.HEADER_BYTES + EventDecoder.ROW_HEADER_BYTES).order(ByteOrder.LITTLE_ENDIAN) + record.putInt(0, record.capacity()) + record.putInt(4, EventKind.ROW.nativeValue) + record.putLong(8, seq) + record.putInt(52, EventDecoder.ROW_HEADER_BYTES) + record.putLong(56, 1) + record.putLong(64, -1) + record.putLong(72, executionId) + return record.array() + } + val both = rowRecord(5, 77) + rowRecord(6, 91) + rowRecord(7, 0) + + assertThat(EventDecoder.decode(both, both.size).map { it.executionId }).containsExactly(77L, 91L, null).inOrder() + } + @Test fun `a record with a 72-byte header is refused`() { // a producer built before interface version 4: header 72 bytes, no data diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin index 43e63094262f16d193ee0aeb3581261b5f9e8fc8..ababd9573d03759dba458f4de7623706da4ef3fb 100644 GIT binary patch literal 2968 zcmb_e-%Aux6rR$4U}abc($l4vRZ!UtO$^N4bw}A)M_Xr2!$31_p)DZ-_fdN3m!Y;}odyRq~qL(1(Auz(uH#46(vwLv~4}13P+_~p`-*@iZJDW8OV}tm` zH|6r}{ze@BQ;T3MwS^9iR)4Qq_6%dY#Cgrg{EoC4vrT2k;we*&=W9pmkYN~E@r~k_ zG&s8}n;e{Id?%(m2ArUkf&)F5H8^K0nhW&Q$b9NxWPZ}>Gt;(8T6T}fQT?%0#_X$Y zucMwT8l2zrEe_6V{=lJuBdio0%$?TYM8CN>g z&ikcKpB~JOic<$8^QkAD?CLVpvW3p6Sf?$&ya%zz!nTT=T}g{W-d+>wvfaQ3&)Q85 zpFIO9hY!yU@{tsutrs7x12ArB`1EJHefRZdmewb6bOxxL_6FRLXqz zpHYS!YiLmRzcnz7yo{p$9ZmhOGlli{%6!&kbc)ND)b~qqm(MvZ&x}nr2HyjBHMq;; zy^b!{MMVE-;0#-J4dwiNITwK2Q+ZT`c`h&Y$#mR$_`Cfk_s0*F*n!3|3-MTVm#ZWh> zGg!A*=9Gy)(A15*F60XU@?^vqjL*kI&3feC4f^y0J1WjPjLi4+x74eBjm`CZABE~w zJ`^4a9}ka)PlU(h(#oV#Dq|((+>6OCFRh{Vh1AAButyp`AAkD!pkG7c!M>5tCb;KT`0v`&4_5!ea94 z0#5U}%N9;Jx>gOKD{v&Mh66qQ0#1JBic3!e^=BO%88?NVHw2vV`T>U?)cEi9Z26(*rhqeA8nkejGvo06pXpIJ z=sPIjP3iL^{bxNqKSKge>9fLN{*1#qD%U|Z z9E=$ja8kR+TzcxMKj-JjJSx_8cRs7O5bGHcaHg}97Eby80ghx6&LtWEJ);87*T%;V zJ?I-IXB`}=$uh=C#oF486m6m7dZg8)fA)e;Ca|rdMq4bwP4-?R>9pOz2WxFi;M2G3 znL{`8QRwdLzw*I60OOXx=Y4j@Q6DgF?q$bM( z0p0vL2bxx(R^%TS^7lS<=ifyAIWI>mIbA5fQ;M2C>$E)9)!S709=I*wHqOskx;QT) z>cmzC^Eu?>bzBl~>Smui>W94B$ypai#^U`?2h0L~n#Sw+j=-n*M)6@h=EHjb zH=q3kgxq&+KBwvwGQambPrq=~2TzxiGY^hxl&0DB2_Y}`>x7WE=Yq=1;}DVeH#$Rm zsZS00q>#6G)yi+p)~+!N+wWBjEg`t{9C&3=9#dHj086KoH51P=#0 zgI#o+$i(A%CK01^FGBz9VS#OrC^x>qrUX6*PB{6XUI)pgx-Fq+a6CtS;mgQjm>+Jl z8noJQ4Rr+mQgXaYYwdgFSg~@|YQ%Em^?YC8d*-6z%VU5YCI>c5SU(G{UygD@>jQyL z&s%5xz+oLZ^Wcbf*iQPcpzqk$RB{i!py)7D%^Gl^;h}(&O}=uSU%+7l$8wW!z5{*K BN`?Rc diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv index 4f2fe000d6..ea1b3835af 100644 --- a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv +++ b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv @@ -1,26 +1,26 @@ -290198 1 1 2680990 1796114805799796834 -1 0 -1 -1 0 CREATE TABLE fx(a) -290199 2 1 2680990 1796114805800796469 1000000 0 0 0 0 CREATE TABLE fx(a) -290200 1 1 2680990 1796114805800878447 -1 0 -1 -1 0 INSERT INTO fx VALUES(?) -290201 2 1 2680990 1796114805801137786 1000000 0 0 1 0 INSERT INTO fx VALUES(?) -290202 1 1 2680990 1796114805801162148 -1 2 -1 -1 0 INSERT INTO fx VALUES(6) -290203 2 1 2680990 1796114805801395872 0 2 0 1 0 INSERT INTO fx VALUES(6) -290204 1 1 2680990 1796114805801472367 -1 0 -1 -1 0 SELECT 'héllo € 😀' -290205 2 1 2680990 1796114805801481382 0 0 1 -1 0 SELECT 'héllo € 😀' -290206 1 1 2680990 1796114805801700178 -1 0 -1 -1 0 CREATE TABLE fxlog(a) -290207 2 1 2680990 1796114805802297271 1000000 0 0 0 0 CREATE TABLE fxlog(a) -290208 1 1 2680990 1796114805802802686 -1 1 -1 -1 0 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA -290209 2 1 2680990 1796114805803731074 1000000 1 0 0 0 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA -290210 1 1 2680990 1796114805803804645 -1 0 -1 -1 0 INSERT INTO fx VALUES(1) -290211 1 1 2680990 1796114805803890684 -1 0 -1 -1 0 -- TRIGGER fxt -290212 1 1 2680990 1796114805803892087 -1 0 -1 -1 0 -- INSERT INTO fxlog VALUES(new.a) -290213 2 1 2680990 1796114805803970589 0 0 0 1 0 INSERT INTO fx VALUES(1) -290214 1 1 2680990 1796114805804024329 -1 1 -1 -1 0 SELECT '€€€€€€€€€€€€€€€€€€ -290215 2 1 2680990 1796114805804029091 0 1 1 -1 0 SELECT '€€€€€€€€€€€€€€€€€€ -290216 1 2427 2680990 1796114805804399716 -1 0 -1 -1 0 SELECT 1 -290217 2 2427 2680990 1796114805804403830 0 0 1 -1 0 SELECT 1 -290218 3 2427 2680990 1796114805804406179 -1 0 -1 -1 0 -290219 1 1 2680990 1796114805804518430 -1 3 -1 -1 0 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 -290220 4 1 2680990 1796114805804528986 -1 1 1 -1 0 5/5|i:7,f:2.5,t*:hél,b*:0a0b0c0d,n: -290221 2 1 2680990 1796114805804535167 0 7 2 -1 0 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 -290222 1 1 2680990 1796114805804554614 -1 0 -1 -1 0 DELETE FROM fxlog -290223 2 1 2680990 1796114805804715879 0 0 0 1 0 DELETE FROM fxlog +311944 1 1 2686304 1796115342580727290 -1 0 -1 -1 311944 CREATE TABLE fx(a) +311945 2 1 2686304 1796115342581566995 1000000 0 0 0 311944 CREATE TABLE fx(a) +311946 1 1 2686304 1796115342581631602 -1 0 -1 -1 311946 INSERT INTO fx VALUES(?) +311947 2 1 2686304 1796115342581799931 0 0 0 1 311946 INSERT INTO fx VALUES(?) +311948 1 1 2686304 1796115342581819456 -1 2 -1 -1 311948 INSERT INTO fx VALUES(6) +311949 2 1 2686304 1796115342581945136 0 2 0 1 311948 INSERT INTO fx VALUES(6) +311950 1 1 2686304 1796115342582013836 -1 0 -1 -1 311950 SELECT 'héllo € 😀' +311951 2 1 2686304 1796115342582020062 0 0 1 -1 311950 SELECT 'héllo € 😀' +311952 1 1 2686304 1796115342582198105 -1 0 -1 -1 311952 CREATE TABLE fxlog(a) +311953 2 1 2686304 1796115342582625717 0 0 0 0 311952 CREATE TABLE fxlog(a) +311954 1 1 2686304 1796115342582807243 -1 1 -1 -1 311954 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +311955 2 1 2686304 1796115342583158810 1000000 1 0 0 311954 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +311956 1 1 2686304 1796115342583228502 -1 0 -1 -1 311956 INSERT INTO fx VALUES(1) +311957 1 1 2686304 1796115342583301956 -1 0 -1 -1 0 -- TRIGGER fxt +311958 1 1 2686304 1796115342583304166 -1 0 -1 -1 0 -- INSERT INTO fxlog VALUES(new.a) +311959 2 1 2686304 1796115342583424767 0 0 0 1 311956 INSERT INTO fx VALUES(1) +311960 1 1 2686304 1796115342583481472 -1 1 -1 -1 311960 SELECT '€€€€€€€€€€€€€€€€€€ +311961 2 1 2686304 1796115342583487595 0 1 1 -1 311960 SELECT '€€€€€€€€€€€€€€€€€€ +311962 1 2612 2686304 1796115342583898175 -1 0 -1 -1 311962 SELECT 1 +311963 2 2612 2686304 1796115342583903116 0 0 1 -1 311962 SELECT 1 +311964 3 2612 2686304 1796115342583906609 -1 0 -1 -1 0 +311965 1 1 2686304 1796115342584039276 -1 3 -1 -1 311965 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +311966 4 1 2686304 1796115342584050652 -1 1 1 -1 311965 5/5|i:7,f:2.5,t*:hél,b*:0a0b0c0d,n: +311967 2 1 2686304 1796115342584058221 0 7 2 -1 311965 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +311968 1 1 2686304 1796115342584084398 -1 0 -1 -1 311968 DELETE FROM fxlog +311969 2 1 2686304 1796115342584272160 0 0 0 1 311968 DELETE FROM fxlog From ec05501f4f3112ffaaf484c865f669797e88e2e6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 00:58:05 -0800 Subject: [PATCH 36/45] ADFA-7379 SQLite debugger: keep the execution id across a SQLITE_SCHEMA rerun When SQLite re-prepares a statement after SQLITE_SCHEMA it fires no second STATEMENT, so the rerun's PROFILE got id 0 and its rows were lost. A PROFILE with no rows that is not busy now leaves its slot, marked ended; a later ROW or PROFILE counts for it only if SQLITE_STMTSTATUS_REPREPARE has grown since the STATEMENT, else the slot is released and the event has no id. claim_slot takes an ended slot before the least recently used live one, so finished 0-row statements do not evict live cursors. The REPREPARE check is defence in depth: the EXPLAIN and nested-statement guards catch every event with no STATEMENT first, so no test fails without it. The retry tests (a SELECT after another connection's DDL and after CREATE TABLE on the same connection, a 0-row write, BUSY then SCHEMA) do fail without the ended slot. README: the retry paragraph. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 1 + .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 32 ++- .../src/test/c/sqlitedbg_test.c | 245 ++++++++++++++++++ 3 files changed, 275 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 9c15e55366..4ca35e85a1 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -34,6 +34,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - `execution_id` tells which run of a statement an event belongs to, so rows of statements stepped interleaved on one connection can be told apart. A STATEMENT's id is its own `seq`. The PROFILE and ROW events of that run carry the same id, not their own `seq`, so ids are not contiguous. 0 means none or unknown (Kotlin: `executionId` null; CLOSE never has one). Ids are unique within a process and restart with it, like `seq`. A run that is stepped, reset and stepped again gets a new STATEMENT and a new id each time, and so does a statement prepared again at the same address. - Events with id 0: a trigger's STATEMENT (its text starts with `-- `, and a STATEMENT whose id equals its `seq` is always the start of a run), a statement an app function runs inside a callback (its STATEMENT and PROFILE; no rows are recorded), an EXPLAIN's PROFILE, and the PROFILE and ROW events of a statement the extension did not see start. A statement evicted from its slot (more than 16 stepped in turn) keeps its id on its STATEMENT, but its later PROFILE and ROW events say 0, so a STATEMENT can have no PROFILE with its id. - A PROFILE is not a reliable "the run ended" event. An EXPLAIN fires a PROFILE with no STATEMENT. A step that returns `SQLITE_BUSY` fires a PROFILE (rows 0) before any row, and the run that resumes may fire no closing PROFILE; it does fire one if the resumed step hits `SQLITE_SCHEMA`. So one `execution_id` can have more than one PROFILE, and a client must not key on one PROFILE per id. +- A statement that SQLite re-prepares after `SQLITE_SCHEMA` (another connection ran DDL since it was prepared, or a CREATE TABLE ran on the same connection) fires one STATEMENT, and the rerun fires none. The rerun's ROW and PROFILE events keep the STATEMENT's id: a PROFILE with no rows that is not busy leaves its slot, marked ended, and later events count for it only if the statement's `SQLITE_STMTSTATUS_REPREPARE` count has grown since the STATEMENT; otherwise they have no id (0) and no rows. So a retried SELECT gives one STATEMENT, a PROFILE with rows 0, its ROW events, and a PROFILE with the row count, all with one id; a retried write gives two PROFILEs, the second with the change count. An ended slot is reused before a live statement's is evicted. An app that calls `sqlite3_stmt_status(..., SQLITE_STMTSTATUS_REPREPARE, 1)` while the statement runs resets that count, and the rerun's rows are then lost, never given a wrong id. A CREATE INDEX on the same connection expires the statement before it runs: one STATEMENT, one PROFILE. - Size: records grew from 72 to 80 bytes, about 10% more for an event with little data. The per-row path with no client connected is unchanged (see the benchmark below). **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 2abffab775..94811d427a 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -53,6 +53,8 @@ typedef struct stmt_slot { sqlite3_int64 total_changes; // sqlite3_total_changes64 when it started uint64_t last_use; // for evicting the least recently used slot uint64_t exec_id; // seq of the STATEMENT record that started this run + int ended; // a PROFILE with no rows and not busy: kept in case of a SQLITE_SCHEMA rerun + int reprepares; // SQLITE_STMTSTATUS_REPREPARE at claim } stmt_slot; typedef struct conn_state { @@ -209,11 +211,13 @@ static stmt_slot *find_slot(conn_state *cs, sqlite3_stmt *stmt) { return NULL; } -// The slot for a statement that starts: its old one if it is restarting, else a free one, else the -// least recently used. +// The slot for a statement that starts: its old one if it is restarting, else a free one, else an +// ended one, else the least recently used. static stmt_slot *claim_slot(conn_state *cs, sqlite3_stmt *stmt) { stmt_slot *slot = find_slot(cs, stmt); if (!slot) slot = find_slot(cs, NULL); + for (int i = 0; !slot && i < SQLITEDBG_STATEMENT_SLOTS; i++) + if (cs->slots[i].ended) slot = &cs->slots[i]; if (!slot) { slot = &cs->slots[0]; for (int i = 1; i < SQLITEDBG_STATEMENT_SLOTS; i++) @@ -222,6 +226,9 @@ static stmt_slot *claim_slot(conn_state *cs, sqlite3_stmt *stmt) { memset(slot, 0, sizeof *slot); slot->stmt = stmt; slot->last_use = ++cs->use_clock; + // Counted from here. An app that calls sqlite3_stmt_status(..., REPREPARE, 1) mid-run resets the + // count, and the rerun after SQLITE_SCHEMA then loses its rows (they never get a wrong id). + slot->reprepares = sqlite3_stmt_status(stmt, SQLITE_STMTSTATUS_REPREPARE, 0); return slot; } @@ -349,6 +356,15 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { memset(slot, 0, sizeof *slot); slot = NULL; } + // A slot that ended is this run's again only if SQLite re-prepared the statement since. + if (slot && slot->ended) { + if (sqlite3_stmt_status(stmt, SQLITE_STMTSTATUS_REPREPARE, 0) > slot->reprepares) { + slot->ended = 0; + } else { + memset(slot, 0, sizeof *slot); + slot = NULL; + } + } // Still busy: the statement did not finish, because it was reset or finalized before its // last step, or its step returned SQLITE_BUSY. int unfinished = sqlite3_stmt_busy(stmt); @@ -370,7 +386,10 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { // fires no other for the execution that resumes when the lock is free: keep the slot, so // its rows are still counted and recorded. A statement that went on to finish leaves it // until the statement starts again (claim_slot reuses it) or is evicted. - if (!(unfinished && slot->rows == 0)) memset(slot, 0, sizeof *slot); + // With no rows and not busy it may still be rerun after SQLITE_SCHEMA, with no STATEMENT: + // the slot is kept, marked ended. + if (slot->rows > 0) memset(slot, 0, sizeof *slot); + else if (!unfinished) slot->ended = 1; } } uint32_t kind = is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE; @@ -386,6 +405,13 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { if (!sqlite3_sql(stmt)) break; stmt_slot *slot = find_slot(cs, stmt); if (!slot) break; + if (slot->ended) { + if (sqlite3_stmt_status(stmt, SQLITE_STMTSTATUS_REPREPARE, 0) <= slot->reprepares) { + memset(slot, 0, sizeof *slot); + break; + } + slot->ended = 0; + } slot->rows++; slot->last_use = ++cs->use_clock; uint32_t max_rows = __atomic_load_n(&g_max_rows, __ATOMIC_RELAXED); diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 22ac697674..c84247088b 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -1181,6 +1181,248 @@ static void test_execution_id(void) { sqlitedbg_set_row_capture(0, 0, 0); } +static void step_to_done(sqlite3_stmt *st) { + while (sqlite3_step(st) == SQLITE_ROW) { + } +} + +// The events of one statement text, after the run: how many STATEMENTs, PROFILEs and ROWs there are, +// and that each carries the STATEMENT's id. Rows are the only ROW events in the batch. +typedef struct retry_events { + const ev *stmt; + const ev *first_profile, *last_profile; + size_t statements, profiles, rows; +} retry_events; + +static retry_events check_retry(const batch *b, const char *sql) { + retry_events r = {0}; + for (size_t i = 0; i < b->count; i++) { + const ev *e = &b->events[i]; + if (e->kind == SQLITEDBG_EVENT_ROW) r.rows++; + if (strcmp(e->sql, sql) != 0) continue; + if (e->kind == SQLITEDBG_EVENT_STATEMENT) { + r.statements++; + r.stmt = e; + } + if (e->kind == SQLITEDBG_EVENT_PROFILE) { + r.profiles++; + if (!r.first_profile) r.first_profile = e; + r.last_profile = e; + } + } + CHECK(r.stmt != NULL); + for (size_t i = 0; r.stmt && i < b->count; i++) { + const ev *e = &b->events[i]; + if (e->kind == SQLITEDBG_EVENT_ROW || (e->kind == SQLITEDBG_EVENT_PROFILE && strcmp(e->sql, sql) == 0)) + CHECK_EQ(e->exec_id, r.stmt->seq); + } + return r; +} + +// A statement that is run again by SQLite after SQLITE_SCHEMA fires no second STATEMENT: the rerun's +// rows and PROFILE keep the id of the one that started it (option b of ADFA-7379). +static void test_schema_retry(void) { + batch b; + uint64_t cur; + sqlite3_stmt *st; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "CREATE TABLE sr(a); INSERT INTO sr VALUES(1),(2)"); + sqlite3 *other = open_app(g_db_path); + + // a SELECT, after another connection's DDL and after a CREATE TABLE on its own connection + for (int same = 0; same < 2; same++) { + const char *sql = same ? "SELECT a FROM sr /* retry same */" : "SELECT a FROM sr /* retry other */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(same ? g_main : other, same ? "CREATE TABLE sr_same(y)" : "CREATE TABLE sr_other(y)"); + step_to_done(st); + CHECK_EQ(sqlite3_stmt_status(st, SQLITE_STMTSTATUS_REPREPARE, 0), 1); // else this checks nothing + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + retry_events r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 2); + CHECK_EQ(r.rows, 2); + if (r.first_profile) CHECK_EQ(r.first_profile->rows, 0); + if (r.last_profile) CHECK_EQ(r.last_profile->rows, 2); + batch_free(&b); + } + + // control: CREATE INDEX on the same connection expires the statement before it runs: one STATEMENT + // and one PROFILE + const char *sql = "SELECT a FROM sr /* control */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(g_main, "CREATE INDEX sr_i ON sr(a)"); + step_to_done(st); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + retry_events r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 1); + CHECK_EQ(r.rows, 2); + if (r.last_profile) CHECK_EQ(r.last_profile->rows, 2); + batch_free(&b); + + // a write with no rows: both PROFILEs carry the id, and the second has the change + sql = "INSERT INTO sr VALUES(7) /* retry write */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(other, "CREATE TABLE sr_w(y)"); + step_to_done(st); + CHECK_EQ(sqlite3_stmt_status(st, SQLITE_STMTSTATUS_REPREPARE, 0), 1); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 2); + if (r.last_profile) CHECK_EQ(r.last_profile->changes, 1); + batch_free(&b); + + // BUSY on the first step, and the lock holder's DDL makes the resumed step hit SQLITE_SCHEMA + sql = "SELECT a FROM sr /* busy then schema */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(other, "BEGIN EXCLUSIVE; CREATE TABLE sr_b(y)"); + CHECK_EQ(sqlite3_step(st), SQLITE_BUSY); + exec_ok(other, "COMMIT"); + step_to_done(st); + CHECK_EQ(sqlite3_stmt_status(st, SQLITE_STMTSTATUS_REPREPARE, 0), 1); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 2); + CHECK_EQ(r.rows, 3); + if (r.last_profile) CHECK_EQ(r.last_profile->rows, 3); + batch_free(&b); + + sqlite3_close(other); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); +} + +// A slot that ended (a finalized statement that returned no rows) stays until its address is used +// again, so an event with no STATEMENT at that address must not be taken for that statement's. The +// REPREPARE check that guards this is defence in depth: the EXPLAIN and nested-statement guards catch +// every such event first, and no event is known to reach it, so a mutation of the check does not fail +// this test; it covers those two guards against ended slots. +static void test_ended_slot(void) { + batch b; + uint64_t cur; + sqlite3_stmt *st, *zero; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "CREATE TABLE ez(a)"); + + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM ez /* ended 1 */", -1, &zero, NULL), SQLITE_OK); + step_to_done(zero); + sqlite3_finalize(zero); + CHECK_EQ(sqlite3_prepare_v2(g_main, "EXPLAIN SELECT 1", -1, &st, NULL), SQLITE_OK); + CHECK(st == zero); // else this checks nothing + step_to_done(st); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + const ev *e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "EXPLAIN SELECT 1"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + batch_free(&b); + + // a statement an app function runs, at that address + sqlite3_create_function(g_main, "nested_fn", 0, SQLITE_UTF8, NULL, nested_fn, NULL, NULL); + exec_ok(g_main, "INSERT INTO ez VALUES(1)"); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM ez WHERE a < 0 /* ended 2 */", -1, &zero, NULL), SQLITE_OK); + step_to_done(zero); + sqlite3_finalize(zero); + sqlite3_stmt *filler, *outerst; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 0 /* filler */", -1, &filler, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT nested_fn()", -1, &outerst, NULL), SQLITE_OK); + sqlite3_finalize(filler); + step_to_done(outerst); + sqlite3_finalize(outerst); + CHECK(g_inner == zero); // else this checks nothing + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 100 UNION ALL SELECT 200 /* nested */"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 1); // the outer statement's only + batch_free(&b); + + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); +} + +// Finished 0-row statements leave ended slots; they are reused before a live cursor's slot is evicted. +static void test_slot_pressure(void) { + enum { CURSORS = SQLITEDBG_STATEMENT_SLOTS - 1, INSERTS = 40 }; + batch b; + sqlite3_stmt *cur_st[CURSORS], *ins[INSERTS]; + char sql[64]; + exec_ok(g_main, "CREATE TABLE sp(a)"); + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(0); + uint64_t cur = cursor_now(); + for (int i = 0; i < CURSORS; i++) { + snprintf(sql, sizeof sql, "SELECT %d UNION ALL SELECT %d", i, i + 100); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &cur_st[i], NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(cur_st[i]), SQLITE_ROW); + } + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_STATEMENT), CURSORS); + uint64_t stmt_id[CURSORS] = {0}; + for (int i = 0; i < CURSORS; i++) { + snprintf(sql, sizeof sql, "SELECT %d UNION ALL SELECT %d", i, i + 100); + const ev *s = find_event(&b, SQLITEDBG_EVENT_STATEMENT, sql); + CHECK(s != NULL); + if (s) stmt_id[i] = s->seq; + } + batch_free(&b); + + // all 40 are prepared before any is finalized, so they are 40 different statements + for (int i = 0; i < INSERTS; i++) { + snprintf(sql, sizeof sql, "INSERT INTO sp VALUES(%d)", i); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &ins[i], NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(ins[i]), SQLITE_DONE); + } + for (int i = 0; i < INSERTS; i++) sqlite3_finalize(ins[i]); + + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + for (int i = 0; i < CURSORS; i++) CHECK_EQ(sqlite3_step(cur_st[i]), SQLITE_ROW); + for (int i = 0; i < CURSORS; i++) sqlite3_finalize(cur_st[i]); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + // every cursor's second row is recorded, with its own statement's id + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), CURSORS); + int k = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW || k >= CURSORS) continue; + CHECK_EQ(b.events[i].rows, 2); + CHECK_EQ(b.events[i].exec_id, stmt_id[k]); + k++; + } + batch_free(&b); +} + static void test_burst(void) { uint64_t cur = cursor_now(); const int stmts = 2000; @@ -1962,6 +2204,9 @@ int main(int argc, char **argv) { test_row_limits(); test_review_fixes(); test_execution_id(); + test_schema_retry(); + test_ended_slot(); + test_slot_pressure(); printf("# burst\n"); test_burst(); printf("# cursor reset\n"); From b9a31297eede4ee3fd001890ab1adaf599c0ea7a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 01:13:41 -0800 Subject: [PATCH 37/45] style: spotless reformat, no functional change EventDecoderTest.kt from the execution id tests: spotlessKotlin wants braces and blank lines in a when. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/engine/EventDecoderTest.kt | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index 28264ea588..62aeb14830 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -115,13 +115,22 @@ class EventDecoderTest { var run: Long? = null for (event in events) { when { - event.kind == EventKind.STATEMENT && event.sql.startsWith("-- ") -> assertThat(event.executionId).isNull() + event.kind == EventKind.STATEMENT && event.sql.startsWith("-- ") -> { + assertThat(event.executionId).isNull() + } + event.kind == EventKind.STATEMENT -> { assertThat(event.executionId).isEqualTo(event.seq) run = event.seq } - event.kind == EventKind.CLOSE -> assertThat(event.executionId).isNull() - else -> assertThat(event.executionId).isEqualTo(run) + + event.kind == EventKind.CLOSE -> { + assertThat(event.executionId).isNull() + } + + else -> { + assertThat(event.executionId).isEqualTo(run) + } } } assertThat(events.single { it.kind == EventKind.ROW }.executionId).isNotNull() From 8760dc0f78dd86cdfc91300e1e91fc0d2c9fc6f2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 11:49:01 -0800 Subject: [PATCH 38/45] ADFA-7379 get_events: every event carries execution_id #2311 (b9a31297e, merged in the previous commit) gives each event record an execution_id: a STATEMENT event's own seq, and on that run's PROFILE and ROW events the same number. get_events now returns it on every event, null when unknown (a trigger's statements, close, a statement whose start was not seen), so an agent can tell apart the rows of two statements stepped in turn on one connection. The tool description and the README say what it means, and that a run can have more than one profile (a retry after a schema change) or none at its end. Tests: DatabaseToolsTest's fixture test checks execution_id on every decoded event (the fixture's ROW events carry ids); JniQueryTest checks that a recorded row's execution_id is the seq of a STATEMENT record in the buffer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 7 ++++++- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 3 +++ .../src/test/jni/JniQueryTest.java | 20 +++++++++++++++++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 41cbc1cff1..8594ad0145 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -51,7 +51,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Storage classes.** JSON alone cannot tell a REAL 2.0 from an INTEGER 2 (org.json writes both as `2`), or a big integer from TEXT, so `query` returns `storage_classes`, one string per row with a letter per column: `i` INTEGER, `r` REAL, `t` TEXT, `b` BLOB, `n` NULL. Row events carry the same string. - **Declared types.** `query` returns `column_types`, each column's `sqlite3_column_decltype`, `null` for an expression. - **Bound parameters (`.parameter`).** `query` and `explain_query_plan` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL, and the error names the key even when a parameter is also left without a value; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. -- **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. +- **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. Every event has `execution_id` (ADFA-7379): a `statement` event's own `seq`, and on that run's `profile` and `row` events the same number, so rows of two statements stepped in turn are told apart; it is `null` for a trigger's statements, `close`, and a statement whose start was not seen. A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. - **Limits.** `execute` (ADFA-7298, a separate PR) binds positional `args` only until the two PRs meet. Row recording is one switch for the process: the last `get_events` call decides it. ## Decisions that shape it 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 8bf356c1f2..539ef5fbee 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 @@ -354,7 +354,11 @@ class DatabaseTools internal constructor( "watching. " + "kind is statement (one starts; a trigger's SQL starts with --), profile (one finished: duration_nanos; rows, the " + "rows it returned; changes, the rows it changed itself, not through triggers, null for a read; null when the " + - "statement's start was not seen), close, or row. With include_rows true (the default), the app's statements " + + "statement's start was not seen), close, or row. execution_id names one run of a statement: a statement event's " + + "own seq, and on that run's profile and row events the same number, so rows of statements stepped in turn " + + "are told apart by it; null for a trigger's statements, close, and a statement whose start was not seen. A run can " + + "have more than one profile (a retry after a schema change), or none at its end. " + + "With include_rows true (the default), the app's statements " + "after the call also record their first $EVENT_ROWS_PER_STATEMENT rows as row events: row_number (from 1), " + "column_count, values, storage_classes and cut_values (indexes of TEXT and BLOB values cut at " + "$EVENT_VALUE_BYTES bytes); a row's data stops at ${EVENT_ROW_BYTES / 1024} KiB, and then values holds fewer " + @@ -640,6 +644,7 @@ class DatabaseTools internal constructor( .put("seq", encodeLong(e.seq)) .put("kind", e.kind.name.lowercase()) .put("connection_id", encodeLong(e.connectionId)) + .put("execution_id", e.executionId?.let { encodeLong(it) } ?: JSONObject.NULL) .put("thread_id", encodeLong(e.threadId)) .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) 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 d5b0f25511..efc469d9ca 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 @@ -1269,6 +1269,7 @@ class DatabaseToolsTest { val bytes = checkNotNull(EventDecoder::class.java.getResourceAsStream("events.bin")).use { it.readBytes() } val decoded = EventDecoder.decode(bytes, bytes.size) assertTrue("the fixture has row events", decoded.any { it.kind == EventKind.ROW }) + assertTrue("and execution ids", decoded.any { it.kind == EventKind.ROW && it.executionId != null }) assertTrue("and a change count", decoded.any { it.changes != null }) decoded.forEach { e -> engine.addEvent { e.copy(seq = it) } } val events = ok("get_events").getJSONArray("events") @@ -1276,6 +1277,8 @@ class DatabaseToolsTest { decoded.forEachIndexed { i, e -> val json = events.getJSONObject(i) assertEquals(e.kind.name.lowercase(), json.getString("kind")) + assertTrue("execution_id is always present", json.has("execution_id")) + assertEquals(e.executionId, if (json.isNull("execution_id")) null else json.getLong("execution_id")) when (e.kind) { EventKind.ROW -> { val row = e.row!! diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 5bb75028fd..88932cc4fc 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -102,6 +102,25 @@ static long rowEvents() { return rows; } + /** + * ADFA-7379: whether the newest row event names a statement event in the buffer by its execution_id (offset 72), + * which is that statement event's seq (offset 8). + */ + static boolean newestRowNamesItsStatement() { + byte[] buf = new byte[1 << 20]; + long[] out = new long[4]; + NativeBridge.readEvents(0, buf, out); + java.nio.ByteBuffer b = java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + Set statements = new HashSet<>(); + long exec = 0; + for (int at = 0; at < out[2]; at += b.getInt(at)) { + int kind = b.getInt(at + 4); + if (kind == 1) statements.add(b.getLong(at + 8)); + if (kind == 4) exec = b.getLong(at + 72); + } + return exec != 0 && statements.contains(exec); + } + /** "code message" of a refused query with args bound by name, or null when it ran. */ static String namedRefusal(long h, String sql, Object[] args, String[] names) { try { @@ -241,6 +260,7 @@ public static void main(String[] a) throws Exception { NativeBridge.setRowCapture(1, 0, 0); eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording on"); eq(rowEvents(), rowsBefore + 1, "one row event: one row per statement"); + eq(newestRowNamesItsStatement(), true, "the row event names its statement event (ADFA-7379)"); NativeBridge.setRowCapture(0, 0, 0); eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off again"); eq(rowEvents(), rowsBefore + 1, "off again"); From 90c62863698904d932d8490e0be104e6ef634200 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 17:29:14 -0800 Subject: [PATCH 39/45] ADFA-7379 SQLite debugger: a trigger step is not a nested statement A trigger step is traced as "-- " + its text with P the running outer statement. When that text equals the outer statement's own (a trigger on t whose step is the UPDATE that fired it), the nested-statement check took the step for an app statement run in a callback and cleared the outer statement's live slot. Its PROFILE then had execution id 0, rows -1 and changes -1. The connection now remembers the statement whose "-- TRIGGER" trace came last, skips the clear for that statement, and forgets it at the statement's next STATEMENT or PROFILE. A new test fires an UPDATE trigger whose step repeats the UPDATE and checks the PROFILE's id, rows and changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 13 ++++++++++-- .../src/test/c/sqlitedbg_test.c | 21 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 94811d427a..66a795d281 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -69,6 +69,10 @@ typedef struct conn_state { // SQLITE_THREADSAFE=2 means one thread at a time, so these need no lock. stmt_slot slots[SQLITEDBG_STATEMENT_SLOTS]; uint64_t use_clock; + // The statement whose trigger was traced last ("-- TRIGGER name", P the outer statement), until + // that statement's PROFILE: its trigger's steps are traced as "-- " + step text, the same shape as a + // statement an app runs in a callback, and must not be taken for one. + sqlite3_stmt *trigger_owner; } conn_state; // Taken only for the fields below; never while SQLite runs. @@ -330,6 +334,7 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { flags |= SQLITEDBG_EVENT_EXPANDED; } } + if (is_stmt && is_trigger && !strncmp(sql, "-- TRIGGER ", 11)) cs->trigger_owner = stmt; int64_t duration = is_stmt ? -1 : *(sqlite3_int64 *)x; int64_t rows = -1, changes = -1; uint64_t exec_id = 0; @@ -340,16 +345,20 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { // handled below. const char *own = sqlite3_sql(stmt); // A statement the app runs inside a callback is traced as "-- " + its own text, with P the - // statement itself: it claims no slot, and one left at this address is not its. - if (own && !strncmp(sql, "-- ", 3) && !strcmp(sql + 3, own)) { + // statement itself: it claims no slot, and one left at this address is not its. Not so for a + // step of the running statement's own trigger, whose text may equal the statement's: P is + // then the running statement, and its live slot stays. + if (own && stmt != cs->trigger_owner && !strncmp(sql, "-- ", 3) && !strcmp(sql + 3, own)) { stmt_slot *old = find_slot(cs, stmt); if (old) memset(old, 0, sizeof *old); } if (!is_trigger) { + if (cs->trigger_owner == stmt) cs->trigger_owner = NULL; claimed = claim_slot(cs, stmt); claimed->total_changes = sqlite3_total_changes64(sqlite3_db_handle(stmt)); } } else { + if (cs->trigger_owner == stmt) cs->trigger_owner = NULL; stmt_slot *slot = find_slot(cs, stmt); // An EXPLAIN is traced with no STATEMENT: a slot at its address is another statement's. if (slot && sqlite3_stmt_isexplain(stmt)) { diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index c84247088b..4e8e902f20 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -1067,6 +1067,27 @@ static void test_execution_id(void) { } batch_free(&b); + // a trigger whose step has the same text as the statement that fires it: the step is traced as + // "-- UPDATE tr SET b=1" with P the running statement, which is not a nested statement. The live slot + // stays, so the PROFILE keeps the id and the counts. + exec_ok(g_main, "CREATE TABLE tr(a, b); INSERT INTO tr VALUES(1, 0)"); + exec_ok(g_main, "CREATE TRIGGER trs AFTER UPDATE ON tr BEGIN UPDATE tr SET b=1; END"); + cur = cursor_now(); + exec_ok(g_main, "UPDATE tr SET b=1"); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "UPDATE tr SET b=1"); + CHECK(os != NULL); + CHECK(find_event(&b, SQLITEDBG_EVENT_STATEMENT, "-- UPDATE tr SET b=1") != NULL); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "UPDATE tr SET b=1"); + CHECK(e != NULL); + if (e && os) { + CHECK_EQ(e->exec_id, os->seq); + CHECK_EQ(e->rows, 0); + CHECK_EQ(e->changes, 1); + } + batch_free(&b); + exec_ok(g_main, "CREATE TABLE xb(a); INSERT INTO xb VALUES(1),(2),(3)"); sqlite3 *other = open_app(g_db_path); sqlite3_create_function(g_main, "nested_fn", 0, SQLITE_UTF8, NULL, nested_fn, NULL, NULL); From 8a60b2b0cd0599089c76bbf313a7648d8b82bb0f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 17:29:25 -0800 Subject: [PATCH 40/45] ADFA-7296 SQLite debugger: changes only from a DML statement's own count A PRAGMA (or another non-read-only statement that is not DML) stepped across another statement's INSERT found the connection's total changed and reported sqlite3_changes64, which then held the INSERT's count. The PROFILE now reports sqlite3_changes64 only for a statement whose own SQL starts with INSERT, UPDATE, DELETE, REPLACE or WITH, after whitespace and comments (a small helper reads sqlite3_sql). Otherwise, when the total moved, it reports -1. A total that did not move still means 0. The header and README say so. New tests step PRAGMA journal_mode once, run a 3-row INSERT, and finish the PRAGMA, whose changes must be -1; a WITH ... INSERT keeps its real count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 33 +++++++++++++++++-- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 5 ++- .../src/test/c/sqlitedbg_test.c | 18 ++++++++++ 4 files changed, 54 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 4ca35e85a1..9eda101d6c 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -38,7 +38,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - Size: records grew from 72 to 80 bytes, about 10% more for an event with little data. The per-row path with no client connected is unchanged (see the benchmark below). **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). -- A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). +- A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). `changes` is -1 as well when the connection's total changed while the statement ran and the statement is not an INSERT, UPDATE, DELETE or REPLACE (a leading WITH counts; decided from its own SQL, after whitespace and comments): a PRAGMA stepped across another statement's INSERT would otherwise get that INSERT's count. - `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). - Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. - The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one; those reads are traced as ROW only and are ignored). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 66a795d281..a249f8f4f9 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -8,9 +8,11 @@ #define _GNU_SOURCE #endif +#include #include #include #include +#include #include #include #include @@ -301,6 +303,30 @@ static int record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number, uint64 return 1; } +// Whether sql starts with INSERT, UPDATE, DELETE or REPLACE (a leading WITH counts), after whitespace and +// comments: the statements that set sqlite3_changes64. +static int is_dml_sql(const char *sql) { + if (!sql) return 0; + for (;;) { + while (*sql == ' ' || *sql == '\t' || *sql == '\n' || *sql == '\r' || *sql == '\f') sql++; + if (sql[0] == '-' && sql[1] == '-') { + while (*sql && *sql != '\n') sql++; + } else if (sql[0] == '/' && sql[1] == '*') { + sql += 2; + while (*sql && !(sql[0] == '*' && sql[1] == '/')) sql++; + if (*sql) sql += 2; + } else { + break; + } + } + static const char *const words[] = {"INSERT", "UPDATE", "DELETE", "REPLACE", "WITH"}; + for (size_t i = 0; i < sizeof words / sizeof words[0]; i++) { + size_t n = strlen(words[i]); + if (!strncasecmp(sql, words[i], n) && !isalnum((unsigned char)sql[n]) && sql[n] != '_') return 1; + } + return 0; +} + // sqlite3_trace_v2 callback. C is the connection's conn_state, which lives until SQLite frees the // connection, so it outlives every callback. static int trace_cb(unsigned type, void *c, void *p, void *x) { @@ -384,12 +410,15 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { if (!sqlite3_stmt_readonly(stmt)) { // sqlite3_changes64 is this statement's count once it has run, but only INSERT, UPDATE // and DELETE set it: after a CREATE TABLE it still holds the last write's. A total that - // did not move means the statement changed nothing. + // did not move means the statement changed nothing. If it moved and the statement is not + // one of those (a PRAGMA stepped across another statement's INSERT), the count is + // another statement's: unknown. sqlite3 *db = sqlite3_db_handle(stmt); // A statement stopped part way (an INSERT ... RETURNING stepped once) has made only part // of its changes, or all of them without sqlite3_changes64 knowing: unknown. if (unfinished) changes = -1; - else changes = sqlite3_total_changes64(db) == slot->total_changes ? 0 : sqlite3_changes64(db); + else if (sqlite3_total_changes64(db) == slot->total_changes) changes = 0; + else changes = is_dml_sql(sqlite3_sql(stmt)) ? sqlite3_changes64(db) : -1; } // A step that returned SQLITE_BUSY before any row also ends in this event, and SQLite // fires no other for the execution that resumes when the lock is free: keep the slot, so diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 43f001d478..639eadbc8e 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -128,7 +128,10 @@ typedef struct sqlitedbg_event_record { // key actions); 0 when it changed none, as a CREATE TABLE. -1 (unknown) for a read-only // statement, for the other kinds, when rows is -1, and when the statement had not finished when // the event fired (reset or finalized part way, as an INSERT ... RETURNING stepped once, or a step - // that returned SQLITE_BUSY): its count is then partial or not yet set. + // that returned SQLITE_BUSY): its count is then partial or not yet set. Also -1 when the + // connection's total changed while the statement ran and it is not an INSERT, UPDATE, DELETE or + // REPLACE (a leading WITH counts), as a PRAGMA stepped across another statement's INSERT: the + // count sqlite3_changes64 holds is then that statement's. int64_t changes; // The run of a statement this event belongs to: the seq of its STATEMENT record, on that record // and on the PROFILE and ROW records of the run. 0: none or unknown (a trigger's STATEMENT, a diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 4e8e902f20..424d65b12f 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -632,8 +632,24 @@ static void test_changes(void) { exec_ok(g_main, "UPDATE c SET a = a WHERE 0"); // t's trigger inserts into log too: only the insert's own row counts exec_ok(g_main, "INSERT INTO t VALUES(5)"); + // a WITH ... INSERT is DML and keeps its count + exec_ok(g_main, "/* lead */ WITH w(x) AS (SELECT 1 UNION ALL SELECT 2) INSERT INTO c SELECT x FROM w"); + // a PRAGMA stepped once, a 3-row INSERT, then the PRAGMA finished: sqlite3_changes64 holds the + // INSERT's 3 at the PRAGMA's PROFILE, which is not the PRAGMA's + exec_ok(g_main, "BEGIN"); + sqlite3_stmt *pragma; + CHECK_EQ(sqlite3_prepare_v2(g_main, "PRAGMA main.journal_mode", -1, &pragma, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(pragma), SQLITE_ROW); + exec_ok(g_main, "INSERT INTO c VALUES(1),(2),(3)"); + while (sqlite3_step(pragma) == SQLITE_ROW) { + } + sqlite3_finalize(pragma); + exec_ok(g_main, "COMMIT"); batch b; read_all(cur, &b); + const ev *pe = find_event(&b, SQLITEDBG_EVENT_PROFILE, "PRAGMA main.journal_mode"); + CHECK(pe != NULL); + if (pe) CHECK_EQ(pe->changes, -1); struct { const char *sql; int64_t changes, rows; @@ -645,6 +661,8 @@ static void test_changes(void) { {"CREATE TABLE c2(a)", 0, 0}, {"UPDATE c SET a = a WHERE 0", 0, 0}, {"INSERT INTO t VALUES(5)", 1, 0}, + {"/* lead */ WITH w(x) AS (SELECT 1 UNION ALL SELECT 2) INSERT INTO c SELECT x FROM w", 2, 0}, + {"INSERT INTO c VALUES(1),(2),(3)", 3, 0}, }; for (size_t i = 0; i < sizeof want / sizeof want[0]; i++) { const ev *e = find_event(&b, SQLITEDBG_EVENT_PROFILE, want[i].sql); From 9c4d0fe17baad3344cac0dc5cc8f14e9d0bf98cb Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 17:29:52 -0800 Subject: [PATCH 41/45] ADFA-7379 SQLite debugger: correct the eviction, version, cost and row-cut docs Eviction: a statement evicted from its slot keeps its id on its STATEMENT and on the ROW events recorded before the eviction. Its later rows are not recorded at all, and only its PROFILE has 0. The header, the README and the test comment said the later ROW events had 0. The eviction test now asserts that statement 0's ROW has exec_id equal to its STATEMENT's seq. README: each ROW trace now makes one extra sqlite3_sql call, and that cost was not re-measured (it said the per-row path was unchanged). The stale claim that the interface version is 3 is gone; sqlitedbg.h has the current value. The limits note that in a UTF-16 database sqlite3_column_bytes converts a whole TEXT value before the 1 MiB guard, and the code comment no longer says it never copies. Behaviour is unchanged. ROWS_CUT and Event.rowsCut also cover a row the producer could not record (a byte budget below a row header, or an allocation failure), not only the per-statement row limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 8 ++++---- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c | 8 +++++--- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h | 8 +++++--- .../appdevforall/sqlitedebugger/engine/DebugEngine.kt | 6 +++++- .../sqlite-debugger/src/test/c/sqlitedbg_test.c | 10 ++++++++-- 5 files changed, 27 insertions(+), 13 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 9eda101d6c..e32ee2b1e6 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -32,15 +32,15 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han **Execution id (ADFA-7379, interface version 4).** The header grew from 72 to 80 bytes: `execution_id` is a `uint64_t` at offset 72, after `changes`; the earlier fields kept their offsets. A 72-byte producer read by the 80-byte `EventDecoder` throws `IllegalArgumentException`: both ship in one AAR, so that pairing does not occur. - `execution_id` tells which run of a statement an event belongs to, so rows of statements stepped interleaved on one connection can be told apart. A STATEMENT's id is its own `seq`. The PROFILE and ROW events of that run carry the same id, not their own `seq`, so ids are not contiguous. 0 means none or unknown (Kotlin: `executionId` null; CLOSE never has one). Ids are unique within a process and restart with it, like `seq`. A run that is stepped, reset and stepped again gets a new STATEMENT and a new id each time, and so does a statement prepared again at the same address. -- Events with id 0: a trigger's STATEMENT (its text starts with `-- `, and a STATEMENT whose id equals its `seq` is always the start of a run), a statement an app function runs inside a callback (its STATEMENT and PROFILE; no rows are recorded), an EXPLAIN's PROFILE, and the PROFILE and ROW events of a statement the extension did not see start. A statement evicted from its slot (more than 16 stepped in turn) keeps its id on its STATEMENT, but its later PROFILE and ROW events say 0, so a STATEMENT can have no PROFILE with its id. +- Events with id 0: a trigger's STATEMENT (its text starts with `-- `, and a STATEMENT whose id equals its `seq` is always the start of a run), a statement an app function runs inside a callback (its STATEMENT and PROFILE; no rows are recorded), an EXPLAIN's PROFILE, and the PROFILE and ROW events of a statement the extension did not see start. A statement evicted from its slot (more than 16 stepped in turn) keeps its id on its STATEMENT and on the ROW events recorded before the eviction; its later rows are not recorded and its PROFILE says 0, so a STATEMENT can have no PROFILE with its id. - A PROFILE is not a reliable "the run ended" event. An EXPLAIN fires a PROFILE with no STATEMENT. A step that returns `SQLITE_BUSY` fires a PROFILE (rows 0) before any row, and the run that resumes may fire no closing PROFILE; it does fire one if the resumed step hits `SQLITE_SCHEMA`. So one `execution_id` can have more than one PROFILE, and a client must not key on one PROFILE per id. - A statement that SQLite re-prepares after `SQLITE_SCHEMA` (another connection ran DDL since it was prepared, or a CREATE TABLE ran on the same connection) fires one STATEMENT, and the rerun fires none. The rerun's ROW and PROFILE events keep the STATEMENT's id: a PROFILE with no rows that is not busy leaves its slot, marked ended, and later events count for it only if the statement's `SQLITE_STMTSTATUS_REPREPARE` count has grown since the STATEMENT; otherwise they have no id (0) and no rows. So a retried SELECT gives one STATEMENT, a PROFILE with rows 0, its ROW events, and a PROFILE with the row count, all with one id; a retried write gives two PROFILEs, the second with the change count. An ended slot is reused before a live statement's is evicted. An app that calls `sqlite3_stmt_status(..., SQLITE_STMTSTATUS_REPREPARE, 1)` while the statement runs resets that count, and the rerun's rows are then lost, never given a wrong id. A CREATE INDEX on the same connection expires the statement before it runs: one STATEMENT, one PROFILE. -- Size: records grew from 72 to 80 bytes, about 10% more for an event with little data. The per-row path with no client connected is unchanged (see the benchmark below). +- Size: records grew from 72 to 80 bytes, about 10% more for an event with little data. Each ROW trace now makes one extra `sqlite3_sql` call (before the slot lookup), with or without a client connected. That cost was not re-measured; the benchmark below predates ADFA-7379. **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). - A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). `changes` is -1 as well when the connection's total changed while the statement ran and the statement is not an INSERT, UPDATE, DELETE or REPLACE (a leading WITH counts; decided from its own SQL, after whitespace and comments): a PRAGMA stepped across another statement's INSERT would otherwise get that INSERT's count. - `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). -- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. +- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. Limit: in a UTF-16 database `sqlite3_column_bytes` on a TEXT value converts the whole value to UTF-8 before this guard can skip it, so a huge value costs a transient copy and the time to make it on the app's thread, for each row recorded while a client is connected (measured with a 25-million-character TEXT: a 100 MB allocation and about 230 ms for one row, against about 54 ms with recording off). This is not fixed yet. - The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one; those reads are traced as ROW only and are ignored). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. - Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). @@ -53,7 +53,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **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). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` became 2 for the changed struct, and is 3 since the row and change fields, ADFA-7296), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. +- **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` became 2 for the changed struct, and was raised again by later layout changes: `sqlitedbg.h` has the current value), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. - **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). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index a249f8f4f9..f2a72a9273 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -276,9 +276,11 @@ static int record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number, uint64 } len += put_value(v, (uint8_t)type, 0, 8, 8) + 8; } else if (type == SQLITE_TEXT || type == SQLITE_BLOB) { - // The size first: sqlite3_column_bytes does not copy a stored value, and it is how a huge - // one is recognised before anything reads it (see ROW_READ_MAX_BYTES). The pointer - // accessor then asks for the type the value already has, so nothing is converted. + // The size first: in a UTF-8 database sqlite3_column_bytes does not copy a stored value, and it + // is how a huge one is recognised before anything reads it (see ROW_READ_MAX_BYTES). In a + // UTF-16 database it converts a whole TEXT value to UTF-8 first (a transient copy and the time + // to make it, whatever the guard), which this does not avoid yet. The pointer accessor then + // asks for the type the value already has, so nothing more is converted. size_t full = (size_t)sqlite3_column_bytes(stmt, i); size_t limit = room < max_value ? room : max_value; const void *p = NULL; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 639eadbc8e..6d098bc592 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -98,8 +98,9 @@ enum { // sql has its bound values written in (sqlite3_expanded_sql). Only while a client is // connected (sqlitedbg_set_client_connected): expanding a 1 MB value costs 2 MB on every run. SQLITEDBG_EVENT_EXPANDED = 1u << 1, - // SQLITEDBG_EVENT_PROFILE only: rows were left unrecorded because the statement returned more than - // the per-statement limit while row recording was on. + // SQLITEDBG_EVENT_PROFILE only: rows were left unrecorded while row recording was on, because the + // statement returned more than the per-statement limit, or because the producer could not record + // a row (the byte budget is below a row header, or an allocation failed). SQLITEDBG_EVENT_ROWS_CUT = 1u << 2, }; @@ -136,7 +137,8 @@ typedef struct sqlitedbg_event_record { // The run of a statement this event belongs to: the seq of its STATEMENT record, on that record // and on the PROFILE and ROW records of the run. 0: none or unknown (a trigger's STATEMENT, a // statement nested in a callback, an EXPLAIN, a CLOSE, or a statement the extension did not see - // start). A statement evicted from its slot keeps its id on the STATEMENT only. Not contiguous, + // start). A statement evicted from its slot keeps its id on its STATEMENT and on the ROW events + // recorded before the eviction; its later rows are not recorded, and its PROFILE has 0. Not contiguous, // and restarting with the process like seq. uint64_t execution_id; } sqlitedbg_event_record; // 80 bytes; the data follows diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 0ed4b115f3..e2cf8e382c 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -125,7 +125,11 @@ data class Event( * part way, or its step returned `SQLITE_BUSY`), as the count is then unknown. */ val changes: Long? = null, - /** [EventKind.PROFILE]: rows went unrecorded because the statement returned more than the per-statement limit. */ + /** + * [EventKind.PROFILE]: rows went unrecorded while row recording was on, because the statement returned + * more than the per-statement limit, or because the producer could not record a row (the byte budget + * was below a row header, or an allocation failed). + */ val rowsCut: Boolean = false, /** [EventKind.ROW] only: the row's values. */ val row: RowValues? = null, diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 424d65b12f..fd3eddb0fa 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -756,7 +756,8 @@ static void test_interleaved_rows(void) { sqlitedbg_set_client_connected(0); sqlitedbg_set_row_capture(0, 0, 0); read_all(cur, &b); - // one row each, plus statement 1's second row; statement 0's second row had no slot + // one row each, plus statement 1's second row; statement 0's first row was recorded before its slot + // was evicted, and its second row found no slot and was not recorded CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), N + 1); const ev *p0 = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 0 UNION ALL SELECT 0"); const ev *p1 = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 1 UNION ALL SELECT 1"); @@ -764,12 +765,17 @@ static void test_interleaved_rows(void) { if (p0) CHECK_EQ(p0->rows, -1); if (p0) CHECK_EQ(p0->changes, -1); if (p1) CHECK_EQ(p1->rows, 2); - // the evicted statement keeps its id on its STATEMENT only; its PROFILE says none + // the evicted statement keeps its id on its STATEMENT and on the ROW recorded before the eviction; its + // later rows are not recorded, and its PROFILE says none const ev *s0 = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 0 UNION ALL SELECT 0"); const ev *s1 = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 1 UNION ALL SELECT 1"); CHECK(s0 && s1); CHECK_EQ(b.dropped, 0); if (s0) CHECK_EQ(s0->exec_id, s0->seq); + size_t s0_rows = 0; + for (size_t i = 0; s0 && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW && b.events[i].exec_id == s0->seq) s0_rows++; + CHECK_EQ(s0_rows, 1); if (p0) CHECK_EQ(p0->exec_id, 0); if (s1 && p1) CHECK_EQ(p1->exec_id, s1->seq); batch_free(&b); From 22009aa6475d41725e49929245e5f0a19c7e34e6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 17:41:40 -0800 Subject: [PATCH 42/45] ADFA-7296 SQLite debugger: the UTF-16 row-size cost is an accepted limit In a UTF-16 database, recording rows converts each TEXT value to UTF-8 in full before the 1 MiB guard applies, so a large value costs its full size in memory and time. Android's own databases and Room use UTF-8. The decision is to document this and not change the behaviour, so the README now states it as an accepted limit instead of "not fixed yet". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index e32ee2b1e6..d55b3aae62 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -40,7 +40,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han **Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). - A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). `changes` is -1 as well when the connection's total changed while the statement ran and the statement is not an INSERT, UPDATE, DELETE or REPLACE (a leading WITH counts; decided from its own SQL, after whitespace and comments): a PRAGMA stepped across another statement's INSERT would otherwise get that INSERT's count. - `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default, and nothing turns it on yet; the server will (ADFA-7297). -- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. Limit: in a UTF-16 database `sqlite3_column_bytes` on a TEXT value converts the whole value to UTF-8 before this guard can skip it, so a huge value costs a transient copy and the time to make it on the app's thread, for each row recorded while a client is connected (measured with a 25-million-character TEXT: a 100 MB allocation and about 230 ms for one row, against about 54 ms with recording off). This is not fixed yet. +- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. Accepted limit: in a UTF-16 database, recording rows converts each TEXT value to UTF-8 in full (`sqlite3_column_bytes`) before the 1 MiB guard applies, so a large value costs its full size in memory and time on the app's thread, for each row recorded while a client is connected (measured with a 25-million-character TEXT: a 100 MB allocation and about 230 ms for one row, against about 54 ms with recording off). Android's own databases and Room use UTF-8, which has no such copy. Decided not to change (David). - The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one; those reads are traced as ROW only and are ignored). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. - Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). From bc41ff2629c13a391845f775f61fd66c951653d2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 18:11:49 -0800 Subject: [PATCH 43/45] ADFA-7296 SQLite debugger: fix the WITH ... INSERT changes test The SQL of a PROFILE is cut at the test's 64-byte limit and keeps a leading comment, so the earlier WITH ... INSERT case never found its event. It now uses a shorter statement that fits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index fd3eddb0fa..03f323abe0 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -632,8 +632,8 @@ static void test_changes(void) { exec_ok(g_main, "UPDATE c SET a = a WHERE 0"); // t's trigger inserts into log too: only the insert's own row counts exec_ok(g_main, "INSERT INTO t VALUES(5)"); - // a WITH ... INSERT is DML and keeps its count - exec_ok(g_main, "/* lead */ WITH w(x) AS (SELECT 1 UNION ALL SELECT 2) INSERT INTO c SELECT x FROM w"); + // a WITH ... INSERT is DML and keeps its count after a comment + exec_ok(g_main, "/*c*/ WITH w(x) AS (VALUES(1),(2)) INSERT INTO c SELECT x FROM w"); // a PRAGMA stepped once, a 3-row INSERT, then the PRAGMA finished: sqlite3_changes64 holds the // INSERT's 3 at the PRAGMA's PROFILE, which is not the PRAGMA's exec_ok(g_main, "BEGIN"); @@ -661,7 +661,7 @@ static void test_changes(void) { {"CREATE TABLE c2(a)", 0, 0}, {"UPDATE c SET a = a WHERE 0", 0, 0}, {"INSERT INTO t VALUES(5)", 1, 0}, - {"/* lead */ WITH w(x) AS (SELECT 1 UNION ALL SELECT 2) INSERT INTO c SELECT x FROM w", 2, 0}, + {"/*c*/ WITH w(x) AS (VALUES(1),(2)) INSERT INTO c SELECT x FROM w", 2, 0}, {"INSERT INTO c VALUES(1),(2),(3)", 3, 0}, }; for (size_t i = 0; i < sizeof want / sizeof want[0]; i++) { From 4ffc26dc00d4f7afde2f2bc860413e8e1486cb55 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 18:11:49 -0800 Subject: [PATCH 44/45] ADFA-7296 SQLite debugger: refuse a cut number or null, keep the fake's STATEMENT id EventDecoder now requires full_bytes to equal stored_bytes for INTEGER and FLOAT, and zero for NULL. The producer never cuts these, so a record that says otherwise is malformed. A new test feeds INTEGER 8/9, FLOAT 8/9 and NULL 0/1, each flagged cut, and expects IllegalArgumentException. FakeDebugEngine.addEvent(Event) renumbers the event. A STATEMENT whose execution id equals its seq now gets the new seq as its id too, as a native STATEMENT has. Null ids and the parent ids of ROW and PROFILE events are left alone. A new FakeDebugEngineTest case covers it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/engine/EventDecoder.kt | 3 ++ .../sqlitedebugger/engine/EventDecoderTest.kt | 50 +++++++++++++++++++ .../sqlitedebugger/engine/FakeDebugEngine.kt | 5 +- .../engine/FakeDebugEngineTest.kt | 23 +++++++++ 4 files changed, 80 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt index cff1a45cb2..468a467c20 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -126,6 +126,8 @@ internal object EventDecoder { when (type) { SQLITE_INTEGER, SQLITE_FLOAT -> { require(stored == 8) { "row at $start: number $i is $stored bytes" } + // The producer never cuts a number: full_bytes is the stored 8. + require(full == stored) { "row at $start: number $i has stored_bytes=$stored full_bytes=$full" } if (type == SQLITE_INTEGER) buffer.getLong(pos) else buffer.getDouble(pos) } @@ -139,6 +141,7 @@ internal object EventDecoder { SQLITE_NULL -> { require(stored == 0) { "row at $start: null $i has $stored bytes" } + require(full == 0) { "row at $start: null $i has full_bytes=$full" } null } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index 62aeb14830..b2bc5aed91 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -239,6 +239,56 @@ class EventDecoderTest { assertThat(e.message).contains("number 0 is 4 bytes") } + @Test + fun `a number or null that claims to be cut is refused`() { + // One ROW record: the 80-byte header, the row header (1 column, 1 value kept), one value header, + // then 8 bytes of value data (none for NULL), padded to a multiple of 8. + fun rowWithValue( + type: Int, + stored: Int, + full: Int, + ): ByteArray { + val data = EventDecoder.ROW_HEADER_BYTES + EventDecoder.ROW_VALUE_BYTES + stored + val record = ByteBuffer.allocate((EventDecoder.HEADER_BYTES + data + 7) and 7.inv()).order(ByteOrder.LITTLE_ENDIAN) + record.putInt(0, record.capacity()) + record.putInt(4, EventKind.ROW.nativeValue) + record.putLong(8, 1) + record.putInt(52, data) + record.putLong(56, 1) + record.putLong(64, -1) + val row = EventDecoder.HEADER_BYTES + record.putInt(row, 1) + record.putInt(row + 4, 1) + val value = row + EventDecoder.ROW_HEADER_BYTES + record.put(value, type.toByte()) + record.put(value + 1, if (full > stored) 1 else 0) + record.putInt(value + 4, stored) + record.putInt(value + 8, full) + return record.array() + } + // whole values decode, so the refusals below are down to full_bytes + val integer = rowWithValue(1, 8, 8) + assertThat( + EventDecoder + .decode(integer, integer.size) + .single() + .row!! + .values, + ).containsExactly(0L) + val nothing = rowWithValue(5, 0, 0) + assertThat( + EventDecoder + .decode(nothing, nothing.size) + .single() + .row!! + .values, + ).containsExactly(null) + // INTEGER and FLOAT with 8 stored of 9, and NULL with 0 stored of 1, each flagged cut + for (broken in listOf(rowWithValue(1, 8, 9), rowWithValue(2, 8, 9), rowWithValue(5, 0, 1))) { + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(broken, broken.size) } + } + } + @Test fun `a row with more values than its bytes hold is refused before they are read`() { val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index 003408819f..19ef46f335 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -55,7 +55,10 @@ class FakeDebugEngine( /** Adds [event] as the next one, numbered after the events before it whatever its own [Event.seq]. */ fun addEvent(event: Event) { lastSeq++ - buffered.addLast(event.copy(seq = lastSeq)) + // A native STATEMENT's execution id is its own seq: keep it so when the seq changes. Null ids, and the + // parent ids of ROW and PROFILE events, stay as given. + val own = event.kind == EventKind.STATEMENT && event.executionId == event.seq + buffered.addLast(event.copy(seq = lastSeq, executionId = if (own) lastSeq else event.executionId)) } /** Drops the [count] oldest buffered events, as a full native buffer would. */ diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt index 806e788c60..094072fdbb 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt @@ -33,4 +33,27 @@ class FakeDebugEngineTest { assertThat(engine.readEvents(0, upTo - 1).events).hasSize(i) } } + + /** + * The native STATEMENT's execution id is its own seq, so the fake's renumbering moves it along. Null ids + * and the parent ids of other kinds are left as given. + */ + @Test + fun `renumbering a STATEMENT keeps its execution id equal to its seq`() { + val engine = FakeDebugEngine() + + fun event( + kind: EventKind, + seq: Long, + executionId: Long?, + ) = Event(seq, kind, 1, 1, seq, null, "SELECT 1", false, false, executionId = executionId) + engine.addEvent(event(EventKind.STATEMENT, 77, 77)) + engine.addEvent(event(EventKind.ROW, 78, 77)) + engine.addEvent(event(EventKind.STATEMENT, 79, null)) + engine.addEvent(event(EventKind.STATEMENT, 80, 77)) + + val events = engine.readEvents(0, Int.MAX_VALUE).events + assertThat(events.map { it.seq }).containsExactly(1L, 2L, 3L, 4L).inOrder() + assertThat(events.map { it.executionId }).containsExactly(1L, 77L, null, 77L).inOrder() + } } From 954de4ae1c57f4d4cbe8525fc4b8bcf28f6fd6d0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 18:16:25 -0800 Subject: [PATCH 45/45] ADFA-7379 get_events: the null cases in full; the JNI test names its statement Review findings on #2319 (an independent review of the ADFA-7379 code): - F07: get_events' description listed only some of the cases where execution_id is null. It now names them all, as #2311's README does: close, a trigger's statements, a statement an app function runs inside a callback, an EXPLAIN's profile, a statement whose start was not seen, and the later profile of a statement pushed out of its slot. It also says that a step that met a busy lock fires a profile with rows 0 before the run's rows. The README's get_events paragraph says the same. - F06: JniQueryTest only checked that a row's execution_id was the seq of some STATEMENT in the buffer, so an id off by one or naming an older statement still passed. It now requires the id to be the seq of the newest STATEMENT before the row, and that statement's SQL to be the query's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 8 ++++-- .../src/test/jni/JniQueryTest.java | 25 +++++++++++++------ 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 8594ad0145..2f1f3be757 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -51,7 +51,7 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Storage classes.** JSON alone cannot tell a REAL 2.0 from an INTEGER 2 (org.json writes both as `2`), or a big integer from TEXT, so `query` returns `storage_classes`, one string per row with a letter per column: `i` INTEGER, `r` REAL, `t` TEXT, `b` BLOB, `n` NULL. Row events carry the same string. - **Declared types.** `query` returns `column_types`, each column's `sqlite3_column_decltype`, `null` for an expression. - **Bound parameters (`.parameter`).** `query` and `explain_query_plan` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL, and the error names the key even when a parameter is also left without a value; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. -- **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. Every event has `execution_id` (ADFA-7379): a `statement` event's own `seq`, and on that run's `profile` and `row` events the same number, so rows of two statements stepped in turn are told apart; it is `null` for a trigger's statements, `close`, and a statement whose start was not seen. A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. +- **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. Every event has `execution_id` (ADFA-7379): a `statement` event's own `seq`, and on that run's `profile` and `row` events the same number, so rows of two statements stepped in turn are told apart; it is `null` for `close`, a trigger's statements, a statement an app function runs inside a callback, an EXPLAIN's `profile`, a statement whose start was not seen, and the later `profile` and `row` events of a statement pushed out of its slot. One run can have more than one `profile`, such as one with `rows` 0 from a step that met a busy lock, before the run's rows (the event format above lists every case). A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. - **Limits.** `execute` (ADFA-7298, a separate PR) binds positional `args` only until the two PRs meet. Row recording is one switch for the process: the last `get_events` call decides it. ## Decisions that shape it 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 539ef5fbee..fd8107fd00 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 @@ -356,8 +356,12 @@ class DatabaseTools internal constructor( "rows it returned; changes, the rows it changed itself, not through triggers, null for a read; null when the " + "statement's start was not seen), close, or row. execution_id names one run of a statement: a statement event's " + "own seq, and on that run's profile and row events the same number, so rows of statements stepped in turn " + - "are told apart by it; null for a trigger's statements, close, and a statement whose start was not seen. A run can " + - "have more than one profile (a retry after a schema change), or none at its end. " + + "are told apart by it. It is null for close, a trigger's statements, a statement an app function runs inside a " + + "callback (its SQL also starts with --), an EXPLAIN's profile, and a statement whose start was not seen; a " + + "statement pushed out after more than 16 were stepped in turn keeps its id on its statement event, but its " + + "later profile and row events have null. A run can have more than one profile (a retry after a schema " + + "change, or a profile with rows 0 from a step that met a busy lock, before the run's rows), or none at its " + + "end. " + "With include_rows true (the default), the app's statements " + "after the call also record their first $EVENT_ROWS_PER_STATEMENT rows as row events: row_number (from 1), " + "column_count, values, storage_classes and cut_values (indexes of TEXT and BLOB values cut at " + diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 88932cc4fc..5fe064fcf2 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -106,19 +106,30 @@ static long rowEvents() { * ADFA-7379: whether the newest row event names a statement event in the buffer by its execution_id (offset 72), * which is that statement event's seq (offset 8). */ - static boolean newestRowNamesItsStatement() { + /** + * The SQL of the STATEMENT event the newest ROW event names by execution_id, or null. The named event must be the + * newest STATEMENT before that row, and its seq must equal the id. + */ + static String newestRowStatementSql() { byte[] buf = new byte[1 << 20]; long[] out = new long[4]; NativeBridge.readEvents(0, buf, out); java.nio.ByteBuffer b = java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); - Set statements = new HashSet<>(); - long exec = 0; + long lastSeq = 0, rowExec = 0, rowStatementSeq = 0; + String lastSql = null, rowStatementSql = null; for (int at = 0; at < out[2]; at += b.getInt(at)) { int kind = b.getInt(at + 4); - if (kind == 1) statements.add(b.getLong(at + 8)); - if (kind == 4) exec = b.getLong(at + 72); + if (kind == 1) { + lastSeq = b.getLong(at + 8); + lastSql = new String(buf, at + 80, b.getInt(at + 52), StandardCharsets.UTF_8); + } + if (kind == 4) { + rowExec = b.getLong(at + 72); + rowStatementSeq = lastSeq; + rowStatementSql = lastSql; + } } - return exec != 0 && statements.contains(exec); + return rowExec != 0 && rowExec == rowStatementSeq ? rowStatementSql : null; } /** "code message" of a refused query with args bound by name, or null when it ran. */ @@ -260,7 +271,7 @@ public static void main(String[] a) throws Exception { NativeBridge.setRowCapture(1, 0, 0); eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording on"); eq(rowEvents(), rowsBefore + 1, "one row event: one row per statement"); - eq(newestRowNamesItsStatement(), true, "the row event names its statement event (ADFA-7379)"); + eq(newestRowStatementSql(), "SELECT id FROM t WHERE id < 3", "the row event names its own statement event (ADFA-7379)"); NativeBridge.setRowCapture(0, 0, 0); eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off again"); eq(rowEvents(), rowsBefore + 1, "off again");