@mailwoman/resolver-wof-sqlite 12.0.0 → 12.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/lib/address/keys/build.ts +35 -0
  2. package/lib/address/keys/lookup.ts +318 -6
  3. package/lib/address/keys/open.ts +1 -0
  4. package/lib/address/keys/point-lookup.ts +61 -2
  5. package/lib/address/keys/schema.ts +37 -0
  6. package/lib/address/number-forms.ts +32 -13
  7. package/lib/address/point/interpolation.ts +23 -6
  8. package/lib/address/point/schema.ts +198 -2
  9. package/lib/address/point/scope-search.ts +179 -0
  10. package/lib/address/point.ts +365 -32
  11. package/lib/build/candidate.ts +36 -9
  12. package/lib/candidate/ancestors/sidecar.ts +73 -4
  13. package/lib/candidate/del1.ts +218 -0
  14. package/lib/candidate/lookup.ts +159 -100
  15. package/lib/candidate/schema.ts +14 -2
  16. package/lib/fst/binary-matcher.ts +9 -1
  17. package/lib/fst/builder.ts +7 -0
  18. package/lib/fst/del1-sidecar.ts +782 -0
  19. package/lib/fst/deserialize-web.ts +14 -2
  20. package/lib/fst/matcher.ts +7 -1
  21. package/lib/fst/types.ts +8 -0
  22. package/lib/fst.ts +1 -0
  23. package/lib/index.ts +22 -2
  24. package/lib/labels/street/canonical.ts +333 -0
  25. package/lib/labels/street/centroid/schema.ts +23 -1
  26. package/lib/labels/street/interpolation.ts +32 -6
  27. package/lib/labels/street/morphology/fst/builder.ts +13 -0
  28. package/lib/labels/street/morphology/fst/loader.ts +32 -2
  29. package/lib/labels/street/normalize.ts +153 -4
  30. package/lib/labels/street.ts +1 -0
  31. package/lib/landmark.ts +43 -2
  32. package/lib/lookup/types.ts +0 -6
  33. package/lib/poi/lookup.ts +148 -52
  34. package/lib/poi/schema.ts +9 -1
  35. package/lib/schema/overture-match.ts +2 -1
  36. package/lib/weights/overlay-linker.ts +6 -2
  37. package/out/address/keys/build.d.ts.map +1 -1
  38. package/out/address/keys/build.js +28 -1
  39. package/out/address/keys/build.js.map +1 -1
  40. package/out/address/keys/lookup.d.ts +42 -0
  41. package/out/address/keys/lookup.d.ts.map +1 -1
  42. package/out/address/keys/lookup.js +182 -6
  43. package/out/address/keys/lookup.js.map +1 -1
  44. package/out/address/keys/open.d.ts.map +1 -1
  45. package/out/address/keys/open.js +1 -0
  46. package/out/address/keys/open.js.map +1 -1
  47. package/out/address/keys/point-lookup.d.ts +6 -1
  48. package/out/address/keys/point-lookup.d.ts.map +1 -1
  49. package/out/address/keys/point-lookup.js +43 -1
  50. package/out/address/keys/point-lookup.js.map +1 -1
  51. package/out/address/keys/schema.d.ts +21 -0
  52. package/out/address/keys/schema.d.ts.map +1 -1
  53. package/out/address/keys/schema.js +18 -0
  54. package/out/address/keys/schema.js.map +1 -1
  55. package/out/address/number-forms.d.ts +10 -1
  56. package/out/address/number-forms.d.ts.map +1 -1
  57. package/out/address/number-forms.js +20 -11
  58. package/out/address/number-forms.js.map +1 -1
  59. package/out/address/point/interpolation.d.ts.map +1 -1
  60. package/out/address/point/interpolation.js +15 -5
  61. package/out/address/point/interpolation.js.map +1 -1
  62. package/out/address/point/schema.d.ts +45 -2
  63. package/out/address/point/schema.d.ts.map +1 -1
  64. package/out/address/point/schema.js +129 -0
  65. package/out/address/point/schema.js.map +1 -1
  66. package/out/address/point/scope-search.d.ts +77 -0
  67. package/out/address/point/scope-search.d.ts.map +1 -0
  68. package/out/address/point/scope-search.js +107 -0
  69. package/out/address/point/scope-search.js.map +1 -0
  70. package/out/address/point.d.ts +24 -1
  71. package/out/address/point.d.ts.map +1 -1
  72. package/out/address/point.js +231 -30
  73. package/out/address/point.js.map +1 -1
  74. package/out/build/candidate.d.ts +8 -0
  75. package/out/build/candidate.d.ts.map +1 -1
  76. package/out/build/candidate.js +17 -7
  77. package/out/build/candidate.js.map +1 -1
  78. package/out/candidate/ancestors/sidecar.d.ts +7 -3
  79. package/out/candidate/ancestors/sidecar.d.ts.map +1 -1
  80. package/out/candidate/ancestors/sidecar.js +56 -4
  81. package/out/candidate/ancestors/sidecar.js.map +1 -1
  82. package/out/candidate/del1.d.ts +61 -0
  83. package/out/candidate/del1.d.ts.map +1 -0
  84. package/out/candidate/del1.js +158 -0
  85. package/out/candidate/del1.js.map +1 -0
  86. package/out/candidate/lookup.d.ts +2 -14
  87. package/out/candidate/lookup.d.ts.map +1 -1
  88. package/out/candidate/lookup.js +122 -84
  89. package/out/candidate/lookup.js.map +1 -1
  90. package/out/candidate/schema.d.ts +8 -2
  91. package/out/candidate/schema.d.ts.map +1 -1
  92. package/out/candidate/schema.js +8 -2
  93. package/out/candidate/schema.js.map +1 -1
  94. package/out/fst/binary-matcher.d.ts +7 -1
  95. package/out/fst/binary-matcher.d.ts.map +1 -1
  96. package/out/fst/binary-matcher.js +7 -1
  97. package/out/fst/binary-matcher.js.map +1 -1
  98. package/out/fst/builder.d.ts +2 -0
  99. package/out/fst/builder.d.ts.map +1 -1
  100. package/out/fst/builder.js +5 -0
  101. package/out/fst/builder.js.map +1 -1
  102. package/out/fst/del1-sidecar.d.ts +158 -0
  103. package/out/fst/del1-sidecar.d.ts.map +1 -0
  104. package/out/fst/del1-sidecar.js +581 -0
  105. package/out/fst/del1-sidecar.js.map +1 -0
  106. package/out/fst/deserialize-web.d.ts +3 -1
  107. package/out/fst/deserialize-web.d.ts.map +1 -1
  108. package/out/fst/deserialize-web.js +9 -2
  109. package/out/fst/deserialize-web.js.map +1 -1
  110. package/out/fst/matcher.d.ts +6 -1
  111. package/out/fst/matcher.d.ts.map +1 -1
  112. package/out/fst/matcher.js +6 -1
  113. package/out/fst/matcher.js.map +1 -1
  114. package/out/fst/types.d.ts +7 -0
  115. package/out/fst/types.d.ts.map +1 -1
  116. package/out/fst.d.ts +1 -0
  117. package/out/fst.d.ts.map +1 -1
  118. package/out/fst.js +1 -0
  119. package/out/fst.js.map +1 -1
  120. package/out/index.d.ts +4 -3
  121. package/out/index.d.ts.map +1 -1
  122. package/out/index.js +3 -2
  123. package/out/index.js.map +1 -1
  124. package/out/labels/street/canonical.d.ts +68 -0
  125. package/out/labels/street/canonical.d.ts.map +1 -0
  126. package/out/labels/street/canonical.js +234 -0
  127. package/out/labels/street/canonical.js.map +1 -0
  128. package/out/labels/street/centroid/schema.d.ts +10 -1
  129. package/out/labels/street/centroid/schema.d.ts.map +1 -1
  130. package/out/labels/street/centroid/schema.js +12 -0
  131. package/out/labels/street/centroid/schema.js.map +1 -1
  132. package/out/labels/street/interpolation.d.ts +9 -1
  133. package/out/labels/street/interpolation.d.ts.map +1 -1
  134. package/out/labels/street/interpolation.js +8 -5
  135. package/out/labels/street/interpolation.js.map +1 -1
  136. package/out/labels/street/morphology/fst/builder.d.ts +8 -0
  137. package/out/labels/street/morphology/fst/builder.d.ts.map +1 -1
  138. package/out/labels/street/morphology/fst/builder.js +5 -0
  139. package/out/labels/street/morphology/fst/builder.js.map +1 -1
  140. package/out/labels/street/morphology/fst/loader.d.ts +12 -0
  141. package/out/labels/street/morphology/fst/loader.d.ts.map +1 -1
  142. package/out/labels/street/morphology/fst/loader.js +18 -2
  143. package/out/labels/street/morphology/fst/loader.js.map +1 -1
  144. package/out/labels/street/normalize.d.ts +8 -0
  145. package/out/labels/street/normalize.d.ts.map +1 -1
  146. package/out/labels/street/normalize.js +138 -4
  147. package/out/labels/street/normalize.js.map +1 -1
  148. package/out/labels/street.d.ts +1 -0
  149. package/out/labels/street.d.ts.map +1 -1
  150. package/out/labels/street.js +1 -0
  151. package/out/labels/street.js.map +1 -1
  152. package/out/landmark.d.ts +8 -0
  153. package/out/landmark.d.ts.map +1 -1
  154. package/out/landmark.js +25 -2
  155. package/out/landmark.js.map +1 -1
  156. package/out/lookup/types.d.ts +0 -5
  157. package/out/lookup/types.d.ts.map +1 -1
  158. package/out/poi/lookup.d.ts +9 -1
  159. package/out/poi/lookup.d.ts.map +1 -1
  160. package/out/poi/lookup.js +111 -53
  161. package/out/poi/lookup.js.map +1 -1
  162. package/out/poi/schema.d.ts +7 -2
  163. package/out/poi/schema.d.ts.map +1 -1
  164. package/out/poi/schema.js +3 -0
  165. package/out/poi/schema.js.map +1 -1
  166. package/out/schema/overture-match.d.ts +2 -1
  167. package/out/schema/overture-match.d.ts.map +1 -1
  168. package/out/schema/overture-match.js.map +1 -1
  169. package/out/weights/overlay-linker.d.ts +1 -1
  170. package/out/weights/overlay-linker.d.ts.map +1 -1
  171. package/out/weights/overlay-linker.js +5 -1
  172. package/out/weights/overlay-linker.js.map +1 -1
  173. package/package.json +12 -12
@@ -2,7 +2,6 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
3
 
4
4
  import { expandPlacetypeFilter } from "@mailwoman/codex/labels/placetype-map"
5
- import type { VariantAliasExemption } from "@mailwoman/core/geocode"
6
5
  import {
7
6
  type Ancestor,
8
7
  type GazetteerArtifactCoverage,
@@ -13,7 +12,6 @@ import { refuseMissingOutcomeTables } from "@mailwoman/core/resolver/outcome"
13
12
  import { allRows } from "@mailwoman/core/utils"
14
13
  import { jaroWinkler, levenshteinSimilarity } from "@mailwoman/match/comparators"
15
14
  import { partitionByContainment } from "@mailwoman/resolver"
16
- import { haversine } from "@mailwoman/spatial/geometries/point/distance"
17
15
  import type { DatabaseClient } from "@mailwoman/sqlite/client"
18
16
  import { SQLiteLookup, type SQLiteLookupOptions } from "@mailwoman/sqlite/lookup"
19
17
 
@@ -25,6 +23,13 @@ import {
25
23
  type IntervalLabel,
26
24
  } from "#candidate/ancestors/schema"
27
25
  import { readGazetteerCoverageManifest } from "#candidate/coverage-manifest"
26
+ import {
27
+ CANDIDATE_DEL1_MAX_LENGTH,
28
+ CANDIDATE_DEL1_TABLE,
29
+ del1Keys,
30
+ firstCodePoint,
31
+ isWithinOneEdit,
32
+ } from "#candidate/del1"
28
33
  import { CANDIDATE_FTS_TABLE } from "#candidate/fts"
29
34
  import { candidateQueryKeyFold } from "#candidate/key-fold"
30
35
  import {
@@ -47,20 +52,9 @@ import { applyProximityRerank } from "#ranking/proximity-rerank"
47
52
  import { hasColumn, hasTable } from "#sqlite-utils"
48
53
 
49
54
  /**
50
- * Where a {@link WOFCandidateTableLookup} reads from
51
- * (a read-only `candidate.db` or a caller-held connection) and how it ranks.
55
+ * Database path or caller-held connection for {@link WOFCandidateTableLookup}.
52
56
  */
53
- export interface WOFCandidateTableLookupOpts extends SQLiteLookupOptions<CandidateDatabase> {
54
- /**
55
- * Exempt `name_role = 'variant'` aliases from the cross-country primary-preference penalty.
56
- *
57
- * - No-ops without the role column.
58
- * - `"not_applied"` penalizes variant aliases like any other.
59
- *
60
- * @defaultValue `"applied"`.
61
- */
62
- variantAliasExemption?: VariantAliasExemption
63
- }
57
+ export type WOFCandidateTableLookupOpts = SQLiteLookupOptions<CandidateDatabase>
64
58
 
65
59
  type CandidateRow = Pick<
66
60
  CandidateTable,
@@ -100,6 +94,8 @@ interface ContainmentOptions {
100
94
 
101
95
  const FUZZY_FETCH = 40
102
96
 
97
+ const DEL1_MAX_MATCHED_KEYS = 128
98
+
103
99
  const WORD_FUZZY_MIN = 0.85
104
100
 
105
101
  function wordFuzzySimilarity(a: string, b: string): number {
@@ -114,8 +110,6 @@ function wordCount(key: string): number {
114
110
  return key ? key.split(" ").length : 0
115
111
  }
116
112
 
117
- const POSTCODE_CONTAINMENT_THRESHOLD_KM = 25
118
-
119
113
  function ftsTrigramQuery(s: string): string {
120
114
  const grams = new Set<string>()
121
115
 
@@ -149,6 +143,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
149
143
 
150
144
  readonly #postalCityProbe: ReturnType<DatabaseClient["prepare"]> | undefined
151
145
 
146
+ readonly #hasDel1Table: boolean
147
+ readonly #del1Probes = new Map<number, ReturnType<DatabaseClient["prepare"]>>()
152
148
  readonly #ftsProbe: ReturnType<DatabaseClient["prepare"]> | undefined
153
149
  /**
154
150
  * Prepared unfiltered `name_key` existence probe, so fuzzy fallback runs only for true name misses.
@@ -160,7 +156,6 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
160
156
  readonly #importanceSelect: string
161
157
 
162
158
  readonly #hasNameRole: boolean
163
- readonly #variantAliasExemption: boolean
164
159
 
165
160
  readonly #roleSelect: string
166
161
 
@@ -209,18 +204,21 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
209
204
  )
210
205
  }
211
206
 
207
+ this.#hasDel1Table = hasTable(this.database, CANDIDATE_DEL1_TABLE)
208
+
212
209
  if (hasTable(this.database, CANDIDATE_FTS_TABLE)) {
213
210
  this.#ftsProbe = this.database.prepare(
214
211
  `SELECT name_key FROM ${CANDIDATE_FTS_TABLE} WHERE ${CANDIDATE_FTS_TABLE} MATCH ? ORDER BY bm25(${CANDIDATE_FTS_TABLE}) LIMIT ?`
215
212
  )
213
+ }
216
214
 
215
+ if (this.#hasDel1Table || this.#ftsProbe) {
217
216
  this.#nameKeyExistsProbe = this.database.prepare("SELECT 1 FROM candidate WHERE name_key = ? LIMIT 1")
218
217
  }
219
218
 
220
219
  // Optional columns are detected once here for hot-path reads.
221
220
  this.#importanceSelect = hasColumn(this.database, "candidate", "importance") ? ", importance" : ""
222
221
  this.#hasNameRole = hasColumn(this.database, "candidate", "name_role")
223
- this.#variantAliasExemption = (opts.variantAliasExemption ?? "applied") === "applied"
224
222
  this.#roleSelect = this.#hasNameRole ? ", name_role" : ""
225
223
 
226
224
  if (hasTable(this.database, CANDIDATE_ANCESTOR_TABLE)) {
@@ -525,29 +523,53 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
525
523
  return expandPlacetypeFilter(want as readonly string[]).includes("locality")
526
524
  }
527
525
 
528
- #postcodeAnchor(postcode: string, country?: string): { lat: number; lon: number } | null {
529
- const placetypeID = this.#placetypeToID.get("postalcode")
526
+ #del1MatchedNameKeys(nameKey: NameKey, hasCountryEvidence: boolean): string[] {
527
+ if (!this.#hasDel1Table) return []
528
+
529
+ const queryDelKeys = del1Keys(nameKey, CANDIDATE_DEL1_MAX_LENGTH + 1)
530
+
531
+ if (!queryDelKeys.length) return []
532
+
533
+ let stmt = this.#del1Probes.get(queryDelKeys.length)
534
+
535
+ if (!stmt) {
536
+ const placeholders = queryDelKeys.map(() => "?").join(",")
537
+
538
+ stmt = this.database.prepare(
539
+ `SELECT DISTINCT name_key FROM ${CANDIDATE_DEL1_TABLE} WHERE del_key IN (${placeholders})`
540
+ )
541
+
542
+ this.#del1Probes.set(queryDelKeys.length, stmt)
543
+ }
544
+
545
+ const hits = allRows<{ name_key: string }>(stmt, ...queryDelKeys)
546
+ const queryFirst = firstCodePoint(nameKey)
547
+ const matched = new Set<string>()
548
+
549
+ for (const hit of hits) {
550
+ const nk = this.#queryKeyFold(String(hit.name_key) as NameKey)
530
551
 
531
- if (typeof placetypeID !== "number") return null
552
+ if (nk === nameKey || matched.has(nk)) continue
532
553
 
533
- const conds = ["name_key = ?", "placetype_id = ?"]
534
- const params: Array<string | number> = [postcode.replaceAll(/\s+/g, ""), placetypeID]
554
+ if (!isWithinOneEdit(nameKey, nk)) continue
535
555
 
536
- if (country) {
537
- const countryID = this.#countryToID.get(country.toUpperCase())
556
+ if (!hasCountryEvidence && firstCodePoint(nk) !== queryFirst) continue
538
557
 
539
- if (typeof countryID !== "number") return null // Unknown country in this artifact.
540
- conds.push("country_id = ?")
541
- params.push(countryID)
558
+ matched.add(nk)
542
559
  }
543
560
 
544
- const row = this.database
545
- .prepare(`SELECT latitude, longitude FROM candidate WHERE ${conds.join(" AND ")} ORDER BY neg_rank ASC LIMIT 1`)
546
- .get(...params) as { latitude: number; longitude: number } | undefined
561
+ const keys = [...matched]
547
562
 
548
- if (!row || (Number(row.latitude) === 0 && Number(row.longitude) === 0)) return null
563
+ if (keys.length <= DEL1_MAX_MATCHED_KEYS) return keys
549
564
 
550
- return { lat: Number(row.latitude), lon: Number(row.longitude) }
565
+ return (
566
+ keys
567
+ .map((nk) => ({ nk, s: wordFuzzySimilarity(nameKey, nk) }))
568
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array on a hot path
569
+ .sort((a, b) => b.s - a.s)
570
+ .slice(0, DEL1_MAX_MATCHED_KEYS)
571
+ .map((h) => h.nk)
572
+ )
551
573
  }
552
574
 
553
575
  async findPlace(query: FindPlaceQuery): Promise<CandidatePlace[]> {
@@ -685,10 +707,58 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
685
707
  // Inside a stated region, an alias yields to a different place whose primary name equals
686
708
  // the query, including an own-name variant the exemption spares from the worldwide penalty.
687
709
  return regionID === null
688
- ? rankByPrimaryPreference(fetched, limit, undefined, this.#idToPlacetype, this.#variantAliasExemption)
710
+ ? rankByPrimaryPreference(fetched, limit, undefined, this.#idToPlacetype, true)
689
711
  : rankByPrimaryPreference(fetched, limit, regionAliasMargin, this.#idToPlacetype)
690
712
  }
691
713
 
714
+ const probeKeys = (
715
+ keys: readonly string[],
716
+ regionID: number | null,
717
+ countryID?: number
718
+ ): Array<RankedRow<CandidateRow>> => {
719
+ if (!keys.length) return []
720
+
721
+ if (keys.length === 1) return probe(keys[0]!, regionID, countryID)
722
+
723
+ const conds = [`name_key IN (${keys.map(() => "?").join(",")})`, ...filters]
724
+ const params: Array<string | number> = [...keys, ...filterParams]
725
+
726
+ if (regionID !== null) {
727
+ conds.push("region_id = ?")
728
+ params.push(regionID)
729
+ }
730
+
731
+ if (typeof countryID === "number") {
732
+ conds.push("country_id = ?")
733
+ params.push(countryID)
734
+ }
735
+
736
+ const sql =
737
+ "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
738
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE ${conds.join(" AND ")} ORDER BY neg_rank ASC LIMIT ?`
739
+
740
+ const fetched = allRows<CandidateRow>(this.database.prepare(sql), ...params, Math.max(limit, RERANK_FETCH))
741
+
742
+ // A place can appear under multiple 1-edit keys (such as primary and alias).
743
+ // Keep its best row per spr_id.
744
+ const bySPR = new Map<number, CandidateRow>()
745
+
746
+ for (const row of fetched) {
747
+ const sprID = Number(row.spr_id)
748
+ const prev = bySPR.get(sprID)
749
+
750
+ if (!prev || (prev.is_primary !== 1 && row.is_primary === 1)) {
751
+ bySPR.set(sprID, row)
752
+ }
753
+ }
754
+
755
+ const deduped = [...bySPR.values()]
756
+
757
+ return regionID === null
758
+ ? rankByPrimaryPreference(deduped, limit, undefined, this.#idToPlacetype, true)
759
+ : rankByPrimaryPreference(deduped, limit, regionAliasMargin, this.#idToPlacetype)
760
+ }
761
+
692
762
  const cascade = (regionID: number | null): Array<RankedRow<CandidateRow>> => {
693
763
  let rows = probe(nameKey, regionID)
694
764
 
@@ -710,35 +780,45 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
710
780
  !rows.length &&
711
781
  !wantsPostcode &&
712
782
  !(query.fuzzyCountry && !query.country && typeof fuzzyCountryID !== "number") &&
713
- this.#ftsProbe &&
714
- this.#nameKeyExistsProbe &&
783
+ (this.#hasDel1Table || this.#ftsProbe != null) &&
784
+ this.#nameKeyExistsProbe != null &&
715
785
  !this.#nameKeyExistsProbe.get(nameKey)
716
786
  ) {
717
- const match = ftsTrigramQuery(nameKey)
787
+ if (this.#hasDel1Table) {
788
+ const matchedKeys = this.#del1MatchedNameKeys(nameKey, hasCountryEvidence)
718
789
 
719
- if (match) {
720
- const hits = allRows<{ name_key: string }>(this.#ftsProbe, match, FUZZY_FETCH)
790
+ if (matchedKeys.length) {
791
+ rows = probeKeys(matchedKeys, regionID, fuzzyCountryID).map((r) => ({ ...r, fuzzy: true }))
792
+ }
793
+ }
721
794
 
722
- const ranked = hits
723
- // An index built before the artifact's key folds holds unfolded keys, so each hit is folded too.
724
- .map((h) => this.#queryKeyFold(String(h.name_key) as NameKey))
725
- .map((nk) => ({ nk, s: wordFuzzySimilarity(nameKey, nk) }))
726
- .filter((h) => h.s >= WORD_FUZZY_MIN && (hasCountryEvidence || h.nk[0] === nameKey[0]))
727
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
728
- .sort((a, b) => b.s - a.s)
795
+ if (!rows.length && this.#ftsProbe) {
796
+ const match = ftsTrigramQuery(nameKey)
729
797
 
730
- const seen = new Set<string>()
798
+ if (match) {
799
+ const hits = allRows<{ name_key: string }>(this.#ftsProbe, match, FUZZY_FETCH)
731
800
 
732
- for (const h of ranked) {
733
- if (seen.has(h.nk)) continue
734
- seen.add(h.nk)
801
+ const ranked = hits
802
+ // An index built before the artifact's key folds holds unfolded keys, so each hit is folded too.
803
+ .map((h) => this.#queryKeyFold(String(h.name_key) as NameKey))
804
+ .map((nk) => ({ nk, s: wordFuzzySimilarity(nameKey, nk) }))
805
+ .filter((h) => h.s >= WORD_FUZZY_MIN && (hasCountryEvidence || h.nk[0] === nameKey[0]))
806
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
807
+ .sort((a, b) => b.s - a.s)
735
808
 
736
- rows.push(...probe(h.nk, regionID, fuzzyCountryID).map((r) => ({ ...r, fuzzy: true })))
809
+ const seen = new Set<string>()
737
810
 
738
- if (rows.length >= limit) break
739
- }
811
+ for (const h of ranked) {
812
+ if (seen.has(h.nk)) continue
813
+ seen.add(h.nk)
740
814
 
741
- rows = rows.slice(0, limit)
815
+ rows.push(...probe(h.nk, regionID, fuzzyCountryID).map((r) => ({ ...r, fuzzy: true })))
816
+
817
+ if (rows.length >= limit) break
818
+ }
819
+
820
+ rows = rows.slice(0, limit)
821
+ }
742
822
  }
743
823
  }
744
824
 
@@ -754,55 +834,34 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
754
834
  regionScopeMiss = rows.length > 0
755
835
  }
756
836
 
757
- if (
758
- query.postcode &&
759
- query.postcodeContainmentCoherence === true &&
760
- this.#wantsLocality(query.placetype) &&
761
- rows.length > 1
762
- ) {
763
- const anchor = this.#postcodeAnchor(query.postcode, query.country)
764
-
765
- if (anchor) {
766
- const insideThreshold: Array<{ row: RankedRow<CandidateRow>; distanceKm: number }> = []
767
- const outsideThreshold: RankedRow<CandidateRow>[] = []
837
+ // Admin-containment re-rank runs last.
838
+ // Test the more specific resolved parent id before falling back to the region qualifier's name.
839
+ if (this.#wantsLocality(query.placetype)) {
840
+ const containmentOptions: ContainmentOptions = {
841
+ nameKey,
842
+ strippedKey: strippedNameKey,
843
+ shapeFilters,
844
+ shapeParams,
845
+ limit,
846
+ outcomeFilter,
847
+ }
768
848
 
769
- for (const row of rows) {
770
- const distanceKm = haversine(anchor.lat, anchor.lon, Number(row.latitude), Number(row.longitude))
849
+ let parentMatched = false
771
850
 
772
- if (distanceKm <= POSTCODE_CONTAINMENT_THRESHOLD_KM) {
773
- insideThreshold.push({ row, distanceKm })
774
- } else {
775
- outsideThreshold.push(row)
776
- }
777
- }
778
-
779
- if (insideThreshold.length) {
780
- // oxlint-disable-next-line unicorn/no-array-sort -- hot-path in-place sort
781
- insideThreshold.sort((a, b) => a.distanceKm - b.distanceKm)
782
- rows = [...insideThreshold.map(({ row }) => row), ...outsideThreshold]
783
- }
851
+ if (typeof query.parentQualifierID === "number" && this.#ancestorsProbe) {
852
+ // A resolved parent qualifies by id, so no name probe runs.
853
+ rows = this.#applyContainment(rows, new Set([query.parentQualifierID]), containmentOptions)
854
+ parentMatched = rows.some((row) => row.containedByQualifier === true)
784
855
  }
785
- }
786
856
 
787
- // Admin-containment re-rank runs last.
788
- const containmentOptions: ContainmentOptions = {
789
- nameKey,
790
- strippedKey: strippedNameKey,
791
- shapeFilters,
792
- shapeParams,
793
- limit,
794
- outcomeFilter,
795
- }
796
-
797
- if (query.regionQualifier?.trim() && this.#qualifierProbe && this.#wantsLocality(query.placetype)) {
798
- rows = this.#applyAdminContainment(rows, query.regionQualifier.trim(), query.country ?? null, containmentOptions)
799
- } else if (
800
- typeof query.parentQualifierID === "number" &&
801
- this.#ancestorsProbe &&
802
- this.#wantsLocality(query.placetype)
803
- ) {
804
- // A resolved parent qualifies by id, so no name probe runs (#2804).
805
- rows = this.#applyContainment(rows, new Set([query.parentQualifierID]), containmentOptions)
857
+ if (!parentMatched && query.regionQualifier?.trim() && this.#qualifierProbe) {
858
+ rows = this.#applyAdminContainment(
859
+ rows,
860
+ query.regionQualifier.trim(),
861
+ query.country ?? null,
862
+ containmentOptions
863
+ )
864
+ }
806
865
  }
807
866
 
808
867
  const candidates = rows.map((row) => this.#toCandidate(row, regionScopeMiss))
@@ -5,6 +5,7 @@ import { sql, type Kysely } from "kysely"
5
5
 
6
6
  import type { CandidateAncestorsDatabase } from "#candidate/ancestors/schema"
7
7
  import type { CapitalTable } from "#candidate/capital-schema"
8
+ import type { CandidateDel1Table } from "#candidate/del1"
8
9
  import type { NameKey } from "#labels/street/normalize"
9
10
  import type { OutcomeDatabase } from "#outcome/schema"
10
11
  import type { OvertureWOFMatchTable } from "#schema/overture-match"
@@ -144,6 +145,10 @@ export interface CandidateDatabase extends CandidateAncestorsDatabase, OutcomeDa
144
145
  * Wikipedia sitelink counts per `spr_id` for cross-layer prominence.
145
146
  */
146
147
  candidate_sitelinks: CandidateSitelinksTable
148
+ /**
149
+ * SymSpell 1-delete fuzzy index over prominent primary `name_key` values.
150
+ */
151
+ candidate_del1: CandidateDel1Table
147
152
  }
148
153
 
149
154
  /**
@@ -285,8 +290,9 @@ export async function createCandidatePostcodePlaceIndex(
285
290
  }
286
291
 
287
292
  /**
288
- * Create the clustered `without rowid` `concordances` table storing Wikidata
289
- * (`wd:id`) links for candidate `spr_id`s.
293
+ * Create the clustered `without rowid` `concordances` table storing Wikidata (`wd:id`)
294
+ * links for candidate `spr_id`s, with a covering reverse index so a QID from a
295
+ * clicked map label resolves to its `spr_id` in one index seek.
290
296
  */
291
297
  export async function createCandidateConcordancesTable(db: Kysely<CandidateDatabase>): Promise<void> {
292
298
  await db.schema
@@ -297,6 +303,12 @@ export async function createCandidateConcordancesTable(db: Kysely<CandidateDatab
297
303
  .addPrimaryKeyConstraint("concordances_pk", ["id", "other_source", "other_id"])
298
304
  .modifyEnd(sql`without rowid`)
299
305
  .execute()
306
+
307
+ await db.schema
308
+ .createIndex("concordances_by_other")
309
+ .on(CANDIDATE_CONCORDANCES_TABLE)
310
+ .columns(["other_source", "other_id", "id"])
311
+ .execute()
300
312
  }
301
313
 
302
314
  /**
@@ -15,6 +15,7 @@
15
15
  import type { AncestrieMatch } from "@mailwoman/ancestrie"
16
16
  import { hashFNV1a } from "@mailwoman/core/coarse-placer/fnv-hash"
17
17
 
18
+ import type { BinaryFSTDel1Lookup } from "#fst/del1-sidecar"
18
19
  import {
19
20
  decodePlaceEntry,
20
21
  idTableOffset,
@@ -65,6 +66,11 @@ function edgeHash(stateID: number, stringIndex: number): number {
65
66
  */
66
67
  export class BinaryFSTMatcher {
67
68
  readonly stateCount: number
69
+ /**
70
+ * Optional 1-delete fuzzy token sidecar (`FD1\0`) paired with this FST binary,
71
+ * or `null` when loaded without a sidecar.
72
+ */
73
+ readonly del1Sidecar: BinaryFSTDel1Lookup | null
68
74
  readonly #view: DataView
69
75
  readonly #bytes: Uint8Array
70
76
  readonly #decoder = new TextDecoder("utf-8")
@@ -88,10 +94,12 @@ export class BinaryFSTMatcher {
88
94
  readonly #edgeSlotTarget: Uint32Array
89
95
  #placeCount: number | null = null
90
96
 
91
- constructor(input: ArrayBuffer | Uint8Array) {
97
+ constructor(input: ArrayBuffer | Uint8Array, del1Sidecar: BinaryFSTDel1Lookup | null = null) {
92
98
  const bytes = input instanceof ArrayBuffer ? new Uint8Array(input) : input
93
99
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
94
100
 
101
+ this.del1Sidecar = del1Sidecar
102
+
95
103
  if (bytes.byteLength < HEADER_SIZE) throw new Error("FST buffer too small for header")
96
104
 
97
105
  if (FST_MAGIC_BYTES.some((byte, index) => bytes[index] !== byte)) {
@@ -16,6 +16,7 @@ import { allRows, getRow } from "@mailwoman/core/utils"
16
16
  import { DatabaseClient } from "@mailwoman/sqlite/client"
17
17
  import { resolvePath } from "path-ts"
18
18
 
19
+ import { buildFSTDel1Sidecar, type BuiltFSTDel1Sidecar } from "#fst/del1-sidecar"
19
20
  import { readWOFSourceIdentity } from "#fst/freshness"
20
21
  import type { FSTNode } from "#fst/matcher"
21
22
  import { FSTMatcher, normalizeTokens } from "#fst/matcher"
@@ -65,6 +66,7 @@ export async function buildFSTFromWOF(opts: BuildFSTOpts): Promise<{
65
66
  matcher: FSTMatcher
66
67
  provenance: FSTProvenance
67
68
  result: BuildFSTResult
69
+ del1Sidecar?: BuiltFSTDel1Sidecar
68
70
  }> {
69
71
  const countries = opts.countries ?? DEFAULT_COUNTRIES
70
72
  const placetypes = opts.placetypes ?? DEFAULT_PLACETYPES
@@ -382,6 +384,10 @@ export async function buildFSTFromWOF(opts: BuildFSTOpts): Promise<{
382
384
  : { exclusionPolicy: null, excludedInsertions: null }),
383
385
  }
384
386
 
387
+ const del1Sidecar = opts.buildDel1Sidecar
388
+ ? buildFSTDel1Sidecar(matcher, opts.buildDel1Sidecar === true ? {} : opts.buildDel1Sidecar)
389
+ : undefined
390
+
385
391
  return {
386
392
  matcher,
387
393
  provenance,
@@ -391,5 +397,6 @@ export async function buildFSTFromWOF(opts: BuildFSTOpts): Promise<{
391
397
  edgeCount,
392
398
  tokenCount: insertCount,
393
399
  },
400
+ ...(del1Sidecar ? { del1Sidecar } : {}),
394
401
  }
395
402
  }