Skip to content

1 - About kbdiag

Purpose, supported builds and operating boundaries.

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.

Run your first check

2 - Command reference

17 commands organized into six operational groups.

kbdiag provides 17 top-level commands grouped by operational workflow. Legacy command paths remain supported as hidden aliases without changing JSON compatibility.

Entry points

CommandQuestion / drill-down
statusFirst look: identity, role, connections and coverage
checkBounded nine-domain patrol; check --html ./patrol.html

Runtime & concurrency

CommandQuestion / drill-down
sessionsession <pid>; session waits
locklock <pid>; lock --tree; lock --table <table>
txnTransaction horizons and 2PC (--xact-warn, --prepared-warn)
progressRunning VACUUM, CREATE INDEX, CLUSTER, and CHECKPOINT phases

Workload

CommandQuestion / drill-down
sqlsql top; sql show --id=<int64>; cumulative statistics

Storage & objects

CommandQuestion / drill-down
spaceLocal filesystems, WAL, databases and tablespaces
objectobject summary; object table/index/seq [name]
vacuumCurrent-database dead tuples and autovacuum; --schema
freezeInstance database ages and current-database table ages

Persistence & writes

CommandQuestion / drill-down
walWAL position, volume and retention; wal archive
checkpointCheckpoint, bgwriter and backend write counters

Replication & server

CommandQuestion / drill-down
replLocal kernel streaming replication, sync state and lag
slotsPhysical/logical replication slots, retained WAL and xmin
clusterExternal repmgr topology; defaults to esrep
serverServer 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

Check instance version, role, replication, activity, license, connections and local disk.

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

kbdiag status                                   # local Unix socket (with disk)
kbdiag -h 10.10.10.22 -p 54321 -U system status # remote TCP connection
kbdiag status --json                            # JSON output

Key Options

OptionEffect
-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)
--jsonEmit 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 (statfs over local Unix socket), or expired license.
  • WARN (exit=1): Data filesystem >= 90%, license <= 30 days 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 false 0 activity; 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)

status  OK  (KingbaseES V009R002C016, primary, oracle, system@local,
    endpoint=/tmp/.s.KINGBASE.54321, 2026-12-02T08:27:16Z)
[INSTANCE]
  uptime       2d 23h  (since 2026-11-29 09:11:19)
  data_dir     /data/kingbase/data  (port 54321)
  connections  2 / 97  (max 100, reserved 3)
  activity     0 active, 0 waiting, 0 idle-in-txn
  license      172d remaining
[REPLICATION]
  downstreams  1
  name   address      state      sync   replay_lag
  node2  10.10.10.22  streaming  async  0 bytes
[STORAGE]
  databases    5, total 26 GB  (largest: oneta_demo 26 GB)
  data_disk    31 GB / 128 GB used (24%), 97 GB free

2.2 - check: nine-domain health patrol

Run a bounded read-only nine-domain health check and export a self-contained offline HTML report.

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

kbdiag check
kbdiag check --json
kbdiag check --html ./patrol.html
kbdiag check --html ./patrol.html --html-raw-sql

Key Options

OptionEffect
--html <file>Write a static offline HTML report atomically (0600, strict CSP, no scripts/CDNs)
--html-raw-sqlOpt in to raw SQL inside HTML (default redacts SQL columns/fields to <redacted>)
--jsonEmit 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] prioritizes FAIL then WARN drilldowns 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].
  • --html security: Zero JavaScript/external resources (script-src 'none'); HTML preserves non-SQL cells alongside <redacted> SQL placeholders and renders redacted[] privilege gaps.

Example (KES V9 Primary, excerpt, COLUMNS=80)

check  UNKNOWN  (KingbaseES V009R002C016, primary, system@local,
    endpoint=/tmp/.s.KINGBASE.54321, 2026-12-03T04:17:23Z)

[COVERAGE]
  space.disk: skipped (insufficient_privilege: statfs
    /data/kingbase/data/sys_wal: permission denied)

[SUMMARY]
  0 FAIL, 0 WARN | covered 8/9 | missing 1
  Missing domains: disk

[DOMAIN MATRIX]
  DOMAIN | STATUS | VERDICT | SUMMARY | DRILLDOWN
  connections | ok | OK | within collected thresholds | kbdiag session
  license | ok | OK | within collected thresholds | kbdiag server license
  disk | skipped | UNKNOWN
    incomplete evidence; missing: space.disk=skipped
    kbdiag space
  ...
  txn | ok | OK | within collected thresholds | kbdiag txn

[NEXT]
  kbdiag space  # disk: inspect findings or restore coverage

2.3 - session: active sessions, PID detail and wait summary

List active and blocking sessions, inspect one PID’s SQL and locks, or group current wait events.

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

kbdiag session                   # overview + active/in-txn/blocking list
kbdiag session --app order-svc   # filter table rows (excludes idle by default)
kbdiag session --all --wide      # include idle/background + client/queryid
kbdiag session 91166             # one PID's SQL, waits, and held/waiting locks
kbdiag session waits             # group active/waiting sessions by wait event

Key Options

OptionEffect
--app, --session-user, --session-dbNarrow displayed rows ([OVERVIEW] and JSON remain instance-wide)
--state, --wait-type, --min-xact-ageFilter by session state (active/idle/idle-in-txn/waiting), wait type, or txn age
--sort xact|query, --limit N, --wideControl row sorting, display cap, and client/queryid columns

Verdict & Reading Output

  • WARN (exit=1): Open idle in transaction session >= 300s (--idle-in-txn-warn), or wait >= 10s (--lock-wait-warn) on session <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 fake 0 activity.
  • session <pid> / session waits: session <pid> labels idle in transaction queries [LAST SQL] and prints blocker jump commands; session waits separates idle background/walsender loops from active waits.

Example (KES V9 Primary, excerpt, COLUMNS=80)

sessions  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-02T14:29:41Z)

[OVERVIEW]
  connected   : 3 client sessions (not counting kbdiag), 7 background
  states      : active=2, idle-in-txn=1
  wait events : Client=1, Lock=1, Timeout=1 (excl. idle Client/Activity)
  blocking    : 1 direct blocker -> 1 waiting session
                (sessions verdict judges idle-in-txn only)

[BLOCKING FOCUS]
  PID 91166  kbdiag_day2_holder idle in txn    (2s) -> blocking 1 (91169)

[ACTIVE & IN-TXN SESSIONS (3)]
  PID    STATE        XACT  QUERY  WAIT                BLOCK
  91166  idle in txn  2s    2s     Client:ClientRead   blocking 1
    > system/test (kbdiag_day2_holder) | UPDATE public.kb_sess_day2 SET val=...
  91169  active       2s    2s     Lock:transactionid  by 91166
    > system/test (kbdiag_day2_waiter) | UPDATE public.kb_sess_day2 SET val=...
  • kbdiag lock — expand the full blocking hierarchy and DDL queue predecessors
  • kbdiag txn — inspect long open transactions and prepared 2PC horizons
  • kbdiag sql — trace a queryid from session --wide into cumulative statistics

2.4 - lock: blocking chains and DDL queue predecessors

Inspect lock waits, blocker trees, 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

kbdiag lock                       # active blockers and waiters summary
kbdiag lock --tree                # blocking hierarchy + DDL predecessors
kbdiag lock 91815                 # focus display on chains touching PID 91815
kbdiag lock --table public.orders # focus display on chains for one table
kbdiag lock --tree --limit 100    # raise waiter display cap (0 for all)

Key Options

OptionEffect
--treeRender 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 (default 10s), including waits blocked by an uncommitted prepared transaction (2PC).
  • UNKNOWN (exit=3): Non-monitoring users unable to read wait times see UNKNOWN; probe collection caps blocker edge lookups at 50 waiting PIDs globally (--table and <pid> filter display after collection without expanding the 50-PID global edge budget).
  • V8R6 vs V9: Versions lacking sys_locks.waitstart estimate upper-bound waits as <=Ns (est.) from state_change.

Example (KES V9 Primary, --lock-wait-warn 1 --tree, COLUMNS=80)

locks  WARN  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321, db=test,
    2026-12-02T14:56:23Z)

[WARN] lock.waiting  session 91817 has waited 2s for AccessExclusiveLock on
  public.kb_lock_day3, blocked by 91815

[WARN] lock.waiting  session 91819 has waited 2s for AccessShareLock on
  public.kb_lock_day3, blocked by 91817

[OVERVIEW]
  waiting : 2 sessions, 2 lock requests

[BLOCKING TREE]
  +- PID 91815 [root holder]
     > public.kb_lock_day3 RowShareLock
     > user=system app=kbdiag_lock_holder
     > SQL: SELECT * FROM public.kb_lock_day3 WHERE id=1 FOR UPDATE;
  | +- PID 91817 [DDL queue predecessor]
        > queued ahead for public.kb_lock_day3 AccessExclusiveLock
        > user=system app=kbdiag_lock_ddl
        > SQL: ALTER TABLE public.kb_lock_day3 ADD COLUMN extra int;
  | | +- PID 91819

[WAITING]
  +- PID 91817 | waited 2s | by 91815
     > AccessExclusiveLock | public.kb_lock_day3
  +- PID 91819 | waited 2s | by 91817
     > AccessShareLock | public.kb_lock_day3
     > user=system app=kbdiag_lock_reader
     > SQL: SELECT * FROM public.kb_lock_day3;

[NEXT]
  - inspect blocker: kbdiag session 91815
  - inspect blocker: kbdiag session 91817
  • kbdiag session — inspect the root holder PID’s transaction state and full SQL
  • kbdiag txn — investigate 2PC prepared transactions or long open blockers
  • kbdiag progress — check whether an index build or vacuum is waiting on snapshots

2.5 - txn: open transactions, 2PC and XID horizons

Inspect open transactions, prepared 2PC transactions, and oldest xmin/xid vacuum horizon holders.

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

kbdiag txn                              # open txns, 2PCs, and oldest horizon holder
kbdiag txn --xact-warn 600 --prepared-warn 600
kbdiag txn --limit 20                   # display cap (0 for all; rules judge all)
kbdiag txn --json                       # raw 64-bit XIDs and raw 2PC GIDs

Key Options

OptionEffect
--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)
--jsonEmit 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, default 300s) or txn.prepared (2PC age >= --prepared-warn, default 900s).
  • UNKNOWN (exit=3): session.activity unavailable/masked or primary txn.prepared probe failed.
  • Horizon & standby rules: [OVERVIEW] compares backend_xid, backend_xmin, 2PC XIDs, and slot xmin together (tie-breaking in favor of actual transaction writers over snapshot retainers). On standbys, txn.prepared reports not_applicable; check 2PC on the primary. Never commit or roll back a prepared 2PC without checking its coordinator first.

Example (KES V9 Primary, --xact-warn 1 --prepared-warn 1, COLUMNS=80)

txn  WARN  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-02T15:14:41Z)

[WARN] txn.long  session 92181 has had a transaction open for 2s, now idle in
  transaction
  verify: kbdiag session 92181  # what it is running, which locks it holds,
    whether it blocks anyone

[WARN] txn.prepared  two-phase transaction kbdiag_txn_2pc_day3 prepared 1s ago
  and not finished, holding back the vacuum horizon
  verify: kbdiag txn --json  # check the 2PC coordinator in database test for
    the intended outcome before COMMIT PREPARED or ROLLBACK PREPARED

[OVERVIEW]
  oldest observed xid/xmin : 6641
  +- horizon holder : slot repmgr_slot_2 xmin

[OPEN TRANSACTIONS]
  open : 2 | hidden/untracked without visible xid : 0
  +- PID 92181 | idle in transaction | xact 2s
     > xid=6681 xmin=- | system/test
     > UPDATE public.kb_txn_day3 SET val='held' WHERE id=1;
  +- PID 92179 | idle in transaction | xact 2s
     > xid=- xmin=6681 | system/test
     > SELECT count(*) FROM public.kb_txn_day3;

[PREPARED TRANSACTIONS]
  prepared : 1
  Check the 2PC coordinator before deciding to commit or roll back.
  +- 2PC | xid 6682 | age 1s
     > gid=kbdiag_txn_2pc_day3 | system/test

[NEXT]
  - inspect horizon/transaction: kbdiag session 92181
  - inspect slot horizon: kbdiag slots
  - check 2PC coordinator before commit/rollback: kbdiag txn --json

2.6 - progress: running maintenance and index builds

Inspect running VACUUM, CREATE INDEX, CLUSTER / VACUUM FULL, and KES CHECKPOINT operations.

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. ANALYZE and base backups have no progress views in KES V8R6/V9.

Usage

kbdiag progress
kbdiag progress --json

Key Options

OptionEffect
--jsonEmit structured JSON (progress.list, progress.checkpoint)

Verdict & Reading Output

  • OK (exit=0): Both progress probes succeeded without redacted rows. When CREATE INDEX CONCURRENTLY is waiting on older transactions, a [NEXT] hint points to kbdiag 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)

progress  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321, db=test,
    2026-12-02T16:02:22Z)
[RUNNING]
  1
  pid 94505  CREATE INDEX CONCURRENTLY  db=test  rel=kb_prog_day3.big  1s
    phase=waiting for old snapshots (1 waiting txns)  progress=42 / 43 blocks
    (97%)
[NEXT]
  kbdiag lock  # inspect transactions holding back waiting index build
  • kbdiag lock — inspect blockers when CREATE INDEX CONCURRENTLY waits on older transactions
  • kbdiag vacuum — current-database dead tuples and autovacuum switches
  • kbdiag checkpoint — background writer, fsync, and checkpoint intervals

2.7 - sql: cumulative workload and queryid profile

Rank cumulative SQL workload and inspect a signed 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

kbdiag sql                                 # default: top by total time
kbdiag sql top --by=calls --limit=20       # time | mean | calls | io | temp
kbdiag sql top --sql-db=app --sql-user=app # filter stats + pass to NEXT
kbdiag sql show --id=-8006383000735440858  # signed int64 profile + active
kbdiag sql show -- -8006383000735440858    # negative positional ID after --

Subcommands & Options

OptionEffect
sql / sql topRank 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-userFilter statement rows without changing the connection’s -d / -U
--jsonEmit structured JSON (sql.top, sql.show, sql.show.active)

Verdict & Reading Output

  • OK (exit=0): Collected requested cumulative metrics and active match status cleanly; equal queryid entries across different (dbid, userid) pairs stay separate, never summed.
  • UNKNOWN (exit=3): sys_stat_statements missing/track=none with no rows, hidden queryid for non-monitoring accounts, or missing sys_stat_activity.queryid capability (e.g. KES V8R6, where sql show explicitly 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)

sql.show  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321, db=test,
    2026-12-02T15:23:05Z)

[PROFILE]
  +- queryid=555503969233108775; cumulative since statistics reset (reset time
     unknown)
  +- scope filter: sql_db=test sql_user=system
  +- dbid=14753 userid=10 queryid=555503969233108775
  |  database=test user=system
  |  calls=1 total=1.25 s mean=1.25 s max=1.25 s rows=1
  |  shared hit=866 read=0 temp written=0 blocks
  |  SQL: SELECT pg_sleep($1) FROM public.kb_sql_day3 WHERE id = $2

[ACTIVE]
  +- current active sessions; separate from cumulative counters
  +- dbid=14753 userid=10 queryid=555503969233108775 pid=92579 age=2s
     wait=Timeout/SysSleep

[NEXT]
  +- kbdiag session 92579
  • kbdiag session — inspect live PID details (sql activity, waits, locks)
  • kbdiag lock — check whether top execution time comes from lock contention
  • kbdiag space — inspect temp file / disk headroom when temp or io leads

2.8 - space: filesystems, WAL size, databases and tablespaces

Check data/WAL/tablespace filesystem usage, WAL retention settings, database sizes, and tablespace capacities.

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

kbdiag space
kbdiag space --json

Key Options

OptionEffect
--jsonEmit JSON probes (space.disk, space.wal, inst.databases, space.tablespaces)

Verdict & Reading Output

  • FAIL (exit=2): space.disk_full when free space on a data_directory or wal filesystem 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 on data_directory and wal filesystems.
  • UNKNOWN (exit=3): Remote connection (space.disk: not_applicable), missing sys_wal or tablespace statfs permission (partial: skipped), denied sys_ls_waldir() (kbdiag_ro), or missing segment size. Surviving mounts remain visible under [DISK] even on partial skips.

Example (KES V9 Primary, COLUMNS=80)

space  UNKNOWN  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-03T03:58:01Z)

[COVERAGE]
  space.disk: skipped (insufficient_privilege: statfs
    /data/kingbase/data/sys_wal: permission denied)
[DISK]
  1 filesystem
  partial: skipped (insufficient_privilege: statfs /data/kingbase/data/sys_wal:
    permission denied)
  holds           used   size    free   use
  data_directory  31 GB  128 GB  97 GB  24%
[WAL]
  57 files, 896 MB
  max_wal_size  1024 MB
  wal_keep      0 bytes  (0 x 16 MB)
[DATABASES]
  5, total 26 GB
  oneta_demo  26 GB
  test        17 MB
  • kbdiag wal — inspect current LSN position, replication slots, and archive_ready backlog
  • kbdiag slots — check inactive replication slots retaining WAL
  • kbdiag object — find the largest tables and indexes inside a database

2.9 - object: database objects, tables, indexes and sequences

Inventory database objects by schema and inspect 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

kbdiag object                                     # schema & type est. summary
kbdiag object summary --schema app --exact        # bounded exact sizing
kbdiag object table --schema app --by=dead        # size | rows | dead | seq_scan
kbdiag object table app.orders                    # 6-clue single-table inspect
kbdiag object index --schema app --unused         # zero-scan index review list
kbdiag object seq --schema app                    # sequences ordered by range

Subcommands & Options

Command / OptionEffect
object / object summaryInventory 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, --exactFilter 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) with 0 remaining 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): --exact exceeded --exact-budget (marked in [COVERAGE] instead of silent truncation), --unused run on a standby (node-local scan counters), object seq missing privilege on restricted sequences, or incomplete single-table size/index probes.

Example (KES V9 Primary, excerpt, COLUMNS=80)

obj.tables  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    db=test, 2026-12-02T15:34:53Z)

[SCOPE]
  scope=current database, schemas=kb_obj_day3

[TABLES]  4 rows  by=dead
  +- kb_obj_day3.orders [none]
     > size: self=64 kB subtree=64 kB exact=-
     > tuples: est=500 live=500 dead=250 seq_scans=3
  +- kb_obj_day3.events [parent]
     > size: self=0 bytes subtree=16 kB exact=-
     > tuples: est=150 live=0 dead=0 seq_scans=0
  +- kb_obj_day3.events_p1 [leaf]
     > size: self=8192 bytes subtree=8192 bytes exact=-
     > tuples: est=99 live=99 dead=0 seq_scans=0

[NEXT]
  kbdiag object table '"kb_obj_day3"."orders"' # drill one table
  kbdiag object index --schema 'kb_obj_day3' # inspect indexes
  • kbdiag vacuum — current-database dead tuples and autovacuum blockers
  • kbdiag freeze — oldest XID/MXID relation ages and wraparound headroom
  • kbdiag space — total database, WAL, and filesystem capacity

2.10 - vacuum: dead tuples and autovacuum

Check dead tuples, autovacuum thresholds, running vacuums, and global switches in the current database.

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

kbdiag vacuum
kbdiag vacuum --schema app --limit 20
kbdiag vacuum --all-schemas
kbdiag vacuum --json

Key Options

OptionEffect
--schema nameLimit tables to specific schema(s) (repeatable; conflicts with --all-schemas)
--all-schemasInclude system schemas such as sysmac, sys_hm, kdb_schedule
--limit NShow at most N tables (default 20, 0 for unlimited; judges all tables in scope)
--jsonEmit structured JSON (vacuum.tables, vacuum.progress, vacuum.settings)

Verdict & Reading Output

  • WARN (exit=1): vacuum.disabled (autovacuum or track_counts is off) or vacuum.table_disabled (table exceeded threshold + scale_factor * reltuples with autovacuum_enabled=off).
  • UNKNOWN (exit=3): vacuum.settings / vacuum.progress failed/skipped (including standby settings errors) or track_counts=off skipped table stats.
  • OK (exit=0): switches are on and no disabled table exceeds threshold; due=yes with autovacuum=on is normal queue behavior, not a fault. On standbys, table stats and running vacuums are not_applicable.

Example (KES V9 Primary, COLUMNS=80)

vacuum  WARN  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321, db=test,
    2026-12-02T15:48:39Z)
[FINDINGS]
  WARN vacuum.table_disabled: table kb_vac_day3.orders has 250 dead tuples,
    past its autovacuum threshold 130, but autovacuum is off for it
    (autovacuum_enabled=off): nothing will clean it
[SCOPE]
  schemas=non-system (current database; pass --schema or --all-schemas)
[SETTINGS]
  autovacuum    on  (3 workers, naptime 1m 0s)
  track_counts  on
  threshold     50 + 0.2 x reltuples
  No running vacuum operations observed
[TABLES IN TEST]
  2, most dead tuples first
  kb_vac_day3.orders  due=yes  autovacuum=off
    dead=250  live=400  threshold=130  last_auto=never  last_vac=never
  public.kbdiag_s1_lock_target  due=-  autovacuum=on
    dead=1  live=1  threshold=50  last_auto=never  last_vac=never
[NEXT]
  fix: VACUUM kb_vac_day3.orders  # connected to database test; requires table
    owner or superuser; turn autovacuum back on with ALTER TABLE ... RESET
    (autovacuum_enabled) unless it was turned off on purpose
  verify: kbdiag txn  # if dead tuples remain after VACUUM: the oldest
    transaction holding back the horizon
  verify: kbdiag slots  # or a replication slot's xmin
  • kbdiag freeze — XID / multixact age and wraparound headroom
  • kbdiag txn — oldest transaction holding back dead-tuple cleanup
  • kbdiag slots — replication slots retaining old xmin

2.11 - freeze: XID and multixact wraparound age

Compare instance-wide database XID/MXID ages against freeze limits and list the oldest relations in the current database.

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

kbdiag freeze
kbdiag freeze --schema app --limit 20
kbdiag -d otherdb freeze
kbdiag freeze --json

Key Options

OptionEffect
--schema nameFilter table listing to specific schema(s); database-level freeze stays instance-wide
--all-schemasShow all schemas in the current database (same as default table coverage; conflicts with --schema)
--limit NShow at most N oldest relations (default 20, 0 for unlimited; DB judgment covers all DBs)
--jsonEmit 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 exceeded autovacuum_freeze_max_age or autovacuum_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, or freeze.tables).
  • 64-bit XID note: On KES V9 64-bit XID servers, kbdiag detects xid width cleanly and skips the PG12 32-bit stop limit (xid stop limit: 64-bit xid).

Example (KES V9 Primary, excerpt, COLUMNS=80)

freeze  OK  (KingbaseES V009R002C016, primary, system@local,
    endpoint=/tmp/.s.KINGBASE.54321, db=test, 2026-12-02T15:56:43Z)
[SCOPE]
  schemas=all (current database; db-level freeze is instance-wide)
[LIMITS]
  autovacuum_freeze_max_age            10000000000
  autovacuum_multixact_freeze_max_age  20000000000
  xid stop limit                       64-bit xid (32-bit PG12 stop limit not
    applicable)
[DATABASES]
  7
  name        xid age  of freeze max  mxid age  xids left
  esrep       5578     0%             0         -
  kingbase    5578     0%             0         -
  oneta_demo  5578     0%             0         -
  security    5578     0%             0         -
  template0   5578     0%             0         -
  template1   5578     0%             0         -
  test        5578     0%             0         -
[TABLES IN TEST]
  176, oldest first
  information_schema.sql_features  table
    xid_age=5578  mxid_age=0  heap_est=56 kB
  ...
  • kbdiag vacuum — dead tuples and autovacuum blockers in the current database
  • kbdiag txn — oldest running transaction or 2PC holding back freeze horizon
  • kbdiag slots — inactive replication slots retaining xmin

2.12 - wal: WAL volume, retention, and archiving

Check WAL LSN position, sys_wal directory size, retention blockers (slots, wal_keep_segments), and archiver health.

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

kbdiag wal
kbdiag wal archive
kbdiag wal --json
kbdiag wal archive --json

Subcommands & Options

Command / OptionEffect
kbdiag walShow WAL/replay LSN, sys_wal size, max_wal_size, wal_keep_segments, slots, and .ready count
kbdiag wal archiveShow archive_mode, archive_command, archiver counts/timestamps, and .ready/.done queue
--jsonEmit 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 to kbdiag slots or kbdiag wal archive.
    • UNKNOWN (exit=3): Non-monitoring roles (kbdiag_ro) skip sys_ls_waldir() and sys_ls_archive_statusdir().
  • wal archive:
    • WARN (exit=1): archive.failing when archive_mode is active (primary, or standby with always), archive_command is non-empty, and last_failed_time is newer than last_archived_time (or never succeeded).
    • OK (exit=0): Archiving healthy, intentionally disabled (off or standby on).
    • UNKNOWN (exit=3): archive.status or archive.ready failed/skipped.

Example (KES V9 Primary, COLUMNS=80)

wal  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-02T16:08:12Z)
[POSITION]
  lsn   10/400FB580
  file  000000010000001000000040
[SYS_WAL]
  58 files, 912 MB
[WHAT KEEPS WAL HERE]
  max_wal_size       1024 MB
  wal_keep_segments  0 bytes  (0 x 16 MB)
  archiving          0 .ready files waiting
  slots (1):
    repmgr_slot_2: 12 MB (inactive)
[NEXT]
  kbdiag slots  # inspect inactive replication slot retaining WAL
archive  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-02T16:08:12Z)
[SETTINGS]
  archive_mode     always
  archive_command  exit 0
  archive_timeout  0 (off)
[ARCHIVER  (COUNTING SINCE 2026-11-29T09:11:20Z)]
  archived  6  last 00000001000000100000003F  8m 35s ago
  failed    0
[WAITING]
  0 .ready, 2 .done
  • kbdiag slots — inspect inactive replication slots and xmin / WAL retention
  • kbdiag checkpoint — checkpoint vs bgwriter vs backend buffer writes
  • kbdiag space — filesystem free space for data_directory, sys_wal, and tablespaces

2.13 - checkpoint: checkpoints, bgwriter, and buffer writes

Inspect the last checkpoint/restartpoint, cumulative bgwriter/backend buffer writes, average rates, and checkpoint GUCs.

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_timed counts restartpoint attempts (one try every 15s when no new checkpoint record arrives) and does not compare directly with primary counts.

Usage

kbdiag checkpoint
kbdiag checkpoint --json

Key Options

OptionEffect
--jsonEmit 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 to kbdiag wal when checkpoints_req > checkpoints_timed or buffers_backend_fsync > 0, and notes log_checkpoints = on when disabled.

Example (KES V9 Primary, COLUMNS=80)

checkpoint  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-02T16:12:53Z)
[LAST CHECKPOINT]
  time  2026-12-02T16:04:29Z  (8m 25s ago)
  redo  10/400FB450  (000000010000001000000040)
[STATISTICS]
  stats_reset=2026-11-29T09:11:20Z (3d 7h ago)
  checkpoints           673: 673 timed, 0 requested (0%; requested covers WAL
    volume, CHECKPOINT, base backups, promotion)
  write, sync time      3m 57s, 704 ms
  buffers written       12929: checkpointer 2226 (17%), bgwriter 0 (0%),
    backends and others 10703 (83%)
  buffers allocated     9927
  backend fsyncs        0
  bgwriter stopped      0 times at bgwriter_lru_maxpages
  window average rates  0.002 checkpoints/s; 0.002 timed/s; 0.000 requested/s
  buffer rates          0.05 blocks/s written (checkpoint 0.01, bgwriter 0.00,
    backend 0.04); 0.03 blocks/s allocated
[SETTINGS]
  checkpoint_timeout            5m 0s
  max_wal_size                  1024 MB
  checkpoint_completion_target  0.5
  checkpoint_warning            30s
  log_checkpoints               off
[NEXT]
  SHOW log_checkpoints  # consider enabling log_checkpoints = on for timing and
    write/sync logs
  • kbdiag wal — inspect WAL footprint, max_wal_size, slots, and archiver retention
  • kbdiag wal (wal archive) — check archiver success/failure and .ready queue
  • kbdiag progress — inspect an in-progress CHECKPOINT

2.14 - repl: streaming replication and sync state

Check synchronous standby settings, downstream replication lag, and standby upstream/replay progress.

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 transaction age even with zero byte lag.

Usage

kbdiag repl
kbdiag repl --json

Key Options

OptionEffect
--jsonEmit structured JSON (repl.sync, inst.upstream, repl.replay, repl.downstreams)

Verdict & Reading Output

  • WARN (exit=1):
    • inst.upstream: standby has no WAL receiver or last_msg_age_s exceeds wal_receiver_timeout.
    • repl.replay_paused: sys_is_wal_replay_paused() is true on standby.
    • repl.sync_short: active sync/quorum candidates are fewer than synchronous_standby_names requires under on/remote_write/remote_apply.
  • UNKNOWN (exit=3): probe error/skip, unparsable synchronous_standby_names, or masked replication state ([REDACTED]).

Example (KES V9 Standby, COLUMNS=80)

repl  WARN  (standby, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-02T16:18:25Z)
[FINDINGS]
  WARN inst.upstream: the standby has no WAL receiver and is not receiving WAL
    from the primary: if the primary fails now, no standby can take over
[UPSTREAM]
  status    (no walreceiver process)
[REPLAY]
  received                   10/3F4D2A00
  replayed                   10/3F4D2A00  (caught up with what was received)
  last replayed transaction  2d 9h ago
  paused                     no
[DOWNSTREAMS]
  0
  No downstream replicas observed
[NEXT]
  verify: kbdiag slots  # run on the primary: is this standby's slot inactive?
  • kbdiag cluster — repmgr node topology, primary visibility, and failover events
  • kbdiag slots — inactive replication slots, WAL retention, and stale xmin
  • kbdiag wal — WAL position, sys_wal size, and archive backlog

2.15 - slots: replication slots and retention

List replication slots, active PIDs, retained WAL bytes, xmin/catalog_xmin blockers, and inactive slot warnings.

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

kbdiag slots
kbdiag slots --json

Key Options

OptionEffect
--jsonEmit structured JSON (slot.list including xmin, catalog_xmin, restart_lsn, retained_wal_bytes)

Verdict & Reading Output

  • WARN (exit=1): slot.inactive when a replication slot is active = false. Output highlights retained WAL plus any xmin (vacuum horizon) or catalog_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. When slot.list succeeds, a non-NULL restart_lsn with a missing LSN diff still displays retained WAL unknown (and active = false triggers WARN).

Example (KES V9 Primary, COLUMNS=80)

slots  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321,
    2026-12-03T03:37:18Z)
[SLOTS]
  1
  repmgr_slot_2  physical  active=yes (pid 97839)  retained=0 bytes
    xmin=6718  xmin_age=0  restart_lsn=10/40110000
  • kbdiag wal — see WAL directory size alongside slot and archive retention
  • kbdiag repl — check streaming replicas and standby receiver/replay status
  • kbdiag vacuum / kbdiag txn — investigate dead tuples or long-running transactions holding xmin

2.16 - cluster: repmgr cluster topology and sync mode

Inspect repmgr nodes, local role match, synchronous config, and recent cluster events (defaults to database esrep).

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

kbdiag cluster
kbdiag cluster --events-limit 0
kbdiag cluster --json

Key Options

OptionEffect
-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)
--jsonEmit 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’s sys_stat_replication), or cluster.sync_degraded (repmgr.conf requests synchronous mode while synchronous_standby_names is empty).
  • UNKNOWN (exit=3): Unresolved local node, insufficient privilege (kbdiag_ro), unreadable local repmgr.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, or repmgr metadata schema is absent (not_applicable).

Example (KES V9 Primary, excerpt, COLUMNS=80)

cluster  OK  (primary, system@local, endpoint=/tmp/.s.KINGBASE.54321, db=esrep,
    2026-12-03T03:48:08Z)
[IDENTIFICATION]
  local identification: recovery role=primary matched the single active primary
    in repmgr.nodes (fallback; no repmgrd ID/primary_slot_name match)
[NODES]
  2  (repmgr metadata in database esrep)
  id  name   type     upstream  active  priority  location  slot
  1   node1  primary  -         yes     100       default   repmgr_slot_1
  2   node2  standby  node1     yes     100       default   repmgr_slot_2
  this node is node1: repmgr says primary, the database is a primary
  attached here: node2
[SYNCHRONOUS]
  repmgr.conf                async  (/data/kingbase/app/Server/bin/../etc/repmgr
    .conf)
  synchronous_standby_names  (empty: asynchronous)
[EVENTS]
  showing 3 of 20 collected (latest first; --events-limit 0 shows all collected)
  2026-11-28T00:04:35Z  node1  child_node_reconnect  ok=yes
    standby node "node2" (ID: 2) has reconnected after 1384 seconds
  ...
  • kbdiag repl — check kernel streaming replication links and replay lag
  • kbdiag slots — inspect physical/logical slots backing cluster standbys
  • kbdiag wal — check WAL retention and archive status

2.17 - server: instance summary, parameters and license

Inspect full KES version/mode, changed and pending_restart parameters, and license expiry, MAC, and max connections.

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

kbdiag server
kbdiag server params
kbdiag server license
kbdiag server --json

Subcommands & Options

Command / OptionEffect
serverInstance identity, connections summary, license summary, and non-default parameter preview
server paramsFull non-default and pending_restart parameter list with source files and line numbers
server licenseLicense expiry countdown, path, bound MAC, and license connection limit
--jsonEmit 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) or inst.connections (ordinary-user connection headroom exhausted on kbdiag server).
  • WARN (exit=1): license.expiring (within 30 days) or params.pending_restart (changed parameter waiting for restart; suggested rollback SQL is printed safely for manual review).
  • UNKNOWN (exit=3): Probe failure or missing sys_read_all_settings / superuser privilege (even when visible file-backed rows are empty).
  • Privacy note: license.dat path and mac print verbatim (not redacted); scrub before external sharing.

Examples (KES V9 Primary, excerpt, COLUMNS=80)

inst.summary  OK  (KingbaseES V009R002C016, primary, system@local,
    endpoint=/tmp/.s.KINGBASE.54321, 2026-12-03T09:40:35Z)
[INST.IDENTITY]
  ok, 1 rows
  full_version=KingbaseES V009R002C016 | server_version_num=120001 |
    database_mode=oracle | role=primary
[INST.INFO]
  ok, 1 rows
  version=V009R002C016 | connections=2 | max_connections=100 |
    usable_connections=97
...
params  OK  (KingbaseES V009R002C016, primary, system@local,
    endpoint=/tmp/.s.KINGBASE.54321, 2026-12-03T04:05:00Z)
[PENDING RESTART]
  0
[CHANGED]
  45 parameters not at their default (sources other than default, override and
    this connection)
  ...
  archive_command = exit 0
    source=configuration file  file=kingbase.conf:236
  archive_mode = always
    source=configuration file  file=kingbase.conf:234
[LICENSE]
  left             171 days
  file             /data/kingbase/app/KESRealPro/V009R002C016/Server/bin/../../l
    icense.dat
  product          KingbaseES
  version          V009
  validity         180
  mac              00:00:00:00:00:00
  max connections  0
  KES checks the license only when the instance starts
  note: file path and MAC shown verbatim (not redacted); scrub before sharing
  • kbdiag check — run nine-domain patrol including connections and license
  • kbdiag session — inspect active backends against max_connections
  • kbdiag status — check instance uptime, primary/standby role, and hosts

3 - Capabilities

Choose among 17 canonical commands by question and scope.

Start with the question and scope. check is a bounded nine-domain patrol, not a full table-by-table audit.

Entry points

CommandQuestion / drill-down
statusFirst look: identity, role, connections and coverage
checkBounded nine-domain patrol; check --html ./patrol.html

Runtime & concurrency

CommandQuestion / drill-down
sessionsession <pid>; session waits
locklock <pid>; lock --tree; lock --table <table>
txnTransaction horizons and 2PC (--xact-warn, --prepared-warn)
progressRunning VACUUM, CREATE INDEX, CLUSTER, and CHECKPOINT phases

Workload

CommandQuestion / drill-down
sqlsql top; sql show --id=<int64>; cumulative statistics

Storage & objects

CommandQuestion / drill-down
spaceLocal filesystems, WAL volume, databases and tablespaces
objectobject summary; object table/index/seq [name]
vacuumCurrent-database dead tuples and autovacuum; --schema
freezeInstance database ages and current-database table ages

Persistence & writes

CommandQuestion / drill-down
walWAL position, volume and retention; wal archive
checkpointCheckpoint, bgwriter and backend write counters

Replication & server

CommandQuestion / drill-down
replLocal kernel streaming replication, sync state and lag
slotsPhysical/logical replication slots, retained WAL and xmin
clusterExternal repmgr topology; defaults to database esrep
serverServer 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

Build, connect, patrol and follow a canonical command.

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.

git clone https://github.com/Kevin-wenyu/kbdiag.git
cd kbdiag
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -ldflags "-X main.version=2.0.0" -o kbdiag ./cmd/kbdiag
scp kbdiag kingbase@db-host:~/kbdiag

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

~/kbdiag status
~/kbdiag check --html ./patrol.html
echo $?
~/kbdiag session
~/kbdiag lock --tree
~/kbdiag sql top

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

CodeMeaning
0OK within collected scope
1WARN: investigate the finding
2FAIL: urgent finding in visible evidence
3UNKNOWN: required evidence missing or masked
64Invalid command or flags
69Could 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.

Read results · All 17 command cards

4.1 - Read the evidence

Terminal layout, verdicts, coverage markers, scope boundaries, and JSON structure.

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].

<command>  <VERDICT>  (<version>, <role>, <user>@<host>, endpoint=<target>, <collected_at>)
[COVERAGE]
  <probe_id>: skipped|error (<reason>)
[REDACTED]
  <probe_id>.<field>: <reason>
[FINDINGS]            # session/lock/txn print [WARN]/[FAIL] directly
  <LEVEL> <finding_id>: <symptom>
    verify: <next command>
[...command sections...]
[NEXT]
  <next command or operator action>

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.

  • point is an instantaneous snapshot; counter accumulates since stats reset; delta compares samples; estimate uses catalog statistics (relpages) rather than locking tables.
  • A current-database check (object, vacuum, freeze table list, lock table names) says nothing about tables in other databases.
  • redacted / [REDACTED] records privilege masking (sys_monitor, sys_read_all_settings, etc.); skipped and error mark uncollected probes; not_applicable marks role/environment inapplicability rather than failure.
  • ? never means zero, and - never proves a healthy value; a higher-severity FAIL/WARN never 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.

Return to quick start

5 - Troubleshooting scenarios

Follow lock chains and distinguish active SQL from cumulative workload.

Start with kbdiag status and kbdiag check. Verify target identity, coverage and node role, then follow one diagnostic chain.

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 blockers, queued DDL predecessors and the transaction owner.

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.

kbdiag lock --tree
kbdiag lock <pid>
kbdiag lock --table public.orders
kbdiag session <pid>
kbdiag txn

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 instantaneous waits, cumulative counters and active query identity.

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.

kbdiag session waits
kbdiag session
kbdiag sql top --by=time
kbdiag sql top --by=calls --sql-db=test --sql-user=system
kbdiag sql show --id=<signed-int64> --sql-db=test --sql-user=system
kbdiag session <pid>

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.

SQL workload reference · Session reference