Query algebra: null handling, lineage checks, and aggregation results that differ from the specification
維護者通常 5 天內回覆
還沒有人認領這個 Issue。
評估
- 難度
- 5/5
- 預估耗時
- 一週以上
- 新手友好度
- 25/100
- Issue 類型
- 缺陷
- 描述清晰度
- 描述清楚
- 活躍度
- 活躍
研究方向
Start with src/datajoint/condition.py, src/datajoint/expression.py, and src/datajoint/lineage.py, then reproduce the sketches as failing integration tests under tests/integration/. The issue identifies fixes for null handling, lineage validation, aggregation, unions, and operand compatibility, with referenced pull requests and reproductions such as #1660, #1661, #1663, #1708, and #1747. A focused contribution should pick one checklist item, add its regression test, implement the stated behavior, and verify the relevant integration tests.
由索引模型根據 Issue 內容生成。
描述
Every query expression should return an entity set: rows identified by a primary key that is never null, operands matched only on attributes that share a lineage, A & c and A - c dividing A between them, and A.aggr(B, ...) returning one row per row of A with a count of zero where nothing matches. The docs state this as algebraic closure (Explanation, "Query Algebra", section "Algebraic Closure"; the Primary Keys specification, opening paragraph). Pipelines depend on it in places where their authors never write a query: populate finds its work as key_source - target (src/datajoint/autopopulate.py:468), and deletes, progress counts, and summaries are built from the same operators. The first eight items below return wrong rows or a null in a key, and raise no error.
This review read origin/master at b2994e5e and ran none of it. An item that cites an existing issue has a reproduction there. The other items that return wrong results carry a sketch, to be turned into a failing test before any fix. Line numbers are at b2994e5e; paths are under src/datajoint/ and tests/integration/ unless stated.
Tables used in the sketches
The nulls come from a nullable foreign key.
@schema
class Subject(dj.Entry):
definition = """
subject_id : int32
---
weight : int32
"""
@schema
class Session(dj.Entry):
definition = """
session_id : int32
---
-> [nullable] Subject
"""
@schema
class Trial(dj.Entry):
definition = """
-> Session
trial_id : int32
"""
Subject.insert([dict(subject_id=1, weight=20), dict(subject_id=2, weight=25)])
Session.insert([dict(session_id=10, subject_id=1),
dict(session_id=11, subject_id=None),
dict(session_id=12, subject_id=1)])
Trial.insert([dict(session_id=10, trial_id=1), dict(session_id=10, trial_id=2)])
Wrong rows or null keys, returned without an error
-
A - cnegates only the first term whencis a mapping, a numpy record, or anAndListwith two or more terms:combine_conditionsemitsNOT (c1)AND(c2)(condition.py:411-412, called at:445,:461,:476).Table - keywith a composite key is this case. The tests onmasternegate one attribute only (test_restriction_values.py:61,:109;test_university.py:97).- Sketch (read, not run):
(Trial - {"session_id": 10, "trial_id": 1}).keys()should return[{"session_id": 10, "trial_id": 2}]; the SQL as written returns[]. - Change: wrap the conjunction before negating. PR #1663 carries the fix and a composite-key test. Compatibility: none in the API; affected queries return different rows.
- Sketch (read, not run):
-
A - Bby a query expression compiles toNOT IN(condition.py:500-503), which follows three-valued logic. A row ofAwhose matched attribute is null is in neitherA & BnorA - B, and one null inB's matched column emptiesA - B.- Sketch (read, not run):
(Subject - Session).keys()should return[{"subject_id": 2}], and(Session - Subject).keys()should return[{"session_id": 11}]; both return[]as written. - Change: merge PR #1663, which compiles the negated form to a correlated
NOT EXISTS(spec text in datajoint/datajoint-docs#307). Compatibility: none in the API; rows change only where a matched attribute is nullable. The PR also warns on MySQL below 8.0.18.
- Sketch (read, not run):
-
dj.U(X) & Aanddj.U(X).aggr(A, ...)keep rows that are null onX, so the result's primary key holds a null andaggrreturns a null group (expression.py:1542-1545,:1600-1606). For a single attribute,len()then disagrees with the fetched rows, becausecount(DISTINCT x)skips nulls (:1198). Reproduced in #1708;test_relation_u.pycovers non-null attributes only.- Sketch:
(dj.U("subject_id") & Session).to_dicts()should return[{"subject_id": 1}]; it also returns{"subject_id": None}. - Change: restrict the operand by
x IS NOT NULLfor each attribute ofX, as #1708 now proposes. PR #1710 implements the earlier proposal, refusing nullable attributes, and needs a decision. Compatibility: breaking for results only, since the null row or group disappears.
- Sketch:
-
dj.U(X) & Aloses itsDISTINCTwhen it is joined, extended, or aggregated._distinctis set on a copy ofA(expression.py:1543) and read only inmake_sql(:162), whilejoinandU.aggrrebuild the query from the operand's tables (:398-445,:1603-1605). A join returns one row per source row under a key that should be unique, and counts are inflated. Reproduced in #1660.- Sketch:
(Subject * (dj.U("subject_id") & Session)).to_dicts()should return one row for subject 1; as written it returns one row per session of subject 1. - Change: merge PR #1662, which keeps such an operand in a subquery. Compatibility: none; duplicate rows and inflated counts disappear.
- Sketch:
-
A + Bnever checks lineage.Union.createcompares key names and secondary overlap only (expression.py:1438-1456), so two unrelated tables whose keys share a name merge into one entity set.lineage.py:11and the Semantic Matching specification ("A + B(Union)") say the check runs. With secondary attributes it runs at fetch, insidemake_sql(:1469-1470). Reproduced in #1747;test_relational_operand.py:199-206pinsIJ + JIas accepted.- Change: call
assert_join_compatibilityinUnion.createand addA.union(B, semantic_check=False), the override thatjoinandrestrictalready have. Compatibility: breaking. A union of operands with different or absent lineage raises until the override is passed; warn for one release first.
- Change: call
-
join(left=True, allow_nullable_pk=True)is public and returns a primary key that contains null (expression.py:343,:359-363,:385-387;heading.py:735-736). Its only caller isAggregation.create(expression.py:1367). Reproduced in #1749.- Sketch:
Session.join(Trial, left=True, allow_nullable_pk=True).keys()includes{"session_id": 11, "trial_id": None}. - Change: move the bypass to a private helper used by
Aggregation.create. Compatibility: deprecation path for callers that pass the keyword.
- Sketch:
-
dj.U(X).aggr(B, ...)aggregates the wrong rows whenBis a union or an aggregation. It copiesB's tables, joins, and restriction (expression.py:1600-1606), so a union loses its second operand and an aggregation loses itsGROUP BY. Only adj.Topoperand is wrapped (:1596-1597), while the regularaggrwraps such groups (:1362-1363,:412-418). Reproduced in #1661.- Change: merge PR #1733. Compatibility: none; affected queries return the documented value or stop raising SQL errors.
-
A.aggr(B, n="count(*)")reports 1 for a row ofAwith no match, because the left join pads one row andcount(*)counts it (expression.py:691,:1367). The method's docstring describes the same call as keeping subjects "with 0 sessions" (:677-679). Reproduced in #1709. The tests countchild_id(test_aggr_left_join.py:117), so none pins the wrong value.- Sketch:
Session.aggr(Trial, n="count(*)")should given = 0for sessions 11 and 12; it gives 1. - Change: when all rows are kept, count a marker column added to
B's subquery.B's key can lie wholly insideA, which leavesBno column of its own to count. Compatibility: none in the API;count(*)changes from 1 to 0 for unmatched rows.
- Sketch:
Checks that are skipped, deferred, or raised as the wrong error
-
A missing
~lineagetable turns the lineage check into a logged warning, and the operator then matches on names alone (condition.py:276-282).lineage_table_existsreads any exception as "no table" (lineage.py:82-87). The Semantic Matching specification documents the fallback ("Missing Lineage Handling").- Sketch (read, not run): in a schema without
~lineageholding two tables that each declare their ownid,A * Bjoins onidand logs a warning; it should raise. - Change: raise when the operands share an attribute name and lineage is unavailable, unless
semantic_check=False.rebuild_lineage()must work on PostgreSQL first (#1641, PR #1664). Compatibility: breaking for schemas that have no~lineagetable; keep the warning for one release and say in it that the next release raises.
- Sketch (read, not run): in a schema without
-
A & Bwith no shared attributes runs a query while the expression is built and keeps the answer.make_conditioncallsbool(B)(condition.py:496-498;expression.py:1215-1219), andrestrictstoresTrueorFalse(expression.py:256-257,:275). The Query Algebra specification says expressions run when data is fetched (§1.3). PR #1663 keeps this branch.- Sketch (read, not run): build
q = Subject & Trialbefore any trial is inserted, then insert a trial:len(q)is still 0 and should be 2. - Change: emit
EXISTS (subquery)orNOT EXISTS (subquery)as the condition. Compatibility: none; an expression held across inserts follows the database.
- Sketch (read, not run): build
-
A.aggr(B, "b_attr")accepts an attribute ofBthat no aggregate function summarizes. The aggregation's heading is the joined heading (expression.py:1370), andprojchecks membership in it (:582,:691). PostgreSQL rejects the query at fetch; MySQL rejects it underONLY_FULL_GROUP_BYand otherwise returns an arbitrary value.- Sketch (read, not run):
Session.aggr(Trial, "trial_id")should raiseDataJointErrorwhen built. - Change: in
QueryExpression.aggr, reject positional attributes that are not in the left operand's heading; the...branch at:685-689already limits itself to them. Compatibility: none for well-defined queries.
- Sketch (read, not run):
-
dj.U("x") & Araises a bareKeyErrorwhenAhas no attributex:set_primary_keyindexes the heading (heading.py:765, called atexpression.py:1544). The Query Algebra specification listsDataJointError(§8.6, §8.7), andU.aggrraises it (expression.py:1592-1594).- Change: make the same check in
U.__and__. Compatibility: none, unless code catchesKeyError.
- Change: make the same check in
-
A & dj.U("x")is accepted and does nothing, whether or notAhasx, andA - dj.U("x")is always empty (condition.py:447-449).test_relation_u.py:25-27pins the no-op.- Change: raise
DataJointErrorfor adj.Uused as a condition. Compatibility: breaking for code that restricts bydj.U;test_ineffective_restrictionchanges.
- Change: raise
-
Three results fail when used as operands. Each is reported, with a fix open. Compatibility: none; each fix turns an error into the documented result.
- Restricting by a union raises
TypeError:condition.py:503passes an argument thatUnion.make_sqldoes not take (expression.py:1458). #1658, #1739; PR #1755, also in PR #1663. - Restricting
dj.U().aggr(...)fails an assertion (expression.py:1384), andlen(dj.U() & A)emitscount(DISTINCT )(:1198). #1580, #1581; PR #1605. - A union on the right of a join with no shared attributes fails the assertion at
expression.py:444::416testsselfwhere it meansother. #1659; PR #1662.
- Restricting by a union raises
Keys, nullability, and lineage reported by result headings
-
Result headings keep the operands'
nullableflags. An attribute padded with nulls byextendor a union keeps its source'snullable=False, and computed and aggregate attributes getnullable=False(heading.py:65,:691-693,:708-756;expression.pynever sets the flag).- Sketch (read, not run):
Session.extend(Subject).heading["weight"].nullableisFalseand should beTrue.Session.extend(Subject).to_arrays()is predicted to fail atexpression.py:1115: a non-nullable integer gets an integer dtype (heading.py:602), and session 11 has no weight. - Change: mark padded and computed attributes nullable in
Heading.joinandHeading.select. #1708 lists the cases, and PR #1710 implements them. Compatibility: none in the API; the dtype of a padded integer column changes toobject.
- Sketch (read, not run):
-
A.proj(dup="(key_attr)")adds the duplicate to the primary key:Heading.selectcopies the source attribute within_key=True(heading.py:680-689;expression.py:546-548,:646). The Query Algebra specification says projection preserves the key (§3.7). The larger key changes which operands determine the result, so a laterextendoraggrcan be refused.test_relational_operand.py:174-175checks names only.- Sketch (read, not run):
Subject.proj(s="(subject_id)").primary_keyshould be["subject_id"]; it is["subject_id", "s"]. - Change: set
in_key=Falseon a duplicate whose source stays selected. Compatibility: breaking only for code that reads the duplicate fromprimary_key.
- Sketch (read, not run):
-
With
semantic_check=False, a shared attribute of the result takes its lineage from the right operand when only the right operand determines the left, or when the attribute is in the right operand's key and secondary on the left (heading.py:741-754). The lineage of a result then depends on which branch of the key rule applied.test_semantic_matching.py:186-193checks the name only.- Sketch (read, not run): for tables
A, keyed onid, andB, keyed on(id, n), that each declare their ownid,A.join(B, semantic_check=False).heading["id"].lineagenamesB; it should nameA. - Change: build every shared attribute's record from the left operand, changing only
in_key. Compatibility: none; only expressions built with the override change.
- Sketch (read, not run): for tables
Public options, ordering, and docstrings
-
aggr(exclude_nonmatching=True)andjoin(left=True)duplicate other operators. The first equals(A & B).aggr(B, ...)(expression.py:651,:664-666,:690; pinned bytest_relational_operand.py:240,:271andtest_university.py:146-152). The second isextend(:498), which the migration guide already recommends (datajoint-docs,how-to/migrate-to-v20.md).- Change: define
exclude_nonmatching=Truein the docstring and in the specification (§5.2) as shorthand for(A & B).aggr(B, ...). Deprecateleft=on the publicjointogether with item 6, and haveextendname itself in its error:Session.extend(Trial)raises "Left join requires the left operand to determine the right operand (A → B)" (:390-395). Compatibility: none for the first; deprecation path forjoin(left=True);test_aggr_regressions.py:132,:182match the substring "left operand to determine" and follow the new text.
- Change: define
-
A & dj.Top(n, order_by)returns an arbitrary subset among ties whenorder_byis not unique:sorting_clausesorders by the given attributes only (expression.py:137-139).- Change: append the primary key as the final sort term. Compatibility: none in the API; results change only among ties.
-
Three docstrings published in the API reference state rules the code does not follow. The
extenddocstring states the determination backward above a correct example (expression.py:469-470): Trial determines Session, because Session's key is in Trial. Therestrictdocstring keeps the pre-2.0 rule that shared attributes must be in a primary key (:217-220), while the code checks lineage (condition.py:284-309). The class docstring omitsextend(expression.py:31).- Change: correct the three docstrings. Compatibility: none. The lineage error that says "Cannot join on attribute" for
&and-is tracked in #1773.
- Change: correct the three docstrings. Compatibility: none. The lineage error that says "Cannot join on attribute" for
Docs that change with this
Paths are under src/ in datajoint/datajoint-docs.
| Page | Section | Change | Item |
|---|---|---|---|
reference/specs/query-algebra.md |
§2.7 Anti-Restriction | State the null rule: a row whose matched attribute is null matches nothing and belongs to A - B (datajoint/datajoint-docs#307) |
2 |
| §4.5 Examples | "Session → Trial … same as Session" is backward: Trial determines Session, and Session * Trial has Trial's key |
20 | |
| §4.6 Left Join | Session.join(Trial, left=True) violates the constraint stated under it; show Trial.extend(Session) |
18, 20 | |
| §5.2, §5.7 | Define exclude_nonmatching; remove the count(pk_attr) note once count(*) returns zero |
8, 18 | |
| §7.2, §7.4, §7.5, §7.7, §13.7 | Add the lineage requirement and the override; delete the row "Overlapping PKs: A's values take precedence"; replace both SQL sketches, which drop one operand's attributes and use NOT IN |
2, 5 | |
| §8.1, §8.2, §8.4, §8.5 | Rows null on a dj.U attribute form no element and no group; dj.U() & table returns no row for an empty table |
3, 14 | |
| "Algebraic Properties" tables (§2.10, §3.7, §4.8, §5.8, §6.5, §7.6) | Add which attributes of the result may be null | 15 | |
| §12 Top | The primary key breaks ties | 19 | |
reference/specs/primary-keys.md |
"Examples", Example 4 | The title says A → B; the body derives B → A | 20 |
| "Non-Commutativity" | A * B and B * A differ in key only when each determines the other and their keys differ; the page says "one direction but not the other" |
20 | |
| "Left Join Constraint" | Session.join(Trial, left=True) # OK is rejected by the library; show Trial.extend(Session), keyed {session_id, trial_num} |
20 | |
| "Bypassing the Left Join Constraint" | Remove the section; its anchor goes | 6 | |
"Universal Set dj.U" |
"all possible values" becomes all non-null value combinations | 3 | |
reference/specs/semantic-matching.md |
"A + B (Union)" |
Add the override | 5 |
| "Universal Set", "Valid Operations" | dj.U() & A is one row if A has any row; the page says "Distinct primary keys of A" |
14 | |
| "Missing Lineage Handling", "Missing Lineage Warning" | Replace the fallback with the error | 9 | |
reference/operators.md |
"Aggregation" | Remove the count(pk_attribute) advice |
8 |
explanation/query-algebra.md |
"Extend" | "primary key is the union of both PKs", stated twice, becomes the join key rule: the key of the operand that determines the other, and the union only when neither does | 20 |
explanation/semantic-matching.md |
"Manual lineage rebuild" | The quoted error, "lineage missing on one side", is one the library no longer raises | 9 |
tutorials/basics/04-queries.ipynb |
"Primary Keys in Join Results" | "Session → Trial … the same primary key as Session" is backward |
20 |
"Aggregation", "The exclude_nonmatching Parameter" |
The SQL equivalent uses an inner JOIN; re-run the cell whose output shows a count of 1 for a subject with no sessions |
8 | |
tutorials/advanced/sql-comparison.ipynb |
"NOT IN — Negative Restriction", summary table | Show NOT EXISTS; retitle the section "Anti-restriction" (its anchor changes) |
2 |
tutorials/basics/01-first-pipeline.ipynb, tutorials/examples/university.ipynb |
count(*) examples |
Re-run; LetterGrade.aggr(Grade, ..., count='COUNT(*)') & 'count > 0' filters nothing until item 8 ships |
8 |
Order: merge the open fixes, then the checks that need a warning release
- Write the failing tests for the items without an existing issue: 1, 2, 9–13, 15–17, 19.
- Merge the open fixes: #1755, #1605, #1733, #1662, then #1663. They overlap: #1755 is the union part of #1663, and #1605 and #1662 both change
__len__. If #1663 waits on the MySQL minimum, take the one-line fix for item 1 on its own, as #1755 did for the union part. - Close the two ways a null reaches a key: #1708 by filtering, with a decision on PR #1710, and #1749.
- Fix #1709 and items 10–12: each changes a wrong result or a wrong error, and none rejects a query that returns the right rows today.
- Ship the breaking checks behind one release of warnings: union lineage with its override (#1747), the
~lineageerror after PR #1664, and item 13. - Correct heading metadata (items 15–17), then the options, tie-breaking, docstrings, and docs (items 18–20).
- 主要語言
- Python
- 星號
- 198
- 分支
- 107
- 平均合併
- 4 天 7 小時
- 30 天內合併 PR
- 12
環境準備
- 提供 Dockerfile 或 Docker Compose 檔案
- 沒有 Pull Request 範本
- 閱讀貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
datajoint/datajoint-python 的其他 Issue
-
bug triage
難度 2/5 1-3 小時 新手友好度 76/100
datajoint/datajoint-python#1775 ·
維護者通常 5 天內回覆
-
MySQL: with use_tls=False, 2.3.6 needs the cryptography package to log in to MySQL 8可能已有人在做 @dimitri-yatsenko 於 5 天前認領。 未關閉bug
難度 2/5 1-3 小時 新手友好度 74/100
datajoint/datajoint-python#1750 ·
維護者通常 5 天內回覆
-
bug
難度 2/5 1-3 小時 新手友好度 78/100
datajoint/datajoint-python#1747 ·
維護者通常 5 天內回覆
-
Reject constant defaults on primary-key attributes可能已有人在做 @godara-alt 於 4 天前認領。 未關閉bug
難度 2/5 1-3 小時 新手友好度 84/100
datajoint/datajoint-python#1712 ·
維護者通常 5 天內回覆
-
Decoding a <blob> value in an unknown format returns None instead of raising an error可能已有人在做 @godara-alt 於 9 天前認領。 未關閉bug
難度 2/5 1-3 小時 新手友好度 78/100
datajoint/datajoint-python#1703 ·
維護者通常 5 天內回覆
查看 datajoint/datajoint-python 的全部 Issue
相似的 Issue
-
[Bug]: test_remote_realpath_uses_argument_vector fails on Windows with Python 3.13+ (ntpath.isabs)可能已有人在做 @gouyu-hou 今天認領。 未關閉triage/confirmed
難度 1/5 1 小時以內 新手友好度 90/100
agentscope-ai/agentscope#4397 ·
維護者通常 2 天內回覆
-
area/profiles area/sessions comp/desktop desktop/chat desktop/sessions P2 type/bug
難度 2/5 1-3 小時 新手友好度 75/100
NousResearch/hermes-agent#161712 ·
維護者通常 1 天內回覆
-
[New Check]: postgresql_flexible_server_public_network_access_disabled可能已有人在做 @pouria-l 今天認領。 未關閉feature-request status/needs-triage
難度 2/5 1-3 小時 新手友好度 78/100
prowler-cloud/prowler#13615 · 1 則留言 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 78/100
SACGF/variantgrid#2941 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 82/100
linkedin/Liger-Kernel#1730 ·
維護者通常 3 天內回覆