Query algebra: null handling, lineage checks, and aggregation results that differ from the specification

未關閉
#1,766 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 5 天內回覆

還沒有人認領這個 Issue。

評估

難度
5/5
預估耗時
一週以上
新手友好度
25/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
python, sql

研究方向

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

  1. A - c negates only the first term when c is a mapping, a numpy record, or an AndList with two or more terms: combine_conditions emits NOT (c1)AND(c2) (condition.py:411-412, called at :445, :461, :476). Table - key with a composite key is this case. The tests on master negate 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.
  2. A - B by a query expression compiles to NOT IN (condition.py:500-503), which follows three-valued logic. A row of A whose matched attribute is null is in neither A & B nor A - B, and one null in B's matched column empties A - 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.
  3. dj.U(X) & A and dj.U(X).aggr(A, ...) keep rows that are null on X, so the result's primary key holds a null and aggr returns a null group (expression.py:1542-1545, :1600-1606). For a single attribute, len() then disagrees with the fetched rows, because count(DISTINCT x) skips nulls (:1198). Reproduced in #1708; test_relation_u.py covers 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 NULL for each attribute of X, 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.
  4. dj.U(X) & A loses its DISTINCT when it is joined, extended, or aggregated. _distinct is set on a copy of A (expression.py:1543) and read only in make_sql (:162), while join and U.aggr rebuild 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.
  5. A + B never checks lineage. Union.create compares 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:11 and the Semantic Matching specification ("A + B (Union)") say the check runs. With secondary attributes it runs at fetch, inside make_sql (:1469-1470). Reproduced in #1747; test_relational_operand.py:199-206 pins IJ + JI as accepted.

    • Change: call assert_join_compatibility in Union.create and add A.union(B, semantic_check=False), the override that join and restrict already have. Compatibility: breaking. A union of operands with different or absent lineage raises until the override is passed; warn for one release first.
  6. 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 is Aggregation.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.
  7. dj.U(X).aggr(B, ...) aggregates the wrong rows when B is a union or an aggregation. It copies B's tables, joins, and restriction (expression.py:1600-1606), so a union loses its second operand and an aggregation loses its GROUP BY. Only a dj.Top operand is wrapped (:1596-1597), while the regular aggr wraps 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.
  8. A.aggr(B, n="count(*)") reports 1 for a row of A with no match, because the left join pads one row and count(*) 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 count child_id (test_aggr_left_join.py:117), so none pins the wrong value.

    • Sketch: Session.aggr(Trial, n="count(*)") should give n = 0 for 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 inside A, which leaves B no column of its own to count. Compatibility: none in the API; count(*) changes from 1 to 0 for unmatched rows.

Checks that are skipped, deferred, or raised as the wrong error

  1. A missing ~lineage table turns the lineage check into a logged warning, and the operator then matches on names alone (condition.py:276-282). lineage_table_exists reads 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 ~lineage holding two tables that each declare their own id, A * B joins on id and 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 ~lineage table; keep the warning for one release and say in it that the next release raises.
  2. A & B with no shared attributes runs a query while the expression is built and keeps the answer. make_condition calls bool(B) (condition.py:496-498; expression.py:1215-1219), and restrict stores True or False (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 & Trial before any trial is inserted, then insert a trial: len(q) is still 0 and should be 2.
    • Change: emit EXISTS (subquery) or NOT EXISTS (subquery) as the condition. Compatibility: none; an expression held across inserts follows the database.
  3. A.aggr(B, "b_attr") accepts an attribute of B that no aggregate function summarizes. The aggregation's heading is the joined heading (expression.py:1370), and proj checks membership in it (:582, :691). PostgreSQL rejects the query at fetch; MySQL rejects it under ONLY_FULL_GROUP_BY and otherwise returns an arbitrary value.

    • Sketch (read, not run): Session.aggr(Trial, "trial_id") should raise DataJointError when built.
    • Change: in QueryExpression.aggr, reject positional attributes that are not in the left operand's heading; the ... branch at :685-689 already limits itself to them. Compatibility: none for well-defined queries.
  4. dj.U("x") & A raises a bare KeyError when A has no attribute x: set_primary_key indexes the heading (heading.py:765, called at expression.py:1544). The Query Algebra specification lists DataJointError (§8.6, §8.7), and U.aggr raises it (expression.py:1592-1594).

    • Change: make the same check in U.__and__. Compatibility: none, unless code catches KeyError.
  5. A & dj.U("x") is accepted and does nothing, whether or not A has x, and A - dj.U("x") is always empty (condition.py:447-449). test_relation_u.py:25-27 pins the no-op.

    • Change: raise DataJointError for a dj.U used as a condition. Compatibility: breaking for code that restricts by dj.U; test_ineffective_restriction changes.
  6. 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:503 passes an argument that Union.make_sql does not take (expression.py:1458). #1658, #1739; PR #1755, also in PR #1663.
    • Restricting dj.U().aggr(...) fails an assertion (expression.py:1384), and len(dj.U() & A) emits count(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: :416 tests self where it means other. #1659; PR #1662.

Keys, nullability, and lineage reported by result headings

  1. Result headings keep the operands' nullable flags. An attribute padded with nulls by extend or a union keeps its source's nullable=False, and computed and aggregate attributes get nullable=False (heading.py:65, :691-693, :708-756; expression.py never sets the flag).

    • Sketch (read, not run): Session.extend(Subject).heading["weight"].nullable is False and should be True. Session.extend(Subject).to_arrays() is predicted to fail at expression.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.join and Heading.select. #1708 lists the cases, and PR #1710 implements them. Compatibility: none in the API; the dtype of a padded integer column changes to object.
  2. A.proj(dup="(key_attr)") adds the duplicate to the primary key: Heading.select copies the source attribute with in_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 later extend or aggr can be refused. test_relational_operand.py:174-175 checks names only.

    • Sketch (read, not run): Subject.proj(s="(subject_id)").primary_key should be ["subject_id"]; it is ["subject_id", "s"].
    • Change: set in_key=False on a duplicate whose source stays selected. Compatibility: breaking only for code that reads the duplicate from primary_key.
  3. 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-193 checks the name only.

    • Sketch (read, not run): for tables A, keyed on id, and B, keyed on (id, n), that each declare their own id, A.join(B, semantic_check=False).heading["id"].lineage names B; it should name A.
    • Change: build every shared attribute's record from the left operand, changing only in_key. Compatibility: none; only expressions built with the override change.

Public options, ordering, and docstrings

  1. aggr(exclude_nonmatching=True) and join(left=True) duplicate other operators. The first equals (A & B).aggr(B, ...) (expression.py:651, :664-666, :690; pinned by test_relational_operand.py:240, :271 and test_university.py:146-152). The second is extend (:498), which the migration guide already recommends (datajoint-docs, how-to/migrate-to-v20.md).

    • Change: define exclude_nonmatching=True in the docstring and in the specification (§5.2) as shorthand for (A & B).aggr(B, ...). Deprecate left= on the public join together with item 6, and have extend name 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 for join(left=True); test_aggr_regressions.py:132, :182 match the substring "left operand to determine" and follow the new text.
  2. A & dj.Top(n, order_by) returns an arbitrary subset among ties when order_by is not unique: sorting_clauses orders 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.
  3. Three docstrings published in the API reference state rules the code does not follow. The extend docstring states the determination backward above a correct example (expression.py:469-470): Trial determines Session, because Session's key is in Trial. The restrict docstring 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 omits extend (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.

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

  1. Write the failing tests for the items without an existing issue: 1, 2, 9–13, 15–17, 19.
  2. 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.
  3. Close the two ways a null reaches a key: #1708 by filtering, with a decision on PR #1710, and #1749.
  4. 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.
  5. Ship the breaking checks behind one release of warnings: union lineage with its override (#1747), the ~lineage error after PR #1664, and item 13.
  6. 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 範本
  • 閱讀貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

datajoint/datajoint-python 的其他 Issue

查看 datajoint/datajoint-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。