mirqab 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. mirqab-0.4.0/.gitignore +11 -0
  2. mirqab-0.4.0/LICENSE +21 -0
  3. mirqab-0.4.0/PKG-INFO +623 -0
  4. mirqab-0.4.0/README.md +591 -0
  5. mirqab-0.4.0/assets/mirqab-logo-dark.svg +9 -0
  6. mirqab-0.4.0/assets/mirqab-logo-light.svg +9 -0
  7. mirqab-0.4.0/assets/mirqab-mark-light.svg +5 -0
  8. mirqab-0.4.0/assets/mirqab-mark.svg +5 -0
  9. mirqab-0.4.0/clients/fixtures/review-stopped.json +39 -0
  10. mirqab-0.4.0/clients/fixtures/review.json +363 -0
  11. mirqab-0.4.0/docs/review.schema.json +324 -0
  12. mirqab-0.4.0/pyproject.toml +66 -0
  13. mirqab-0.4.0/src/mirqab/__init__.py +33 -0
  14. mirqab-0.4.0/src/mirqab/analyze/__init__.py +0 -0
  15. mirqab-0.4.0/src/mirqab/analyze/indexes.py +131 -0
  16. mirqab-0.4.0/src/mirqab/analyze/params.py +320 -0
  17. mirqab-0.4.0/src/mirqab/analyze/plans.py +454 -0
  18. mirqab-0.4.0/src/mirqab/analyze/sqltext.py +160 -0
  19. mirqab-0.4.0/src/mirqab/analyze/statements.py +420 -0
  20. mirqab-0.4.0/src/mirqab/api.py +148 -0
  21. mirqab-0.4.0/src/mirqab/cli.py +783 -0
  22. mirqab-0.4.0/src/mirqab/collect.py +363 -0
  23. mirqab-0.4.0/src/mirqab/config.py +230 -0
  24. mirqab-0.4.0/src/mirqab/export.py +181 -0
  25. mirqab-0.4.0/src/mirqab/fmt.py +85 -0
  26. mirqab-0.4.0/src/mirqab/llm.py +350 -0
  27. mirqab-0.4.0/src/mirqab/models.py +446 -0
  28. mirqab-0.4.0/src/mirqab/pipeline.py +182 -0
  29. mirqab-0.4.0/src/mirqab/py.typed +0 -0
  30. mirqab-0.4.0/src/mirqab/readonly.py +159 -0
  31. mirqab-0.4.0/src/mirqab/report_markdown.py +487 -0
  32. mirqab-0.4.0/src/mirqab/report_slack.py +393 -0
  33. mirqab-0.4.0/src/mirqab/slack.py +136 -0
  34. mirqab-0.4.0/src/mirqab/sources/__init__.py +20 -0
  35. mirqab-0.4.0/src/mirqab/sources/base.py +92 -0
  36. mirqab-0.4.0/src/mirqab/sources/metabase.py +89 -0
  37. mirqab-0.4.0/src/mirqab/sources/postgres.py +62 -0
  38. mirqab-0.4.0/src/mirqab/sqllex.py +125 -0
  39. mirqab-0.4.0/src/mirqab/state.py +158 -0
  40. mirqab-0.4.0/src/mirqab/trial.py +976 -0
  41. mirqab-0.4.0/tests/client_fixtures.py +114 -0
  42. mirqab-0.4.0/tests/conftest.py +21 -0
  43. mirqab-0.4.0/tests/fakes.py +395 -0
  44. mirqab-0.4.0/tests/fixtures/plans/conversation_events_join.json +104 -0
  45. mirqab-0.4.0/tests/fixtures/plans/events_sort_limit.json +47 -0
  46. mirqab-0.4.0/tests/fixtures/plans/orders_repeated_subplans.json +96 -0
  47. mirqab-0.4.0/tests/fixtures/plans/orders_seq_scan.json +28 -0
  48. mirqab-0.4.0/tests/fixtures/plans/presence_update.json +46 -0
  49. mirqab-0.4.0/tests/fixtures/plans/presence_update_placeholders.json +79 -0
  50. mirqab-0.4.0/tests/fixtures/plans/stages_update.json +29 -0
  51. mirqab-0.4.0/tests/fixtures/plans/users_pk.json +2 -0
  52. mirqab-0.4.0/tests/test_api.py +129 -0
  53. mirqab-0.4.0/tests/test_classify.py +353 -0
  54. mirqab-0.4.0/tests/test_cli.py +306 -0
  55. mirqab-0.4.0/tests/test_config.py +97 -0
  56. mirqab-0.4.0/tests/test_export.py +181 -0
  57. mirqab-0.4.0/tests/test_guard.py +61 -0
  58. mirqab-0.4.0/tests/test_inactive.py +130 -0
  59. mirqab-0.4.0/tests/test_indexes.py +113 -0
  60. mirqab-0.4.0/tests/test_integration.py +217 -0
  61. mirqab-0.4.0/tests/test_llm.py +266 -0
  62. mirqab-0.4.0/tests/test_metabase.py +117 -0
  63. mirqab-0.4.0/tests/test_params.py +121 -0
  64. mirqab-0.4.0/tests/test_placeholder_plans.py +146 -0
  65. mirqab-0.4.0/tests/test_readonly.py +114 -0
  66. mirqab-0.4.0/tests/test_slack.py +533 -0
  67. mirqab-0.4.0/tests/test_state.py +100 -0
  68. mirqab-0.4.0/tests/test_statements.py +123 -0
  69. mirqab-0.4.0/tests/test_trial.py +1041 -0
  70. mirqab-0.4.0/tests/test_trial_integration.py +333 -0
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[oc]
3
+ build/
4
+ dist/
5
+ wheels/
6
+ *.egg-info
7
+ .venv
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ mirqab-*.md
11
+ *.db
mirqab-0.4.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mirqab contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mirqab-0.4.0/PKG-INFO ADDED
@@ -0,0 +1,623 @@
1
+ Metadata-Version: 2.5
2
+ Name: mirqab
3
+ Version: 0.4.0
4
+ Summary: Periodic, read-only PostgreSQL performance review posted to Slack
5
+ Project-URL: Homepage, https://github.com/alialhawas/mirqab
6
+ Project-URL: Repository, https://github.com/alialhawas/mirqab
7
+ Project-URL: Issues, https://github.com/alialhawas/mirqab/issues
8
+ Author: mirqab contributors
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: index,performance,pg_stat_statements,postgres,postgresql,query review,slack
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Topic :: Database
21
+ Classifier: Topic :: System :: Monitoring
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: anthropic>=2.12.0
25
+ Requires-Dist: httpx>=0.28.1
26
+ Requires-Dist: psycopg[binary]>=3.3.9
27
+ Requires-Dist: rich>=15.0.0
28
+ Requires-Dist: sqlglot>=30.33.0
29
+ Requires-Dist: tomli-w>=1.2.0
30
+ Requires-Dist: typer>=0.29.2
31
+ Description-Content-Type: text/markdown
32
+
33
+ <p align="center">
34
+ <picture>
35
+ <source media="(prefers-color-scheme: dark)" srcset="assets/mirqab-logo-dark.svg">
36
+ <img src="assets/mirqab-logo-light.svg" alt="Mirqab, a lookout for your database" width="360">
37
+ </picture>
38
+ </p>
39
+
40
+ # Mirqab
41
+
42
+ Mirqab (مرقاب, a lookout post) keeps watch on your PostgreSQL database and reports what to fix, every two weeks, in Slack.
43
+
44
+ Mirqab reads `pg_stat_statements`, the table and index statistics and query plans, works out
45
+ which statements cost your application the most database time, says *why* in plain sentences, and suggests a candidate index when one is likely. It also reports index hygiene: unused,
46
+ duplicate and invalid indexes, foreign keys without an index, and vacuum state.
47
+
48
+ The analysis is deterministic. An LLM is optional: when you choose one, it rewrites the findings in
49
+ plain language from the measurements Mirqab already took (see [What is sent to the LLM](#what-is-sent-to-the-llm)).
50
+ With `none`, nothing leaves your network except the Slack message.
51
+
52
+ ```
53
+ *Mirqab review: shop*
54
+ 2026-11-08 to 2026-11-22 · 14 days
55
+
56
+ *7 findings · 98% of database time*
57
+
58
+ *1. UPDATE on UserPresenceSessions* · *46%* of database time
59
+ > Reads many rows through an index to return few · 83,000 calls/day · 36 ms per call
60
+
61
+ *2. SELECT on orders* · *20%* of database time
62
+ > Reads a whole big table; likely missing index · 9,000 calls/day · 140 ms per call
63
+ ...
64
+ ```
65
+
66
+ ## Read-only guarantee
67
+
68
+ Mirqab never writes to the database it reviews. It only reads it.
69
+
70
+ - Every query passes a guard before it is sent: the first keyword must be `SELECT`, `WITH`,
71
+ `EXPLAIN` or `SHOW`; more than one statement is refused; `EXPLAIN ANALYZE` is refused (it
72
+ executes the statement); `SELECT … INTO`, `FOR UPDATE/SHARE`, data-modifying CTEs and functions
73
+ that change server state (`pg_stat_statements_reset`, `pg_terminate_backend`, `set_config`,
74
+ `nextval`, …) are refused.
75
+ - A direct connection also sets `default_transaction_read_only = on`, `statement_timeout = '60s'`
76
+ and `application_name = 'mirqab'`.
77
+ - Plans use `EXPLAIN (GENERIC_PLAN, FORMAT JSON)` or plain `EXPLAIN (FORMAT JSON)`; neither runs the
78
+ statement.
79
+
80
+ The guard is a second line of defence. The first is a reader role that cannot write, and Mirqab
81
+ checks it every time (below). Nothing in this section changes when the staging trial is turned on.
82
+
83
+ ### The one place Mirqab writes: the optional trial database
84
+
85
+ If you set up a [staging trial](#staging-trial), Mirqab opens a second, separately configured connection to a
86
+ database that is not production. That database is the only place Mirqab ever writes, and the only thing it writes
87
+ there is one temporary index at a time, which Mirqab creates and drops again itself:
88
+
89
+ - The trial connection runs with `default_transaction_read_only = on`. It is turned off only around one
90
+ `CREATE INDEX CONCURRENTLY` or `DROP INDEX CONCURRENTLY IF EXISTS` statement, and turned on again right after.
91
+ - The `CREATE INDEX` accepts only the exact text Mirqab's candidate generator produces. Mirqab parses it, checks it is
92
+ byte for byte what the generator would write for those parts, renames the index to `mirqab_trial_<8 hex
93
+ characters>`, and rebuilds the statement with psycopg's SQL composition (identifiers and literals are quoted by
94
+ psycopg, nothing is pasted). Other DDL, several statements, a system schema, an expression index or a partial-index
95
+ condition with anything but columns, constants, `=`, `<>`, `IS [NOT] NULL/TRUE/FALSE`, `NOT` and `AND` is refused.
96
+ - `DROP` accepts only names that match `mirqab_trial_[0-9a-f]{8}`.
97
+ - Every other statement on the trial connection passes the same guard as above. The statement under test is only
98
+ ever run as a `SELECT` (an `UPDATE` or `DELETE` becomes `SELECT 1 FROM … WHERE …`), inside a `READ ONLY`
99
+ transaction with `SET LOCAL statement_timeout`. Mirqab never executes a write statement there.
100
+ - The index is dropped in a `finally` block, also when anything fails or times out (a failed concurrent build
101
+ leaves an invalid index; that is dropped too). A session starts by dropping any `mirqab_trial_…` index a crashed
102
+ run left behind, and holds an advisory lock so two Mirqab runs never test on the same database at once.
103
+ - Before every session Mirqab checks that the trial database is not a standby and is not the reviewed database
104
+ ([same-instance guard](#same-instance-guard)).
105
+
106
+ Building an index makes PostgreSQL refresh the table's size estimate in `pg_class`; Mirqab does not run `ANALYZE`
107
+ or change anything else.
108
+
109
+ ### Read-only check
110
+
111
+ `mirqab init`, `check`, `run` and `snapshot` first run one query that inspects the current role.
112
+ Mirqab stops, and `init` writes no config, when the role:
113
+
114
+ - is a superuser, or has `CREATEDB`, `CREATEROLE`, `REPLICATION` or `BYPASSRLS`;
115
+ - is a member of `pg_write_all_data`, `pg_write_server_files` or `pg_execute_server_program`;
116
+ - has `CREATE` on the database, or on any non-system schema;
117
+ - can `INSERT`, `UPDATE`, `DELETE` or `TRUNCATE` on any table, or owns any table.
118
+
119
+ `TEMP`, `pg_read_all_stats`, `pg_read_all_data` and `pg_monitor` are read-only and allowed. Through
120
+ Metabase, Mirqab also checks the API key: a key in the Administrators group is refused
121
+ (`GET /api/user/current` returns `is_superuser`). There is no override.
122
+
123
+ When the check fails, Mirqab prints each problem in one sentence and the SQL for a dedicated role,
124
+ with your database and schemas filled in:
125
+
126
+ ```sql
127
+ CREATE ROLE mirqab_reader LOGIN PASSWORD '<choose a password>';
128
+ GRANT CONNECT ON DATABASE "app" TO mirqab_reader;
129
+ GRANT pg_read_all_stats TO mirqab_reader;
130
+ GRANT USAGE ON SCHEMA "public" TO mirqab_reader; -- per non-system schema
131
+ GRANT SELECT ON ALL TABLES IN SCHEMA "public" TO mirqab_reader;
132
+ ALTER DEFAULT PRIVILEGES IN SCHEMA "public" GRANT SELECT ON TABLES TO mirqab_reader;
133
+ ALTER ROLE mirqab_reader SET default_transaction_read_only = on;
134
+ ```
135
+
136
+ On PostgreSQL 14 and older every role has `CREATE` on schema `public` by default, so the check fails
137
+ until an administrator runs `REVOKE CREATE ON SCHEMA public FROM PUBLIC;` (this affects every role;
138
+ check that your application does not create objects in `public` first).
139
+
140
+ ## Requirements
141
+
142
+ - PostgreSQL 13 or newer with `pg_stat_statements` in `shared_preload_libraries` and
143
+ `CREATE EXTENSION pg_stat_statements;` run in the reviewed database. Generic plans
144
+ need 16+ (older servers get plans with placeholder values); `stats_since` and `last_idx_scan`
145
+ are used on 16+/17 when present.
146
+ - `track_io_timing = on` is recommended; without it the report says "disk time not tracked".
147
+ - Python 3.11+.
148
+
149
+ ### Reader role
150
+
151
+ Use the role from [Read-only check](#read-only-check). `pg_read_all_data` (PostgreSQL 14+) can replace
152
+ the per-schema `SELECT` grants, and `pg_monitor` can replace `pg_read_all_stats`. Without either of the
153
+ last two, statements of other roles show up as `<insufficient privilege>` and the report tells you so.
154
+
155
+ PostgreSQL checks write privileges even for a plain `EXPLAIN` of `UPDATE`/`DELETE`. When planning
156
+ fails with "permission denied", mirqab plans the equivalent `SELECT 1 FROM <table> WHERE <same
157
+ condition>` instead and says so in the finding. The scan part of the plan is the same.
158
+
159
+ ### Metabase
160
+
161
+ Mirqab can read through Metabase instead of connecting directly. It calls
162
+ `POST /api/dataset` with a native query, so the API key needs a Metabase group with **native query
163
+ (SQL) access** to the database. The database connection configured in Metabase is what runs the
164
+ queries, so give *that* connection the read-only role above. Create the API key in its own group
165
+ (Admin → Settings → Authentication → API keys), not in Administrators. Metabase returns at most
166
+ 2,000 rows per query; mirqab pages with `ORDER BY … LIMIT 2000 OFFSET n`.
167
+
168
+ ## Quick start
169
+
170
+ ```bash
171
+ uv tool install mirqab # or: pipx install mirqab
172
+ mirqab init # database, Slack, LLM; writes ~/.config/mirqab/config.toml (0600)
173
+ mirqab run --dry-run # prints the Slack messages and writes mirqab-YYYY-MM-DD.md; sends nothing
174
+ mirqab run # collect, analyse, post
175
+ mirqab schedule # prints a crontab and a GitHub Actions workflow
176
+ ```
177
+
178
+ Other commands: `mirqab check` (connection, read-only access, privileges, Slack, LLM and staging trial settings),
179
+ `mirqab snapshot` (store counters; run daily). Every command runs without prompts when the config
180
+ file or the environment provides what it needs; `mirqab init --yes` accepts defaults.
181
+
182
+ ## Set-up
183
+
184
+ `mirqab init` walks through three steps and an optional fourth, then asks for the review period.
185
+
186
+ 1. **Database.** Choose `metabase` or `postgres`.
187
+ - Metabase: Mirqab explains where to create the API key and asks for the URL, the key (hidden)
188
+ and the database id (it lists the PostgreSQL databases it can see).
189
+ - Postgres: Mirqab prints the reader-role SQL, then asks for a DSN (hidden). Leave it empty to
190
+ enter host, port (5432), database, user and password one by one; Mirqab builds and URL-encodes
191
+ the DSN.
192
+
193
+ Then it tests the connection and runs the [read-only check](#read-only-check). If the access can
194
+ change data, `init` prints the problems and the role SQL and exits without writing the config.
195
+ Last, it shows the roles it found and asks which ones are the application.
196
+ 2. **Slack.** Choose `bot` (default), `webhook` or `none`.
197
+ - `bot`: Mirqab prints a link (and opens it unless `--no-browser`) that creates a Slack app named
198
+ Mirqab from a manifest with one bot scope, `chat:write`. Sign in, pick the workspace, Create,
199
+ Install to Workspace, then copy the "Bot User OAuth Token" (`xoxb-…`). Mirqab checks the token
200
+ with `auth.test`, shows the workspace and bot name, and warns when the token is a user token or
201
+ has more scopes than `chat:write`. Then give a channel id (`C…`; run `/invite @Mirqab` there
202
+ first) or a member id (`U…`; profile → ⋮ → Copy member ID) for direct messages.
203
+ - `webhook`: Slack app → Incoming Webhooks → Add New Webhook, then paste the URL.
204
+ 3. **LLM.** Choose `anthropic` (default), `openai` (any OpenAI-compatible Chat Completions
205
+ endpoint) or `none`.
206
+ - `anthropic`: model `claude-opus-5-5` by default. The API key may be left empty; the Anthropic
207
+ SDK then finds credentials itself (`ANTHROPIC_API_KEY` and the other methods it supports).
208
+ - `openai`: base URL `https://api.openai.com/v1` by default; type the model name your endpoint
209
+ expects. The key may be empty for a local server.
210
+ - Mirqab offers to send one short test request.
211
+ 4. **Staging trial (optional).** See [Staging trial](#staging-trial). Default: no.
212
+
213
+ The last question is whether to store the secrets in the config file. Answer no to supply them by
214
+ environment variable instead.
215
+
216
+ `mirqab init --yes` asks nothing. Without `--llm-provider`, it keeps the configured LLM, or `none`
217
+ when there is none, so a non-interactive set-up never starts sending data to an LLM by itself. It
218
+ sends no Slack test message and does not call `auth.test`.
219
+
220
+ | Flag | Meaning |
221
+ |---|---|
222
+ | `--source`, `--metabase-url`, `--database-id` | database step |
223
+ | `--app-roles` | application roles, comma-separated |
224
+ | `--slack-method`, `--slack-channel`, `--no-browser` | Slack step |
225
+ | `--llm-provider`, `--llm-model`, `--llm-base-url` | LLM step |
226
+ | `--trial`, `--no-trial` | staging trial step (with `--yes`, `--trial` needs `MIRQAB_TRIAL_DSN`) |
227
+ | `--period-days` | review period |
228
+
229
+ Secrets have no flags; use the environment variables below.
230
+
231
+ ### What is sent to the LLM
232
+
233
+ One request per run, covering at most 8 findings. For each finding: the statement text as PostgreSQL
234
+ stores it (values are already replaced by `$1`, `$2`…), calls, share of time, mean time, rows and
235
+ blocks per call, the diagnosis and Mirqab's own explanation, the plan shape, the candidate index, and
236
+ the tables involved with row counts, sizes and existing index names and columns, plus the other
237
+ reviewed statements that read or write the candidate's table, and, when a staging trial ran, its status and
238
+ the before and after numbers (blocks and time per call, estimated cost), and the name of an equivalent index the
239
+ trial database already has. For the database: its name, version,
240
+ the period, the number of findings and the index hygiene counts. Table rows are never sent.
241
+
242
+ The answer is used only when it is valid JSON. Text for a finding is dropped, and Mirqab's built-in
243
+ explanation is kept, when it names an unknown finding or contains `CREATE INDEX` or `DROP INDEX`.
244
+ Any failure (key, rate limit, network, refusal, invalid answer, timeout) prints one line, "LLM
245
+ explanations skipped: …", and the run continues with the built-in report.
246
+
247
+ In the report, the LLM text comes first under "In plain words"; Mirqab's measurements and candidate
248
+ SQL follow unchanged. The overview goes at the top of the Markdown report and into the Slack
249
+ "Report details" reply, with the footer "Explanations written by <model> from the measurements shown. Verify before acting."
250
+
251
+ Turn it off for one run with `mirqab run --no-llm`, or for good with `provider = "none"`.
252
+ `--dry-run` still asks the LLM, because it previews what would be posted.
253
+
254
+ ### Secrets
255
+
256
+ The wizard can store secrets in the config file (mode 0600). Environment variables take
257
+ precedence and are never written to the file by `init`:
258
+
259
+ | Variable | Meaning |
260
+ |---|---|
261
+ | `MIRQAB_POSTGRES_DSN` | direct connection string |
262
+ | `MIRQAB_METABASE_API_KEY` | Metabase API key |
263
+ | `MIRQAB_SLACK_TOKEN` | Slack bot token (`chat:write` scope) |
264
+ | `MIRQAB_SLACK_WEBHOOK_URL` | Slack incoming webhook |
265
+ | `MIRQAB_LLM_API_KEY` | LLM API key (Anthropic or OpenAI-compatible) |
266
+ | `MIRQAB_TRIAL_DSN` | staging trial database connection string |
267
+ | `MIRQAB_CONFIG`, `MIRQAB_STATE` | config and state paths |
268
+
269
+ Secrets are masked in all output.
270
+
271
+ ### Settings (`[review]` in the config)
272
+
273
+ | Setting | Default | Meaning |
274
+ |---|---|---|
275
+ | `period_days` | 14 | review window |
276
+ | `app_roles` | `[]` | roles whose statements are reviewed; empty = picked automatically |
277
+ | `min_calls` | 1000 | minimum calls in the period |
278
+ | `min_time_share_pct` | 1.0 | minimum share of the reviewed roles' time |
279
+ | `max_findings` | 8 | findings per report |
280
+ | `unused_index_min_mb` | 10 | smallest index reported as unused |
281
+ | `unused_index_days` | 30 | on 16+, an index not scanned for this long counts as unused |
282
+ | `big_table_rows` | 100000 | "big table" threshold for plan rules |
283
+
284
+ ### LLM (`[llm]` in the config)
285
+
286
+ | Setting | Default | Meaning |
287
+ |---|---|---|
288
+ | `provider` | none | `anthropic`, `openai` or `none` |
289
+ | `model` | `claude-opus-5-5` for anthropic | model id |
290
+ | `base_url` | `https://api.openai.com/v1` | OpenAI-compatible endpoint (openai only) |
291
+ | `api_key` | empty | stored only if you chose to store secrets; `MIRQAB_LLM_API_KEY` wins |
292
+
293
+ ### Staging trial (`[trial]` in the config)
294
+
295
+ | Setting | Default | Meaning |
296
+ |---|---|---|
297
+ | `dsn` | empty | stored only if you chose to store secrets; `MIRQAB_TRIAL_DSN` wins |
298
+ | `confirmed_not_production` | false | set by `init` after you confirm; without it no trial runs |
299
+ | `runs` | 3 | measured runs per statement, after one warm-up; the median is reported |
300
+ | `statement_timeout_ms` | 30000 | limit for each read on the trial database |
301
+ | `build_timeout_s` | 600 | limit for building (and dropping) one trial index |
302
+
303
+ ### Slack
304
+
305
+ - **Bot token** (`chat:write`): the summary goes to a channel id (`C…`, invite the bot) or a user id
306
+ (`U…`, a direct message). The thread holds the detail: "Report details" (period, notes, roles,
307
+ thresholds, staging trial, statements no longer running), one reply per finding, other database users and
308
+ index clean-up.
309
+ - **Incoming webhook**: one message; the detail is appended below the summary up to Slack's size
310
+ limit, followed by the path of the full Markdown report.
311
+
312
+ The summary has one bold line per finding (label and share of database time) and one sentence that
313
+ names the rule and the measured numbers that triggered it, for example "Filters after a row-by-row
314
+ join: 11,916 blocks per call for 1 row." The Markdown report's Summary uses the same sentence. When a staging
315
+ trial tested the finding, a short clause follows:
316
+
317
+ - "Trial: confirmed, 5,200 → 24 blocks." (or "cost 7,629 → 8.4" when nothing was measured)
318
+ - "Trial: index used, small gain, 5,200 → 3,000 blocks."
319
+ - "Trial: index used, no gain, 900 → 1,200 blocks." (unchanged or rising)
320
+ - "Trial: index used, already cheap on staging, 1 → 2 blocks." (both under 10 blocks, or under 10 cost units)
321
+ - "Trial: staging already has this index."
322
+ - "Trial: index not used." or "Trial: could not test."
323
+
324
+ ## JSON output
325
+
326
+ `mirqab run --json` prints exactly one JSON document to stdout and nothing else; progress, the dry-run preview,
327
+ tables and warnings go to stderr. It combines with `--dry-run` (no Slack post), `--trial`/`--no-trial`, `--no-llm`,
328
+ `--no-slack` and `--output` (the Markdown report is still written).
329
+
330
+ ```bash
331
+ mirqab run --json --dry-run --no-llm --output /tmp/mirqab.md > review.json
332
+ ```
333
+
334
+ Exit codes do not change. When the run fails before a review exists (configuration, connection, read-only check),
335
+ stdout carries `{"schema": 1, "error": "<message>"}` and the exit code is not 0. When the review exists but the Slack
336
+ post fails, stdout carries the full review with `slack.error` set, and the exit code is 1.
337
+
338
+ The document never holds secrets or the sample values used on the trial database. Numbers are JSON numbers
339
+ (percentages as 0–100, `disk_share` as 0–1, times in milliseconds), timestamps are ISO 8601 UTC
340
+ (`2026-11-22T06:00:00Z`), and absent values are `null`. The schema is
341
+ [`docs/review.schema.json`](docs/review.schema.json) (JSON Schema draft 2020-12); example documents are
342
+ [`clients/fixtures/review.json`](clients/fixtures/review.json) and
343
+ [`clients/fixtures/review-stopped.json`](clients/fixtures/review-stopped.json).
344
+
345
+ | Field | Contents |
346
+ |---|---|
347
+ | `schema` | `1` |
348
+ | `mirqab_version`, `database`, `source`, `server_version` | strings; `source` carries no credentials |
349
+ | `generated_at` | when the review was made |
350
+ | `stopped` | why the review stopped early (for example `pg_stat_statements` is missing), or `null` |
351
+ | `period` | `start`, `end`, `days`, `first_run`; `null` when stopped |
352
+ | `covered_share_pct` | the findings' share of the reviewed roles' time |
353
+ | `notes` | strings |
354
+ | `roles` | `reviewed` (names), `auto_selected`, `ignored` (`role`, `reason`) |
355
+ | `thresholds` | `min_calls`, `min_share_pct` |
356
+ | `findings[]` | `rank`, `label`, `kind`, `tables`, `role`, `queryid`, `rule` (the diagnosis code), `headline`, `reason`, `explanation`, `share_pct`, `calls`, `calls_per_day`, `mean_ms`, `blocks_per_call`, `rows_per_call`, `disk_share`, `flags`, `candidate_index`, `plan_note`, `statement`, `explained`, `trial` |
357
+ | `findings[].explained` | the LLM's `what_it_does`, `why_slow`, `what_to_try`, `watch_out`, or `null` |
358
+ | `findings[].trial` | `null`, or `status`, `sentence`, `reason`, `trial_rows`, `production_rows`, `build_ms`, `index_bytes`, `blocks_before`, `blocks_after`, `ms_before`, `ms_after`, `cost_before`, `cost_after`, `timed_out_before`, `timed_out_after`, `existing_index`, `existing_index_used`, `missing_samples`, `unanalyzed_tables`. With `already_present` only the `*_after` numbers are set: they describe the trial database as it is, with its existing index |
359
+ | `inactive[]` | statements that stopped running: `label`, `share_pct`, `calls_per_day`, `expected_calls` |
360
+ | `previous_reading` | the reading the inactive check compared with, or `null` |
361
+ | `hygiene` | `unused[]` (`index`, `table`, `schema`, `bytes`, `scans`, `last_scan`, `table_writes`), `duplicates[]` (`index`, `table`, `schema`, `bytes`, `scans`, `covered_by`), `invalid[]` (`index`, `table`, `schema`, `bytes`), `fk_missing[]` (`constraint`, `table`, `schema`, `columns`, `referenced_table`, `table_rows`) |
362
+ | `other_users[]` | `role`, `share_pct`, `hours`, `slow_statements`, `heaviest[]` (`statement`, `calls`, `mean_ms`, `blocks_per_call`) |
363
+ | `llm` | `model`, `overview`, or `null` |
364
+ | `trial` | `database`, `host`, `role`, `tested`, `candidates`, `reason`, `warnings`, or `null` |
365
+ | `slack` | `posted`, `messages` (count), `error` |
366
+ | `report_path` | the Markdown report this run wrote, or `null` |
367
+
368
+ ## Use as a library
369
+
370
+ ```python
371
+ import mirqab
372
+
373
+ config = mirqab.load_config() # or load_config("path/to/config.toml")
374
+ review = mirqab.run_review(config, state_path="state.db", llm=False, trial=None,
375
+ progress=print) # collects and analyses; never posts
376
+ for finding in review.findings:
377
+ print(finding.rank, finding.label, f"{finding.share_pct:.0f}%", finding.candidate_index or "")
378
+ markdown = mirqab.render_markdown(review) # the full report
379
+ document = mirqab.review_to_dict(review) # the `--json` document
380
+ mirqab.post_to_slack(review, config) # returns the number of messages sent
381
+ ```
382
+
383
+ `run_review` applies the same read-only check as the command line and raises `mirqab.ReadOnlyError` (with the
384
+ problems in `.report`) for a source that can change data. It raises `mirqab.ConfigError` for an incomplete
385
+ configuration and `mirqab.SourceError` when the database cannot be read. `trial=None` runs the staging trial when
386
+ it is configured, `True` asks for it, `False` turns it off. `render_slack(review)` returns the Slack messages
387
+ without sending them. The package ships type hints (`py.typed`). `mirqab run` calls the same functions.
388
+
389
+ ## How the two-week window works
390
+
391
+ `pg_stat_statements` counters only ever grow until someone resets them, so a review needs two
392
+ points in time. Each `mirqab run` and `mirqab snapshot` stores a snapshot of the counters in
393
+ SQLite (`~/.local/state/mirqab/state.db`). A review compares the newest snapshot with the stored
394
+ one closest to `period_days` ago (anything from half to twice the period is accepted).
395
+
396
+ - **First run** (no usable snapshot): the figures are totals since the statistics were last reset,
397
+ and the report says so: "first run: figures cover N days since the statistics were last reset".
398
+ Totals that old can include statements whose code was since changed or removed. When a snapshot
399
+ at least 30 minutes old exists (taken after the reset), a statement whose call count has not
400
+ moved since then, although its average rate predicts at least 50 calls in that gap, is not
401
+ ranked; the report lists it under "No longer running". Its time stays in the totals. Without
402
+ such a snapshot, the report says that stopped statements can still appear.
403
+ - A statement whose counters went backwards (reset, or evicted and re-added) uses zero as its
404
+ baseline. On 17+, a statement whose `stats_since` is newer than the baseline does too, and its
405
+ per-day rate uses its own age.
406
+ - Snapshots taken before the latest statistics reset are ignored.
407
+
408
+ Run `mirqab snapshot` daily (see `mirqab schedule`) so a baseline of the right age exists.
409
+ On GitHub Actions, the workflow keeps `state.db` in the Actions cache between runs.
410
+
411
+ ## Who is "the application"?
412
+
413
+ Only statements of `app_roles` are reviewed, and percentages are shares of *their* time. `init`
414
+ shows every role with its calls, time and heaviest statement, and pre-selects all roles except:
415
+
416
+ - managed-service monitoring (heaviest statement is `pg_sleep` or mentions "rds internal"), and
417
+ - roles that spend more than half of their time in statements called fewer than `min_calls` times
418
+ (people and BI tools running ad-hoc SQL).
419
+
420
+ You confirm or edit the list. The report footer lists ignored roles and why.
421
+
422
+ ## How plans are made
423
+
424
+ Statement text from `pg_stat_statements` contains `$1`, `$2`… in place of values.
425
+
426
+ - **Direct connection to PostgreSQL 16+**: `EXPLAIN (GENERIC_PLAN, FORMAT JSON) <text>` plans the
427
+ text as it is. The finding says "generic plan".
428
+ - **Metabase, or PostgreSQL below 16**: Metabase's JDBC driver uses the extended protocol, so the
429
+ server treats `$1` as a bind parameter that is never supplied (`bind message supplies 0
430
+ parameters`). Mirqab never sends `$n` through Metabase. Instead it reads the column types of the
431
+ tables involved, infers each `$n`'s type from where it is used (`col = $1`, `$2 = col`, `IN`,
432
+ `ANY`, `BETWEEN`, `LIKE`, `SET col = $1`, `INSERT … VALUES`, `$1::type`), and replaces it with
433
+ `(SELECT NULL::<type>)`. The planner treats that like a parameter (an InitPlan), so index
434
+ conditions stay usable; a bare `NULL` would be folded away. `LIMIT $n` becomes the statement's
435
+ rows per call (1 to 1,000; 50 when unknown), `OFFSET $n` becomes 0, a bare `SELECT $n` becomes
436
+ `1`, and a parameter used as a condition on its own becomes `true`. Literals, comments and
437
+ dollar-quoted strings are never changed. Then plain `EXPLAIN (FORMAT JSON)` runs. The finding
438
+ says "plan with placeholder values". If a type cannot be inferred and the plan fails, the
439
+ finding says "plan not available: could not infer the type of $n".
440
+
441
+ ## Other database users
442
+
443
+ Roles that are not reviewed (BI tools, people running SQL) still slow the application down. The
444
+ report lists every such role with at least 1% of all database time in the period: its share, its
445
+ hours and its three heaviest statements (calls, mean seconds, blocks per call). Managed-service
446
+ monitoring roles and mirqab's own reader role are left out.
447
+
448
+ ## What a finding says
449
+
450
+ Each finding has one diagnosis:
451
+
452
+ | Diagnosis | Meaning |
453
+ |---|---|
454
+ | `lock_wait` | a write with mean ≥ 100 ms but < 200 blocks per call: it waits on locks; an index will not help |
455
+ | `repeated_subquery` | the plan runs the same lookup several times (SubPlans/InitPlans/lateral); rewrite the query |
456
+ | `seq_scan_big_table` | a sequential scan with a filter on a big table; candidate index on the filter columns |
457
+ | `index_then_filter` | an index scan reads many blocks per row returned and a filter is checked on each row; candidate partial or composite index, which helps only if the filter is what removes the rows |
458
+ | `join_then_filter` | a join looks up one row per outer row and filters after the lookup; no single-table index fixes it |
459
+ | `sort_before_limit` | sorts all matching rows to return a few |
460
+ | `high_frequency` | cheap per call but ≥ 50,000 calls/day; reduce the calls |
461
+ | `heavy_read` | ≥ 1,000 blocks per call and no pattern matched; run `EXPLAIN (ANALYZE, BUFFERS)` yourself |
462
+ | `review_manually` | listed for its share of time only |
463
+
464
+ Every candidate index comes with its consequences: the table's size and existing indexes, the
465
+ other reviewed statements that write to the table (each call maintains one more index entry) and
466
+ read it (their plans may change). The benefit is bounded by the statement's share of time.
467
+ **Candidates are not verified fixes. Test them on a copy of the database before applying.** The
468
+ [staging trial](#staging-trial) does the first part of that test for you.
469
+
470
+ ## Staging trial
471
+
472
+ When Mirqab suggests a candidate index, it can test it on a staging database you connect during set-up, and report
473
+ whether the index works there and how much it changes the statement.
474
+
475
+ **What it shows.** Whether the planner on that database chooses the candidate index for the statement, the plan
476
+ before and after (scan node, index, estimated cost), and, when sample values are available, the measured shared
477
+ blocks and execution time per call before and after (median of `runs` runs after one warm-up), plus how long the
478
+ index took to build and its size. Each finding gets a block "Tested on <database>" after "What to try", with a
479
+ result:
480
+
481
+ | Status | Meaning |
482
+ |---|---|
483
+ | `confirmed` | the planner uses the index, and blocks per call (or the estimated cost, when nothing was measured) fall by at least half |
484
+ | `used_small_gain` | the planner uses the index, but the numbers fall by less than half, stay the same or rise; the sentence says which. When before and after are both under 10 blocks (or 10 cost units), it says the statement is already cheap on the trial database, so the test cannot show a difference |
485
+ | `not_used` | the planner does not choose the index |
486
+ | `already_present` | the trial database already has an equivalent index (below); Mirqab builds nothing and reports its name, the current plan, the measurement when sample values exist, and whether the planner uses that index |
487
+ | `untested` | "could not test: <reason>" |
488
+
489
+ **An equivalent index already exists.** Before building, Mirqab compares the candidate with the valid indexes of
490
+ that table on the trial database: same access method (btree), default operator classes, no expressions, the same
491
+ key columns in the same order, and the same partial-index condition after normalising whitespace, quoting,
492
+ redundant parentheses, the type casts PostgreSQL adds when it stores the condition, and the order of `AND` terms
493
+ (the condition comes from `pg_get_expr`). Uniqueness and `INCLUDE` columns are not compared. If one matches, nothing
494
+ is built.
495
+
496
+ **What it cannot show.** How much time production saves. A staging database is usually smaller, has different data
497
+ and cache, other hardware and no production load, so its timings do not carry over. Blocks per call and the plan
498
+ choice carry over better, and only when the data is similar. When the trial table has fewer than 10% of
499
+ production's rows, the finding says: "The trial table has N rows; production has ~M. This shows the index is used,
500
+ not how much time production saves." The trial also does not measure what the index costs writes, or how it
501
+ changes other statements' plans; the finding's "What the change touches" still applies.
502
+
503
+ **How a finding is tested.** One finding at a time, never two trial indexes at once:
504
+
505
+ 1. The candidate's table and columns must exist on the trial database, and the role must be able to index it.
506
+ 2. The statement, without comments, becomes a `SELECT`. `UPDATE` and `DELETE` use their `SELECT 1 FROM … WHERE …`
507
+ form; other statements cannot be tested.
508
+ 3. Each `$n` gets a sample value from that database's own `pg_stats` (no table rows are read): `col = $n`, `IN` and
509
+ `LIKE` take the column's most common value (or the middle histogram bound when there are no common values),
510
+ `= ANY($n)` a one-element array of it, `>`/`>=` the histogram bound three quarters of the way up, `<`/`<=` the
511
+ last bound, `LIMIT` the statement's rows per call, `OFFSET` 0, a bare condition `true`. Values are quoted by psycopg
512
+ and cast to the column type. The report names the kind of value ("the most common values on the trial database")
513
+ but never the values themselves. If any `$n` has no sample, nothing is measured and only the plans are compared;
514
+ the report says which parameters had none. When a sample is missing because a table has never been analysed on
515
+ the trial database (no `pg_stats` rows, and not known to be empty), the report says so: "Table X has no
516
+ statistics on the trial database. Run ANALYZE "X" there and try again." Mirqab never runs `ANALYZE` itself.
517
+ 4. Before: the plan (`EXPLAIN (GENERIC_PLAN)` on PostgreSQL 16+, placeholder values below 16), then
518
+ `EXPLAIN (ANALYZE, BUFFERS)` of the `SELECT` in a `READ ONLY` transaction.
519
+ 5. The trial index is built with `CREATE INDEX CONCURRENTLY` under `build_timeout_s`.
520
+ 6. After: the same plan and measurement.
521
+ 7. The index is dropped, whatever happened.
522
+
523
+ A trial failure never fails the review; the finding then says "could not test" and why.
524
+
525
+ **Set-up.** `mirqab init` step 4 explains the above and asks "Test suggested indexes on a staging database? [y/N]".
526
+ Give a DSN (hidden) or leave it empty to enter the staging endpoint (host), port, database, user and password or
527
+ token one by one. Mirqab then checks and prints: that it connects, that it is not a standby, that it is not the
528
+ reviewed database, and on how many user tables the role can create an index (it refuses when none). Last, it asks
529
+ "Mirqab will create and drop temporary indexes on database <db> at <host>. Confirm this is not a production
530
+ database [y/N]". Without that confirmation the trial is not saved; the rest of the set-up still is.
531
+ `mirqab check` shows a "Staging trial" row: not configured, ready (database, role, tables it can index), or the
532
+ problem.
533
+
534
+ The trial needs a direct PostgreSQL connection (Metabase cannot create indexes); the reviewed database can still be
535
+ read through Metabase.
536
+
537
+ **The role it needs.** Only a table's owner (or a member of the owner role) can create an index on it, and creating
538
+ one also needs `CREATE` on the table's schema. On the staging server, as an administrator:
539
+
540
+ ```sql
541
+ CREATE ROLE mirqab_trial LOGIN PASSWORD '<choose a password>';
542
+ GRANT app_owner TO mirqab_trial; -- the role that owns the application tables
543
+ GRANT CREATE ON SCHEMA public TO mirqab_trial; -- only if app_owner does not have it already
544
+ ```
545
+
546
+ This role can change the staging data. Mirqab does not use that ability beyond the trial index, but use a database
547
+ you could restore, never production.
548
+
549
+ **Flags.**
550
+
551
+ | Command | Flag | Meaning |
552
+ |---|---|---|
553
+ | `run` | (none) | trials run when the trial is configured and confirmed |
554
+ | `run` | `--dry-run` | trials do not run (a dry run does not write anywhere by surprise); Mirqab says so |
555
+ | `run` | `--trial` | run trials, also in a dry run |
556
+ | `run` | `--no-trial` | do not run trials |
557
+ | `init` | `--trial` | skip the first question; with `--yes`, enables the trial from `MIRQAB_TRIAL_DSN` and counts as the confirmation |
558
+ | `init` | `--no-trial` | remove a configured trial |
559
+
560
+ `init --yes` without either flag keeps whatever is configured. If `init --yes --trial` finds a problem, it saves the
561
+ rest of the set-up, prints the problem and exits with status 1.
562
+
563
+ ### Same-instance guard
564
+
565
+ `init`, `check` and every trial session run this query on the reviewed source (through Metabase too) and on the trial
566
+ connection:
567
+
568
+ ```sql
569
+ SELECT current_database() AS db,
570
+ to_char(pg_postmaster_start_time() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.US') AS started,
571
+ inet_server_addr()::text AS addr, inet_server_port() AS port, pg_is_in_recovery() AS in_recovery
572
+ ```
573
+
574
+ When `db` and `started` are equal, the two connections reach the same database on the same running server, and
575
+ the trial is refused: "the trial database is the database being reviewed". The address and port are not needed for
576
+ that decision, because one server can be reached through several addresses. Mirqab does not use the system
577
+ identifier: a staging database restored from a production backup shares it.
578
+
579
+ Two cases the guard cannot refuse, so it warns instead: a different database on the same server as the reviewed one
580
+ (the index build then uses that server's disk and CPU), and a reviewed database that is a standby (Mirqab cannot
581
+ tell whether the trial database is its primary).
582
+
583
+ ## Getting endpoint names in the report
584
+
585
+ If a statement's text carries a leading or trailing SQL comment, the report shows it as the caller
586
+ instead of the table names. `pg_stat_statements` keeps the comment of the first execution it saw.
587
+
588
+ - **EF Core**: `query.TagWith("GetOpenSessions")` or `TagWithCallSite()` adds `-- …` lines.
589
+ - **sqlcommenter** (`/* route='…',controller='…' */`): available for Django, Rails (`marginalia` /
590
+ Rails 7 `query_log_tags`), Node (Knex, Sequelize, TypeORM), Go, Java (Hibernate) and
591
+ OpenTelemetry instrumentations. mirqab shows `route`, `controller` and `action` when present.
592
+
593
+ ## Limitations
594
+
595
+ - PostgreSQL only; supports 13+ and works best on 16+/17.
596
+ - Plans are made without real parameter values (generic plans on 16+, placeholder values
597
+ otherwise), so they can differ from the plans real values get. Some statements cannot be
598
+ planned (a parameter type that cannot be inferred, truncated text, missing privileges); the
599
+ finding then says "plan not available".
600
+ - Suggestions are candidates to test before applying, including the LLM's text.
601
+ - Index usage on read replicas is not visible: an index that is unused on the primary may serve
602
+ replica traffic.
603
+ - Only the database you connect to is reviewed.
604
+ - The staging trial shows plan choice and blocks on staging data; it cannot predict production timings.
605
+ - Through Metabase, statement text containing a `?` operator (jsonb) may not plan, because the
606
+ JDBC driver treats `?` as a parameter marker.
607
+
608
+ ## Development
609
+
610
+ ```bash
611
+ uv sync
612
+ uv run pytest -q # unit tests
613
+ uv run pytest -q -m integration # starts postgres:17-alpine in Docker (pipeline, read-only check, staging trial)
614
+ uv run ruff check
615
+ uv run python tests/client_fixtures.py # rewrite clients/fixtures/*.json after a deliberate change to the document
616
+ ```
617
+
618
+ A unit test fails when `clients/fixtures/*.json` no longer matches what the code produces, and another validates the
619
+ documents against `docs/review.schema.json`.
620
+
621
+ ## License
622
+
623
+ MIT