Snapshot leak warning with lo_export in subtransaction
Heikki Linnakangas <hlinnaka@iki.fi>
From: Heikki Linnakangas <hlinnaka@iki.fi>
To: Pg Bugs <pgsql-bugs@postgresql.org>
Cc: Andrew B <pgsql.20.drkshadow@spamgourmet.com>
Date: 2021-09-27T10:55:00Z
Lists: pgsql-bugs
Attachments
- 0001-Fix-snapshot-reference-leak-if-lo_export-fails.patch (text/x-patch)
Hi,
Andrew B reported this warning off-list:
postgres=# SELECT lo_create(41174);
lo_create
-----------
41174
(1 row)
postgres=# DO $$
BEGIN
PERFORM lo_export(41174, '/invalid/path');
EXCEPTION
WHEN others THEN RAISE NOTICE 'error: %', sqlerrm;
END;
$$;
NOTICE: error: could not create server file "/invalid/path": No such
file or directory
WARNING: Snapshot reference leak: Snapshot 0x5634afd61cb8 still referenced
DO
The code in be_lo_export does this:
>
> CreateFSContext();
>
> /*
> * open the inversion object (no need to test for failure)
> */
> lobj = inv_open(lobjId, INV_READ, fscxt);
>
> /*
> * open the file to be written to
> *
> ...
And inv_open does this:
> /* OK to create a descriptor */
> retval = (LargeObjectDesc *) MemoryContextAlloc(mcxt,
> sizeof(LargeObjectDesc));
> retval->id = lobjId;
> retval->subid = GetCurrentSubTransactionId();
> retval->offset = 0;
> retval->flags = descflags;
>
> /*
> * We must register the snapshot in TopTransaction's resowner, because it
> * must stay alive until the LO is closed rather than until the current
> * portal shuts down. Do this last to avoid uselessly leaking the
> * snapshot if an error is thrown above.
> */
> if (snapshot)
> snapshot = RegisterSnapshotOnOwner(snapshot,
> TopTransactionResourceOwner);
> retval->snapshot = snapshot;
So this is pretty clear-cut: if opening the file fails, the snapshot
reference is leaked in TopTransactionResourceOwner. Similarly, the
LargeObjectDesc is leaked in 'fscxt', which is a subcontext of
TopMemoryContext, but that doesn't generate a warning.
I propose the attached patch to fix that. With the patch, we use
CurrentMemoryContext and no resource owner for transient
LargeObjectDescs that are opened and closed in the same function call.
This should be backpatched to all supported versions. This adds an
argument to 'inv_open' function, but I don't think there are extensions
that use the inv_*() functions directly. inv_api.c relies on
close_lo_relation() being called at the end of transaction, so I think
an extension would find it hard to use those functions correctly, anyway.
- Heikki
Commits
-
Fix snapshot reference leak if lo_export fails.
- 8f32afee0179 9.6.24 landed
- 7b55bb892a0b 10.19 landed
- 6bf00da11536 11.14 landed
- 11a399f9cfc3 12.9 landed
- 07070c0082aa 13.5 landed
- 4ebd740cd3f3 14.1 landed
- 6b1b405ebfdc 15.0 landed