This is the multi-page printable view of this section. .
Documentation
- 1: About kbdiag
- 2: Command reference
- 2.1: status: instance overview and local health
- 2.2: check: nine-domain health patrol
- 2.3: session: active sessions, PID detail and wait summary
- 2.4: lock: blocking chains and DDL queue predecessors
- 2.5: txn: open transactions, 2PC and XID horizons
- 2.6: progress: running maintenance and index builds
- 2.7: sql: cumulative workload and queryid profile
- 2.8: space: filesystems, WAL size, databases and tablespaces
- 2.9: object: database objects, tables, indexes and sequences
- 2.10: vacuum: dead tuples and autovacuum
- 2.11: freeze: XID and multixact wraparound age
- 2.12: wal: WAL volume, retention, and archiving
- 2.13: checkpoint: checkpoints, bgwriter, and buffer writes
- 2.14: repl: streaming replication and sync state
- 2.15: slots: replication slots and retention
- 2.16: cluster: repmgr cluster topology and sync mode
- 2.17: server: instance summary, parameters and license
- 3: Capabilities
- 4: Your first check
- 4.1: Read the evidence
- 5: Troubleshooting scenarios
Use status for the first look and check --html patrol.html for a bounded health report. The reference follows 17 canonical top-level commands in six groups.
1 - About kbdiag
Purpose
kbdiag translates KingbaseES system evidence into a verdict, supporting facts and the next diagnostic command. It serves DBAs, operations teams and automation scripts handling sessions, locks, transaction horizons, workload, storage and replication.
Runtime and requirements
One static Linux amd64/arm64 binary speaks the database protocol directly; the database host needs no ksql, Go runtime or agent service. Supported families are KES V8R6 + V9 (V008R006* and V009R002* verified). SQL variants follow detected views, columns, database mode and XID width rather than a guessed version number. repmgr is optional and isolated in cluster.
Operating boundaries
Diagnostic connections run read-only with a 500ms lock timeout, bounded execution budget and cancellation. kbdiag never alters data, terminates sessions or runs online EXPLAIN ANALYZE. Bounded --exact object-size lookups can request relation locks; review the object reference before opting in.
point, counter, delta and estimate describe different evidence semantics. Missing or masked evidence is always shown explicitly; a visible FAIL never hides incomplete coverage. Each command captures a snapshot rather than running continuous monitoring. check --html exports a zero-JS, CSP-restricted static file (0600) with SQL redacted by default.
Reference and next step
Use the command reference to check required privileges, standby behavior, and verdict rules before automation or incident response.
2 - Command reference
kbdiag provides 17 top-level commands grouped by operational workflow. Legacy command paths remain supported as hidden aliases without changing JSON compatibility.
Entry points
| Command | Question / drill-down |
|---|---|
status | First look: identity, role, connections and coverage |
check | Bounded nine-domain patrol; check --html ./patrol.html |
Runtime & concurrency
| Command | Question / drill-down |
|---|---|
session | session <pid>; session waits |
lock | lock <pid>; lock --tree; lock --table <table> |
txn | Transaction horizons and 2PC (--xact-warn, --prepared-warn) |
progress | Running VACUUM, CREATE INDEX, CLUSTER, and CHECKPOINT phases |
Workload
| Command | Question / drill-down |
|---|---|
sql | sql top; sql show --id=<int64>; cumulative statistics |
Storage & objects
| Command | Question / drill-down |
|---|---|
space | Local filesystems, WAL, databases and tablespaces |
object | object summary; object table/index/seq [name] |
vacuum | Current-database dead tuples and autovacuum; --schema |
freeze | Instance database ages and current-database table ages |
Persistence & writes
| Command | Question / drill-down |
|---|---|
wal | WAL position, volume and retention; wal archive |
checkpoint | Checkpoint, bgwriter and backend write counters |
Replication & server
| Command | Question / drill-down |
|---|---|
repl | Local kernel streaming replication, sync state and lag |
slots | Physical/logical replication slots, retained WAL and xmin |
cluster | External repmgr topology; defaults to esrep |
server | Server summary; server params; server license |
Connection and exit codes
Use -h/--host, -p, -d, -U, -W/--password and --sslmode to specify the target instance (precedence: explicit CLI flag > KINGBASE_* > PG* > defaults; password via -W, KINGBASE_PASSWORD, PGPASSWORD or ~/.pgpass); use --help for command usage. --json emits machine-readable output.
Exit codes: 0 OK, 1 WARN, 2 FAIL, 3 UNKNOWN, 64 usage error, 69 connection failure.
2.1 - status: instance overview and local health
First command to run on an instance: one screen showing role, connection headroom, active/waiting sessions, license validity, replication lag and local data-directory disk usage. Read-only: never modifies sessions, settings or data.
Usage
Key Options
| Option | Effect |
|---|---|
-h <host> | Target host IP/DNS or Unix socket directory (default /tmp); TCP skips local disk checks with [COVERAGE] |
-p <port>, -d <db>, -U <user> | Target port (default 54321), database (test), and user (system) |
--json | Emit structured JSON (inst.info, inst.downstreams, inst.upstream, inst.databases, inst.disk) |
Verdict & Reading Output
FAIL(exit=2): Ordinary-user connections exhausted, data filesystem>= 95%used (statfsover local Unix socket), or expired license.WARN(exit=1): Data filesystem>= 90%, license<= 30days remaining, or standby WAL receiver missing/disconnected/replay paused.UNKNOWN(exit=3): Required probes failed or masked—non-monitoring users who cannot read other sessions see[REDACTED]instead of false0activity; remote TCP runs skip local disk cleanly.- Standbys:
[REPLICATION]shows upstream host/slot, WAL replay state (active/paused), and byte lag.
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag check— run the bounded nine-domain health patrol and offline HTML exportkbdiag session— inspect active, waiting, oridle in transactionconnectionskbdiag space/kbdiag server— inspect host disk mounts or license/parameter details
2.2 - check: nine-domain health patrol
Patrols nine bounded domains in one connection (connections, license, disk, replication, slots, archive, freeze, locks, txn) without scanning user table sizes. Read-only: never modifies sessions, parameters, or objects.
Usage
Key Options
| Option | Effect |
|---|---|
--html <file> | Write a static offline HTML report atomically (0600, strict CSP, no scripts/CDNs) |
--html-raw-sql | Opt in to raw SQL inside HTML (default redacts SQL columns/fields to <redacted>) |
--json | Emit check.domains matrix plus all 16 domain probes and redacted[] metadata |
Verdict & Reading Output
FAIL(exit=2) /WARN(exit=1): Any domain triggers a rule finding;[NEXT]prioritizesFAILthenWARNdrilldowns ahead of missing-coverage items so confirmed incidents are never crowded out.UNKNOWN(exit=3): Missing/skipped/error/redacted coverage without a higher-severity finding; failed/skipped probes are listed in top[COVERAGE]and affected domains are summarized under[SUMMARY](Missing domains) and wrapped cleanly inside[DOMAIN MATRIX].--htmlsecurity: Zero JavaScript/external resources (script-src 'none'); HTML preserves non-SQL cells alongside<redacted>SQL placeholders and rendersredacted[]privilege gaps.
Example (KES V9 Primary, excerpt, COLUMNS=80)
Related Commands
kbdiag space— inspect full filesystem mounts and database/tablespace sizeskbdiag repl/kbdiag slots— drill into standby streaming links and slot retentionkbdiag session/kbdiag lock— inspect active sessions, waits, and lock trees
2.3 - session: active sessions, PID detail and wait summary
Inspect live instance sessions from three angles: session (overview and active/blocking list), session <pid> (one session’s full SQL, waits, and locks), and session waits (wait-event distribution). Read-only: never terminates or cancels backends.
Usage
Key Options
| Option | Effect |
|---|---|
--app, --session-user, --session-db | Narrow displayed rows ([OVERVIEW] and JSON remain instance-wide) |
--state, --wait-type, --min-xact-age | Filter by session state (active/idle/idle-in-txn/waiting), wait type, or txn age |
--sort xact|query, --limit N, --wide | Control row sorting, display cap, and client/queryid columns |
Verdict & Reading Output
WARN(exit=1): Openidle in transactionsession>= 300s(--idle-in-txn-warn), or wait>= 10s(--lock-wait-warn) onsession <pid>.OK(exit=0): All visible sessions within configured thresholds.UNKNOWN(exit=3): Non-monitoring roles unable to read other sessions’ SQL/waits see[REDACTED]and visible counts rather than fake0activity.session <pid>/session waits:session <pid>labelsidle in transactionqueries[LAST SQL]and prints blocker jump commands;session waitsseparates idle background/walsenderloops from active waits.
Example (KES V9 Primary, excerpt, COLUMNS=80)
Related Commands
kbdiag lock— expand the full blocking hierarchy and DDL queue predecessorskbdiag txn— inspect long open transactions and prepared2PChorizonskbdiag sql— trace aqueryidfromsession --wideinto cumulative statistics
2.4 - lock: blocking chains and DDL queue predecessors
Find who holds locks, who is waiting in the queue, and whether a blocked DDL request is stalling downstream reads or writes. Read-only: never terminates holders or drops locks.
Usage
Key Options
| Option | Effect |
|---|---|
--tree | Render blocking hierarchy and highlight [DDL queue predecessor] nodes |
--table <name> | Filter displayed chains to one relation (resolved within current database) |
--lock-wait-warn <sec> | Wait duration threshold for WARN (default 10s) |
--limit <N> | Cap rendered waiter rows (0 unlimited); blocker edge lookup samples up to 50 global waiting PIDs |
Verdict & Reading Output
WARN(exit=1): Waiting lock duration>= --lock-wait-warn(default10s), including waits blocked by an uncommitted prepared transaction (2PC).UNKNOWN(exit=3): Non-monitoring users unable to read wait times seeUNKNOWN; probe collection caps blocker edge lookups at 50 waiting PIDs globally (--tableand<pid>filter display after collection without expanding the 50-PID global edge budget).- V8R6 vs V9: Versions lacking
sys_locks.waitstartestimate upper-bound waits as<=Ns (est.)fromstate_change.
Example (KES V9 Primary, --lock-wait-warn 1 --tree, COLUMNS=80)
Related Commands
kbdiag session— inspect the root holder PID’s transaction state and full SQLkbdiag txn— investigate2PCprepared transactions or long open blockerskbdiag progress— check whether an index build or vacuum is waiting on snapshots
2.5 - txn: open transactions, 2PC and XID horizons
Identify long-running transactions, unfinished two-phase commits (2PC), and the session, 2PC, or replication slot holding back the vacuum horizon. Read-only: never commits, rolls back, or cancels transactions.
Usage
Key Options
| Option | Effect |
|---|---|
--xact-warn <sec> | WARN age threshold for open transactions (default 300s) |
--prepared-warn <sec> | WARN age threshold for prepared 2PC transactions (default 900s) |
--limit <N> | Max open-transaction rows rendered (0 unlimited; prepared 2PC rows remain unlimited and verdict evaluates all rows) |
--json | Emit structured JSON (session.activity, txn.prepared, slot.list, raw GIDs and XIDs) |
Verdict & Reading Output
WARN(exit=1):txn.long(open transaction age>= --xact-warn, default300s) ortxn.prepared(2PCage>= --prepared-warn, default900s).UNKNOWN(exit=3):session.activityunavailable/masked or primarytxn.preparedprobe failed.- Horizon & standby rules:
[OVERVIEW]comparesbackend_xid,backend_xmin,2PCXIDs, and slotxmintogether (tie-breaking in favor of actual transaction writers over snapshot retainers). On standbys,txn.preparedreportsnot_applicable; check2PCon the primary. Never commit or roll back a prepared2PCwithout checking its coordinator first.
Example (KES V9 Primary, --xact-warn 1 --prepared-warn 1, COLUMNS=80)
Related Commands
kbdiag session— inspect a long transaction PID’s current SQL and held lockskbdiag slots— inspect replication slots retainingxminorcatalog_xminkbdiag vacuum/kbdiag freeze— measure dead-tuple accumulation and XID age impact
2.6 - progress: running maintenance and index builds
Reads sys_stat_progress_vacuum, sys_stat_progress_create_index, sys_stat_progress_cluster, and sys_stat_progress_checkpoint across the instance. Read-only: never starts or cancels maintenance operations.
Phase progress reflects only the current stage (for example, block scan or sort), not total ETA.
ANALYZEand base backups have no progress views in KES V8R6/V9.
Usage
Key Options
| Option | Effect |
|---|---|
--json | Emit structured JSON (progress.list, progress.checkpoint) |
Verdict & Reading Output
OK(exit=0): Both progress probes succeeded without redacted rows. WhenCREATE INDEX CONCURRENTLYis waiting on older transactions, a[NEXT]hint points tokbdiag lock.UNKNOWN(exit=3): A progress view failed/timed out or rows were hidden from non-monitoring users ([REDACTED] progress.list.phase). Incomplete probes never claim no operations are running.
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag lock— inspect blockers whenCREATE INDEX CONCURRENTLYwaits on older transactionskbdiag vacuum— current-database dead tuples and autovacuum switcheskbdiag checkpoint— background writer, fsync, and checkpoint intervals
2.7 - sql: cumulative workload and queryid profile
Find top cumulative statements from sys_stat_statements (sql / sql top), then inspect one signed 64-bit queryid profile and its matching active sessions (sql show). Read-only: never runs online EXPLAIN.
Usage
Subcommands & Options
| Option | Effect |
|---|---|
sql / sql top | Rank cumulative statements (--by=time|mean|calls|io|temp, --limit N) |
sql show --id=<int64> | Show one statement’s cumulative metrics plus live sessions sharing queryid |
--sql-db, --sql-user | Filter statement rows without changing the connection’s -d / -U |
--json | Emit structured JSON (sql.top, sql.show, sql.show.active) |
Verdict & Reading Output
OK(exit=0): Collected requested cumulative metrics and active match status cleanly; equalqueryidentries across different(dbid, userid)pairs stay separate, never summed.UNKNOWN(exit=3):sys_stat_statementsmissing/track=nonewith no rows, hiddenqueryidfor non-monitoring accounts, or missingsys_stat_activity.queryidcapability (e.g. KES V8R6, wheresql showexplicitly marks active matching unavailable).- Cumulative window caveat: Counters accumulate since the last statistics reset (or retain older rows when
sys_stat_statements.track=none).
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag session— inspect live PID details (sqlactivity, waits, locks)kbdiag lock— check whether top execution time comes from lock contentionkbdiag space— inspect temp file / disk headroom whentemporioleads
2.8 - space: filesystems, WAL size, databases and tablespaces
Inspects host filesystems for data_directory, sys_wal, and external tablespaces (local Unix socket only), plus WAL directory volume/limits, database sizes, and tablespaces. Read-only: never removes WAL segments or inspects table contents.
Usage
Key Options
| Option | Effect |
|---|---|
--json | Emit JSON probes (space.disk, space.wal, inst.databases, space.tablespaces) |
Verdict & Reading Output
FAIL(exit=2):space.disk_fullwhen free space on adata_directoryorwalfilesystem drops below one WAL segment (wal_segment_size).OK(exit=0): All probes collected cleanly with no redacted sizes and at least one WAL segment free ondata_directoryandwalfilesystems.UNKNOWN(exit=3): Remote connection (space.disk: not_applicable), missingsys_walortablespacestatfspermission (partial: skipped), deniedsys_ls_waldir()(kbdiag_ro), or missing segment size. Surviving mounts remain visible under[DISK]even on partial skips.
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag wal— inspect current LSN position, replication slots, andarchive_readybacklogkbdiag slots— check inactive replication slots retaining WALkbdiag object— find the largest tables and indexes inside a database
2.9 - object: database objects, tables, indexes and sequences
Survey the current database with object (summary), then inspect object table [name], object index [name], or object seq [name]. Repeat --schema to target specific schemas, or --all-schemas to include system schemas. Read-only: never executes VACUUM or DROP INDEX.
Usage
Subcommands & Options
| Command / Option | Effect |
|---|---|
object / object summary | Inventory object counts and estimated size by schema and relation kind |
object table [name] | Rank tables (--by=size|rows|dead|seq_scan, --partitioned) or inspect one table in 6 clues |
object index [name] | Rank indexes (--by=size|scans, --unused, --invalid) or inspect one index |
object seq [name] | Check integer/range exhaustion risk across sequences |
--schema, --all-schemas, --exact | Filter schema scope; opt in to locked/exact pg_table_size within --exact-budget (default 20) |
Verdict & Reading Output
FAIL(exit=2): Exhausted non-cycling sequence (seq.exhausted) with0remaining values; for cached sequences (cache_size > 1), existing backends may continue briefly until their local cache depletes while new allocations already fail.WARN(exit=1): Invalid/unready indexes or autovacuum disabled past dead-tuple threshold (sequences with remaining capacity remain informational until exhausted).UNKNOWN(exit=3):--exactexceeded--exact-budget(marked in[COVERAGE]instead of silent truncation),--unusedrun on a standby (node-local scan counters),object seqmissing privilege on restricted sequences, or incomplete single-table size/index probes.
Example (KES V9 Primary, excerpt, COLUMNS=80)
Related Commands
kbdiag vacuum— current-database dead tuples and autovacuum blockerskbdiag freeze— oldest XID/MXID relation ages and wraparound headroomkbdiag space— total database, WAL, and filesystem capacity
2.10 - vacuum: dead tuples and autovacuum
Inspects sys_stat_user_tables, pg_class.reloptions, sys_stat_progress_vacuum, and autovacuum switches in the current database. Read-only: never executes VACUUM.
Usage
Key Options
| Option | Effect |
|---|---|
--schema name | Limit tables to specific schema(s) (repeatable; conflicts with --all-schemas) |
--all-schemas | Include system schemas such as sysmac, sys_hm, kdb_schedule |
--limit N | Show at most N tables (default 20, 0 for unlimited; judges all tables in scope) |
--json | Emit structured JSON (vacuum.tables, vacuum.progress, vacuum.settings) |
Verdict & Reading Output
WARN(exit=1):vacuum.disabled(autovacuumortrack_countsis off) orvacuum.table_disabled(table exceededthreshold + scale_factor * reltupleswithautovacuum_enabled=off).UNKNOWN(exit=3):vacuum.settings/vacuum.progressfailed/skipped (including standby settings errors) ortrack_counts=offskipped table stats.OK(exit=0): switches are on and no disabled table exceeds threshold;due=yeswithautovacuum=onis normal queue behavior, not a fault. On standbys, table stats and running vacuums arenot_applicable.
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag freeze— XID / multixact age and wraparound headroomkbdiag txn— oldest transaction holding back dead-tuple cleanupkbdiag slots— replication slots retaining oldxmin
2.11 - freeze: XID and multixact wraparound age
Inspects database-wide datfrozenxid / datminmxid ages across the cluster and relation relfrozenxid / relminmxid ages in the current database. Read-only: never runs VACUUM FREEZE.
Usage
Key Options
| Option | Effect |
|---|---|
--schema name | Filter table listing to specific schema(s); database-level freeze stays instance-wide |
--all-schemas | Show all schemas in the current database (same as default table coverage; conflicts with --schema) |
--limit N | Show at most N oldest relations (default 20, 0 for unlimited; DB judgment covers all DBs) |
--json | Emit structured JSON (freeze.limits, freeze.databases, freeze.tables) |
Verdict & Reading Output
FAIL(exit=2): On 32-bit XID kernels (e.g. KES V8), database XID/MXID age reached the hard stop limit (2146483647/2147483547). Writes fail and single-user maintenance may be required.WARN(exit=1): Database age exceededautovacuum_freeze_max_ageorautovacuum_multixact_freeze_max_age; anti-wraparound autovacuum is due or blocked.UNKNOWN(exit=3): Limits, databases, or tables probes incomplete/failed (freeze.limits,freeze.databases, orfreeze.tables).- 64-bit XID note: On KES V9 64-bit XID servers, kbdiag detects
xidwidth cleanly and skips the PG12 32-bit stop limit (xid stop limit: 64-bit xid).
Example (KES V9 Primary, excerpt, COLUMNS=80)
Related Commands
kbdiag vacuum— dead tuples and autovacuum blockers in the current databasekbdiag txn— oldest running transaction or 2PC holding back freeze horizonkbdiag slots— inactive replication slots retainingxmin
2.12 - wal: WAL volume, retention, and archiving
Inspects current WAL/replay position, sys_wal disk footprint, retention factors (replication slots, wal_keep_segments, pending .ready files), and archiver status (kbdiag wal archive). Read-only: never switches, deletes, or checkpoints WAL.
Usage
Subcommands & Options
| Command / Option | Effect |
|---|---|
kbdiag wal | Show WAL/replay LSN, sys_wal size, max_wal_size, wal_keep_segments, slots, and .ready count |
kbdiag wal archive | Show archive_mode, archive_command, archiver counts/timestamps, and .ready/.done queue |
--json | Emit structured JSON (wal.position, space.wal, slot.list, archive.ready, archive.status) |
Verdict & Reading Output
wal:OK(exit=0): All WAL probes collected cleanly; retention items with[NEXT]guide follow-up tokbdiag slotsorkbdiag wal archive.UNKNOWN(exit=3): Non-monitoring roles (kbdiag_ro) skipsys_ls_waldir()andsys_ls_archive_statusdir().
wal archive:WARN(exit=1):archive.failingwhenarchive_modeis active (primary, or standby withalways),archive_commandis non-empty, andlast_failed_timeis newer thanlast_archived_time(or never succeeded).OK(exit=0): Archiving healthy, intentionally disabled (offor standbyon).UNKNOWN(exit=3):archive.statusorarchive.readyfailed/skipped.
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag slots— inspect inactive replication slots andxmin/ WAL retentionkbdiag checkpoint— checkpoint vs bgwriter vs backend buffer writeskbdiag space— filesystem free space fordata_directory,sys_wal, and tablespaces
2.13 - checkpoint: checkpoints, bgwriter, and buffer writes
Reads sys_control_checkpoint(), sys_stat_bgwriter, and checkpoint GUCs (checkpoint_timeout, max_wal_size, checkpoint_completion_target, checkpoint_warning, log_checkpoints). Read-only: never runs CHECKPOINT.
Counters accumulate since
stats_reset; on standbys,checkpoints_timedcounts restartpoint attempts (one try every 15s when no new checkpoint record arrives) and does not compare directly with primary counts.
Usage
Key Options
| Option | Effect |
|---|---|
--json | Emit structured JSON (checkpoint.last, checkpoint.stats, checkpoint.settings) |
Verdict & Reading Output
OK(exit=0): All three probes succeeded (informational metrics — cumulative counters are shown, never turned into synthetic alarms).UNKNOWN(exit=3): Any checkpoint probe failed, timed out, or lacked permission.[NEXT]hints: Guides tokbdiag walwhencheckpoints_req > checkpoints_timedorbuffers_backend_fsync > 0, and noteslog_checkpoints = onwhen disabled.
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag wal— inspect WAL footprint,max_wal_size, slots, and archiver retentionkbdiag wal(wal archive) — check archiver success/failure and.readyqueuekbdiag progress— inspect an in-progressCHECKPOINT
2.14 - repl: streaming replication and sync state
Reads sys_stat_replication, synchronous_standby_names / synchronous_commit, and standby receiver/replay views (sys_stat_wal_receiver, sys_is_wal_replay_paused()). Read-only: never modifies configuration or pauses/resumes replay; use kbdiag cluster for repmgr topology.
Lag values are descriptive only. A standby replaying no new writes on an idle primary shows rising
last replayed transactionage even with zero byte lag.
Usage
Key Options
| Option | Effect |
|---|---|
--json | Emit structured JSON (repl.sync, inst.upstream, repl.replay, repl.downstreams) |
Verdict & Reading Output
WARN(exit=1):inst.upstream: standby has no WAL receiver orlast_msg_age_sexceedswal_receiver_timeout.repl.replay_paused:sys_is_wal_replay_paused()is true on standby.repl.sync_short: activesync/quorumcandidates are fewer thansynchronous_standby_namesrequires underon/remote_write/remote_apply.
UNKNOWN(exit=3): probe error/skip, unparsablesynchronous_standby_names, or masked replication state ([REDACTED]).
Example (KES V9 Standby, COLUMNS=80)
Related Commands
kbdiag cluster— repmgr node topology, primary visibility, and failover eventskbdiag slots— inactive replication slots, WAL retention, and stalexminkbdiag wal— WAL position,sys_walsize, and archive backlog
2.15 - slots: replication slots and retention
Reads sys_replication_slots and computes retained WAL from the current insert LSN (primary) or replay LSN (standby). Read-only: never drops or modifies replication slots.
Usage
Key Options
| Option | Effect |
|---|---|
--json | Emit structured JSON (slot.list including xmin, catalog_xmin, restart_lsn, retained_wal_bytes) |
Verdict & Reading Output
WARN(exit=1):slot.inactivewhen a replication slot isactive = false. Output highlights retained WAL plus anyxmin(vacuum horizon) orcatalog_xmin(logical catalog horizon) held back, sorted with inactive horizon blockers first.OK(exit=0): No inactive slots (or no slots configured).UNKNOWN(exit=3): Probe failure or timeout. Whenslot.listsucceeds, a non-NULLrestart_lsnwith a missing LSN diff still displaysretained WAL unknown(andactive = falsetriggersWARN).
Example (KES V9 Primary, COLUMNS=80)
Related Commands
kbdiag wal— see WAL directory size alongside slot and archive retentionkbdiag repl— check streaming replicas and standby receiver/replay statuskbdiag vacuum/kbdiag txn— investigate dead tuples or long-running transactions holdingxmin
2.16 - cluster: repmgr cluster topology and sync mode
Reads external repmgr metadata from database esrep by default, identifies the local node against KES recovery role, inspects local repmgr.conf synchronous settings, and lists recent events. Read-only: never promotes, rejoins, or contacts peer nodes over SSH.
Usage
Key Options
| Option | Effect |
|---|---|
-d <db> | Query repmgr metadata in <db> instead of auto-selecting esrep |
--events-limit <n> | Limit events shown in text output (5 by default; 0 shows all collected) |
--json | Emit structured JSON (cluster.nodes, cluster.sync, cluster.events, inst.downstreams) |
Verdict & Reading Output
WARN(exit=1):cluster.primaries(multiple active primaries in repmgr metadata),cluster.role_mismatch(repmgr metadata disagrees with database recovery role),cluster.inactive(node marked inactive),cluster.detached(active repmgr standby not attached to this primary’ssys_stat_replication), orcluster.sync_degraded(repmgr.confrequests synchronous mode whilesynchronous_standby_namesis empty).UNKNOWN(exit=3): Unresolved local node, insufficient privilege (kbdiag_ro), unreadable localrepmgr.conf(or remote TCP connection), or failed downstream check. Narrow terminals switch[NODES]and[EVENTS]to compact cards automatically.OK(exit=0): Single consistent topology and synchronous state match across collected metadata and kernel views, orrepmgrmetadata schema is absent (not_applicable).
Example (KES V9 Primary, excerpt, COLUMNS=80)
Related Commands
kbdiag repl— check kernel streaming replication links and replay lagkbdiag slots— inspect physical/logical slots backing cluster standbyskbdiag wal— check WAL retention and archive status
2.17 - server: instance summary, parameters and license
Covers instance summary (server), non-default / pending_restart settings (server params), and license validity/binding (server license). Read-only: never modifies parameters, reloads configs, or restarts the instance.
Usage
Subcommands & Options
| Command / Option | Effect |
|---|---|
server | Instance identity, connections summary, license summary, and non-default parameter preview |
server params | Full non-default and pending_restart parameter list with source files and line numbers |
server license | License expiry countdown, path, bound MAC, and license connection limit |
--json | Emit structured JSON (inst.identity, inst.info, params.changed, license.info) |
Verdict & Reading Output
FAIL(exit=2):license.expired(instance keeps running, next restart fails; check primary and standby separately) orinst.connections(ordinary-user connection headroom exhausted onkbdiag server).WARN(exit=1):license.expiring(within 30 days) orparams.pending_restart(changed parameter waiting for restart; suggested rollback SQL is printed safely for manual review).UNKNOWN(exit=3): Probe failure or missingsys_read_all_settings/ superuser privilege (even when visible file-backed rows are empty).- Privacy note:
license.datpath andmacprint verbatim (not redacted); scrub before external sharing.
Examples (KES V9 Primary, excerpt, COLUMNS=80)
Related Commands
kbdiag check— run nine-domain patrol including connections and licensekbdiag session— inspect active backends againstmax_connectionskbdiag status— check instance uptime, primary/standby role, and hosts
3 - Capabilities
Start with the question and scope. check is a bounded nine-domain patrol, not a full table-by-table audit.
Entry points
| Command | Question / drill-down |
|---|---|
status | First look: identity, role, connections and coverage |
check | Bounded nine-domain patrol; check --html ./patrol.html |
Runtime & concurrency
| Command | Question / drill-down |
|---|---|
session | session <pid>; session waits |
lock | lock <pid>; lock --tree; lock --table <table> |
txn | Transaction horizons and 2PC (--xact-warn, --prepared-warn) |
progress | Running VACUUM, CREATE INDEX, CLUSTER, and CHECKPOINT phases |
Workload
| Command | Question / drill-down |
|---|---|
sql | sql top; sql show --id=<int64>; cumulative statistics |
Storage & objects
| Command | Question / drill-down |
|---|---|
space | Local filesystems, WAL volume, databases and tablespaces |
object | object summary; object table/index/seq [name] |
vacuum | Current-database dead tuples and autovacuum; --schema |
freeze | Instance database ages and current-database table ages |
Persistence & writes
| Command | Question / drill-down |
|---|---|
wal | WAL position, volume and retention; wal archive |
checkpoint | Checkpoint, bgwriter and backend write counters |
Replication & server
| Command | Question / drill-down |
|---|---|
repl | Local kernel streaming replication, sync state and lag |
slots | Physical/logical replication slots, retained WAL and xmin |
cluster | External repmgr topology; defaults to database esrep |
server | Server summary; server params; server license |
Scope and interpretation
session, lock, txn, progress, repl, slots and server describe the connected instance. Lock object names resolve only for the connected database or shared objects. object and vacuum describe the current database. freeze combines instance database ages with current-database tables. space includes local-only filesystem facts (Unix socket only). cluster queries the repmgr metadata database (esrep by default).
sql ranks cumulative sys_stat_statements statistics per (dbid, userid, queryid); it is not a slow-query log.
4 - Your first check
1. Prepare and install
Use a KES V8R6 or V9 instance. Build using the Go version required by the source repository’s go.mod, then copy the static binary to the database host. Choose GOARCH=arm64 for ARM.
On the host, use your approved OS account and chmod +x ~/kbdiag. Run ~/kbdiag --version to confirm the binary (builds without -ldflags "-X main.version=..." print dev).
2. Connect
Defaults: -h /tmp, -p 54321, -d test, -U system (Unix socket /tmp/.s.KINGBASE.54321). Precedence is explicit CLI flag > KINGBASE_* > PG* > default (KINGBASE_HOST/PGHOST, KINGBASE_PORT/PGPORT, KINGBASE_DATABASE/PGDATABASE, KINGBASE_USER/PGUSER, KINGBASE_PASSWORD/PGPASSWORD, PGSSLMODE). Use -h <hostname> for TCP connections, -W/--password for no-echo TTY password prompts, --sslmode to set SSL mode, and --help for command help. Passwords are also read from KINGBASE_PASSWORD, PGPASSWORD, or ~/.pgpass. --timeout bounds each query and --total-timeout bounds the whole command. If the server requires scram-sm3 authentication, kbdiag reports guidance to use a local Unix socket or a compatible authentication channel.
Use an approved monitoring account. sys_monitor can reveal fields hidden from ordinary users; a missing privilege is reported, not silently treated as empty. TCP cannot provide local database-host filesystem measurements.
3. Run
The HTML report omits raw SQL and configuration credentials (passwords, connection URIs, env secrets) by default and writes atomically with 0600 permissions. Review it before sharing. See Read results for output format and exit code details.
4. Read exit codes
| Code | Meaning |
|---|---|
| 0 | OK within collected scope |
| 1 | WARN: investigate the finding |
| 2 | FAIL: urgent finding in visible evidence |
| 3 | UNKNOWN: required evidence missing or masked |
| 64 | Invalid command or flags |
| 69 | Could not connect |
Read $? immediately after the command. WARN/FAIL can coexist with missing coverage; inspect both. Scope and permission gaps remain meaningful even when the exit code is 1 or 2.
5. Drill down
Use lock --tree then session <pid> for blockers; session waits for wait distributions; sql top then sql show --id=<int64> for cumulative workload. object table [name], vacuum and freeze inspect the selected database; switch with -d for another database.
4.1 - Read the evidence
Output layout
Every command begins with a single header line identifying the command/operation ID, verdict, target identity, and timestamp. Depending on the command, it is followed by optional [COVERAGE] (skipped/error), [REDACTED] (masked fields), findings ([FINDINGS] or inline [WARN]/[FAIL] blocks on session/lock/txn), command-specific data sections, and [NEXT].
Long context headers wrap cleanly to 80 columns. Scripts should inspect --json fields (command, verdict, context, findings, data, redacted) rather than parsing terminal wording; legacy operation IDs (such as inst.summary on server) remain stable in JSON output.
Verdict, scope and missing evidence
Always verify target identity, collection time, and coverage before interpreting rows.
pointis an instantaneous snapshot;counteraccumulates since stats reset;deltacompares samples;estimateuses catalog statistics (relpages) rather than locking tables.- A current-database check (
object,vacuum,freezetable list, lock table names) says nothing about tables in other databases. redacted/[REDACTED]records privilege masking (sys_monitor,sys_read_all_settings, etc.);skippedanderrormark uncollected probes;not_applicablemarks role/environment inapplicability rather than failure.?never means zero, and-never proves a healthy value; a higher-severityFAIL/WARNnever hides coverage gaps.
Example interpretation & safety
Reference pages show captured KES V9 terminal outputs illustrating healthy, alert, or restricted-privilege paths depending on the command. Where a card omits routine rows with ... or lowers threshold flags to capture a warning sample, the example heading states it explicitly.
JSON and follow-up actions
Run kbdiag check --json or kbdiag session <pid> --json for structured JSON containing top-level command, verdict, context, findings, data (map keyed by probe_id), and redacted. Follow-up suggestions include read-only verification commands (kbdiag ...) and, where human intervention is needed, proposed SQL or DBA actions shown strictly for review—never executed by kbdiag.
5 - Troubleshooting scenarios
Start with kbdiag status and kbdiag check. Verify target identity, coverage and node role, then follow one diagnostic chain.
- Lock waits:
`lock --tree`→`session <pid>`→`txn` - Slow SQL:
`session waits`→`sql top`→`sql show --id=<int64>`
Storage and horizon investigations continue through space, wal archive, slots, vacuum, freeze and object table [name]. No scenario triggers automatic repair.
5.1 - Investigate lock waits
Find the chain
Use lock --tree first to see the full dependency hierarchy before narrowing to one PID or table. A queued DDL request can delay later queries before it holds its requested lock, and a direct blocker is not always the root holder.
Snapshots can change between commands. --table and <pid> filter displayed chains while [GLOBAL FINDINGS] still evaluates all collected lock rows; blocker edge resolution itself is capped globally at 50 waiting PIDs. Cross-database lock OIDs are not resolved against tables in other databases.
Inspect the owner
session <pid> displays full SQL (or [LAST SQL] when idle in transaction), waits, held/requested locks, and transaction age. idle in transaction shows an open transaction, not proof that it blocks anyone. Check txn for aged open transactions or prepared 2PC transactions that can hold locks after their session closes.
Verify before acting
Without monitoring privileges (sys_monitor), SQL for other users is masked; where wait-start timestamps are unavailable (such as versions relying on state_change), wait durations can also be hidden and yield UNKNOWN (while V9 sys_locks.waitstart may still expose wait duration even with SQL redacted). Coordinate with the application or transaction owner before committing, rolling back, or cancelling a backend; kbdiag never executes session termination.
Lock evidence and rules · Session evidence · Transaction horizons
5.2 - Investigate slow SQL
Separate now from history
session waits shows what is waiting right now; session identifies active PIDs. sql top ranks cumulative sys_stat_statements workload since the last reset—it does not prove a query is slow at this exact second. Review calls, mean, max, and total together.
Statement queryid values are signed 64-bit integers and can be negative; always pass negative values via --id=<negative> or after --. --sql-db and --sql-user filter statement metrics, while -d and -U choose the database connection.
Match identity and capability
Keep (dbid, userid, queryid) distinct—the same queryid under two users or databases represents separate entries. On KES V9, sql show matches active sessions sharing sys_stat_activity.queryid; on kernels without sys_stat_activity.queryid (such as KES V8R6), sql show reports active matching as unavailable (UNKNOWN) rather than falsely claiming zero matches. SQL text similarity alone is never treated as an identity match.
Follow the bottleneck
Continue with lock --tree for Lock waits, progress for long maintenance operations, or space/wal for heavy temp-block or I/O activity. When statement statistics are missing, or track=none returns zero retained rows, kbdiag reports UNKNOWN/skipped (retained historical rows remain readable as OK with a track=none note) without modifying parameters or enabling extensions. kbdiag never runs automatic EXPLAIN.