Repository navigation
OpenConceptLab/ocl_online#452 | Expansions can be evaluated at request time, under a resolution the caller supplies, with code references in one query - #1086
Conversation
…sionEvaluation the caller may supply An ExpansionEvaluation says how one expansion is evaluated: which rules it follows (fhir_rules: OCL's new EXPANSION_FHIR_RULES_TOGGLE decides for API requests, read only when asked; a caller can set them) and how what its references and system-version entries name resolves. Its resolve() is the one entry point for both, ahead of the shared resolver, so a caller with content of its own can answer for a canonical first, even with the URL registry on. The version is passed apart from the URL. add_references and seed_children take an optional evaluation and set it on each reference while they evaluate it. Callers that pass none are unchanged: each reference resolves under its own default, which calls the resolver exactly as before. Nothing reads fhir_rules yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…est time, rolled back, with side effects refused and a deadline ExpansionEvaluation.at_request_time(seconds) opens an evaluation for one request: a transaction rolled back when it closes; side effects refused while it's open (Celery tasks and cache writes raise in tests and are skipped in production with an error logged; a search index write raises in both; an on_commit hook is refused at close, the rollback dropping it); and one deadline for all it runs. Each statement gets SET LOCAL statement_timeout from the time left, add_references checks it before each reference, and running out raises EvaluationTooCostly once rolled back. Under it, add_references and seed_children index nothing and write nothing back to the references or to health, and Expansion.build_at_request_time builds a new expansion of a collection version at once. The guard lives in core/side_effects.py: the task classes check it before they queue (a once task before it takes its lock), the cache backend is django_redis's with its writes checked (core.common.cache.RedisCache), and the search client's transport refuses writes (RefusingTransport). With no evaluation open they behave as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…ences to one source version in one query A reference to one concept by its code, with nothing else to apply (no concept version, cascade, transform or value set), is now evaluated with the others like it: add_references resolves each as before, then finds all their codes with one query per source version (CodeReferenceBatch), applies the expansion's parameters once to what they found, adds it once, and writes back and records each reference's result as it did one at a time. Each finds what it found on its own: in a version, the concept with that code, the newest if the version holds two; in HEAD, the concept itself; only in versions its creator can view. add_references also reads its owner's resolution namespace once rather than once per reference (a toggle read each). A request-time build of 10 or 40 code references now runs the same number of queries; one at a time it ran about six more per reference. Tests build each case both ways (batched and one at a time) and compare members, mappings, recorded versions, unresolved entries, each reference's reason, what's written back and what's indexed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…32-bit link sequences it advances A rollback gives back none of the ids a request-time evaluation used, so each request advances the sequences of the link tables it writes for good. LINK_SEQUENCE_TABLES lists the ones with 32-bit ids (concept and mapping source links, parent links, expansion members, reference results and an expansion's recorded versions), and link_sequence_usage() reads how much of each range is used. at_request_time() refuses to open (EvaluationUnavailable) once one reaches 90%, leaving the rest to OCL's own writes. A test checks that every table with 32-bit ids a request-time build inserts into is on the list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…ethod itself Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…der kept, the guard tightened - Code references excluded are evaluated together too, one query per source version. - A run of code references is applied before any other reference, which may read the expansion being built (a value set reference to its own collection), so every reference sees what it saw one at a time. - Members a request-time evaluation removes no longer mark the stored collection's last_child_removal_at, which held its row until the rollback. - Bulk indexing and the indexing signal tasks check the guard in the calling thread, before their worker threads (which don't see it) start. - An on_commit hook is refused when it's registered, savepoints included, not only at close. - The deadline covers the sequence check, and an evaluation that finishes past it is too costly. - A relative url|version is split for the evaluation's resolve too, unless the resolver reads it as canonical. - The test runner's no-op cache refuses writes at request time, as the deployed cache does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…e deadline, one search per version, nested guards - Search index reads during a request-time evaluation get only the time its deadline leaves, with no retries, and a search ends on the index's side too (its timeout); out of time, or timed out, is too costly. - A code batch is told every code the expansion's code references name, so each source version is searched once, however other references split them into runs. - Expansion parameters that read members (exclude-system, date) apply reference by reference, as before, since an earlier reference's concepts can change what a later one adds. - The sequence check runs inside the evaluation, within its deadline. - A nested evaluation restores the outer one's on_commit guard when it closes. - Fix: the bulk index guard named its document with __name__, which an instance doesn't have, on every bulk index. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…erence at a time did - What batched code exclusions removed is queued for indexing as a list: a set isn't JSON, so a build that indexes outside tests failed (found by crew fhir-b-versions' review). - With a parameter that reads members (exclude-system, date), what's indexed is re-read once added, as one reference at a time did, so the same members are indexed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…ested deadlines, read routes, indexing re-read - A savepoint's rollback or release, and a statement in a failed transaction, run without the deadline's SET LOCAL, so an error caught in a savepoint leaves the evaluation usable. - A nested evaluation ends by the outer one's deadline, for statements and search reads alike. - A search request is a read by its endpoint (the first segment starting with _), so a document whose id looks like a read's endpoint is still a write. - With a parameter that reads members, what's indexed is the parameters' own query re-read once added, as one reference at a time did (a text filter's matches stay as matched). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…tes, one forwarding test less - The search transport takes for reads only the endpoints OCL sends (_search, _count, _msearch, _mget and a scroll); any other request is a write. - A test that seed_children forwards its evaluation goes: the request-time tests go through it. - Import order and a long line (lint). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
…queries, a test stub's model - A search of every index (_all) is a search: _all names indexes, it isn't an endpoint. - The deadline wrapper passes a composed query (psycopg2.sql) through; only a string can be a savepoint's rollback. - The equivalence test's text filter stand-in answers with the model it was given (mappings too). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61
snyaggarwal
left a comment
There was a problem hiding this comment.
Review (Sunny): verdict needs changes
Nothing blocking. Three should-fix items, all on paths with no production caller yet, plus nits.
Switch off: API behaviour is unchanged. I read the off path line by line against master:
split_version+ExpansionEvaluation.resolvegive the resolver the same url and version it got before (same|split and version precedence, same canonical test, two|still refused by the resolver).owner_namespaceis the valueresolution_namespacecomputed per reference.CodeReferenceBatchmatchesget_conceptsfor a plain code reference. Filters never apply to code references (should_apply_filterisnot self.code and self.filter). Viewability uses the reference creator. A version holding two concept versions gives the newest. HEAD gives the versioned object. Write-back,last_resolved_at, reasons, exclusions (every version) and what gets indexed come out the same. The flush before each non-code reference keeps the order.- The guard is a no-op outside an evaluation.
RedisCacheandRefusingTransportpass straight through.
The one API-visible change is the batching, which is intended. I found no case where it differs on a rebuild. The incremental add path is untested (finding 3).
| # | Severity | Where | Finding |
|---|---|---|---|
| 1 | should fix | core/collections/models.py:2700 |
A request-time evaluation of a stored expansion holds row locks until it rolls back |
| 2 | should fix | core/collections/models.py:2868 |
A request-time build has no caller: visibility is the reference creator's, and the default resolution checks none |
| 3 | should fix | core/collections/tests/tests_evaluation.py:519 |
The equivalence tests cover full rebuilds only, not the incremental add path API users hit |
| 4 | nit | core/collections/evaluation.py:210 |
Every source version is searched for every deferred code, including other systems' codes |
| 5 | nit | core/collections/evaluation.py:42 |
The sequence check reads usage but doesn't limit the burn; a NULL last_value passes as 0 |
| 6 | nit | core/collections/evaluation.py:135 |
One extra SET LOCAL round trip before every statement |
| 7 | nit | core/side_effects.py:54 |
A second side-effect guard next to dry_runs.py; refused effects log one error each |
Against the design (#798, lead's calls). This PR has the rolled-back transaction, the side-effect guard, the deadline and the link-sequence check. It has no kill-switch toggle and no measured staging load. Both are conditions of W1 and should land with the first caller of at_request_time. fhir_rules isn't read anywhere yet, and at_request_time / build_at_request_time have no production caller. That's fine for groundwork, but this code runs only in tests until the next PR.
Version locking and health. Off the request-time path, evaluated_* / explicit_*, unresolved_repo_versions, get_unresolved_entry_keys_of, write-back and mark_health_not_current are unchanged. dry_run_rebuild is unaffected: it has its own patches, and Toggle.get is still patched there.
Not verified: how the batch query performs on production-sized data (one mnemonic IN per version over CIEL or LOINC HEAD); whether FhirResolution restricts OCL-path (non-canonical) references to what the caller can view; the guard's behaviour under concurrent requests. I relied on CI for tests and didn't run pylint.
| def seed_children(self, index=True, force_reevaluate=False, evaluation=None): | ||
| version = self.collection_version | ||
| if force_reevaluate: | ||
| is_request_time = bool(evaluation and evaluation.is_request_time) |
There was a problem hiding this comment.
should fix. seed_children(evaluation=...) and add_references(evaluation=...) accept a stored expansion, and test_rebuilding_a_default_expansion_writes_nothing_back_and_marks_no_health does exactly that. A rebuild clears the stored member rows (DELETE on collection_expansions_concepts) and saves unresolved_repo_versions on the stored expansions row. Both row locks are held until the rollback, which can be up to the deadline.
Scenario: a request-time evaluation of a collection's default expansion is running. A Celery rebuild or health compute on that expansion now waits on the lock. A second request for the same expansion also waits, then hits statement_timeout and returns EvaluationTooCostly. Concurrent requests for one value set run one at a time.
Fix: allow request-time evaluation only on an expansion created inside the evaluation (build_at_request_time). Raise otherwise, and change the test to assert the refusal.
There was a problem hiding this comment.
Fixed in 80266e2. At request time, add_references (and so seed_children) refuses any expansion the evaluation didn't build. ExpansionEvaluation.check_own raises before anything is read or written, and build_at_request_time registers the expansion it creates. The test now asserts the refusal on the stored default expansion, with no INSERT, UPDATE, DELETE or FOR UPDATE issued, and that a build under the evaluation still gives the same members.
What's still written is the new expansion's own rows, in the rolled-back transaction, which no other transaction sees. Their foreign keys take key-share locks on the rows they point at until the rollback, at most the deadline. Those block only deletes and FOR UPDATE on those rows. So a new version of a concept whose HEAD row is a member (lock_versioned_object), or of a collection built at its HEAD, waits for the rollback. I left that as it is. Taking those two locks FOR NO KEY UPDATE would remove the wait, but that's a separate change.
There was a problem hiding this comment.
Verified in 80266e2. check_own runs first in add_references, before any read or write, and the test shows no INSERT, UPDATE, DELETE or FOR UPDATE on the stored expansion. I agree with leaving the key-share wait you describe for now; it belongs in the first caller's staging load measure.
| return expansion | ||
|
|
||
| @classmethod | ||
| def build_at_request_time(cls, collection_version, evaluation, parameters=None): |
There was a problem hiding this comment.
should fix. There's no caller in this evaluation. Members are filtered by can_view_all_content(reference.created_by) (CodeReferenceBatch.can_view, get_resource_queryset_from_system_and_valueset). With resolution=None, the shared resolver applies no visibility check. parameters, including system-version, will be request input.
Scenario (next PR): a FHIR $expand on a public collection passes system-version=/orgs/X/sources/Private/v1/. The collection's references were created by a member of X. The members of that private version come back to a caller who can't view it. The API can't reach this today, because creating an expansion needs edit rights on the collection. Request-time builds remove that barrier.
Fix: require a caller-scoped resolution, or a caller, in at_request_time / build_at_request_time, and check that every resolved repo version is visible to the caller. Add a test with a private source named in system-version.
There was a problem hiding this comment.
Fixed in 80266e2, with follow-ups in bc89616, c4923df and 024b03b. A request-time evaluation now answers its caller: ExpansionEvaluation(caller=request.user). The caller is anonymous unless one is given, so leaving it out gives public content only.
- Content: every check that used the reference's creator now goes through
ExpansionEvaluation.can_view(version, reference). The viewer is the creator, as before, or at request time the caller. That covers the code batch, the system version, value sets and a cascade's version;omit_if_exists_inuses the same viewer. - Existence: at request time, a version the caller can't view is answered as one not found where it would be recorded: a
system-versionentry, a reference's own versions, a value set. So the expansion lists it as unresolved, not as a version it was evaluated in. This is done where versions are recorded, not inresolve(): hiding it inresolve()also hid which source a reference names, so a public release named insystem-versionstopped applying when the source's newer release was private. - The collection:
build_at_request_timerefuses a collection version the caller can't view (ExpansionEvaluation.can_build:has_view_access, as the API's views ask;PermissionDenied). The FHIR layer should answer that as not found before it gets there. - Content an evaluation brings itself: an evaluation with content of its own (the FHIR workspace's, in an organization the caller can't view) extends
can_viewandcan_buildto let its own versions through. A test shows one. Each answer is read once per version and viewer while the evaluation is open, not once per reference, and read again the next time it opens.
RequestTimeVisibilityTest has your case: a public collection whose references a member of a private org made, built with system-version naming the private source's version. With no caller, an anonymous user or a signed-in non-member, the build gets nothing and records none of that source's versions. The member gets the concept. A newer private release doesn't stop a public one named in system-version from applying. A stored build still reads as the creator, so without an evaluation nothing changes for API users.
Members taken from a stored expansion of a collection version the caller can view aren't filtered again: a pinned reference's saved results, and an imported value set's members. The API already lists those to anyone who can view that version.
There was a problem hiding this comment.
Verified across 80266e2 to 024b03b. Every check on the request-time path (code batch, system and system-version, value sets, cascade version, omit_if_exists_in) uses the caller, anonymous gets public content only, a hidden version is recorded as unresolved, and the build refuses a collection the caller can't view before writing anything. I agree that saved results of a viewable collection need no second filter, since the API already lists them.
| expansion = Expansion.objects.get(id=self.expansion.id) | ||
| expansion.parameters = parameters or {} | ||
| references = list(self.collection.references.order_by('id')) | ||
| expansion.add_references(references, index=True, is_adding_all=True, force_reevaluate=True) |
There was a problem hiding this comment.
should fix. snapshot compares batched and one-at-a-time evaluation only for add_references(..., is_adding_all=True, force_reevaluate=True). The PR's dry-run evidence also covers rebuilds only. The most common API path is PUT .../references/, which goes through Collection.add_references to Expansion.add_references with is_adding_all=False. There, the collection's existing exclusions are appended and re-evaluated, and now they're batched too. I didn't find a difference by reading, but nothing compares the two ways on this path.
Fix: add an assert_same_either_way case that builds the expansion, then adds new code references incrementally, with an existing code exclusion and an existing cascade exclusion present.
There was a problem hiding this comment.
Added in 80266e2. snapshot(..., added=...) builds the expansion, then adds new references through Expansion.add_references with its defaults (is_adding_all=False), as PUT .../references/ does. So the collection's code exclusions and its cascade exclusion of c are evaluated again with them.
test_the_same_expansion_when_code_references_are_added_to_it adds seven code references: one new member, codes the exclusions take out again, one that finds nothing, an encoded code and a canonical system. A second case does the same under system-version. Batched and one at a time give the same members, mappings, recorded versions, unresolved entries, reasons, write-back and indexing.
There was a problem hiding this comment.
Verified in 80266e2. Both cases add through add_references with is_adding_all=False, with the code and cascade exclusions re-evaluated, and compare every recorded output.
| for version, codes in needed.values(): | ||
| searched = self.searched.setdefault(version.id, set()) | ||
| if codes - searched: | ||
| self.search(version, (codes | self.codes) - searched) |
There was a problem hiding this comment.
nit. (codes | self.codes) - searched searches each source version for every deferred code in the collection, not only the codes of references to that source.
Scenario: a collection has 50k CIEL code references and a few LOINC ones. Every version touched (a CIEL release, a LOINC release, a HEAD) gets a 50k-element mnemonic IN. Short numeric codes also match unrelated rows. The results are correct, but the statements are large and the extra rows are wasted. At request time, they also eat into the deadline.
Fix: key self.codes by the reference's system (or by the resolved source id), so each version is searched only for codes that can resolve to it.
There was a problem hiding this comment.
Fixed in 80266e2. The batch now keeps the codes it's told of by the repository each reference's system names, without its version. A version is searched for the codes of references that name its repository, by its OCL path or its canonical URL, or that name it as the references that reached it do. In your example, a LOINC release is searched for LOINC's codes only.
A version reached through a URL it doesn't carry (through a registry entry, say) gets its references' codes in one more query, with the same result. test_each_version_is_searched_only_for_its_own_source_s_codes checks that another source's version is searched once, for its own code only. The existing test still sees one query per version of the batch's source.
There was a problem hiding this comment.
Verified in 80266e2. Codes are kept by repository, a version reached through another URL gets one more query with the same result, and the new test shows the other source searched once, for its own code.
| """{link table: the share of its 32-bit id range its sequence has used}, for LINK_SEQUENCE_TABLES""" | ||
| with connection.cursor() as cursor: | ||
| cursor.execute( | ||
| 'SELECT tables.name, COALESCE(sequences.last_value, 0), LEAST(sequences.max_value, %s) ' |
There was a problem hiding this comment.
nit. Two things here:
- The check stops evaluations at 90% but doesn't slow the burn. Each request-time build permanently uses up as many
collection_expansions_conceptsids as it has members. A 100k-member LOINC value set uses about 100k ids per call. The lasting fix is bigint ids on these link tables (a migration), which would make the check unnecessary. Worth a ticket before anonymous/fhir/exposure. COALESCE(last_value, 0):pg_sequences.last_valueis NULL for a sequence that's never been used, and also when the role lacks privilege on it. A missing grant passes as 0% used. Treat NULL as unknown whenhas_sequence_privilegeis false.
There was a problem hiding this comment.
Both are in 80266e2.
- NULL
last_value: the check now also readshas_sequence_privilege(..., 'USAGE, SELECT'). A sequence never used counts as none used. One this role can't read counts as unknown, and then no request-time evaluation opens. Tests cover both, the second with a role that has no privileges. - The burn: agreed, the check limits how far evaluations go, not how fast. The comment by
LINK_SEQUENCE_LIMITnow says that bigint ids on these tables are the lasting fix, which would make the check unneeded. I've suggested the migration as a follow-up, to land before anonymous/fhir/use.
There was a problem hiding this comment.
Verified in 80266e2. An unreadable sequence now counts as unknown and blocks opening, with tests for both cases. Tracking bigint ids as a follow-up before anonymous /fhir/ use works for me.
| if left <= 0: | ||
| raise EvaluationTooCostly() | ||
| with context['connection'].connection.cursor() as cursor: # the driver's own cursor, past the wrappers | ||
| cursor.execute('SET LOCAL statement_timeout = %s', [left]) |
There was a problem hiding this comment.
nit. Every statement under the evaluation now runs an extra SET LOCAL statement_timeout first, doubling round trips. A request-time build with per-reference cascades runs thousands of statements. Consider re-setting only when the time left has fallen by more than a margin since the last SET, and relying on check_deadline in between.
There was a problem hiding this comment.
Done in 80266e2. The timeout is set again only when the time left has dropped STATEMENT_TIMEOUT_MARGIN (0.25 s) below the one last set on the connection, or when a shorter evaluation opens inside this one. check_deadline covers the references in between, so a statement can now run at most the margin past the deadline.
A savepoint's rollback undoes a SET LOCAL made inside it. So a rollback clears the record of the last setting, and the next statement sets it again.
When an execute wrapper that isn't an evaluation's runs first, the timeout is set before every statement, as before. FHIR's search timeout is one: it sets its own before each statement (bc89616). The timeout it sets is the time left or the one already in effect, whichever is shorter, read and set in one statement: an enclosing search with less time left keeps its own (c4923df).
Tests:
- five statements share one
SET; - a drop past the margin sets it again;
- a shorter nested evaluation sets its own, and the outer one's comes back when it closes;
- a rolled-back savepoint leaves no stale timeout;
- a wrapper outside the evaluation that sets a longer timeout doesn't outlast it, and one that sets a shorter timeout keeps it.
| message = f'Refused during a request-time evaluation: {kind} {detail}' | ||
| if getattr(settings, 'TEST_MODE', False): | ||
| raise SideEffectRefused(message) | ||
| logger.error(message) |
There was a problem hiding this comment.
nit (follow-up).
core/collections/dry_runs.py(ExpansionDryRun.rolled_back) blocks the same side effects with patches, includingapp.send_task, which this guard doesn't cover. Consider moving dry runs ontorefusing_side_effectsso there's one guard.- In production, each refused effect logs an error. Once carried content is loaded under the guard (the next PRs),
CelerySignalProcessorwill try to queuehandle_save/handle_m2m_changedfor every saved concept, which means one error log per row. Have the signal processor skip quietly whileis_refusing().
There was a problem hiding this comment.
The signal processor is done in 80266e2. CelerySignalProcessor.handle_save and handle_m2m_changed return quietly while side effects are refused, so content loaded under the guard queues nothing and logs nothing per row.
Moving dry runs onto refusing_side_effects is a follow-up. The guard doesn't cover app.send_task yet, and dry_run_rebuild is an existing staff path I'd rather not change in this PR.
There was a problem hiding this comment.
Verified in 80266e2. The signal processor returns quietly under the guard, with a test. Moving dry runs onto the guard as a follow-up is fine.
…s only its own expansions, for its caller - At request time an evaluation evaluates only expansions built under it (build_at_request_time). A stored one is refused before anything is read or written: its rows would stay locked, and its members cleared, until the rollback. - A request-time evaluation answers its caller (ExpansionEvaluation(caller=...), anonymous unless given). What each reference finds is what the caller can view, not what its creator can (CollectionReference.viewer), and resolve() answers a version the caller can't view as one not found. build_at_request_time refuses a collection version the caller can't view. Without an evaluation nothing changes. - Equivalence tests for the incremental add (PUT .../references/, is_adding_all=False), with the collection's code and cascade exclusions evaluated again. - Code references: each version is searched for the codes of references naming its repository, not every source's. A stored build reads each creator once, not once per reference. - The sequence check: a sequence never used counts as none used, one this role can't read as unknown (no evaluation opens). Bigint ids on these tables would be the lasting fix. - SET LOCAL statement_timeout only once the time left has dropped STATEMENT_TIMEOUT_MARGIN (0.25 s) below the one last set, or a shorter evaluation opens inside; a savepoint's rollback has it set again. - The search index signal processor skips quietly while side effects are refused: no task and no error per row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qXjDrGi7Trb7ERK92a
…n't view is hidden where it's recorded, not resolved away - resolve() no longer answers a version the caller can't view as unresolved. That also hid which repository a reference names, so a public release named in system-version no longer applied to it when the source's newer release was private. At request time, the expansion now answers such a version as one not found where it's recorded: a system-version entry, a reference's own versions and its value sets (ExpansionEvaluation.hides). - The viewer checks go through ExpansionEvaluation.can_view, which an evaluation with content of its own can extend to let its own versions through. - The statement timeout is trusted as last set only when every execute wrapper that runs before the evaluation's is an evaluation's: another (FHIR's search timeout) may set a longer one before each statement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qXjDrGi7Trb7ERK92a
…per version, a shorter timeout set around it kept - ExpansionEvaluation.can_view reads whether a version may reach the caller once per version and viewer, not per reference: an anonymous build of thousands of code references to a public release was two queries per reference. - The statement timeout set is the time left or the one already in effect, whichever is shorter (set_config from pg_settings, in one statement): an enclosing search with less time left keeps its own. - build_at_request_time asks the evaluation whether the collection version may be built (can_view), so an evaluation with content of its own can build its own value sets; a test shows such an evaluation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qXjDrGi7Trb7ERK92a
…iew read again each opening; the build asks has_view_access - The evaluation's visibility answers are read again each time it opens: access can change between two requests. - build_at_request_time asks ExpansionEvaluation.can_build, by default has_view_access as the API's views ask, which an evaluation with content of its own extends for its own value sets. - The timeout tests start from a known timeout, and one checks a shorter timeout in effect when it opens is kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qXjDrGi7Trb7ERK92a
…owner collection the build refuses, as the API does Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qXjDrGi7Trb7ERK92a
|
Sunny's review is answered in 80266e2, with follow-ups in bc89616 to 0984907. Each thread has a reply:
The kill switch and the staging load measure are conditions of W1. They land with the first caller of Review:
The affected suites pass locally (1,790 tests that don't use the search index), and CI runs the rest. |
…valuation has no deadline within_deadline sets no timeout and cancels nothing while the evaluation's deadline is None, as it did before the deadline's rewrite: an evaluation opened within none, with no time of its own, has none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWddiMQHvvG5BYWRfh
…for no caller views as each reference's creator at_request_time takes for_caller (True by default). Opened with False, only so that nothing it evaluates is kept, as an expansion built outside a request may (an import evaluated again, in the stacked #1091), it answers no caller: each reference finds what its creator can view, as outside a request, nothing is hidden, and build_at_request_time builds what the references reached. answers_caller says which; viewer, viewer_id, hides and can_build follow it. The rollback, side-effect guard, deadline and own-expansion check are as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWddiMQHvvG5BYWRfh
snyaggarwal
left a comment
There was a problem hiding this comment.
Review round 2 (Sunny): verdict comment, approve once CI passes
Thanks for the thread replies and the summary. The Codex checks after each commit caught real cases I hadn't raised: a newer private release blocking a public system-version, a wrapper outside the evaluation outlasting its timeout, and visibility read twice per reference. I didn't repeat that ground. Each round-1 thread has a reply.
| # | Round 1 | Status | Commit |
|---|---|---|---|
| 1 | Request-time evaluation of a stored expansion held row locks | Fixed. check_own refuses before any read or write; test asserts no write or FOR UPDATE |
80266e2 |
| 2 | No caller identity; system-version could reach a private version |
Fixed. Caller-scoped on every request-time path; anonymous gets public only; hidden versions recorded as unresolved; build refuses an unviewable collection | 80266e2, bc89616, c4923df, 024b03b, 0984907 |
| 3 | Equivalence tests covered full rebuilds only | Fixed. Incremental PUT references cases, with code and cascade exclusions |
80266e2 |
| 4 | Every version searched for every deferred code | Fixed | 80266e2 |
| 5 | Sequence check: NULL last_value passed as 0 |
Fixed. Bigint ids tracked as a follow-up | 80266e2 |
| 6 | Extra SET LOCAL before every statement |
Fixed | 80266e2, c4923df |
| 7 | Second guard; one error log per refused row | Signal processor fixed. Moving dry runs onto the guard is a follow-up | 80266e2 |
How I checked finding 2. I traced each request-time path that resolves a repo version or reads members: the code batch, get_resource_queryset_from_system_and_valueset, system-version entries, a reference's own and resource-version-pinned versions, value sets (viewable_valueset_version_ids, unapplied_valuesets, recorded versions), the cascade version and omit_if_exists_in. All go through ExpansionEvaluation.can_view or hides. An anonymous caller becomes None, and can_view_all_content(None) and has_view_access(None) give public content only. The default resolution's result is checked in the same places, so it isn't trusted on its own. The refusal and the permission check both happen before the new expansion is saved.
New findings
| Severity | Where | Finding |
|---|---|---|
| nit | core/collections/evaluation.py:108 |
for_caller=False (c3aa422) turns off every caller check, can_build included. It's safe today, but a request path passing it along with request input would bring finding 2 back. Raise if a caller is given with it, and keep it to paths whose collection and parameters come from stored data. |
| nit (test) | core/collections/tests/tests_evaluation.py:478 |
There's no request-time test for a valueset naming a collection the caller can't view, or a cascade source_version the caller can't view. The code is correct by reading. |
7881fbf (no timeout while there's no deadline) is fine. Nothing else new. The keyed code batch, the timeout bookkeeping (nesting, savepoint rollback, outer wrappers) and the privilege-aware sequence read all look correct.
Kill switch and staging load. Deferring both to the first caller of at_request_time is acceptable, since nothing in production calls it yet. That PR must not merge without them. The key-share wait on member rows you described fits in that measure.
Switch off: API behaviour is unchanged. No production code calls at_request_time or build_at_request_time. With no evaluation, hides is always false, the viewer is the reference creator as before, and the new branches in add_references are skipped. The keyed code batch searches fewer codes per version but finds the same members; your equivalence tests cover rebuilds and incremental adds. The signal processor only skips under the guard, which only an evaluation opens.
CI: Pylint and Snyk passed on earlier heads; the Tests run on c3aa422 is still pending (the run on 0984907 was cancelled by the new push). I will approve once it passes.
Not verified: Reviewed up to c3aa422. I didn't run the tests locally (no DB); I relied on CI. Not checked: performance on production-sized data, and the role-switch sequence test on a non-superuser CI role.
| self.viewable = {} # (version class, version id, viewer id): what can_view answered while it's open | ||
|
|
||
| @contextmanager | ||
| def at_request_time(self, seconds, for_caller=True): |
There was a problem hiding this comment.
nit. for_caller=False turns off every caller check, can_build included. If a request path ever passes it along with request input such as system-version, finding 2 comes back. The default is safe and nothing calls it yet. Consider raising when a caller is given with for_caller=False, and keep the no-caller mode to paths whose collection and parameters come from stored data. I'll check that in #1091.
| return cursor.fetchone()[0] | ||
|
|
||
|
|
||
| class RequestTimeVisibilityTest(OCLTestCase): |
There was a problem hiding this comment.
nit (test). At request time, two visibility paths are correct by reading but have no test: a reference whose valueset names a collection the caller can't view (it should be unapplied as not found, and give nothing), and a cascade whose source_version names a version the caller can't view (it should add only the concept). Consider adding both cases here, built as anonymous and as the member.
snyaggarwal
left a comment
There was a problem hiding this comment.
Approved (Sunny). CI passes on c3aa422: Pylint, Tests and Snyk. This is the round-2 review's "approve once CI passes" (#1086 (review)). Its two nits stay open: the for_caller=False mode, and a request-time test for a value set or cascade version the caller can't view.
…ead (fhir-452-b-eval) into the version rules Brings in #1086's review answers (cc020b1..0984907): a request-time evaluation evaluates only expansions built under it, for its caller, and a version the caller can't view is answered as one not found. Conflicts, in core/collections: - evaluation.py imports: both sides' names kept. - Expansion.add_references, system-version entries: resolved under the build's evaluation, as the version rules have it; an entry the evaluation hides is answered as not found, as the request-time evaluation has it, and only a found one is asked whether it's held apart. - Expansion.add_references, a reference's versions: those the caller can't view are left out first, then check-system-version is checked against the versions it uses, so a failed check never names a version the caller can't view. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWddiMQHvvG5BYWRfh
…ead (fhir-452-b-eval) into reference filters Brings in #1086's review answers (cc020b1..0984907): a request-time evaluation evaluates only expansions built under it, for its caller, and a version the caller can't view is answered as one not found. Conflicts, in core/collections: - CodeReferenceBatch: it takes the references, as the request-time evaluation has it, and keeps the build's evaluation for matching codes ignoring case. A version is searched for the codes of references to its own repository (told_codes), and the search ignoring case then covers those codes. - Expansion.add_references: the batch is given the references and the evaluation. - tests_evaluation.py: both sides' tests kept. Adapted to the new interface (each creator check goes through the evaluation's can_view, so at request time it is the caller's): - _apply_database_filters walks a hierarchy in the version evaluated if its viewer can view it. - get_declared_filter_properties reads the properties of versions its viewer can view, cached by version and viewer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWddiMQHvvG5BYWRfh
…52-b-versions) into versions kept apart Brings in #1087's new head, which carries #1086's review answers: a request-time evaluation evaluates only expansions built under it, for its caller, and a version the caller can't view is answered as one not found, by the version rules' parameters too. One conflict, in core/collections/models.py: this branch moved the system version's queryset into get_system_queryset, and #1086 made the check there ask the evaluation's can_view (its viewer: the creator, or at request time the caller). get_system_queryset now asks can_view. Adapted to the new interface (each creator check goes through the evaluation): - CodeReferenceBatch.found_by_version reads viewability by the reference's viewer, as the batch now records it (it was keyed by creator, so at request time it found nothing). - member_versions.held_at_version groups plain codes by their reference's viewer and asks can_view. - In add_references the versions a caller can't view are left out before kept.meet, so a kept member version is never one the caller can't view (as for the version rules' checks). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWddiMQHvvG5BYWRfh
…r-452-b-apart) into imports Brings in #1090's new head, which carries #1087's and #1086's: a request-time evaluation evaluates only expansions built under it, for its caller (what references find is what the caller can view) unless opened for none, a version the caller can't view is answered as one not found, and a statement runs as it is while the evaluation has no deadline. Conflicts, in core/collections: - evaluation.py: ExpansionEvaluation keeps both sides' state (the caller, its own expansions and what it may view; what it built and the imports it evaluated). at_request_time's description keeps both halves, the no-seconds sentence included. within_deadline is #1086's, which lets a statement through with no deadline, as this branch's did. - models.py, build_at_request_time: both sides kept: refused for a version the evaluation may not build; locks_of's locks and the parameters it was built under recorded; the expansion registered as its own. Adapted to the new interface: this branch opens an evaluation at request time outside a request too, so that nothing a stored expansion's import evaluates again is kept (ValueSetImports.evaluate). An opening answers its caller unless opened with for_caller False, which #1086 now offers, so that path opens with for_caller False: the import is evaluated as its references' creators view it, as the stored build is, rather than as an anonymous caller (which refused a private import). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWddiMQHvvG5BYWRfh
…es), which the FHIR series builds on fhir-452-b-codes ends the queue of OCL API PRs, so the FHIR series sits on all of them: #1085, #1086, #1089, #1088, #1087, #1090, #1091, #1092 and #1093, and the core changes that need them together. No conflicts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qV2gzsF5GhF5BwTJ6x
Brings in #1085, #1086, #1082 and #1073. The two conflicts were adjacent additions (master's EXPANSION_FHIR_RULES_TOGGLE and evaluation import next to this branch's REFERENCE_SEARCH_OPTIONS_TOGGLE); both are kept. No change to this branch's own code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWUTom6BGgjQy6oehZ
Brings in the squash merges of #1085 and #1086, whose original commits this branch already holds, and #1082. Every conflict keeps this branch's side: the squashes match the original commits byte for byte, and the merged tree equals this branch's previous head plus #1082's changes. No change to this branch's own code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWUTom6BGgjQy6oehZ
Brings in the squash merge of #1086, whose original commits this branch already holds, and #1085 and #1082. Both conflicts keep this branch's side: the squash matches the original commits byte for byte, and the merged tree equals this branch's previous head merged cleanly with #1085 and #1082. No change to this branch's own code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWUTom6BGgjQy6oehZ
…into fhir-452-b-ops Takes #1098's new head, which brings in master's #1085, #1086 and #1082. No change to this branch's own code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qWUTom6BGgjQy6oehZ
Part of OpenConceptLab/ocl_online#452. Not part of the Dec 1 run.
What this does
Groundwork so OCL's own expansion model (
CollectionReference,Expansion) can evaluate value sets at request time. The HL7 Terminology Ecosystem IG's tests send the code systems and value sets a request uses with the request, so OCL needs to evaluate them without keeping anything. Nothing changes for API users: each new piece is used only when a caller asks for it, except the batching of code references, which gives the same results faster.ExpansionEvaluation(core/collections/evaluation.py) says how one expansion is evaluated:fhir_rules: which set of expansion rules it follows. A new toggle,EXPANSION_FHIR_RULES_TOGGLE, decides for API requests (absent, so off). A caller can set it for its own evaluation, so a FHIR evaluation and a collections request on one deployment each get their own. Nothing reads it yet; later changes put rules behind it.resolve(): one entry point through which a reference's system and value sets and thesystem-versionparameter resolve, with the version apart from the URL. A subclass can answer for its own canonicals before the shared resolver (which, with the URL registry on, answers a canonical with no registry entry as unresolved). By default it callsresolve_reference_expressionexactly as before.add_referencesandseed_childrentake an optionalevaluation. Without one, nothing changes.evaluation.at_request_time(seconds)opens one for a request:core/side_effects.py). Celery tasks and cache writes raise in tests and are skipped in production with an error logged. Search-index writes raise. On-commit hooks are refused when registered. Member removals don't mark the stored collection'slast_child_removal_at.SET LOCAL statement_timeoutfrom the time left, and search-index reads get the time left with no retries. Running out raisesEvaluationTooCostlyonce rolled back.Expansion.build_at_request_time()builds a new expansion of a collection version at once. It evaluates only expansions built under it: a stored one is refused before anything is written.ExpansionEvaluation(caller=...), anonymous unless one is given). What references find is what the caller can view, not what their creator can, and a version the caller can't view is answered as one not found. A collection version the caller can't view isn't built.CodeReferenceBatch). A reference to one concept by its code, with nothing else to apply, is no longer looked up on its own: each source version is searched once for all such codes. Includes and exclusions are applied in runs, before any other reference, so a reference that reads the expansion being built sees what it saw before. Expansion parameters that read members (exclude-system,date) apply reference by reference, as before.add_referencesalso reads its owner's resolution namespace once, not once per reference. On a request-time build, 10 or 40 code references now take the same number of queries.LINK_SEQUENCE_TABLESlists the link tables with 32-bit ids that a request-time evaluation writes, andlink_sequence_usage()reads each one's usage. A request-time evaluation doesn't open once one of them reaches 90% of its range, or can't be read. Bigint ids on these tables would be the lasting fix.Settings: the cache backend is now
core.common.cache.RedisCache(django_redis's, with its writes checked by the guard), and the search client usesRefusingTransport. With no evaluation open, both behave exactly as before.Evidence of no change for API users
activeOnly,system-version,exclude-systemnaming the collection itself, exclusions, cascades and a value set reference to its own collection. Deliberately breaking the batch makes them fail.exclude-system/datepath, which none of these expansions use and the equivalence tests cover.Left as it is
|versioncontains a:reachesresolve()as written: the shared resolver reads it as a canonical URL, and splitting it would change what such a reference resolves to.omit_if_exists_instill resolves through the shared resolver, not the evaluation'sresolve().Review
Three Codex defect passes (8, 7 and 4 findings; all fixed but the two above), a simplification review (2 of 8 cuts applied), a final Codex check (3 fixed) and a check of those fixes, plus two bugs found by the full test gate and a related branch's review, fixed with tests.
Since then, one small follow-up: a statement runs as it is while an evaluation has no deadline, as before the deadline rewrite. #1091 opens one with no time of its own, inside none. With a test; a Codex check found one P2, answered (no caller reopens an evaluation that is already open).
And a second: an evaluation can be opened at request time for no caller (
at_request_time(..., for_caller=False)), only so that nothing it evaluates is kept. #1091 does this when an expansion built outside a request evaluates an import again. Then each reference finds what its creator can view, as outside a request, and nothing is hidden or refused for a caller. With a test; Codex checks: two P2s, one fixed in the test, one answered.🤖 Generated with Claude Code
https://claude.ai/code/session_01AaZ4qWrEkUwedkj6bUPC61