Oh, here's a simpler reproducer:
create or replace function foo (out schemaname text, out relname text)
returns setof record language sql
as $$
select nspname, relname from pg_class c join pg_namespace n
on (n.oid = relnamespace)
order by 1
$$;
select * from foo();
It doesn't fail without the ORDER BY, suggesting that the problem
is localized in failing to handle the case where a sort key
column needs to be coerced.
regards, tom lane