CDX-301c · Module 3

Cost Controls & Budget Management

3 min read

Cost control is the governance layer that prevents CI Codex usage from exceeding budget. The three levers are: trigger frequency (how often Codex runs), model selection (which model processes each task), and scope (how much of the diff Codex analyzes). A misconfigured trigger — running on every push instead of every PR — can multiply costs by 10x. A misconfigured model — using o3 for style checks instead of gpt-4.1-mini — can multiply costs by 20x. Both mistakes are common and preventable.

Build a cost dashboard that tracks API spend per workflow, per repository, and per team. Set alerts at 50%, 75%, and 90% of monthly budget. When the 75% alert fires, automatically switch non-critical workflows to cheaper models. When the 90% alert fires, disable non-essential workflows entirely. This tiered response prevents budget overruns while keeping critical checks (security review, deployment gates) running through the end of the month.

name: Cost-Aware Codex Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - run: npm install -g @openai/codex
      - name: Check diff size
        id: diff-size
        run: |
          LINES=$(git diff --stat origin/${{ github.base_ref }}...HEAD | tail -1 | grep -oP '\d+(?= insertion)')
          echo "lines=${LINES:-0}" >> "$GITHUB_OUTPUT"
          echo "Diff size: ${LINES:-0} lines changed"
      - name: Select model by diff size
        id: model
        run: |
          LINES=${{ steps.diff-size.outputs.lines }}
          if [ "$LINES" -gt 500 ]; then
            echo "profile=review" >> "$GITHUB_OUTPUT"    # o3 for large diffs
          elif [ "$LINES" -gt 100 ]; then
            echo "profile=ci" >> "$GITHUB_OUTPUT"        # gpt-4.1 for medium
          else
            echo "profile=quick" >> "$GITHUB_OUTPUT"     # gpt-4.1-mini for small
          fi
      - name: Run Review
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          echo "Using profile: ${{ steps.model.outputs.profile }}"
          codex --profile ${{ steps.model.outputs.profile }} \
            --approval full-auto \
            review --base origin/${{ github.base_ref }} --json
  1. Instrument cost tracking Log token usage from every CI Codex run. Aggregate by workflow, repo, and team. Build a weekly cost report that shows trends.
  2. Implement model routing Route reviews to models based on diff size: small diffs get the cheapest model, large diffs get the best model. This alone can cut costs 30-50%.
  3. Set budget guardrails Configure monthly spending limits on your CI API key. Set alerts at 50%, 75%, 90%. Automate model downgrade at 75% and workflow disable at 90%.