cockroachdb / cockroachdb/cockroach
opt: treat foreign keys with pending deferred checks as not valid
- Dominant language
- Go
- Stars
- 32.5k
- Forks
- 4.1k
- PR merge metrics
- PR metrics pending
Description
Part of the deferrable-constraints work (#31632).
**Is your feature request related to a problem? Please describe.**
When a foreign-key check is deferred to transaction commit (`DEFERRABLE INITIALLY DEFERRED` semantics), the referencing data may transiently violate the constraint between the mutation and COMMIT. The optimizer currently assumes every validated FK holds at all times, and exploits that assumption in ways that would produce wrong results mid-transaction once deferral exists:
- FK-based join elimination (`pkg/sql/opt/norm/multiplicity_builder.go`) can remove a join against the parent table on the grounds that every child row has a match.
- FK-based filter/join derivation (`pkg/sql/opt/xform/join_funcs.go`) is similarly only sound once the pending checks pass.
A query planned (or a cached plan reused) inside a transaction with a pending deferred check could then return rows as if the constraint held — e.g. a join eliminated against a parent row that has not been inserted yet.
**Describe the solution you'd like**
- While a transaction has a pending deferred check for a foreign key, planning must treat that FK as not valid — per table and per constraint, analogous to unvalidated constraints — suppressing the optimizations above.
- Plan caching must respect this: deferral state is transaction-local, but memos outlive the statement that built them (prepared statements, the node-global query cache). A memo built under one set of pending deferred checks must not be reused under another, and memos built while checks are pending should not churn the shared query cache entries that other sessions rely on.
- The insert fast path runs its FK checks inline in the insert batch and cannot postpone them, so it must be avoided for statements whose checks are deferred.
Jira issue: CRDB-67828
Contributor guide
Assessment
This issue has not been assessed yet.