# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL Advanced"

on:
  workflow_dispatch:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]
  schedule:
    - cron: '40 3 * * 4'

# A cold-cache run rebuilds PostgreSQL and pgvector from source and downloads
# SVS's prebuilt release (up to the 180-minute timeout below), so a
# superseded run on the same ref is cancelled rather than left to run to
# completion alongside its replacement.
concurrency:
  group: codeql-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  analyze:
    name: Analyze (${{ matrix.language }})
    # Runner size impacts CodeQL analysis time. To learn more, please see:
    #   - https://gh.io/recommended-hardware-resources-for-running-codeql
    #   - https://gh.io/supported-runners-and-hardware-resources
    #   - https://gh.io/using-larger-runners (GitHub.com only)
    # Consider using larger runners or machines with greater resources for possible analysis time improvements.
    runs-on: ubuntu-latest
    # Cold-cache runs build PostgreSQL from source; the timeout keeps a hung
    # dependency build from consuming the 6 hour default.
    timeout-minutes: 180
    permissions:
      # required for all workflows
      security-events: write

      # required to fetch internal or private CodeQL packs
      packages: read

      # only required for workflows in private repositories
      actions: read
      contents: read

    strategy:
      fail-fast: false
      matrix:
        include:
        - language: c-cpp
          # 'manual' rather than 'none': this extension only compiles against
          # PostgreSQL, SVS and pgvector headers, so buildless extraction cannot
          # resolve its macros and types.
          build-mode: manual
        # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
        # Use `c-cpp` to analyze code written in C, C++ or both
        # Use 'java-kotlin' to analyze code written in Java, Kotlin or both
        # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
        # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
        # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
        # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
        # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
    steps:
    - name: Checkout repository
      uses: actions/checkout@v7

    # A CodeQL build-mode:manual analysis reports on everything built during
    # the trace, with no path-based filtering -- paths/paths-ignore do not
    # apply to a compiled language analyzed with build-mode: manual/autobuild
    # (see "Alerts found in generated code" in GitHub's code-scanning docs).
    # The only way to keep the vendored PostgreSQL/SVS/pgvector dependency
    # trees out of this analysis is to build them outside the checkout root
    # entirely, so the extractor never attributes anything in them to this
    # repository. $RUNNER_TEMP is a sibling of the checkout, not under it.
    #
    # Copying docs/build_guide/ there, rather than overriding its scripts'
    # directory variables, needs no changes to docs/build_guide/config at
    # all: every path in it is already derived from BASE_DIR, which the
    # scripts compute from their own invocation path
    # ($(dirname "${BASH_SOURCE[0]}")). Invoking the copies makes BASE_DIR
    # -- and everything under it -- land under $RUNNER_TEMP for free.
    - name: Copy build_guide outside the checkout root
      run: cp -r docs/build_guide "${RUNNER_TEMP}/build_guide"

    # The dependency builds below deliberately run *before* `init` so that the
    # CodeQL tracer only wraps this repository's `make`. Building PostgreSQL and
    # the SVS C++ library after `init` would extract them into the database too.
    # See docs/build_guide/README.md for the equivalent local build.
    - name: Install build dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y --no-install-recommends \
          build-essential cmake git bison flex pkg-config \
          libreadline-dev zlib1g-dev libicu-dev

    # pgvector installs into the PostgreSQL prefix, so caching pgsql_install
    # also caches the vector/halfvec headers the Makefile compiles against.
    - name: Restore PostgreSQL and SVS builds
      id: deps-cache
      uses: actions/cache@v4
      with:
        path: |
          ${{ runner.temp }}/build_guide/pgsql_install
          ${{ runner.temp }}/build_guide/svs_install
        key: svs-deps-${{ runner.os }}-${{ hashFiles('docs/build_guide/config', 'docs/build_guide/install_postgres.sh', 'docs/build_guide/build_svs.sh', 'docs/build_guide/build_pgvector_vanilla.sh') }}

    - name: Build PostgreSQL
      if: steps.deps-cache.outputs.cache-hit != 'true'
      run: bash "${RUNNER_TEMP}/build_guide/install_postgres.sh"

    - name: Build SVS library
      if: steps.deps-cache.outputs.cache-hit != 'true'
      run: bash "${RUNNER_TEMP}/build_guide/build_svs.sh"

    - name: Build and install vanilla pgvector
      if: steps.deps-cache.outputs.cache-hit != 'true'
      run: bash "${RUNNER_TEMP}/build_guide/build_pgvector_vanilla.sh"

    # Initializes the CodeQL tools for scanning.
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v4
      with:
        languages: ${{ matrix.language }}
        build-mode: ${{ matrix.build-mode }}
        # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
        queries: security-and-quality
        # No paths-ignore here: it does not apply to a build-mode:manual
        # analysis (see the "Copy build_guide outside the checkout root"
        # step above, which is what actually keeps the vendored PostgreSQL/
        # SVS/pgvector dependency trees out of this analysis). An earlier
        # version of this workflow had a paths-ignore block here; it was
        # syntactically valid but had no effect on the scan results and was
        # removed rather than left as misleading dead configuration.

    # Build only the extension, so this is the compilation CodeQL traces.
    # Source the copy under $RUNNER_TEMP, not docs/build_guide/config itself:
    # that is where install_postgres.sh/build_svs.sh actually installed to
    # (see "Copy build_guide outside the checkout root" above), and PG_CONFIG/
    # SVS_INSTALL_DIR are derived from the same BASE_DIR either copy resolves
    # for itself, so sourcing the in-tree config here would point at empty
    # directories instead. PG_CONFIG is exported rather than passed on the
    # command line, matching build_svs_extension.sh's own convention, so the
    # two don't drift into different patterns for the same variable.
    - name: Run manual build steps
      if: matrix.build-mode == 'manual'
      shell: bash
      run: |
        source "${RUNNER_TEMP}/build_guide/config"
        export PG_CONFIG
        make -j"$(nproc)" SVS_INSTALL="$SVS_INSTALL_DIR"

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v4
      with:
        category: "/language:${{matrix.language}}"
        
    # Report only on a manual run, never on push/PR/schedule.
    - name: Generate Security Report
      if: github.event_name == 'workflow_dispatch'
      uses: rsdmike/github-security-report-action@v3.0.4
      with:
        template: report
        token: ${{ secrets.GITHUB_TOKEN }}

    - name: GitHub Upload Release Artifacts
      if: github.event_name == 'workflow_dispatch'
      uses: actions/upload-artifact@v4
      with:
        name: report
        path: |
         ./report.pdf
 
