Production bug fix stored functions

From CarlosCaPe/octorato · View interactive version

Production bug fix stored functions is an AI agent skill from the GitHub repository CarlosCaPe/octorato. Production Bug Fix in Stored Functions

How to use this skill

Skill file

Production Bug Fix in Stored Functions

What

A disciplined approach to finding, fixing, and validating logic bugs in stored

functions/procedures -- wrong filters, missing predicates, incorrect joins,

or flawed business logic.

Why

A bug in a stored function is worse than a bug in application code because:

How

Step 1: Root-cause analysis

-- Get the current function definition
SELECT pg_get_functiondef(oid)
FROM pg_proc
WHERE proname = 'get_feature_flag_value_or_list'
  AND pronamespace = 'feature_flags'::regnamespace;

Read the logic line by line. Common bug patterns:

Step 2: Write a test query that proves the bug

-- Before fix: returns inactive flags (bug)
SELECT * FROM feature_flags.get_feature_flag_value_or_list('MyFlag');
-- Returns rows where Active = false (should not!)

-- Expected: only active flags
SELECT * FROM feature_flags."FeatureFlags"
WHERE "FlagName" = 'MyFlag' AND "Active" = true;

Step 3: Fix with CREATE OR REPLACE

CREATE OR REPLACE FUNCTION feature_flags.get_feature_flag_value_or_list(
    p_flag_name text
)
RETURNS TABLE(...) AS $$
BEGIN
    RETURN QUERY
    SELECT ...
    FROM feature_flags."FeatureFlags" f
    WHERE f."FlagName" = p_flag_name
      AND f."Active" = true;  -- THE FIX: was missing
END;
$$ LANGUAGE plpgsql;

Step 4: Validate the fix

-- After fix: only active flags returned
SELECT * FROM feature_flags.get_feature_flag_value_or_list('MyFlag');
-- Should return 0 rows for inactive flags

-- Regression check: existing behavior preserved for active flags
SELECT * FROM feature_flags.get_feature_flag_value_or_list('ActiveFlag');
-- Should still return expected rows

Step 5: Document in CLOSURE_NOTE

## Bug Details
- **Function**: feature_flags.get_feature_flag_value_or_list
- **Bug**: Missing `AND "Active" = true` predicate
- **Impact**: Returned inactive feature flags to all callers
- **Fix**: Added `Active` filter to WHERE clause
- **Root cause**: Original function copied from a different context
  where all records were assumed active

When to Use

Where We Used It

by Active column, returning inactive feature flags to all callers

Related Skills

Gotchas

re-grant after the fix (PG 16 docs: sql-createfunction.html).

Note: you cannot change the return type with OR REPLACE -- you must

DROP and recreate the function in that case

1. The bug is fixed (negative case)

2. Existing behavior is preserved (positive case)


Category: Reliability | Origin:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.