Skip to content

Commit 42441f5

Browse files
Merge pull request #1302 from datajoint/claude/pk-rules
Implement primary key rules for joins
2 parents 7d855b7 + 85ee0f8 commit 42441f5

File tree

6 files changed

+750
-47
lines changed

6 files changed

+750
-47
lines changed

docs/src/design/pk-rules-spec.md

Lines changed: 318 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,318 @@
1+
# Primary Key Rules in Relational Operators
2+
3+
In DataJoint, the result of each query operator produces a valid **entity set** with a well-defined **entity type** and **primary key**. This section specifies how the primary key is determined for each relational operator.
4+
5+
## General Principle
6+
7+
The primary key of a query result identifies unique entities in that result. For most operators, the primary key is preserved from the left operand. For joins, the primary key depends on the functional dependencies between the operands.
8+
9+
## Integration with Semantic Matching
10+
11+
Primary key determination is applied **after** semantic compatibility is verified. The evaluation order is:
12+
13+
1. **Semantic Check**: `assert_join_compatibility()` ensures all namesakes are homologous (same lineage)
14+
2. **PK Determination**: The "determines" relationship is computed using attribute names
15+
3. **Left Join Validation**: If `left=True`, verify A → B
16+
17+
This ordering is important because:
18+
- After semantic matching passes, namesakes represent semantically equivalent attributes
19+
- The name-based "determines" check is therefore semantically valid
20+
- Attribute names in the context of a semantically-valid join represent the same entity
21+
22+
The "determines" relationship uses attribute **names** (not lineages directly) because:
23+
- Lineage ensures namesakes are homologous
24+
- Once verified, checking by name is equivalent to checking by semantic identity
25+
- Aliased attributes (same lineage, different names) don't participate in natural joins anyway
26+
27+
## Notation
28+
29+
In the examples below, `*` marks primary key attributes:
30+
- `A(x*, y*, z)` means A has primary key `{x, y}` and secondary attribute `z`
31+
- `A → B` means "A determines B" (defined below)
32+
33+
### Rules by Operator
34+
35+
| Operator | Primary Key Rule |
36+
|----------|------------------|
37+
| `A & B` (restriction) | PK(A) — preserved from left operand |
38+
| `A - B` (anti-restriction) | PK(A) — preserved from left operand |
39+
| `A.proj(...)` (projection) | PK(A) — preserved from left operand |
40+
| `A.aggr(B, ...)` (aggregation) | PK(A) — preserved from left operand |
41+
| `A.extend(B)` (extension) | PK(A) — requires A → B |
42+
| `A * B` (join) | Depends on functional dependencies (see below) |
43+
44+
### Join Primary Key Rule
45+
46+
The join operator requires special handling because it combines two entity sets. The primary key of `A * B` depends on the **functional dependency relationship** between the operands.
47+
48+
#### Definitions
49+
50+
**A determines B** (written `A → B`): Every attribute in PK(B) is in A.
51+
52+
```
53+
A → B iff ∀b ∈ PK(B): b ∈ A
54+
```
55+
56+
Since `PK(A) ∪ secondary(A) = all attributes in A`, this is equivalent to saying every attribute in B's primary key exists somewhere in A (as either a primary key or secondary attribute).
57+
58+
Intuitively, `A → B` means that knowing A's primary key is sufficient to determine B's primary key through the functional dependencies implied by A's structure.
59+
60+
**B determines A** (written `B → A`): Every attribute in PK(A) is in B.
61+
62+
```
63+
B → A iff ∀a ∈ PK(A): a ∈ B
64+
```
65+
66+
#### Join Primary Key Algorithm
67+
68+
For `A * B`:
69+
70+
| Condition | PK(A * B) | Attribute Order |
71+
|-----------|-----------|-----------------|
72+
| A → B | PK(A) | A's attributes first |
73+
| B → A (and not A → B) | PK(B) | B's attributes first |
74+
| Neither | PK(A) ∪ PK(B) | PK(A) first, then PK(B) − PK(A) |
75+
76+
When both `A → B` and `B → A` hold, the left operand takes precedence (use PK(A)).
77+
78+
#### Examples
79+
80+
**Example 1: B → A**
81+
```
82+
A: x*, y*
83+
B: x*, z*, y (y is secondary in B, so z → y)
84+
```
85+
- A → B? PK(B) = {x, z}. Is z in PK(A) or secondary in A? No (z not in A). **No.**
86+
- B → A? PK(A) = {x, y}. Is y in PK(B) or secondary in B? Yes (secondary). **Yes.**
87+
- Result: **PK(A * B) = {x, z}** with B's attributes first.
88+
89+
**Example 2: Both directions (bijection-like)**
90+
```
91+
A: x*, y*, z (z is secondary in A)
92+
B: y*, z*, x (x is secondary in B)
93+
```
94+
- A → B? PK(B) = {y, z}. Is z in PK(A) or secondary in A? Yes (secondary). **Yes.**
95+
- B → A? PK(A) = {x, y}. Is x in PK(B) or secondary in B? Yes (secondary). **Yes.**
96+
- Both hold, prefer left operand: **PK(A * B) = {x, y}** with A's attributes first.
97+
98+
**Example 3: Neither direction**
99+
```
100+
A: x*, y*
101+
B: z*, x (x is secondary in B)
102+
```
103+
- A → B? PK(B) = {z}. Is z in PK(A) or secondary in A? No. **No.**
104+
- B → A? PK(A) = {x, y}. Is y in PK(B) or secondary in B? No (y not in B). **No.**
105+
- Result: **PK(A * B) = {x, y, z}** (union) with A's attributes first.
106+
107+
**Example 4: A → B (subordinate relationship)**
108+
```
109+
Session: session_id*
110+
Trial: session_id*, trial_num* (references Session)
111+
```
112+
- A → B? PK(Trial) = {session_id, trial_num}. Is trial_num in PK(Session) or secondary? No. **No.**
113+
- B → A? PK(Session) = {session_id}. Is session_id in PK(Trial)? Yes. **Yes.**
114+
- Result: **PK(Session * Trial) = {session_id, trial_num}** with Trial's attributes first.
115+
116+
**Join primary key determination**:
117+
- `A * B` where `A → B`: result has PK(A)
118+
- `A * B` where `B → A` (not `A → B`): result has PK(B), B's attributes first
119+
- `A * B` where both `A → B` and `B → A`: result has PK(A) (left preference)
120+
- `A * B` where neither direction: result has PK(A) ∪ PK(B)
121+
- Verify attribute ordering matches primary key source
122+
- Verify non-commutativity: `A * B` vs `B * A` may differ in PK and order
123+
124+
### Design Tradeoff: Predictability vs. Minimality
125+
126+
The join primary key rule prioritizes **predictability** over **minimality**. In some cases, the resulting primary key may not be minimal (i.e., it may contain functionally redundant attributes).
127+
128+
**Example of non-minimal result:**
129+
```
130+
A: x*, y*
131+
B: z*, x (x is secondary in B, so z → x)
132+
```
133+
134+
The mathematically minimal primary key for `A * B` would be `{y, z}` because:
135+
- `z → x` (from B's structure)
136+
- `{y, z} → {x, y, z}` (z gives us x, and we have y)
137+
138+
However, `{y, z}` is problematic:
139+
- It is **not the primary key of either operand** (A has `{x, y}`, B has `{z}`)
140+
- It is **not the union** of the primary keys
141+
- It represents a **novel entity type** that doesn't correspond to A, B, or their natural pairing
142+
143+
This creates confusion: what kind of entity does `{y, z}` identify?
144+
145+
**The simplified rule produces `{x, y, z}`** (the union), which:
146+
- Is immediately recognizable as "one A entity paired with one B entity"
147+
- Contains A's full primary key and B's full primary key
148+
- May have redundancy (`x` is determined by `z`) but is semantically clear
149+
150+
**Rationale:** Users can always project away redundant attributes if they need the minimal key. But starting with a predictable, interpretable primary key reduces confusion and errors.
151+
152+
### Attribute Ordering
153+
154+
The primary key attributes always appear **first** in the result's attribute list, followed by secondary attributes. When `B → A` (and not `A → B`), the join is conceptually reordered as `B * A` to maintain this invariant:
155+
156+
- If PK = PK(A): A's attributes appear first
157+
- If PK = PK(B): B's attributes appear first
158+
- If PK = PK(A) ∪ PK(B): PK(A) attributes first, then PK(B) − PK(A), then secondaries
159+
160+
### Non-Commutativity
161+
162+
With these rules, join is **not commutative** in terms of:
163+
1. **Primary key selection**: `A * B` may have a different PK than `B * A` when one direction determines but not the other
164+
2. **Attribute ordering**: The left operand's attributes appear first (unless B → A)
165+
166+
The **result set** (the actual rows returned) remains the same regardless of order, but the **schema** (primary key and attribute order) may differ.
167+
168+
### Left Join Constraint
169+
170+
For left joins (`A.join(B, left=True)`), the functional dependency **A → B is required**.
171+
172+
**Why this constraint exists:**
173+
174+
In a left join, all rows from A are retained even if there's no matching row in B. For unmatched rows, B's attributes are NULL. This creates a problem for primary key validity:
175+
176+
| Scenario | PK by inner join rule | Left join problem |
177+
|----------|----------------------|-------------------|
178+
| A → B | PK(A) | ✅ Safe — A's attrs always present |
179+
| B → A | PK(B) | ❌ B's PK attrs could be NULL |
180+
| Neither | PK(A) ∪ PK(B) | ❌ B's PK attrs could be NULL |
181+
182+
**Example of invalid left join:**
183+
```
184+
A: x*, y* PK(A) = {x, y}
185+
B: x*, z*, y PK(B) = {x, z}, y is secondary
186+
187+
Inner join: PK = {x, z} (B → A rule)
188+
Left join attempt: FAILS because z could be NULL for unmatched A rows
189+
```
190+
191+
**Valid left join example:**
192+
```
193+
Session: session_id*, date
194+
Trial: session_id*, trial_num*, stimulus (references Session)
195+
196+
Session.join(Trial, left=True) # OK: Session → Trial
197+
# PK = {session_id}, all sessions retained even without trials
198+
```
199+
200+
**Error message:**
201+
```
202+
DataJointError: Left join requires the left operand to determine the right operand (A → B).
203+
The following attributes from the right operand's primary key are not determined by
204+
the left operand: ['z']. Use an inner join or restructure the query.
205+
```
206+
207+
### Conceptual Note: Left Join as Extension
208+
209+
When `A → B`, the left join `A.join(B, left=True)` is conceptually distinct from the general join operator `A * B`. It is better understood as an **extension** operation rather than a join:
210+
211+
| Aspect | General Join (A * B) | Left Join when A → B |
212+
|--------|---------------------|----------------------|
213+
| Conceptual model | Cartesian product restricted to matching rows | Extend A with attributes from B |
214+
| Row count | May increase, decrease, or stay same | Always equals len(A) |
215+
| Primary key | Depends on functional dependencies | Always PK(A) |
216+
| Relation to projection | Different operation | Variation of projection |
217+
218+
**The extension perspective:**
219+
220+
The operation `A.join(B, left=True)` when `A → B` is closer to **projection** than to **join**:
221+
- It adds new attributes to A (like `A.proj(..., new_attr=...)`)
222+
- It preserves all rows of A
223+
- It preserves A's primary key
224+
- It lacks the Cartesian product aspect that defines joins
225+
226+
DataJoint provides an explicit `extend()` method for this pattern:
227+
228+
```python
229+
# These are equivalent when A → B:
230+
A.join(B, left=True)
231+
A.extend(B) # clearer intent: extend A with B's attributes
232+
```
233+
234+
The `extend()` method:
235+
- Requires `A → B` (raises `DataJointError` otherwise)
236+
- Does not expose `allow_nullable_pk` (that's an internal mechanism)
237+
- Expresses the semantic intent: "add B's attributes to A's entities"
238+
239+
**Relationship to aggregation:**
240+
241+
A similar argument applies to `A.aggr(B, ...)`:
242+
- It preserves A's primary key
243+
- It adds computed attributes derived from B
244+
- It's conceptually a variation of projection with grouping
245+
246+
Both `A.join(B, left=True)` (when A → B) and `A.aggr(B, ...)` can be viewed as **projection-like operations** that extend A's attributes while preserving its entity identity.
247+
248+
### Bypassing the Left Join Constraint
249+
250+
For special cases where the user takes responsibility for handling the potentially nullable primary key, the constraint can be bypassed using `allow_nullable_pk=True`:
251+
252+
```python
253+
# Normally blocked - A does not determine B
254+
A.join(B, left=True) # Error: A → B not satisfied
255+
256+
# Bypass the constraint - user takes responsibility
257+
A.join(B, left=True, allow_nullable_pk=True) # Allowed, PK = PK(A) ∪ PK(B)
258+
```
259+
260+
When bypassed, the resulting primary key is the union of both operands' primary keys (PK(A) ∪ PK(B)). The user must ensure that subsequent operations (such as `GROUP BY` or projection) establish a valid primary key. The parameter name `allow_nullable_pk` reflects the specific issue: primary key attributes from the right operand could be NULL for unmatched rows.
261+
262+
This mechanism is used internally by aggregation (`aggr`) with `keep_all_rows=True`, which resets the primary key via the `GROUP BY` clause.
263+
264+
### Aggregation Exception
265+
266+
`A.aggr(B, keep_all_rows=True)` uses a left join internally but has the **opposite requirement**: **B → A** (the group expression B must have all of A's primary key attributes).
267+
268+
This apparent contradiction is resolved by the `GROUP BY` clause:
269+
270+
1. Aggregation requires B → A so that B can be grouped by A's primary key
271+
2. The intermediate left join `A LEFT JOIN B` would have an invalid PK under the normal left join rules
272+
3. Aggregation internally allows the invalid PK, producing PK(A) ∪ PK(B)
273+
4. The `GROUP BY PK(A)` clause then **resets** the primary key to PK(A)
274+
5. The final result has PK(A), which consists entirely of non-NULL values from A
275+
276+
Note: The semantic check (homologous namesake validation) is still performed for aggregation's internal join. Only the primary key validity constraint is bypassed.
277+
278+
**Example:**
279+
```
280+
Session: session_id*, date
281+
Trial: session_id*, trial_num*, response_time (references Session)
282+
283+
# Aggregation with keep_all_rows=True
284+
Session.aggr(Trial, keep_all_rows=True, avg_rt='avg(response_time)')
285+
286+
# Internally: Session LEFT JOIN Trial (with invalid PK allowed)
287+
# Intermediate PK would be {session_id} ∪ {session_id, trial_num} = {session_id, trial_num}
288+
# But GROUP BY session_id resets PK to {session_id}
289+
# Result: All sessions, with avg_rt=NULL for sessions without trials
290+
```
291+
292+
## Universal Set `dj.U`
293+
294+
`dj.U()` or `dj.U('attr1', 'attr2', ...)` represents the universal set of all possible values and lineages.
295+
296+
### Homology with `dj.U`
297+
Since `dj.U` conceptually contains all possible lineages, its attributes are **homologous to any namesake attribute** in other expressions.
298+
299+
### Valid Operations
300+
301+
```python
302+
# Restriction: promotes a, b to PK; lineage transferred from A
303+
dj.U('a', 'b') & A
304+
305+
# Aggregation: groups by a, b
306+
dj.U('a', 'b').aggr(A, count='count(*)')
307+
```
308+
309+
### Invalid Operations
310+
311+
```python
312+
# Anti-restriction: produces infinite set
313+
dj.U('a', 'b') - A # DataJointError
314+
315+
# Join: deprecated, use & instead
316+
dj.U('a', 'b') * A # DataJointError with migration guidance
317+
```
318+

0 commit comments

Comments
 (0)