supabase/wrappers

`EXPLAIN ANALYZE` crashes the backend for queries with quals

EdMcBane opened this issue · 1 comments

Bug report

EXPLAIN ANALYZE crashes the backend for queries with quals

Running an EXPLAIN ANALYZE query using quals on an fdw table crashes the backend.

To Reproduce

  • deploy helloworld_fdw as per documentation
  • EXPLAIN ANALYZE SELECT * FROM hello WHERE id IS NOT NULL

Removing the qual eliminates the problem; both of these work:

  • EXPLAIN ANALYZE SELECT * FROM hello
  • EXPLAIN ANALYZE SELECT * FROM hello WHERE true

Expected behavior

Query should not crash the backend

System information

  • OS: Linux (PopOs) kernel 6.0.6 x86_64

It looks like supabase_wrappers::scan::get_foreign_plan allocates the scan_clauses that end up in the query plan from the FDW temp memory context (state.tmp_ctx), which appears to be erroneous, as EXPLAIN ANALYZE accesses the plan and its quals well after the context has been reset by the many other calls to temp_ctx.reset.

It appears the plan and quals need to be allocated in the query memory context (the current one when supabase_wrappers::scan::get_foreign_plan is called) to live enough.

I'm wondering whether there are other similar instances due to the extensive use of state.temp_ctx for allocating data returned to pg.

At the moment, changing the code of supabase_wrappers::scan::get_foreign_plan as follows fixes the problem:

#[pg_guard]
pub(super) extern "C" fn get_foreign_plan<W: ForeignDataWrapper>(
    _root: *mut pg_sys::PlannerInfo,
    baserel: *mut pg_sys::RelOptInfo,
    _foreigntableid: pg_sys::Oid,
    _best_path: *mut pg_sys::ForeignPath,
    tlist: *mut pg_sys::List,
    scan_clauses: *mut pg_sys::List,
    outer_plan: *mut pg_sys::Plan,
) -> *mut pg_sys::ForeignScan {
    debug2!("---> get_foreign_plan");
    unsafe {
        let mut state = PgBox::<FdwState<W>>::from_pg((*baserel).fdw_private as _);
        // DO NOT ALLOCATE IN THE TEMP MEMCTX; pg will use the plan later if EXPLAIN ANALYZEing
        // state.tmp_ctx.reset();
        // let mut old_ctx = state.tmp_ctx.set_as_current();

        // make foreign scan plan
        let scan_clauses = pg_sys::extract_actual_clauses(scan_clauses, false);

        // old_ctx.set_as_current();