BEGIN;

DROP FUNCTION IF EXISTS state_max_bytea(bytea, bytea) CASCADE;
DROP TABLE IF EXISTS crash;

CREATE FUNCTION public.state_max_bytea(st bytea, inp bytea) RETURNS bytea
    LANGUAGE plpgsql
    AS $$
    BEGIN
         if st is null
         then
            return inp;
         elseif st<inp then
            return inp;
         else
            return st;
         end if;
    END;$$;


CREATE AGGREGATE public.max(bytea) (
    SFUNC = public.state_max_bytea,
    STYPE = bytea
);

CREATE TABLE crash(grp int, onecatanddata bool, nullordata bool, data bytea);

INSERT INTO crash VALUES
    -- Create nonnull agg input into *group 1* that had two concats applied,
    -- this primes resvalue = palloc(50) * 2
    (1, true, true, 'Aurea prima sata est aetas, quae vindice nullo'),
    -- Create null agg input, but with previous row's resvalue still set. This results
    -- in transition output of isnull = 1, resvalue = palloc(50) * 2
    (2, false, true, 'Aurea prima sata est aetas, quae vindice nullo'),
    -- Create nonnull agg input, with one concat applied, plpgsql then copies that again.
    -- As prev and cur transition datum are the same (with different nullness), the new
    -- transition value does not get properly reparented.
    (2, false, false, 'Aurea prima sata est aetas, quae vindice nullo'),
    -- Create nonnull agg input, specific value does not matter. We'll now free previous
    -- transition value that's long since been freed by context reset.
    (2, false, true, 'blarg');

SELECT grp,
    max((CASE WHEN onecatanddata THEN data ||'' WHEN nullordata THEN NULL ELSE data END)||'')
FROM crash
GROUP BY grp;

ROLLBACK;
