@mailwoman/resolver 9.0.0 → 9.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.
- package/README.md +89 -0
- package/admin-coherence-passes.ts +435 -0
- package/admin-containment.ts +101 -0
- package/admin-winner.ts +178 -0
- package/backend-capabilities.ts +88 -0
- package/bare-toponym-race.ts +129 -0
- package/decorate-node.ts +127 -0
- package/fold-name.ts +19 -3
- package/index.ts +14 -0
- package/out/admin-coherence-passes.d.ts +70 -0
- package/out/admin-coherence-passes.d.ts.map +1 -0
- package/out/admin-coherence-passes.js +327 -0
- package/out/admin-coherence-passes.js.map +1 -0
- package/out/admin-containment.d.ts +48 -0
- package/out/admin-containment.d.ts.map +1 -0
- package/out/admin-containment.js +82 -0
- package/out/admin-containment.js.map +1 -0
- package/out/admin-winner.d.ts +109 -0
- package/out/admin-winner.d.ts.map +1 -0
- package/out/admin-winner.js +119 -0
- package/out/admin-winner.js.map +1 -0
- package/out/backend-capabilities.d.ts +37 -0
- package/out/backend-capabilities.d.ts.map +1 -0
- package/out/backend-capabilities.js +75 -0
- package/out/backend-capabilities.js.map +1 -0
- package/out/bare-toponym-race.d.ts +55 -0
- package/out/bare-toponym-race.d.ts.map +1 -0
- package/out/bare-toponym-race.js +110 -0
- package/out/bare-toponym-race.js.map +1 -0
- package/out/decorate-node.d.ts +24 -0
- package/out/decorate-node.d.ts.map +1 -0
- package/out/decorate-node.js +103 -0
- package/out/decorate-node.js.map +1 -0
- package/out/fold-name.d.ts +18 -3
- package/out/fold-name.d.ts.map +1 -1
- package/out/fold-name.js +19 -3
- package/out/fold-name.js.map +1 -1
- package/out/index.d.ts +4 -1
- package/out/index.d.ts.map +1 -1
- package/out/index.js +3 -1
- package/out/index.js.map +1 -1
- package/out/postcode-country-coherence.d.ts +91 -14
- package/out/postcode-country-coherence.d.ts.map +1 -1
- package/out/postcode-country-coherence.js +279 -42
- package/out/postcode-country-coherence.js.map +1 -1
- package/out/postcode-prefix.d.ts +101 -0
- package/out/postcode-prefix.d.ts.map +1 -0
- package/out/postcode-prefix.js +125 -0
- package/out/postcode-prefix.js.map +1 -0
- package/out/postcode-shape-coherence.d.ts +113 -0
- package/out/postcode-shape-coherence.d.ts.map +1 -0
- package/out/postcode-shape-coherence.js +193 -0
- package/out/postcode-shape-coherence.js.map +1 -0
- package/out/resolve.d.ts +1 -1
- package/out/resolve.d.ts.map +1 -1
- package/out/resolve.js +592 -410
- package/out/resolve.js.map +1 -1
- package/out/span-rescore.d.ts +28 -0
- package/out/span-rescore.d.ts.map +1 -1
- package/out/span-rescore.js +151 -17
- package/out/span-rescore.js.map +1 -1
- package/out/street-evidence.js +1 -1
- package/out/street-evidence.js.map +1 -1
- package/out/street-tier.d.ts.map +1 -1
- package/out/street-tier.js +28 -5
- package/out/street-tier.js.map +1 -1
- package/out/toponym-prior.d.ts +139 -0
- package/out/toponym-prior.d.ts.map +1 -0
- package/out/toponym-prior.js +308 -0
- package/out/toponym-prior.js.map +1 -0
- package/package.json +98 -7
- package/postcode-country-coherence.ts +355 -50
- package/postcode-prefix.ts +166 -0
- package/postcode-shape-coherence.ts +248 -0
- package/resolve.ts +809 -527
- package/span-rescore.ts +206 -19
- package/street-evidence.ts +1 -1
- package/street-tier.ts +31 -5
- package/toponym-prior.ts +367 -0
package/resolve.ts
CHANGED
|
@@ -13,52 +13,294 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
|
|
16
|
-
import { isStreetDirectionalToken } from "@mailwoman/codex/us"
|
|
17
16
|
import type { AddressNode, AddressTree, ComponentTag, Interpretation } from "@mailwoman/core/decoder"
|
|
18
17
|
import {
|
|
19
|
-
type
|
|
18
|
+
type BackendCapabilityGap,
|
|
20
19
|
type CoincidentLocality,
|
|
20
|
+
compareReferential,
|
|
21
|
+
type ResolveCandidateTrace,
|
|
22
|
+
type ResolveNodeTrace,
|
|
21
23
|
DEFAULT_PLACETYPE_MAP,
|
|
22
|
-
type InterpolationLookup,
|
|
23
24
|
isPlacetypeFallback,
|
|
24
25
|
type PlacetypeMap,
|
|
26
|
+
type PostcodePrefixIndexLike,
|
|
27
|
+
referentialFromPopulation,
|
|
25
28
|
type ResolvedPlace,
|
|
26
29
|
type ResolveOpts,
|
|
27
30
|
type Resolver,
|
|
28
31
|
type ResolverBackend,
|
|
29
|
-
|
|
32
|
+
countriesFromPostcodeFormat,
|
|
30
33
|
} from "@mailwoman/core/resolver"
|
|
34
|
+
import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
|
|
31
35
|
import { haversineKm } from "@mailwoman/spatial"
|
|
32
36
|
|
|
33
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
applyAdminCoherence,
|
|
39
|
+
applyExplicitCountryCoherence,
|
|
40
|
+
applyRegionCountryCoherence,
|
|
41
|
+
} from "./admin-coherence-passes.ts"
|
|
42
|
+
import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "./admin-containment.ts"
|
|
43
|
+
import { describeCapabilityGaps, reportCapabilityGaps } from "./backend-capabilities.ts"
|
|
44
|
+
import {
|
|
45
|
+
BARE_REGION_DOMINANCE_LOG10,
|
|
46
|
+
bareCountryCandidate,
|
|
47
|
+
bareRegionCandidate,
|
|
48
|
+
logPopulation,
|
|
49
|
+
loneBareLocalityNode,
|
|
50
|
+
pickLargerAdmin,
|
|
51
|
+
} from "./bare-toponym-race.ts"
|
|
52
|
+
import { decorateNode, isResolvedWithCoord } from "./decorate-node.ts"
|
|
34
53
|
import {
|
|
35
54
|
findPostcodeCountryScope,
|
|
36
55
|
type PostcodeCountryScope,
|
|
37
56
|
stampPostcodeCountryScope,
|
|
38
57
|
} from "./postcode-country-coherence.ts"
|
|
58
|
+
import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "./postcode-prefix.ts"
|
|
59
|
+
import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.ts"
|
|
39
60
|
import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.ts"
|
|
40
61
|
import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.ts"
|
|
62
|
+
import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
|
|
41
63
|
|
|
42
64
|
/**
|
|
43
65
|
* Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
|
|
44
|
-
* `PlaceLookup` — e.g. `new
|
|
66
|
+
* `PlaceLookup` — e.g. `new WOFSQLitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
|
|
45
67
|
*/
|
|
46
68
|
export function createWOFResolver(backend: ResolverBackend): Resolver {
|
|
47
69
|
return new WOFResolver(backend)
|
|
48
70
|
}
|
|
49
71
|
|
|
72
|
+
/**
|
|
73
|
+
* #1735 (second half) — the tree's own country statement, when it is unambiguous.
|
|
74
|
+
*
|
|
75
|
+
* "SW1A 1AA, UK" under the en-US default parsed correctly and still failed: the walk resolved the country NODE to GB,
|
|
76
|
+
* but a sibling's resolution never scopes a sibling — the postcode lookup ran under the locale-inferred `country=US`
|
|
77
|
+
* hard filter and missed. An explicit country token is the address's OWN scope declaration, which outranks a locale
|
|
78
|
+
* inference the same way the #912 posture ranks explicit over inferred.
|
|
79
|
+
*
|
|
80
|
+
* Deterministically guarded: exactly ONE country-tagged node, whose value `matchCountry` maps to one ISO country, and
|
|
81
|
+
* whose value is NOT also a subdivision name — "Georgia" maps to GE _and_ names a US state, so it never pre-scopes (the
|
|
82
|
+
* existing coherence passes keep handling it). Returns the alpha-2 or null.
|
|
83
|
+
*/
|
|
84
|
+
function explicitCountryScope(roots: readonly AddressNode[]): string | null {
|
|
85
|
+
const countryNodes: AddressNode[] = []
|
|
86
|
+
const stack = [...roots]
|
|
87
|
+
|
|
88
|
+
while (stack.length) {
|
|
89
|
+
const node = stack.pop()!
|
|
90
|
+
|
|
91
|
+
if (node.tag === "country" && node.value.trim()) {
|
|
92
|
+
countryNodes.push(node)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
stack.push(...node.children)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (countryNodes.length !== 1) return null
|
|
99
|
+
const value = countryNodes[0]!.value.trim()
|
|
100
|
+
const matched = matchCountry(value)
|
|
101
|
+
|
|
102
|
+
if (!matched) return null
|
|
103
|
+
|
|
104
|
+
if (matchSubdivision(value)) return null
|
|
105
|
+
|
|
106
|
+
return matched.iso2
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Cap on candidates recorded per {@link ResolveNodeTrace} — the trace is a record, not a dump. The count past the cap is
|
|
111
|
+
* reported in `candidatesTruncated`, so absence of a row is never silent.
|
|
112
|
+
*/
|
|
113
|
+
const TRACE_CANDIDATE_CAP = 10
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The fine end of the probe window: `microhood` and no finer.
|
|
117
|
+
*
|
|
118
|
+
* Everything above it — `postalcode`, `venue`, `campus`, `building`, `address` — is excluded because a mislabeled ADMIN
|
|
119
|
+
* span lands on another admin band, and probing every venue in a country per miss buys a long tail of coincidental name
|
|
120
|
+
* matches for a diagnostic that is meant to be read.
|
|
121
|
+
*/
|
|
122
|
+
const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"]!
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The coarse end of the probe window. `country` and no coarser: a name matching at `continent` or `planet` says nothing
|
|
126
|
+
* about a mislabeled admin span, and the walk resolves the country from its own node anyway.
|
|
127
|
+
*/
|
|
128
|
+
const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The admin bands `ResolveOpts.diagnoseUnreachable` re-probes, coarse to fine.
|
|
132
|
+
*
|
|
133
|
+
* Derived from `PLACETYPE_SPECIFICITY` rather than typed out, so a placetype added there is probed here without anyone
|
|
134
|
+
* remembering to.
|
|
135
|
+
*/
|
|
136
|
+
const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
|
|
137
|
+
.filter(([, rank]) => rank !== undefined && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
|
|
138
|
+
.toSorted((a, b) => (a[1] as number) - (b[1] as number))
|
|
139
|
+
.map(([placetype]) => placetype)
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Per-lookup trace bookkeeping (#1721). `#lookupAndPick` talks to ONE of these unconditionally — a real recorder when
|
|
143
|
+
* `ResolveOpts.traceSink` is set, the frozen {@link NOOP_TRACE_RECORDER} otherwise — so the hot path carries no
|
|
144
|
+
* per-event branches and the no-sink walk costs a handful of empty calls per node.
|
|
145
|
+
*/
|
|
146
|
+
interface NodeTraceRecorder {
|
|
147
|
+
bind(
|
|
148
|
+
node: AddressNode,
|
|
149
|
+
placetype: string,
|
|
150
|
+
query: {
|
|
151
|
+
country?: string
|
|
152
|
+
parentID?: string | number
|
|
153
|
+
postcode?: string
|
|
154
|
+
regionQualifier?: string
|
|
155
|
+
limit?: number
|
|
156
|
+
},
|
|
157
|
+
defaultLimit: number
|
|
158
|
+
): void
|
|
159
|
+
gate(name: string): void
|
|
160
|
+
stage(name: string, order: readonly ResolvedPlace[]): void
|
|
161
|
+
reachable(bands: NonNullable<ResolveNodeTrace["reachableIn"]>): void
|
|
162
|
+
emit(picked: NonNullable<ResolveNodeTrace["picked"]> | null): void
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
|
|
166
|
+
bind() {},
|
|
167
|
+
gate() {},
|
|
168
|
+
stage() {},
|
|
169
|
+
reachable() {},
|
|
170
|
+
emit() {},
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void): NodeTraceRecorder {
|
|
174
|
+
const gates: string[] = []
|
|
175
|
+
const stageOrders: Array<[string, readonly ResolvedPlace[]]> = []
|
|
176
|
+
|
|
177
|
+
let reachableIn: ResolveNodeTrace["reachableIn"]
|
|
178
|
+
|
|
179
|
+
let ctx: {
|
|
180
|
+
node: AddressNode
|
|
181
|
+
placetype: string
|
|
182
|
+
query: Parameters<NodeTraceRecorder["bind"]>[2]
|
|
183
|
+
defaultLimit: number
|
|
184
|
+
} | null = null
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
bind(node, placetype, query, defaultLimit) {
|
|
188
|
+
ctx = { node, placetype, query, defaultLimit }
|
|
189
|
+
},
|
|
190
|
+
gate(name) {
|
|
191
|
+
gates.push(name)
|
|
192
|
+
},
|
|
193
|
+
stage(name, order) {
|
|
194
|
+
stageOrders.push([name, order])
|
|
195
|
+
},
|
|
196
|
+
reachable(bands) {
|
|
197
|
+
reachableIn = bands
|
|
198
|
+
},
|
|
199
|
+
emit(picked) {
|
|
200
|
+
if (!ctx) return
|
|
201
|
+
|
|
202
|
+
const rankMap = new Map<ResolvedPlace, Record<string, number>>()
|
|
203
|
+
|
|
204
|
+
for (const [stage, order] of stageOrders) {
|
|
205
|
+
order.forEach((candidate, index) => {
|
|
206
|
+
let ranks = rankMap.get(candidate)
|
|
207
|
+
|
|
208
|
+
if (!ranks) {
|
|
209
|
+
ranks = {}
|
|
210
|
+
rankMap.set(candidate, ranks)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
ranks[stage] = index + 1
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const finalOrder = stageOrders.at(-1)?.[1] ?? []
|
|
218
|
+
|
|
219
|
+
const rows: ResolveCandidateTrace[] = finalOrder.slice(0, TRACE_CANDIDATE_CAP).map((c) => ({
|
|
220
|
+
id: c.id,
|
|
221
|
+
name: c.name,
|
|
222
|
+
country: c.country,
|
|
223
|
+
placetype: c.placetype,
|
|
224
|
+
score: c.score,
|
|
225
|
+
...(c.prominence !== undefined ? { prominence: c.prominence } : {}),
|
|
226
|
+
...(c.importance !== undefined ? { importance: c.importance } : {}),
|
|
227
|
+
...(c.population !== undefined ? { population: c.population } : {}),
|
|
228
|
+
...(c.exactMatch !== undefined ? { exactMatch: c.exactMatch } : {}),
|
|
229
|
+
...(c.containedByQualifier !== undefined ? { containedByQualifier: c.containedByQualifier } : {}),
|
|
230
|
+
ranks: rankMap.get(c) ?? {},
|
|
231
|
+
}))
|
|
232
|
+
|
|
233
|
+
sink({
|
|
234
|
+
tag: ctx.node.tag,
|
|
235
|
+
value: ctx.node.value,
|
|
236
|
+
placetype: ctx.placetype,
|
|
237
|
+
query: {
|
|
238
|
+
...(ctx.query.country ? { country: ctx.query.country } : {}),
|
|
239
|
+
...(ctx.query.parentID !== undefined ? { parentID: ctx.query.parentID } : {}),
|
|
240
|
+
...(ctx.query.postcode ? { postcode: ctx.query.postcode } : {}),
|
|
241
|
+
...(ctx.query.regionQualifier ? { regionQualifier: ctx.query.regionQualifier } : {}),
|
|
242
|
+
limit: ctx.query.limit ?? ctx.defaultLimit,
|
|
243
|
+
},
|
|
244
|
+
gates,
|
|
245
|
+
...(reachableIn ? { reachableIn } : {}),
|
|
246
|
+
candidates: rows,
|
|
247
|
+
candidatesTruncated: Math.max(0, finalOrder.length - TRACE_CANDIDATE_CAP),
|
|
248
|
+
picked,
|
|
249
|
+
})
|
|
250
|
+
},
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
50
254
|
interface ResolutionState {
|
|
51
255
|
lookupsRemaining: number
|
|
52
256
|
placetypeMap: PlacetypeMap
|
|
53
257
|
minWinningScore: number
|
|
54
258
|
candidatesPerLookup: number
|
|
55
259
|
defaultCountry?: string
|
|
260
|
+
/**
|
|
261
|
+
* Whether {@link defaultCountry} came from the locale rather than the caller. Consulted only by `country`-placetype
|
|
262
|
+
* lookups, which skip an inferred scope — see `ResolveOpts.defaultCountryIsInferred`.
|
|
263
|
+
*/
|
|
264
|
+
defaultCountryIsInferred: boolean
|
|
265
|
+
/**
|
|
266
|
+
* The tree's single value-bearing node when it is locality-tagged (the bare-toponym shape), else null. Gates the
|
|
267
|
+
* country-placetype sibling race in `#lookupAndPick` — a bare name can be a country the parser tagged `locality`
|
|
268
|
+
* ("Japan", "China"), and the locality placetype filter makes the country row unreachable no matter how it ranks.
|
|
269
|
+
*/
|
|
270
|
+
bareLocalityNode: AddressNode | null
|
|
56
271
|
parentFallback: boolean
|
|
57
272
|
/**
|
|
58
273
|
* The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
|
|
59
274
|
* can inject postcode-proximal locality candidates.
|
|
60
275
|
*/
|
|
61
276
|
postcode?: string
|
|
277
|
+
/**
|
|
278
|
+
* Postcode-containment coherence (#31, Mechanism 2) — forwarded to locality lookups so a coordinate-first backend can
|
|
279
|
+
* re-rank name candidates by proximity to the postcode's own centroid. Opt-in; OFF by default.
|
|
280
|
+
*/
|
|
281
|
+
postcodeContainmentCoherence: boolean
|
|
282
|
+
/**
|
|
283
|
+
* Postcode-prefix prior (#31, Mechanism 3) — on a `postalcode` miss, derive the code's prefix and probe
|
|
284
|
+
* `postcodePrefixIndex`. Opt-in; OFF by default.
|
|
285
|
+
*/
|
|
286
|
+
postcodePrefixPrior: boolean
|
|
287
|
+
/**
|
|
288
|
+
* #1589 — the countries the parsed postcode's FORMAT implies (the #928 singles plus the shared `NNN NN` family). When
|
|
289
|
+
* set AND no country constraint survives, the `postalcode` lookup probes exactly these countries and abstains if all
|
|
290
|
+
* miss — never falling through to an unconstrained probe, whose space-stripped fold collides across systems (`100 00`
|
|
291
|
+
* folded to `10000` answers Troyes FR while Prague sits in the artifact under both keyings).
|
|
292
|
+
*/
|
|
293
|
+
postcodeFormatCountries?: readonly string[]
|
|
294
|
+
/**
|
|
295
|
+
* #1585 — the locale hint's country, forwarded to the backend as `fuzzyCountry` on every primary lookup. Scopes the
|
|
296
|
+
* typo-fuzzy tier only; exact matches stay worldwide. See `ResolveOpts.fuzzyCountryScope`.
|
|
297
|
+
*/
|
|
298
|
+
fuzzyCountryScope?: string
|
|
299
|
+
/**
|
|
300
|
+
* The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
|
|
301
|
+
* fire.
|
|
302
|
+
*/
|
|
303
|
+
postcodePrefixIndex?: PostcodePrefixIndexLike
|
|
62
304
|
/**
|
|
63
305
|
* Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
|
|
64
306
|
*/
|
|
@@ -71,6 +313,28 @@ interface ResolutionState {
|
|
|
71
313
|
* Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
|
|
72
314
|
*/
|
|
73
315
|
anchorWeight: number
|
|
316
|
+
/**
|
|
317
|
+
* #1721 resolver-interior trace sink. Undefined (the default) = zero bookkeeping, byte-identical walk.
|
|
318
|
+
*/
|
|
319
|
+
traceSink?: (record: ResolveNodeTrace) => void
|
|
320
|
+
/**
|
|
321
|
+
* Re-probe a resolved-nothing lookup across the other admin bands and record which hold it. Diagnostic only — never
|
|
322
|
+
* reaches the pick. See `ResolveOpts.diagnoseUnreachable`.
|
|
323
|
+
*/
|
|
324
|
+
diagnoseUnreachable?: boolean
|
|
325
|
+
/**
|
|
326
|
+
* #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
|
|
327
|
+
* byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
|
|
328
|
+
*/
|
|
329
|
+
localeCountryPrior?: string
|
|
330
|
+
/**
|
|
331
|
+
* Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
|
|
332
|
+
*/
|
|
333
|
+
localeCountryPriorWeight: number
|
|
334
|
+
/**
|
|
335
|
+
* #1880 capital status per candidate, from `ResolveOpts.capitalLevel`. Undefined → no promotion, byte-stable.
|
|
336
|
+
*/
|
|
337
|
+
capitalLevel?: (place: { name: string; country?: string; lat: number; lon: number }) => number
|
|
74
338
|
/**
|
|
75
339
|
* #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
|
|
76
340
|
*/
|
|
@@ -83,6 +347,16 @@ interface ResolutionState {
|
|
|
83
347
|
* Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
|
|
84
348
|
*/
|
|
85
349
|
includeAncestors: boolean
|
|
350
|
+
/**
|
|
351
|
+
* Admin-containment re-rank (#1717 stage 2). Off by default → byte-stable. See `ResolveOpts.adminContainmentRerank`.
|
|
352
|
+
*/
|
|
353
|
+
adminContainmentRerank: boolean
|
|
354
|
+
/**
|
|
355
|
+
* The tree's first parsed region-tagged span, extracted once up front (the `postcode` pattern above — region and
|
|
356
|
+
* locality are siblings, so the top-down walk wouldn't otherwise let the locality lookup see it). Only consulted when
|
|
357
|
+
* {@link adminContainmentRerank} is on.
|
|
358
|
+
*/
|
|
359
|
+
regionQualifier?: string
|
|
86
360
|
/**
|
|
87
361
|
* Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
|
|
88
362
|
* fires when the parser emitted no locality at all, never to override one.
|
|
@@ -91,7 +365,7 @@ interface ResolutionState {
|
|
|
91
365
|
/**
|
|
92
366
|
* The first region that resolved (its place — for the coincident-roles lookup).
|
|
93
367
|
*/
|
|
94
|
-
resolvedRegion:
|
|
368
|
+
resolvedRegion: CoordinateOptionalPlace | null
|
|
95
369
|
/**
|
|
96
370
|
* The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
|
|
97
371
|
* it in place (no synthesized sibling).
|
|
@@ -100,17 +374,27 @@ interface ResolutionState {
|
|
|
100
374
|
}
|
|
101
375
|
|
|
102
376
|
/**
|
|
103
|
-
* Pick the completion locality when an admin maps to several coincident same-name candidates (#405).
|
|
104
|
-
* PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
|
|
105
|
-
* same-name hamlet (the Niigata case from #403). Nearest centroid breaks a
|
|
106
|
-
* population AND distance) ABSTAINS rather than guess.
|
|
377
|
+
* Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
|
|
378
|
+
* likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
|
|
379
|
+
* centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
|
|
380
|
+
* genuine tie (same population AND distance) ABSTAINS rather than guess.
|
|
381
|
+
*
|
|
382
|
+
* ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
|
|
383
|
+
* ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
|
|
384
|
+
* saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
|
|
385
|
+
* that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
|
|
107
386
|
*/
|
|
108
387
|
function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
|
|
109
388
|
if (!candidates.length) return null
|
|
110
389
|
|
|
111
390
|
if (candidates.length === 1) return candidates[0]!
|
|
112
|
-
|
|
113
|
-
const ranked = [...candidates]
|
|
391
|
+
|
|
392
|
+
const ranked = [...candidates]
|
|
393
|
+
.map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
|
|
394
|
+
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
395
|
+
.sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
|
|
396
|
+
.map((x) => x.c)
|
|
397
|
+
|
|
114
398
|
const [first, second] = ranked
|
|
115
399
|
|
|
116
400
|
if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
|
|
@@ -128,7 +412,9 @@ function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
|
|
|
128
412
|
while (stack.length) {
|
|
129
413
|
const n = stack.pop()!
|
|
130
414
|
|
|
131
|
-
|
|
415
|
+
// #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
|
|
416
|
+
// must never become the address's postcode (it would poison the country-scope pass's anchor).
|
|
417
|
+
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
|
|
132
418
|
stack.push(...n.children)
|
|
133
419
|
}
|
|
134
420
|
|
|
@@ -173,7 +459,7 @@ async function applySpanRescore(
|
|
|
173
459
|
// 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
|
|
174
460
|
if (!hit && opts.postalCompoundRecovery !== false) {
|
|
175
461
|
try {
|
|
176
|
-
await recoverPostcodeNode(roots, backend, opts.defaultCountry)
|
|
462
|
+
await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
|
|
177
463
|
} catch {
|
|
178
464
|
// degrade to no-recovery, never crash the resolve
|
|
179
465
|
}
|
|
@@ -191,13 +477,31 @@ async function applySpanRescore(
|
|
|
191
477
|
children: [],
|
|
192
478
|
}
|
|
193
479
|
|
|
194
|
-
|
|
480
|
+
// #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
|
|
481
|
+
// ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
|
|
482
|
+
// resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
|
|
483
|
+
// dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
|
|
484
|
+
// The winner is unchanged (see findRescoreCandidate); this is additive.
|
|
485
|
+
decorateNode(node, hit.place, hit.alternatives)
|
|
195
486
|
// `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
|
|
196
487
|
// calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
|
|
197
488
|
// be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
|
|
198
489
|
// (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
|
|
199
490
|
node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated }
|
|
200
491
|
roots.push(node)
|
|
492
|
+
|
|
493
|
+
// #1721 follow-up: this tier answers OFF the walk, and it used to answer off the record too — the famous-name
|
|
494
|
+
// class ("Frankfurt") returned a coordinate beside an empty resolver trace, blinding every retrieval account.
|
|
495
|
+
// One record per rescue keeps the trace's promise: no resolved coordinate without a lookup record.
|
|
496
|
+
if (opts.traceSink) {
|
|
497
|
+
const rec = createNodeTraceRecorder(opts.traceSink)
|
|
498
|
+
|
|
499
|
+
rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry } : {}, 1)
|
|
500
|
+
rec.gate("span_rescore")
|
|
501
|
+
rec.gate(hit.gated ? "rescore_gated" : "rescore_ungated")
|
|
502
|
+
rec.stage("rescore", [hit.place, ...hit.alternatives])
|
|
503
|
+
rec.emit({ id: hit.place.id, name: hit.place.name, source: "span_rescore" })
|
|
504
|
+
}
|
|
201
505
|
}
|
|
202
506
|
|
|
203
507
|
/**
|
|
@@ -209,7 +513,8 @@ async function applySpanRescore(
|
|
|
209
513
|
async function recoverPostcodeNode(
|
|
210
514
|
roots: AddressNode[],
|
|
211
515
|
backend: ResolverBackend,
|
|
212
|
-
country: string | undefined
|
|
516
|
+
country: string | undefined,
|
|
517
|
+
traceSink?: (record: ResolveNodeTrace) => void
|
|
213
518
|
): Promise<void> {
|
|
214
519
|
const stack: AddressNode[] = [...roots]
|
|
215
520
|
|
|
@@ -226,6 +531,16 @@ async function recoverPostcodeNode(
|
|
|
226
531
|
if (top) {
|
|
227
532
|
decorateNode(n, top, [])
|
|
228
533
|
n.metadata = { ...n.metadata, postal_compound_recovered: true }
|
|
534
|
+
|
|
535
|
+
// The same off-the-record hole the span-rescore record closes (#1721 follow-up).
|
|
536
|
+
if (traceSink) {
|
|
537
|
+
const rec = createNodeTraceRecorder(traceSink)
|
|
538
|
+
|
|
539
|
+
rec.bind(n, "postalcode", { ...(country ? { country } : {}), limit: 1 }, 1)
|
|
540
|
+
rec.gate("postal_compound_recovery")
|
|
541
|
+
rec.stage("recovery", hits)
|
|
542
|
+
rec.emit({ id: top.id, name: top.name, source: "postal_compound_recovery" })
|
|
543
|
+
}
|
|
229
544
|
}
|
|
230
545
|
|
|
231
546
|
return // first postcode node only — one recovery per tree
|
|
@@ -237,13 +552,6 @@ async function recoverPostcodeNode(
|
|
|
237
552
|
}
|
|
238
553
|
}
|
|
239
554
|
|
|
240
|
-
/**
|
|
241
|
-
* A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
|
|
242
|
-
*/
|
|
243
|
-
function isResolvedWithCoord(n: AddressNode): boolean {
|
|
244
|
-
return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
|
|
245
|
-
}
|
|
246
|
-
|
|
247
555
|
/**
|
|
248
556
|
* Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
|
|
249
557
|
* same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
|
|
@@ -272,7 +580,8 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
|
|
|
272
580
|
while (findAnchor.length) {
|
|
273
581
|
const n = findAnchor.pop()!
|
|
274
582
|
|
|
275
|
-
|
|
583
|
+
// #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
|
|
584
|
+
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
|
|
276
585
|
anchor = { lat: n.lat!, lon: n.lon! }
|
|
277
586
|
|
|
278
587
|
break
|
|
@@ -331,416 +640,6 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
|
|
|
331
640
|
}
|
|
332
641
|
}
|
|
333
642
|
|
|
334
|
-
/**
|
|
335
|
-
* Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
|
|
336
|
-
* resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
|
|
337
|
-
* Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
|
|
338
|
-
* same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
|
|
339
|
-
* greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
|
|
340
|
-
* same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
|
|
341
|
-
*
|
|
342
|
-
* Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
|
|
343
|
-
* well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
|
|
344
|
-
* per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
|
|
345
|
-
*/
|
|
346
|
-
async function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
|
|
347
|
-
const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
|
|
348
|
-
const regionHere = node.tag === "region" && isResolvedWithCoord(node) ? node : regionAncestor
|
|
349
|
-
|
|
350
|
-
if (
|
|
351
|
-
regionHere &&
|
|
352
|
-
(node.tag === "locality" || node.tag === "dependent_locality") &&
|
|
353
|
-
!isResolvedWithCoord(node) &&
|
|
354
|
-
node.value.trim().length
|
|
355
|
-
) {
|
|
356
|
-
await reconcileAdminPair(regionHere, node, backend)
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
for (const child of node.children) {
|
|
360
|
-
await visit(child, regionHere)
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
for (const root of roots) {
|
|
365
|
-
await visit(root, null)
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/**
|
|
370
|
-
* Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
|
|
371
|
-
* `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
|
|
372
|
-
* types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
|
|
373
|
-
* same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
|
|
374
|
-
* un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
|
|
375
|
-
* namesake).
|
|
376
|
-
*/
|
|
377
|
-
async function reconcileAdminPair(
|
|
378
|
-
regionNode: AddressNode,
|
|
379
|
-
localityNode: AddressNode,
|
|
380
|
-
backend: ResolverBackend
|
|
381
|
-
): Promise<void> {
|
|
382
|
-
// EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
|
|
383
|
-
// Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
|
|
384
|
-
// (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
|
|
385
|
-
const regionCands = ((regionNode.alternatives as ResolvedPlace[] | undefined) ?? []).filter((r) => r.exactMatch)
|
|
386
|
-
|
|
387
|
-
// For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
|
|
388
|
-
// The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
|
|
389
|
-
// instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
|
|
390
|
-
// Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
|
|
391
|
-
// region candidates are score-ordered, so a tie breaks toward the more prominent place.
|
|
392
|
-
for (const region of regionCands) {
|
|
393
|
-
const scoped = await backend.findPlace({
|
|
394
|
-
text: localityNode.value,
|
|
395
|
-
placetype: "locality",
|
|
396
|
-
parentID: region.id,
|
|
397
|
-
limit: 3,
|
|
398
|
-
})
|
|
399
|
-
|
|
400
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
401
|
-
|
|
402
|
-
if (lc) {
|
|
403
|
-
decorateNode(
|
|
404
|
-
regionNode,
|
|
405
|
-
region,
|
|
406
|
-
regionCands.filter((r) => r !== region)
|
|
407
|
-
)
|
|
408
|
-
|
|
409
|
-
regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
|
|
410
|
-
|
|
411
|
-
decorateNode(
|
|
412
|
-
localityNode,
|
|
413
|
-
lc,
|
|
414
|
-
scoped.filter((l) => l !== lc)
|
|
415
|
-
)
|
|
416
|
-
|
|
417
|
-
localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
|
|
418
|
-
|
|
419
|
-
return
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
// #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
|
|
424
|
-
// Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
|
|
425
|
-
// region candidate holds the locality, try same-named country candidates: a foreign capital under its
|
|
426
|
-
// country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
|
|
427
|
-
// #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
|
|
428
|
-
const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter(
|
|
429
|
-
(c) => c.exactMatch
|
|
430
|
-
)
|
|
431
|
-
|
|
432
|
-
for (const country of countryCands) {
|
|
433
|
-
const scoped = await backend.findPlace({
|
|
434
|
-
text: localityNode.value,
|
|
435
|
-
placetype: "locality",
|
|
436
|
-
parentID: country.id,
|
|
437
|
-
limit: 3,
|
|
438
|
-
})
|
|
439
|
-
|
|
440
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
441
|
-
|
|
442
|
-
if (lc) {
|
|
443
|
-
decorateNode(regionNode, country, regionCands)
|
|
444
|
-
regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
|
|
445
|
-
|
|
446
|
-
decorateNode(
|
|
447
|
-
localityNode,
|
|
448
|
-
lc,
|
|
449
|
-
scoped.filter((l) => l !== lc)
|
|
450
|
-
)
|
|
451
|
-
|
|
452
|
-
localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
|
|
453
|
-
|
|
454
|
-
return
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
// #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
|
|
459
|
-
// foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
|
|
460
|
-
// hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
|
|
461
|
-
// descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
|
|
462
|
-
// ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
|
|
463
|
-
// row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
|
|
464
|
-
// ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
|
|
465
|
-
// null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
|
|
466
|
-
// never reaches here — this stays inert on the domestic path.
|
|
467
|
-
const mc = matchCountry(regionNode.value)
|
|
468
|
-
|
|
469
|
-
if (mc) {
|
|
470
|
-
const scoped = await backend.findPlace({
|
|
471
|
-
text: localityNode.value,
|
|
472
|
-
placetype: "locality",
|
|
473
|
-
country: mc.iso2,
|
|
474
|
-
limit: 3,
|
|
475
|
-
})
|
|
476
|
-
|
|
477
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
478
|
-
|
|
479
|
-
if (lc) {
|
|
480
|
-
decorateNode(
|
|
481
|
-
localityNode,
|
|
482
|
-
lc,
|
|
483
|
-
scoped.filter((l) => l !== lc)
|
|
484
|
-
)
|
|
485
|
-
|
|
486
|
-
localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
|
|
487
|
-
// The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
|
|
488
|
-
// already decorated the region node with the US-state namesake. Revert that stale decoration so the
|
|
489
|
-
// node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
|
|
490
|
-
// into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
|
|
491
|
-
// region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
|
|
492
|
-
revertResolverDecoration(regionNode)
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
/**
|
|
498
|
-
* Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
|
|
499
|
-
* `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
|
|
500
|
-
* country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
|
|
501
|
-
* — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
|
|
502
|
-
*/
|
|
503
|
-
function revertResolverDecoration(node: AddressNode): void {
|
|
504
|
-
const meta = { ...node.metadata }
|
|
505
|
-
const priorSource = meta["classifier_source"]
|
|
506
|
-
const priorSourceID = meta["classifier_source_id"]
|
|
507
|
-
node.source = typeof priorSource === "string" ? priorSource : undefined
|
|
508
|
-
node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined
|
|
509
|
-
|
|
510
|
-
for (const key of [
|
|
511
|
-
"classifier_source",
|
|
512
|
-
"classifier_source_id",
|
|
513
|
-
"resolver_score",
|
|
514
|
-
"resolver_name",
|
|
515
|
-
"resolver_country",
|
|
516
|
-
"resolution_quality",
|
|
517
|
-
"postcode_city_mismatch",
|
|
518
|
-
]) {
|
|
519
|
-
// oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
|
|
520
|
-
delete meta[key]
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
node.metadata = meta
|
|
524
|
-
node.lat = undefined
|
|
525
|
-
node.lon = undefined
|
|
526
|
-
node.placeID = undefined
|
|
527
|
-
node.alternatives = undefined
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
/**
|
|
531
|
-
* Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
|
|
532
|
-
* The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
|
|
533
|
-
* (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
|
|
534
|
-
* _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
|
|
535
|
-
* country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
|
|
536
|
-
* normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
|
|
537
|
-
* column does the geographic confirmation. No pin, no list; generalizes to every country.
|
|
538
|
-
*
|
|
539
|
-
* Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
|
|
540
|
-
* locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
|
|
541
|
-
* and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
|
|
542
|
-
* → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
|
|
543
|
-
* US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
|
|
544
|
-
* named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
|
|
545
|
-
* trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
|
|
546
|
-
* lookup per triggering pair. See `ResolveOpts.adminCoherence`.
|
|
547
|
-
*/
|
|
548
|
-
async function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
|
|
549
|
-
const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
|
|
550
|
-
const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
|
|
551
|
-
const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion"
|
|
552
|
-
|
|
553
|
-
// Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
|
|
554
|
-
// When a region IS present, applyAdminCoherence + the region's `parentID` scope already disambiguate the
|
|
555
|
-
// locality — applying the coarse country filter there would wrongly re-pick "Springfield, IL" to the most
|
|
556
|
-
// populous US "Springfield". Fires regardless of the locality's resolution state, so it PRE-EMPTS the
|
|
557
|
-
// span-rescore tier (which would otherwise back-fill the unresolved locality with the US namesake).
|
|
558
|
-
if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
|
|
559
|
-
await reconcileExplicitCountry(countryHere, node, backend)
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
for (const child of node.children) {
|
|
563
|
-
await visit(child, countryHere, regionHere)
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
for (const root of roots) {
|
|
568
|
-
await visit(root, null, false)
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
/**
|
|
573
|
-
* Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
|
|
574
|
-
* country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
|
|
575
|
-
* the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
|
|
576
|
-
* unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
|
|
577
|
-
* that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
|
|
578
|
-
* well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
|
|
579
|
-
* with; the locality coordinate is what the re-pick fixes.
|
|
580
|
-
*/
|
|
581
|
-
async function reconcileExplicitCountry(
|
|
582
|
-
countryNode: AddressNode,
|
|
583
|
-
localityNode: AddressNode,
|
|
584
|
-
backend: ResolverBackend
|
|
585
|
-
): Promise<void> {
|
|
586
|
-
const mc = matchCountry(countryNode.value)
|
|
587
|
-
|
|
588
|
-
if (!mc) return
|
|
589
|
-
|
|
590
|
-
const scoped = await backend.findPlace({
|
|
591
|
-
text: localityNode.value,
|
|
592
|
-
placetype: "locality",
|
|
593
|
-
country: mc.iso2,
|
|
594
|
-
limit: 3,
|
|
595
|
-
})
|
|
596
|
-
|
|
597
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
598
|
-
|
|
599
|
-
if (!lc) return
|
|
600
|
-
|
|
601
|
-
// Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
|
|
602
|
-
if (localityNode.placeID === `wof:${lc.id}`) return
|
|
603
|
-
|
|
604
|
-
decorateNode(
|
|
605
|
-
localityNode,
|
|
606
|
-
lc,
|
|
607
|
-
scoped.filter((l) => l !== lc)
|
|
608
|
-
)
|
|
609
|
-
|
|
610
|
-
localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true }
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
/**
|
|
614
|
-
* Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
|
|
615
|
-
* filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
|
|
616
|
-
* and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
|
|
617
|
-
* where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
|
|
618
|
-
*
|
|
619
|
-
* "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
|
|
620
|
-
* lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
|
|
621
|
-
* redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
|
|
622
|
-
* The greedy order threw away the evidence that could correct it.
|
|
623
|
-
*
|
|
624
|
-
* The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
|
|
625
|
-
* `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
|
|
626
|
-
* questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
|
|
627
|
-
* same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
|
|
628
|
-
* Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
|
|
629
|
-
*
|
|
630
|
-
* Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
|
|
631
|
-
* the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
|
|
632
|
-
* well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
|
|
633
|
-
* (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
|
|
634
|
-
* resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
|
|
635
|
-
* triggering pair. See `ResolveOpts.adminCoherence`.
|
|
636
|
-
*/
|
|
637
|
-
async function applyRegionCountryCoherence(
|
|
638
|
-
roots: readonly AddressNode[],
|
|
639
|
-
backend: ResolverBackend,
|
|
640
|
-
defaultCountry: string | undefined
|
|
641
|
-
): Promise<void> {
|
|
642
|
-
// No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
|
|
643
|
-
// this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
|
|
644
|
-
if (!defaultCountry) return
|
|
645
|
-
|
|
646
|
-
const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
|
|
647
|
-
// Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
|
|
648
|
-
const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor
|
|
649
|
-
|
|
650
|
-
// Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
|
|
651
|
-
// exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
|
|
652
|
-
// (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
|
|
653
|
-
// otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
|
|
654
|
-
if (
|
|
655
|
-
regionHere &&
|
|
656
|
-
!isResolvedWithCoord(regionHere) &&
|
|
657
|
-
(node.tag === "locality" || node.tag === "dependent_locality") &&
|
|
658
|
-
node.value.trim().length
|
|
659
|
-
) {
|
|
660
|
-
await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
for (const child of node.children) {
|
|
664
|
-
await visit(child, regionHere)
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
for (const root of roots) {
|
|
669
|
-
await visit(root, null)
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
/**
|
|
674
|
-
* Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
|
|
675
|
-
* default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
|
|
676
|
-
* that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
|
|
677
|
-
* the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
|
|
678
|
-
* untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
|
|
679
|
-
* under it, and a same-named locality exists there — so the domestic path stays byte-identical.
|
|
680
|
-
*/
|
|
681
|
-
async function reconcileRegionCountry(
|
|
682
|
-
regionNode: AddressNode,
|
|
683
|
-
localityNode: AddressNode,
|
|
684
|
-
backend: ResolverBackend,
|
|
685
|
-
defaultCountry: string
|
|
686
|
-
): Promise<void> {
|
|
687
|
-
const sub = matchSubdivision(regionNode.value)
|
|
688
|
-
|
|
689
|
-
if (!sub) return
|
|
690
|
-
|
|
691
|
-
// The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
|
|
692
|
-
// (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
|
|
693
|
-
if (sub.country.toUpperCase() === defaultCountry.toUpperCase()) return
|
|
694
|
-
|
|
695
|
-
// The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
|
|
696
|
-
const localityCountry = (localityNode.metadata?.["resolver_country"] as string | undefined)?.toUpperCase()
|
|
697
|
-
|
|
698
|
-
if (localityCountry === sub.country.toUpperCase()) return
|
|
699
|
-
|
|
700
|
-
// Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
|
|
701
|
-
// form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
|
|
702
|
-
const regionScoped = await backend.findPlace({
|
|
703
|
-
text: sub.name,
|
|
704
|
-
placetype: "region",
|
|
705
|
-
country: sub.country,
|
|
706
|
-
limit: 3,
|
|
707
|
-
})
|
|
708
|
-
|
|
709
|
-
const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0))
|
|
710
|
-
|
|
711
|
-
if (!rc) return
|
|
712
|
-
|
|
713
|
-
// Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
|
|
714
|
-
// reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
|
|
715
|
-
const scoped = await backend.findPlace({
|
|
716
|
-
text: localityNode.value,
|
|
717
|
-
placetype: "locality",
|
|
718
|
-
country: sub.country,
|
|
719
|
-
limit: 3,
|
|
720
|
-
})
|
|
721
|
-
|
|
722
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
723
|
-
|
|
724
|
-
if (!lc) return
|
|
725
|
-
|
|
726
|
-
// Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
|
|
727
|
-
decorateNode(
|
|
728
|
-
regionNode,
|
|
729
|
-
rc,
|
|
730
|
-
regionScoped.filter((r) => r !== rc)
|
|
731
|
-
)
|
|
732
|
-
|
|
733
|
-
regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true }
|
|
734
|
-
|
|
735
|
-
decorateNode(
|
|
736
|
-
localityNode,
|
|
737
|
-
lc,
|
|
738
|
-
scoped.filter((l) => l !== lc)
|
|
739
|
-
)
|
|
740
|
-
|
|
741
|
-
localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true }
|
|
742
|
-
}
|
|
743
|
-
|
|
744
643
|
class WOFResolver implements Resolver {
|
|
745
644
|
readonly #backend: ResolverBackend
|
|
746
645
|
/**
|
|
@@ -748,13 +647,36 @@ class WOFResolver implements Resolver {
|
|
|
748
647
|
* read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
|
|
749
648
|
*/
|
|
750
649
|
readonly artifactCoverage: Resolver["artifactCoverage"]
|
|
650
|
+
/**
|
|
651
|
+
* Optional backend methods this backend omits, each naming the default-ON option it silently disables. Computed once
|
|
652
|
+
* here rather than at each guard site so a caller can read the gap before running a query that would quietly skip the
|
|
653
|
+
* feature. See `backend-capabilities.ts`.
|
|
654
|
+
*/
|
|
655
|
+
readonly capabilityGaps: readonly BackendCapabilityGap[]
|
|
751
656
|
|
|
752
657
|
constructor(backend: ResolverBackend) {
|
|
753
658
|
this.#backend = backend
|
|
754
659
|
this.artifactCoverage = backend.artifactCoverage
|
|
660
|
+
this.capabilityGaps = describeCapabilityGaps(backend)
|
|
661
|
+
reportCapabilityGaps(this.capabilityGaps)
|
|
755
662
|
}
|
|
756
663
|
|
|
664
|
+
/**
|
|
665
|
+
* The `Resolver.findPlace` passthrough — one direct gazetteer probe for pipeline-level consumers (#1738's
|
|
666
|
+
* dominant-bearer guard). Bound as a method so `this.#backend` stays private.
|
|
667
|
+
*/
|
|
668
|
+
findPlace: Resolver["findPlace"] = (query) => this.#backend.findPlace(query)
|
|
669
|
+
|
|
757
670
|
async resolveTree(tree: AddressTree, opts: ResolveOpts = {}): Promise<AddressTree> {
|
|
671
|
+
// Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
|
|
672
|
+
// backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
|
|
673
|
+
// address's postcode. Opt-in (`postcodeShapeCoherence: true`), OFF by default (D-rule: demotion
|
|
674
|
+
// is the failure mode with teeth). A confirmed span's narrowed systems — the intersection of
|
|
675
|
+
// its codex shape with the tree's confident sibling systems — bound the country-scope pass
|
|
676
|
+
// below; a pure subset of codex's own candidate list, so it can only narrow, never widen.
|
|
677
|
+
// See postcode-shape-coherence.ts.
|
|
678
|
+
const shapeVerdict = opts.postcodeShapeCoherence === true ? applyPostcodeShapeCoherence(tree.roots) : null
|
|
679
|
+
|
|
758
680
|
const state: ResolutionState = {
|
|
759
681
|
lookupsRemaining: opts.maxLookups ?? 10,
|
|
760
682
|
// Full replacement when `placetypeMap` is supplied — callers that want to extend rather
|
|
@@ -763,37 +685,87 @@ class WOFResolver implements Resolver {
|
|
|
763
685
|
minWinningScore: opts.minWinningScore ?? 0,
|
|
764
686
|
candidatesPerLookup: opts.candidatesPerLookup ?? 5,
|
|
765
687
|
defaultCountry: opts.defaultCountry,
|
|
688
|
+
defaultCountryIsInferred: opts.defaultCountryIsInferred === true,
|
|
689
|
+
bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
|
|
766
690
|
parentFallback: opts.parentFallback ?? true,
|
|
691
|
+
// Requires a sink: with nowhere to record the answer the probes would be pure cost.
|
|
692
|
+
...(opts.diagnoseUnreachable && opts.traceSink ? { diagnoseUnreachable: true } : {}),
|
|
767
693
|
postcode: firstPostcodeValue(tree.roots),
|
|
694
|
+
// #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
|
|
695
|
+
postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
|
|
696
|
+
// #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
|
|
697
|
+
postcodePrefixPrior: opts.postcodePrefixPrior === true,
|
|
698
|
+
postcodePrefixIndex: opts.postcodePrefixIndex,
|
|
699
|
+
// #1589: derived here when the caller didn't thread it, so the browser cascade and the
|
|
700
|
+
// drop-ins get the implied-set probe without per-caller wiring (the staged-repoint e2e
|
|
701
|
+
// caught `100 00` resolving in Node and not in the browser over the same artifact).
|
|
702
|
+
postcodeFormatCountries:
|
|
703
|
+
opts.postcodeFormatCountries ?? countriesFromPostcodeFormat(firstPostcodeValue(tree.roots)),
|
|
704
|
+
fuzzyCountryScope: opts.fuzzyCountryScope,
|
|
768
705
|
bias: opts.bias,
|
|
769
706
|
anchorPosterior: opts.anchorPosterior,
|
|
770
707
|
anchorWeight: opts.anchorWeight ?? 2,
|
|
708
|
+
localeCountryPrior: opts.localeCountryPrior,
|
|
709
|
+
localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
|
|
710
|
+
capitalLevel: opts.capitalLevel,
|
|
771
711
|
hardCountry: opts.hardCountry,
|
|
772
712
|
// Default-ON (#402): completion only fires for a dual-role region whose locality the parser
|
|
773
713
|
// dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
|
|
774
714
|
// a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
|
|
715
|
+
//
|
|
716
|
+
// Default-ON is nominal on the SHIPPED backend: `WOFCandidateTableLookup` implements no
|
|
717
|
+
// `coincidentLocalitiesFor`, so this attaches nothing there. Measured 2026-08-15 on FTS, which
|
|
718
|
+
// does implement it, the flag changed 0 of 837 board inputs — see ResolveOpts.hierarchyCompletion.
|
|
775
719
|
hierarchyCompletion: opts.hierarchyCompletion ?? true,
|
|
776
720
|
includeAncestors: opts.includeAncestors ?? false,
|
|
721
|
+
// #1717 stage 2 — default OFF (D-rule); the qualifier is pre-scanned like `postcode` above
|
|
722
|
+
// because region and locality are siblings the walk visits independently.
|
|
723
|
+
adminContainmentRerank: opts.adminContainmentRerank === true,
|
|
724
|
+
regionQualifier: firstRegionQualifier(tree.roots),
|
|
725
|
+
...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
|
|
777
726
|
localityNodePresent: false,
|
|
778
727
|
resolvedRegion: null,
|
|
779
728
|
resolvedRegionNode: null,
|
|
780
729
|
}
|
|
781
730
|
|
|
782
|
-
// Postcode-country coherence (#42): the
|
|
783
|
-
//
|
|
784
|
-
//
|
|
785
|
-
//
|
|
786
|
-
// the
|
|
787
|
-
//
|
|
788
|
-
//
|
|
789
|
-
//
|
|
731
|
+
// Postcode-country coherence (#42): the one pre-walk LOOKUP pass (the shape verdict above is
|
|
732
|
+
// pure-sync, backend-free), and the only mechanism allowed to override `defaultCountry`. Its three
|
|
733
|
+
// sibling coherence passes re-pick nodes AFTER the walk; that shape cannot work here, because what
|
|
734
|
+
// needs correcting is the walk's country SCOPE — which poisons the postcode node's own resolution,
|
|
735
|
+
// the postcode-consistency fallback that then drags the locality onto it, and the hard `country`
|
|
736
|
+
// filter on every admin lookup. So the verdict is taken once, up front, and the walk runs under the
|
|
737
|
+
// corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) — needs a default
|
|
738
|
+
// country to correct and both a postcode and a locality to be coherent about; abstains unless
|
|
739
|
+
// EXACTLY one country (never the already-coherent default) makes the pair consistent. See
|
|
790
740
|
// postcode-country-coherence.ts.
|
|
791
741
|
let postcodeScope: PostcodeCountryScope | null = null
|
|
792
742
|
|
|
793
|
-
|
|
743
|
+
// The pass also runs with NO default in force (#1585/#861 convergence): there is nothing to
|
|
744
|
+
// override, but the same exactly-one-country abstention lets the postcode+locality pair
|
|
745
|
+
// CONSTRAIN an otherwise population-first walk — `Zabiče 8, 6250 Zabiče` picks the SI row
|
|
746
|
+
// coherent with the SI 6250 centroid instead of the more-populous Polish namesake. The
|
|
747
|
+
// browser cascade (which sets no default by design) is the consumer this exists for.
|
|
748
|
+
// #1735 second half: the address's own country statement scopes the walk BEFORE anything
|
|
749
|
+
// resolves — a sibling's resolution never reaches a sibling, so without this the postcode
|
|
750
|
+
// lookup in "RM10 8AB, UK" ran under the locale-inferred US filter while the country node
|
|
751
|
+
// resolved to GB beside it. Explicit-over-inferred, the #912 precedence, decided from the
|
|
752
|
+
// tree's own text; an EXPLICIT caller scope is never overridden.
|
|
753
|
+
let explicitScope: string | null = null
|
|
754
|
+
|
|
755
|
+
if (!state.defaultCountry || state.defaultCountryIsInferred) {
|
|
756
|
+
explicitScope = explicitCountryScope(tree.roots)
|
|
757
|
+
|
|
758
|
+
if (explicitScope) {
|
|
759
|
+
state.defaultCountry = explicitScope
|
|
760
|
+
state.defaultCountryIsInferred = false
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
if (opts.postcodeCountryCoherence !== false && state.postcode) {
|
|
794
765
|
postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
|
|
795
766
|
postcode: state.postcode,
|
|
796
767
|
defaultCountry: state.defaultCountry,
|
|
768
|
+
...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
|
|
797
769
|
...(opts.postcodeCountryCoherenceGateKm !== undefined ? { gateKm: opts.postcodeCountryCoherenceGateKm } : {}),
|
|
798
770
|
})
|
|
799
771
|
|
|
@@ -816,6 +788,20 @@ class WOFResolver implements Resolver {
|
|
|
816
788
|
stampPostcodeCountryScope(newRoots, postcodeScope)
|
|
817
789
|
}
|
|
818
790
|
|
|
791
|
+
// The pre-scope's receipt (#1735): consumers that select country-scoped artifacts AFTER the walk
|
|
792
|
+
// (geocode-core's rooftop-shard second pass) key on a scope stamp. Without this, an address whose
|
|
793
|
+
// country was right FROM THE TREE never writes one — the #42 pass stays silent because the default
|
|
794
|
+
// is already coherent — and the FR rooftop shard silently stops loading for "…, France" inputs
|
|
795
|
+
// under a non-FR locale (six board venue rows dropped from rooftop to city centroid; the battery
|
|
796
|
+
// caught it).
|
|
797
|
+
if (explicitScope) {
|
|
798
|
+
for (const root of newRoots) {
|
|
799
|
+
if (root.tag === "country") {
|
|
800
|
+
root.metadata = { ...root.metadata, explicit_country_scope: explicitScope }
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
819
805
|
// Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
|
|
820
806
|
// emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
|
|
821
807
|
// resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
|
|
@@ -873,6 +859,15 @@ class WOFResolver implements Resolver {
|
|
|
873
859
|
await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
|
|
874
860
|
}
|
|
875
861
|
|
|
862
|
+
// A failed admin walk can leave the exact-point tier without a locality even though span-rescore
|
|
863
|
+
// recovers one immediately afterward (for example, a locality the model tagged as `region`). Give
|
|
864
|
+
// the exact register one bounded retry with that newly established scope. An existing situs hit is
|
|
865
|
+
// returned early by applyAddressPoint, so the normal path performs no duplicate lookup; interpolation
|
|
866
|
+
// remains subordinate because an exact point is allowed to replace its estimate.
|
|
867
|
+
if (opts.addressPoints) {
|
|
868
|
+
applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
|
|
869
|
+
}
|
|
870
|
+
|
|
876
871
|
// Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
|
|
877
872
|
// country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
|
|
878
873
|
// admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
|
|
@@ -893,7 +888,7 @@ class WOFResolver implements Resolver {
|
|
|
893
888
|
* relation, the region isn't a dual-role place, or it abstains. The region node's primary role stays `region`; the
|
|
894
889
|
* locality rides alongside.
|
|
895
890
|
*/
|
|
896
|
-
#completeRegionRole(region:
|
|
891
|
+
#completeRegionRole(region: CoordinateOptionalPlace, regionNode: AddressNode): void {
|
|
897
892
|
if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor) return
|
|
898
893
|
const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
|
|
899
894
|
|
|
@@ -912,7 +907,11 @@ class WOFResolver implements Resolver {
|
|
|
912
907
|
regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
|
|
913
908
|
}
|
|
914
909
|
|
|
915
|
-
async #walk(
|
|
910
|
+
async #walk(
|
|
911
|
+
node: AddressNode,
|
|
912
|
+
parentResolved: CoordinateOptionalPlace | null,
|
|
913
|
+
state: ResolutionState
|
|
914
|
+
): Promise<AddressNode> {
|
|
916
915
|
// Always clone — never mutate input nodes.
|
|
917
916
|
const decorated: AddressNode = { ...node, children: [] }
|
|
918
917
|
|
|
@@ -925,15 +924,39 @@ class WOFResolver implements Resolver {
|
|
|
925
924
|
state.localityNodePresent = true
|
|
926
925
|
}
|
|
927
926
|
|
|
928
|
-
let resolved:
|
|
927
|
+
let resolved: CoordinateOptionalPlace | null = null
|
|
929
928
|
|
|
930
|
-
|
|
929
|
+
// Shape-excluded postcode spans (letter-bearing ones keep their tag; #31 Mechanism 1) are
|
|
930
|
+
// stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
|
|
931
|
+
// spans were retagged to `house_number` and flow through their correct sibling placetype.
|
|
932
|
+
if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
|
|
931
933
|
const picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
|
|
932
934
|
|
|
933
935
|
if (picked) {
|
|
934
936
|
resolved = picked.top
|
|
935
937
|
decorateNode(decorated, picked.top, picked.alternatives)
|
|
936
938
|
|
|
939
|
+
if (picked.metadata) {
|
|
940
|
+
decorated.metadata = { ...decorated.metadata, ...picked.metadata }
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// #1678 thread 2 — the parse half, resolved from the atlas rather than trained in.
|
|
944
|
+
//
|
|
945
|
+
// The bare-toponym race exists because the model reads a lone country or region name as a
|
|
946
|
+
// `locality`; the race finds the right PLACE and the node keeps the wrong TAG. So
|
|
947
|
+
// `mw geocode 格鲁吉亚` lands on Georgia the country and reports `{"locality": "格鲁吉亚"}`,
|
|
948
|
+
// which is a correct coordinate under a label that will mislead the moment the same toponym
|
|
949
|
+
// appears inside a longer address.
|
|
950
|
+
//
|
|
951
|
+
// The repick metadata already marks exactly these nodes, so the correction is free: retrieval
|
|
952
|
+
// established the placetype, and the tag follows it. Only the race's own picks are retagged —
|
|
953
|
+
// an ordinary locality that resolved to a locality is untouched.
|
|
954
|
+
if (decorated.metadata?.["bare_country_repick"]) {
|
|
955
|
+
decorated.tag = "country"
|
|
956
|
+
} else if (decorated.metadata?.["bare_region_repick"]) {
|
|
957
|
+
decorated.tag = "region"
|
|
958
|
+
}
|
|
959
|
+
|
|
937
960
|
// Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
|
|
938
961
|
// + only when the backend supplies it, so the default stays byte-identical (no extra query).
|
|
939
962
|
if (state.includeAncestors && this.#backend.ancestors) {
|
|
@@ -958,12 +981,48 @@ class WOFResolver implements Resolver {
|
|
|
958
981
|
return decorated
|
|
959
982
|
}
|
|
960
983
|
|
|
984
|
+
/**
|
|
985
|
+
* Which admin bands hold a value the probed band did not, keeping the country and dropping the parent.
|
|
986
|
+
*
|
|
987
|
+
* Bands come from `PLACETYPE_SPECIFICITY` rather than a list typed here: that table is already the repo's answer to
|
|
988
|
+
* how coarse a placetype is, and a second hand-kept copy would agree right up until a placetype is added. Probed
|
|
989
|
+
* coarse-to-fine so the report reads down the admin ladder.
|
|
990
|
+
*/
|
|
991
|
+
async #probeOtherBands(
|
|
992
|
+
query: Parameters<ResolverBackend["findPlace"]>[0],
|
|
993
|
+
probed: string
|
|
994
|
+
): Promise<NonNullable<ResolveNodeTrace["reachableIn"]>> {
|
|
995
|
+
const found: NonNullable<ResolveNodeTrace["reachableIn"]> = []
|
|
996
|
+
|
|
997
|
+
for (const band of DIAGNOSTIC_BANDS) {
|
|
998
|
+
if (band === probed) continue
|
|
999
|
+
|
|
1000
|
+
try {
|
|
1001
|
+
const hits = await this.#backend.findPlace({ ...query, placetype: band, parentID: undefined })
|
|
1002
|
+
|
|
1003
|
+
if (hits.length) {
|
|
1004
|
+
found.push({ placetype: band, n: hits.length })
|
|
1005
|
+
}
|
|
1006
|
+
} catch {
|
|
1007
|
+
// A band the backend cannot answer for is not evidence that the key is absent from it, so it is
|
|
1008
|
+
// skipped rather than recorded as an empty result.
|
|
1009
|
+
continue
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
return found
|
|
1014
|
+
}
|
|
1015
|
+
|
|
961
1016
|
async #lookupAndPick(
|
|
962
1017
|
node: AddressNode,
|
|
963
1018
|
placetype: string,
|
|
964
|
-
parentResolved:
|
|
1019
|
+
parentResolved: CoordinateOptionalPlace | null,
|
|
965
1020
|
state: ResolutionState
|
|
966
|
-
): Promise<{
|
|
1021
|
+
): Promise<{
|
|
1022
|
+
top: CoordinateOptionalPlace
|
|
1023
|
+
alternatives: ResolvedPlace[]
|
|
1024
|
+
metadata?: Record<string, unknown>
|
|
1025
|
+
} | null> {
|
|
967
1026
|
state.lookupsRemaining--
|
|
968
1027
|
|
|
969
1028
|
const query: Parameters<ResolverBackend["findPlace"]>[0] = {
|
|
@@ -998,49 +1057,226 @@ class WOFResolver implements Resolver {
|
|
|
998
1057
|
// collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
|
|
999
1058
|
// #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
|
|
1000
1059
|
// today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
|
|
1001
|
-
// lookup
|
|
1002
|
-
//
|
|
1060
|
+
// lookup when the caller supplied no locale/default country. A caller scope outranks this derived hint:
|
|
1061
|
+
// `WA` is both Washington and Western Australia, so en-AU must reach the AU candidate instead of being
|
|
1062
|
+
// overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
|
|
1063
|
+
// later by region-country coherence after the scoped lookup abstains.
|
|
1003
1064
|
const countryHint = node.metadata?.["country_hint"]
|
|
1004
1065
|
|
|
1066
|
+
// A locale-INFERRED default country never filters a `country`-placetype lookup: the span names a
|
|
1067
|
+
// country outright, and the filter can only admit the scope country itself (bare "Germany" under
|
|
1068
|
+
// the en-US default filtered out the DE row; the unresolved span then fell to a US locality whose
|
|
1069
|
+
// historical alias is "Germany, Ohio"). An EXPLICIT caller scope stays supreme, matching the #912
|
|
1070
|
+
// posture; parent evidence and the confident placer are untouched.
|
|
1071
|
+
const defaultCountryForLookup =
|
|
1072
|
+
placetype === "country" && state.defaultCountryIsInferred ? undefined : state.defaultCountry
|
|
1073
|
+
|
|
1005
1074
|
const country =
|
|
1006
1075
|
parentResolved?.country ??
|
|
1076
|
+
defaultCountryForLookup ??
|
|
1007
1077
|
(typeof countryHint === "string" ? countryHint : undefined) ??
|
|
1008
|
-
state.defaultCountry ??
|
|
1009
1078
|
state.hardCountry
|
|
1010
1079
|
|
|
1011
1080
|
if (country) {
|
|
1012
1081
|
query.country = country
|
|
1013
1082
|
}
|
|
1014
1083
|
|
|
1084
|
+
// #1585: the locale hint's country rides on every primary lookup as the TYPO-FUZZY tier's scope.
|
|
1085
|
+
// Deliberately set even when `query.country` is (the backend ignores it there — the hard filter
|
|
1086
|
+
// is already narrower): the field's contract lives in one place, the backend.
|
|
1087
|
+
if (state.fuzzyCountryScope) {
|
|
1088
|
+
query.fuzzyCountry = state.fuzzyCountryScope
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// Admin-containment re-rank (#1717 stage 2): thread the tree's region qualifier onto locality
|
|
1092
|
+
// lookups so a capable backend can vouch for (and surface) the candidates that sit UNDER it.
|
|
1093
|
+
// Stands down under an EXPLICIT caller country scope (the #912 posture — only a locale-INFERRED
|
|
1094
|
+
// scope is bypassable by the address's own evidence); the resolved-parent and placer scopes are
|
|
1095
|
+
// left alone, since a resolved parent usually IS the qualifier and the injection dedupes.
|
|
1096
|
+
const containmentEligible =
|
|
1097
|
+
state.adminContainmentRerank &&
|
|
1098
|
+
placetype === "locality" &&
|
|
1099
|
+
state.regionQualifier !== undefined &&
|
|
1100
|
+
(!state.defaultCountry || state.defaultCountryIsInferred)
|
|
1101
|
+
|
|
1102
|
+
if (containmentEligible) {
|
|
1103
|
+
query.regionQualifier = state.regionQualifier
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1015
1106
|
// Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
|
|
1016
1107
|
// postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
|
|
1017
|
-
// `locality` and `dependent_locality` map to); other placetypes ignore it.
|
|
1108
|
+
// `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
|
|
1109
|
+
// (#31, Mechanism 2) asks a coordinate-first backend to re-rank the candidates by proximity to
|
|
1110
|
+
// the postcode's own centroid — opt-in, OFF by default.
|
|
1018
1111
|
if (placetype === "locality" && state.postcode) {
|
|
1019
1112
|
query.postcode = state.postcode
|
|
1113
|
+
|
|
1114
|
+
if (state.postcodeContainmentCoherence) {
|
|
1115
|
+
query.postcodeContainmentCoherence = true
|
|
1116
|
+
}
|
|
1020
1117
|
}
|
|
1021
1118
|
|
|
1119
|
+
// #1721 resolver-interior trace. Stage orders hold the SAME candidate objects across re-ranks
|
|
1120
|
+
// (every stage reorders, never clones), which is what lets emit assemble a per-stage rank
|
|
1121
|
+
// vector per row. The no-sink walk talks to the frozen no-op recorder — zero per-event branches.
|
|
1122
|
+
const rec = state.traceSink ? createNodeTraceRecorder(state.traceSink) : NOOP_TRACE_RECORDER
|
|
1123
|
+
|
|
1124
|
+
// The query is SNAPSHOT, not bound live. `emit` reads `ctx.query.parentID` at the END of the walk, and the
|
|
1125
|
+
// parent-fallback retry `delete`s that key mid-lookup — so binding the object itself lets a later mutation
|
|
1126
|
+
// rewrite history. That is how 196 lookups which every one of them carried a parent came out of the
|
|
1127
|
+
// constraint census reading `parentID: absent`.
|
|
1128
|
+
rec.bind(node, placetype, { ...query }, state.candidatesPerLookup)
|
|
1129
|
+
|
|
1022
1130
|
let candidates: ResolvedPlace[]
|
|
1023
1131
|
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1132
|
+
// #1589: a `postalcode` whose FORMAT implies specific countries, with no surviving country
|
|
1133
|
+
// constraint, probes exactly the implied set — most populous hit wins, and an all-miss
|
|
1134
|
+
// leaves the candidate set EMPTY rather than falling through to the unconstrained fold:
|
|
1135
|
+
// `100 00` space-strips to `10000`, which answers Troyes FR while the CZ rows sit in the
|
|
1136
|
+
// artifact under both keyings; a scoped empty must stay empty (the same contract as the
|
|
1137
|
+
// fuzzy tier's, #1585). The postcode-prefix prior below still gets its turn on the empty
|
|
1138
|
+
// set — its index is country-scoped by construction, so it is not the fold this branch
|
|
1139
|
+
// exists to avoid (the B3 tests hold that path).
|
|
1140
|
+
if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
|
|
1141
|
+
rec.gate("postcode_format_probe")
|
|
1142
|
+
let best: ResolvedPlace | undefined
|
|
1143
|
+
|
|
1144
|
+
for (const impliedCountry of state.postcodeFormatCountries) {
|
|
1145
|
+
try {
|
|
1146
|
+
const hits = await this.#backend.findPlace({ ...query, country: impliedCountry })
|
|
1147
|
+
const top = hits[0]
|
|
1148
|
+
|
|
1149
|
+
// `score` is the backend's own population-first ranking metric, so comparing the
|
|
1150
|
+
// per-country winners by it keeps the cross-country pick population-first too.
|
|
1151
|
+
if (top && (!best || top.score > best.score)) {
|
|
1152
|
+
best = top
|
|
1153
|
+
}
|
|
1154
|
+
} catch {
|
|
1155
|
+
// A per-country probe failure reads as a miss for that country, never an abort.
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
if (best) {
|
|
1160
|
+
rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" })
|
|
1161
|
+
|
|
1162
|
+
return { top: best, alternatives: [] }
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
candidates = []
|
|
1166
|
+
} else {
|
|
1167
|
+
try {
|
|
1035
1168
|
candidates = await this.#backend.findPlace(query)
|
|
1169
|
+
rec.stage("initial", candidates)
|
|
1170
|
+
|
|
1171
|
+
// #1731: the backend's interior region-scope fallback, surfaced as a gate — the resolver
|
|
1172
|
+
// never sees the scoped probe miss, only the stamp the re-admitted rows carry.
|
|
1173
|
+
if (candidates[0]?.regionScopeMiss) {
|
|
1174
|
+
rec.gate("region_scope_miss")
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
|
|
1178
|
+
// zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
|
|
1179
|
+
// (a real locality whose `ancestors` chain is missing its region). Rather than turn a
|
|
1180
|
+
// resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
|
|
1181
|
+
// prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
|
|
1182
|
+
// this still can't wander to a foreign place. Same logical resolution → no extra budget.
|
|
1183
|
+
if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
|
|
1184
|
+
delete query.parentID
|
|
1185
|
+
rec.gate("parent_fallback_retry")
|
|
1186
|
+
candidates = await this.#backend.findPlace(query)
|
|
1187
|
+
rec.stage("parent_fallback", candidates)
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
// DIAGNOSTIC ONLY, and after every real attempt: which OTHER bands hold this value. The answer never
|
|
1191
|
+
// becomes the pick — a band the model did not ask for is not evidence about what the string means —
|
|
1192
|
+
// but it separates the two facts a `null` cannot: a key we hold under another placetype is a
|
|
1193
|
+
// reachability failure the tag caused, while a key nowhere is coverage. Off by default; one extra call
|
|
1194
|
+
// per band per miss.
|
|
1195
|
+
if (!candidates.length && state.diagnoseUnreachable) {
|
|
1196
|
+
rec.reachable(await this.#probeOtherBands(query, placetype))
|
|
1197
|
+
}
|
|
1198
|
+
} catch (error) {
|
|
1199
|
+
// Defensive: a backend failure should not abort the whole tree walk. Leave the node with
|
|
1200
|
+
// its classifier attribution intact.
|
|
1201
|
+
//
|
|
1202
|
+
// The reason rides the gate name. A bare `backend_error` cannot tell a closed database from a
|
|
1203
|
+
// finalized statement from a genuine query fault, which is what made three full-board constraint
|
|
1204
|
+
// runs unreadable — 64 of 591 rows errored and the census could not say why.
|
|
1205
|
+
rec.gate(`backend_error: ${(error as Error).message}`)
|
|
1206
|
+
rec.emit(null)
|
|
1207
|
+
|
|
1208
|
+
return null
|
|
1036
1209
|
}
|
|
1037
|
-
}
|
|
1038
|
-
|
|
1039
|
-
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
|
|
1213
|
+
// the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
|
|
1214
|
+
// resolves the node to a synthetic place (id 0), carrying a coordinate ONLY when the index node
|
|
1215
|
+
// does — the ancestry-only tier stays coordinate-free (B3-3's 0% half, meaning-of-zero). The
|
|
1216
|
+
// prior's payload is returned as node metadata for #walk to stamp. Opt-in via `postcodePrefixPrior`
|
|
1217
|
+
// + `postcodePrefixIndex`; OFF by default (D-rule: the PCN1 posture).
|
|
1218
|
+
if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
|
|
1219
|
+
const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country)
|
|
1220
|
+
|
|
1221
|
+
if (probe) {
|
|
1222
|
+
const metadata: Record<string, unknown> = {
|
|
1223
|
+
postcode_prefix: probe.prefix,
|
|
1224
|
+
postcode_prefix_ancestors: probe.node.ancestors,
|
|
1225
|
+
...(probe.node.radiusP95Km !== undefined ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
|
|
1226
|
+
...(probe.node.lat !== undefined && probe.node.lon !== undefined
|
|
1227
|
+
? { coordinate_source: "postcode_prefix" }
|
|
1228
|
+
: {}),
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
rec.gate("postcode_prefix_prior")
|
|
1232
|
+
const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
|
|
1233
|
+
|
|
1234
|
+
rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
|
|
1235
|
+
|
|
1236
|
+
return {
|
|
1237
|
+
top: prefixPlace,
|
|
1238
|
+
alternatives: [],
|
|
1239
|
+
metadata,
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
// The bare-toponym country race (fix B of the bare-country class): a lone locality-tagged span
|
|
1245
|
+
// also races the `country` placetype, because the parser tags bare country names `locality`
|
|
1246
|
+
// about half the time ("Japan", "China") and the locality filter makes the country row
|
|
1247
|
+
// unreachable at any rank. Runs ONLY for the tree's single value-bearing node, so every
|
|
1248
|
+
// address-shaped input is byte-stable. The locality winner's prominence arbitrates below;
|
|
1249
|
+
// with no locality candidates at all, a country hit resolves the span outright.
|
|
1250
|
+
const isBareRace = placetype === "locality" && node === state.bareLocalityNode
|
|
1251
|
+
|
|
1252
|
+
if (isBareRace) {
|
|
1253
|
+
rec.gate("bare_race")
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null
|
|
1257
|
+
const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null
|
|
1258
|
+
|
|
1259
|
+
if (!candidates.length) {
|
|
1260
|
+
// With no locality candidates at all, the admin namesake with the larger population answers
|
|
1261
|
+
// outright (the same precedence the dominance rule below applies).
|
|
1262
|
+
const admin = pickLargerAdmin(bareCountry, bareRegion)
|
|
1263
|
+
|
|
1264
|
+
if (admin) {
|
|
1265
|
+
rec.gate("empty_admin_pick")
|
|
1266
|
+
rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" })
|
|
1267
|
+
|
|
1268
|
+
return {
|
|
1269
|
+
top: admin,
|
|
1270
|
+
alternatives: [],
|
|
1271
|
+
metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
rec.emit(null)
|
|
1276
|
+
|
|
1040
1277
|
return null
|
|
1041
1278
|
}
|
|
1042
1279
|
|
|
1043
|
-
if (!candidates.length) return null
|
|
1044
1280
|
// Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
|
|
1045
1281
|
// postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
|
|
1046
1282
|
// postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
|
|
@@ -1089,6 +1325,70 @@ class WOFResolver implements Resolver {
|
|
|
1089
1325
|
|
|
1090
1326
|
return bKey - aKey || b.score - a.score
|
|
1091
1327
|
})
|
|
1328
|
+
|
|
1329
|
+
rec.stage("anchor", ranked)
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
|
|
1333
|
+
// toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
|
|
1334
|
+
// `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
|
|
1335
|
+
// country for this shape rather than choosing between "hard filter" and "nothing". This is the
|
|
1336
|
+
// third option: an additive bonus inside the exact tier, never a filter.
|
|
1337
|
+
//
|
|
1338
|
+
// Three stand-downs, in the order they matter. A `defaultCountry` makes the prior a no-op by
|
|
1339
|
+
// construction (every candidate is already in it), so we skip the work rather than pretend. An
|
|
1340
|
+
// `anchorPosterior` is derived from the address's OWN postcode — evidence, which outranks a guess
|
|
1341
|
+
// about where the user is sitting. And an absent prior is the SHIPPED default: `ResolveOpts`
|
|
1342
|
+
// documents why (the weight that flips the four bare GB rows and the weight that holds the en-US
|
|
1343
|
+
// board are disjoint intervals), so this is inert unless a caller opts in.
|
|
1344
|
+
//
|
|
1345
|
+
// Runs BEFORE the importance key deliberately, matching span-rescore: fame is the stronger signal
|
|
1346
|
+
// wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
|
|
1347
|
+
if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
|
|
1348
|
+
ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight)
|
|
1349
|
+
rec.stage("locale_prior", ranked)
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
|
|
1353
|
+
// alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
|
|
1354
|
+
// (128,377) over Whitby, North Yorkshire (13,130), 5,508 km from where the person meant. Fame is
|
|
1355
|
+
// what a bare toponym is asking about, and the candidate build's blended `importance` column
|
|
1356
|
+
// measures it. Tier-safe and positive-evidence-only (an UNSCORED candidate keeps the rank
|
|
1357
|
+
// population gave it; only the scored ones permute), so it abstains byte-stably on an artifact
|
|
1358
|
+
// that predates the column.
|
|
1359
|
+
//
|
|
1360
|
+
// Skipped outright when an anchor posterior is in force. Fame is the prior of LAST resort: it answers
|
|
1361
|
+
// "which one did you probably mean" only when nothing in the query answered it, and a #369 posterior is
|
|
1362
|
+
// derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
|
|
1363
|
+
if (!state.anchorPosterior) {
|
|
1364
|
+
ranked = rankByImportance(ranked)
|
|
1365
|
+
rec.stage("importance", ranked)
|
|
1366
|
+
|
|
1367
|
+
// #1880 — bounded capital promotion, directly above the fame key it corrects and below the
|
|
1368
|
+
// containment partition (the qualifier is the address's own text; evidence outranks a prior).
|
|
1369
|
+
// Same stand-down as fame: an anchor posterior is postcode evidence and silences the prior.
|
|
1370
|
+
if (state.capitalLevel) {
|
|
1371
|
+
ranked = promoteCapitals(ranked, state.capitalLevel)
|
|
1372
|
+
rec.stage("capital", ranked)
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// Admin-containment partition (#1717 stage 2): the LAST soft re-rank, after the anchor/fame keys
|
|
1377
|
+
// above, because the qualifier is the address's OWN text — evidence, which outranks a prior. The
|
|
1378
|
+
// backend already put contained rows first; this second partition is load-bearing, not belt-and-
|
|
1379
|
+
// braces: `rankByImportance` just re-ordered the exact tier by fame, and Richmond, Virginia
|
|
1380
|
+
// outscores Richmond, North Yorkshire on importance — without this the lever loses exactly where
|
|
1381
|
+
// fame disagrees with the qualifier (the shared-function partition, tier-safe + stable, so it can
|
|
1382
|
+
// never promote a contained partial match over an exact one). No stamps → identity → byte-stable
|
|
1383
|
+
// on any backend that ignored `regionQualifier`.
|
|
1384
|
+
if (containmentEligible) {
|
|
1385
|
+
ranked = partitionByContainment(
|
|
1386
|
+
ranked,
|
|
1387
|
+
(c) => c.containedByQualifier === true,
|
|
1388
|
+
(c) => c.exactMatch === true
|
|
1389
|
+
)
|
|
1390
|
+
|
|
1391
|
+
rec.stage("containment", ranked)
|
|
1092
1392
|
}
|
|
1093
1393
|
|
|
1094
1394
|
// Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
|
|
@@ -1106,77 +1406,59 @@ class WOFResolver implements Resolver {
|
|
|
1106
1406
|
...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
|
|
1107
1407
|
...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
|
|
1108
1408
|
]
|
|
1409
|
+
|
|
1410
|
+
rec.stage("exact_type", ranked)
|
|
1109
1411
|
}
|
|
1110
1412
|
|
|
1111
1413
|
const top = ranked[0]!
|
|
1112
1414
|
|
|
1113
|
-
if (top.score < state.minWinningScore)
|
|
1415
|
+
if (top.score < state.minWinningScore) {
|
|
1416
|
+
rec.gate("min_score_reject")
|
|
1417
|
+
rec.emit(null)
|
|
1114
1418
|
|
|
1115
|
-
|
|
1116
|
-
// existed for this span, annotate that a broader tier stood in for the true one. Additive —
|
|
1117
|
-
// identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
|
|
1118
|
-
if (isPlacetypeFallback(placetype, top.placetype)) {
|
|
1119
|
-
top.resolutionQuality = "fallback"
|
|
1419
|
+
return null
|
|
1120
1420
|
}
|
|
1121
1421
|
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
}
|
|
1422
|
+
// The admin side of the bare-toponym race. The COUNTRY row wins on prominence alone —
|
|
1423
|
+
// Japan-the-country (pop 126M) over Japan, Pennsylvania (pop 0) — while the REGION row must
|
|
1424
|
+
// DOMINATE the locality winner by {@link BARE_REGION_DOMINANCE_LOG10} in log-population:
|
|
1425
|
+
// prominence saturates at the backend's populationBoost cap, so the margin is measured on the
|
|
1426
|
+
// raw populations, and the margin is what keeps bare "New York" on the city (state 19.6M vs
|
|
1427
|
+
// city 8.8M = 0.35, under the cut) while bare "Georgia" promotes to the 11M state over the
|
|
1428
|
+
// Vermont hamlet (margin 3.4). A bare name with no admin namesake never reaches these lines,
|
|
1429
|
+
// and the displaced locality stays first among the alternatives either way.
|
|
1430
|
+
if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
|
|
1431
|
+
rec.gate("bare_country_repick")
|
|
1432
|
+
rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" })
|
|
1433
|
+
|
|
1434
|
+
return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } }
|
|
1435
|
+
}
|
|
1125
1436
|
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
* assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
|
|
1130
|
-
* failures, [#8 in the failure catalogue]).
|
|
1131
|
-
*/
|
|
1132
|
-
function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives: ResolvedPlace[]): void {
|
|
1133
|
-
if (node.source !== undefined || node.sourceID !== undefined) {
|
|
1134
|
-
const meta = { ...node.metadata }
|
|
1437
|
+
if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
|
|
1438
|
+
rec.gate("bare_region_repick")
|
|
1439
|
+
rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" })
|
|
1135
1440
|
|
|
1136
|
-
|
|
1137
|
-
meta["classifier_source"] = node.source
|
|
1441
|
+
return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } }
|
|
1138
1442
|
}
|
|
1139
1443
|
|
|
1140
|
-
|
|
1141
|
-
|
|
1444
|
+
// Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
|
|
1445
|
+
// existed for this span, annotate that a broader tier stood in for the true one. Additive —
|
|
1446
|
+
// identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
|
|
1447
|
+
if (isPlacetypeFallback(placetype, top.placetype)) {
|
|
1448
|
+
top.resolutionQuality = "fallback"
|
|
1449
|
+
rec.gate("placetype_fallback")
|
|
1142
1450
|
}
|
|
1143
1451
|
|
|
1144
|
-
|
|
1145
|
-
}
|
|
1452
|
+
rec.emit({ id: top.id, name: top.name, source: "ranked" })
|
|
1146
1453
|
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name }
|
|
1157
|
-
|
|
1158
|
-
// The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
|
|
1159
|
-
// forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
|
|
1160
|
-
// though it has no `ancestors()` table.
|
|
1161
|
-
if (resolved.country) {
|
|
1162
|
-
node.metadata["resolver_country"] = resolved.country
|
|
1163
|
-
}
|
|
1164
|
-
|
|
1165
|
-
// The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
|
|
1166
|
-
// geographically different place than the parsed city name. Surface it so callers can warn rather
|
|
1167
|
-
// than silently trust the resolved point.
|
|
1168
|
-
if (resolved.mismatch) {
|
|
1169
|
-
node.metadata["postcode_city_mismatch"] = true
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
// Fallback-observability (#718): a broader admin tier (macroregion/macrocounty) stood in for the
|
|
1173
|
-
// true region/county because no exact-type candidate existed. Additive annotation only — the
|
|
1174
|
-
// resolved coordinate/identity above is untouched; this just lets a consumer / QA pass see it.
|
|
1175
|
-
if (resolved.resolutionQuality) {
|
|
1176
|
-
node.metadata["resolution_quality"] = resolved.resolutionQuality
|
|
1177
|
-
}
|
|
1178
|
-
|
|
1179
|
-
if (alternatives.length) {
|
|
1180
|
-
node.alternatives = alternatives
|
|
1454
|
+
// The lever's trace stamp (#1717 stage 2 / #1719's rule): an opted-in mechanism that cannot fire
|
|
1455
|
+
// — a pre-sidecar artifact, an incapable backend — must say so in the result, not degrade
|
|
1456
|
+
// silently. The parse-side census cannot see resolver levers, so this stamp is its census
|
|
1457
|
+
// surface. Only under the lever: the stamp asserts a question was asked.
|
|
1458
|
+
return {
|
|
1459
|
+
top,
|
|
1460
|
+
alternatives: ranked.slice(1),
|
|
1461
|
+
...(containmentEligible ? { metadata: { admin_containment: adminContainmentVerdict(ranked) } } : {}),
|
|
1462
|
+
}
|
|
1181
1463
|
}
|
|
1182
1464
|
}
|