# This manifest is intended exclusively for use on the Antithesis platform.
# It hardcodes the Antithesis image registry and configures a placeholder
# secret for the PostgreSQL superuser password.
#
# The two ConfigMaps and the Cluster are rendered from the ParadeDB Helm chart
# (https://github.com/paradedb/charts, currently 0.19.12) with these values:
#
#   type: paradedb
#   mode: standalone
#   version: { postgresql: "18", paradedb: "0.26.0" }
#   cluster:
#     instances: 1
#     imageName: us-central1-docker.pkg.dev/molten-verve-216720/paradedb-repository/paradedb
#     storage: { size: 256Mi }
#     affinity: { topologyKey: topology.kubernetes.io/zone }
#     env:
#       - { name: RUST_BACKTRACE, value: "1" }
#       - { name: RUST_LIB_BACKTRACE, value: "1" }
#     enableSuperuserAccess: true
#     superuserSecret: paradedb-superuser
#     monitoring:
#       enabled: false
#       instrumentation: { pgStatStatements: false, pgStatActivity: false }
#
# On top of that render, `enableAlterSystem`, `enablePodMonitor`, the Secret and
# the vanilla-Postgres publisher are added by hand, and the chart's `helm test`
# Job is dropped.
---
# Source: paradedb/templates/monitoring-logical-replication.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: paradedb-monitoring-logical-replication
  namespace: default
  labels:
    cnpg.io/reload: "true"
    cnpg.io/cluster: paradedb
    helm.sh/chart: paradedb-0.19.12
    app.kubernetes.io/name: paradedb
    app.kubernetes.io/instance: paradedb
    app.kubernetes.io/part-of: cloudnative-pg
    app.kubernetes.io/version: "0.26.0"
    app.kubernetes.io/managed-by: Helm
data:
  custom-queries: |
    # Subscriber-side health, restricted to subscriptions owned by the scraped database.
    # A subscription can have multiple worker rows. Receipt age measures transport activity;
    # received_lsn and latest_end_lsn do not establish committed apply progress.
    pg_stat_subscription:
      query: |
        SELECT current_database() AS datname
             , s.oid AS subid
             , s.subname AS subname
             , subenabled AS enabled
             , worker_type
             , relid
             , pg_wal_lsn_diff(received_lsn, '0/0') AS received_lsn
             , last_msg_send_time
             , last_msg_receipt_time
             , pg_wal_lsn_diff(latest_end_lsn, '0/0') AS latest_end_lsn
             , latest_end_time
             , apply_error_count
             , sync_error_count
             , stats_reset
             , ss.pid
             , CASE
                 WHEN last_msg_receipt_time IS NOT NULL
                 THEN EXTRACT(EPOCH FROM (NOW() - last_msg_receipt_time))
                 ELSE NULL
               END AS receipt_lag_seconds
        FROM pg_subscription s
        LEFT JOIN pg_stat_subscription ss ON s.oid = ss.subid
        LEFT JOIN pg_stat_subscription_stats sss ON s.oid = sss.subid
        WHERE s.subdbid = (SELECT oid FROM pg_database WHERE datname = current_database());
      target_databases: ["*"]
      metrics:
        - datname:
            description: Name of the database
            usage: LABEL
        - subid:
            description: ID of the subscription
            usage: LABEL
        - subname:
            description: Name of the subscription
            usage: LABEL
        - worker_type:
            description: Type of the worker
            usage: LABEL
        - relid:
            description: OID of the relation
            usage: LABEL
        - received_lsn:
            description: Last written LSN received from the publisher
            usage: GAUGE
        - last_msg_send_time:
            description: Timestamp of the last message sent
            usage: GAUGE
        - last_msg_receipt_time:
            description: Timestamp of the last message receipt
            usage: GAUGE
        - latest_end_lsn:
            description: Latest end LSN received
            usage: GAUGE
        - latest_end_time:
            description: Timestamp associated with the latest reported WAL position
            usage: GAUGE
        - enabled:
            description: Subscription status (enabled/disabled)
            usage: GAUGE
        - apply_error_count:
            description: Number of times an error occurred while applying changes
            usage: GAUGE
        - sync_error_count:
            description: Number of times an error occurred during the initial table synchronization
            usage: GAUGE
        - stats_reset:
            description: Time at which these statistics were last reset
            usage: GAUGE
        - pid:
            description: Process ID of the subscription worker process
            usage: GAUGE
        - receipt_lag_seconds:
            description: Seconds since last message receipt
            usage: GAUGE


---
# Source: paradedb/templates/monitoring-paradedb-index.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: paradedb-monitoring-paradedb-index
  namespace: default
  labels:
    cnpg.io/reload: "true"
    helm.sh/chart: paradedb-0.19.12
    app.kubernetes.io/name: paradedb
    app.kubernetes.io/instance: paradedb
    app.kubernetes.io/part-of: cloudnative-pg
    app.kubernetes.io/version: "0.26.0"
    app.kubernetes.io/managed-by: Helm
data:
  custom-queries: |
    # This query must remain catalog-only. Calling into pg_search while its SQL
    # catalog and loaded binary disagree can cause errors.
    paradedb_version:
      query: |
        SELECT current_database() AS datname
             , e.extversion AS installed_version
             , a.default_version AS expected_version
             , (e.extversion = a.default_version)::int AS "match"
        FROM pg_extension e
        JOIN pg_available_extensions a ON a.name = e.extname
        WHERE e.extname = 'pg_search';
      target_databases: ["*"]
      metrics:
        - datname:
            description: Name of the database
            usage: LABEL
        - installed_version:
            description: Version recorded in the pg_search extension catalog
            usage: LABEL
        - expected_version:
            description: Default pg_search extension version shipped in the image
            usage: LABEL
        - match:
            description: Whether the pg_search extension catalog matches the image extension version
            usage: GAUGE
    # Materialize the catalog filter before opening index storage. pdb.indexes()
    # inspects invalid concurrent-build leftovers before callers can filter them.
    paradedb_index:
      query: |
        WITH valid_indexes AS MATERIALIZED (
          SELECT n.nspname AS schemaname, t.relname AS tablename,
                 c.relname AS indexname, c.oid AS indexrelid
          FROM pg_class c
          JOIN pg_namespace n ON n.oid = c.relnamespace
          JOIN pg_index i ON i.indexrelid = c.oid
          JOIN pg_class t ON t.oid = i.indrelid
          JOIN pg_am am ON am.oid = c.relam
          WHERE am.amname IN ('paradedb', 'bm25')
            AND i.indisvalid AND i.indisready AND i.indislive
        )
        SELECT current_database() as datname
             , i.schemaname AS schema
             , i.tablename
             , i.indexname AS relname
             , pg_relation_size(i.indexrelid) AS relation_size
             , COALESCE(s.segments_count, 0) AS segments_count
             , COALESCE(s.total_docs, 0) AS total_docs
             , COALESCE(s.deleted_docs, 0) AS deleted_docs
             , COALESCE(s.max_docs, 0) AS max_docs
             , CASE
                 WHEN COALESCE(s.max_docs, 0) = 0 THEN 0::double precision
                 ELSE s.deleted_docs::double precision / s.max_docs
               END AS deleted_ratio
        FROM valid_indexes i
        LEFT JOIN LATERAL (
          SELECT COUNT(*) AS segments_count
               , SUM(num_docs)::bigint AS total_docs
               , SUM(num_deleted)::bigint AS deleted_docs
               , SUM(max_doc)::bigint AS max_docs
          FROM pdb.index_segments(i.indexrelid::regclass)
        ) s ON true;
      target_databases: ["*"]
      predicate_query: "SELECT 1 FROM pg_extension e JOIN pg_available_extensions a ON a.name = e.extname WHERE e.extname = 'pg_search' AND e.extversion = a.default_version;"
      metrics:
        - datname:
            description: Name of the database
            usage: LABEL
        - schema:
            description: Schema within the database
            usage: LABEL
        - tablename:
            description: Table the index is on
            usage: LABEL
        - relname:
            description: Index name
            usage: LABEL
        - relation_size:
            description: Full Relation size
            usage: GAUGE
        - segments_count:
            description: Segment count
            usage: GAUGE
        - total_docs:
            description: Total live documents across all segments
            usage: GAUGE
        - deleted_docs:
            description: Total deleted documents across all segments
            usage: GAUGE
        - max_docs:
            description: Total allocated document slots across all segments
            usage: GAUGE
        - deleted_ratio:
            description: Fraction of allocated document slots that are deleted
            usage: GAUGE
    # Keep health separate from pdb.indexes() and pdb.index_segments(). An invalid or
    # incomplete index must still be observable even when ParadeDB cannot inspect it.
    paradedb_index_health:
      query: |
        SELECT current_database() AS datname
             , n.nspname AS schema
             , t.relname AS tablename
             , c.relname AS relname
             , i.indisvalid::int AS is_valid
             , i.indisready::int AS is_ready
        FROM pg_class c
        JOIN pg_namespace n ON n.oid = c.relnamespace
        JOIN pg_index i ON i.indexrelid = c.oid
        JOIN pg_class t ON t.oid = i.indrelid
        JOIN pg_am am ON am.oid = c.relam
        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
          AND am.amname IN ('paradedb', 'bm25');
      target_databases: ["*"]
      predicate_query: "SELECT 1 FROM pg_extension WHERE extname = 'pg_search';"
      metrics:
        - datname:
            description: Name of the database
            usage: LABEL
        - schema:
            description: Schema within the database
            usage: LABEL
        - tablename:
            description: Table the index is on
            usage: LABEL
        - relname:
            description: Index name
            usage: LABEL
        - is_valid:
            description: Whether the index is valid for queries
            usage: GAUGE
        - is_ready:
            description: Whether the index is ready for inserts
            usage: GAUGE
    # Always emit a count, including zero when no ParadeDB indexes exist.
    paradedb_invalid_indexes:
      query: |
        SELECT current_database() AS datname, COUNT(*) AS count
        FROM pg_index i
        JOIN pg_class c ON c.oid = i.indexrelid
        JOIN pg_am am ON am.oid = c.relam
        WHERE am.amname IN ('paradedb', 'bm25')
          AND (NOT i.indisvalid OR NOT i.indisready)
          AND NOT EXISTS (
            SELECT 1 FROM pg_stat_progress_create_index p
            WHERE p.datname = current_database()
              AND p.index_relid = i.indexrelid
          );
      target_databases: ["*"]
      predicate_query: "SELECT 1 FROM pg_extension WHERE extname = 'pg_search';"
      metrics:
        - datname:
            description: Name of the database
            usage: LABEL
        - count:
            description: Number of ParadeDB indexes that are invalid or not ready for inserts, excluding active builds
            usage: GAUGE
    paradedb_index_document_distribution:
      query: |
        WITH valid_indexes AS MATERIALIZED (
          SELECT n.nspname AS schemaname, t.relname AS tablename,
                 c.relname AS indexname, c.oid AS indexrelid
          FROM pg_class c
          JOIN pg_namespace n ON n.oid = c.relnamespace
          JOIN pg_index i ON i.indexrelid = c.oid
          JOIN pg_class t ON t.oid = i.indrelid
          JOIN pg_am am ON am.oid = c.relam
          WHERE am.amname IN ('paradedb', 'bm25')
            AND i.indisvalid AND i.indisready AND i.indislive
        ),
        buckets(range_order, document_range, min_docs, max_docs) AS (
          VALUES (1, '<= 100K docs', NULL::bigint, 100000::bigint)
               , (2, '100K-1M docs', 100000::bigint, 1000000::bigint)
               , (3, '1M-10M docs', 1000000::bigint, 10000000::bigint)
               , (4, '> 10M docs', 10000000::bigint, NULL::bigint)
        )
        SELECT current_database() as datname
             , i.schemaname AS schema
             , i.indexname AS relname
             , b.range_order::text
             , b.document_range
             , COUNT(s.segment_idx) AS segment_count
        FROM valid_indexes i
        CROSS JOIN buckets b
        LEFT JOIN LATERAL pdb.index_segments(i.indexrelid::regclass) s
          ON (b.min_docs IS NULL OR s.num_docs > b.min_docs)
         AND (b.max_docs IS NULL OR s.num_docs <= b.max_docs)
        GROUP BY current_database(), i.schemaname, i.indexname, b.range_order, b.document_range
        ORDER BY i.schemaname, i.indexname, b.range_order;
      target_databases: ["*"]
      predicate_query: "SELECT 1 FROM pg_extension e JOIN pg_available_extensions a ON a.name = e.extname WHERE e.extname = 'pg_search' AND e.extversion = a.default_version;"
      metrics:
        - datname:
            description: Name of the database
            usage: LABEL
        - schema:
            description: Schema within the database
            usage: LABEL
        - relname:
            description: Index name
            usage: LABEL
        - range_order:
            description: Numeric display order for the document-count range
            usage: LABEL
        - document_range:
            description: Number of live documents in each segment
            usage: LABEL
        - segment_count:
            description: Number of segments in the document-count range
            usage: GAUGE

---
apiVersion: v1
kind: Secret
metadata:
  name: paradedb-superuser
  namespace: default
type: kubernetes.io/basic-auth
stringData:
  username: postgres
  password: antithesis-super-secret-password
---
# Source: paradedb/templates/cluster.yaml
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: paradedb
  namespace: default
  labels:
    helm.sh/chart: paradedb-0.19.12
    app.kubernetes.io/name: paradedb
    app.kubernetes.io/instance: paradedb
    app.kubernetes.io/part-of: cloudnative-pg
    app.kubernetes.io/version: "0.26.0"
    app.kubernetes.io/managed-by: Helm
spec:
  instances: 1
  imageName: us-central1-docker.pkg.dev/molten-verve-216720/paradedb-repository/paradedb
  imagePullPolicy: IfNotPresent
  postgresUID: 999
  postgresGID: 999
  storage:
    size: 256Mi
  affinity:
    topologyKey: topology.kubernetes.io/zone
  env:
    - name: RUST_BACKTRACE
      value: "1"
    - name: RUST_LIB_BACKTRACE
      value: "1"

  primaryUpdateMethod: switchover
  primaryUpdateStrategy: unsupervised
  stopDelay: 1800
  logLevel: info
  enableSuperuserAccess: true
  superuserSecret:
    name: paradedb-superuser
  enablePDB: true
  postgresql:
    enableAlterSystem: true
    shared_preload_libraries:
      - pg_search
      - pg_cron
    parameters:
      cron.database_name: postgres

  monitoring:
    enablePodMonitor: false
    disableDefaultQueries: false
    customQueriesConfigMap:
      - name: paradedb-monitoring-paradedb-index
        key: custom-queries
      - name: paradedb-monitoring-logical-replication
        key: custom-queries
    tls:
      enabled: false


  bootstrap:
    initdb:
      database: paradedb
      postInitSQL:
        - CREATE EXTENSION IF NOT EXISTS pg_cron;
      postInitApplicationSQL:
        - CREATE EXTENSION IF NOT EXISTS vector;
        - CREATE EXTENSION IF NOT EXISTS pg_search;
        - ALTER DATABASE "paradedb" SET search_path TO public,paradedb;
      postInitTemplateSQL:
        - CREATE EXTENSION IF NOT EXISTS vector;
        - CREATE EXTENSION IF NOT EXISTS pg_search;
        - ALTER DATABASE template1 SET search_path TO public,paradedb;
---
# Vanilla Postgres publisher used by the logical-replication Stressgres suites.
# Lives outside the CNPG cluster because real-world logical-replication
# customers typically don't control the upstream primary. Both network and
# container stop/kill faults on this pod are excluded (see the trigger workflow):
# partitioning or killing the publisher only stalls the WAL stream, so the
# subscriber's row-count assertions fail on ordinary replication lag rather than
# any ParadeDB defect.
apiVersion: v1
kind: Service
metadata:
  name: logical-replication-publisher
  namespace: default
spec:
  selector:
    app: logical-replication-publisher
  ports:
    - port: 5432
      targetPort: 5432
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: logical-replication-publisher
  namespace: default
  labels:
    app: logical-replication-publisher
spec:
  replicas: 1
  selector:
    matchLabels:
      app: logical-replication-publisher
  template:
    metadata:
      labels:
        app: logical-replication-publisher
    spec:
      containers:
        - name: postgres
          image: docker.io/postgres:18
          imagePullPolicy: IfNotPresent
          args: ["-c", "wal_level=logical"]
          env:
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: paradedb-superuser
                  key: password
          ports:
            - containerPort: 5432
              name: postgres
