Files
solon/scripts/places-queue.ts
CatoandClaude Opus 5.5 266a4d5b68 perf: the World Bank fetched from a runner; statistics in one query; imports and deploys skip what did not change (#576)
* perf(places): place pages kept for an hour; the run log indexed and bounded; a place's country by its ISO code

- A place's country (its profile, budget, photograph and share card) is its
  own ISO 3166-1 code, else its pack's root, else a world nation's slug, never
  the last slug segment: the Djibouti Region (world/djibouti/djibouti), the
  City of San Marino and the US state of Georgia showed a country's page.
- /places/[...slug] is ISR for an hour with nothing built ahead, instead of
  force-dynamic: its queries run about once an hour per place and language.
- place_import_runs gets indexes on (source_key, started_at) and (status,
  finished_at); sourceRuns is one DISTINCT ON query, read once per call and
  passed to the worker.
- Runs a stopped process left `running` are closed as failed after two worker
  budgets, so they are reported once and backed off.
- The worker starts on a day with nothing due as well, for the daily rebuild
  of the ancestors view.
- verify runs places:world-countries --check, now comparing the countries the
  file holds rather than CLDR's names; geography:world writes its registry as
  Prettier formats it. The engineering audit's claim that both were checked is
  corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* feat(places): a source a publisher refuses to the box is fetched daily from a runner

The World Bank's API answers the box HTTP 403 (2026-11-10), and its source is
the only one for eight statistics in about 210 countries: none had ever loaded
in production, and the box's queue failed it and alerted every cycle.

- A source may say `fetchFrom: "runner"`. The box's worker leaves it out of
  its queue; `pnpm run places:queue --from runner` drains it, with the same
  cadence, retries and run log.
- places-load-cloud.yml runs that daily (and on dispatch with kind=queue),
  through its SSH tunnel to the production database, copying the snapshots
  back to the box as it already did for hand-dispatched loads.
- The World Bank's source is the one runner source; a test fails if another
  side gets it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* refactor(statistics): a governance indicator is five lines; shared scopes and sentence()

- statistic-templates.ts holds sentence() (moved from the budgets' metrics),
  the scope of general government at every level and the scope of a
  perception score, and wgiMetric({ key, code, name }).
- The six Worldwide Governance Indicators are written with wgiMetric: 204
  lines become 66, and the generated metrics were checked identical to the
  hand-written ones, word for word in every language.
- Government consumption and tax revenue share one scope sentence instead of
  two copies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(statistics): every statistic in one query; a new statistic adds no queries

- loadSeriesFor(db, config, keys, locale, { latestOnly }) reads any number of
  metrics in one facts query and names their places once. latestOnly keeps
  each place's latest value within the metric's plausible band, as a chart's
  screening leaves it.
- /statistics: 4 queries instead of 136 (34 statistics x loadSeries +
  placeLabels); 104-131 ms instead of 325-548 ms on a database holding the
  live OECD, Eurostat and World Bank figures. Checked identical to the old
  per-metric query for all 34 statistics (2,403 series), and latest-only
  identical to the screened full series.
- The dimension, event, compare and saved-view pages load their metrics in
  one call each.
- placeLabels groups names and codes once instead of filtering every row per
  place, and builds one Intl.DisplayNames for the list.
- facts gets a partial index on (metric_key, jurisdiction_id, valid_from DESC)
  for current, unvaried figures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(ci): a deploy that touched no Places data clones, installs and reads nothing

places-data.yml ran after every deploy: a full clone and pnpm install on the
memory-tight box, a runner install, and 798 image requests through the live
site, though most deploys change no Places data and no photograph.

- A first job diffs the deployed commit against the one this workflow last
  loaded successfully (a failed load is retried by the next deploy; a
  dispatch, perhaps a dry run, does not count). The import runs when Places
  data, its config, adapters or importer changed; the photo warm-up when
  photos.json or the photo code changed. A dispatch runs both.
- The box fetches the deployed commit at depth 1 instead of cloning the
  repository's history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(places): an old /places/<slug> link is redirected after a two-query lookup

It ran the full place-page load (about 17 queries) only to learn whether the
world pack holds the place. Links no longer point there (#572); the redirect
stays for old ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(law): a register import reads only its own register, and stops when nothing changed

About 34 register imports run every week. Each made one query per law
authority (311, one after another) and read every current act, title, number
and page in the law database, however small its register; and
missingFromSource counted every act sharing the identity scheme, so it was
wrong for every publisher_ref register.

- A retrieval whose acts, as read, are those the register last applied is
  recorded as applied and `unchanged` and goes no further. The recorded
  importer version carries a hash of the rows read, so the same bytes read by
  a changed reader are applied again.
- The authorities the retrieval names are resolved to places in one query.
- Known acts are read for the identities the retrieval lists, a thousand at
  a time, with their titles, numbers and pages for those acts only.
- missingFromSource counts only the identities this register itself stated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* fix(law): the weekly sync waits for a heavy load; verify reads a sample, a second apart

- law-sync.yml took /tmp/solon-law-load.lock while a heavy load dispatched by
  hand (law-text.yml) takes /tmp/solon-law-load-heavy.lock, so the two never
  excluded each other, the pairing that ran the box out of memory on
  2026-11-08. The sync now takes the heavy lock, and after two hours' wait
  leaves that week's sync be, saying so.
- `law:text verify` read its sample size from --limit, which the workflow
  passes every source (1,500 by default): a dispatch read 1,500 publisher
  pages back to back. It reads --sample (30 by default) and pauses a second
  between reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* fix(law): an act held in two languages is listed once, titled in the reader's language

recentChanges joined every current title to every current version, so an act
held in German and French appeared up to four times in a place's recent
changes (with repeated React keys), and a constitution's title on the
profile card came out in whichever language the database returned first.

- actTitleSql (src/lib/law/act-title.ts): an act's current title in the
  reader's language, else its first other language, as one value.
- recentChanges takes the reader's language and keeps one row an act, its
  latest current version; the profile's constitution lookup uses the same
  title rule.
- An integration test holds one act in two languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* refactor(generators): one polite Wikidata client; scratch scripts removed

world-profiles, places-photos and law-plan each carried their own SPARQL
helper: world-profiles retried any error four times (a 400 included), law-plan
did not retry at all, and each sent its own user agent. They use the shared
client (src/lib/wikidata/query.ts), which waits as long as the server asks on
a 429 or 503 and fails at once on anything else. law-plan now checks that
Constitute's index answered before reading it. scripts/_ws.ts and _ws2.ts,
committed scratch files, are deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* refactor(statistics): one rule a unit, so a statistic in a new unit is a line in units.ts

What a unit means was decided in six places: the chart scale (present.ts),
the label (shared.ts), the brief's value text and points (brief.ts), the
profile figure's format (place-figures.tsx), the axis panel's percent sign
and the divisor a published percentage is stored with (sources.ts). A
statistic in a count or a currency would have been shown with no unit, or
scaled wrong, in some of them.

src/lib/config/places/units.ts holds, per unit, its scale and decimals,
whether publishers print it in per cent, whether it is a percentage, and the
key of its words under Statistics.units; every site reads it. A test fails
when a unit's words are missing in a language. Nothing shown changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(law): a place's page counts its own authorities' acts, not the whole register's

loadPlaceLaw ran loadLawCoverage, three aggregates over every act and version
in the law database, to show the counts of a handful of authorities: the
place's chain and the parts of its nearest. loadLawCoverage takes an optional
list of authorities and counts only theirs; a place's page passes the ones it
shows. Checked against a database of 9,119 acts in 14 authorities: the counts
of all 132 shown authorities are the same as before. The pages that show the
whole register still count it all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* fix: findings of an adversarial review of this stack

- Place pages are rendered on every visit again: ISR made Next keep every
  rendered URL on the server's disk (a few thousand places in five languages,
  and any made-up path besides, with no bound), and kept a not-found path as
  not found for an hour. A view's cost is cut where it is spent instead.
- A failed source retried by a once-a-day queue (the runner's) waited a full
  24 hours from the failed run's start, so the next day's run, starting a few
  minutes earlier, missed it: retries allow two hours' slack.
- Abandoned runs are closed after eight hours, longer than any import runs
  from the box or a runner (a workflow job stops at six), instead of after
  two worker budgets.
- One concurrency group for every cloud load, so the daily queue and a fetch
  dispatched by hand never write the same source at once.
- The saved-axis page scores, as the index does, on each place's latest
  plausible value; loadSeriesFor dedupes its keys.
- places-data runs the import weekly whatever changed, for a file applied
  while some of its places were not held (`+partial`) or one whose import
  failed.
- An unchanged register import still reports what the register no longer
  lists.
- The shared Wikidata client retries 500, 502 and 504 too, as world-profiles
  did; a bad query still fails at once.
- The weekly law sync waits 45 minutes for the heavy lock, not two hours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 09:11:31 +01:00

73 lines
2.4 KiB
TypeScript

/**
* Drains the import queue for one side (design §8.3): every source of that
* side the run log says is behind, until the queue is empty or the time is
* up. The box's hourly worker does this inside the app for `fetchFrom: box`
* sources; a GitHub runner runs this daily for `fetchFrom: runner` sources,
* publishers that refuse the box's address, writing to the production
* database through a tunnel (.github/workflows/places-load-cloud.yml). The
* run log is the same record whichever side fetched.
*
* pnpm run places:queue --from runner [--minutes 25] [--plan]
*
* --plan prints the sources behind and stops. Exit 1 when a source failed.
*/
import { execFileSync } from "node:child_process";
import { placesConfig } from "@/lib/config/places";
import { db } from "@/lib/db/client";
import { drainQueue, pendingSources, type QueueSide } from "@/lib/places/importer/queue";
import { defaultSnapshotStore } from "@/lib/places/importer/snapshots";
const args = process.argv.slice(2);
const value = (flag: string) => {
const at = args.indexOf(flag);
return at >= 0 ? args[at + 1] : undefined;
};
const side = value("--from");
const minutes = Number(value("--minutes") ?? 25);
function gitSha(): string | null {
try {
return execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
} catch {
return process.env.GIT_SHA ?? null;
}
}
async function main(): Promise<number> {
if (side !== "box" && side !== "runner") {
console.error("usage: pnpm run places:queue --from runner|box [--minutes 25] [--plan]");
return 2;
}
if (args.includes("--plan")) {
const pending = await pendingSources(
db,
placesConfig,
new Date(),
undefined,
side as QueueSide,
);
console.log(pending.map((s) => s.key).join("\n") || "(nothing behind)");
return 0;
}
const report = await drainQueue(db, {
config: placesConfig,
snapshots: defaultSnapshotStore(),
gitSha: gitSha(),
budgetMs: minutes * 60_000,
side: side as QueueSide,
// The box's worker rebuilds the ancestors view daily; a runner's imports rebuild it when
// they move a place.
dailyRefresh: false,
});
console.log(JSON.stringify(report, null, 2));
return report.ran.some((r) => r.status === "failed") ? 1 : 0;
}
main().then(
(code) => process.exit(code),
(error: unknown) => {
console.error(error);
process.exit(2);
},
);