Skip to content

Fix prepared statement cache invalidation on DEALLOCATE#1235

Open
evkuzin wants to merge 12 commits intoyandex:masterfrom
evkuzin:deallocate_fix
Open

Fix prepared statement cache invalidation on DEALLOCATE#1235
evkuzin wants to merge 12 commits intoyandex:masterfrom
evkuzin:deallocate_fix

Conversation

@evkuzin
Copy link
Contributor

@evkuzin evkuzin commented Feb 5, 2026

When pool_reserve_prepared_statement is enabled, Odyssey tracks which prepared statements have been deployed to each backend connection. However, when a client sends DEALLOCATE ALL, PostgreSQL removes all prepared statements but Odyssey's cache (server->prep_stmts) was not being cleared.

This caused "prepared statement does not exist" errors when:

Client prepares and executes a statement
Client sends DEALLOCATE ALL (e.g., psycopg after ROLLBACK)
Client reuses the same query - Odyssey skips Parse (thinks statement exists), sends only Bind
PostgreSQL returns error since the statement was deallocated
Fix: Detect DEALLOCATE queries and invalidate server->prep_stmts, matching the existing behavior for DISCARD. Handles both simple query protocol and extended query protocol (Parse/Bind).

You can use this script to replicate a bug:

#!/usr/bin/env python3


import sys

try:
    import psycopg
except ImportError:
    print("ERROR: psycopg not installed.")
    sys.exit(1)


def main():
    # Default connection string - connect via Odyssey
    conninfo = sys.argv[1] if len(sys.argv) > 1 else "host=localhost port=5433"
    
    print("=== Odyssey DEALLOCATE ALL Bug Reproducer ===")
    print(f"Connection: {conninfo}")
    print()

    # Reproduce the bug using a temp table (no special permissions needed)
    print("Step 1: Execute prepared statement, DEALLOCATE ALL, then reuse...")
    with psycopg.connect(conninfo, prepare_threshold=0) as conn:
        # Create temp table (exists only for this session)
        conn.execute("CREATE TEMP TABLE _deallocate_test (id int PRIMARY KEY, val text)")
        conn.execute("INSERT INTO _deallocate_test VALUES (1, 'test')")
        conn.commit()
        
        with conn.cursor() as cur:
            # First use - creates prepared statement on backend
            cur.execute("SELECT * FROM _deallocate_test WHERE id = %s", (1,))
            row = cur.fetchone()
            print(f"  First query OK: {row}")

            # Send DEALLOCATE ALL (this is what psycopg does after ROLLBACK)
            print("  Sending DEALLOCATE ALL...")
            conn.execute("DEALLOCATE ALL")

            # Clear psycopg's internal prepared statement cache
            conn._prepared.clear()

            # Reuse the same query - this triggers the bug
            try:
                cur.execute("SELECT * FROM _deallocate_test WHERE id = %s", (1,))
                row = cur.fetchone()
                print(f"  Second query OK: {row}")
                print()
                print("=== RESULT: Bug NOT reproduced (fix is in place) ===")
                return 0
            except psycopg.errors.InvalidSqlStatementName as e:
                print(f"  ERROR: {e}")
                print()
                print("=== RESULT: BUG REPRODUCED! ===")
                print("Odyssey did not clear prep_stmts after DEALLOCATE ALL")
                return 1


if __name__ == "__main__":
    sys.exit(main())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant