postgresai 0.18.0-rc.2 → 0.18.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -957,6 +957,10 @@ membership, `SELECT` on the relevant catalogs/views, and the appropriate
957
957
  [prepare-db](#prepare-db-create-monitoring-user-in-postgres) for details and
958
958
  provider-specific behavior.
959
959
 
960
+ A005 (Extensions) also opens one connection to each other database of the server
961
+ with the same credentials, so the role needs CONNECT there (the default for
962
+ PUBLIC); a database it cannot read is listed in the report with the reason.
963
+
960
964
  ### What runs locally vs. server-side
961
965
 
962
966
  | Output | Where it is produced | Available offline (`--no-upload`) |
@@ -13538,7 +13538,7 @@ var {
13538
13538
  // package.json
13539
13539
  var package_default = {
13540
13540
  name: "postgresai",
13541
- version: "0.18.0-rc.2",
13541
+ version: "0.18.0-rc.4",
13542
13542
  description: "postgres_ai CLI",
13543
13543
  license: "Apache-2.0",
13544
13544
  private: false,
@@ -16898,7 +16898,7 @@ var Result = import_lib.default.Result;
16898
16898
  var TypeOverrides = import_lib.default.TypeOverrides;
16899
16899
  var defaults = import_lib.default.defaults;
16900
16900
  // package.json
16901
- var version = "0.18.0-rc.2";
16901
+ var version = "0.18.0-rc.4";
16902
16902
  var package_default2 = {
16903
16903
  name: "postgresai",
16904
16904
  version,
@@ -17619,6 +17619,34 @@ async function fetchIssueComments(params) {
17619
17619
  throw new Error(formatHttpError("Failed to fetch issue comments", response.status, data));
17620
17620
  }
17621
17621
  }
17622
+ async function recordIssueView(params) {
17623
+ const { apiKey, apiBaseUrl, orgScope, issueId, via, debug, timeoutMs = 3000 } = params;
17624
+ const url = `${normalizeBaseUrl(apiBaseUrl)}/rpc/issue_view_record`;
17625
+ const controller = new AbortController;
17626
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
17627
+ try {
17628
+ const response = await fetch(url, {
17629
+ method: "POST",
17630
+ headers: { ...issueRequestHeaders(apiKey, orgScope), "Content-Type": "application/json" },
17631
+ body: JSON.stringify({ issue_id: issueId, via }),
17632
+ signal: controller.signal
17633
+ });
17634
+ if (debug) {
17635
+ console.error(`Debug: POST ${url} -> ${response.status}`);
17636
+ }
17637
+ if (!response.ok)
17638
+ return null;
17639
+ const data = await response.json();
17640
+ return Array.isArray(data) ? data : null;
17641
+ } catch (err) {
17642
+ if (debug) {
17643
+ console.error(`Debug: recording the issue view failed: ${err instanceof Error ? err.message : String(err)}`);
17644
+ }
17645
+ return null;
17646
+ } finally {
17647
+ clearTimeout(timer);
17648
+ }
17649
+ }
17622
17650
  async function fetchIssue(params) {
17623
17651
  const { apiKey, apiBaseUrl, orgScope, issueId, debug } = params;
17624
17652
  if (!apiKey) {
@@ -31840,8 +31868,11 @@ async function handleToolCall(req, rootOpts, extra) {
31840
31868
  if (!issue) {
31841
31869
  return { content: [{ type: "text", text: "Issue not found" }], isError: true };
31842
31870
  }
31843
- const comments = await fetchIssueComments({ apiKey, apiBaseUrl, issueId, orgScope: scope.orgScope, debug });
31844
- const combined = { issue: presentIssue(issue), comments };
31871
+ const [comments, seenBy] = await Promise.all([
31872
+ fetchIssueComments({ apiKey, apiBaseUrl, issueId, orgScope: scope.orgScope, debug }),
31873
+ recordIssueView({ apiKey, apiBaseUrl, issueId, orgScope: scope.orgScope, via: "agent", debug })
31874
+ ]);
31875
+ const combined = { issue: { ...presentIssue(issue), ...seenBy ? { seen_by: seenBy } : {} }, comments };
31845
31876
  return { content: [{ type: "text", text: JSON.stringify(combined, null, 2) }] };
31846
31877
  }
31847
31878
  if (toolName === "post_issue_comment") {
@@ -32156,7 +32187,7 @@ async function startMcpServer(rootOpts, extra) {
32156
32187
  },
32157
32188
  {
32158
32189
  name: "view_issue",
32159
- description: "View a specific issue with its comments",
32190
+ description: "View a specific issue with its comments and who has seen it (seen_by). Viewing records the token owner in the issue's seen-by list as an AI agent.",
32160
32191
  inputSchema: {
32161
32192
  type: "object",
32162
32193
  properties: {
@@ -32577,6 +32608,48 @@ async function fetchIssueComments2(params) {
32577
32608
  throw new Error(formatHttpError("Failed to fetch issue comments", response.status, data));
32578
32609
  }
32579
32610
  }
32611
+ var AGENT_ENV_MARKERS = [
32612
+ "AI_AGENT",
32613
+ "CLAUDECODE",
32614
+ "CURSOR_AGENT",
32615
+ "GEMINI_CLI",
32616
+ "CODEX_SANDBOX",
32617
+ "CODEX_THREAD_ID"
32618
+ ];
32619
+ function cliViewVia(env = process.env) {
32620
+ const explicit = env.PGAI_VIA?.trim().toLowerCase();
32621
+ if (explicit === "agent" || explicit === "cli")
32622
+ return explicit;
32623
+ return AGENT_ENV_MARKERS.some((name) => (env[name] ?? "") !== "") ? "agent" : "cli";
32624
+ }
32625
+ async function recordIssueView2(params) {
32626
+ const { apiKey, apiBaseUrl, orgScope, issueId, via, debug, timeoutMs = 3000 } = params;
32627
+ const url = `${normalizeBaseUrl(apiBaseUrl)}/rpc/issue_view_record`;
32628
+ const controller = new AbortController;
32629
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
32630
+ try {
32631
+ const response = await fetch(url, {
32632
+ method: "POST",
32633
+ headers: { ...issueRequestHeaders2(apiKey, orgScope), "Content-Type": "application/json" },
32634
+ body: JSON.stringify({ issue_id: issueId, via }),
32635
+ signal: controller.signal
32636
+ });
32637
+ if (debug) {
32638
+ console.error(`Debug: POST ${url} -> ${response.status}`);
32639
+ }
32640
+ if (!response.ok)
32641
+ return null;
32642
+ const data = await response.json();
32643
+ return Array.isArray(data) ? data : null;
32644
+ } catch (err) {
32645
+ if (debug) {
32646
+ console.error(`Debug: recording the issue view failed: ${err instanceof Error ? err.message : String(err)}`);
32647
+ }
32648
+ return null;
32649
+ } finally {
32650
+ clearTimeout(timer);
32651
+ }
32652
+ }
32580
32653
  async function fetchIssue2(params) {
32581
32654
  const { apiKey, apiBaseUrl, orgScope, issueId, debug } = params;
32582
32655
  if (!apiKey) {
@@ -43027,6 +43100,8 @@ function generateCheckSummary(checkId, report) {
43027
43100
  return summarizeA003(nodeData);
43028
43101
  case "A004":
43029
43102
  return summarizeA004(nodeData);
43103
+ case "A005":
43104
+ return summarizeA005(nodeData);
43030
43105
  case "A007":
43031
43106
  return summarizeA007(nodeData);
43032
43107
  case "D001":
@@ -43064,6 +43139,22 @@ function summarizeA003(nodeData) {
43064
43139
  message: `${settingsCount} setting${settingsCount > 1 ? "s" : ""} collected`
43065
43140
  };
43066
43141
  }
43142
+ function summarizeA005(nodeData) {
43143
+ const databases = Object.values(nodeData?.data?.databases || {});
43144
+ if (databases.length === 0) {
43145
+ return { status: "info", message: "No databases listed" };
43146
+ }
43147
+ const extensions = new Set;
43148
+ for (const db of databases)
43149
+ for (const name of Object.keys(db.extensions || {}))
43150
+ extensions.add(name);
43151
+ const unread = databases.filter((db) => !db.read).length;
43152
+ const message = `${extensions.size} extension${extensions.size === 1 ? "" : "s"} in ` + `${databases.length - unread} of ${databases.length} database${databases.length === 1 ? "" : "s"}`;
43153
+ if (unread > 0) {
43154
+ return { status: "warning", message: `${message}; ${unread} not read` };
43155
+ }
43156
+ return { status: "info", message };
43157
+ }
43067
43158
  function summarizeA004(nodeData) {
43068
43159
  const data = nodeData?.data;
43069
43160
  if (!data) {
@@ -44292,6 +44383,220 @@ async function generateA004(client, nodeName = "node-01") {
44292
44383
  };
44293
44384
  return report;
44294
44385
  }
44386
+ var A005_MAX_DATABASES = 100;
44387
+ var A005_TIME_BUDGET_MS = 60000;
44388
+ var A005_ERROR_CHARS = 200;
44389
+ var A005_DATABASE_SQL = `
44390
+ select
44391
+ coalesce((select json_object_agg(e.extname, e.extversion order by e.extname)
44392
+ from pg_extension as e), '{}'::json) as extensions,
44393
+ coalesce((select json_agg(json_build_object('am', t.am, 'extension', t.extension, 'indexes', t.indexes)
44394
+ order by t.am, t.extension nulls first)
44395
+ from (
44396
+ select am.amname as am, x.extname as extension, count(*)::int as indexes
44397
+ from pg_index as i
44398
+ join pg_class as c on c.oid = i.indexrelid
44399
+ join pg_namespace as n on n.oid = c.relnamespace
44400
+ join pg_am as am on am.oid = c.relam
44401
+ left join lateral (
44402
+ select distinct e.extname
44403
+ from unnest(i.indclass::oid[]) as opc(oid)
44404
+ join pg_depend as d on d.classid = 'pg_opclass'::regclass and d.objid = opc.oid
44405
+ and d.refclassid = 'pg_extension'::regclass and d.deptype = 'e'
44406
+ join pg_extension as e on e.oid = d.refobjid
44407
+ ) as x on true
44408
+ where n.nspname not in ('pg_catalog', 'information_schema', 'pg_toast')
44409
+ and n.nspname !~ '^pg_(toast_)?temp_'
44410
+ group by am.amname, x.extname
44411
+ ) as t), '[]'::json) as index_access_methods,
44412
+ (select count(*) from pg_policy)::int as row_security_policies,
44413
+ (select count(*) from pg_statistic_ext)::int as extended_statistics
44414
+ `;
44415
+ var A005_DATABASES_SQL = `
44416
+ select d.datname, d.datname = current_database() as is_current,
44417
+ has_database_privilege(d.oid, 'CONNECT') as can_connect,
44418
+ (select count(*) from pg_roles as r
44419
+ where not r.rolsuper and has_database_privilege(r.oid, d.oid, 'CREATE'))::int as roles_with_create
44420
+ from pg_database as d
44421
+ where d.datallowconn
44422
+ order by d.datname
44423
+ `;
44424
+ var A005_SLOTS_SQL = `
44425
+ select database, plugin, count(*)::int as slots, (count(*) filter (where active))::int as active
44426
+ from pg_replication_slots
44427
+ where slot_type = 'logical'
44428
+ group by database, plugin
44429
+ order by database, plugin
44430
+ `;
44431
+ var A005_REPLICATION_ROLES_SQL = `
44432
+ select count(*)::int as replication
44433
+ from pg_roles as r
44434
+ where not r.rolsuper
44435
+ and (r.rolreplication or exists (
44436
+ select 1 from pg_roles as p
44437
+ where p.rolname = 'rds_replication' and p.oid <> r.oid and pg_has_role(r.oid, p.oid, 'member')))
44438
+ `;
44439
+ var A005_PASSWORD_HASHES_SQL = `
44440
+ select (count(*) filter (where rolpassword like 'md5%'))::int as md5_passwords,
44441
+ (count(*) filter (where rolpassword like 'SCRAM-SHA-256$%'
44442
+ and split_part(split_part(rolpassword, '$', 2), ':', 1) <> '4096'))::int
44443
+ as nondefault_scram_iterations
44444
+ from pg_authid
44445
+ `;
44446
+ var A005_HBA_SQL = `
44447
+ select (count(*) filter (where auth_method = 'cert'))::int as cert,
44448
+ (count(*) filter (where auth_method = 'trust'))::int as trust,
44449
+ (count(*) filter (where type = 'hostgssenc'))::int as hostgssenc,
44450
+ (count(*) filter (where error is not null))::int as errors
44451
+ from pg_hba_file_rules
44452
+ `;
44453
+ function a005Error(err) {
44454
+ const message = err instanceof Error ? err.message : String(err);
44455
+ return message.replace(/\s+/g, " ").trim().slice(0, A005_ERROR_CHARS) || "unknown error";
44456
+ }
44457
+ var a005OpenDatabase = async (client, database) => {
44458
+ const params = client.connectionParameters;
44459
+ if (!params || typeof client.constructor !== "function") {
44460
+ throw new Error("cannot open another connection from this client");
44461
+ }
44462
+ const Ctor = client.constructor;
44463
+ const other = new Ctor({
44464
+ host: params.host,
44465
+ port: params.port,
44466
+ user: params.user,
44467
+ password: client.password ?? params.password,
44468
+ database,
44469
+ ssl: client.ssl,
44470
+ options: params.options,
44471
+ application_name: params.application_name,
44472
+ enableChannelBinding: client.enableChannelBinding,
44473
+ connectionTimeoutMillis: 1e4
44474
+ });
44475
+ try {
44476
+ await other.connect();
44477
+ await other.query("set search_path = pg_catalog, pg_temp");
44478
+ await other.query("set statement_timeout = '30s'");
44479
+ } catch (err) {
44480
+ await other.end().catch(() => {});
44481
+ throw err;
44482
+ }
44483
+ return other;
44484
+ };
44485
+ async function a005ReadDatabase(client) {
44486
+ const row = (await client.query(A005_DATABASE_SQL)).rows[0] || {};
44487
+ return {
44488
+ extensions: row.extensions || {},
44489
+ index_access_methods: row.index_access_methods || [],
44490
+ row_security_policies: Number(row.row_security_policies ?? 0),
44491
+ extended_statistics: Number(row.extended_statistics ?? 0)
44492
+ };
44493
+ }
44494
+ function a005Conclusions(data) {
44495
+ const conclusions = [];
44496
+ const recommendations = [];
44497
+ const dbs = Object.entries(data.databases);
44498
+ const unread = dbs.filter(([, db]) => !db.read);
44499
+ const installed = new Set;
44500
+ for (const [, db] of dbs)
44501
+ for (const name of Object.keys(db.extensions || {}))
44502
+ installed.add(name);
44503
+ const n = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
44504
+ conclusions.push(`${dbs.length - unread.length} of ${n(dbs.length, "database")} read; ${n(installed.size, "distinct extension")} installed.`);
44505
+ if (unread.length) {
44506
+ conclusions.push(`Not read: ${unread.map(([name]) => name).join(", ")}. A fact about extensions or indexes is not known for the server.`);
44507
+ recommendations.push("Let the checkup role connect to every database (CONNECT privilege) so that A005 covers the whole server.");
44508
+ }
44509
+ const withCreate = dbs.filter(([, db]) => db.roles_with_create > 0).length;
44510
+ if (withCreate) {
44511
+ conclusions.push(`${withCreate} of ${n(dbs.length, "database")} ${withCreate === 1 ? "has" : "have"} a non-superuser role with CREATE: it can install trusted extensions itself.`);
44512
+ }
44513
+ const roles = data.roles || {};
44514
+ if (roles.md5_passwords === null) {
44515
+ conclusions.push(`Stored password hashes are not known: ${roles.password_hashes_error || "pg_authid is not readable"}.`);
44516
+ } else if (roles.md5_passwords > 0) {
44517
+ conclusions.push(`${n(roles.md5_passwords, "role")} with an MD5 password hash.`);
44518
+ recommendations.push("Set password_encryption = 'scram-sha-256' and reset the passwords of the roles with MD5 hashes.");
44519
+ }
44520
+ const slots = data.logical_slots.reduce((sum, s) => sum + s.slots, 0);
44521
+ if (slots) {
44522
+ conclusions.push(`${n(slots, "logical replication slot")}.`);
44523
+ }
44524
+ return { conclusions, recommendations };
44525
+ }
44526
+ async function generateA005(client, nodeName = "node-01") {
44527
+ const report = createBaseReport("A005", "Extensions", nodeName);
44528
+ const postgresVersion = await getPostgresVersion(client);
44529
+ const started = Date.now();
44530
+ const databases = Object.create(null);
44531
+ const listed = (await client.query(A005_DATABASES_SQL)).rows;
44532
+ let opened = 0;
44533
+ for (const row of listed) {
44534
+ const entry = { read: false, roles_with_create: Number(row.roles_with_create ?? 0) };
44535
+ databases[row.datname] = entry;
44536
+ try {
44537
+ if (row.is_current) {
44538
+ Object.assign(entry, await a005ReadDatabase(client), { read: true });
44539
+ continue;
44540
+ }
44541
+ if (!toBool(row.can_connect))
44542
+ throw new Error("the checkup role has no CONNECT privilege on this database");
44543
+ if (opened >= A005_MAX_DATABASES)
44544
+ throw new Error(`not read: more than ${A005_MAX_DATABASES} databases`);
44545
+ if (Date.now() - started > A005_TIME_BUDGET_MS)
44546
+ throw new Error("not read: the time budget ran out");
44547
+ opened += 1;
44548
+ const other = await a005OpenDatabase(client, row.datname);
44549
+ try {
44550
+ Object.assign(entry, await a005ReadDatabase(other), { read: true });
44551
+ } finally {
44552
+ await other.end().catch(() => {});
44553
+ }
44554
+ } catch (err) {
44555
+ entry.error = a005Error(err);
44556
+ }
44557
+ }
44558
+ const optional = async (fn) => {
44559
+ try {
44560
+ return { value: await fn(), error: null };
44561
+ } catch (err) {
44562
+ return { value: null, error: a005Error(err) };
44563
+ }
44564
+ };
44565
+ const slots = await optional(async () => (await client.query(A005_SLOTS_SQL)).rows.map((r) => ({
44566
+ database: r.database,
44567
+ plugin: r.plugin,
44568
+ slots: Number(r.slots),
44569
+ active: Number(r.active)
44570
+ })));
44571
+ const replication = await optional(async () => Number((await client.query(A005_REPLICATION_ROLES_SQL)).rows[0].replication));
44572
+ const hashes = await optional(async () => (await client.query(A005_PASSWORD_HASHES_SQL)).rows[0]);
44573
+ const scram = await optional(async () => (await client.query("select current_setting('scram_iterations', true) as v")).rows[0]?.v ?? null);
44574
+ const subscriptions = await optional(async () => Number((await client.query("select count(*)::int as n from pg_subscription")).rows[0].n));
44575
+ const hba = await optional(async () => {
44576
+ const r = (await client.query(A005_HBA_SQL)).rows[0];
44577
+ return { cert: Number(r.cert), trust: Number(r.trust), hostgssenc: Number(r.hostgssenc), errors: Number(r.errors) };
44578
+ });
44579
+ const data = {
44580
+ databases,
44581
+ logical_slots: slots.value ?? [],
44582
+ logical_slots_error: slots.error,
44583
+ roles: {
44584
+ replication: replication.value,
44585
+ replication_error: replication.error,
44586
+ md5_passwords: hashes.value ? Number(hashes.value.md5_passwords) : null,
44587
+ nondefault_scram_iterations: hashes.value ? Number(hashes.value.nondefault_scram_iterations) : null,
44588
+ password_hashes_error: hashes.error,
44589
+ scram_iterations: scram.value
44590
+ },
44591
+ subscriptions: subscriptions.value,
44592
+ subscriptions_error: subscriptions.error,
44593
+ hba_rules: hba.value,
44594
+ hba_rules_error: hba.error
44595
+ };
44596
+ Object.assign(data, a005Conclusions(data));
44597
+ report.results[nodeName] = { data, postgres_version: postgresVersion };
44598
+ return report;
44599
+ }
44295
44600
  var generateA007 = (client, nodeName = "node-01") => generateSettingsReport(client, nodeName, "A007", "Altered settings", getAlteredSettings);
44296
44601
  var generateA013 = (client, nodeName = "node-01") => generateVersionReport(client, nodeName, "A013", "Postgres minor version");
44297
44602
  var generateH001 = (client, nodeName = "node-01") => generateIndexReport(client, nodeName, "H001", "Invalid indexes", "invalid_indexes", getInvalidIndexes);
@@ -45650,6 +45955,7 @@ var REPORT_GENERATORS = {
45650
45955
  A002: generateA002,
45651
45956
  A003: generateA003,
45652
45957
  A004: generateA004,
45958
+ A005: generateA005,
45653
45959
  A007: generateA007,
45654
45960
  A013: generateA013,
45655
45961
  D001: generateD001,
@@ -46031,6 +46337,8 @@ function generateCheckSummary2(checkId, report) {
46031
46337
  return summarizeA0032(nodeData);
46032
46338
  case "A004":
46033
46339
  return summarizeA0042(nodeData);
46340
+ case "A005":
46341
+ return summarizeA0052(nodeData);
46034
46342
  case "A007":
46035
46343
  return summarizeA0072(nodeData);
46036
46344
  case "D001":
@@ -46068,6 +46376,22 @@ function summarizeA0032(nodeData) {
46068
46376
  message: `${settingsCount} setting${settingsCount > 1 ? "s" : ""} collected`
46069
46377
  };
46070
46378
  }
46379
+ function summarizeA0052(nodeData) {
46380
+ const databases = Object.values(nodeData?.data?.databases || {});
46381
+ if (databases.length === 0) {
46382
+ return { status: "info", message: "No databases listed" };
46383
+ }
46384
+ const extensions = new Set;
46385
+ for (const db of databases)
46386
+ for (const name of Object.keys(db.extensions || {}))
46387
+ extensions.add(name);
46388
+ const unread = databases.filter((db) => !db.read).length;
46389
+ const message = `${extensions.size} extension${extensions.size === 1 ? "" : "s"} in ` + `${databases.length - unread} of ${databases.length} database${databases.length === 1 ? "" : "s"}`;
46390
+ if (unread > 0) {
46391
+ return { status: "warning", message: `${message}; ${unread} not read` };
46392
+ }
46393
+ return { status: "info", message };
46394
+ }
46071
46395
  function summarizeA0042(nodeData) {
46072
46396
  const data = nodeData?.data;
46073
46397
  if (!data) {
@@ -51846,9 +52170,12 @@ withOrgOptions(issues.command("view <issueId>")).description("view issue details
51846
52170
  return;
51847
52171
  }
51848
52172
  spinner.update("Fetching comments...");
51849
- const comments = await fetchIssueComments2({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug });
52173
+ const [comments, seenBy] = await Promise.all([
52174
+ fetchIssueComments2({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug }),
52175
+ recordIssueView2({ apiKey, apiBaseUrl, issueId, via: cliViewVia(), debug: !!opts.debug })
52176
+ ]);
51850
52177
  spinner.stop();
51851
- const combined = { issue: presentIssue2(issue), comments };
52178
+ const combined = { issue: { ...presentIssue2(issue), ...seenBy ? { seen_by: seenBy } : {} }, comments };
51852
52179
  printResult(combined, opts.json);
51853
52180
  } catch (err) {
51854
52181
  spinner.stop();
@@ -1,5 +1,5 @@
1
1
  -- Required permissions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
- -- The first DO block also runs as the admin; pin before any name resolution.
2
+ -- The first DO blocks also run as the admin; pin before any name resolution.
3
3
  set search_path = pg_catalog, pg_temp;
4
4
 
5
5
  -- Allow connect
@@ -14,9 +14,34 @@ grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
14
14
  -- is not granted directly: on PostgreSQL 16+ that needs ADMIN OPTION on pg_read_all_stats,
15
15
  -- which Supabase's `postgres` role does not have (it has ADMIN OPTION on pg_monitor only).
16
16
 
17
- -- Create postgres_ai schema for our objects
18
- -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times
19
- create schema if not exists postgres_ai;
17
+ -- Create postgres_ai schema for our objects; an existing one is kept (prepare-db
18
+ -- can be run multiple times). Default privileges can grant CREATE on every new
19
+ -- schema to another role (ClickHouse Cloud grants it to chpg_console_admin).
20
+ -- A schema created here is still empty, so revoke those grants.
21
+ do {{DO_QUOTE}}
22
+ declare
23
+ create_grantee text;
24
+ begin
25
+ set local search_path = pg_catalog, pg_temp;
26
+ if exists (select from pg_catalog.pg_namespace where nspname = 'postgres_ai') then
27
+ return;
28
+ end if;
29
+ begin
30
+ create schema postgres_ai;
31
+ exception when duplicate_schema or unique_violation then
32
+ -- Created concurrently (unique_violation when its CREATE raced this one
33
+ -- past the exists check): checked below like any existing schema.
34
+ return;
35
+ end;
36
+ for create_grantee in
37
+ select distinct case when a.grantee = 0 then 'public'
38
+ else pg_catalog.quote_ident(pg_catalog.pg_get_userbyid(a.grantee)) end
39
+ from pg_catalog.pg_namespace n, pg_catalog.aclexplode(n.nspacl) a
40
+ where n.nspname = 'postgres_ai' and a.privilege_type = 'CREATE' and a.grantee <> n.nspowner
41
+ loop
42
+ execute pg_catalog.format('revoke create on schema postgres_ai from %s', create_grantee);
43
+ end loop;
44
+ end {{DO_QUOTE}};
20
45
  -- An existing schema keeps its owner, and CREATE OR REPLACE keeps the owner of
21
46
  -- existing functions/views. Refuse a schema that another role can still write:
22
47
  -- the monitoring role searches postgres_ai and calls our helper from it.
@@ -32,6 +57,13 @@ begin
32
57
  set local search_path = pg_catalog, pg_temp;
33
58
  select oid into admin_oid from pg_catalog.pg_roles where rolname = current_user;
34
59
  select oid into schema_oid from pg_catalog.pg_namespace where nspname = 'postgres_ai';
60
+ -- Under repeatable read, a schema another session committed after this
61
+ -- snapshot is invisible here; it cannot be checked, so refuse.
62
+ if schema_oid is null then
63
+ raise exception 'postgres_ai schema was created by another session during prepare-db'
64
+ using errcode = '40001',
65
+ hint = 'Run prepare-db again.';
66
+ end if;
35
67
 
36
68
  select pg_catalog.pg_get_userbyid(n.nspowner) into schema_owner
37
69
  from pg_catalog.pg_namespace n where n.oid = schema_oid;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postgresai",
3
- "version": "0.18.0-rc.2",
3
+ "version": "0.18.0-rc.4",
4
4
  "description": "postgres_ai CLI",
5
5
  "license": "Apache-2.0",
6
6
  "private": false,
@@ -0,0 +1,399 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "A005 report schema",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "required": [
7
+ "checkId",
8
+ "checkTitle",
9
+ "timestamptz",
10
+ "nodes",
11
+ "results"
12
+ ],
13
+ "properties": {
14
+ "contract_version": {
15
+ "type": [
16
+ "string",
17
+ "null"
18
+ ]
19
+ },
20
+ "summary": {
21
+ "type": "object",
22
+ "additionalProperties": false,
23
+ "required": [
24
+ "status",
25
+ "message"
26
+ ],
27
+ "properties": {
28
+ "status": {
29
+ "enum": [
30
+ "ok",
31
+ "warning",
32
+ "info"
33
+ ]
34
+ },
35
+ "message": {
36
+ "type": "string"
37
+ }
38
+ }
39
+ },
40
+ "version": {
41
+ "type": [
42
+ "string",
43
+ "null"
44
+ ]
45
+ },
46
+ "build_ts": {
47
+ "type": [
48
+ "string",
49
+ "null"
50
+ ]
51
+ },
52
+ "generation_mode": {
53
+ "type": [
54
+ "string",
55
+ "null"
56
+ ]
57
+ },
58
+ "checkId": {
59
+ "const": "A005"
60
+ },
61
+ "checkTitle": {
62
+ "const": "Extensions"
63
+ },
64
+ "timestamptz": {
65
+ "type": "string"
66
+ },
67
+ "nodes": {
68
+ "$ref": "#/$defs/nodes"
69
+ },
70
+ "results": {
71
+ "type": "object",
72
+ "minProperties": 1,
73
+ "additionalProperties": {
74
+ "$ref": "#/$defs/nodeResult"
75
+ }
76
+ }
77
+ },
78
+ "$defs": {
79
+ "nodes": {
80
+ "type": "object",
81
+ "additionalProperties": false,
82
+ "required": [
83
+ "primary",
84
+ "standbys"
85
+ ],
86
+ "properties": {
87
+ "primary": {
88
+ "type": "string"
89
+ },
90
+ "standbys": {
91
+ "type": "array",
92
+ "items": {
93
+ "type": "string"
94
+ }
95
+ }
96
+ }
97
+ },
98
+ "postgresVersion": {
99
+ "type": "object",
100
+ "additionalProperties": false,
101
+ "required": [
102
+ "version",
103
+ "server_version_num",
104
+ "server_major_ver",
105
+ "server_minor_ver"
106
+ ],
107
+ "properties": {
108
+ "version": {
109
+ "type": "string"
110
+ },
111
+ "server_version_num": {
112
+ "type": "string"
113
+ },
114
+ "server_major_ver": {
115
+ "type": "string"
116
+ },
117
+ "server_minor_ver": {
118
+ "type": "string"
119
+ }
120
+ }
121
+ },
122
+ "database": {
123
+ "type": "object",
124
+ "additionalProperties": false,
125
+ "required": [
126
+ "read",
127
+ "roles_with_create"
128
+ ],
129
+ "properties": {
130
+ "read": {
131
+ "type": "boolean"
132
+ },
133
+ "error": {
134
+ "type": "string"
135
+ },
136
+ "roles_with_create": {
137
+ "type": "integer",
138
+ "minimum": 0
139
+ },
140
+ "extensions": {
141
+ "type": "object",
142
+ "additionalProperties": {
143
+ "type": "string"
144
+ }
145
+ },
146
+ "index_access_methods": {
147
+ "type": "array",
148
+ "items": {
149
+ "type": "object",
150
+ "additionalProperties": false,
151
+ "required": [
152
+ "am",
153
+ "extension",
154
+ "indexes"
155
+ ],
156
+ "properties": {
157
+ "am": {
158
+ "type": "string"
159
+ },
160
+ "extension": {
161
+ "type": [
162
+ "string",
163
+ "null"
164
+ ]
165
+ },
166
+ "indexes": {
167
+ "type": "integer",
168
+ "minimum": 0
169
+ }
170
+ }
171
+ }
172
+ },
173
+ "row_security_policies": {
174
+ "type": "integer",
175
+ "minimum": 0
176
+ },
177
+ "extended_statistics": {
178
+ "type": "integer",
179
+ "minimum": 0
180
+ }
181
+ },
182
+ "if": {
183
+ "properties": {
184
+ "read": {
185
+ "const": true
186
+ }
187
+ }
188
+ },
189
+ "then": {
190
+ "required": [
191
+ "extensions",
192
+ "index_access_methods",
193
+ "row_security_policies",
194
+ "extended_statistics"
195
+ ]
196
+ },
197
+ "else": {
198
+ "required": [
199
+ "error"
200
+ ]
201
+ }
202
+ },
203
+ "data": {
204
+ "type": "object",
205
+ "additionalProperties": false,
206
+ "required": [
207
+ "databases",
208
+ "logical_slots",
209
+ "logical_slots_error",
210
+ "roles",
211
+ "subscriptions",
212
+ "subscriptions_error",
213
+ "hba_rules",
214
+ "hba_rules_error",
215
+ "conclusions",
216
+ "recommendations"
217
+ ],
218
+ "properties": {
219
+ "databases": {
220
+ "type": "object",
221
+ "additionalProperties": {
222
+ "$ref": "#/$defs/database"
223
+ }
224
+ },
225
+ "logical_slots": {
226
+ "type": "array",
227
+ "items": {
228
+ "type": "object",
229
+ "additionalProperties": false,
230
+ "required": [
231
+ "database",
232
+ "plugin",
233
+ "slots",
234
+ "active"
235
+ ],
236
+ "properties": {
237
+ "database": {
238
+ "type": [
239
+ "string",
240
+ "null"
241
+ ]
242
+ },
243
+ "plugin": {
244
+ "type": [
245
+ "string",
246
+ "null"
247
+ ]
248
+ },
249
+ "slots": {
250
+ "type": "integer",
251
+ "minimum": 0
252
+ },
253
+ "active": {
254
+ "type": "integer",
255
+ "minimum": 0
256
+ }
257
+ }
258
+ }
259
+ },
260
+ "logical_slots_error": {
261
+ "type": [
262
+ "string",
263
+ "null"
264
+ ]
265
+ },
266
+ "roles": {
267
+ "type": "object",
268
+ "additionalProperties": false,
269
+ "required": [
270
+ "replication",
271
+ "replication_error",
272
+ "md5_passwords",
273
+ "nondefault_scram_iterations",
274
+ "password_hashes_error",
275
+ "scram_iterations"
276
+ ],
277
+ "properties": {
278
+ "replication": {
279
+ "type": [
280
+ "integer",
281
+ "null"
282
+ ],
283
+ "minimum": 0
284
+ },
285
+ "replication_error": {
286
+ "type": [
287
+ "string",
288
+ "null"
289
+ ]
290
+ },
291
+ "md5_passwords": {
292
+ "type": [
293
+ "integer",
294
+ "null"
295
+ ],
296
+ "minimum": 0
297
+ },
298
+ "nondefault_scram_iterations": {
299
+ "type": [
300
+ "integer",
301
+ "null"
302
+ ],
303
+ "minimum": 0
304
+ },
305
+ "password_hashes_error": {
306
+ "type": [
307
+ "string",
308
+ "null"
309
+ ]
310
+ },
311
+ "scram_iterations": {
312
+ "type": [
313
+ "string",
314
+ "null"
315
+ ]
316
+ }
317
+ }
318
+ },
319
+ "subscriptions": {
320
+ "type": [
321
+ "integer",
322
+ "null"
323
+ ],
324
+ "minimum": 0
325
+ },
326
+ "subscriptions_error": {
327
+ "type": [
328
+ "string",
329
+ "null"
330
+ ]
331
+ },
332
+ "hba_rules": {
333
+ "type": [
334
+ "object",
335
+ "null"
336
+ ],
337
+ "additionalProperties": false,
338
+ "required": [
339
+ "cert",
340
+ "trust",
341
+ "hostgssenc",
342
+ "errors"
343
+ ],
344
+ "properties": {
345
+ "cert": {
346
+ "type": "integer",
347
+ "minimum": 0
348
+ },
349
+ "trust": {
350
+ "type": "integer",
351
+ "minimum": 0
352
+ },
353
+ "hostgssenc": {
354
+ "type": "integer",
355
+ "minimum": 0
356
+ },
357
+ "errors": {
358
+ "type": "integer",
359
+ "minimum": 0
360
+ }
361
+ }
362
+ },
363
+ "hba_rules_error": {
364
+ "type": [
365
+ "string",
366
+ "null"
367
+ ]
368
+ },
369
+ "conclusions": {
370
+ "type": "array",
371
+ "items": {
372
+ "type": "string"
373
+ }
374
+ },
375
+ "recommendations": {
376
+ "type": "array",
377
+ "items": {
378
+ "type": "string"
379
+ }
380
+ }
381
+ }
382
+ },
383
+ "nodeResult": {
384
+ "type": "object",
385
+ "additionalProperties": false,
386
+ "required": [
387
+ "data"
388
+ ],
389
+ "properties": {
390
+ "data": {
391
+ "$ref": "#/$defs/data"
392
+ },
393
+ "postgres_version": {
394
+ "$ref": "#/$defs/postgresVersion"
395
+ }
396
+ }
397
+ }
398
+ }
399
+ }
@@ -245,13 +245,15 @@
245
245
  "type": [
246
246
  "number",
247
247
  "null"
248
- ]
248
+ ],
249
+ "description": "95th percentile of the 5-minute averages of read + write IOPS (Supabase: all block devices, root disk included)."
249
250
  },
250
251
  "iops_max": {
251
252
  "type": [
252
253
  "number",
253
254
  "null"
254
- ]
255
+ ],
256
+ "description": "The highest 5-minute average of read + write IOPS, not the busiest minute."
255
257
  },
256
258
  "free_bytes": {
257
259
  "type": [
@@ -356,7 +358,15 @@
356
358
  "number",
357
359
  "null"
358
360
  ]
359
- }
361
+ },
362
+ "description": "Read + write IOPS, each point the average over its 5 minutes."
363
+ },
364
+ "disk_iops_kind": {
365
+ "type": "string",
366
+ "enum": [
367
+ "avg_5m"
368
+ ],
369
+ "description": "What a disk_iops point is: avg_5m = the 5-minute average. Reports from older reporters omit it (their points were the busiest minute), and the platform does not judge their IOPS."
360
370
  }
361
371
  }
362
372
  }
@@ -1,5 +1,5 @@
1
1
  -- Required permissions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
- -- The first DO block also runs as the admin; pin before any name resolution.
2
+ -- The first DO blocks also run as the admin; pin before any name resolution.
3
3
  set search_path = pg_catalog, pg_temp;
4
4
 
5
5
  -- Allow connect
@@ -14,9 +14,34 @@ grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
14
14
  -- is not granted directly: on PostgreSQL 16+ that needs ADMIN OPTION on pg_read_all_stats,
15
15
  -- which Supabase's `postgres` role does not have (it has ADMIN OPTION on pg_monitor only).
16
16
 
17
- -- Create postgres_ai schema for our objects
18
- -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times
19
- create schema if not exists postgres_ai;
17
+ -- Create postgres_ai schema for our objects; an existing one is kept (prepare-db
18
+ -- can be run multiple times). Default privileges can grant CREATE on every new
19
+ -- schema to another role (ClickHouse Cloud grants it to chpg_console_admin).
20
+ -- A schema created here is still empty, so revoke those grants.
21
+ do {{DO_QUOTE}}
22
+ declare
23
+ create_grantee text;
24
+ begin
25
+ set local search_path = pg_catalog, pg_temp;
26
+ if exists (select from pg_catalog.pg_namespace where nspname = 'postgres_ai') then
27
+ return;
28
+ end if;
29
+ begin
30
+ create schema postgres_ai;
31
+ exception when duplicate_schema or unique_violation then
32
+ -- Created concurrently (unique_violation when its CREATE raced this one
33
+ -- past the exists check): checked below like any existing schema.
34
+ return;
35
+ end;
36
+ for create_grantee in
37
+ select distinct case when a.grantee = 0 then 'public'
38
+ else pg_catalog.quote_ident(pg_catalog.pg_get_userbyid(a.grantee)) end
39
+ from pg_catalog.pg_namespace n, pg_catalog.aclexplode(n.nspacl) a
40
+ where n.nspname = 'postgres_ai' and a.privilege_type = 'CREATE' and a.grantee <> n.nspowner
41
+ loop
42
+ execute pg_catalog.format('revoke create on schema postgres_ai from %s', create_grantee);
43
+ end loop;
44
+ end {{DO_QUOTE}};
20
45
  -- An existing schema keeps its owner, and CREATE OR REPLACE keeps the owner of
21
46
  -- existing functions/views. Refuse a schema that another role can still write:
22
47
  -- the monitoring role searches postgres_ai and calls our helper from it.
@@ -32,6 +57,13 @@ begin
32
57
  set local search_path = pg_catalog, pg_temp;
33
58
  select oid into admin_oid from pg_catalog.pg_roles where rolname = current_user;
34
59
  select oid into schema_oid from pg_catalog.pg_namespace where nspname = 'postgres_ai';
60
+ -- Under repeatable read, a schema another session committed after this
61
+ -- snapshot is invisible here; it cannot be checked, so refuse.
62
+ if schema_oid is null then
63
+ raise exception 'postgres_ai schema was created by another session during prepare-db'
64
+ using errcode = '40001',
65
+ hint = 'Run prepare-db again.';
66
+ end if;
35
67
 
36
68
  select pg_catalog.pg_get_userbyid(n.nspowner) into schema_owner
37
69
  from pg_catalog.pg_namespace n where n.oid = schema_oid;