fix(canonical): serialize junction observation_count with KeyedMutex + add removeObservation#179
Closed
sroussey wants to merge 1 commit into
Closed
fix(canonical): serialize junction observation_count with KeyedMutex + add removeObservation#179sroussey wants to merge 1 commit into
sroussey wants to merge 1 commit into
Conversation
The four canonical junction repos (CanonicalPersonAddressRepo, CanonicalPersonPhoneRepo, CanonicalCompanyAddressRepo, CanonicalCompanyPhoneRepo) did get(pk) -> mutate observation_count -> put(row) without serialization. Two concurrent EntityObserver.observePerson calls resolving to the same canonical id for the same address/phone raced their increments; one was lost. The reap path amplifies this: decrements race the same code. Wrap recordObservation and removeObservation in a module-scoped KeyedMutex<string> per repo, keyed on the serialized composite PK (uses \x00 as a sentinel that can't occur in a UUID / hash / phone / resolver_version). The lock scope is get + put only — the resolver call in EntityObserver already sits outside the junction critical section. Different PKs still run concurrently; each repo file has its own module mutex so distinct repos never contend with each other either.
Contributor
Author
|
Integrated into #176. The four junction repos' Generated by Claude Code |
sroussey
pushed a commit
that referenced
this pull request
Jul 2, 2026
Correctness: - parseDate: restore the literal year via setUTCFullYear before the calendar probe. Date.UTC remaps years 0-99 to 1900-1999, so a valid 4-digit year like '0099-01-01' was wrongly rejected as an invalid calendar date. Regression test added; Feb-30-style rollover detection is unaffected. Resilience regression from #178's stricter parseDate throw: - FetchQuarterlyIndexTask / FetchQuarterlyFormIdxTask: wrap the per-row secDate() in try/catch so a single calendar-invalid EDGAR 'Date Filed' row is skipped+warned instead of aborting the whole quarter's batch (parseDate now throws where it previously rolled forward). Cleanup: - XbrlFactRepo.clearForAccession delegates to replaceForAccession(acc, [], { intentionalClear: true }), removing a byte-identical duplicate delete loop. Skipped (documented in review): the 4-way junction-repo copy-paste (would need a shared CanonicalJunctionRepo base — larger refactor beyond this diff); the CLI --date throw (operator fail-fast is acceptable); wiring clearForAccession into xbrlEnrichment (pre-existing behavior #177 deliberately left unchanged); and 5 concurrency observations that are pre-existing #175 reap-path limitations or documented single-process scope, not wave-2 regressions.
sroussey
pushed a commit
that referenced
this pull request
Jul 2, 2026
The four Canonical{Person,Company}{Address,Phone}Repo files each carried an
identical copy of the #179 concurrency logic — a module-scoped KeyedMutex, a
\x00-joined junctionKey helper, and the lock-wrapped recordObservation /
removeObservation read-modify-write (increment / decrement / delete-at-zero).
A fix to the lock key or the count math had to be applied four times, and
patching three of four would silently leave the fourth table racy.
Extract one generic CanonicalJunctionRepo<TRow> base (mirroring the existing
FamilyMembershipRepo<TRow> precedent) that owns the mutex, key composition, and
record/remove/list/delete logic, parameterized by the row type and the two
composite-PK column names. The four repos become thin subclasses that bind their
DI token + columns and adapt the named-field public API to the base — so the
public surface (recordObservation/removeObservation/listForCanonical/
deleteForResolverVersion + the { canonicalXRepository } options) is unchanged and
no caller or test needed edits.
A single process-wide lock map is now shared, with keys namespaced by a per-kind
prefix so distinct junction tables still never contend (behaviorally identical to
the prior four separate mutexes). Net -70 production LOC; the concurrency-sensitive
logic lives in one place.
Verified: bun run build clean; storage/canonical 94, resolver 66,
storage/versioning 103, exempt-offerings forms 169; full suite 1578 pass / 7
pre-existing network fails.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The four canonical junction repos (
CanonicalPersonAddressRepo,CanonicalPersonPhoneRepo,CanonicalCompanyAddressRepo,CanonicalCompanyPhoneRepo) didget(pk) -> mutate observation_count -> put(row)without serialization. Two concurrentEntityObserver.observePersoncalls resolving to the samecanonical_person_idfor the same address/phone raced their increments; one was lost. The reap path introduced in #175 amplifies this:removeObservationdecrements race the same code.The fix
recordObservationandremoveObservationin a module-scopedKeyedMutex<string>inside each of the four junction repos.\x00sentinel (never occurs in a UUID / address hash / E.164 number / semver, so distinct PKs can't collide):${canonical_(person|company)_id}\x00${address_hash_id}\x00${resolver_version}${canonical_(person|company)_id}\x00${international_number}\x00${resolver_version}get + putonly. The resolver call inEntityObserveralready sits outside the junction critical section, so no head-of-line blocking of resolves.removeObservationremoveObservation(pk)(the inverse ofrecordObservation) is already present on all four repos and is what the reaper calls. It stays no-op when the row doesn't exist (idempotent replays), decrements whenobservation_count > 1, and deletes when<= 1. The mutex now serialises it too, so concurrent record + remove for the same PK can't lose an update.Tests
Canonical{Person,Company}{Address,Phone}Repo.concurrency.test.ts(4 files):recordObservationfor the same PK -> finalobservation_count === 100.observation_count === 50(net zero delta).putproves no head-of-line blocking across keys.Canonical{Person,Company}{Address,Phone}Repo.removeObservation.test.ts(4 files):> 1; deletes when=== 1; no-op when absent.EntityObserver.concurrency.test.ts:observePersoncalls for the same canonical + same address ->observation_count === 2.Verification
bun test src/storage/canonical/-> 94 pass.bun test src/resolver/-> 66 pass.bun test src/task/forms/ProcessAccessionDocFormTask-> 14 pass.bunx tsc --noEmit-> clean.bun test(full suite) -> 1453 pass, 7 pre-existing network fetch-index test timeouts (FetchQuarterlyIndexTask/FetchDailyIndexTask) unrelated to this change.Test plan
bun test src/storage/canonical/locallybun test src/resolver/locallyGenerated by Claude Code