{
  "summary": "Tenant isolation is not enforced inside privileged SECURITY DEFINER APIs: callers control p_tenant_id. Claiming uses FOR UPDATE SKIP LOCKED correctly for concurrent queue consumption, but delivery is at-least-once, so external handlers must be idempotent. Retry delay and several lease/limit inputs are not fully bounded.",
  "detectedLanguage": "SQL",
  "framework": null,
  "runtime": "PostgreSQL 17",
  "detectedTechniques": [
    {
      "name": "Durable job state machine",
      "category": "reliability",
      "evidence": "States, attempts, lease tokens, expiry timestamps, and terminal dead-lettering appear in lines 11-35, 118-125, 226-242, and 286-299."
    },
    {
      "name": "Multi-tenant row-level security",
      "category": "security",
      "evidence": "RLS and tenant SELECT policies are defined in lines 64-83."
    },
    {
      "name": "Security-definer API functions",
      "category": "security",
      "evidence": "SECURITY DEFINER functions use SET search_path = '' and are granted to service_role in lines 85-87 and 89-329."
    },
    {
      "name": "PostgreSQL row leasing with SKIP LOCKED",
      "category": "concurrency",
      "evidence": "Claim and recovery select candidates with FOR UPDATE SKIP LOCKED in lines 101-125 and 274-294."
    }
  ],
  "modernityAnalysis": [
    {
      "technique": "Durable job state machine",
      "status": "acceptable",
      "explanation": "Explicit states, leases, tokens, expiry, and attempts provide a durable database state machine. It guarantees committed state transitions, not exactly-once external execution.",
      "recommendation": "Keep the model; require idempotent handlers and bound retry delays at the API boundary.",
      "citations": [
        "WEB-5"
      ]
    },
    {
      "technique": "Multi-tenant row-level security",
      "status": "outdated",
      "explanation": "RLS policies protect ordinary row access, but privileged functions accept p_tenant_id without checking app.current_tenant_id(). An owner that bypasses RLS can therefore cross tenant boundaries.",
      "recommendation": "Enforce tenant equality inside every function and use an owner with NOBYPASSRLS where appropriate.",
      "citations": [
        "WEB-3",
        "WEB-4"
      ]
    },
    {
      "technique": "Security-definer API functions",
      "status": "acceptable",
      "explanation": "SECURITY DEFINER with SET search_path = '' is an established hardening pattern, but authorization must not rely on caller-controlled arguments.",
      "recommendation": "Derive or verify tenant identity and restrict execution to a dedicated role.",
      "citations": [
        "WEB-4"
      ]
    },
    {
      "technique": "PostgreSQL row leasing with SKIP LOCKED",
      "status": "modern",
      "explanation": "The candidate rows are locked and updated in one statement and transaction. Row locks persist until transaction end; SKIP LOCKED is intended for queue-like consumers but has an inconsistent view.",
      "recommendation": "Retain the pattern, keep transactions short, and monitor starvation.",
      "citations": [
        "WEB-1",
        "WEB-2"
      ]
    }
  ],
  "securityConcerns": [
    {
      "title": "Tenant authorization is caller-controlled",
      "severity": "high",
      "codeEvidence": "where tenant_id = p_tenant_id",
      "explanation": "Each privileged function uses the supplied tenant identifier without comparing it with app.current_tenant_id(). RLS does not automatically constrain SECURITY DEFINER execution when the owner bypasses RLS.",
      "recommendation": "Derive tenant identity from trusted session context or require p_tenant_id = app.current_tenant_id(); use a controlled owner with NOBYPASSRLS where feasible.",
      "citations": [
        "WEB-3",
        "WEB-4"
      ],
      "codeLocation": {
        "filename": "durable-queue.sql",
        "startLine": 115,
        "endLine": 115
      }
    },
    {
      "title": "Delivery is not exactly-once",
      "severity": "high",
      "codeEvidence": "and lease_expires_at > v_now",
      "explanation": "Lease ownership prevents stale completion, but a worker can perform an external side effect and crash before complete_job commits. Database transactions cannot roll back that external effect.",
      "recommendation": "Treat delivery as at-least-once and make handlers idempotent using tenant_id plus operation_key.",
      "citations": [
        "WEB-5"
      ],
      "codeLocation": {
        "filename": "durable-queue.sql",
        "startLine": 179,
        "endLine": 179
      }
    }
  ],
  "performanceConcerns": [
    {
      "title": "SKIP LOCKED trades fairness for throughput",
      "severity": "medium",
      "codeEvidence": "for update skip locked",
      "explanation": "Concurrent workers may temporarily skip locked rows; PostgreSQL documents this as suitable for queue-like consumers but not a consistent view.",
      "recommendation": "Accept the tradeoff for throughput and monitor starvation, lease expiry, and retry metrics.",
      "citations": [
        "WEB-1"
      ],
      "codeLocation": {
        "filename": "durable-queue.sql",
        "startLine": 119,
        "endLine": 119
      }
    },
    {
      "title": "Retry delay is unbounded",
      "severity": "medium",
      "codeEvidence": "available_at = case when attempts >= max_attempts then available_at else v_now + p_retry_delay end",
      "explanation": "p_retry_delay is not validated, so callers can schedule arbitrarily long delays. This is an operational bound issue rather than a locking defect.",
      "recommendation": "Reject nonpositive or excessive delays and apply a documented backoff/jitter policy.",
      "citations": [
        "citation undiscovered"
      ],
      "codeLocation": {
        "filename": "durable-queue.sql",
        "startLine": 249,
        "endLine": 249
      }
    }
  ],
  "maintainability": {
    "assessment": "The schema and state transitions are explicit, but security assumptions and delivery semantics need to be made contractual.",
    "strengths": [
      "Lease token and owner checks reject stale workers.",
      "The tenant-scoped operation key supports deduplication.",
      "Claim and recovery use matching partial indexes."
    ],
    "improvements": [
      "Centralize tenant authorization and interval validation.",
      "Document that events commit or roll back with their state transition.",
      "Test claim races, rollback, expiry recovery, and idempotent handlers."
    ]
  },
  "modernAlternatives": [
    {
      "current": "Caller-supplied p_tenant_id in SECURITY DEFINER functions",
      "alternative": "Derive tenant identity from a trusted session setting or verify it inside each function.",
      "rationale": "Prevents the API authorization boundary from depending on an untrusted argument.",
      "citations": [
        "WEB-3",
        "WEB-4"
      ]
    },
    {
      "current": "External completion after lease claim",
      "alternative": "Idempotent processing keyed by tenant_id and operation_key.",
      "rationale": "Handles redelivery after worker failure without claiming exactly-once execution.",
      "citations": [
        "WEB-5"
      ]
    }
  ],
  "upgradeSuggestions": [
    {
      "priority": "now",
      "title": "Close the tenant authorization gap",
      "steps": [
        "Add a trusted tenant check or derive the tenant inside all five privileged functions.",
        "Review function ownership and BYPASSRLS attributes.",
        "Add cross-tenant authorization tests."
      ],
      "citations": [
        "WEB-3",
        "WEB-4"
      ]
    },
    {
      "priority": "next",
      "title": "Bound operational inputs",
      "steps": [
        "Validate p_lease in renew_job_lease.",
        "Validate p_limit in release_expired_jobs.",
        "Set an explicit maximum for p_retry_delay and test interval edge cases."
      ],
      "citations": [
        "WEB-4"
      ]
    },
    {
      "priority": "later",
      "title": "Operationalize at-least-once delivery",
      "steps": [
        "Require idempotent handlers keyed by tenant_id and operation_key.",
        "Monitor skipped rows, lease expiry, retries, and dead-letter transitions."
      ],
      "citations": [
        "WEB-1",
        "WEB-5"
      ]
    }
  ],
  "educationalExamples": [
    {
      "title": "Atomic queue claiming",
      "concept": "FOR UPDATE SKIP LOCKED",
      "explanation": "Lock eligible rows, skip rows held by other workers, and update the locked candidates in the same transaction.",
      "code": "BEGIN;\nWITH picked AS MATERIALIZED (\n  SELECT id FROM app.jobs\n  WHERE tenant_id = $1 AND state = 'pending'\n  ORDER BY available_at, id\n  FOR UPDATE SKIP LOCKED\n  LIMIT $2\n)\nUPDATE app.jobs j\nSET state = 'running'\nFROM picked p\nWHERE j.id = p.id;\nCOMMIT;",
      "language": "sql",
      "citations": [
        "WEB-1",
        "WEB-2"
      ]
    },
    {
      "title": "Tenant-safe privileged function check",
      "concept": "Authorization independent of caller arguments",
      "explanation": "A privileged function should reject a tenant argument that differs from trusted session context before changing rows.",
      "code": "IF p_tenant_id IS NULL\n   OR p_tenant_id <> app.current_tenant_id() THEN\n  RAISE EXCEPTION 'unauthorized'\n    USING ERRCODE = '42501';\nEND IF;",
      "language": "sql",
      "citations": [
        "WEB-3",
        "WEB-4"
      ]
    }
  ],
  "generatedAt": "2026-08-12T14:48:53.252Z",
  "sources": [
    {
      "id": "WEB-1",
      "title": "PostgreSQL 17 SELECT",
      "url": "https://www.postgresql.org/docs/17/sql-select.html",
      "publisher": "postgresql.org",
      "kind": "official-doc",
      "summary": "Current evidence retrieved by Luna web research.",
      "relevance": "Supplemental evidence used to verify current practice.",
      "official": true,
      "publishedAt": null
    },
    {
      "id": "WEB-2",
      "title": "PostgreSQL 17 Explicit Locking",
      "url": "https://www.postgresql.org/docs/17/explicit-locking.html",
      "publisher": "postgresql.org",
      "kind": "official-doc",
      "summary": "Current evidence retrieved by Luna web research.",
      "relevance": "Supplemental evidence used to verify current practice.",
      "official": true,
      "publishedAt": null
    },
    {
      "id": "WEB-3",
      "title": "PostgreSQL 17 Row Security Policies",
      "url": "https://www.postgresql.org/docs/17/ddl-rowsecurity.html",
      "publisher": "postgresql.org",
      "kind": "official-doc",
      "summary": "Current evidence retrieved by Luna web research.",
      "relevance": "Supplemental evidence used to verify current practice.",
      "official": true,
      "publishedAt": null
    },
    {
      "id": "WEB-4",
      "title": "PostgreSQL 17 CREATE FUNCTION",
      "url": "https://www.postgresql.org/docs/17/sql-createfunction.html",
      "publisher": "postgresql.org",
      "kind": "official-doc",
      "summary": "Current evidence retrieved by Luna web research.",
      "relevance": "Supplemental evidence used to verify current practice.",
      "official": true,
      "publishedAt": null
    },
    {
      "id": "WEB-5",
      "title": "PostgreSQL 17 PL/pgSQL Transaction Management",
      "url": "https://www.postgresql.org/docs/17/plpgsql-transactions.html",
      "publisher": "postgresql.org",
      "kind": "official-doc",
      "summary": "Current evidence retrieved by Luna web research.",
      "relevance": "Supplemental evidence used to verify current practice.",
      "official": true,
      "publishedAt": null
    }
  ]
}
