Oracle 12cR2 / ORA-04031 - Unable to allocate xx bytes of shared memory (Shared Pool) (Hard Parse & Parallel Queries)
With only that information, I can give only the below.
Yes, I am aware that the bug is fixed in 12.2 and you wrote in the title the database was 12.2 (but no other proof).
ORA-04031: (&quot;shared Pool&quot;..&quot;KKSSP^nnnn&quot;,&quot;kglseshtSegs&quot;) (Doc ID 2151847.1)

SOLUTION

Download and apply Patch 23315153.

In case the needed patch is not available, please open a Service
Request with Oracle Support.

The fix is included in Oracle release 12.2.

The bug has no workaround.