@mailwoman/resolver 7.2.0 → 7.3.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.
@@ -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
+ }