Key source: restrict-only `key_scope`, scope references in the dependency order, and `populate()` checks

Đang mở
#1,769 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 5 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
30/100
Loại issue
Tính năng
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
python, sql

Hướng nghiên cứu

Start with src/datajoint/autopopulate.py, especially populate(), _populate1(), _populate_distributed(), and progress(), then inspect src/datajoint/dependencies.py and src/datajoint/schemas.py for scope dependencies and ordering. Use the relevant tests in tests/integration/test_autopopulate.py, tests/integration/test_jobs_refresh.py, and tests/schema_uuid.py to reproduce the listed behaviors. Done means each item has a failing test, the key-source and populate() semantics are implemented with the specified compatibility behavior, and the affected documentation matches the new library behavior.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

An auto-populated table (tier Ingest or Compute; the classes dj.Imported and dj.Computed, also exported as dj.Ingest and dj.Compute) should contain one row for each key in its key source: the join of its primary parents' keys, narrowed only by a scope declared with the table. populate() should call make() for the pending keys (the anti-restriction key_source - table) and for no others, and a make() call that returns should have inserted the row for its key. A pipeline author depends on both: an empty pending set then means the table is complete, and every row was computed for a key the declaration admits. #1523 proposes key_scope, which does not exist on master yet (git grep key_scope -- src tests returns nothing), and, as amended on 2026-11-17, deprecates overriding key_source. This issue tracks what that plan leaves open and where populate() departs from the key source today.

Every item is read, not run: it comes from reading master at b2994e5e (v2.3.4-101) and its tests, and line numbers refer to that commit. Each sketch becomes a failing test before the change is made.

Where the key source and populate() disagree

  • A key_source override can drop a parent, change the key, or enlarge the source, and nothing warns. The docstrings invite it (src/datajoint/autopopulate.py:101, :247: "change the scope or granularity of make calls"), and the only guard (:355-363) checks that the override's key attributes exist in the target's heading. Pinned by tests/schema_uuid.py:50: key_source = Topic, a secondary parent, on a table keyed by its own item_id.
    Change: #1523 as amended on 2026-11-17, plus one check in the guard at :355-363: compare the override's primary key with the default join's, and give the stronger warning when they differ. No interim raise, which would break schema_uuid.Item.
    Compatibility: deprecation path (warn in 2.4, raise in 3.0).

    @schema
    class A(dj.Entry):
        definition = "a : int32"
    
    @schema
    class B(dj.Entry):
        definition = "b : int32"
    
    @schema
    class AB(dj.Compute):
        definition = """
        -> A
        -> B
        """
        key_source = A                      # drops parent B
    
        def make(self, key):                # key == {"a": 1}: no b
            self.insert1(dict(key, b=1))
    
    A.insert1(dict(a=1))
    B.insert([dict(b=1), dict(b=2)])
    AB.populate()
    # today, by reading: no warning, one make() call, AB.progress() == (0, 1),
    #   and (a=1, b=2) is never computed
    # expected: 2.4 warns and names the missing key attribute b; 3.0 raises DataJointError
    
  • An unrestricted populate(reserve_jobs=True) runs every queued key without checking it against the key source. _populate_distributed intersects the queue with the key source only inside if restrictions: (autopopulate.py:561-566), and _populate1 checks presence only (:674). A job whose key has left the key source stays queued for stale_timeout (default 3600 s; src/datajoint/jobs.py:436-443, src/datajoint/settings.py:484-485), and with refresh=False it stays with no time bound. test_stale_timeout_zero_means_no_grace_period (tests/integration/test_jobs_refresh.py:171-180) pins the retention. The if restrictions: test came with #1414, the fix for #1413, whose test plan kept the unrestricted path unchanged; this item asks for the unrestricted path to be restricted by the key source too.
    Change: remove the if restrictions: test at :562, so the queue is always restricted by self._jobs_to_do(restrictions). A second membership check beside key in self at :674 would cover a key that leaves after the list is fetched, in both modes, at one query per key.
    Compatibility: none. The change adds one subquery per call; measure it on the key source of #1673.

    @schema
    class Raw(dj.Entry):
        definition = """
        raw_id : int32
        ---
        v : float32
        """
    
    @schema
    class Gated(dj.Compute):                # as in tests/integration/test_jobs_refresh.py:146-159
        definition = """
        -> Raw
        ---
        w : float32
        """
    
        @property
        def key_source(self):               # key_scope once it exists
            return Raw & "v >= 0"
    
        def make(self, key):
            self.insert1(dict(key, w=1.0))
    
    Raw.insert1(dict(raw_id=0, v=1.0))
    Gated.jobs.refresh(delay=-1)            # queues raw_id=0
    Raw.update1(dict(raw_id=0, v=-1.0))     # the key leaves the key source
    Gated.populate(reserve_jobs=True)
    # today, by reading: Gated holds a row for raw_id=0
    # expected: len(Gated()) == 0
    
  • populate() records success when make() returns without inserting its key. _populate1 commits at autopopulate.py:734 and calls jobs.complete(key) at :749 with no check that self & key has a row. A three-part make whose make_compute returns None stops at :322 on the second pass and commits the same way. The AutoPopulate specification §4.2 already states the rule ("make() must insert exactly one row matching the key"). No test covers either path.
    Change: at the end of the try body (after make returns at :699, and after gen.send at :714), raise DataJointError when self & key is empty. The except at :716 then rolls back and records the error. A raise in the else branch would leave the transaction open.
    Compatibility: breaking for a make() that returns to skip a key. Warn for one minor release, then raise.

    @schema
    class Src(dj.Entry):
        definition = "src_id : int32"
    
    @schema
    class Skips(dj.Compute):
        definition = """
        -> Src
        ---
        x : float32
        """
    
        def make(self, key):
            return                          # inserts nothing
    
    Src.insert1(dict(src_id=1))
    Skips.populate()
    # today, by reading: {"success_count": 1, "error_list": []} on every call, and no row
    # expected: DataJointError; with reserve_jobs=True, an error job for src_id=1
    
  • A table named in a scope is not a dependency for the cycle check or for table order. Dependencies.load() builds the graph from primary and foreign keys only (src/datajoint/dependencies.py:163-218, cycle check at :220). A table whose key source restricts by a non-ancestor can therefore precede that table in topo_sort() and Schema.list_tables() (src/datajoint/schemas.py:542-560), and a key source that names the table itself or a descendant is accepted; the Run Computations how-to shows one that subtracts self.
    Change: record the tables a key_scope names in a separate map or a typed edge, read by the cycle check and the order only, and reject a scope that names the table or a descendant. parents(), children(), cascade, and Diagram skip these references, because a computed row stays when its key leaves the scope (test_refresh_keeps_success_records_of_existing_rows, tests/integration/test_jobs_refresh.py:135, assumes it).
    Compatibility: none while cascade ignores the references.

  • #1523's examples put conditions on parents' secondary attributes into the scope (key_scope = 'quality = "good"', {"quality": "good"}) and compute default_key_source & key_scope. Each parent enters the default join as its key projection (autopopulate.py:250-263), so quality is not in the heading. The string form then raises "Attribute quality is not found in query" (src/datajoint/expression.py:258-264) when the key source is built. The mapping form names no attribute of the heading, so it evaluates to true (src/datajoint/condition.py:456-459) and restricts nothing, with no warning. #1561 reports the same silent drop for a mapping that names a hidden attribute; this item adds the key_scope case, where one declared scope governs every populate() of the table.
    Change: amend #1523 and implement this grammar: a condition on key attributes, an entity set (a table or query, such as Session & 'quality = "good"'), the negation of either, or a conjunction of these. Reject at declaration a string or mapping that names a non-key attribute.
    Compatibility: none (unreleased).

  • Job state withholds pending keys from populate(reserve_jobs=True) outside the declaration. jobs.ignore(key) (jobs.py:561-578), a future scheduled_time (autopopulate.py:561), and the priority argument (:567-568) each keep a key out of the run, and refresh() never removes an ignored job (jobs.py:439). Direct populate() computes the same keys (autopopulate.py:468), so the two modes disagree. Pinned by test_populate_exclude_error_and_ignore_jobs (tests/integration/test_autopopulate.py:63-83).
    Change: none in code. The docs state that these are holds on the queue, in effect under reserve_jobs=True only; that a held key stays in key_source - table and in the progress() count; and that a permanent exclusion is declared in key_scope.
    Compatibility: none.

  • An auto-populated table declares without a make(). Schema._decorate_table (schemas.py:271-340) has no check, and NotImplementedError is raised only when populate() calls make (autopopulate.py:305-310). A legacy _make_tuples outranks make (:659), and the Imported and Computed docstrings still require _make_tuples (src/datajoint/user_tables.py:158, :168).
    Change: warn in 2.4 and raise in 3.0 when a declared class defines none of make, the three make_* methods, or _make_tuples. Test cls.make is AutoPopulate.make, since the base class defines make. Exempt classes created by Schema.make_classes (schemas.py:386). The two docstrings are rewritten with the other tier docstrings in #1773.
    Compatibility: deprecation path. Six test classes declare without one, among them tests/schema_alter.py:6 and tests/integration/test_diagram_style.py:60.

  • progress() merges distinct composite keys. It counts COUNT(DISTINCT CONCAT_WS('|', ...)) over the key columns (autopopulate.py:819-820, :828-829), so the string keys ('a|b', 'c') and ('a', 'b|c') count as one: a table with those two pending keys reports (1, 1) where (2, 2) is expected. No test has a key value that contains |. The expression key_source - table is unaffected.
    Change: count the rows of a SELECT DISTINCT over the key columns in a subquery, or use the two-query branch at :794-795 for composite keys.
    Compatibility: none.

    @schema
    class Pair(dj.Entry):
        definition = """
        x : varchar(8)
        y : varchar(8)
        """
    
    @schema
    class PairStat(dj.Compute):
        definition = """
        -> Pair
        ---
        n : int32
        """
    
        def make(self, key):
            self.insert1(dict(key, n=0))
    
    Pair.insert([dict(x="a|b", y="c"), dict(x="a", y="b|c")])
    PairStat.progress()
    # today, by reading: (1, 1)
    # expected: (2, 2)
    

Docs that change with the library

Line numbers refer to datajoint-docs at b68b6cc6.

Wrong today, whatever the library does:

  • Computation Model, "Key Source" (explanation/computation-model.md:97-103): defines the key source as the pending set (key_source = Scan - Segmentation, "all upstream keys not yet in this table") and overrides it with (Scan & 'quality > 0.8') - self. The key source is Scan.proj(), the pending set is key_source - Segmentation, and the example drops - self.
  • Run Computations, "Custom Key Source" (how-to/run-computations.md:237-240): the same - self. With it, progress() reports a total equal to the remaining count.
  • Schema as a Workflow Specification, "Self-healing operational semantics" (explanation/schema-as-workflow-specification.md:154-155): calls the key source "the set of upstream keys not yet present". That is the pending set.
  • AutoPopulate specification §9.3 "Job Statuses" (reference/specs/autopopulate.md:809) and §10.2 "Scheduling" (:869); Handle Errors, "Ignore Problematic Jobs" (how-to/handle-errors.md:66): "skipped by populate()" and "skip permanently" hold under reserve_jobs=True only.
  • AutoPopulate specification §3 "The Populate Process"; Computation Model, "Workflow Integrity" (computation-model.md:202): state that the caller populates tables in dependency order, each after its parents and after any table its key source names.

With key_scope in 2.4:

  • AutoPopulate specification §2.3 "Custom Key Source" (autopopulate.md:126-165): key_scope and a migration note replace the override examples. Keep the heading or add an explicit anchor, so #23-custom-key-source resolves.
  • AutoPopulate specification §2.1 "Definition" (:86) and Entity Integrity, "Grain" (explanation/entity-integrity.md:242-245): the grain of an auto-populated table is its primary key, where both pages equate the grain with the key_source (the specification: "operates at the grain of its key_source").
  • Computation tutorial, "Custom Key Source" (tutorials/basics/05-computation.ipynb, cells 32 and 33): declare key_scope = good_sessions and re-execute the notebook.
  • Computation Model, "Key Source", and Run Computations, "Custom Key Source": the examples become key_scope.

With the make() check:

  • AutoPopulate specification §4.2 "Requirements" (autopopulate.md:300): say that populate() records a failure when the row is absent.
  • Handle Errors, "Error Handling in make()" (how-to/handle-errors.md:94-96): the example returns without inserting and says the "job remains pending"; the call counts as a success today. Replace return with raise.

Order: the queue check and the stale docs now, key_scope in 2.4, the raises in 3.0

  1. Turn the four sketches into failing tests.
  2. Patch release: the unconditional key-source restriction in _populate_distributed, the progress() count, and the docs that are wrong today.
  3. Amend #1523 with the scope grammar and the separate scope references, before key_scope is implemented.
  4. 2.4: key_scope; the override warning with the stronger text for a changed key; warnings for a make() that inserts nothing and for a class without make(); the 2.4 docs.
  5. 3.0: an overridden key_source raises, as do a make() that inserts nothing and a class without make().

Related and tracked elsewhere: #1576 (auto-populated tables that declare their own key attributes), #1673 (cost of nesting key_source in refresh()), #1601 (a dropped table's jobs table).

Ngôn ngữ chính
Python
Star
198
Fork
107
Merge trung bình
4 ngày 7 giờ
Pull request đã merge (30 ngày)
12

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của datajoint/datajoint-python

Tất cả issue của datajoint/datajoint-python

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.