From 67355bdbdfad3e3d311a060b4258ee122b43fd47 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 03:22:17 +0000 Subject: [PATCH 01/21] 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/21] 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/21] 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/21] 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/21] 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/21] 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/21] 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 0c9a19ea37b5fa712f40717a0135835b05294cd1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 15:21:05 -0800 Subject: [PATCH 08/21] 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 09/21] 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 5d8acf62d8211922906e33e2f999f6493c1df2b9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 16:20:35 -0800 Subject: [PATCH 10/21] 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 dd7ee1953149bed5fe5ad3e30acc3b33db0ed836 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 30 Nov 2026 23:49:28 -0800 Subject: [PATCH 11/21] 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 f4c3722c377ee7acf4ff0e1616e972e541e1bd80 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 00:48:28 -0800 Subject: [PATCH 12/21] 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 13/21] 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 14/21] 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 15/21] 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 90c62863698904d932d8490e0be104e6ef634200 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 1 Dec 2026 17:29:14 -0800 Subject: [PATCH 16/21] 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 17/21] 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 18/21] 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 19/21] 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 20/21] 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 21/21] 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() + } }