-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcheckup.ts
More file actions
1961 lines (1773 loc) · 68.4 KB
/
checkup.ts
File metadata and controls
1961 lines (1773 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Express Checkup Module
* ======================
* Generates JSON health check reports directly from PostgreSQL without Prometheus.
*
* ARCHITECTURAL DECISIONS
* -----------------------
*
* 1. SINGLE SOURCE OF TRUTH FOR SQL QUERIES
* Complex metrics (index health, settings, db_stats) are loaded from
* config/pgwatch-prometheus/metrics.yml via getMetricSql() from metrics-loader.ts.
*
* Simple queries (version, database list, connection states, uptime) use
* inline SQL as they're trivial and CLI-specific.
*
* 2. JSON SCHEMA COMPLIANCE
* All generated reports MUST comply with JSON schemas in reporter/schemas/.
* These schemas define the expected format for both:
* - Full-fledged monitoring reporter output
* - Express checkup output
*
* Before adding or modifying a report, verify the corresponding schema exists
* and ensure the output matches. Run schema validation tests to confirm.
*
* 3. ERROR HANDLING STRATEGY
* Functions follow two patterns based on criticality:
*
* PROPAGATING (throws on error):
* - Core data functions: getPostgresVersion, getSettings, getAlteredSettings,
* getDatabaseSizes, getInvalidIndexes, getUnusedIndexes, getRedundantIndexes
* - If these fail, the entire report should fail (data is required)
* - Callers should handle errors at the report generation level
*
* GRACEFUL DEGRADATION (catches errors, includes error in output):
* - Optional/supplementary queries: pg_stat_statements, pg_stat_kcache checks,
* memory calculations, postmaster startup time
* - These are nice-to-have; missing data shouldn't fail the whole report
* - Errors are logged and included in report output for visibility
*
* ADDING NEW REPORTS
* ------------------
* 1. Add/verify the metric exists in config/pgwatch-prometheus/metrics.yml
* 2. Add the metric name mapping to METRIC_NAMES in metrics-loader.ts
* 3. Verify JSON schema exists in reporter/schemas/{CHECK_ID}.schema.json
* 4. Implement the generator function using getMetricSql()
* 5. Add schema validation test in test/schema-validation.test.ts
*/
import { Client } from "pg";
import * as fs from "fs";
import * as path from "path";
import * as pkg from "../package.json";
import { getMetricSql, transformMetricRow, METRIC_NAMES } from "./metrics-loader";
import { getCheckupTitle, buildCheckInfoMap } from "./checkup-dictionary";
// Time constants
const SECONDS_PER_DAY = 86400;
const SECONDS_PER_HOUR = 3600;
const SECONDS_PER_MINUTE = 60;
/**
* Convert various boolean representations to boolean.
* PostgreSQL returns booleans as true/false, 1/0, 't'/'f', or 'true'/'false'
* depending on context (query result, JDBC driver, etc.).
*/
function toBool(val: unknown): boolean {
return val === true || val === 1 || val === "t" || val === "true";
}
/**
* PostgreSQL version information
*/
export interface PostgresVersion {
version: string;
server_version_num: string;
server_major_ver: string;
server_minor_ver: string;
}
/**
* Setting information from pg_settings
*/
export interface SettingInfo {
setting: string;
unit: string;
category: string;
context: string;
vartype: string;
pretty_value: string;
}
/**
* Altered setting (A007) - subset of SettingInfo
*/
export interface AlteredSetting {
value: string;
unit: string;
category: string;
pretty_value: string;
}
/**
* Cluster metric (A004)
*/
export interface ClusterMetric {
value: string;
unit: string;
description: string;
}
/**
* Invalid index entry (H001) - matches H001.schema.json invalidIndex
*
* Decision tree for remediation recommendations:
* 1. has_valid_duplicate=true → DROP (valid duplicate exists, safe to remove)
* 2. is_pk=true or is_unique=true → RECREATE (backs a constraint, must restore)
* 3. table_row_estimate < 10000 → RECREATE (small table, quick rebuild)
* 4. Otherwise → UNCERTAIN (needs manual analysis of query plans)
*/
export interface InvalidIndex {
schema_name: string;
table_name: string;
index_name: string;
relation_name: string;
index_size_bytes: number;
index_size_pretty: string;
/** Full CREATE INDEX statement from pg_get_indexdef() - useful for DROP/RECREATE migrations */
index_definition: string;
supports_fk: boolean;
/** True if this index backs a PRIMARY KEY constraint */
is_pk: boolean;
/** True if this is a UNIQUE index (includes PK indexes) */
is_unique: boolean;
/** Name of the constraint this index backs, or null if none */
constraint_name: string | null;
/** Estimated row count of the table from pg_class.reltuples */
table_row_estimate: number;
/** True if there is a valid index on the same column(s) */
has_valid_duplicate: boolean;
/** Name of the valid duplicate index if one exists */
valid_duplicate_name: string | null;
/** Full CREATE INDEX statement of the valid duplicate index */
valid_duplicate_definition: string | null;
}
/** Recommendation for handling an invalid index */
export type InvalidIndexRecommendation = "DROP" | "RECREATE" | "UNCERTAIN";
/** Threshold for considering a table "small" (quick to rebuild) */
const SMALL_TABLE_ROW_THRESHOLD = 10000;
/**
* Compute remediation recommendation for an invalid index using decision tree.
*
* Decision tree logic:
* 1. If has_valid_duplicate is true → DROP (valid duplicate exists, safe to remove)
* 2. If is_pk or is_unique is true → RECREATE (backs a constraint, must restore)
* 3. If table_row_estimate < 10000 → RECREATE (small table, quick rebuild)
* 4. Otherwise → UNCERTAIN (needs manual analysis of query plans)
*
* @param index - Invalid index with observation data
* @returns Recommendation: "DROP", "RECREATE", or "UNCERTAIN"
*/
export function getInvalidIndexRecommendation(index: InvalidIndex): InvalidIndexRecommendation {
// 1. Valid duplicate exists - safe to drop
if (index.has_valid_duplicate) {
return "DROP";
}
// 2. Backs a constraint - must recreate
if (index.is_pk || index.is_unique) {
return "RECREATE";
}
// 3. Small table - quick to recreate
if (index.table_row_estimate < SMALL_TABLE_ROW_THRESHOLD) {
return "RECREATE";
}
// 4. Large table without clear path - needs manual analysis
return "UNCERTAIN";
}
/**
* Unused index entry (H002) - matches H002.schema.json unusedIndex
*/
export interface UnusedIndex {
schema_name: string;
table_name: string;
index_name: string;
index_definition: string;
reason: string;
idx_scan: number;
index_size_bytes: number;
idx_is_btree: boolean;
supports_fk: boolean;
index_size_pretty: string;
}
/**
* Stats reset info for H002 - matches H002.schema.json statsReset
*/
export interface StatsReset {
stats_reset_epoch: number | null;
stats_reset_time: string | null;
days_since_reset: number | null;
postmaster_startup_epoch: number | null;
postmaster_startup_time: string | null;
/** Set when postmaster startup time query fails - indicates data availability issue */
postmaster_startup_error?: string;
}
/**
* Redundant index entry (H004) - matches H004.schema.json redundantIndex
*/
/**
* Index that makes another index redundant.
* Used in redundant_to array to show which indexes this one is redundant to.
*/
export interface RedundantToIndex {
index_name: string;
index_definition: string;
index_size_bytes: number;
index_size_pretty: string;
}
export interface RedundantIndex {
schema_name: string;
table_name: string;
index_name: string;
relation_name: string;
access_method: string;
reason: string;
index_size_bytes: number;
table_size_bytes: number;
index_usage: number;
supports_fk: boolean;
index_definition: string;
index_size_pretty: string;
table_size_pretty: string;
redundant_to: RedundantToIndex[];
/** Set when redundant_to_json parsing fails - indicates data quality issue */
redundant_to_parse_error?: string;
}
/**
* I/O statistics by backend type (I001) - matches I001.schema.json backendIOStats
*/
export interface BackendIOStats {
backend_type: string;
reads: number;
/** Read MiB. The historical `_mb` suffix is retained for schema compatibility. */
read_bytes_mb: number;
read_time_ms: number;
writes: number;
/** Written MiB. The historical `_mb` suffix is retained for schema compatibility. */
write_bytes_mb: number;
write_time_ms: number;
writebacks: number;
/** Writeback MiB. The historical `_mb` suffix is retained for schema compatibility. */
writeback_bytes_mb: number;
writeback_time_ms: number;
fsyncs: number;
fsync_time_ms: number;
/** Relation extension operations reported by pg_stat_io for PostgreSQL 16+. */
extends?: number;
/** Extended MiB; PG16 derives extends * op_bytes, PG18+ uses native extend_bytes. */
extend_bytes_mb?: number;
hits: number;
evictions: number;
reuses: number;
}
/**
* I/O statistics analysis summary (I001)
*/
export interface IOAnalysis {
total_read_mb: number;
total_write_mb: number;
/** read_time_ms + write_time_ms across backends. Excludes writeback and fsync time. */
total_io_time_ms: number;
/** Buffer hit ratio: hits / (hits + reads) * 100. */
read_hit_ratio_pct: number;
/** Average read latency, or null when there are no reads. */
avg_read_time_ms: number | null;
/** Average write latency, or null when there are no writes. */
avg_write_time_ms: number | null;
}
/**
* Node result for reports
*/
export interface NodeResult {
data: Record<string, any>;
postgres_version?: PostgresVersion;
}
/**
* Report structure matching JSON schemas
*/
export interface Report {
version: string | null;
build_ts: string | null;
generation_mode: string | null;
checkId: string;
checkTitle: string;
timestamptz: string;
nodes: {
primary: string;
standbys: string[];
};
results: Record<string, NodeResult>;
}
/**
* Parse PostgreSQL version number into major and minor components
*/
export function parseVersionNum(versionNum: string): { major: string; minor: string } {
if (!versionNum || versionNum.length < 6) {
return { major: "", minor: "" };
}
try {
const num = parseInt(versionNum, 10);
return {
major: Math.floor(num / 10000).toString(),
minor: (num % 10000).toString(),
};
} catch (err) {
// parseInt shouldn't throw, but handle edge cases defensively
const errorMsg = err instanceof Error ? err.message : String(err);
console.error(`[parseVersionNum] Warning: Failed to parse "${versionNum}": ${errorMsg}`);
return { major: "", minor: "" };
}
}
/**
* Format bytes to human readable string using binary units (1024-based).
* Uses IEC standard: KiB, MiB, GiB, etc.
*
* Note: PostgreSQL's pg_size_pretty() uses kB/MB/GB with 1024 base (technically
* incorrect SI usage), but we follow IEC binary units per project style guide.
*/
export function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
if (bytes < 0) return `-${formatBytes(-bytes)}`; // Handle negative values
if (!Number.isFinite(bytes)) return `${bytes} B`; // Handle NaN/Infinity
const units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
}
/**
* Format a setting's pretty value from the normalized value and unit.
* The settings metric provides setting_normalized (bytes or seconds) and unit_normalized.
*/
function formatSettingPrettyValue(
settingNormalized: number | null,
unitNormalized: string | null,
rawValue: string
): string {
if (settingNormalized === null || unitNormalized === null) {
return rawValue;
}
if (unitNormalized === "bytes") {
return formatBytes(settingNormalized);
}
if (unitNormalized === "seconds") {
// Format time values with appropriate units based on magnitude:
// - Sub-second values (< 1s): show in milliseconds for precision
// - Small values (< 60s): show in seconds
// - Larger values (>= 60s): show in minutes for readability
const MS_PER_SECOND = 1000;
if (settingNormalized < 1) {
return `${(settingNormalized * MS_PER_SECOND).toFixed(0)} ms`;
} else if (settingNormalized < SECONDS_PER_MINUTE) {
return `${settingNormalized} s`;
} else {
return `${(settingNormalized / SECONDS_PER_MINUTE).toFixed(1)} min`;
}
}
return rawValue;
}
/**
* Get PostgreSQL version information.
* Uses simple inline SQL (trivial query, CLI-specific).
*
* @throws {Error} If database query fails (propagating - critical data)
*/
export async function getPostgresVersion(client: Client): Promise<PostgresVersion> {
const result = await client.query(`
select name, setting
from pg_settings
where name in ('server_version', 'server_version_num')
`);
let version = "";
let serverVersionNum = "";
for (const row of result.rows) {
if (row.name === "server_version") {
version = row.setting;
} else if (row.name === "server_version_num") {
serverVersionNum = row.setting;
}
}
const { major, minor } = parseVersionNum(serverVersionNum);
return {
version,
server_version_num: serverVersionNum,
server_major_ver: major,
server_minor_ver: minor,
};
}
/**
* Get all PostgreSQL settings
* Uses 'settings' metric from metrics.yml
*/
export async function getSettings(client: Client, pgMajorVersion: number = 16): Promise<Record<string, SettingInfo>> {
const sql = getMetricSql(METRIC_NAMES.settings, pgMajorVersion);
const result = await client.query(sql);
const settings: Record<string, SettingInfo> = {};
for (const row of result.rows) {
// The settings metric uses tag_setting_name, tag_setting_value, etc.
const name = row.tag_setting_name;
const settingValue = row.tag_setting_value;
const unit = row.tag_unit || "";
const category = row.tag_category || "";
const vartype = row.tag_vartype || "";
const settingNormalized = row.setting_normalized !== null ? parseFloat(row.setting_normalized) : null;
const unitNormalized = row.unit_normalized || null;
settings[name] = {
setting: settingValue,
unit,
category,
context: "", // Not available in the monitoring metric
vartype,
pretty_value: formatSettingPrettyValue(settingNormalized, unitNormalized, settingValue),
};
}
return settings;
}
/**
* Get altered (non-default) PostgreSQL settings
* Uses 'settings' metric from metrics.yml and filters for non-default
*/
export async function getAlteredSettings(client: Client, pgMajorVersion: number = 16): Promise<Record<string, AlteredSetting>> {
const sql = getMetricSql(METRIC_NAMES.settings, pgMajorVersion);
const result = await client.query(sql);
const settings: Record<string, AlteredSetting> = {};
for (const row of result.rows) {
// Filter for non-default settings (is_default = 0 means non-default)
if (!toBool(row.is_default)) {
const name = row.tag_setting_name;
const settingValue = row.tag_setting_value;
const unit = row.tag_unit || "";
const category = row.tag_category || "";
const settingNormalized = row.setting_normalized !== null ? parseFloat(row.setting_normalized) : null;
const unitNormalized = row.unit_normalized || null;
settings[name] = {
value: settingValue,
unit,
category,
pretty_value: formatSettingPrettyValue(settingNormalized, unitNormalized, settingValue),
};
}
}
return settings;
}
/**
* Get database sizes (all non-template databases)
* Uses simple inline SQL (lists all databases, CLI-specific)
*/
export async function getDatabaseSizes(client: Client): Promise<Record<string, number>> {
const result = await client.query(`
select
datname,
pg_database_size(datname) as size_bytes
from pg_database
where datistemplate = false
order by size_bytes desc
`);
const sizes: Record<string, number> = {};
for (const row of result.rows) {
sizes[row.datname] = parseInt(row.size_bytes, 10);
}
return sizes;
}
/**
* Get cluster general info metrics
* Uses 'db_stats' metric and inline SQL for connection states/uptime
*/
export async function getClusterInfo(client: Client, pgMajorVersion: number = 16): Promise<Record<string, ClusterMetric>> {
const info: Record<string, ClusterMetric> = {};
// Get database statistics from db_stats metric
const dbStatsSql = getMetricSql(METRIC_NAMES.dbStats, pgMajorVersion);
const statsResult = await client.query(dbStatsSql);
if (statsResult.rows.length > 0) {
const stats = statsResult.rows[0];
info.total_connections = {
value: String(stats.numbackends || 0),
unit: "connections",
description: "Current database connections",
};
info.total_commits = {
value: String(stats.xact_commit || 0),
unit: "transactions",
description: "Total committed transactions",
};
info.total_rollbacks = {
value: String(stats.xact_rollback || 0),
unit: "transactions",
description: "Total rolled back transactions",
};
const blocksHit = parseInt(stats.blks_hit || "0", 10);
const blocksRead = parseInt(stats.blks_read || "0", 10);
const totalBlocks = blocksHit + blocksRead;
const cacheHitRatio = totalBlocks > 0 ? ((blocksHit / totalBlocks) * 100).toFixed(2) : "0.00";
info.cache_hit_ratio = {
value: cacheHitRatio,
unit: "%",
description: "Buffer cache hit ratio",
};
info.blocks_read = {
value: String(blocksRead),
unit: "blocks",
description: "Total disk blocks read",
};
info.blocks_hit = {
value: String(blocksHit),
unit: "blocks",
description: "Total buffer cache hits",
};
info.tuples_returned = {
value: String(stats.tup_returned || 0),
unit: "rows",
description: "Total rows returned by queries",
};
info.tuples_fetched = {
value: String(stats.tup_fetched || 0),
unit: "rows",
description: "Total rows fetched by queries",
};
info.tuples_inserted = {
value: String(stats.tup_inserted || 0),
unit: "rows",
description: "Total rows inserted",
};
info.tuples_updated = {
value: String(stats.tup_updated || 0),
unit: "rows",
description: "Total rows updated",
};
info.tuples_deleted = {
value: String(stats.tup_deleted || 0),
unit: "rows",
description: "Total rows deleted",
};
info.total_deadlocks = {
value: String(stats.deadlocks || 0),
unit: "deadlocks",
description: "Total deadlocks detected",
};
info.temp_files_created = {
value: String(stats.temp_files || 0),
unit: "files",
description: "Total temporary files created",
};
const tempBytes = parseInt(stats.temp_bytes || "0", 10);
info.temp_bytes_written = {
value: formatBytes(tempBytes),
unit: "bytes",
description: "Total temporary file bytes written",
};
// Uptime from db_stats
if (stats.postmaster_uptime_s) {
const uptimeSeconds = parseInt(stats.postmaster_uptime_s, 10);
const days = Math.floor(uptimeSeconds / SECONDS_PER_DAY);
const hours = Math.floor((uptimeSeconds % SECONDS_PER_DAY) / SECONDS_PER_HOUR);
const minutes = Math.floor((uptimeSeconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
info.uptime = {
value: `${days} days ${hours}:${String(minutes).padStart(2, "0")}:${String(uptimeSeconds % SECONDS_PER_MINUTE).padStart(2, "0")}`,
unit: "interval",
description: "Server uptime",
};
}
}
// Get connection states (simple inline SQL)
const connResult = await client.query(`
select
coalesce(state, 'null') as state,
count(*) as count
from pg_stat_activity
group by state
`);
for (const row of connResult.rows) {
const stateKey = `connections_${row.state.replace(/\s+/g, "_")}`;
info[stateKey] = {
value: String(row.count),
unit: "connections",
description: `Connections in '${row.state}' state`,
};
}
// Get uptime info (simple inline SQL)
const uptimeResult = await client.query(`
select
pg_postmaster_start_time() as start_time,
current_timestamp - pg_postmaster_start_time() as uptime
`);
if (uptimeResult.rows.length > 0) {
const uptime = uptimeResult.rows[0];
const startTime = uptime.start_time instanceof Date
? uptime.start_time.toISOString()
: String(uptime.start_time);
info.start_time = {
value: startTime,
unit: "timestamp",
description: "PostgreSQL server start time",
};
if (!info.uptime) {
info.uptime = {
value: String(uptime.uptime),
unit: "interval",
description: "Server uptime",
};
}
}
return info;
}
/**
* Get invalid indexes from the database (H001).
* Invalid indexes have indisvalid = false, typically from failed CREATE INDEX CONCURRENTLY.
*
* @param client - Connected PostgreSQL client
* @param pgMajorVersion - PostgreSQL major version (default: 16)
* @returns Array of invalid index entries with observation data for decision tree analysis
*/
export async function getInvalidIndexes(client: Client, pgMajorVersion: number = 16): Promise<InvalidIndex[]> {
const sql = getMetricSql(METRIC_NAMES.H001, pgMajorVersion);
const result = await client.query(sql);
return result.rows.map((row) => {
const transformed = transformMetricRow(row);
const indexSizeBytes = parseInt(String(transformed.index_size_bytes || 0), 10);
return {
schema_name: String(transformed.schema_name || ""),
table_name: String(transformed.table_name || ""),
index_name: String(transformed.index_name || ""),
relation_name: String(transformed.relation_name || ""),
index_size_bytes: indexSizeBytes,
index_size_pretty: formatBytes(indexSizeBytes),
index_definition: String(transformed.index_definition || ""),
supports_fk: toBool(transformed.supports_fk),
is_pk: toBool(transformed.is_pk),
is_unique: toBool(transformed.is_unique),
constraint_name: transformed.constraint_name ? String(transformed.constraint_name) : null,
table_row_estimate: parseInt(String(transformed.table_row_estimate || 0), 10),
has_valid_duplicate: toBool(transformed.has_valid_duplicate),
valid_duplicate_name: transformed.valid_index_name ? String(transformed.valid_index_name) : null,
valid_duplicate_definition: transformed.valid_index_definition ? String(transformed.valid_index_definition) : null,
};
});
}
/**
* Get unused indexes from the database (H002).
* Unused indexes have zero scans since stats were last reset.
*
* @param client - Connected PostgreSQL client
* @param pgMajorVersion - PostgreSQL major version (default: 16)
* @returns Array of unused index entries with scan counts and FK support info
*/
export async function getUnusedIndexes(client: Client, pgMajorVersion: number = 16): Promise<UnusedIndex[]> {
const sql = getMetricSql(METRIC_NAMES.H002, pgMajorVersion);
const result = await client.query(sql);
return result.rows.map((row) => {
const transformed = transformMetricRow(row);
const indexSizeBytes = parseInt(String(transformed.index_size_bytes || 0), 10);
return {
schema_name: String(transformed.schema_name || ""),
table_name: String(transformed.table_name || ""),
index_name: String(transformed.index_name || ""),
index_definition: String(transformed.index_definition || ""),
reason: String(transformed.reason || ""),
idx_scan: parseInt(String(transformed.idx_scan || 0), 10),
index_size_bytes: indexSizeBytes,
idx_is_btree: toBool(transformed.idx_is_btree),
supports_fk: toBool(transformed.supports_fk),
index_size_pretty: formatBytes(indexSizeBytes),
};
});
}
/**
* Get stats reset info (H002)
* SQL loaded from config/pgwatch-prometheus/metrics.yml (stats_reset)
*/
export async function getStatsReset(client: Client, pgMajorVersion: number = 16): Promise<StatsReset> {
const sql = getMetricSql(METRIC_NAMES.statsReset, pgMajorVersion);
const result = await client.query(sql);
const row = result.rows[0] || {};
// The stats_reset metric returns stats_reset_epoch and seconds_since_reset
// We need to calculate additional fields
const statsResetEpoch = row.stats_reset_epoch ? parseFloat(row.stats_reset_epoch) : null;
const secondsSinceReset = row.seconds_since_reset ? parseInt(row.seconds_since_reset, 10) : null;
// Calculate stats_reset_time from epoch
const statsResetTime = statsResetEpoch
? new Date(statsResetEpoch * 1000).toISOString()
: null;
// Calculate days since reset
const daysSinceReset = secondsSinceReset !== null
? Math.floor(secondsSinceReset / SECONDS_PER_DAY)
: null;
// Get postmaster startup time separately (simple inline SQL)
// This is supplementary data - errors are captured in output, not propagated
let postmasterStartupEpoch: number | null = null;
let postmasterStartupTime: string | null = null;
let postmasterStartupError: string | undefined;
try {
const pmResult = await client.query(`
select
extract(epoch from pg_postmaster_start_time()) as postmaster_startup_epoch,
pg_postmaster_start_time()::text as postmaster_startup_time
`);
if (pmResult.rows.length > 0) {
postmasterStartupEpoch = pmResult.rows[0].postmaster_startup_epoch
? parseFloat(pmResult.rows[0].postmaster_startup_epoch)
: null;
postmasterStartupTime = pmResult.rows[0].postmaster_startup_time || null;
}
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
postmasterStartupError = `Failed to query postmaster start time: ${errorMsg}`;
console.error(`[getStatsReset] Warning: ${postmasterStartupError}`);
}
const statsResult: StatsReset = {
stats_reset_epoch: statsResetEpoch,
stats_reset_time: statsResetTime,
days_since_reset: daysSinceReset,
postmaster_startup_epoch: postmasterStartupEpoch,
postmaster_startup_time: postmasterStartupTime,
};
// Only include error field if there was an error (keeps output clean)
if (postmasterStartupError) {
statsResult.postmaster_startup_error = postmasterStartupError;
}
return statsResult;
}
/**
* Get current database name and size
* Uses 'db_size' metric from metrics.yml
*/
export async function getCurrentDatabaseInfo(client: Client, pgMajorVersion: number = 16): Promise<{ datname: string; size_bytes: number }> {
const sql = getMetricSql(METRIC_NAMES.dbSize, pgMajorVersion);
const result = await client.query(sql);
const row = result.rows[0] || {};
// db_size metric returns tag_datname and size_b
return {
datname: row.tag_datname || "postgres",
size_bytes: parseInt(row.size_b || "0", 10),
};
}
/**
* Type guard to validate redundant_to_json item structure.
* Returns true if item is a valid object (may have expected properties).
*/
function isValidRedundantToItem(item: unknown): item is Record<string, unknown> {
return typeof item === "object" && item !== null && !Array.isArray(item);
}
/**
* Get redundant indexes from the database (H004).
* Redundant indexes are covered by other indexes (same leading columns).
*
* @param client - Connected PostgreSQL client
* @param pgMajorVersion - PostgreSQL major version (default: 16)
* @returns Array of redundant index entries with covering index info
*/
export async function getRedundantIndexes(client: Client, pgMajorVersion: number = 16): Promise<RedundantIndex[]> {
const sql = getMetricSql(METRIC_NAMES.H004, pgMajorVersion);
const result = await client.query(sql);
return result.rows.map((row) => {
const transformed = transformMetricRow(row);
const indexSizeBytes = parseInt(String(transformed.index_size_bytes || 0), 10);
const tableSizeBytes = parseInt(String(transformed.table_size_bytes || 0), 10);
// Parse redundant_to JSON array (indexes that make this one redundant)
let redundantTo: RedundantToIndex[] = [];
let parseError: string | undefined;
try {
const jsonStr = String(transformed.redundant_to_json || "[]");
const parsed = JSON.parse(jsonStr);
if (Array.isArray(parsed)) {
redundantTo = parsed
.filter(isValidRedundantToItem)
.map((item) => {
const sizeBytes = parseInt(String(item.index_size_bytes ?? 0), 10);
return {
index_name: String(item.index_name ?? ""),
index_definition: String(item.index_definition ?? ""),
index_size_bytes: sizeBytes,
index_size_pretty: formatBytes(sizeBytes),
};
});
}
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
const indexName = String(transformed.index_name || "unknown");
parseError = `Failed to parse redundant_to_json: ${errorMsg}`;
console.error(`[H004] Warning: ${parseError} for index "${indexName}"`);
}
const result: RedundantIndex = {
schema_name: String(transformed.schema_name || ""),
table_name: String(transformed.table_name || ""),
index_name: String(transformed.index_name || ""),
relation_name: String(transformed.relation_name || ""),
access_method: String(transformed.access_method || ""),
reason: String(transformed.reason || ""),
index_size_bytes: indexSizeBytes,
table_size_bytes: tableSizeBytes,
index_usage: parseInt(String(transformed.index_usage || 0), 10),
supports_fk: toBool(transformed.supports_fk),
index_definition: String(transformed.index_definition || ""),
index_size_pretty: formatBytes(indexSizeBytes),
table_size_pretty: formatBytes(tableSizeBytes),
redundant_to: redundantTo,
};
// Only include parse error field if there was an error (keeps output clean)
if (parseError) {
result.redundant_to_parse_error = parseError;
}
return result;
});
}
/**
* Create base report structure
*/
export function createBaseReport(
checkId: string,
checkTitle: string,
nodeName: string
): Report {
const buildTs = resolveBuildTs();
return {
version: pkg.version || null,
build_ts: buildTs,
generation_mode: "express",
checkId,
checkTitle,
timestamptz: new Date().toISOString(),
nodes: {
primary: nodeName,
standbys: [],
},
results: {},
};
}
function readTextFileSafe(p: string): string | null {
try {
const value = fs.readFileSync(p, "utf8").trim();
return value || null;
} catch {
// Intentionally silent: this is a "safe" read that returns null on any error
// (file not found, permission denied, etc.) - used for optional config files
return null;
}
}
function resolveBuildTs(): string | null {
// Follow reporter.py approach: read BUILD_TS from filesystem, with env override.
// Default: /BUILD_TS (useful in container images).
const envPath = process.env.PGAI_BUILD_TS_FILE;
const p = (envPath && envPath.trim()) ? envPath.trim() : "/BUILD_TS";
const fromFile = readTextFileSafe(p);
if (fromFile) return fromFile;
// Fallback for packaged CLI: allow placing BUILD_TS next to dist/ (package root).
// dist/lib/checkup.js => package root: dist/..
try {
const pkgRoot = path.resolve(__dirname, "..");
const fromPkgFile = readTextFileSafe(path.join(pkgRoot, "BUILD_TS"));
if (fromPkgFile) return fromPkgFile;
} catch (err) {
// Path resolution failing is unexpected - warn about it
const errorMsg = err instanceof Error ? err.message : String(err);
console.warn(`[resolveBuildTs] Warning: path resolution failed: ${errorMsg}`);
}
// Last resort: use package.json mtime as an approximation (non-null, stable-ish).
try {
const pkgJsonPath = path.resolve(__dirname, "..", "package.json");
const st = fs.statSync(pkgJsonPath);
return st.mtime.toISOString();
} catch (err) {
// package.json not found is expected in some environments (e.g., bundled) - debug only
if (process.env.DEBUG) {
const errorMsg = err instanceof Error ? err.message : String(err);
console.error(`[resolveBuildTs] Could not stat package.json, using current time: ${errorMsg}`);
}
return new Date().toISOString();
}
}
/**
* Generate a simple version report (A002, A013).
* These reports only contain PostgreSQL version information.
*/
async function generateVersionReport(
client: Client,
nodeName: string,
checkId: string,
checkTitle: string
): Promise<Report> {
const report = createBaseReport(checkId, checkTitle, nodeName);
const postgresVersion = await getPostgresVersion(client);
report.results[nodeName] = { data: { version: postgresVersion } };
return report;
}
/**
* Generate a settings-based report (A003, A007).
* Fetches settings using provided function and includes postgres_version.
*/
async function generateSettingsReport(
client: Client,
nodeName: string,
checkId: string,
checkTitle: string,
fetchSettings: (client: Client, pgMajorVersion: number) => Promise<Record<string, unknown>>
): Promise<Report> {
const report = createBaseReport(checkId, checkTitle, nodeName);
const postgresVersion = await getPostgresVersion(client);
const pgMajorVersion = parseInt(postgresVersion.server_major_ver, 10) || 16;
const settings = await fetchSettings(client, pgMajorVersion);
report.results[nodeName] = { data: settings, postgres_version: postgresVersion };
return report;
}
/**
* Generate an index report (H001, H002, H004).
* Common structure: index list + totals + database info, keyed by database name.
*/
async function generateIndexReport<T extends { index_size_bytes: number }>(
client: Client,
nodeName: string,
checkId: string,