PostgreSQL: restrict a GUC variable to only be set in proconfig? If a C extension defines a custom GUC variable, is there any combination of GUC "context","source","flags", etc., that can be used to make the system only allow it to be set from the SET (i.e. proconfig) attribute of a function declaration, and not from an ordinary SET command?

Or, is there any way for a check or assign hook for that variable to tell whether the assignment is coming from a proconfig and otherwise reject it?
There's no flag for it, though it's an interesting idea.

If proconfig is non-null then the security-definer function call path fmgr_security_definer is invoked. Interestingly this means that using function-level SET has a higher overhead, which I didn't expect. That path can be entered if a fmgr hook is needed or if the function is actually SECURITY DEFINER so you can't use that alone for testing how a var is set.

Applying proconfig creates a new GUC nesting level with NewGUCNestLevel then applies the GUC array with ProcessGUCArray, passing flags PGC_USERSET (for non-superusers) and PGC_S_SESSION. Those are the same flags passed to a normal SET so it doesn't look like there's any information cleanly available to GUC callbacks to tell if they're called in this context.

However:

It looks like you can hook function entry/exit in the fmgr. See FmgrHookIsNeeded, needs_fmgr_hook and fmgr_hook. A demonstration of use of the fmgr hook infrastructure can be found in contrib/sepgsql. This would let you apply custom GUCs that're otherwise defined as not settable at session level. You couldn't put them in proconfig though, since the fmgr will try to apply them and fail; you'd have to store them elsewhere. You can't apply them and remove them from the proconfig array because it's cached and you really don't want to go modifying things returned from the syscache. Anyway, the fmgr hook is fired just after GUCs are applied.

I'd look into doing it with a fmgr hook.