codecop 0.1.0__py3-none-any.whl
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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/realdb/locks.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""Lock and contention evidence from a real database, read-only, aggregates only (`codecop db pull --watch-locks`).
|
|
2
|
+
|
|
3
|
+
PostgreSQL: pg_stat_activity and pg_locks are point-in-time views, so one look proves little: a lock wait of 150 ms is
|
|
4
|
+
almost never caught. The watch samples them: counters (pg_stat_database) at the start, then `watch_samples` looks
|
|
5
|
+
`watch_interval_ms` apart (one grouped activity statement each, and the blocking-pairs statement only in a sample that
|
|
6
|
+
saw a session waiting on a lock), counters again at the end. Everything is grouped on the server and aggregated here:
|
|
7
|
+
counts per wait event and state, per normalized statement id (query_id, PostgreSQL 14+ with compute_query_id), blocking
|
|
8
|
+
pairs by statement id and table. No statement text, user, host, client address or application name is selected.
|
|
9
|
+
Once each: the settings that decide how contention shows up, foreign keys without an index that starts with the key
|
|
10
|
+
(with the parent's delete and update counts), and the tables where dead rows pile up.
|
|
11
|
+
|
|
12
|
+
ClickHouse has no row locks; its contention is merges and mutations. Once each: mutations per table, merges running now,
|
|
13
|
+
active parts per partition (the "too many parts" limit is per partition), inserts and merges per hour from the part log,
|
|
14
|
+
and delayed or refused inserts by normalized_query_hash. Evidence only: there is no ClickHouse contention sandbox.
|
|
15
|
+
|
|
16
|
+
`db_locks.json` stays on this machine. Table names and numbers only.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import time
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
|
|
24
|
+
from . import Limits, Refused, Statement, with_limits
|
|
25
|
+
|
|
26
|
+
LOCKS_FILE = "db_locks.json"
|
|
27
|
+
# one sample: a few catalog views of the server's memory, grouped; it must stay cheap because it runs every interval
|
|
28
|
+
SAMPLE_LIMITS = Limits(seconds=5, rows_to_read=1_000_000, bytes_to_read=200_000_000, result_rows=2_000, memory_bytes=200_000_000, threads=1)
|
|
29
|
+
ONCE_LIMITS = Limits(seconds=15, rows_to_read=5_000_000, bytes_to_read=1_000_000_000, result_rows=5_000, memory_bytes=500_000_000, threads=2)
|
|
30
|
+
CH_LOG_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=5_000, memory_bytes=1_000_000_000, threads=2)
|
|
31
|
+
|
|
32
|
+
_ACT_COLS = ("a.wait_event_type, a.wait_event, a.state, a.backend_type")
|
|
33
|
+
_ACT_AGG = ("count(*) AS sessions, "
|
|
34
|
+
"count(*) FILTER (WHERE a.xact_start < now() - interval '1 second') AS in_tx_over_1s, "
|
|
35
|
+
"max(extract(epoch FROM now() - a.xact_start))::float8 AS oldest_tx_s, "
|
|
36
|
+
"max(extract(epoch FROM now() - a.state_change)) FILTER (WHERE a.state = 'idle in transaction')::float8 AS longest_idle_in_tx_s, "
|
|
37
|
+
"max(age(a.backend_xmin))::bigint AS oldest_xmin_age ")
|
|
38
|
+
_ACT_FROM = "FROM pg_stat_activity a WHERE a.datname = current_database() AND a.pid <> pg_backend_pid() "
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _activity(query_id: bool) -> str:
|
|
42
|
+
qid = "a.query_id::text AS query_id, " if query_id else ""
|
|
43
|
+
return (f"SELECT {_ACT_COLS}, {qid}{_ACT_AGG}{_ACT_FROM}GROUP BY {_ACT_COLS}{', a.query_id' if query_id else ''}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _blocking(v14: bool) -> str:
|
|
47
|
+
ids = "w.query_id::text AS waiting_queryid, b.query_id::text AS blocking_queryid, " if v14 else ""
|
|
48
|
+
wait = "max(extract(epoch FROM now() - l.waitstart))::float8 AS longest_wait_s " if v14 else "NULL::float8 AS longest_wait_s "
|
|
49
|
+
group = "w.query_id, b.query_id, " if v14 else ""
|
|
50
|
+
return (f"SELECT {ids}b.state AS blocker_state, l.locktype, l.mode, l.relation::regclass::text AS relation, "
|
|
51
|
+
f"count(DISTINCT w.pid) AS waiters, {wait}"
|
|
52
|
+
"FROM pg_stat_activity w CROSS JOIN LATERAL unnest(pg_blocking_pids(w.pid)) AS bp(pid) "
|
|
53
|
+
"JOIN pg_stat_activity b ON b.pid = bp.pid LEFT JOIN pg_locks l ON l.pid = w.pid AND NOT l.granted "
|
|
54
|
+
"WHERE w.wait_event_type = 'Lock' AND w.datname = current_database() "
|
|
55
|
+
f"GROUP BY {group}b.state, l.locktype, l.mode, l.relation")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _counters(v14: bool) -> str:
|
|
59
|
+
extra = ("active_time::float8 AS active_time_ms, idle_in_transaction_time::float8 AS idle_in_transaction_time_ms, sessions, "
|
|
60
|
+
"sessions_abandoned, sessions_fatal, sessions_killed, ") if v14 else ""
|
|
61
|
+
return ("SELECT deadlocks, conflicts, xact_commit, xact_rollback, temp_files, " + extra
|
|
62
|
+
+ "stats_reset::text AS stats_reset FROM pg_stat_database WHERE datname = current_database()")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
PG_STATEMENTS: dict[str, Statement] = {s.id: s for s in [
|
|
66
|
+
Statement("pg.locks.activity", "L", _activity(True),
|
|
67
|
+
"One sample of the sessions of this database, grouped by wait event, state, backend type and normalized statement "
|
|
68
|
+
"id (PostgreSQL 14+): counts, oldest transaction and longest idle-in-transaction age. No text, user or host.", SAMPLE_LIMITS),
|
|
69
|
+
Statement("pg.locks.activity_v13", "L", _activity(False),
|
|
70
|
+
"The same sample on PostgreSQL 13 (no statement id).", SAMPLE_LIMITS),
|
|
71
|
+
Statement("pg.locks.blocking", "L", _blocking(True),
|
|
72
|
+
"Who waits on whom in one sample: waiting and blocking statement ids, the holder's state, lock type, mode and "
|
|
73
|
+
"table, counts and the longest wait (PostgreSQL 14+). Sent only in a sample that saw a session waiting on a lock.",
|
|
74
|
+
SAMPLE_LIMITS),
|
|
75
|
+
Statement("pg.locks.blocking_v13", "L", _blocking(False),
|
|
76
|
+
"The same on PostgreSQL 13 (no statement ids, no wait start).", SAMPLE_LIMITS),
|
|
77
|
+
Statement("pg.locks.counters", "L", _counters(True),
|
|
78
|
+
"Deadlocks, conflicts, commits, rollbacks, session and idle-in-transaction time of this database (PostgreSQL 14+): "
|
|
79
|
+
"read at the start and the end of the watch, the difference is kept.", SAMPLE_LIMITS),
|
|
80
|
+
Statement("pg.locks.counters_v13", "L", _counters(False),
|
|
81
|
+
"The same on PostgreSQL 13 (no session or idle-in-transaction time).", SAMPLE_LIMITS),
|
|
82
|
+
Statement("pg.locks.settings", "L",
|
|
83
|
+
"SELECT name, setting, unit FROM pg_settings WHERE name IN ('deadlock_timeout', 'lock_timeout', "
|
|
84
|
+
"'idle_in_transaction_session_timeout', 'statement_timeout', 'log_lock_waits', 'max_connections', "
|
|
85
|
+
"'default_transaction_isolation', 'compute_query_id', 'track_activities') ORDER BY name",
|
|
86
|
+
"The settings that decide how contention shows up (timeouts, isolation, whether statement ids are computed).", ONCE_LIMITS),
|
|
87
|
+
Statement("pg.locks.fk_without_index", "L",
|
|
88
|
+
"SELECT c.conrelid::regclass::text AS child, c.confrelid::regclass::text AS parent, c.conname::text AS constraint_name, "
|
|
89
|
+
"c.confdeltype::text AS on_delete, c.confupdtype::text AS on_update, s.n_live_tup AS child_rows, "
|
|
90
|
+
"p.n_tup_del AS parent_deletes, p.n_tup_upd AS parent_updates "
|
|
91
|
+
"FROM pg_constraint c JOIN pg_stat_user_tables s ON s.relid = c.conrelid JOIN pg_stat_user_tables p ON p.relid = c.confrelid "
|
|
92
|
+
"WHERE c.contype = 'f' AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.conrelid AND i.indpred IS NULL "
|
|
93
|
+
"AND i.indisvalid AND (string_to_array(i.indkey::text, ' ')::int2[])[1:cardinality(c.conkey)] @> c.conkey) "
|
|
94
|
+
"ORDER BY p.n_tup_del DESC, s.n_live_tup DESC LIMIT 2000",
|
|
95
|
+
"Foreign keys with no index that starts with the key, with the child's rows and the parent's deletes and updates: "
|
|
96
|
+
"a parent delete or key update then scans the child under a lock.", ONCE_LIMITS),
|
|
97
|
+
Statement("pg.locks.dead_rows", "L",
|
|
98
|
+
"SELECT relid::regclass::text AS table_name, n_live_tup AS live_rows, n_dead_tup AS dead_rows, n_tup_upd AS updates, "
|
|
99
|
+
"n_tup_hot_upd AS hot_updates, last_autovacuum::text AS last_autovacuum FROM pg_stat_user_tables "
|
|
100
|
+
"ORDER BY n_dead_tup DESC LIMIT 20",
|
|
101
|
+
"The 20 tables with the most dead rows (vacuum held back by long transactions).", ONCE_LIMITS),
|
|
102
|
+
]}
|
|
103
|
+
|
|
104
|
+
CH_STATEMENTS: dict[str, Statement] = {s.id: s for s in [
|
|
105
|
+
Statement("ch.locks.mutations", "L",
|
|
106
|
+
"SELECT database, table, count() AS mutations, countIf(NOT is_done) AS running, max(parts_to_do) AS parts_to_do, "
|
|
107
|
+
"toString(min(create_time)) AS oldest, countIf(latest_fail_reason != '') AS failed FROM system.mutations "
|
|
108
|
+
"WHERE create_time > now() - toIntervalDay({days:UInt32}) AND database NOT IN ('system', 'INFORMATION_SCHEMA', 'information_schema') "
|
|
109
|
+
"GROUP BY database, table ORDER BY running DESC, mutations DESC LIMIT 2000",
|
|
110
|
+
"Mutations (ALTER UPDATE/DELETE) per table over the last days: how many, still running, failed (counts, no text).",
|
|
111
|
+
ONCE_LIMITS, optional=True),
|
|
112
|
+
Statement("ch.locks.merges", "L",
|
|
113
|
+
"SELECT database, table, count() AS merges, max(elapsed) AS longest_s, sum(total_size_bytes_compressed) AS bytes, "
|
|
114
|
+
"countIf(is_mutation) AS mutation_merges FROM system.merges GROUP BY database, table ORDER BY merges DESC LIMIT 2000",
|
|
115
|
+
"Merges running at this moment per table (point in time).", ONCE_LIMITS, optional=True),
|
|
116
|
+
Statement("ch.locks.parts", "L",
|
|
117
|
+
"SELECT database, table, partition_id, count() AS active_parts, sum(rows) AS rows FROM system.parts WHERE active "
|
|
118
|
+
"AND database NOT IN ('system', 'INFORMATION_SCHEMA', 'information_schema') "
|
|
119
|
+
"GROUP BY database, table, partition_id ORDER BY active_parts DESC LIMIT 50",
|
|
120
|
+
"The 50 partitions with the most active parts (the too-many-parts limit is per partition).", ONCE_LIMITS),
|
|
121
|
+
Statement("ch.locks.part_log", "L",
|
|
122
|
+
"SELECT database, table, toString(toStartOfHour(event_time)) AS hour, countIf(event_type = 'NewPart') AS new_parts, "
|
|
123
|
+
"quantileIf(0.5)(rows, event_type = 'NewPart') AS median_rows_per_insert, countIf(event_type = 'MergeParts') AS merges, "
|
|
124
|
+
"sumIf(duration_ms, event_type = 'MergeParts') AS merge_ms, countIf(event_type = 'MutatePart') AS mutated_parts "
|
|
125
|
+
"FROM system.part_log WHERE event_date >= today() - {days:UInt32} AND database NOT IN ('system') "
|
|
126
|
+
"GROUP BY database, table, hour ORDER BY database, table, hour LIMIT 5000",
|
|
127
|
+
"Inserts (new parts, median rows per insert) and merge work per table and hour (system.part_log, when enabled).",
|
|
128
|
+
CH_LOG_LIMITS, optional=True),
|
|
129
|
+
Statement("ch.locks.delayed_inserts", "L",
|
|
130
|
+
"SELECT toString(normalized_query_hash) AS hash, count() AS calls, sum(query_duration_ms) AS ms, "
|
|
131
|
+
"sum(ProfileEvents['DelayedInserts']) AS delayed_inserts, sum(ProfileEvents['DelayedInsertsMilliseconds']) AS delayed_ms, "
|
|
132
|
+
"sum(ProfileEvents['RejectedInserts']) AS rejected_inserts, countIf(exception_code = 252) AS too_many_parts "
|
|
133
|
+
"FROM system.query_log WHERE event_date >= today() - {days:UInt32} AND type IN ('QueryFinish', 'ExceptionWhileProcessing') "
|
|
134
|
+
"AND query_kind = 'Insert' GROUP BY normalized_query_hash HAVING delayed_inserts > 0 OR too_many_parts > 0 OR rejected_inserts > 0 "
|
|
135
|
+
"ORDER BY delayed_ms DESC LIMIT 50",
|
|
136
|
+
"Inserts the server slowed down or refused for too many parts, by normalized statement hash (no text).",
|
|
137
|
+
CH_LOG_LIMITS, optional=True),
|
|
138
|
+
]}
|
|
139
|
+
|
|
140
|
+
SAMPLE_IDS = ("pg.locks.activity", "pg.locks.blocking")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def pg_form(version_num: int) -> str:
|
|
144
|
+
"""'' on PostgreSQL 14+, '_v13' before (no query_id, waitstart or session counters)."""
|
|
145
|
+
return "" if not version_num or version_num >= 140000 else "_v13"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def planned(engine: str, settings: dict | None = None) -> list[Statement]:
|
|
149
|
+
"""What --watch-locks may send, with the limits the settings give each (the newest forms; older servers get the _v13 ones)."""
|
|
150
|
+
lim = (settings or {}).get("limits")
|
|
151
|
+
if engine == "clickhouse":
|
|
152
|
+
return [with_limits(s, lim) for s in CH_STATEMENTS.values()]
|
|
153
|
+
return [with_limits(s, lim) for k, s in PG_STATEMENTS.items() if not k.endswith("_v13")]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def plan_text(settings: dict) -> str:
|
|
157
|
+
n, every = int(settings["watch_samples"]), int(settings["watch_interval_ms"])
|
|
158
|
+
return (f"--watch-locks: pg.locks.counters at the start and the end; {n:,} samples {every / 1000:g} s apart (about {n * every / 1000:g} s): "
|
|
159
|
+
f"each sends pg.locks.activity, and pg.locks.blocking only when that sample saw a session waiting on a lock; then "
|
|
160
|
+
f"pg.locks.settings, pg.locks.fk_without_index and pg.locks.dead_rows once. At most {2 * n + 5:,} statements, at least "
|
|
161
|
+
f"{n + 5:,}. pg_stat_activity is point-in-time: a wait shorter than the interval is seen only by chance, and nothing "
|
|
162
|
+
"outside the window is seen (db_pull.watch_samples, db_pull.watch_interval_ms). Counts only; no text, user, host "
|
|
163
|
+
"or application name is read.")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _f(v) -> float | None:
|
|
167
|
+
try:
|
|
168
|
+
return None if v is None else float(v)
|
|
169
|
+
except (TypeError, ValueError):
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _run(reader, sid: str, form: str, **params) -> list[dict] | None:
|
|
174
|
+
"""Run the form of a statement for this server; on a refusal of the newer form, the older one once; None if refused."""
|
|
175
|
+
lim = (getattr(reader, "settings", None) or {}).get("limits")
|
|
176
|
+
first = sid + form if sid + form in PG_STATEMENTS else sid # a statement with one form for every version
|
|
177
|
+
ids = [first] + ([sid + "_v13"] if first == sid and sid + "_v13" in PG_STATEMENTS else [])
|
|
178
|
+
for i, k in enumerate(ids):
|
|
179
|
+
try:
|
|
180
|
+
return reader.run_statement(with_limits(PG_STATEMENTS[k], lim), params)
|
|
181
|
+
except Refused:
|
|
182
|
+
if i == len(ids) - 1:
|
|
183
|
+
return None
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class Watch:
|
|
188
|
+
"""Aggregates samples client-side. `add_activity(rows)`, `add_blocking(rows)` per sample, then `result()`."""
|
|
189
|
+
|
|
190
|
+
def __init__(self):
|
|
191
|
+
self.samples = 0
|
|
192
|
+
self.events: dict[tuple, dict] = {}
|
|
193
|
+
self.queries: dict[str, dict] = {}
|
|
194
|
+
self.pairs: dict[tuple, dict] = {}
|
|
195
|
+
self.lock_wait_samples = 0
|
|
196
|
+
self.idle_in_tx_samples = 0
|
|
197
|
+
self.longest_idle = 0.0
|
|
198
|
+
self.oldest_tx = 0.0
|
|
199
|
+
self.oldest_xmin_age = 0
|
|
200
|
+
self.failed = 0
|
|
201
|
+
|
|
202
|
+
def add_activity(self, rows: list[dict]) -> bool:
|
|
203
|
+
"""One sample's grouped rows. Returns whether a session waited on a lock in it."""
|
|
204
|
+
self.samples += 1
|
|
205
|
+
seen: dict[tuple, int] = {}
|
|
206
|
+
waiting = idle_tx = False
|
|
207
|
+
for r in rows:
|
|
208
|
+
key = (r.get("wait_event_type") or "", r.get("wait_event") or "", r.get("state") or "", r.get("backend_type") or "")
|
|
209
|
+
n = int(r.get("sessions") or 0)
|
|
210
|
+
seen[key] = seen.get(key, 0) + n
|
|
211
|
+
if key[0] == "Lock" and n:
|
|
212
|
+
waiting = True
|
|
213
|
+
if key[2] == "idle in transaction" and n:
|
|
214
|
+
idle_tx = True
|
|
215
|
+
self.longest_idle = max(self.longest_idle, _f(r.get("longest_idle_in_tx_s")) or 0.0)
|
|
216
|
+
self.oldest_tx = max(self.oldest_tx, _f(r.get("oldest_tx_s")) or 0.0)
|
|
217
|
+
self.oldest_xmin_age = max(self.oldest_xmin_age, int(r.get("oldest_xmin_age") or 0))
|
|
218
|
+
qid = r.get("query_id")
|
|
219
|
+
if qid not in (None, "", "0") and (key[0] == "Lock" or key[2] in ("active", "idle in transaction")):
|
|
220
|
+
q = self.queries.setdefault(str(qid), {"queryid": str(qid), "lock_wait_samples": 0, "idle_in_tx_samples": 0,
|
|
221
|
+
"active_samples": 0, "max_sessions": 0})
|
|
222
|
+
q["lock_wait_samples" if key[0] == "Lock" else "idle_in_tx_samples" if key[2] == "idle in transaction" else "active_samples"] += 1
|
|
223
|
+
q["max_sessions"] = max(q["max_sessions"], n)
|
|
224
|
+
for key, n in seen.items():
|
|
225
|
+
e = self.events.setdefault(key, {"wait_event_type": key[0], "wait_event": key[1], "state": key[2], "backend_type": key[3],
|
|
226
|
+
"samples_seen": 0, "max_sessions": 0, "sum_sessions": 0})
|
|
227
|
+
e["samples_seen"] += 1
|
|
228
|
+
e["max_sessions"] = max(e["max_sessions"], n)
|
|
229
|
+
e["sum_sessions"] += n
|
|
230
|
+
self.lock_wait_samples += waiting
|
|
231
|
+
self.idle_in_tx_samples += idle_tx
|
|
232
|
+
return waiting
|
|
233
|
+
|
|
234
|
+
def add_blocking(self, rows: list[dict]) -> None:
|
|
235
|
+
seen = set()
|
|
236
|
+
for r in rows:
|
|
237
|
+
key = (str(r.get("waiting_queryid") or ""), str(r.get("blocking_queryid") or ""), r.get("blocker_state") or "",
|
|
238
|
+
r.get("locktype") or "", r.get("mode") or "", r.get("relation") or "")
|
|
239
|
+
p = self.pairs.setdefault(key, {"waiting_queryid": key[0] or None, "blocking_queryid": key[1] or None, "blocker_state": key[2],
|
|
240
|
+
"locktype": key[3], "mode": key[4], "relation": key[5] or None, "samples": 0,
|
|
241
|
+
"max_waiters": 0, "longest_wait_s": None})
|
|
242
|
+
if key not in seen:
|
|
243
|
+
p["samples"] += 1
|
|
244
|
+
seen.add(key)
|
|
245
|
+
p["max_waiters"] = max(p["max_waiters"], int(r.get("waiters") or 0))
|
|
246
|
+
w = _f(r.get("longest_wait_s"))
|
|
247
|
+
if w is not None:
|
|
248
|
+
p["longest_wait_s"] = round(max(p["longest_wait_s"] or 0.0, w), 3)
|
|
249
|
+
|
|
250
|
+
def result(self) -> dict:
|
|
251
|
+
n = max(self.samples, 1)
|
|
252
|
+
events = sorted(({**{k: v for k, v in e.items() if k != "sum_sessions"}, "avg_sessions": round(e["sum_sessions"] / n, 3)}
|
|
253
|
+
for e in self.events.values()), key=lambda e: (-e["samples_seen"], -e["max_sessions"]))
|
|
254
|
+
return {"samples": self.samples, "failed_samples": self.failed, "lock_wait_samples": self.lock_wait_samples,
|
|
255
|
+
"idle_in_tx_samples": self.idle_in_tx_samples, "longest_idle_in_tx_s": round(self.longest_idle, 3),
|
|
256
|
+
"oldest_tx_s": round(self.oldest_tx, 3), "oldest_xmin_age": self.oldest_xmin_age, "by_wait_event": events,
|
|
257
|
+
"by_query": sorted(self.queries.values(), key=lambda q: (-q["lock_wait_samples"], -q["idle_in_tx_samples"]))[:200],
|
|
258
|
+
"blocking_pairs": sorted(self.pairs.values(), key=lambda p: (-p["samples"], -p["max_waiters"]))[:200]}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
COUNTER_KEYS = ("deadlocks", "conflicts", "xact_commit", "xact_rollback", "temp_files", "active_time_ms", "idle_in_transaction_time_ms",
|
|
262
|
+
"sessions", "sessions_abandoned", "sessions_fatal", "sessions_killed")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def counters_delta(start: dict | None, end: dict | None) -> dict:
|
|
266
|
+
if not start or not end:
|
|
267
|
+
return {}
|
|
268
|
+
out = {}
|
|
269
|
+
for k in COUNTER_KEYS:
|
|
270
|
+
a, b = _f(start.get(k)), _f(end.get(k))
|
|
271
|
+
if a is not None and b is not None:
|
|
272
|
+
d = b - a
|
|
273
|
+
out[k] = round(d, 1) if k.endswith("_ms") else int(d)
|
|
274
|
+
if start.get("stats_reset") != end.get("stats_reset"):
|
|
275
|
+
out["stats_reset_during_watch"] = True
|
|
276
|
+
return out
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def watch_postgres(reader, settings: dict, *, sleep=time.sleep, clock=time.monotonic, log=None) -> dict:
|
|
280
|
+
"""The sampled watch on one PostgreSQL connection (reader: realdb.postgres.PostgresReader after check())."""
|
|
281
|
+
form = pg_form(getattr(reader, "version_num", 0))
|
|
282
|
+
n, every = int(settings["watch_samples"]), int(settings["watch_interval_ms"]) / 1000.0
|
|
283
|
+
started_at = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
284
|
+
start = (_run(reader, "pg.locks.counters", form) or [None])[0]
|
|
285
|
+
w = Watch()
|
|
286
|
+
t0 = clock()
|
|
287
|
+
for i in range(n):
|
|
288
|
+
due = t0 + i * every
|
|
289
|
+
wait = due - clock()
|
|
290
|
+
if wait > 0:
|
|
291
|
+
sleep(wait)
|
|
292
|
+
rows = _run(reader, "pg.locks.activity", form)
|
|
293
|
+
if rows is None:
|
|
294
|
+
w.failed += 1
|
|
295
|
+
continue
|
|
296
|
+
if w.add_activity(rows):
|
|
297
|
+
pairs = _run(reader, "pg.locks.blocking", form)
|
|
298
|
+
if pairs:
|
|
299
|
+
w.add_blocking(pairs)
|
|
300
|
+
if log and n >= 10 and (i + 1) % max(1, n // 4) == 0:
|
|
301
|
+
log(f"{i + 1} of {n} samples")
|
|
302
|
+
window = clock() - t0
|
|
303
|
+
end = (_run(reader, "pg.locks.counters", form) or [None])[0]
|
|
304
|
+
settings_rows = _run(reader, "pg.locks.settings", form) or []
|
|
305
|
+
fks = _run(reader, "pg.locks.fk_without_index", form)
|
|
306
|
+
dead = _run(reader, "pg.locks.dead_rows", form)
|
|
307
|
+
return {"engine": "postgres", "started_at": started_at, "interval_s": every, "window_s": round(window, 1),
|
|
308
|
+
"form": "14+" if not form else "13", **w.result(),
|
|
309
|
+
"counters_delta": counters_delta(start, end),
|
|
310
|
+
"settings": {r["name"]: (f"{r['setting']}{r.get('unit') or ''}" if r.get("unit") not in (None, "") else r["setting"])
|
|
311
|
+
for r in settings_rows},
|
|
312
|
+
"fk_without_index": [{"child": r["child"], "parent": r["parent"], "constraint": r["constraint_name"],
|
|
313
|
+
"on_delete": r["on_delete"], "on_update": r["on_update"], "child_rows": int(r["child_rows"] or 0),
|
|
314
|
+
"parent_deletes": int(r["parent_deletes"] or 0), "parent_updates": int(r["parent_updates"] or 0)}
|
|
315
|
+
for r in fks or []],
|
|
316
|
+
"dead_rows": [{"table": r["table_name"], "live_rows": int(r["live_rows"] or 0), "dead_rows": int(r["dead_rows"] or 0),
|
|
317
|
+
"updates": int(r["updates"] or 0), "hot_updates": int(r["hot_updates"] or 0)} for r in dead or []],
|
|
318
|
+
"notes": [x for x in (
|
|
319
|
+
"" if fks is not None else "foreign keys without an index: refused",
|
|
320
|
+
"" if settings_rows else "settings: refused",
|
|
321
|
+
"statement ids need PostgreSQL 14 and compute_query_id" if form else "") if x]}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def evidence_clickhouse(reader, settings: dict) -> dict:
|
|
325
|
+
"""The ClickHouse statements, once each. A refused optional one (no part_log) is a note."""
|
|
326
|
+
days = int(settings.get("watch_days") or 7)
|
|
327
|
+
out: dict = {"engine": "clickhouse", "notes": []}
|
|
328
|
+
lim = (settings or {}).get("limits")
|
|
329
|
+
for sid, key in (("ch.locks.mutations", "mutations"), ("ch.locks.merges", "merges"), ("ch.locks.parts", "parts"),
|
|
330
|
+
("ch.locks.part_log", "part_log"), ("ch.locks.delayed_inserts", "delayed_inserts")):
|
|
331
|
+
stmt = with_limits(CH_STATEMENTS[sid], lim)
|
|
332
|
+
params = {"days": days} if "{days:" in stmt.sql else {}
|
|
333
|
+
try:
|
|
334
|
+
out[key] = reader.run_statement(stmt, params)
|
|
335
|
+
except Refused as e:
|
|
336
|
+
out[key] = None
|
|
337
|
+
out["notes"].append(f"{sid}: the server refused it ({str(e)[:80]})" if not stmt.optional else f"{sid}: not available")
|
|
338
|
+
parts = out.get("parts") or []
|
|
339
|
+
out["max_active_parts_per_partition"] = max((int(p.get("active_parts") or 0) for p in parts), default=0)
|
|
340
|
+
out["days"] = days
|
|
341
|
+
return out
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def link_workload(locks: dict, workload: dict | None) -> None:
|
|
345
|
+
"""Mark the statement ids the watch saw that the pulled workload also holds (`in_workload`): numbers only."""
|
|
346
|
+
known = {}
|
|
347
|
+
for name, c in ((workload or {}).get("connections") or {}).items():
|
|
348
|
+
known[name] = {str(q.get("hash")) for q in c.get("queries") or [] if q.get("hash") is not None}
|
|
349
|
+
for name, c in (locks.get("connections") or {}).items():
|
|
350
|
+
ids = known.get(name) or set()
|
|
351
|
+
for q in c.get("by_query") or []:
|
|
352
|
+
q["in_workload"] = q["queryid"] in ids
|
|
353
|
+
for p in c.get("blocking_pairs") or []:
|
|
354
|
+
p["waiting_in_workload"] = bool(p.get("waiting_queryid")) and p["waiting_queryid"] in ids
|
|
355
|
+
p["blocking_in_workload"] = bool(p.get("blocking_queryid")) and p["blocking_queryid"] in ids
|