@mailwoman/resolver 7.2.0 → 7.2.1
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/index.ts +39 -0
- package/package.json +35 -15
- package/plausibility.ts +170 -0
- package/remote-resolver.ts +103 -0
- package/rerank.ts +135 -0
- package/resolve.ts +1379 -0
- package/span-rescore.ts +316 -0
- package/street-evidence.ts +190 -0
- package/vitest.config.ts +39 -0
package/index.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* `@mailwoman/resolver` — the address resolver implementation, lifted out of `@mailwoman/core`
|
|
7
|
+
* (#215) so it can depend on `@mailwoman/spatial` (haversine) + `@mailwoman/codex` (USPS
|
|
8
|
+
* directionals) instead of reinventing them. The TYPE contract stays in
|
|
9
|
+
* `@mailwoman/core/resolver` (so the `core/pipeline` composes the resolver structurally without a
|
|
10
|
+
* package cycle); this barrel re-exports it, so `@mailwoman/resolver` is a complete drop-in for
|
|
11
|
+
* what used to be `@mailwoman/core/resolver`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export { RemoteResolver, serializableResolveOpts } from "./remote-resolver.ts"
|
|
15
|
+
export type {
|
|
16
|
+
RemoteResolverOpts,
|
|
17
|
+
ResolveTreeRequest,
|
|
18
|
+
ResolveTreeResponse,
|
|
19
|
+
SerializableResolveOpts,
|
|
20
|
+
} from "./remote-resolver.ts"
|
|
21
|
+
export { createWOFResolver } from "./resolve.ts"
|
|
22
|
+
export { finestResolvedCoordinate, isImplausibleResolution } from "./plausibility.ts"
|
|
23
|
+
export type { PlausibilityVerdict, ResolvedCoordinate } from "./plausibility.ts"
|
|
24
|
+
export { foldStreetSurface, isPureTypeVocabulary, pickByStreetEvidence } from "./street-evidence.ts"
|
|
25
|
+
export type {
|
|
26
|
+
PickByStreetEvidenceOpts,
|
|
27
|
+
StreetCandidate,
|
|
28
|
+
StreetEvidencePick,
|
|
29
|
+
StreetEvidenceScope,
|
|
30
|
+
StreetLocalityEvidence,
|
|
31
|
+
} from "./street-evidence.ts"
|
|
32
|
+
export { findRescoreCandidate, hasResolvedPlace } from "./span-rescore.ts"
|
|
33
|
+
export type { RescoreCandidate, SpanRescoreOptions } from "./span-rescore.ts"
|
|
34
|
+
|
|
35
|
+
// The type contract + placetype helpers live in core (pure types, keep core a leaf). Re-export so
|
|
36
|
+
// consumers get the whole surface from `@mailwoman/resolver`.
|
|
37
|
+
export * from "@mailwoman/core/resolver"
|
|
38
|
+
|
|
39
|
+
export * from "./rerank.ts"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mailwoman/resolver",
|
|
3
|
-
"version": "7.2.
|
|
3
|
+
"version": "7.2.1",
|
|
4
4
|
"description": "The address resolver: walk an AddressTree, decorate nodes with gazetteer-supplied coordinates + attribution. Backend-agnostic (any ResolverBackend), with the span-rescore + postcode-consistency levers. Lifted out of @mailwoman/core so it can depend on @mailwoman/spatial (haversine) + @mailwoman/codex (USPS directionals) instead of reinventing them; the type contract stays in core so the pipeline composes it without a cycle.",
|
|
5
5
|
"license": "AGPL-3.0-only OR LicenseRef-Commercial",
|
|
6
6
|
"repository": {
|
|
@@ -12,33 +12,53 @@
|
|
|
12
12
|
"out/**/*.js",
|
|
13
13
|
"out/**/*.js.map",
|
|
14
14
|
"out/**/*.d.ts",
|
|
15
|
-
"out/**/*.d.ts.map"
|
|
15
|
+
"out/**/*.d.ts.map",
|
|
16
|
+
"*.ts",
|
|
17
|
+
"*.tsx",
|
|
18
|
+
"**/*.ts",
|
|
19
|
+
"**/*.tsx",
|
|
20
|
+
"!*.test.ts",
|
|
21
|
+
"!*.test.tsx",
|
|
22
|
+
"!**/*.test.ts",
|
|
23
|
+
"!**/*.test.tsx"
|
|
16
24
|
],
|
|
17
25
|
"type": "module",
|
|
18
26
|
"exports": {
|
|
19
27
|
"./package.json": "./package.json",
|
|
20
28
|
".": {
|
|
21
|
-
"
|
|
22
|
-
"default": "./out/index.js"
|
|
23
|
-
"types": "./out/index.d.ts"
|
|
29
|
+
"types": "./out/index.d.ts",
|
|
30
|
+
"default": "./out/index.js"
|
|
24
31
|
},
|
|
25
32
|
"./resolve": {
|
|
26
|
-
"
|
|
27
|
-
"default": "./out/resolve.js"
|
|
28
|
-
"types": "./out/resolve.d.ts"
|
|
33
|
+
"types": "./out/resolve.d.ts",
|
|
34
|
+
"default": "./out/resolve.js"
|
|
29
35
|
},
|
|
30
36
|
"./span-rescore": {
|
|
31
|
-
"
|
|
32
|
-
"default": "./out/span-rescore.js"
|
|
33
|
-
"types": "./out/span-rescore.d.ts"
|
|
37
|
+
"types": "./out/span-rescore.d.ts",
|
|
38
|
+
"default": "./out/span-rescore.js"
|
|
34
39
|
}
|
|
35
40
|
},
|
|
36
41
|
"publishConfig": {
|
|
37
|
-
"access": "public"
|
|
42
|
+
"access": "public",
|
|
43
|
+
"exports": {
|
|
44
|
+
"./package.json": "./package.json",
|
|
45
|
+
".": {
|
|
46
|
+
"types": "./out/index.d.ts",
|
|
47
|
+
"default": "./out/index.js"
|
|
48
|
+
},
|
|
49
|
+
"./resolve": {
|
|
50
|
+
"types": "./out/resolve.d.ts",
|
|
51
|
+
"default": "./out/resolve.js"
|
|
52
|
+
},
|
|
53
|
+
"./span-rescore": {
|
|
54
|
+
"types": "./out/span-rescore.d.ts",
|
|
55
|
+
"default": "./out/span-rescore.js"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
38
58
|
},
|
|
39
59
|
"dependencies": {
|
|
40
|
-
"@mailwoman/codex": "7.2.
|
|
41
|
-
"@mailwoman/core": "7.2.
|
|
42
|
-
"@mailwoman/spatial": "7.2.
|
|
60
|
+
"@mailwoman/codex": "7.2.1",
|
|
61
|
+
"@mailwoman/core": "7.2.1",
|
|
62
|
+
"@mailwoman/spatial": "7.2.1"
|
|
43
63
|
}
|
|
44
64
|
}
|
package/plausibility.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Resolution-plausibility guard (#727 / v7 excision arc).
|
|
7
|
+
*
|
|
8
|
+
* The 2026-07-15 coordinate-parity study
|
|
9
|
+
* (`docs/articles/evals/2026-07-15-v7-parity-floor-diagnosis.md`) found the neural parser is
|
|
10
|
+
* coordinate-safe on well-formed input (98.6% within 1 km of the rules parser through the same
|
|
11
|
+
* resolver) but produces a garbage-geocode tail on the bare-fragment / bare-state-name / US-highway
|
|
12
|
+
* classes — inputs like `California` or `6000, NSW, Australia` that resolve to nothing finer than a
|
|
13
|
+
* country centroid.
|
|
14
|
+
*
|
|
15
|
+
* This guard is the cheap post-resolve check for that tail: a resolved tree whose finest resolved
|
|
16
|
+
* place is only a `country` centroid is implausible for a structured address. It reads only the
|
|
17
|
+
* decorated tree — no gazetteer, no extra query — so it is free to run on every resolve. It is
|
|
18
|
+
* deliberately DIRECTION-AGNOSTIC about what the caller does with the signal: serve the result with
|
|
19
|
+
* a low-confidence marker, prefer a sibling parse hypothesis (the #727 k-best rerank), or decline to
|
|
20
|
+
* emit a coordinate. It is NOT a rules-fallback trigger — the v7 excision deletes the rules parser
|
|
21
|
+
* outright (operator ruling 2026-07-15), so no consumer may route through legacy rules on a trip.
|
|
22
|
+
*
|
|
23
|
+
* It deliberately does NOT flag region-tier resolutions: a US state or a province centroid
|
|
24
|
+
* (`Texas` → the TX centroid) is a legitimate coarse geocode, not garbage. Only "resolved no finer
|
|
25
|
+
* than a country" trips it.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type { AddressNode, AddressTree, ComponentTag } from "@mailwoman/core/decoder"
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Resolution granularity, coarse → fine. A resolved node's {@link AddressNode.tag} places it on this ladder; the
|
|
32
|
+
* geocode a caller serves comes from the FINEST resolved node. Tags absent here (unit, po_box, intersection halves, …)
|
|
33
|
+
* are treated as street-tier specificity when resolved.
|
|
34
|
+
*/
|
|
35
|
+
const RESOLUTION_TIER: Partial<Record<ComponentTag, number>> = {
|
|
36
|
+
country: 0,
|
|
37
|
+
region: 1,
|
|
38
|
+
subregion: 2,
|
|
39
|
+
dependent_locality: 3,
|
|
40
|
+
locality: 3,
|
|
41
|
+
postcode: 4,
|
|
42
|
+
venue: 4,
|
|
43
|
+
street: 4,
|
|
44
|
+
street_prefix: 4,
|
|
45
|
+
street_suffix: 4,
|
|
46
|
+
house_number: 5,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A resolved place lifted off the tree — the coordinate a caller would serve, plus its granularity tag. */
|
|
50
|
+
export interface ResolvedCoordinate {
|
|
51
|
+
tag: ComponentTag
|
|
52
|
+
lat: number
|
|
53
|
+
lon: number
|
|
54
|
+
/** Canonical place URI (`wof:…`) when the resolver supplied one. */
|
|
55
|
+
placeID?: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Walk a resolved {@link AddressTree} and return the FINEST resolved place — the node carrying a resolver-supplied
|
|
60
|
+
* coordinate at the deepest granularity tier. Returns `null` when nothing resolved (no node carries a `lat`/`lon`).
|
|
61
|
+
* Ties break toward the first node in document order.
|
|
62
|
+
*/
|
|
63
|
+
export function finestResolvedCoordinate(tree: AddressTree): ResolvedCoordinate | null {
|
|
64
|
+
let best: ResolvedCoordinate | null = null
|
|
65
|
+
let bestTier = -1
|
|
66
|
+
|
|
67
|
+
const visit = (node: AddressNode): void => {
|
|
68
|
+
if (node.lat !== undefined && node.lon !== undefined) {
|
|
69
|
+
const tier = RESOLUTION_TIER[node.tag] ?? 4
|
|
70
|
+
|
|
71
|
+
if (tier > bestTier) {
|
|
72
|
+
bestTier = tier
|
|
73
|
+
best = { tag: node.tag, lat: node.lat, lon: node.lon, placeID: node.placeID }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
for (const child of node.children) {
|
|
78
|
+
visit(child)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
for (const root of tree.roots) {
|
|
83
|
+
visit(root)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return best
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Coarse per-country bounding boxes `[latMin, latMax, lonMin, lonMax]` for the cross-country guard (guard B). These are
|
|
91
|
+
* DELIBERATELY rough — a guard needs "obviously the wrong country", not cartography — and they mirror the boxes the
|
|
92
|
+
* 2026-07-15 coordinate-parity receipt harness measured with (`scratchpad/coord-parity.mjs`). The US box spans Alaska →
|
|
93
|
+
* the mainland east coast; continental FR only; etc. A country absent here simply never trips the guard (fail-open).
|
|
94
|
+
*/
|
|
95
|
+
const COUNTRY_BBOX: Readonly<Record<string, readonly [number, number, number, number]>> = {
|
|
96
|
+
US: [18, 72, -180, -66],
|
|
97
|
+
AU: [-44, -10, 112, 154],
|
|
98
|
+
BR: [-34, 6, -74, -34],
|
|
99
|
+
CZ: [48, 51.5, 12, 19],
|
|
100
|
+
DE: [47, 55.5, 5.5, 15.5],
|
|
101
|
+
ES: [35, 44, -10, 5],
|
|
102
|
+
FR: [41, 51.5, -5.5, 9.8],
|
|
103
|
+
GB: [49, 61, -8.7, 2],
|
|
104
|
+
HR: [42, 46.6, 13, 19.5],
|
|
105
|
+
IN: [6, 36, 68, 98],
|
|
106
|
+
NL: [50.7, 53.7, 3.3, 7.3],
|
|
107
|
+
NO: [57, 71.5, 4, 31],
|
|
108
|
+
PL: [49, 55, 14, 24.2],
|
|
109
|
+
PT: [36.5, 42.2, -9.6, -6.1],
|
|
110
|
+
RO: [43.5, 48.3, 20, 30],
|
|
111
|
+
SE: [55, 69.1, 10.9, 24.2],
|
|
112
|
+
SK: [47.7, 49.7, 16.8, 22.6],
|
|
113
|
+
SI: [45.4, 46.9, 13.3, 16.6],
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** True when the coordinate lies outside `countryCode`'s coarse bbox. Unknown country codes are fail-open (false). */
|
|
117
|
+
export function outsideExpectedCountry(countryCode: string, lat: number, lon: number): boolean {
|
|
118
|
+
const b = COUNTRY_BBOX[countryCode.toUpperCase()]
|
|
119
|
+
|
|
120
|
+
if (!b) return false
|
|
121
|
+
|
|
122
|
+
return lat < b[0] || lat > b[1] || lon < b[2] || lon > b[3]
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Result of {@link isImplausibleResolution} — the boolean plus the reason, for telemetry + fallback logs. */
|
|
126
|
+
export interface PlausibilityVerdict {
|
|
127
|
+
implausible: boolean
|
|
128
|
+
/**
|
|
129
|
+
* Set when `implausible` is true. `country-centroid` = resolved no finer than a country (guard A);
|
|
130
|
+
* `outside-expected-country` = the served coordinate lies outside the expected country's bbox (guard B).
|
|
131
|
+
*/
|
|
132
|
+
reason?: "country-centroid" | "outside-expected-country"
|
|
133
|
+
/** The coordinate the verdict was drawn from, when anything resolved. */
|
|
134
|
+
coordinate?: ResolvedCoordinate
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface PlausibilityOpts {
|
|
138
|
+
/**
|
|
139
|
+
* ISO-2 country the resolution is EXPECTED to land in, when the caller knows it (a locale hint, a parsed country, a
|
|
140
|
+
* fixture's gold country). Enables guard B: a coordinate outside this country's coarse bbox is implausible — the
|
|
141
|
+
* cross-country-jump class guard A structurally cannot catch (`1210a IA 10 W IA` → a coordinate ~10,000 km from the
|
|
142
|
+
* US was country-centroid-free and sailed through until guard B landed here, 2026-07-17; previously the check lived
|
|
143
|
+
* only in the receipt harness, so the shipped residual read 5/321 while the receipt said 3/321).
|
|
144
|
+
*/
|
|
145
|
+
expectedCountry?: string
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Decide whether a resolved tree's geocode is implausible for a structured address — the cheap guard the v7 hybrid gate
|
|
150
|
+
* runs after routing an input to the neural parser (#38). Trips when the finest resolved place is a bare `country`
|
|
151
|
+
* centroid (guard A), or — when the caller supplies `expectedCountry` — when the served coordinate falls outside that
|
|
152
|
+
* country's coarse bbox (guard B). An unresolved tree (nothing to serve) is plausible: there is no garbage to serve.
|
|
153
|
+
*/
|
|
154
|
+
export function isImplausibleResolution(tree: AddressTree, opts: PlausibilityOpts = {}): PlausibilityVerdict {
|
|
155
|
+
const coordinate = finestResolvedCoordinate(tree)
|
|
156
|
+
|
|
157
|
+
if (coordinate && coordinate.tag === "country") {
|
|
158
|
+
return { implausible: true, reason: "country-centroid", coordinate }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (
|
|
162
|
+
coordinate &&
|
|
163
|
+
opts.expectedCountry &&
|
|
164
|
+
outsideExpectedCountry(opts.expectedCountry, coordinate.lat, coordinate.lon)
|
|
165
|
+
) {
|
|
166
|
+
return { implausible: true, reason: "outside-expected-country", coordinate }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return { implausible: false, coordinate: coordinate ?? undefined }
|
|
170
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* `RemoteResolver` — the `Resolver` interface (`resolveTree`) over HTTP. The adapter the interface
|
|
7
|
+
* docstring anticipated (Phase 4.4): a client POSTs a parsed `AddressTree` + the serializable
|
|
8
|
+
* `ResolveOpts` to a resolver service, which owns the gazetteer + situs/interpolation shards,
|
|
9
|
+
* runs the cascade, and returns the resolved tree. Two payoffs:
|
|
10
|
+
*
|
|
11
|
+
* 1. **Multi-instance** — stateless parser nodes (the ~30 MB ONNX model) talk to ONE resolver service
|
|
12
|
+
* (the multi-GB gazetteer + shards). `parse` locally, `new RemoteResolver(...).resolveTree`
|
|
13
|
+
* remotely — same interface the in-process `WOFResolver` satisfies, so it's a drop-in.
|
|
14
|
+
* 2. **Canary** — point it at a second resolver build (or an adapter fronting Pelias/Nominatim/BAN)
|
|
15
|
+
* and diff the resolved trees through the identical contract.
|
|
16
|
+
*
|
|
17
|
+
* Pure transport: `fetch` only, no node-specific deps (runs in the browser too). The
|
|
18
|
+
* `addressPoints` / `interpolation` opts are LIVE SQLite handles — not serializable — so they're
|
|
19
|
+
* stripped before the POST; the resolver service supplies its own from the tree's region (the
|
|
20
|
+
* data lives server-side, which is the whole point). All other opts (defaultCountry, calibration,
|
|
21
|
+
* hierarchyCompletion, …) ride along.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { AddressTree } from "@mailwoman/core/decoder"
|
|
25
|
+
import type { ResolveOpts, Resolver } from "@mailwoman/core/resolver"
|
|
26
|
+
|
|
27
|
+
/** `ResolveOpts` minus the non-serializable live lookup handles. What actually crosses the wire. */
|
|
28
|
+
export type SerializableResolveOpts = Omit<ResolveOpts, "addressPoints" | "interpolation">
|
|
29
|
+
|
|
30
|
+
/** Strip the live lookup handles from `ResolveOpts` so the rest can be JSON-serialized over HTTP. */
|
|
31
|
+
export function serializableResolveOpts(opts?: ResolveOpts): SerializableResolveOpts | undefined {
|
|
32
|
+
if (!opts) return undefined
|
|
33
|
+
const { addressPoints: _ap, interpolation: _ip, ...rest } = opts
|
|
34
|
+
|
|
35
|
+
return rest
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface RemoteResolverOpts {
|
|
39
|
+
/**
|
|
40
|
+
* Full URL of the resolver service's resolve-tree endpoint, e.g. `http://resolver:7081/v1/resolve`.
|
|
41
|
+
*/
|
|
42
|
+
endpoint: string
|
|
43
|
+
/** Injectable fetch (tests / custom agents). Defaults to the global `fetch`. */
|
|
44
|
+
fetch?: typeof fetch
|
|
45
|
+
/** Per-request timeout in ms. Default 10000. */
|
|
46
|
+
timeoutMs?: number
|
|
47
|
+
/** Extra headers (auth, tracing). `Content-Type: application/json` is always set. */
|
|
48
|
+
headers?: Record<string, string>
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The wire request body `POST <endpoint>` expects (and the matching server handler parses). */
|
|
52
|
+
export interface ResolveTreeRequest {
|
|
53
|
+
tree: AddressTree
|
|
54
|
+
opts?: SerializableResolveOpts
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The wire response body the server returns. */
|
|
58
|
+
export interface ResolveTreeResponse {
|
|
59
|
+
tree: AddressTree
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class RemoteResolver implements Resolver {
|
|
63
|
+
readonly #endpoint: string
|
|
64
|
+
readonly #fetch: typeof fetch
|
|
65
|
+
readonly #timeoutMs: number
|
|
66
|
+
readonly #headers: Record<string, string>
|
|
67
|
+
|
|
68
|
+
constructor(opts: RemoteResolverOpts) {
|
|
69
|
+
if (!opts.endpoint) throw new Error("RemoteResolver: `endpoint` is required")
|
|
70
|
+
this.#endpoint = opts.endpoint
|
|
71
|
+
this.#fetch = opts.fetch ?? globalThis.fetch
|
|
72
|
+
this.#timeoutMs = opts.timeoutMs ?? 10_000
|
|
73
|
+
this.#headers = opts.headers ?? {}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async resolveTree(tree: AddressTree, opts?: ResolveOpts): Promise<AddressTree> {
|
|
77
|
+
const controller = new AbortController()
|
|
78
|
+
const timer = setTimeout(() => controller.abort(), this.#timeoutMs)
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
const body: ResolveTreeRequest = { tree, opts: serializableResolveOpts(opts) }
|
|
82
|
+
const res = await this.#fetch(this.#endpoint, {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: { "Content-Type": "application/json", ...this.#headers },
|
|
85
|
+
body: JSON.stringify(body),
|
|
86
|
+
signal: controller.signal,
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
if (!res.ok) {
|
|
90
|
+
throw new Error(`RemoteResolver: ${this.#endpoint} → HTTP ${res.status} ${res.statusText}`)
|
|
91
|
+
}
|
|
92
|
+
const json = (await res.json()) as Partial<ResolveTreeResponse>
|
|
93
|
+
|
|
94
|
+
if (!json || !json.tree || !Array.isArray(json.tree.roots)) {
|
|
95
|
+
throw new Error("RemoteResolver: malformed response (missing `tree.roots`)")
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return json.tree
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(timer)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
package/rerank.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* #727 stage-2 Phase 4a — reranking a k-best parse list on RESOLUTION EVIDENCE.
|
|
7
|
+
*
|
|
8
|
+
* The arc's thesis, stated by the operator (2026-07-15): the arbiter for a k-best list is the
|
|
9
|
+
* resolver, not hand-weights. A rank-2 parse that resolves to a real place beats a rank-1 that
|
|
10
|
+
* resolves to a country centroid.
|
|
11
|
+
*
|
|
12
|
+
* The measured case for this existing at all: on the triaged parity corpus the shipped decode gets
|
|
13
|
+
* street 0.573 while the span decode's top-10 CONTAINS the right answer 0.775 of the time
|
|
14
|
+
* (oracle@5 0.723). Rank-1 cannot reach that headroom; only a reranker can.
|
|
15
|
+
*
|
|
16
|
+
* ## Why this is deliberately, almost embarrassingly small
|
|
17
|
+
*
|
|
18
|
+
* The failure mode we are avoiding is Pelias's: a ladder of per-class hand-tuned weights that
|
|
19
|
+
* nobody can re-derive (see `docs/articles/evals/competitive-parity/2026-07-15-pelias-dictionary-overrides.md`
|
|
20
|
+
* — 94 of 276 dictionary lines are hand-written deletions, each resolving a collision in favour of
|
|
21
|
+
* whoever complained loudest). The moment this file grows a per-hypothesis score blend, we have
|
|
22
|
+
* rebuilt that with extra steps.
|
|
23
|
+
*
|
|
24
|
+
* So the rule is ONE bit of evidence, not a score: **drop hypotheses whose resolution is
|
|
25
|
+
* implausible; otherwise keep the model's own ranking.** The parse scores already share a partition
|
|
26
|
+
* function and are comparable within an input — the reranker's job is not to re-score them, it is to
|
|
27
|
+
* veto the ones the world says are wrong.
|
|
28
|
+
*
|
|
29
|
+
* Adding a second signal here requires the same bar the first one cleared: a MEASURED win on the
|
|
30
|
+
* parity + Paris fixtures, stated in a verdict doc. Not a plausible story.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import type { AddressTree } from "@mailwoman/core/decoder"
|
|
34
|
+
|
|
35
|
+
import { isImplausibleResolution } from "./plausibility.ts"
|
|
36
|
+
|
|
37
|
+
/** One candidate parse from the k-best decode, with its (within-input comparable) score. */
|
|
38
|
+
export interface RerankCandidate<T = unknown> {
|
|
39
|
+
/** The parse's own score. Comparable to its siblings from the SAME input; not across inputs. */
|
|
40
|
+
score: number
|
|
41
|
+
/** The parse tree, UNRESOLVED — `rerankByResolution` resolves it via the injected resolver. */
|
|
42
|
+
tree: AddressTree
|
|
43
|
+
/** Opaque caller payload carried through to the result (the segmentation, a surface string, …). */
|
|
44
|
+
payload?: T
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface RerankedCandidate<T = unknown> extends RerankCandidate<T> {
|
|
48
|
+
/** The resolved tree (the resolver's output), or null when resolution threw. */
|
|
49
|
+
resolved: AddressTree | null
|
|
50
|
+
/** True when the resolution is implausible (today: resolves no finer than a country centroid). */
|
|
51
|
+
implausible: boolean
|
|
52
|
+
/** Why it was vetoed, when it was. */
|
|
53
|
+
reason?: string
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface RerankResult<T = unknown> {
|
|
57
|
+
/** Candidates in FINAL order: plausible ones first (model order preserved), vetoed ones after. */
|
|
58
|
+
ranked: Array<RerankedCandidate<T>>
|
|
59
|
+
/** The winner — the first plausible candidate, or the model's rank-1 when ALL were vetoed. */
|
|
60
|
+
best: RerankedCandidate<T>
|
|
61
|
+
/**
|
|
62
|
+
* True when the winner is NOT the model's rank-1 — i.e. resolution evidence actually changed the answer. This is the
|
|
63
|
+
* metric the arc is judged on (`rank-2-beats-rank-1 rate`); log it, because a rerank that never fires is a rerank
|
|
64
|
+
* that is not earning its resolver calls.
|
|
65
|
+
*/
|
|
66
|
+
changed: boolean
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Resolve a tree. Structural — any `Resolver`-shaped thing satisfies it. */
|
|
70
|
+
export type ResolveTree = (tree: AddressTree) => Promise<AddressTree>
|
|
71
|
+
|
|
72
|
+
export interface RerankOpts {
|
|
73
|
+
/**
|
|
74
|
+
* Resolve at most this many candidates (default 5). Each costs a resolver round-trip, so this is the latency knob.
|
|
75
|
+
* oracle@5 (0.723) captures nearly all the measured headroom of oracle@10 (0.775), so 5 is the default rather than 10
|
|
76
|
+
* — the last 5 candidates cost 2x the resolves for ~5pp of ceiling.
|
|
77
|
+
*/
|
|
78
|
+
maxResolve?: number
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Rerank a k-best parse list on resolution evidence.
|
|
83
|
+
*
|
|
84
|
+
* Resolves up to `maxResolve` candidates IN MODEL ORDER and returns the first whose resolution is plausible. Candidates
|
|
85
|
+
* beyond `maxResolve` are never resolved (and never vetoed — they simply keep their model rank behind the resolved
|
|
86
|
+
* ones).
|
|
87
|
+
*
|
|
88
|
+
* **When every resolved candidate is implausible, the model's rank-1 wins.** A reranker that returns nothing is worse
|
|
89
|
+
* than one that defers: "all my evidence says these are all bad" is not grounds to invent a different answer, only
|
|
90
|
+
* grounds to flag low confidence (the Phase-4b ambiguity gate).
|
|
91
|
+
*/
|
|
92
|
+
export async function rerankByResolution<T>(
|
|
93
|
+
candidates: ReadonlyArray<RerankCandidate<T>>,
|
|
94
|
+
resolveTree: ResolveTree,
|
|
95
|
+
opts: RerankOpts = {}
|
|
96
|
+
): Promise<RerankResult<T>> {
|
|
97
|
+
if (candidates.length === 0) throw new Error("rerankByResolution: candidates must not be empty")
|
|
98
|
+
const maxResolve = Math.max(1, Math.min(opts.maxResolve ?? 5, candidates.length))
|
|
99
|
+
const ranked: Array<RerankedCandidate<T>> = []
|
|
100
|
+
|
|
101
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
102
|
+
const candidate = candidates[i]!
|
|
103
|
+
|
|
104
|
+
if (i >= maxResolve) {
|
|
105
|
+
// Beyond the resolve budget: carried through unresolved, never vetoed.
|
|
106
|
+
ranked.push({ ...candidate, resolved: null, implausible: false })
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
let resolved: AddressTree | null = null
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
resolved = await resolveTree(candidate.tree)
|
|
113
|
+
} catch {
|
|
114
|
+
// A resolver failure is NOT evidence against the parse — treat it as "no evidence" and let
|
|
115
|
+
// the model's rank stand, rather than vetoing a possibly-correct hypothesis on an outage.
|
|
116
|
+
ranked.push({ ...candidate, resolved: null, implausible: false })
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
const verdict = isImplausibleResolution(resolved)
|
|
120
|
+
ranked.push({
|
|
121
|
+
...candidate,
|
|
122
|
+
resolved,
|
|
123
|
+
implausible: verdict.implausible,
|
|
124
|
+
...(verdict.reason ? { reason: verdict.reason } : {}),
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Stable partition: plausible first (model order preserved within each group), vetoed after.
|
|
129
|
+
const plausible = ranked.filter((r) => !r.implausible)
|
|
130
|
+
const vetoed = ranked.filter((r) => r.implausible)
|
|
131
|
+
const finalOrder = [...plausible, ...vetoed]
|
|
132
|
+
const best = finalOrder[0]!
|
|
133
|
+
|
|
134
|
+
return { ranked: finalOrder, best, changed: best !== ranked[0] }
|
|
135
|
+
}
|