Skip to content

OpenConceptLab/ocl_online#268 | Large imports record what they didn't index, and an off-peak job indexes it - #1018

Open
paynejd wants to merge 11 commits into
masterfrom
ocl_online-268-import-index
Open

paynejd wants to merge 11 commits into
masterfrom
ocl_online-268-import-index

Conversation

@paynejd

@paynejd paynejd commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

OpenConceptLab/ocl_online#268

Problem

Since #917, an import over IMPORT_INDEX_MAX_LINES (default 5,000) skips search indexing unless the request sends index=true, and TBv3's import screen never sends index. Nothing indexes those rows later, so a large import leaves:

  • the versions it superseded flagged is_latest_version: true. A later release indexes the new versions but never re-flags the old ones, so HEAD search shows both. For example, a 10,643-line update import into a public source left 2,045 duplicates;
  • in a source with no release since, new rows with no document at all. For example, a 20,191-line import into a private source left all 14,231 new mappings unsearchable.

Change

A large import records what it skipped, and a job indexes it off-peak.

  • When an import part doesn't index, ImportIndexer.finish() writes what it would have queued to a new table, deferred_import_indexes (DeferredImportIndex). Each row is one stage of up to 5,000 ids for one import part:
    • index: a full index of the versions the part created or retired, their versioned objects and latest versions;
    • mapped codes: the mapped codes in the documents of the concepts the part's mappings come from;
    • latest flags: the documents of the versions the part superseded.
  • run_deferred_import_indexing runs every 10 minutes from beat, on the indexing queue:
    • index and mapped codes rows run only while IMPORT_INDEX_WINDOW is open. It's a new setting, HH:MM-HH:MM in UTC, default 01:00-04:30. An empty window pauses the job, and so does one shorter than the 10 minutes between beat runs, which logs an error. Rows go oldest part first, 500 ids at a time. What's left is saved after each batch and the window is checked before the next, so the job stops within a batch of the window closing and picks up there the next night.
    • A run indexes for at most 5 minutes, then queues the next run on the indexing queue, behind whatever was queued meanwhile. Each pass over the latest flags has a 5-minute budget of its own.
    • latest flags rows run on every pass, inside the window or not. Inside the window they also run every 10 minutes between rows. A superseded version is updated once a search finds its concept's current latest version flagged latest. Until then it keeps its flag, so search finds the concept by its previous version rather than not at all. The others wait for a later pass.
    • The same check guards the full writes. An index row doesn't rewrite a version that was superseded since, while its replacement isn't searchable, because that would un-flag the only document search finds. It hands the version over to a latest flags row instead: the superseding import's own if one is waiting, else a new one for its part.
  • One runner at a time, through a cache lock. Before each batch a run renews the lock only if it still holds the run's token, and stops otherwise. The lock expires an hour after its runner dies. Beat ticks expire after 9 minutes, so they don't pile up behind a busy indexing queue.
  • Durable. The rows are in Postgres, not in queued tasks, so deploys and worker restarts lose nothing: a row stays until its work has succeeded.
  • Failures. A failed row stops the pass.
    • If Elasticsearch was only refusing writes for now, the row waits 20 minutes and no attempt is counted.
    • Any other failure counts one attempt and holds the row back for 6 hours (retry_at), so the rows after it go on and an outage costs each row one attempt a night.
    • After 5 attempts the row is skipped, and kept with its error until someone resets attempts.

The superseded versions are updated by a script, not reindexed. It sets is_latest_version from the database and takes HEAD out of source_version, keeping the releases another job may be appending. For a concept, it also sets everything MappedCodes.get_fields gives the row, release_map_codes included, built once per batch: once a version isn't the latest, its own codes come from its public releases (#1010). Nothing is re-embedded. A version with no document (one created and superseded in the same part, say) goes to an index row of its part instead, so it's fully indexed in the window, a batch at a time.

What's waiting is visible. The table is exactly what's still waiting, with each row's import task, stage, ids, attempts and last error. For example:

SELECT stage, resource, count(*) AS rows, sum(cardinality(ids)) AS ids, min(created_at), max(attempts)
FROM deferred_import_indexes GROUP BY 1, 2 ORDER BY 1, 2;

Each run also logs how many rows it finished and how many are waiting.

Behaviour changes

  • index=false now defers instead of skipping. It used to mean "never indexed by the import". It now means "indexed by the off-peak job", like an import over the limit with no index. No caller in the OCL repos sends index=false, and nothing in this repo relies on rows staying unindexed. The index param's swagger text says so.
  • Not at import time: the latest flags. The ticket asked for every import to clear the flag on the versions it supersedes as it finishes. Before the new versions have documents, that would leave each updated concept with no document flagged latest, so it would drop out of HEAD and global search until the window, instead of showing its previous version as it does now. So the flag is cleared as soon as the replacement is searchable: within about 10 minutes of a release or edit that indexes it, or right after the window's run indexes it.
  • The window's indexing shares the indexing worker. Each run indexes for at most 5 minutes, then queues the next one behind the indexing tasks queued meanwhile. Edits and releases indexed during the window wait at most a run's batch on that slot, not the whole window.
  • Small imports and index=true index as they finish, as before.

Tests

  • core/importers/tests_deferred_index.py:
    • recording: an update import over the limit queues nothing, leaves only the new versions flagged latest in the database, and records the right ids per stage. index=false defers a small import, while index=true and small imports still queue their indexing. A mapping import records its mapped codes, rows hold at most a chunk, and the import_type subtask records its rows with its task id;
    • the window: UTC, spanning midnight, empty, invalid, or shorter than the time between beat runs;
    • the job:
      • nothing outside the window except latest flags, and parts run in order;
      • an index row hands a version superseded since over to a flags row, its own or the superseding import's; a version with no document goes from a flags row to an index row and isn't resent outside the window; hand-overs skip ids that an active row has, but not a parked one;
      • in the window, the flags update every 10 minutes between rows;
      • a superseded version keeps its flag while its current replacement isn't searchable, including when a second import superseded the first one's version and the window closes between them. Once a release indexes the replacement, its flag clears outside the window, and a row keeps just the versions still waiting;
      • it stops within a batch of the window closing and resumes;
      • a failed row waits while the rows after it go on. Writes refused for now hold a row back 20 minutes without counting, an outage costs a row one attempt until its retry, and a row that keeps failing is skipped;
      • rows survive a runner that dies mid-row, and a dead runner's lock is respected until it expires;
      • a run stops once its lock holds another runner's token;
      • a run indexes for 5 minutes and queues the next run, and a slow pass over the latest flags doesn't use up that time;
      • the beat entry and its route;
    • the latest-flags script's params for concepts (everything MappedCodes gives the row) and mappings, and the replacement check;
    • a version only a private release holds, superseded by an import, keeps that release's codes in release_map_codes;
    • against real Elasticsearch, a large update import:
      • search finds the previous version while the replacement has no document;
      • a release's version appended to the old document survives the update;
      • once something indexes the replacement, the old document has is_latest_version: false, no HEAD and its release-based mapped codes, outside the window;
      • the window's run then indexes the rest;
      • a superseded version with no document isn't indexed outside the window; the window's run indexes it.
    • With the replacement check, the flags update or the missing-document handling removed, these tests fail.
  • Existing index=false and over-the-limit tests also check that the rows are recorded.
  • Locally, after merging master, the full suite passes as CI runs it (TEST_ES=off --parallel=4, then the tests tagged es), with 97% coverage. pylint 4.0.9 rates core/ 10.00 with no messages.

Review

Three Codex passes, a simplification review and checks of every later commit, all posted below. After a maintainer's review of 7bbdcfc, master was merged in and the changes it asked for were made. Those commits were checked too.

  • Fixed: what drove the design above, mainly:
    • the latest flags waiting for a searchable replacement, at any time of day;
    • full writes guarded the same way;
    • a scripted update that keeps the release versions and sets the mapped codes;
    • batches checked against the window;
    • retry delays instead of quick parking.
  • Accepted:
    • a worker killed before it records its rows, and retire lines indexing at import time, both from oclapi2#917;
    • a 429 near the cutoff, which can overrun it by one batch's backoff;
    • a parked index row holding a version a flags row handed to it;
    • a flags batch racing a release being made private, where the last writer wins, as with index_mapped_codes.

Deploy

  • Migration: importers.0001_initial creates the new, empty table deferred_import_indexes. It's instant.
  • Settings: none needed. IMPORT_INDEX_WINDOW defaults to 01:00-04:30 UTC. The 01:00 vacuum-and-analyze-db beat task runs at the start of that window.
  • Order: as usual, the API runs the migration before it serves. An import part that finishes on an updated worker before the migration has run fails to record its rows, and its task fails, so it's visible.
  • Beat installs the new entry from core/celery.py when it starts.

Not in this change

  • Raising or removing IMPORT_INDEX_MAX_LINES once indexing has its own worker (OpenConceptLab/ocl_online#250).
  • FHIR CodeSystem imports, which still index row by row outside the limit (the checklist on OpenConceptLab/ocl_online#268).
  • Any TBv3 change, such as telling the importer that indexing is deferred.
  • Retire (delete) lines for rows that are already indexed still index as the import runs, as since oclapi2#917.
  • A worker killed mid-part, before it records its rows, still leaves them unindexed, as before this change. The drift check is the backstop.
  • Repairing the documents earlier imports left behind. That's a separate cleanup.

🤖 Generated with Claude Code

https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K

… index, and an off-peak job indexes it

An import over IMPORT_INDEX_MAX_LINES, or sent with index=false, now records the
indexing it skipped in deferred_import_indexes. A beat task on the indexing queue
works through it while IMPORT_INDEX_WINDOW (default 01:00-04:30 UTC) is open, part
by part: the new versions, the mapped codes, then a partial update of
is_latest_version and source_version in the documents of the versions the import
superseded, so they stop showing as duplicates in HEAD search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 1 (codex-cli 0.169.0, commit 9b84b24)

Verdict: findings: 7 findings (P1, P2).

  • F1.1 (P1) core/importers/models.py:1282: Deferring every latest-flag update leaves the release-triggered duplicates that criterion 1 was meant to prevent.
  • F1.2 (P1) core/importers/models.py:1370: Completing a part's INDEX stage does not guarantee that a current replacement is searchable when LATEST_FLAGS runs.
  • F1.3 (P1) core/importers/models.py:1216: Committed import rows can lose their indexing work before it reaches the durable queue.
  • F1.4 (P1) core/common/mixins.py:881: The partial update leaves stale mapped-code fields on superseded concept documents.
  • F1.5 (P1) core/importers/models.py:1380: A temporary Elasticsearch outage can permanently park otherwise valid indexing work.
  • F1.6 (P1) core/importers/models.py:1346: A deferred row can start additional Elasticsearch batches after the off-peak cutoff.
  • F1.7 (P2) core/common/mixins.py:881: Replacing the entire source_version list can erase a concurrent release update.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "full",
  "commit": "9b84b24e3f76307f24492dd4bc7ff2cbe7b96fe9",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "F1.1",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1282,
      "claim": "Deferring every latest-flag update leaves the release-triggered duplicates that criterion 1 was meant to prevent.",
      "scenario": "A daytime import replaces A with B and defers indexing. A subsequent release indexes the missing B document with is_latest_version=true and HEAD membership. A keeps both values in Elasticsearch until the off-peak job runs, so HEAD and global searches can match both versions. Keeping A searchable is useful while B has no document, but the release can make B searchable hours before the deferred patch runs.",
      "action": "Make the path that publishes a replacement also partially update its superseded documents. Cover a release that indexes the replacement before the off-peak window.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.2",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1370,
      "claim": "Completing a part's INDEX stage does not guarantee that a current replacement is searchable when LATEST_FLAGS runs.",
      "scenario": "A is searchable. Two deferred imports replace A with B and then B with C before the window opens. The first part indexes B from its current database state, where it is already superseded, then removes A from HEAD. If the window closes before the second part indexes C, the concept disappears from HEAD and global search until the next run.",
      "action": "Resolve the current replacement when processing a demotion and keep the demotion pending until that replacement is searchable. Test two successive updates with a window cutoff between their parts.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.3",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1216,
      "claim": "Committed import rows can lose their indexing work before it reaches the durable queue.",
      "scenario": "A deploy kills an import worker after it commits new concepts with _index=False but before ImportIndexer.finish records the IDs. The IDs were held in memory and the off-peak runner only reads DeferredImportIndex. The concepts can stay missing from search with no pending record an admin can inspect. Resubmitting a create-only import skips the concepts that already exist.",
      "action": "Persist indexing intent with the resource writes, or add a recovery path that can reconstruct the affected IDs from committed state after an interrupted import.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.4",
      "severity": "P1",
      "tag": null,
      "file": "core/common/mixins.py",
      "line": 881,
      "claim": "The partial update leaves stale mapped-code fields on superseded concept documents.",
      "scenario": "Release v1 contains concept A and its mapping to code X. While A is still latest, a HEAD mapping update changes its indexed target to Y. A later deferred concept update supersedes A. ConceptDocument.prepare now derives A's mapped codes from its release memberships, but the deferred patch leaves Y in the document, so a v1 search can match a mapping absent from v1.",
      "action": "Recompute same_as_map_codes, other_map_codes, and mapped_codes for superseded concepts in the partial update using the existing document helper. Verify the release search without recomputing vectors.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.5",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1380,
      "claim": "A temporary Elasticsearch outage can permanently park otherwise valid indexing work.",
      "scenario": "Elasticsearch returns connection failures or HTTP 503 for five scheduled attempts. These failures are outside BatchIndexRun.is_rejected, so the row reaches the attempt cap. After Elasticsearch recovers, the worker skips that row and its part's later stages on every subsequent night until someone resets the attempts.",
      "action": "Retry transient infrastructure failures with backoff across windows. Reserve manual reset for failures that require intervention and test recovery after more than five transient failures.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.6",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1346,
      "claim": "A deferred row can start additional Elasticsearch batches after the off-peak cutoff.",
      "scenario": "A 5,000-ID concept row starts at 04:29 UTC. Its first 500-document batch takes more than a minute. The full-index helper then starts the remaining batches, including any embedding and retries, because the runner only checks the window after the whole row returns.",
      "action": "Check the deadline between the underlying batches and leave the unfinished IDs pending for the next window.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.7",
      "severity": "P2",
      "tag": null,
      "file": "core/common/mixins.py",
      "line": 881,
      "claim": "Replacing the entire source_version list can erase a concurrent release update.",
      "scenario": "A release seed captures A while it is current and finishes writing its membership after the deferred job has read A's source versions. The release task appends the release to A's Elasticsearch document before the deferred bulk request arrives. The deferred request overwrites the list with its earlier snapshot, leaving A absent from version-scoped search even after both jobs succeed.",
      "action": "Apply the HEAD membership change without replacing release memberships written by other jobs, or use a conditional update that rereads memberships after a conflict.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

…ce their replacement is searchable, at any time of day

Review pass 1 fixes:
- The latest-flags rows now run on every pass of the job, inside the window or not,
  and update a superseded version only once its concept's current latest version has
  a document flagged latest; the others wait. That covers a release indexing the
  replacement before the window, and a version superseded again by a later import.
- The update is a script that takes HEAD out of source_version without replacing the
  releases another job may be appending, and also sets a superseded concept's mapped
  codes, which prepare() takes from its releases' mappings once it isn't the latest.
- Index rows run INDEX_BATCH_SIZE ids at a time, saving what's left after each batch
  and checking the window before the next, so a run stops within a batch of the
  window closing.
- A failure counts as an attempt only while Elasticsearch answers, so an outage
  can't park rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Responses to Codex pass 1 (fixes in 44af16d):

  • F1.1 (P1) fixed. Latest-flags rows now run on every pass of the job, inside the window or not, as soon as the replacement has a document flagged latest, so a release that indexes it clears the old flag within about 10 minutes. Tests: test_flags_update_outside_the_window_once_something_else_indexed_the_replacement, and the ES test.
  • F1.2 (P1) fixed. Before un-flagging a superseded version, the job reads the documents of its concept's current latest version(s) in real time, and leaves it flagged while none says latest. Test: test_superseded_version_keeps_its_flag_until_the_current_replacement_is_searchable (B, then C, with the window closing between parts).
  • F1.3 (P1) accepted, not fixed. This predates this PR: oclapi2#917's "Things to know" already lists a worker killed mid-part as leaving rows deferred, and this change doesn't widen it. Those rows keep _index=False, and the drift check is the backstop. Closing it needs the intent written with each row save. That's a follow-up.
  • F1.4 (P1) fixed. The update also sets a superseded concept's mapped codes from ConceptDocument.get_mapped_codes, which takes them from its releases once it isn't the latest. Tests: test_concept_actions_set_what_a_new_version_changes, and the ES test.
  • F1.5 (P1) fixed. A failure counts as an attempt only while Elasticsearch answers a ping and isn't refusing writes. Test: test_failures_while_elasticsearch_is_down_or_refusing_writes_are_not_counted.
  • F1.6 (P1) fixed. Index rows run INDEX_BATCH_SIZE (500) ids at a time. What's left is saved after each batch, and the window is checked before the next. Test: test_run_stops_within_a_batch_of_the_window_closing_and_the_next_one_resumes.
  • F1.7 (P2) fixed. The update is a script that only takes HEAD out of source_version (or puts it in) and keeps the other versions. The ES test appends a release to the document first and checks that it survives.

…uperseded versions without a document aren't indexed

Review pass 2 fixes:
- The latest-flags update leaves a version with no document without one, instead of
  fully indexing it, so a pass outside the window never embeds anything.
- The window's run updates the latest flags after each row it indexes, so a version
  isn't left flagged while a long backlog runs.
- Whether a replacement is searchable is now read with a search, not a real-time get,
  so a document written but not yet refreshed doesn't count.
- A failed row (other than Elasticsearch refusing writes) counts one attempt and is
  held back for 6 hours, so the rows after it go on and an outage costs each row one
  attempt a night. This replaces the ping check, which a write outage could pass.
- IMPORT_INDEX_WINDOW's comment says it should be at least as long as the 10 minutes
  between beat runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 2 (codex-cli 0.169.0, commit 44af16d)

Verdict: findings: 6 new findings (P1, P2). Earlier: F1.1 unresolved, F1.2 unresolved, F1.3 unresolved, F1.4 resolved, F1.5 unresolved, F1.6 resolved, F1.7 resolved.

  • F2.1 (P1) core/common/mixins.py:898: The daytime flag pass can start full indexing and embedding outside the configured window.
  • F2.2 (P1) core/importers/models.py:1344: An active off-peak run can delay ready flag updates for the rest of the window.
  • F2.3 (P1) core/importers/models.py:1390: A temporary write outage can still permanently park valid deferred work.
  • F2.4 (P1) core/importers/models.py:229: Bulk retirements of previously indexed rows ignore the import's deferral choice.
  • F2.5 (P2) core/common/mixins.py:930: The replacement check can pass before the replacement is visible to search.
  • F2.6 (P2) core/celery.py:46: The ten-minute beat interval can miss a valid configured window every night.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "verify",
  "commit": "44af16d739b07336956a329ea09ef09f1419aec5",
  "verdict": "findings",
  "prior": [
    {
      "id": "F1.1",
      "status": "unresolved"
    },
    {
      "id": "F1.2",
      "status": "unresolved"
    },
    {
      "id": "F1.3",
      "status": "unresolved"
    },
    {
      "id": "F1.4",
      "status": "resolved"
    },
    {
      "id": "F1.5",
      "status": "unresolved"
    },
    {
      "id": "F1.6",
      "status": "resolved"
    },
    {
      "id": "F1.7",
      "status": "resolved"
    }
  ],
  "findings": [
    {
      "id": "F2.1",
      "severity": "P1",
      "tag": null,
      "file": "core/common/mixins.py",
      "line": 898,
      "claim": "The daytime flag pass can start full indexing and embedding outside the configured window.",
      "scenario": "Two deferred imports create A and then supersede it with B before A gets an Elasticsearch document. A daytime release indexes B. The next flag pass tries to patch A, receives a 404, and the shared partial-update helper full-indexes A immediately. A large set of missing versions can send thousands of full writes and embedding requests during peak hours.",
      "action": "Handle missing documents separately in the flag pass. Keep any required full writes in the durable off-peak queue and test a daytime pass with a searchable replacement and an absent superseded document.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.2",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1344,
      "claim": "An active off-peak run can delay ready flag updates for the rest of the window.",
      "scenario": "The opening flag sweep leaves A flagged because B is missing. An early full-index batch makes B searchable, but the runner keeps working through an hours-long backlog under the shared lock. Subsequent beat invocations return without processing flags, so HEAD search can show both A and B until the backlog drains or the window closes.",
      "action": "Process newly ready flag updates between bounded units of full indexing, or give flag processing an independent execution path. Test a replacement indexed early in a run with more index work still pending.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.3",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1390,
      "claim": "A temporary write outage can still permanently park valid deferred work.",
      "scenario": "An index's primary shard is unavailable while the Elasticsearch cluster still answers ping. Bulk writes return HTTP 503, which BatchIndexRun does not classify as a retryable rejection. Five such runs exhaust the row's attempts, and the worker skips it after the shard recovers.",
      "action": "Preserve transient error classifications through BatchIndexRun and keep retrying those failures across windows. Test recovery after five bulk 503 responses with a successful ping.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.4",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 229,
      "claim": "Bulk retirements of previously indexed rows ignore the import's deferral choice.",
      "scenario": "An inline import sent with index=false contains Concept or Mapping delete lines for existing resources whose latest versions have _index=True. The retire path inherits that flag, so it indexes the retired versions and their predecessors at import time. ImportIndexer.add skips those rows, leaving no off-peak record for them.",
      "action": "Pass the effective import indexing decision into the retire path. Keep the immediate behavior for imports that index, and test deferred delete lines against previously indexed concepts and mappings.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.5",
      "severity": "P2",
      "tag": null,
      "file": "core/common/mixins.py",
      "line": 930,
      "claim": "The replacement check can pass before the replacement is visible to search.",
      "scenario": "On a multi-shard index, A and its replacement C are on different shards. The real-time mget sees C immediately after indexing. A's shard refreshes after the demotion and before C's shard refreshes, so a HEAD search in that interval returns neither version. [Elasticsearch multi-get](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-mget) and [refresh behavior](https://www.elastic.co/docs/manage-data/data-store/near-real-time-search).",
      "action": "Check replacement visibility through search, or wait for the replacement write to become searchable before allowing the demotion. Cover a replacement that mget can see before search can.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.6",
      "severity": "P2",
      "tag": null,
      "file": "core/celery.py",
      "line": 46,
      "claim": "The ten-minute beat interval can miss a valid configured window every night.",
      "scenario": "An operator configures 03:00-03:05 UTC. Beat dispatches around 02:57 and 03:07, and the worker starts promptly. Neither invocation sees the window open. The same cadence can recur on subsequent nights, leaving the backlog untouched.",
      "action": "Schedule a run at the configured start, or validate and document a minimum window length that accommodates the beat interval.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Responses to Codex pass 2 (fixes in 0742f3d):

  • F1.1, F1.2: pass 2 marked them unresolved because of F2.2 and F2.5, both fixed below.
  • F1.5: see F2.3.
  • F1.3: still accepted. It predates this PR (oclapi2#917). It's a follow-up.
  • F2.1 (P1) fixed. The latest-flags update now leaves a version with no document without one (raise_unless_missing drops the 404s), so a pass outside the window never full-indexes or embeds. No document means nothing in search says it's the latest, and a release it's in would already have indexed it. Tests: test_missing_documents_are_not_failures_of_the_flags_update, and the ES test test_superseded_version_without_a_document_is_left_without_one.
  • F2.2 (P1) fixed. During the window, the job updates the latest flags after each row it indexes. Test: the replacement's flags now land before the next part's rows in test_run_indexes_the_parts_in_order_and_flags_the_superseded_versions_once_replaced.
  • F2.3 (P1) fixed differently. I dropped the ping check. A failure other than Elasticsearch refusing writes counts one attempt and holds the row back for 6 hours (retry_at), so the rows after it go on and an outage costs each row one attempt a night. A row is parked only after failing on 5 separate occasions, which an outage of a few hours can't cause. Tests: test_an_outage_costs_a_row_one_attempt_until_its_retry, test_failed_row_waits_while_the_rows_after_it_go_on.
  • F2.4 (P1) accepted, not fixed. This predates this PR: oclapi2#917's "Things to know" says retires of rows that are already indexed still index through the normal save path, with index true or false. This PR defers what the import's own indexing would queue. Deferring retires too means plumbing the decision into the retire path and leaving retired concepts unretired in search until the window. That's a follow-up.
  • F2.5 (P2) fixed. Whether a replacement is searchable is now read with a search (ids + is_latest_version term), not a real-time get, so a written but unrefreshed document doesn't count.
  • F2.6 (P2) addressed in docs. IMPORT_INDEX_WINDOW's comment says the window should be at least as long as the 10 minutes between beat runs. The default is 3.5 hours.

…lacement too, and never-indexed versions get indexed in the window

Review pass 3 fixes:
- An index row no longer rewrites a version that was superseded since, while its
  replacement isn't searchable: that would take the only document search finds out
  of HEAD. It waits in a latest-flags row (usually the superseding import's own).
- A superseded version with no document is fully indexed by its latest-flags row
  inside the window, and waits outside it, so a version created and superseded in
  one part still gets a document.
- In the window, the latest flags are updated every 10 minutes between rows and at
  the end of the run, instead of after every row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 3 (codex-cli 0.169.0, commit 0742f3d)

Verdict: findings: 4 new findings (P1, P2). Earlier: F1.1 resolved, F1.2 resolved, F1.3 unresolved, F1.4 resolved, F1.5 unresolved, F1.6 unresolved, F1.7 resolved, F2.1 regressed, F2.2 unresolved, F2.3 unresolved, F2.4 unresolved, F2.5 resolved, F2.6 unresolved.

  • F3.1 (P1) core/importers/models.py:1409: An older full-index row can remove the only searchable HEAD version before its replacement is ready.
  • F3.2 (P1) core/importers/models.py:1351: Each completed index row triggers a rescan of every pending demotion, including those whose replacements were untouched.
  • F3.3 (P2) core/importers/models.py:1280: A version created and superseded within one deferred part can disappear from the queue without ever getting a document.
  • F3.4 (P2) core/importers/models.py:1409: A rejected bulk write can start a fresh indexing attempt after the off-peak cutoff.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "verify",
  "commit": "0742f3d5061e24096d4af1b35f609a4e112d2448",
  "verdict": "findings",
  "prior": [
    {
      "id": "F1.1",
      "status": "resolved"
    },
    {
      "id": "F1.2",
      "status": "resolved"
    },
    {
      "id": "F1.3",
      "status": "unresolved"
    },
    {
      "id": "F1.4",
      "status": "resolved"
    },
    {
      "id": "F1.5",
      "status": "unresolved"
    },
    {
      "id": "F1.6",
      "status": "unresolved"
    },
    {
      "id": "F1.7",
      "status": "resolved"
    },
    {
      "id": "F2.1",
      "status": "regressed"
    },
    {
      "id": "F2.2",
      "status": "unresolved"
    },
    {
      "id": "F2.3",
      "status": "unresolved"
    },
    {
      "id": "F2.4",
      "status": "unresolved"
    },
    {
      "id": "F2.5",
      "status": "resolved"
    },
    {
      "id": "F2.6",
      "status": "unresolved"
    }
  ],
  "findings": [
    {
      "id": "F3.1",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1409,
      "claim": "An older full-index row can remove the only searchable HEAD version before its replacement is ready.",
      "scenario": "A deferred import creates A, and a release indexes A before its pending INDEX row runs. A second deferred import replaces A with B. The opening flag sweep correctly leaves A alone because B is absent. The older INDEX row then rewrites A from the database with is_latest_version=false and without HEAD membership. If the window closes before B is indexed, the concept disappears from HEAD and global search until the next run.",
      "action": "Apply the replacement-visibility guard to full writes that would demote an existing document. Add an Elasticsearch regression test with a release-indexed A, a pending INDEX row for A, and a window cutoff before B.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F3.2",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1351,
      "claim": "Each completed index row triggers a rescan of every pending demotion, including those whose replacements were untouched.",
      "scenario": "A backlog contains 100 flag rows of 5,000 IDs each and 100 older index rows that publish none of their replacements. The job can make 100,000 Elasticsearch searches rechecking those same replacements before reaching the relevant index rows. Those repeated reads consume the off-peak window and delay the work that would make the replacements searchable.",
      "action": "Limit the immediate checks to replacements the completed batch could have published. Use a bounded periodic sweep to pick up replacements published by other tasks.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F3.3",
      "severity": "P2",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1280,
      "claim": "A version created and superseded within one deferred part can disappear from the queue without ever getting a document.",
      "scenario": "Two consecutive lines for the same concept in one index=false part create version A and then replace it with B. Recording subtracts A from the full-index IDs because it was also superseded. Once B is searchable, the partial update for A returns 404 and the job deletes its flag row. A remains missing from Elasticsearch with no pending work. The new missing-document test uses separate parts, so A still has a full-index row there.",
      "action": "Track versions created by the part separately from pre-existing versions it superseded. Keep missing newly created versions queued for a full write during the window and test both lines in one part.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F3.4",
      "severity": "P2",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1409,
      "claim": "A rejected bulk write can start a fresh indexing attempt after the off-peak cutoff.",
      "scenario": "A deferred batch starts at 04:29:55 UTC and Elasticsearch immediately returns 429. The shared helper sleeps for its default 10-second backoff, then starts preparing and sending the batch again after 04:30. Further retries can repeat that work because the window is checked only outside the helper.",
      "action": "Pass the window deadline through to the full-index retry loop. Before starting another attempt, stop and leave the batch queued if the window has closed. Test a rejection just before cutoff.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Responses to Codex pass 3 (fixes in 33d6392). This was the last defect pass; a final check of the commits since follows the simplification review.

  • F2.1 regressed: see F3.3, fixed.
  • F2.2: see F3.2, fixed.
  • F1.3 and F2.4: still accepted. Both predate this PR (oclapi2#917). They're follow-ups.
  • F1.5 and F2.3: kept as in pass 2. An outage costs each row one attempt per 6 hours, so an index row is parked only after failing on 5 nights. A latest-flags row, which runs all day, is parked after about 30 hours of failing. Parked rows stay in the table with their errors.
  • F1.6: see F3.4.
  • F2.6: docs only, as in pass 2.
  • F3.1 (P1) fixed. An index row now checks its batch with the same replacement check. A version superseded since whose replacement isn't searchable isn't rewritten. It waits in a latest-flags row: the superseding import's own if one is waiting, else a new one for this part. Tests: test_index_row_hands_over_a_version_superseded_since_while_its_replacement_is_not_searchable (a release indexed A, a later import superseded it, and the window closes before B), and test_index_row_hands_over_to_a_flags_row_of_its_own_when_none_has_the_version.
  • F3.2 (P1) fixed. In the window, the job updates the latest flags every 10 minutes between rows (DEFERRED_INDEX_FLAGS_SECONDS) and at the end of the run, not after every row. Test: test_run_in_the_window_updates_the_latest_flags_every_few_minutes_not_after_every_row.
  • F3.3 (P2) fixed. A latest-flags update that finds no document fully indexes that version, but only inside the window. Outside it, the version waits in the row. Tests: test_version_created_and_superseded_in_one_part_is_fully_indexed_in_the_window, and the ES test test_superseded_version_without_a_document_waits_for_the_window.
  • F3.4 (P2) accepted. A 429 met just before the cutoff can keep one 500-document batch retrying in BatchIndexRun for its backoff (10+20+40+80 s), a few minutes past 04:30. That's within the 20 minutes before the next export window. Threading a deadline into the shared retry helper isn't worth it here.

@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Simplification review (claude subagent, commit 33d6392)

Verdict: findings: 2 low-confidence cuts, both tests.

  • S1 (dup-test) core/importers/tests_deferred_index.py:897: test_window_is_checked_against_the_current_time_by_default only checks that is_window_open() falls back to timezone.now(). test_window_is_in_utc and the run tests (which leave now unpatched or use a fixed one) already cover the window boundaries.
  • S2 (dup-test) core/importers/tests_deferred_index.py:1303: test_index_latest_flags_updates_documents_without_a_refresh_and_returns_the_missing_ones mocks batch_index_partial_by_ids and asserts its exact call arguments. It tests wiring, not behaviour. The missing-document handling is covered by test_missing_documents_are_not_failures_of_the_flags_update and the ES test test_superseded_version_without_a_document_waits_for_the_window.

Responses (nothing cut):

  • S1, kept. The run tests patch is_window_open itself, and the empty-window test returns before reading the time, so this is the only test of the fall-back to the current time. CI's 97% coverage floor counts it.
  • S2, kept. In TEST_MODE the ES tests can't see refresh=False, and this is the only test that pins it (an import's indexing must not force a refresh per batch). It's also the only unit test of the missing ids collected through on_bulk_error.
findings.json
{
  "reviewer": "claude subagent",
  "perspective": "simplify",
  "mode": "full",
  "commit": "33d63929c37aead53d5ccea42f63bdbf57642150",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "S1",
      "severity": null,
      "tag": "dup-test",
      "file": "core/importers/tests_deferred_index.py",
      "line": 897,
      "claim": "test_window_is_checked_against_the_current_time_by_default only checks that is_window_open() falls back to timezone.now(). test_window_is_in_utc and the run tests (which leave now unpatched or use a fixed one) already cover the window boundaries.",
      "action": "Fold one patched-now assertion into test_window_is_in_utc, or drop the test.",
      "lines_delta": -7,
      "confidence": "low"
    },
    {
      "id": "S2",
      "severity": null,
      "tag": "dup-test",
      "file": "core/importers/tests_deferred_index.py",
      "line": 1303,
      "claim": "test_index_latest_flags_updates_documents_without_a_refresh_and_returns_the_missing_ones mocks batch_index_partial_by_ids and asserts its exact call arguments. It tests wiring, not behaviour. The missing-document handling is covered by test_missing_documents_are_not_failures_of_the_flags_update and the ES test test_superseded_version_without_a_document_waits_for_the_window.",
      "action": "Drop the call-argument assertion, or the whole test, and keep the behavioural tests.",
      "lines_delta": -14,
      "confidence": "low"
    }
  ]
}

… goes to an index row, and parked rows don't absorb hand-overs

Final review check fixes:
- The latest-flags update hands a version with no document to an index row of its
  part instead of indexing it there, so it's indexed a batch at a time with the
  window checked between batches, and later passes outside the window don't resend it.
- A hand-over skips only ids that a row of the same stage that isn't parked already
  has, so a parked row can't keep a version from being indexed or re-flagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Codex check of commits 0742f3d..33d6392 (codex-cli 0.169.0, commit 33d6392)

Verdict: findings: 3 findings (P1, P2).

  • FC.1 (P1) core/importers/models.py:1439: The missing-document fallback can start new full-index batches after the off-peak cutoff.
  • FC.2 (P1) core/importers/models.py:1441: Daytime sweeps repeatedly send partial updates for documents already found missing.
  • FC.3 (P2) core/importers/models.py:1450: A parked flags row can absorb work that an active index row was still able to complete.

Responses (fixes in c4d3961):

  • FC.1 (P1) fixed. A latest-flags update that finds no document no longer indexes the version itself. It hands the version to an index row of its part, which indexes it 500 at a time and checks the window before each batch.
  • FC.2 (P1) fixed by the same change. The handed-over ids leave the flags row, so later passes outside the window don't resend them. Test: test_version_created_and_superseded_in_one_part_is_fully_indexed_in_the_window (a second outside-window run sends nothing).
  • FC.3 (P2) fixed. A hand-over skips only ids that a row of the same stage that isn't parked already has. Test: test_hand_over_skips_ids_another_active_row_has_but_not_a_parked_one.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "33d63929c37aead53d5ccea42f63bdbf57642150",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "FC.1",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1439,
      "claim": "The missing-document fallback can start new full-index batches after the off-peak cutoff.",
      "scenario": "A flags sweep finds 5,000 missing documents just before 04:30 UTC. The window closes during the first 500-document batch. The full-index helper still starts the remaining nine batches, even if Elasticsearch accepts every request.",
      "action": "Check the window before each fallback batch and save the IDs that remain when it closes. Add a regression test that closes the window after the first batch.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.2",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1441,
      "claim": "Daytime sweeps repeatedly send partial updates for documents already found missing.",
      "scenario": "A release publishes 100,000 replacement versions before their predecessors get indexed. An outside-window sweep receives a 404 for each predecessor and keeps the same IDs in the flags rows. Each subsequent sweep recomputes mapped codes and resends the same updates until the window opens, putting repeated daytime load on Postgres and Elasticsearch.",
      "action": "Persist confirmed-missing IDs as work that runs only in the indexing window. Test that a second outside-window run skips those IDs.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.3",
      "severity": "P2",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1450,
      "claim": "A parked flags row can absorb work that an active index row was still able to complete.",
      "scenario": "A release indexes version A. A later deferred import supersedes it with B, and its flags row parks after repeated failures on another ID in the same row. When A's original index row runs, B is still unsearchable. The handoff sees the parked row and removes A from the active index row. After B is indexed, A remains flagged as latest and can still match HEAD searches until someone resets the parked row.",
      "action": "Exclude parked rows from handoff deduplication so eligible work remains queued for A. Add a test with an overlapping flags row at the attempt limit.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

…ses waits 20 minutes, so the rows after it go on

Final review check fix: a row Elasticsearch keeps refusing (a circuit breaker on its
batch, say) no longer stops every run at the same row. It's held back for 20 minutes,
without counting an attempt, and the rows after it go on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Codex check of commit 33d6392..c4d3961 (codex-cli 0.169.0, commit c4d3961)

Verdict: findings: 2 findings (P1, P2).

  • FC.1 (P1) core/importers/models.py:1440: A rejected fallback batch can block unrelated deferred imports for the entire indexing window.
  • FC.2 (P2) core/importers/models.py:1456: Deduplicating against an active INDEX row can strand a missing historical document when that row later parks.

Responses (fix in 7bbdcfc):

  • FC.1 (P1) fixed. A row whose writes Elasticsearch refuses for now is held back for 20 minutes (DEFERRED_INDEX_REJECTED_RETRY_SECONDS) without counting an attempt, so the rows after it go on. That holds for any index row, not only one handed over from flags. Test: test_elasticsearch_refusing_writes_holds_the_row_back_briefly_without_counting_an_attempt.
  • FC.2 (P2) accepted. It needs an index row that parks, after 5 failures on separate occasions, before it reaches a version a flags row handed to it. That version then waits with the parked row, which stays in the table with its error until someone resets attempts, the same recovery as any parked row.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "c4d3961af6be52d0d36b1e51e99cf83ea1fb9549",
  "verdict": "findings",
  "prior": [
    {
      "id": "FC.1",
      "status": "resolved"
    },
    {
      "id": "FC.2",
      "status": "regressed"
    },
    {
      "id": "FC.3",
      "status": "resolved"
    }
  ],
  "findings": [
    {
      "id": "FC.1",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1440,
      "claim": "A rejected fallback batch can block unrelated deferred imports for the entire indexing window.",
      "scenario": "An older fallback batch repeatedly trips an Elasticsearch circuit breaker while smaller writes would succeed. The rejection leaves the fallback INDEX row immediately eligible, so every scheduled run selects it first and stops before reaching newer imports. In the previous revision, the fallback failure ended the flags sweep and the regular indexing loop still ran.",
      "action": "Give rejected fallback rows a retry delay that lets other rows run, or process fallback rows separately. Test that a newer INDEX row advances when the fallback keeps returning 429.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.2",
      "severity": "P2",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1456,
      "claim": "Deduplicating against an active INDEX row can strand a missing historical document when that row later parks.",
      "scenario": "A flags sweep finds a missing superseded version whose replacement is searchable. It drops the missing ID because the ID is in the second batch of an active INDEX row. A permanent error on an unrelated document in the first batch parks that row before the second batch runs. The historical version stays absent from search until manual recovery. The previous fallback could index it independently.",
      "action": "Keep an independent fallback for confirmed-missing IDs or requeue them if the covering row parks. Test an overlapping INDEX row that fails before it reaches the missing ID.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Codex check of commit c4d3961..7bbdcfc (codex-cli 0.169.0, commit 7bbdcfc)

Verdict: clean. No findings.

findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "7bbdcfc7de948d976a6327e54816dbdd74af373e",
  "verdict": "clean",
  "prior": [
    {
      "id": "FC.1",
      "status": "resolved"
    },
    {
      "id": "FC.2",
      "status": "unresolved"
    }
  ],
  "findings": []
}

@paynejd
paynejd requested a review from snyaggarwal November 21, 2026 03:58

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 7bbdcfc, after your three Codex passes, the simplification review and the checks after them. The design holds on the paths I traced: rows survive restarts, a failed row waits without blocking the others, a superseded version keeps its flag until its replacement is searchable, and the flags script keeps the releases another job appends. Beat's expire_seconds works because beat runs django-celery-beat's database scheduler, and the lock is safe on the Redis cache. I haven't run the tests.

Before merge (inline): this branch breaks once master is merged in. #1010, merged after 7bbdcfc, moved concept mapped codes into MappedCodes:

  • get_latest_flags_fields calls ConceptDocument.get_mapped_codes, which #1010 removed, so every concept flags update raises AttributeError.
  • Even with that call fixed, the update leaves release_map_codes as it was while the row was the latest.

GitHub shows no conflict, so only CI after a master merge would catch it. Master now also has #1007, #1023 and #1024, and #1007 changed the same import code.

Nits (inline): the window run holds an indexing slot for the whole window, the lock renewal doesn't check its token, and a window shorter than a beat tick may never open.

Comment thread core/concepts/models.py Outdated
def get_latest_flags_fields(instance):
"""A superseded version's mapped codes come from its releases' mappings, not HEAD's (get_indexed_mappings)."""
from core.concepts.documents import ConceptDocument
same_as_codes, other_codes, mapped_codes = ConceptDocument.get_mapped_codes(instance)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before merge: this raises AttributeError on master. #1010 removed ConceptDocument.get_mapped_codes (and get_indexed_mappings, which the docstring names) when it moved mapped codes into MappedCodes. On a merge with master, every concept flags row fails here, counts an attempt and parks after 5. The superseded versions then stay is_latest_version: true, so HEAD search keeps showing both versions.

One way, building MappedCodes once per batch instead of once per row. The hook takes the batch, and the mixin's default returns {}:

@staticmethod
def get_latest_flags_fields(instances):
    """The mapped codes prepare() gives these rows now (MappedCodes), release_map_codes included."""
    from core.concepts.documents import MappedCodes
    mapped_codes = MappedCodes(instances)
    return {instance.id: mapped_codes.get_fields(instance) for instance in instances}

get_latest_flags_actions would then list the batch's rows once, call the hook and send fields.get(instance.id, {}).

Two tests encode the codes from before #1010. Under #1010, a superseded row that no release holds reads HEAD's codes:

  • empty_codes in LatestFlagsTest.test_concept_actions_set_what_a_new_version_changes;
  • (False, ['v1'], []) in DeferredImportSearchTest, where v1 is only appended in Elasticsearch, so the row has no release in the database.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e39f966: get_latest_flags_fields now takes the batch and returns MappedCodes(instances).get_fields(...) per row id, and get_latest_flags_actions lists the rows once and sends fields.get(instance.id, {}); the two tests now expect HEAD's codes for a superseded row no release holds (['To']).

Comment thread core/concepts/models.py Outdated
"""A superseded version's mapped codes come from its releases' mappings, not HEAD's (get_indexed_mappings)."""
from core.concepts.documents import ConceptDocument
same_as_codes, other_codes, mapped_codes = ConceptDocument.get_mapped_codes(instance)
return {'same_as_map_codes': same_as_codes, 'other_map_codes': other_codes, 'mapped_codes': mapped_codes}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before merge: release_map_codes stays stale. Under #1010, a document has a release_map_codes entry for each release whose codes differ from the document's own codes. Once a row stops being the latest, its own codes switch from HEAD's to the public releases'. This sets only the three own-code fields, so the entries stay as they were computed while the row was the latest.

Example: v1 is only in private release P, and P's codes equal HEAD's, so v1's document has no entry for P. After an import supersedes v1, its own codes become the public releases' (none here), and there's still no entry for P. A search in P for v1's mapped code then reads the empty own fields and misses it. Sending everything MappedCodes.get_fields returns, as in the comment above, covers this too.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e39f966 by the same change: the update sends everything MappedCodes.get_fields returns, release_map_codes included; test_superseded_version_only_in_a_private_release_keeps_that_release_s_codes is your example (v1 only in private release P, superseded by an import, ends with an entry for P holding its code).

Comment thread core/importers/models.py
done = cls.update_latest_flags()
if cls.is_window_open():
flagged_at = time.monotonic()
for row in iter(lambda: cls.get_pending().exclude(stage=cls.Stage.LATEST_FLAGS).first(), None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. With a backlog, this loop keeps one run_deferred_import_indexing task on the indexing queue until the window closes, up to 3.5 hours. docker-compose.prod.yml starts that worker with -c 2, so edits and releases indexed during 01:00–04:30 UTC (06:30–10:00 IST) share the one remaining slot. Could Behaviour changes say so, and is the ECS task's concurrency the same? Alternatively, stopping each run after a few minutes of batches would let the next tick resume it, with other indexing tasks running in between. The lock and the saved ids already support that.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e39f966 (budget kept from the flags pass in 3527f0b): a run indexes for at most 5 minutes, then queues the next run on the indexing queue behind whatever was queued meanwhile, so it no longer holds a slot for the window; Behaviour changes in the description says so.

Comment thread core/importers/models.py Outdated

@staticmethod
def renew_lock():
django_cache.touch(DEFERRED_INDEX_LOCK_KEY, timeout=DEFERRED_INDEX_LOCK_SECONDS)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. This renews the key whoever holds it, while run's finally checks the token before it deletes. If a runner stalls past DEFERRED_INDEX_LOCK_SECONDS (a long 429 backoff on one batch, say), another runner takes the lock. The first then extends the second's lock and carries on, so both work the same rows, and the first one's save of its stale ids can put back ids the other already finished. Passing the token in, renewing only while the key still holds it, and stopping the run otherwise would close that.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e39f966: before each batch the run renews the lock only if it still holds the run's token, and stops otherwise; test_run_stops_once_its_lock_is_another_runners covers it.

Comment thread core/importers/models.py
return False
start, end = window
current = (now or timezone.now()).astimezone(dt_timezone.utc).time()
return start <= current < end if start <= end else (current >= start or current < end)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. A window shorter than beat's 10 minutes may never contain a tick, as the interval counts from when beat started. For example, 02:00-02:05 with ticks at 01:58 and 02:08. 02:00-02:00 never opens. Either way the INDEX rows wait and nothing is logged. The settings comment asks for at least 10 minutes. get_window could treat a shorter window as paused and log an error, as it does for a value that doesn't parse.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e39f966: get_window treats a window shorter than the 10 minutes between beat runs, 02:00-02:00 included, as paused and logs an error, as for a value that doesn't parse.

paynejd and others added 3 commits November 23, 2026 17:07
…68-import-index

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
…MappedCodes' fields, and runs are time-boxed

Review changes after merging master (#1010 moved concept mapped
codes into MappedCodes):
- The latest-flags update sends everything MappedCodes.get_fields gives a row,
  release_map_codes included, built once per batch. get_latest_flags_fields takes the
  batch. A version only a private release holds then keeps that release's codes in
  release_map_codes once an import supersedes it.
- A run indexes for at most 5 minutes, then queues the next run behind the indexing
  tasks queued meanwhile, so the window no longer holds an indexing slot throughout.
- A run renews its lock only while the lock still holds its token, and stops once it
  doesn't.
- A window shorter than the 10 minutes between beat runs pauses the job and logs an
  error, as a value that doesn't parse does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
…own time budget, so it can't starve the indexing

Codex check fix: the indexing's 5 minutes now start once the opening pass over the
latest-flags rows is done, and each such pass stops after 5 minutes of its own. A pass
takes the rows checked longest ago first, so a long list of waiting rows rotates
instead of the same ones being checked every time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Codex check of commits 7bbdcfc..e39f966 (codex-cli 0.169.0, commit e39f966)

The merge of master and the changes for the review of 7bbdcfc.

Verdict: findings: 3 findings (P1, P2).

  • FC.1 (P1) core/importers/models.py:1445: The initial latest-flags scan can consume the entire time budget and prevent the indexing that would clear its backlog.
  • FC.2 (P1) core/importers/models.py:1438: With Redis Sentinel configured, the new ownership check can mistake a freshly acquired lock for a lost lock.
  • FC.3 (P2) core/common/mixins.py:886: A delayed latest-flags update can undo the mapped-code refresh that makes a release private.

Responses:

  • FC.1 (P1) fixed in 3527f0b. The indexing's 5 minutes start once the opening pass over the latest flags is done, and each pass has a 5-minute budget of its own. A pass takes the rows checked longest ago first, so a long list of waiting rows rotates. Test: test_a_slow_pass_over_the_latest_flags_leaves_the_indexing_its_own_time.
  • FC.2 (P1) accepted: it doesn't apply to this cache config. CACHES has a single LOCATION, and the Sentinel URL names the master. So django-redis sends reads and writes to the same server, the master, and a read can't lag the write it follows. clone_lock and celery_once rely on the same behaviour.
  • FC.3 (P2) accepted. It needs a release made private while a deferred flags batch for a version that release holds is in flight, with the access-change refresh landing in between. The last writer wins, as with index_mapped_codes on master, and the next refresh of that concept corrects it.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "e39f966fb94104c9820e54a10e5fc3b90f13cc6f",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "FC.1",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1445,
      "claim": "The initial latest-flags scan can consume the entire time budget and prevent the indexing that would clear its backlog.",
      "scenario": "A large import leaves enough LATEST_FLAGS rows for the Elasticsearch replacement checks to take more than five minutes. The replacements are still waiting in INDEX rows, so the flags scan clears nothing. The first INDEX batch then sees an expired deadline. The worker scans the flags again before requeuing, and each continuation can repeat this without indexing a single replacement.",
      "action": "Bound the flags work per run and reserve time for INDEX batches. Add a regression test where the pending flags take longer than the run budget and the runner still makes progress on replacement indexing.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.2",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1438,
      "claim": "With Redis Sentinel configured, the new ownership check can mistake a freshly acquired lock for a lost lock.",
      "scenario": "The primary accepts the lock acquisition, but django-redis reads the token from a replica that has yet to receive it. The runner stops before starting a batch. If the replica is still behind during cleanup, the primary retains the unused lock and subsequent runs skip the backlog for up to an hour.",
      "action": "Check the token and renew the lease atomically on the Redis primary. Release it with an atomic token check as well.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.3",
      "severity": "P2",
      "tag": null,
      "file": "core/common/mixins.py",
      "line": 886,
      "claim": "A delayed latest-flags update can undo the mapped-code refresh that makes a release private.",
      "scenario": "A superseded concept row is still used by a public collection. The deferred runner prepares its mapped-code fields while a release holding that row is public. The release becomes private, and the second indexing slot finishes the access-change refresh before the deferred bulk write lands. The deferred write restores the stale fields, so public collection search can match a code held only by the private release until another reindex.",
      "action": "Use Elasticsearch document version checks for the mapped-code write and rebuild its fields from current database state on conflict.",
      "lines_delta": null,
      "confidence": "medium"
    }
  ]
}

…ags passes and the indexing, and outside the window the flags pass has no limit

Codex check fixes:
- In the window, a run takes about 5 minutes in all: the opening pass over the latest
  flags gets a third, the indexing the rest (a third at least), and the closing pass
  another third. It queues the next run if indexing or flags work is left.
- Outside the window, where there's no indexing to make room for, the flags pass
  goes through every row again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Codex check of commits e39f966..3527f0b (codex-cli 0.169.0, commit 3527f0b)

Verdict: findings: 2 findings (P1), both about how long a run holds the worker.

  • FC.1 (P1) core/importers/models.py:1458: A flags pass that runs out of time cannot queue a continuation on its own.
  • FC.2 (P1) core/importers/models.py:1449: Resetting the deadline after the opening flags pass makes ordinary indexing tasks wait longer for the worker.

Responses (fixes in 1f98dcc):

  • FC.1 fixed. Outside the window there's no indexing to make room for, so the flags pass goes through every row again. In the window, a run whose flags pass runs out of time queues the next run. Test: test_outside_the_window_the_flags_pass_goes_through_every_row.
  • FC.2 fixed. A run in the window takes about 5 minutes in all. The opening flags pass gets a third, the indexing the rest (a third at least, if that pass ran over), and the closing pass another third. Then it queues the next run if work is left. Tests: test_a_slow_pass_over_the_latest_flags_leaves_the_indexing_its_own_time, test_run_indexes_for_a_few_minutes_then_queues_the_next_run.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "3527f0b09cefd9c20952fc77b4d64429434591e3",
  "verdict": "findings",
  "prior": [
    {
      "id": "FC.1",
      "status": "resolved"
    },
    {
      "id": "FC.2",
      "status": "unresolved"
    },
    {
      "id": "FC.3",
      "status": "unresolved"
    }
  ],
  "findings": [
    {
      "id": "FC.1",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1458,
      "claim": "A flags pass that runs out of time cannot queue a continuation on its own.",
      "scenario": "Outside the indexing window, a release makes a replacement searchable behind a backlog that takes 12 minutes to check. The previous runner reached it in the same invocation. The capped pass now needs three scheduled invocations because continuations require an open window and pending full-index work. HEAD search shows both versions for about ten extra minutes.",
      "action": "Queue a continuation when the flags pass leaves rows unchecked, including outside the indexing window. Carry forward the sweep position so rows already checked and still waiting cannot keep the continuation running.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.2",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1449,
      "claim": "Resetting the deadline after the opening flags pass makes ordinary indexing tasks wait longer for the worker.",
      "scenario": "The opening pass clears four minutes of ready flags, full-index work remains, and the other indexing slot is busy. A normal save queues an indexing task during the opening pass. The previous runner yielded after five minutes. The new runner spends five more minutes on full indexing and ties up the slot for nine minutes, even with an empty closing pass.",
      "action": "Give the opening flags pass a shorter slice of the worker's time budget and reserve time for full indexing before yielding. Defer remaining flags work to a subsequent task.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

…nutes, and checks the window again after its opening pass

Codex check fixes:
- The closing flags pass now ends with the run's budget: a third for the opening
  pass, a third for the indexing (two, if the opening pass was quick, and at least
  one), and the rest for the closing pass.
- A run queues the next one only for indexing that's left, not for unchecked flags,
  so flags rows whose replacements can't be searched yet don't keep the worker busy.
  Beat's next run picks them up, and outside the window it goes through them all.
- After the opening pass, the run checks the window again, so a pass that took it
  into the window is followed by indexing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qWWFiC4BMWhVDdX48K
@paynejd

paynejd commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Codex check of commits 3527f0b..1f98dcc (codex-cli 0.169.0, commit 1f98dcc)

Verdict: findings: 4 findings (P1, P2), all about scheduling.

  • FC.1 (P1) core/importers/models.py:1462: The closing flags pass adds 100 seconds to the five-minute budget.
  • FC.2 (P1) core/importers/models.py:1465: Flags-only continuations can repeatedly scan a backlog that cannot make progress.
  • FC.3 (P2) core/importers/models.py:1452: A run skips full indexing if its opening flags pass crosses into the window.
  • FC.4 (P2) core/importers/models.py:1464: Closing the indexing window suppresses a continuation for unchecked flags.

Responses (fixes in 7e6a53b):

  • FC.1 fixed. The closing pass ends with the run's budget: a third for the opening pass, a third for the indexing (two, if the opening pass was quick, and at least one), and the rest for the closing pass.
  • FC.2 fixed. A run queues the next one only for indexing that's left, never for unchecked flags. Rows whose replacements can't be searched yet wait for beat's next run, and outside the window that run goes through them all.
  • FC.3 fixed. After the opening pass, the run checks the window again. Test: test_run_indexes_if_its_opening_flags_pass_took_it_into_the_window.
  • FC.4 accepted. At the end of a window, flags a run didn't reach wait for beat's next run, at most 10 minutes later and outside the window, where the pass has no time limit.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "1f98dccdbd14164291b8dc7c0225dc1a48a4f68b",
  "verdict": "findings",
  "prior": [
    {
      "id": "FC.1",
      "status": "resolved"
    },
    {
      "id": "FC.2",
      "status": "unresolved"
    }
  ],
  "findings": [
    {
      "id": "FC.1",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1462,
      "claim": "The closing flags pass adds 100 seconds to the five-minute budget.",
      "scenario": "The opening pass uses 100 seconds and full-index work runs until the 300-second deadline. With enough flags still pending, the closing pass starts new rows until second 400. An ordinary indexing task waiting for that slot waits an extra minute and 40 seconds even when no batch overruns.",
      "action": "Reserve the closing third within the shared budget. End full indexing by the start of that third and give the closing pass the shared deadline.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.2",
      "severity": "P1",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1465,
      "claim": "Flags-only continuations can repeatedly scan a backlog that cannot make progress.",
      "scenario": "The replacement index rows are in retry backoff and checking the waiting flags rows takes longer than a closing pass. Each continuation starts a new sweep, checks rows whose replacements are still unsearchable, and queues another task even though it finished no rows. This keeps an indexing slot busy and sends repeated Elasticsearch queries throughout the window.",
      "action": "Carry a sweep boundary across continuations and stop after every row in that sweep has been checked once. Leave rows whose replacements are still unsearchable for a later scheduled run.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.3",
      "severity": "P2",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1452,
      "claim": "A run skips full indexing if its opening flags pass crosses into the window.",
      "scenario": "A scheduled run starts ten seconds before the window opens and spends 40 seconds checking flags. The previous runner started full indexing as soon as the flags pass finished. The new runner skips it using the earlier window check. For a supported ten-minute window, the next scheduled run has only ten seconds left if it starts on time.",
      "action": "Check the current window again after the opening flags pass and enter full indexing if it has opened.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.4",
      "severity": "P2",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1464,
      "claim": "Closing the indexing window suppresses a continuation for unchecked flags.",
      "scenario": "A run starts 4 minutes and 45 seconds before the window closes, with four minutes of ready flags and a full-index backlog. The previous opening pass cleared all four minutes of flags. The new opening pass stops after about 100 seconds, indexing runs until the window closes, and the closing pass runs out of time with ready flags still unchecked. Both versions can remain visible in HEAD search until the next scheduled run because the closed window blocks the continuation.",
      "action": "Allow an unfinished flags sweep to queue a continuation after the window closes. Keep the open-window check on full indexing.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Codex check of commits 1f98dcc..7e6a53b (codex-cli 0.169.0, commit 7e6a53b)

Verdict: findings: 1 (P2), no P0 or P1.

  • FC.1 (P2) core/importers/models.py:1451: If the window closes during the opening pass, the run skips the closing flags pass even when time remains.

Response:

  • FC.1 (P2) accepted. If the window closes during the opening pass, any flags it didn't reach wait for beat's next run, at most 10 minutes later. Outside the window that run's flags pass has no time limit.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "7e6a53bd3a61e0f5ea6ab5300fe5c886d6181d69",
  "verdict": "findings",
  "prior": [
    {
      "id": "FC.1",
      "status": "resolved"
    },
    {
      "id": "FC.2",
      "status": "resolved"
    },
    {
      "id": "FC.3",
      "status": "regressed"
    },
    {
      "id": "FC.4",
      "status": "unresolved"
    }
  ],
  "findings": [
    {
      "id": "FC.1",
      "severity": "P2",
      "tag": null,
      "file": "core/importers/models.py",
      "line": 1451,
      "claim": "If the window closes during the opening pass, the run skips the closing flags pass even when time remains.",
      "scenario": "A run starts 60 seconds before the window closes with five ready flags rows that take 30 seconds each. The opening pass finishes four rows at second 120. The previous revision processed the fifth row in its closing pass. This revision returns with 180 seconds left in the five-minute budget, so both versions for that row can remain visible in HEAD search until the next scheduled run.",
      "action": "Use the second window check to gate full indexing. If the run started inside the window, still use the remaining budget for a closing flags pass. Add a test where the window closes during the opening pass.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Changes for the review of 7bbdcfc (head now 7e6a53b):

  • Master merged in (ea02759, a merge, no rebase). The only conflict was an import line in core/common/mixins.py. Master's get_mapped_concept_ids now also covers older versions no release holds, and the deferred mapped-codes stage picks that up.
  • Before merge, both fixed (e39f966). get_latest_flags_fields takes the batch and returns everything MappedCodes.get_fields gives each row, release_map_codes included, built once per batch. get_latest_flags_actions lists the rows once and sends fields.get(instance.id, {}). The two tests now expect HEAD's codes for a superseded row no release holds. test_superseded_version_only_in_a_private_release_keeps_that_release_s_codes is your example.
  • Nits, all fixed:
    • Time-boxed runs (e39f966, budget refined in 3527f0b, 1f98dcc, 7e6a53b). In the window, a run takes about 5 minutes: a third for the opening latest-flags pass, a third or more for indexing, and the rest for the closing pass. If indexing is left, it queues the next run behind whatever the indexing queue got meanwhile. Outside the window there's only the flags pass, with no limit.
    • Lock token (e39f966). The lock is renewed only while it holds the run's token, and the run stops otherwise.
    • Short windows (e39f966). A window shorter than the 10 minutes between beat runs, 02:00-02:00 included, pauses the job and logs an error.
  • Checks: pylint 4.0.9 rates core/ 10.00. The full suite passes locally as CI runs it, with 97% coverage; one failure is core.capacity's timing test, a known flake under load, and core.capacity passes alone. Codex checked 7bbdcfc..e39f966 and each later commit (comments above). The last check found one P2, accepted.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants