@mailwoman/core 8.6.0 → 9.0.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 +2 -2
- package/api/clock.ts +1 -1
- package/api/disk-storage.ts +7 -4
- package/api/test-clocks.ts +57 -9
- package/api/test-transport.ts +182 -0
- package/coarse-placer/coarse-placer.ts +2 -1
- package/coarse-placer/tools/build-outlier-latin.ts +1 -0
- package/coarse-placer/tools/build-outlier-oa.ts +1 -0
- package/coarse-placer/tools/eval-latin-offmap.ts +7 -5
- package/coarse-placer/tools/eval-openset.ts +19 -10
- package/coarse-placer/tools/eval-quant-compare.ts +7 -7
- package/coarse-placer/tools/eval.ts +29 -21
- package/coarse-placer/tools/probe-frontier.ts +8 -4
- package/coarse-placer/tools/quantize.ts +2 -1
- package/coarse-placer/tools/train.ts +9 -8
- package/collections.ts +2 -128
- package/crypto/node.ts +68 -0
- package/env/schema.ts +49 -2
- package/identifiers.ts +48 -0
- package/layers/manifest.ts +2 -1
- package/locale/profiles/en-us.ts +2 -3
- package/locale/profiles/fr-fr.ts +1 -1
- package/locale/profiles/ja-jp.ts +7 -7
- package/objects.ts +40 -8
- package/out/api/clock.d.ts +1 -1
- package/out/api/clock.js +1 -1
- package/out/api/disk-storage.d.ts +1 -1
- package/out/api/disk-storage.d.ts.map +1 -1
- package/out/api/disk-storage.js +5 -5
- package/out/api/disk-storage.js.map +1 -1
- package/out/api/test-clocks.d.ts +2 -2
- package/out/api/test-clocks.d.ts.map +1 -1
- package/out/api/test-clocks.js +51 -9
- package/out/api/test-clocks.js.map +1 -1
- package/out/api/test-transport.d.ts +112 -0
- package/out/api/test-transport.d.ts.map +1 -0
- package/out/api/test-transport.js +84 -0
- package/out/api/test-transport.js.map +1 -0
- package/out/coarse-placer/coarse-placer.d.ts.map +1 -1
- package/out/coarse-placer/coarse-placer.js +2 -1
- package/out/coarse-placer/coarse-placer.js.map +1 -1
- package/out/coarse-placer/tools/build-outlier-latin.d.ts.map +1 -1
- package/out/coarse-placer/tools/build-outlier-latin.js +1 -0
- package/out/coarse-placer/tools/build-outlier-latin.js.map +1 -1
- package/out/coarse-placer/tools/build-outlier-oa.d.ts.map +1 -1
- package/out/coarse-placer/tools/build-outlier-oa.js +1 -0
- package/out/coarse-placer/tools/build-outlier-oa.js.map +1 -1
- package/out/coarse-placer/tools/eval-latin-offmap.d.ts.map +1 -1
- package/out/coarse-placer/tools/eval-latin-offmap.js +4 -5
- package/out/coarse-placer/tools/eval-latin-offmap.js.map +1 -1
- package/out/coarse-placer/tools/eval-openset.d.ts.map +1 -1
- package/out/coarse-placer/tools/eval-openset.js +11 -9
- package/out/coarse-placer/tools/eval-openset.js.map +1 -1
- package/out/coarse-placer/tools/eval-quant-compare.d.ts.map +1 -1
- package/out/coarse-placer/tools/eval-quant-compare.js +6 -7
- package/out/coarse-placer/tools/eval-quant-compare.js.map +1 -1
- package/out/coarse-placer/tools/eval.d.ts.map +1 -1
- package/out/coarse-placer/tools/eval.js +19 -19
- package/out/coarse-placer/tools/eval.js.map +1 -1
- package/out/coarse-placer/tools/probe-frontier.d.ts.map +1 -1
- package/out/coarse-placer/tools/probe-frontier.js +7 -5
- package/out/coarse-placer/tools/probe-frontier.js.map +1 -1
- package/out/coarse-placer/tools/quantize.d.ts.map +1 -1
- package/out/coarse-placer/tools/quantize.js +2 -1
- package/out/coarse-placer/tools/quantize.js.map +1 -1
- package/out/coarse-placer/tools/train.d.ts.map +1 -1
- package/out/coarse-placer/tools/train.js +6 -8
- package/out/coarse-placer/tools/train.js.map +1 -1
- package/out/collections.d.ts +1 -59
- package/out/collections.d.ts.map +1 -1
- package/out/collections.js +2 -90
- package/out/collections.js.map +1 -1
- package/out/crypto/node.d.ts +43 -0
- package/out/crypto/node.d.ts.map +1 -0
- package/out/crypto/node.js +43 -0
- package/out/crypto/node.js.map +1 -0
- package/out/env/index.d.ts +5 -0
- package/out/env/index.d.ts.map +1 -1
- package/out/env/schema.d.ts +6 -1
- package/out/env/schema.d.ts.map +1 -1
- package/out/env/schema.js +46 -2
- package/out/env/schema.js.map +1 -1
- package/out/identifiers.d.ts +23 -0
- package/out/identifiers.d.ts.map +1 -1
- package/out/identifiers.js +39 -0
- package/out/identifiers.js.map +1 -1
- package/out/layers/manifest.d.ts.map +1 -1
- package/out/layers/manifest.js +2 -1
- package/out/layers/manifest.js.map +1 -1
- package/out/locale/profiles/en-us.d.ts +2 -3
- package/out/locale/profiles/en-us.d.ts.map +1 -1
- package/out/locale/profiles/en-us.js +2 -3
- package/out/locale/profiles/en-us.js.map +1 -1
- package/out/locale/profiles/fr-fr.d.ts +1 -1
- package/out/locale/profiles/fr-fr.js +1 -1
- package/out/locale/profiles/ja-jp.d.ts +7 -7
- package/out/locale/profiles/ja-jp.js +7 -7
- package/out/objects.d.ts +18 -2
- package/out/objects.d.ts.map +1 -1
- package/out/objects.js +29 -3
- package/out/objects.js.map +1 -1
- package/out/pipeline/index.d.ts +2 -2
- package/out/pipeline/index.d.ts.map +1 -1
- package/out/pipeline/index.js +1 -1
- package/out/pipeline/index.js.map +1 -1
- package/out/pipeline/runtime-pipeline.d.ts +1 -1
- package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
- package/out/pipeline/runtime-pipeline.js +57 -17
- package/out/pipeline/runtime-pipeline.js.map +1 -1
- package/out/pipeline/span-proposer.d.ts +24 -0
- package/out/pipeline/span-proposer.d.ts.map +1 -1
- package/out/pipeline/span-proposer.js +36 -1
- package/out/pipeline/span-proposer.js.map +1 -1
- package/out/pipeline/types.d.ts +40 -1
- package/out/pipeline/types.d.ts.map +1 -1
- package/out/pipeline/types.js +11 -1
- package/out/pipeline/types.js.map +1 -1
- package/out/resolver/types.d.ts +41 -0
- package/out/resolver/types.d.ts.map +1 -1
- package/out/resolver/types.js.map +1 -1
- package/out/resources/index.d.ts +0 -1
- package/out/resources/index.d.ts.map +1 -1
- package/out/resources/index.js +0 -1
- package/out/resources/index.js.map +1 -1
- package/out/resources/libpostal.d.ts.map +1 -1
- package/out/resources/libpostal.js +3 -4
- package/out/resources/libpostal.js.map +1 -1
- package/out/resources/whosonfirst/index.d.ts +1 -0
- package/out/resources/whosonfirst/index.d.ts.map +1 -1
- package/out/resources/whosonfirst/index.js +1 -0
- package/out/resources/whosonfirst/index.js.map +1 -1
- package/out/resources/whosonfirst/placetypes/Placetype.d.ts.map +1 -1
- package/out/resources/whosonfirst/placetypes/Placetype.js +5 -4
- package/out/resources/whosonfirst/placetypes/Placetype.js.map +1 -1
- package/out/resources/whosonfirst/placetypes/admin.d.ts +12 -3
- package/out/resources/whosonfirst/placetypes/admin.d.ts.map +1 -1
- package/out/resources/whosonfirst/placetypes/admin.js +1 -1
- package/out/resources/whosonfirst/placetypes/admin.js.map +1 -1
- package/out/resources/whosonfirst/sharded-repo.d.ts +28 -0
- package/out/resources/whosonfirst/sharded-repo.d.ts.map +1 -0
- package/out/resources/whosonfirst/sharded-repo.js +58 -0
- package/out/resources/whosonfirst/sharded-repo.js.map +1 -0
- package/out/tools/download-libpostal-resources.d.ts.map +1 -1
- package/out/tools/download-libpostal-resources.js +1 -0
- package/out/tools/download-libpostal-resources.js.map +1 -1
- package/out/tools/generate-language-types.d.ts.map +1 -1
- package/out/tools/generate-language-types.js +5 -11
- package/out/tools/generate-language-types.js.map +1 -1
- package/out/utils/data-root.d.ts +20 -6
- package/out/utils/data-root.d.ts.map +1 -1
- package/out/utils/data-root.js +24 -5
- package/out/utils/data-root.js.map +1 -1
- package/out/utils/hash.d.ts +6 -0
- package/out/utils/hash.d.ts.map +1 -1
- package/out/utils/hash.js +8 -0
- package/out/utils/hash.js.map +1 -1
- package/out/utils/index.d.ts +1 -0
- package/out/utils/index.d.ts.map +1 -1
- package/out/utils/index.js +1 -0
- package/out/utils/index.js.map +1 -1
- package/out/utils/jsonl.d.ts +17 -3
- package/out/utils/jsonl.d.ts.map +1 -1
- package/out/utils/jsonl.js +23 -6
- package/out/utils/jsonl.js.map +1 -1
- package/out/utils/python-json.d.ts +3 -3
- package/out/utils/python-json.js +9 -9
- package/out/utils/python-numeric.d.ts +33 -0
- package/out/utils/python-numeric.d.ts.map +1 -0
- package/out/utils/python-numeric.js +149 -0
- package/out/utils/python-numeric.js.map +1 -0
- package/out/utils/python-random.d.ts +26 -1
- package/out/utils/python-random.d.ts.map +1 -1
- package/out/utils/python-random.js +43 -7
- package/out/utils/python-random.js.map +1 -1
- package/out/utils/repo.d.ts.map +1 -1
- package/out/utils/repo.js +18 -0
- package/out/utils/repo.js.map +1 -1
- package/out/utils/sealed-db.d.ts +12 -0
- package/out/utils/sealed-db.d.ts.map +1 -1
- package/out/utils/sealed-db.js +32 -1
- package/out/utils/sealed-db.js.map +1 -1
- package/package.json +22 -6
- package/pipeline/index.ts +2 -1
- package/pipeline/runtime-pipeline.ts +69 -26
- package/pipeline/span-proposer.ts +64 -1
- package/pipeline/types.ts +43 -1
- package/resolver/types.ts +41 -0
- package/resources/index.ts +0 -1
- package/resources/libpostal.ts +8 -7
- package/resources/whosonfirst/index.ts +1 -0
- package/resources/whosonfirst/placetypes/Placetype.ts +12 -7
- package/resources/whosonfirst/placetypes/admin.ts +12 -2
- package/resources/whosonfirst/sharded-repo.ts +69 -0
- package/tools/download-libpostal-resources.ts +1 -0
- package/tools/generate-language-types.ts +5 -14
- package/utils/data-root.ts +27 -6
- package/utils/hash.ts +9 -0
- package/utils/index.ts +1 -0
- package/utils/jsonl.ts +26 -7
- package/utils/python-json.ts +10 -10
- package/utils/python-numeric.ts +168 -0
- package/utils/python-random.ts +49 -8
- package/utils/repo.ts +18 -0
- package/utils/sealed-db.ts +38 -1
- package/out/resources/collections.d.ts +0 -22
- package/out/resources/collections.d.ts.map +0 -1
- package/out/resources/collections.js +0 -69
- package/out/resources/collections.js.map +0 -1
- package/resources/collections.ts +0 -96
package/README.md
CHANGED
|
@@ -81,8 +81,8 @@ The dictionaries are ~9 MB total and are loaded lazily.
|
|
|
81
81
|
- [`mailwoman`](../mailwoman) — the user-facing CLI + `AddressParser`
|
|
82
82
|
- [`@mailwoman/normalize`](../normalize) — Stage 1 of the pipeline
|
|
83
83
|
- [`@mailwoman/neural`](../neural) — neural classifier (ONNX runtime)
|
|
84
|
-
- [What Mailwoman Is](https://mailwoman.sister.software/
|
|
85
|
-
- [Staged Pipeline Contract](https://
|
|
84
|
+
- [What Mailwoman Is](https://mailwoman.sister.software/docs/developers/get-started/what-mailwoman-is)
|
|
85
|
+
- [Staged Pipeline Contract](https://github.com/sister-software/mailwoman/blob/main/docs/engineering/reference/STAGES.mdx)
|
|
86
86
|
|
|
87
87
|
## License
|
|
88
88
|
|
package/api/clock.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @author Teffen Ellis, et al.
|
|
5
5
|
* @file The injectable time source every timing-sensitive part of {@linkcode APIClient} reads through.
|
|
6
6
|
*
|
|
7
|
-
* Lifted from `filer/sdk/sec-client.ts`
|
|
7
|
+
* Lifted from `filer/sdk/sec-client.ts` when the SEC client's bespoke pacing/retry
|
|
8
8
|
* machinery moved down into `@mailwoman/core/api`. Keeping the seam is the whole reason the pacing
|
|
9
9
|
* and backoff suites are deterministic and finish in milliseconds instead of sleeping on the wall
|
|
10
10
|
* clock — a rate-limit test that actually waits 100ms per grant costs 4s for a 40-call fan-out and
|
package/api/disk-storage.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* @license AGPL-3.0
|
|
4
4
|
* @author Teffen Ellis, et al.
|
|
5
5
|
* @file An on-disk `axios-cache-interceptor` storage adapter, so a client gets a durable HTTP cache by
|
|
6
|
-
* CONFIGURATION rather than by hand-rolling one
|
|
6
|
+
* CONFIGURATION rather than by hand-rolling one.
|
|
7
7
|
*
|
|
8
8
|
* NODE ONLY, and deliberately NOT re-exported from `./index.ts`: `core/api` reaches a browser bundle
|
|
9
9
|
* (`docs`'s `DashboardMap` → `@mailwoman/cartographer` → `tiles/api.ts` → `@mailwoman/core/api`),
|
|
@@ -30,6 +30,7 @@ import { join } from "node:path"
|
|
|
30
30
|
import { type AxiosStorage, buildStorage, type NotEmptyStorageValue, type StorageValue } from "axios-cache-interceptor"
|
|
31
31
|
|
|
32
32
|
import { ConsoleLogger, type IRuntimeLogger } from "../logging/index.ts"
|
|
33
|
+
import { tryParsingJSON } from "../objects.ts"
|
|
33
34
|
import { sha256Hex } from "../utils/hash.ts"
|
|
34
35
|
|
|
35
36
|
/**
|
|
@@ -157,9 +158,9 @@ export function buildDiskStorage(options: DiskStorageOptions): AxiosStorage {
|
|
|
157
158
|
return undefined
|
|
158
159
|
}
|
|
159
160
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
161
|
+
const parsed = tryParsingJSON<StorageValue>(raw)
|
|
162
|
+
|
|
163
|
+
if (parsed === null) {
|
|
163
164
|
// A truncated or hand-edited entry is a miss, not a crash — re-fetching is always safe.
|
|
164
165
|
logger.warn(`Discarding an unreadable cache entry for ${key}.`)
|
|
165
166
|
|
|
@@ -167,6 +168,8 @@ export function buildDiskStorage(options: DiskStorageOptions): AxiosStorage {
|
|
|
167
168
|
|
|
168
169
|
return undefined
|
|
169
170
|
}
|
|
171
|
+
|
|
172
|
+
return parsed
|
|
170
173
|
},
|
|
171
174
|
|
|
172
175
|
set: async (key, value) => {
|
package/api/test-clocks.ts
CHANGED
|
@@ -13,11 +13,36 @@
|
|
|
13
13
|
import type { ClockLike } from "./clock.ts"
|
|
14
14
|
|
|
15
15
|
/**
|
|
16
|
-
* How
|
|
17
|
-
*
|
|
18
|
-
*
|
|
16
|
+
* How much REAL time {@linkcode VirtualClock.runUntilSettled} tolerates with nothing pending before declaring the work
|
|
17
|
+
* stuck. Finite, so a genuinely blocked test reports what happened instead of timing out.
|
|
18
|
+
*
|
|
19
|
+
* This used to be a budget of 1000 idle event-loop TURNS, on the stated assumption that "a real `readFile` resolves in
|
|
20
|
+
* a handful of turns". Turns are not time: an idle turn is a `setImmediate` round-trip costing microseconds, so the
|
|
21
|
+
* whole budget expired in single-digit milliseconds while the I/O it was waiting for took tens. On an unloaded machine
|
|
22
|
+
* the race happened to go the right way. Under load it did not, and the guard fired on WORKING code — observed
|
|
23
|
+
* 2026-08-02 on the lab at load 15.25 and then on a hosted GitHub runner, in `filer/sdk/sec-client.test.ts` and
|
|
24
|
+
* `bdc/sdk/client.test.ts`.
|
|
25
|
+
*
|
|
26
|
+
* Measured with `performance.now()`, NOT `Date.now()`: consumers run under `vi.useFakeTimers({ toFake: ["Date"] })`,
|
|
27
|
+
* which freezes `Date` while leaving `performance` and `setTimeout` real. A Date-based budget would never expire inside
|
|
28
|
+
* those blocks, so genuinely stuck work would hang exactly where this is supposed to report it.
|
|
29
|
+
*/
|
|
30
|
+
const IDLE_BUDGET_MS = 5000
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Idle turns to spin on {@linkcode drainMicrotasks} before backing off to real sleeps.
|
|
34
|
+
*
|
|
35
|
+
* The spin is the fast path — work that is one promise-chain away settles within a few turns and should not pay a
|
|
36
|
+
* timer. Past that the wait is on something real, and continuing to spin actively HARMS it: back-to-back `setImmediate`
|
|
37
|
+
* turns monopolize the event loop and starve the very I/O the loop is waiting for. That feedback loop is why the old
|
|
38
|
+
* guard got worse exactly when the machine was busiest.
|
|
19
39
|
*/
|
|
20
|
-
const
|
|
40
|
+
const IDLE_SPIN_TURNS = 50
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Real backoff between idle polls once {@linkcode IDLE_SPIN_TURNS} is exhausted.
|
|
44
|
+
*/
|
|
45
|
+
const IDLE_BACKOFF_MS = 1
|
|
21
46
|
|
|
22
47
|
/**
|
|
23
48
|
* Run every queued microtask to quiescence. A `setImmediate` is scheduled behind the entire microtask queue, so
|
|
@@ -29,6 +54,16 @@ export function drainMicrotasks(): Promise<void> {
|
|
|
29
54
|
})
|
|
30
55
|
}
|
|
31
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Yield the event loop for `ms` of REAL time. Used only by {@linkcode VirtualClock.runUntilSettled}'s idle backoff, to
|
|
59
|
+
* let pending real I/O actually be serviced instead of competing with a `setImmediate` spin.
|
|
60
|
+
*/
|
|
61
|
+
function realDelay(ms: number): Promise<void> {
|
|
62
|
+
return new Promise<void>((resolve) => {
|
|
63
|
+
setTimeout(resolve, ms)
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
32
67
|
/**
|
|
33
68
|
* A {@linkcode ClockLike} whose `sleep()` bumps `now()` and resolves immediately.
|
|
34
69
|
*/
|
|
@@ -135,8 +170,8 @@ export class VirtualClock implements ClockLike {
|
|
|
135
170
|
* the clock past the deadlines that are registered a moment later, and the test hangs. This polls instead: drain, and
|
|
136
171
|
* if any sleep is pending, advance to the earliest deadline; if none is, yield and look again.
|
|
137
172
|
*
|
|
138
|
-
* Throws rather than hanging when the work neither settles nor schedules anything for {@linkcode
|
|
139
|
-
*
|
|
173
|
+
* Throws rather than hanging when the work neither settles nor schedules anything for {@linkcode IDLE_BUDGET_MS} of
|
|
174
|
+
* REAL time — a diagnosable failure beats a test-timeout stack trace pointing at the `it()`.
|
|
140
175
|
*/
|
|
141
176
|
public async runUntilSettled<T>(work: Promise<T>): Promise<T> {
|
|
142
177
|
let settled = false
|
|
@@ -159,6 +194,7 @@ export class VirtualClock implements ClockLike {
|
|
|
159
194
|
observed.catch(() => undefined)
|
|
160
195
|
|
|
161
196
|
let idleTurns = 0
|
|
197
|
+
let idleSince: number | null = null
|
|
162
198
|
|
|
163
199
|
for (;;) {
|
|
164
200
|
await drainMicrotasks()
|
|
@@ -170,19 +206,31 @@ export class VirtualClock implements ClockLike {
|
|
|
170
206
|
const earliest = this.#earliestPendingDeadline()
|
|
171
207
|
|
|
172
208
|
if (earliest === null) {
|
|
209
|
+
idleSince ??= performance.now()
|
|
210
|
+
|
|
173
211
|
idleTurns++
|
|
174
212
|
|
|
175
|
-
|
|
213
|
+
const idleFor = performance.now() - idleSince
|
|
214
|
+
|
|
215
|
+
if (idleFor > IDLE_BUDGET_MS) {
|
|
176
216
|
throw new Error(
|
|
177
|
-
`VirtualClock.runUntilSettled: no pending sleep and no progress for ${
|
|
178
|
-
`t=${this.#now}. The work is blocked on something this clock does not drive.`
|
|
217
|
+
`VirtualClock.runUntilSettled: no pending sleep and no progress for ${Math.round(idleFor)}ms of ` +
|
|
218
|
+
`real time at t=${this.#now}. The work is blocked on something this clock does not drive.`
|
|
179
219
|
)
|
|
180
220
|
}
|
|
181
221
|
|
|
222
|
+
// Past the spin window the wait is on something real. Back off so it can be serviced —
|
|
223
|
+
// spinning here starves the I/O we are waiting for, which is why the old turn-budgeted
|
|
224
|
+
// guard failed hardest on the busiest machines.
|
|
225
|
+
if (idleTurns > IDLE_SPIN_TURNS) {
|
|
226
|
+
await realDelay(IDLE_BACKOFF_MS)
|
|
227
|
+
}
|
|
228
|
+
|
|
182
229
|
continue
|
|
183
230
|
}
|
|
184
231
|
|
|
185
232
|
idleTurns = 0
|
|
233
|
+
idleSince = null
|
|
186
234
|
|
|
187
235
|
await this.advance(Math.max(earliest - this.#now, 0))
|
|
188
236
|
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file A scripted stub Axios ADAPTER for testing {@linkcode APIClient} subclasses, and the
|
|
6
|
+
* Axios-shaped error builder it rejects with. The sibling of `./test-clocks.ts`: that module makes
|
|
7
|
+
* time deterministic, this one makes the network deterministic, and a pacing test needs both.
|
|
8
|
+
*
|
|
9
|
+
* Extracted from `filer/sdk/sec-client.test.ts` and `bdc/sdk/client.test.ts`, which had grown
|
|
10
|
+
* near-identical copies of it. That is the expected shape of the duplication rather than a
|
|
11
|
+
* surprise: `AGENTS.md` names those two as the worked examples for the `APIClient` migration, so
|
|
12
|
+
* the second client's tests were written from the first's, and every client migrated after them
|
|
13
|
+
* would have copied it again.
|
|
14
|
+
*
|
|
15
|
+
* Everything here is built STRUCTURALLY — `isAxiosError: true` plus `config`/`code`/`response`,
|
|
16
|
+
* and the adapter typed through `APIClientConfig["axios"]` — because the packages under test
|
|
17
|
+
* depend on neither `axios` nor `axios-cache-interceptor`, reaching both only through
|
|
18
|
+
* `@mailwoman/core`. A test file is not a reason to breach that, so this module does not import
|
|
19
|
+
* axios either.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { APIClientConfig } from "./APIClient.ts"
|
|
23
|
+
|
|
24
|
+
const HTTP_OK = 200
|
|
25
|
+
const HTTP_MULTIPLE_CHOICES = 300
|
|
26
|
+
const HTTP_SERVER_ERROR_MIN = 500
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The interesting subset of an Axios request config, as a stub adapter sees it.
|
|
30
|
+
*/
|
|
31
|
+
export interface StubRequestConfig {
|
|
32
|
+
url?: string
|
|
33
|
+
headers?: Record<string, unknown>
|
|
34
|
+
timeout?: number
|
|
35
|
+
/**
|
|
36
|
+
* Set by a binary request path (`"arraybuffer"`). Absent on a JSON client's calls.
|
|
37
|
+
*/
|
|
38
|
+
responseType?: string
|
|
39
|
+
/**
|
|
40
|
+
* The per-request `axios-cache-interceptor` override — `false` is how a caller turns caching off for one call without
|
|
41
|
+
* touching `core/api`.
|
|
42
|
+
*/
|
|
43
|
+
cache?: unknown
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* One scripted adapter outcome.
|
|
48
|
+
*/
|
|
49
|
+
export interface StubOutcome {
|
|
50
|
+
status?: number
|
|
51
|
+
statusText?: string
|
|
52
|
+
/**
|
|
53
|
+
* The RAW body, as the transport would hand it to Axios's `transformResponse`. A string here is what an upstream
|
|
54
|
+
* serving HTML under a 200 actually looks like; a `Buffer` is what Axios's Node adapter produces for `responseType:
|
|
55
|
+
* "arraybuffer"`. Anything else is JSON-serialized the way a JSON endpoint would.
|
|
56
|
+
*/
|
|
57
|
+
body?: unknown
|
|
58
|
+
headers?: Record<string, string>
|
|
59
|
+
/**
|
|
60
|
+
* A transport-level failure — no HTTP response ever arrives. `code` picks the class: `ERR_NETWORK` for a dropped
|
|
61
|
+
* socket, `ECONNABORTED` for this attempt's own timeout firing.
|
|
62
|
+
*/
|
|
63
|
+
throws?: { message: string; code: string }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The Axios overrides an {@linkcode APIClient} accepts, reached through `APIClientConfig` rather than by importing
|
|
68
|
+
* `axios`.
|
|
69
|
+
*/
|
|
70
|
+
export type AxiosOverrides = NonNullable<APIClientConfig["axios"]>
|
|
71
|
+
|
|
72
|
+
export interface StubTransport {
|
|
73
|
+
/**
|
|
74
|
+
* Spread into the client factory as its `axios` override.
|
|
75
|
+
*/
|
|
76
|
+
axios: AxiosOverrides
|
|
77
|
+
/**
|
|
78
|
+
* Every dispatched URL, in order.
|
|
79
|
+
*/
|
|
80
|
+
calls: string[]
|
|
81
|
+
/**
|
|
82
|
+
* Every dispatched request config, in order — headers, timeout, responseType, per-request cache override.
|
|
83
|
+
*/
|
|
84
|
+
configs: StubRequestConfig[]
|
|
85
|
+
/**
|
|
86
|
+
* `clock.now()` at each dispatch, when a clock was supplied. The pacing assertions read this.
|
|
87
|
+
*/
|
|
88
|
+
dispatchTimes: number[]
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface StubTransportOptions {
|
|
92
|
+
/**
|
|
93
|
+
* Records a timestamp into {@linkcode StubTransport.dispatchTimes} on every dispatch. Omit when timing is not under
|
|
94
|
+
* test.
|
|
95
|
+
*/
|
|
96
|
+
clock?: { now(): number }
|
|
97
|
+
/**
|
|
98
|
+
* The body served when an outcome names none. Defaults to `{ ok: true }`; pass the envelope the client under test
|
|
99
|
+
* expects when it validates one (BDC's `{ data: [] }`, say).
|
|
100
|
+
*/
|
|
101
|
+
defaultBody?: unknown
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Build an Axios-shaped rejection without importing `axios`. `isAxiosError(payload)` is `isObject(payload) &&
|
|
106
|
+
* payload.isAxiosError === true`, and everything downstream reads `config`, `code`, and `response` — so this is the
|
|
107
|
+
* full contract that matters.
|
|
108
|
+
*/
|
|
109
|
+
export function axiosLikeError(message: string, code: string, config: StubRequestConfig, response?: unknown): Error {
|
|
110
|
+
const error = new Error(message) as Error & Record<string, unknown>
|
|
111
|
+
|
|
112
|
+
error.isAxiosError = true
|
|
113
|
+
error.code = code
|
|
114
|
+
error.config = config
|
|
115
|
+
|
|
116
|
+
if (response) {
|
|
117
|
+
error.response = response
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return error
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A stub Axios adapter that replays `outcomes` (holding on the last entry once exhausted) and records every dispatch.
|
|
125
|
+
*
|
|
126
|
+
* It reproduces what Axios's real adapters do on a failing status — reject with an Axios-shaped error CARRYING the
|
|
127
|
+
* response — because `validateStatus` is applied by the adapter, not by the interceptor chain. A test that resolves
|
|
128
|
+
* with a 4xx instead would exercise a path the real transport never takes.
|
|
129
|
+
*/
|
|
130
|
+
export function stubTransport(outcomes: StubOutcome[], options: StubTransportOptions = {}): StubTransport {
|
|
131
|
+
const { clock, defaultBody = { ok: true } } = options
|
|
132
|
+
const calls: string[] = []
|
|
133
|
+
const configs: StubRequestConfig[] = []
|
|
134
|
+
const dispatchTimes: number[] = []
|
|
135
|
+
let index = 0
|
|
136
|
+
|
|
137
|
+
const adapter = async (config: StubRequestConfig): Promise<unknown> => {
|
|
138
|
+
calls.push(String(config.url))
|
|
139
|
+
configs.push(config)
|
|
140
|
+
|
|
141
|
+
if (clock) {
|
|
142
|
+
dispatchTimes.push(clock.now())
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const outcome = outcomes[Math.min(index, outcomes.length - 1)]!
|
|
146
|
+
|
|
147
|
+
index++
|
|
148
|
+
|
|
149
|
+
if (outcome.throws) {
|
|
150
|
+
throw axiosLikeError(outcome.throws.message, outcome.throws.code, config)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const status = outcome.status ?? HTTP_OK
|
|
154
|
+
|
|
155
|
+
const response = {
|
|
156
|
+
// Axios's `transformResponse` runs on the RAW body, so hand it exactly what the wire would: a
|
|
157
|
+
// string passes through untouched (that is how an HTML error page under a 200 actually arrives),
|
|
158
|
+
// bytes pass through untouched, and anything else is serialized the way a JSON endpoint would.
|
|
159
|
+
data:
|
|
160
|
+
typeof outcome.body === "string" || Buffer.isBuffer(outcome.body)
|
|
161
|
+
? outcome.body
|
|
162
|
+
: JSON.stringify(outcome.body ?? defaultBody),
|
|
163
|
+
status,
|
|
164
|
+
statusText: outcome.statusText ?? "OK",
|
|
165
|
+
headers: outcome.headers ?? {},
|
|
166
|
+
config,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (status >= HTTP_OK && status < HTTP_MULTIPLE_CHOICES) return response
|
|
170
|
+
|
|
171
|
+
throw axiosLikeError(
|
|
172
|
+
`Request failed with status code ${status}`,
|
|
173
|
+
status >= HTTP_SERVER_ERROR_MIN ? "ERR_BAD_RESPONSE" : "ERR_BAD_REQUEST",
|
|
174
|
+
config,
|
|
175
|
+
response
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Structurally an Axios adapter. The precise `AxiosAdapter` signature isn't nameable here without
|
|
180
|
+
// importing `axios`, which the packages under test deliberately do not depend on.
|
|
181
|
+
return { axios: { adapter } as AxiosOverrides, calls, configs, dispatchTimes }
|
|
182
|
+
}
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import { $public } from "../env/index.ts"
|
|
14
|
+
import { parseJSONStrict } from "../objects.ts"
|
|
14
15
|
import { featurize } from "./featurize.ts"
|
|
15
16
|
|
|
16
17
|
export { COARSE_CLASSES, FEATURE_DIM, featurize } from "./featurize.ts"
|
|
@@ -152,7 +153,7 @@ export class CoarsePlacer {
|
|
|
152
153
|
static async fromArtifactDir(dir: string, opts?: CoarsePlacerOpts): Promise<CoarsePlacer> {
|
|
153
154
|
const { readFile } = await import("node:fs/promises")
|
|
154
155
|
const { join } = await import("node:path")
|
|
155
|
-
const meta =
|
|
156
|
+
const meta = parseJSONStrict<CoarsePlacerMeta>(await readFile(join(dir, "meta.json"), "utf8"))
|
|
156
157
|
const buf = await readFile(join(dir, "weights.bin"))
|
|
157
158
|
// Copy out of the (possibly pooled, possibly mis-aligned) Buffer into a fresh ArrayBuffer so the
|
|
158
159
|
// typed-array view is always validly aligned.
|
|
@@ -151,6 +151,7 @@ export async function buildOutlierLatin(
|
|
|
151
151
|
`SELECT number, street, postcode, postal_city, address_levels FROM read_parquet('${f}') LIMIT ${PER}`
|
|
152
152
|
)
|
|
153
153
|
} catch (error) {
|
|
154
|
+
// oxlint-disable-next-line mailwoman/prefer-spliterator -- An in-memory error message, not a file.
|
|
154
155
|
report?.(` ${cc}: SKIP (${(error as Error).message.split("\n")[0]})`)
|
|
155
156
|
|
|
156
157
|
return []
|
|
@@ -168,6 +168,7 @@ export async function buildOutlierOA(
|
|
|
168
168
|
`SELECT COLUMNS('(?i)^(number|street|city|postcode)$') FROM read_csv_auto('${glob}', union_by_name=true, ignore_errors=true, sample_size=-1) LIMIT ${PER * 8}`
|
|
169
169
|
)
|
|
170
170
|
} catch (error) {
|
|
171
|
+
// oxlint-disable-next-line mailwoman/prefer-spliterator -- An in-memory error message, not a file.
|
|
171
172
|
report?.(` ${cc}: SKIP (${(error as Error).message.split("\n")[0]})`)
|
|
172
173
|
|
|
173
174
|
return []
|
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
import { readFileSync } from "node:fs"
|
|
17
17
|
import * as path from "node:path"
|
|
18
18
|
|
|
19
|
+
import { JSONSpliterator } from "spliterator"
|
|
20
|
+
|
|
21
|
+
import { parseJSONStrict } from "../../objects.ts"
|
|
19
22
|
import { dataRootPath } from "../../utils/data-root.ts"
|
|
20
23
|
import { repoRootPath } from "../../utils/repo.ts"
|
|
21
24
|
import { formatPercent } from "../../utils/stats.ts"
|
|
@@ -67,7 +70,7 @@ export async function evalLatinOffmap(options: EvalLatinOffmapOptions = {}): Pro
|
|
|
67
70
|
const abstain = options.abstain ?? 0.5
|
|
68
71
|
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
69
72
|
|
|
70
|
-
const meta =
|
|
73
|
+
const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(modelDir, "meta.json"), "utf8"))
|
|
71
74
|
const buf = readFileSync(path.join(modelDir, "weights.bin"))
|
|
72
75
|
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
|
|
73
76
|
let weights: Float32Array
|
|
@@ -93,10 +96,9 @@ export async function evalLatinOffmap(options: EvalLatinOffmapOptions = {}): Pro
|
|
|
93
96
|
|
|
94
97
|
const placer = new CoarsePlacer({ ...meta, weights }, { abstainBelow: abstain })
|
|
95
98
|
|
|
96
|
-
const rows
|
|
97
|
-
.
|
|
98
|
-
|
|
99
|
-
.map((l) => JSON.parse(l) as OffMapRow)
|
|
99
|
+
const rows = await Array.fromAsync(
|
|
100
|
+
JSONSpliterator.fromAsync<OffMapRow>(path.join(dataDir, "test-latin-offmap.jsonl"))
|
|
101
|
+
)
|
|
100
102
|
|
|
101
103
|
const handled = (p: CoarsePrediction): boolean => p.abstained || p.country === "OTHER"
|
|
102
104
|
const by: Record<string, { n: number; ok: number }> = {} // key → {n, ok}
|
|
@@ -36,6 +36,9 @@
|
|
|
36
36
|
import { readFileSync, writeFileSync } from "node:fs"
|
|
37
37
|
import * as path from "node:path"
|
|
38
38
|
|
|
39
|
+
import { JSONSpliterator } from "spliterator"
|
|
40
|
+
|
|
41
|
+
import { parseJSONStrict } from "../../objects.ts"
|
|
39
42
|
import { dataRootPath } from "../../utils/data-root.ts"
|
|
40
43
|
import { repoRootPath } from "../../utils/repo.ts"
|
|
41
44
|
import type { CoarsePlacerMeta } from "../coarse-placer.ts"
|
|
@@ -192,8 +195,17 @@ export async function evalOpenSet(
|
|
|
192
195
|
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
193
196
|
const fitPerClass = options.fitPerClass ?? 2000
|
|
194
197
|
|
|
195
|
-
const meta =
|
|
196
|
-
const
|
|
198
|
+
const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(modelDir, "meta.json"), "utf8"))
|
|
199
|
+
const weightBytes = readFileSync(path.join(modelDir, "weights.bin"))
|
|
200
|
+
|
|
201
|
+
// Read through the Buffer's own window: `readFileSync` serves files under 4 KiB out of a shared 8 KiB pool, so
|
|
202
|
+
// `.buffer` alone would start at the pool's origin and run its full length — the wrong floats, and 2048 of them.
|
|
203
|
+
const W = new Float32Array(
|
|
204
|
+
weightBytes.buffer,
|
|
205
|
+
weightBytes.byteOffset,
|
|
206
|
+
weightBytes.byteLength / Float32Array.BYTES_PER_ELEMENT
|
|
207
|
+
)
|
|
208
|
+
|
|
197
209
|
const bias = Float32Array.from(meta.bias)
|
|
198
210
|
const C = meta.classes.length
|
|
199
211
|
const D = meta.featureDim
|
|
@@ -229,17 +241,14 @@ export async function evalOpenSet(
|
|
|
229
241
|
*/
|
|
230
242
|
const inVec = (z: Float64Array): number[] => IN.map((c) => z[c]!)
|
|
231
243
|
|
|
232
|
-
function load(file: string): DataRow[] {
|
|
233
|
-
return
|
|
234
|
-
.trim()
|
|
235
|
-
.split("\n")
|
|
236
|
-
.map((l) => JSON.parse(l) as DataRow)
|
|
244
|
+
function load(file: string): Promise<DataRow[]> {
|
|
245
|
+
return Array.fromAsync(JSONSpliterator.fromAsync<DataRow>(path.join(dataDir, file)))
|
|
237
246
|
}
|
|
238
247
|
|
|
239
248
|
// Fit the Mahalanobis params on IN-MAP TRAIN logits (no test leak): per-class
|
|
240
249
|
// mean in the nIn-dim in-map-logit space + a tied (shared) covariance.
|
|
241
250
|
report?.("fitting Mahalanobis on in-map train logits…")
|
|
242
|
-
const trainRows = load("train.jsonl")
|
|
251
|
+
const trainRows = await load("train.jsonl")
|
|
243
252
|
const byClass = new Map<string, string[]>(COARSE_CLASSES.map((c): [string, string[]] => [c, []]))
|
|
244
253
|
|
|
245
254
|
for (const r of trainRows) {
|
|
@@ -387,8 +396,8 @@ export async function evalOpenSet(
|
|
|
387
396
|
}
|
|
388
397
|
}
|
|
389
398
|
|
|
390
|
-
const inmapTest = load("test.jsonl").filter((r) => r.country !== "OTHER") // the 11 countries only
|
|
391
|
-
const heldout = load("test-latin-offmap.jsonl").filter((r) => r.group === "heldout")
|
|
399
|
+
const inmapTest = (await load("test.jsonl")).filter((r) => r.country !== "OTHER") // the 11 countries only
|
|
400
|
+
const heldout = (await load("test-latin-offmap.jsonl")).filter((r) => r.group === "heldout")
|
|
392
401
|
|
|
393
402
|
const inmapScored = inmapTest.map((r) => scoreRow(r.raw, r.country))
|
|
394
403
|
const heldoutScored = heldout.map((r) => scoreRow(r.raw, undefined))
|
|
@@ -14,6 +14,9 @@
|
|
|
14
14
|
import { readFileSync } from "node:fs"
|
|
15
15
|
import * as path from "node:path"
|
|
16
16
|
|
|
17
|
+
import { JSONSpliterator } from "spliterator"
|
|
18
|
+
|
|
19
|
+
import { parseJSONStrict } from "../../objects.ts"
|
|
17
20
|
import { dataRootPath } from "../../utils/data-root.ts"
|
|
18
21
|
import { repoRootPath } from "../../utils/repo.ts"
|
|
19
22
|
import { CoarsePlacer, type CoarsePlacerMeta } from "../coarse-placer.ts"
|
|
@@ -74,7 +77,7 @@ export async function evalQuantCompare(options: EvalQuantCompareOptions = {}): P
|
|
|
74
77
|
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
75
78
|
|
|
76
79
|
function loadFp32(dir: string): CoarsePlacer {
|
|
77
|
-
const meta =
|
|
80
|
+
const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(dir, "meta.json"), "utf8"))
|
|
78
81
|
const buf = readFileSync(path.join(dir, "weights.bin"))
|
|
79
82
|
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
|
|
80
83
|
const weights = new Float32Array(ab)
|
|
@@ -83,7 +86,7 @@ export async function evalQuantCompare(options: EvalQuantCompareOptions = {}): P
|
|
|
83
86
|
}
|
|
84
87
|
|
|
85
88
|
function loadInt8(dir: string): CoarsePlacer {
|
|
86
|
-
const meta =
|
|
89
|
+
const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(dir, "meta.json"), "utf8"))
|
|
87
90
|
const buf = readFileSync(path.join(dir, "weights.bin"))
|
|
88
91
|
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
|
|
89
92
|
const int8 = new Int8Array(ab)
|
|
@@ -107,12 +110,9 @@ export async function evalQuantCompare(options: EvalQuantCompareOptions = {}): P
|
|
|
107
110
|
const fp32 = loadFp32(fp32Dir)
|
|
108
111
|
const int8 = loadInt8(int8Dir)
|
|
109
112
|
|
|
110
|
-
const test
|
|
111
|
-
.trim()
|
|
112
|
-
.split("\n")
|
|
113
|
-
.map((l) => JSON.parse(l) as TestRow)
|
|
113
|
+
const test = await Array.fromAsync(JSONSpliterator.fromAsync<TestRow>(path.join(dataDir, "test.jsonl")))
|
|
114
114
|
|
|
115
|
-
const classes = (
|
|
115
|
+
const classes = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(fp32Dir, "meta.json"), "utf8")).classes
|
|
116
116
|
let okF = 0
|
|
117
117
|
let okI = 0
|
|
118
118
|
let agree = 0
|
|
@@ -14,6 +14,9 @@
|
|
|
14
14
|
import { readFileSync } from "node:fs"
|
|
15
15
|
import * as path from "node:path"
|
|
16
16
|
|
|
17
|
+
import { JSONSpliterator } from "spliterator"
|
|
18
|
+
|
|
19
|
+
import { parseJSONStrict } from "../../objects.ts"
|
|
17
20
|
import { dataRootPath } from "../../utils/data-root.ts"
|
|
18
21
|
import { repoRootPath } from "../../utils/repo.ts"
|
|
19
22
|
import { CoarsePlacer, type CoarsePlacerMeta, type CoarsePrediction } from "../coarse-placer.ts"
|
|
@@ -80,23 +83,30 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
|
|
|
80
83
|
const abstain = options.abstain ?? 0.5
|
|
81
84
|
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
82
85
|
|
|
83
|
-
const meta =
|
|
84
|
-
const
|
|
86
|
+
const meta = parseJSONStrict<CoarsePlacerMeta>(readFileSync(path.join(modelDir, "meta.json"), "utf8"))
|
|
87
|
+
const weightBytes = readFileSync(path.join(modelDir, "weights.bin"))
|
|
88
|
+
|
|
89
|
+
// Read through the Buffer's own window: `readFileSync` serves files under 4 KiB out of a shared 8 KiB pool, so
|
|
90
|
+
// `.buffer` alone would start at the pool's origin and run its full length — the wrong floats, and 2048 of them.
|
|
91
|
+
const weights = new Float32Array(
|
|
92
|
+
weightBytes.buffer,
|
|
93
|
+
weightBytes.byteOffset,
|
|
94
|
+
weightBytes.byteLength / Float32Array.BYTES_PER_ELEMENT
|
|
95
|
+
)
|
|
96
|
+
|
|
85
97
|
const placer = new CoarsePlacer({ ...meta, weights }, { abstainBelow: abstain })
|
|
86
98
|
|
|
87
99
|
// --- In-distribution test: accuracy + per-class + ECE ---
|
|
88
|
-
|
|
89
|
-
.trim()
|
|
90
|
-
.split("\n")
|
|
91
|
-
.map((l) => JSON.parse(l) as TestRow)
|
|
92
|
-
|
|
100
|
+
let testN = 0
|
|
93
101
|
let correct = 0
|
|
94
102
|
const perClass: Record<string, { n: number; ok: number }> = {} // country → {n, ok}
|
|
95
103
|
const confusion: Record<string, Record<string, number>> = {} // true → {pred → n}
|
|
96
104
|
const buckets = Array.from({ length: 10 }, () => ({ n: 0, ok: 0 }))
|
|
97
105
|
|
|
98
|
-
// ECE deciles
|
|
99
|
-
for (const r of test) {
|
|
106
|
+
// ECE deciles. The split streams: every figure below is an accumulator, so the rows never all need to be resident.
|
|
107
|
+
for await (const r of JSONSpliterator.fromAsync<TestRow>(path.join(dataDir, "test.jsonl"))) {
|
|
108
|
+
testN++
|
|
109
|
+
|
|
100
110
|
const p = placer.predict(r.raw)
|
|
101
111
|
|
|
102
112
|
const pred = p.country ?? "(abstain)"
|
|
@@ -119,8 +129,8 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
|
|
|
119
129
|
}
|
|
120
130
|
}
|
|
121
131
|
|
|
122
|
-
console.log(`coarse-placer eval — test n=${
|
|
123
|
-
console.log(` overall accuracy: ${((100 * correct) /
|
|
132
|
+
console.log(`coarse-placer eval — test n=${testN}`)
|
|
133
|
+
console.log(` overall accuracy: ${((100 * correct) / testN).toFixed(2)}% (abstain threshold ${abstain})`)
|
|
124
134
|
console.log(` per-class recall:`)
|
|
125
135
|
|
|
126
136
|
for (const c of meta.classes) {
|
|
@@ -132,7 +142,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
|
|
|
132
142
|
}
|
|
133
143
|
|
|
134
144
|
let ece = 0
|
|
135
|
-
const N =
|
|
145
|
+
const N = testN
|
|
136
146
|
|
|
137
147
|
for (let i = 0; i < 10; i++) {
|
|
138
148
|
const bk = buckets[i]!
|
|
@@ -165,24 +175,22 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
|
|
|
165
175
|
const msPath = repoRootPath("data", "eval", "multi-script", "v0.5.0-a0.jsonl")
|
|
166
176
|
|
|
167
177
|
try {
|
|
168
|
-
const ms: MultiScriptRow[] = readFileSync(msPath, "utf8")
|
|
169
|
-
.trim()
|
|
170
|
-
.split("\n")
|
|
171
|
-
.map((l) => JSON.parse(l) as MultiScriptRow)
|
|
172
|
-
|
|
173
178
|
const TRAINED_SCRIPTS = new Set(["latin", "cjk"]) // the only scripts among the 11 trained countries
|
|
174
179
|
// With the OTHER class, an off-map input is HANDLED if it routes to OTHER or abstains — either way
|
|
175
180
|
// it's not a confident mis-placement onto a wrong country.
|
|
176
181
|
const handled = (p: CoarsePrediction): boolean => p.abstained || p.country === "OTHER"
|
|
177
182
|
|
|
178
|
-
let
|
|
183
|
+
let msN = 0,
|
|
184
|
+
offN = 0,
|
|
179
185
|
offOk = 0,
|
|
180
186
|
missN = 0,
|
|
181
187
|
missOk = 0
|
|
182
188
|
|
|
183
189
|
const offMiss: string[] = []
|
|
184
190
|
|
|
185
|
-
for (const r of
|
|
191
|
+
for await (const r of JSONSpliterator.fromAsync<MultiScriptRow>(msPath)) {
|
|
192
|
+
msN++
|
|
193
|
+
|
|
186
194
|
const p = placer.predict(r.raw)
|
|
187
195
|
const offMap = !TRAINED_SCRIPTS.has(r.script)
|
|
188
196
|
|
|
@@ -205,7 +213,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
|
|
|
205
213
|
}
|
|
206
214
|
}
|
|
207
215
|
|
|
208
|
-
console.log(`\nmulti-script off-map handling (n=${
|
|
216
|
+
console.log(`\nmulti-script off-map handling (n=${msN}):`)
|
|
209
217
|
console.log(
|
|
210
218
|
` OFF-map scripts (Cyrillic/Arabic/Thai/…) routed to OTHER-or-abstain: ${offOk}/${offN} (${((100 * offOk) / Math.max(1, offN)).toFixed(0)}%) ← want HIGH`
|
|
211
219
|
)
|
|
@@ -221,5 +229,5 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
|
|
|
221
229
|
console.log(`\n(multi-script set not found at ${msPath}: ${(error as Error).message})`)
|
|
222
230
|
}
|
|
223
231
|
|
|
224
|
-
return { n:
|
|
232
|
+
return { n: testN, accuracy: (100 * correct) / testN, ece }
|
|
225
233
|
}
|