name: Memory tests
"on":
  push:
    branches:
      - main
      - ?.*.x
      - memory_test
      - trigger/memory_test
  pull_request:
    paths: .github/workflows/memory-tests.yaml
jobs:
  memory_leak:
    name: Memory leak on insert PG${{ matrix.pg }}
    runs-on: ubuntu-22.04
    strategy:
      matrix:
        pg: [15, 16, 17, 18]
      fail-fast: false

    steps:
    - name: Install Dependencies
      run: |
        sudo apt-get update
        sudo apt-get install gnupg systemd-coredump gdb postgresql-common python3-psutil
        yes | sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
        sudo apt-get update
        sudo apt-get install postgresql-${{ matrix.pg }} postgresql-server-dev-${{ matrix.pg }}

    - name: Checkout TimescaleDB
      uses: actions/checkout@v4

    - name: Build TimescaleDB
      run: |
        PATH="/usr/lib/postgresql/${{ matrix.pg }}/bin:$PATH"
        ./bootstrap -DCMAKE_BUILD_TYPE=Release
        make -C build
        sudo make -C build install

    - name: Setup database
      run: |
        sudo pg_createcluster ${{matrix.pg}} main
        sudo tee -a /etc/postgresql/${{ matrix.pg }}/main/postgresql.conf <<-CONF
          shared_preload_libraries = 'timescaledb'
          max_worker_processes = 0
          log_destination = syslog
          max_wal_size = 8GB
          max_wal_senders = 0
          wal_level = minimal
          checkpoint_timeout = 20min
          log_checkpoints = on
          bgwriter_lru_maxpages = 0
          track_counts = off
          fsync = off
          port = 5432
        CONF
        sudo grep port /etc/postgresql/${{ matrix.pg }}/main/postgresql.conf
        sudo systemctl start postgresql@${{ matrix.pg }}-main.service
        sudo -u postgres psql -X -c "CREATE USER runner SUPERUSER LOGIN;"

    - name: Run insert memory test
      run: |
        sudo -u postgres python ./scripts/test_memory_spikes.py & sleep 5 \
          && psql -d postgres -v ECHO=all -X -f scripts/out_of_order_random_direct.sql

    - name: Run generic memory test
      run: |
        sudo -u postgres python ./scripts/test_memory_spikes.py & sleep 5 \
          && psql -d postgres -v ECHO=all -X -f scripts/memory_leaks.sql

    - name: Postgres log
      if: always()
      run: |
        sudo journalctl -u postgresql@${{ matrix.pg }}-main.service

