Inspiration
Every developer knows the 2:00 AM debugging nightmare: half the truth lives cleanly inside your relational database (like an order marked failed in SQLite), while the actual root cause—gateway timeouts, fraud declines, malformed payloads—is buried inside a multi-megabyte .log file.
Jumping back and forth between a SQL client and grep breaks your train of thought and makes correlation painful. Inspired by the Kiroween Stitch / Frankenstein theme, I wanted to stitch "dead" server logs and "live" relational databases into one unified, retro Windows 95–inspired browser workstation where both can be queried together in a single SQL JOIN—with zero setup and strict read-only safety.
What It Does
NecroQuery is a zero-trust, in-browser debugging workstation that unifies structured SQLite databases (.sqlite, .db) and unstructured server logs (.log) inside a per-session in-memory DuckDB engine:
- 1-Click Demo Mode: Boots live with pre-loaded relational tables (
customers,orders,products) andpayment_gateway.logdata so you can run cross-source joins in under a second. - Stitch Upload: Drag and drop up to 5 SQLite files and 5
.logfiles (up to $100\text{ MB}$ each), with an auto-mapped collapsible schema tree and instant replace-on-reupload semantics. - Plain-English NL-to-SQL (
NL_Translator): Ask questions in plain English, review or tweak the generated SQL preview before execution, and run it safely. - Zero-Trust
Query_Sanitizer: Strips SQL comments (--,/* ... */) and enforces a strict read-only policy before touching DuckDB—blocking mutating keywords (DROP,DELETE,ATTACH,COPY,INSERT,UPDATE,CREATE,ALTER) and path-traversal tokens (.., UNC paths, system directories). - Autopsy Time Machine (
Autopsy_Tool): Save timestamped session snapshots and compute visual schema diffs (added/removed tables, column type changes) alongside severity spike alerts. - Heartbeat Monitor & Exports: Real-time ECG-style query latency visualizer plus one-click RFC-4180 CSV and rollback SQL exports.
- MCP AI Agent Bridge: Exposes
GET /api/mcp/tool-schemaandPOST /api/mcp/queryso external AI agents can inspect schemas and run queries through the exact same sanitization gate.
How I Built It
1. Lossless Log Stitching & Relational Joins
Traditional log pipelines drop malformed lines. Log_Parser in stitch_engine/parsers.py scans every non-empty line against a compiled ISO-8601 + severity regex while guaranteeing zero raised exceptions—preserving malformed lines as severity = 'UNPARSED':
$$|L_{\text{view}}| = \bigl|{\ell \in L : \text{strip}(\ell) \neq \varepsilon}\bigr|$$
Once parsed, logs are registered as <view_name>.log_entries(timestamp, severity, user_id, message) alongside mounted SQLite schemas inside an isolated :memory: DuckDB instance (DuckDB_Connector). Cross-source correlation becomes a standard relational equijoin:
$$R_{\text{stitched}} = R_{\text{customers}} \bowtie_{\,c.\text{id} = o.\text{customer_id}} R_{\text{orders}} \bowtie_{\,\text{user_id} = \text{'u00'} \,|\, \text{CAST}(c.\text{id}\ \text{AS VARCHAR})} L_{\text{log_entries}}$$
Query execution enforces bounded resource guarantees with result cap $N_{\max} = 10{,}000$ rows and timeout $t_q \le 30\text{ s}$.
2. Snapshot Diffing & Error Spike Detection
In stitch_engine/autopsy.py, Autopsy_Tool captures a snapshot tuple $S_t = (\mathcal{S}_t, \mathcal{C}_t)$ containing full information_schema column signatures $\mathcal{S}_t$ and severity histograms $\mathcal{C}_t$. When comparing snapshot $S_A$ against $S_B$, log deltas and critical regressions are classified automatically:
$$\Delta(s) = \mathcal{C}_B(s) - \mathcal{C}_A(s), \qquad \text{is_spike}(s) = \bigl(s \in {\text{ERROR}, \text{FATAL}}\bigr) \land \bigl(\Delta(s) > 10\bigr)$$
3. Tech Stack & Testing
- Backend: Python, Django 4.2, DuckDB ($\ge 0.10$), Django Channels + Uvicorn (WebSockets locally) & WhiteNoise (
CompressedStaticFilesStorageon Vercel WSGI). - Frontend: Vanilla HTML/CSS/JavaScript styled in crisp Windows 95 CRT chrome with modular terminal, upload tree, Autopsy diff, and Heartbeat ECG windows.
- Verification: Tested with pytest and Hypothesis property-based tests—65/65 tests passing (
pytest tests/) covering log parsing round-trips, SQL injection sanitization, snapshot diffs, exports, and MCP endpoints.
Challenges I Faced
- Serverless Read-Only Filesystems & DuckDB SQLite Attachment on Vercel: On Vercel Python runtimes (
VERCEL=1),$HOMEis unset and only/tmpis writable, causing DuckDB's native extension installer to fail when executingATTACH ... (TYPE sqlite, READ_ONLY). I solved this by configuring DuckDBSET home_directoryto a writable temporary path and implementing_attach_sqlite_via_stdlib()institch_engine/connector.py—a read-onlysqlite3URI fallback (?mode=ro) that inspectssqlite_masterandPRAGMA table_infoand mirrors tables cleanly into in-memory DuckDB schemas. - Real-Time WebSockets vs. Stateless WSGI Deployment: Locally, NecroQuery streams results over Django Channels WebSockets, whereas serverless Python deployments do not maintain long-lived ASGI WebSocket loops. I engineered a dual-transport browser client (
ws_client.js) that gracefully bridges WebSockets locally and HTTP/sessions/<id>/send/+/poll/in serverless production with zero change to the UI. - Keeping Both Humans and AI Agents Strictly Read-Only: Supporting an MCP endpoint without widening the attack surface required normalizing SQL comments before lexical tokenization inside
Query_Sanitizer, ensuring hidden keywords or../traversals are rejected deterministically regardless of whether a query comes from a human or an AI agent.
What I Learned
- Zero-trust boundaries belong in the engine, not the UI: Putting
Query_Sanitizerdirectly in front of every DuckDB execution path meant the query terminal, NL-to-SQL translator, and MCP API all inherited identical safety guarantees. - Property-based testing pays off on parsers and sanitizers: Writing Hypothesis fuzz tests surfaced malformed timestamp encodings and edge-case comment obfuscations far faster than hand-written unit examples alone.
- Serverless compatibility rewards clean abstractions: Isolating storage roots (
/tmpvs. local directories) and dual-mode SQLite ingestion turned a host-environment blocker into a portable architecture.
Built With
- django
- duckdb
- javascript
- mcp
- openai
- python
- sql
- uvicorn
- websockets
- whitenoise