hub v0.118.0: the household's e-mails follow the household's language (R-558 Part A)
gates / gates (push) Successful in 23s

The hub has written every customer e-mail in Hungarian whatever the box was set
to. The box has published its language since controller v0.247.0; nothing read
it. Now it does.

Nothing an operator reads changes. The Hungarian mails are byte-identical, and
that is a diff rather than a reading: 56 goldens per language captured from
v0.117.0 BEFORE any string moved, and all 56 Hungarian ones pass unchanged after
every sentence was routed through the new bundle.

- internal/i18n: flat bundle, 79 keys, hu authoritative + hu fallback, ceiling 0.
- customerMessages/severityLabels are DERIVED from the bundle, so a sentence is
  written in one place and all 40+ tests that read those maps still work.
- Language order: last reported -> created-with -> hu. reports.language defaults
  to EMPTY, never hu: "never told us" is not "chose Hungarian".
- message_customer on POST /api/v1/event, additive and optional forever, for the
  sentences the box composes and the hub cannot translate.
- The bind page is per-language, and its `expired` state stays Hungarian: it is
  the state an unknown token lands in, so rendering a real English customer's
  token in English would make the LANGUAGE answer what the TEXT refuses to.

Two defects found inside the release:
- R-581: the newest report was picked by received_at, which has SECOND
  granularity, so same-second reports tied and the winner was arbitrary. Ordered
  by the autoincrement id now. GetCustomers() still has the shape - row open.
- R-582: the English copy-guard stems, ported word for word from Hungarian,
  convicted 141 honest sentences. The English claim is a phrase with a modal.

R-555 closed: the language allowlist entry is out of wire_contract_gate.py.
hub_copy_gate.py follows the sentences into the bundle - without that it would
have scanned four files that no longer hold any customer text and reported
success. Three new decoys incl. an innocent control.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
adminandClaude Opus 5 committed 2026-09-18 16:20:11 +02:00
1 parent 20aafc3dec
commit 9167cf53af
150 files changed
+4063 -410

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
package store
import (
"io"
"log"
"path/filepath"
"testing"
)
func langStore(t *testing.T) *Store {
t.Helper()
s, err := New(filepath.Join(t.TempDir(), "lang.db"), log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
return s
}
func saveCfg(t *testing.T, s *Store, id, lang string) {
t.Helper()
if err := s.SaveCustomerConfig(&CustomerConfig{
CustomerID: id, CustomerName: id, Domain: "x.example",
RetrievalPassword: "p", APIKey: "k-" + id, ConfigJSON: "{}", Language: lang,
}); err != nil {
t.Fatal(err)
}
}
// S2 — the language order IS the design: last reported → created-with → Hungarian.
//
// Each step is checked on its own AND in combination, because the interesting failure is not "the
// wrong default" but "the reported one is ignored" — a household that switches their dashboard to
// English and keeps getting Hungarian mail would look exactly like the feature not shipping at all.
func TestCustomerLanguageOrder(t *testing.T) {
s := langStore(t)
// 3. Neither: Hungarian.
if got := s.CustomerLanguage("nobody"); got != "hu" {
t.Errorf("an unknown customer = %q, want hu", got)
}
// 2. Created-with, no report yet — the window the claim mail and the bind page live in.
saveCfg(t, s, "c-en", "en")
saveCfg(t, s, "c-hu", "hu")
if got := s.CustomerLanguage("c-en"); got != "en" {
t.Errorf("created-with-en, no report = %q, want en", got)
}
if got := s.CustomerLanguage("c-hu"); got != "hu" {
t.Errorf("created-with-hu, no report = %q, want hu", got)
}
// 1. Reported WINS over created-with, in both directions. The household outranks the operator.
if err := s.SaveReport("c-en", []byte(`{"controller_version":"0.256.0","language":"hu"}`)); err != nil {
t.Fatal(err)
}
if got := s.CustomerLanguage("c-en"); got != "hu" {
t.Errorf("created en but reported hu = %q, want hu — the household's choice lost", got)
}
if err := s.SaveReport("c-hu", []byte(`{"controller_version":"0.256.0","language":"en"}`)); err != nil {
t.Fatal(err)
}
if got := s.CustomerLanguage("c-hu"); got != "en" {
t.Errorf("created hu but reported en = %q, want en — the household's choice lost", got)
}
}
// A box that reports NOTHING (a controller older than 0.247.0) must not erase the creation-time
// language. This is the live case: three boxes in the fleet report no language at all.
func TestOldControllerReportDoesNotOverrideTheCreationLanguage(t *testing.T) {
s := langStore(t)
saveCfg(t, s, "old", "en")
if err := s.SaveReport("old", []byte(`{"controller_version":"0.245.0"}`)); err != nil {
t.Fatal(err)
}
if got := s.CustomerLanguage("old"); got != "en" {
t.Errorf("a report with no language = %q, want en — the creation default was erased", got)
}
}
// Garbage on the wire is stored as "never told us", NOT as Hungarian. Storing it as Hungarian would
// make a later real choice indistinguishable from the absence of one.
func TestGarbageReportedLanguageIsNotStoredAsHungarian(t *testing.T) {
s := langStore(t)
saveCfg(t, s, "g", "en")
for _, bad := range []string{`"de"`, `"EN-gb"`, `""`, `"; DROP TABLE reports"`} {
if err := s.SaveReport("g", []byte(`{"language":`+bad+`}`)); err != nil {
t.Fatal(err)
}
if got := s.CustomerLanguage("g"); got != "en" {
t.Errorf("reported %s = %q, want en (the creation default, because the report said nothing usable)", bad, got)
}
}
// ...and a REAL one still lands.
if err := s.SaveReport("g", []byte(`{"language":"hu"}`)); err != nil {
t.Fatal(err)
}
if got := s.CustomerLanguage("g"); got != "hu" {
t.Errorf("a real reported language after garbage = %q, want hu", got)
}
}
// The NEWEST report wins, not the first or an arbitrary one.
func TestNewestReportedLanguageWins(t *testing.T) {
s := langStore(t)
saveCfg(t, s, "n", "hu")
for _, lang := range []string{"hu", "en", "hu", "en"} {
if err := s.SaveReport("n", []byte(`{"language":"`+lang+`"}`)); err != nil {
t.Fatal(err)
}
}
if got := s.CustomerLanguage("n"); got != "en" {
t.Errorf("after hu,en,hu,en the language is %q, want en (the newest)", got)
}
}
// A creation-time language that is not a real language stores as Hungarian rather than as itself:
// the form is operator-driven, and an unsupported value must never reach a mail renderer.
func TestCreationLanguageIsValidated(t *testing.T) {
s := langStore(t)
saveCfg(t, s, "bad", "klingon")
cfg, err := s.GetCustomerConfig("bad")
if err != nil {
t.Fatal(err)
}
if cfg.Language != "hu" {
t.Errorf("an unsupported creation language stored as %q, want hu", cfg.Language)
}
}
// The language survives a round trip through the config record — the value configgen writes into
// controller.yaml comes from here.
func TestCustomerConfigLanguageRoundTrips(t *testing.T) {
s := langStore(t)
saveCfg(t, s, "rt", "en")
cfg, err := s.GetCustomerConfig("rt")
if err != nil {
t.Fatal(err)
}
if cfg.Language != "en" {
t.Errorf("GetCustomerConfig language = %q, want en", cfg.Language)
}
list, err := s.ListCustomerConfigs()
if err != nil {
t.Fatal(err)
}
for _, c := range list {
if c.CustomerID == "rt" && c.Language != "en" {
t.Errorf("ListCustomerConfigs language = %q, want en", c.Language)
}
}
}
+116 -13
View File
@@ -12,6 +12,8 @@ import (
"gitea.dooplex.hu/admin/felhom-hub/internal/semver"
_ "modernc.org/sqlite"
"gitea.dooplex.hu/admin/felhom-hub/internal/i18n"
)
// Store handles SQLite persistence for customer reports.
@@ -183,6 +185,29 @@ func (s *Store) migrate() error {
// at 1, so an already-running box records that as its baseline on its next report without restarting.
s.db.Exec("ALTER TABLE customer_configs ADD COLUMN config_version INTEGER NOT NULL DEFAULT 1")
// v0.118.0 (R-558, localisation slice 3): the language the hub writes this household's e-mails in.
//
// TWO COLUMNS BECAUSE THERE ARE TWO FACTS, and collapsing them would lose one:
//
// - customer_configs.language is what the OPERATOR chose when creating the customer. It is a
// DEFAULT — it seeds the box and it is what the claim mail and the bind page use, because
// both happen before any box has ever reported. Default 'hu': every existing customer is
// Hungarian, which is what they are today.
// - reports.language is what the BOX last reported, i.e. what the HOUSEHOLD actually chose on
// their own dashboard. It wins, because the household outranks the operator's default.
// Default '' — empty means "this box has never told us", which is NOT the same as "Hungarian"
// and must not be stored as it (a box on a controller older than 0.247.0 sends no language at
// all, and pretending it chose Hungarian would make a later real choice indistinguishable
// from the absence of one).
//
// ROLLBACK: none needed, and none is possible cleanly — SQLite drops columns only from 3.35 and
// the data is worth keeping anyway. Rolling BACK the hub image is the whole rollback: v0.117.0
// and earlier neither write nor read either column, and both carry a DEFAULT, so every INSERT
// those versions perform still succeeds. Verified by running the previous image against a
// migrated DB before the sync.
s.db.Exec("ALTER TABLE reports ADD COLUMN language TEXT NOT NULL DEFAULT ''")
s.db.Exec("ALTER TABLE customer_configs ADD COLUMN language TEXT NOT NULL DEFAULT 'hu'")
// v0.51.0 (DR-tier-by-default): per-customer DR-tier flag. NEW customers default ON (the
// create handler sets it); the column default 0 is the LEGACY initialization — an existing
// customer is only flipped ON by the one-time backfill (initialize from reality: its host
@@ -943,7 +968,11 @@ func (s *Store) SaveReport(customerID string, reportJSON []byte) error {
var parsed struct {
ControllerVersion string `json:"controller_version"`
ControllerURL string `json:"controller_url"`
System struct {
// Language (controller v0.247.0) — the household's dashboard choice. Denormalised out of
// report_json so the mail path is one indexed read, not a JSON parse per send. An old
// controller omits it and it stores as "" — "never told us", not "Hungarian".
Language string `json:"language"`
System struct {
CPUPercent float64 `json:"cpu_percent"`
MemoryPercent float64 `json:"memory_percent"`
} `json:"system"`
@@ -971,17 +1000,71 @@ func (s *Store) SaveReport(customerID string, reportJSON []byte) error {
_, err := s.db.Exec(`
INSERT INTO reports (customer_id, report_json, health_status, cpu_percent,
memory_percent, container_total, container_running,
backup_last_snapshot, controller_version, controller_url)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
backup_last_snapshot, controller_version, controller_url, language)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
customerID, string(reportJSON),
parsed.Health.Status, parsed.System.CPUPercent,
parsed.System.MemoryPercent, parsed.Containers.Total,
parsed.Containers.Running, backupSnapshot,
parsed.ControllerVersion, parsed.ControllerURL,
parsed.ControllerVersion, parsed.ControllerURL, reportedLanguage(parsed.Language),
)
return err
}
// reportedLanguage keeps only a language the hub can actually write a mail in.
//
// It does NOT normalise to Hungarian: i18n.Normalize maps everything unknown to "hu", which is right
// at RENDER time and wrong at STORAGE time. Storing "hu" for a box that reported garbage — or
// reported nothing — would erase the difference between "this household chose Hungarian" and "we
// have never been told", and the second is what the creation-time default exists to answer.
func reportedLanguage(raw string) string {
l := strings.ToLower(strings.TrimSpace(raw))
if i18n.IsSupported(l) {
return l
}
return ""
}
// CustomerLanguage answers "which language do we write to this household in?".
//
// THE ORDER IS THE DESIGN (R-558): last reported → created-with → Hungarian.
//
// 1. What the BOX last reported is what the HOUSEHOLD chose on their own dashboard. It outranks
// everything: the operator's creation-time pick is a default, never an override.
// 2. The creation-time language covers the window before a box has ever reported — which is exactly
// when the claim mail and the bind page are sent, so it is not an edge case.
// 3. Hungarian, for every customer that predates all of this.
//
// A quiet-box alarm deliberately uses (1) even though the box is silent: the last thing it said is
// still the best thing known about the household, and a box being down is no reason to switch a
// family's language.
func (s *Store) CustomerLanguage(customerID string) string {
// ORDER BY id, NOT BY received_at. `received_at` is `datetime('now')` — SECOND granularity — so
// two reports that arrive in the same second TIE, and the winner among ties is whatever SQLite
// feels like returning. A box that reports every few seconds during a settle, or two reports
// racing at a restart, would then resolve to an ARBITRARY one of them, and a household that had
// just switched language would get the old language back at random.
//
// `id` is INTEGER PRIMARY KEY AUTOINCREMENT: strictly increasing, never reused, and it is the
// real insertion order. Caught by TestNewestReportedLanguageWins, which failed on the
// received_at version — the same second-granularity trap the dispatcher already carries a note
// about for its recovery pairing.
var reported string
err := s.db.QueryRow(`SELECT language FROM reports WHERE customer_id = ?
ORDER BY id DESC LIMIT 1`, customerID).Scan(&reported)
if err == nil && i18n.IsSupported(reported) {
return reported
}
var created string
err = s.db.QueryRow(`SELECT language FROM customer_configs WHERE customer_id = ?`,
customerID).Scan(&created)
if err == nil && i18n.IsSupported(created) {
return created
}
return i18n.Default
}
// reportOffsitePresence is the minimal parse for "does this controller report show an offsite tier
// that is actually CONFIGURED on the box" — the R-70 delivery-state signal, i.e. applied-on-the-box.
//
@@ -1345,7 +1428,13 @@ type CustomerConfig struct {
// rows were initialized from reality by the one-time backfill (enabled descriptor → ON).
// OFF = zero Felhom-side cost (no ep0 namespace is provisioned) and offsite provisioning is
// refused (the escrow ceremony depends on the PBS key — drill F-6, closed by policy).
DRTier bool
DRTier bool
// Language (v0.118.0, R-558) is the language this customer was CREATED with — the operator's
// pick on the create form, "hu" or "en". It is a DEFAULT, never an override: it seeds the box
// (configgen writes it as `customer.language`) and it is what the claim mail and the public bind
// page use, because both happen before any box has ever reported. The moment the household picks
// a language on their own dashboard, the reported one wins. See Store.CustomerLanguage.
Language string
CreatedAt time.Time
UpdatedAt time.Time
}
@@ -1359,8 +1448,8 @@ type CustomerConfig struct {
func (s *Store) SaveCustomerConfig(cfg *CustomerConfig) error {
_, err := s.db.Exec(`
INSERT INTO customer_configs (customer_id, customer_name, domain, email,
retrieval_password, api_key, config_json, min_controller_version, dr_tier, config_version, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, datetime('now'))
retrieval_password, api_key, config_json, min_controller_version, dr_tier, language, config_version, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, datetime('now'))
ON CONFLICT(customer_id) DO UPDATE SET
customer_name = excluded.customer_name,
domain = excluded.domain,
@@ -1370,26 +1459,40 @@ func (s *Store) SaveCustomerConfig(cfg *CustomerConfig) error {
config_json = excluded.config_json,
min_controller_version = excluded.min_controller_version,
dr_tier = excluded.dr_tier,
language = excluded.language,
config_version = customer_configs.config_version + 1,
updated_at = datetime('now')`,
cfg.CustomerID, cfg.CustomerName, cfg.Domain, cfg.Email,
cfg.RetrievalPassword, cfg.APIKey, cfg.ConfigJSON, cfg.MinControllerVersion, cfg.DRTier,
createdLanguage(cfg.Language),
)
return err
}
// createdLanguage keeps only a language the hub can write mail in, defaulting to Hungarian.
//
// Unlike reportedLanguage this one DOES default: an absent creation-time pick is genuinely
// "Hungarian", because that is what every customer created before v0.118.0 is and what the form
// offers first. The distinction the two functions draw is the point — see reportedLanguage.
func createdLanguage(raw string) string {
if i18n.IsSupported(raw) {
return raw
}
return i18n.Default
}
// GetCustomerConfig returns a customer configuration by ID, or nil if not found.
func (s *Store) GetCustomerConfig(customerID string) (*CustomerConfig, error) {
var cfg CustomerConfig
var createdAt, updatedAt string
err := s.db.QueryRow(`
SELECT customer_id, customer_name, domain, email,
retrieval_password, api_key, config_json, status, min_controller_version, dr_tier, config_version, created_at, updated_at
retrieval_password, api_key, config_json, status, min_controller_version, dr_tier, language, config_version, created_at, updated_at
FROM customer_configs WHERE customer_id = ?`,
customerID,
).Scan(&cfg.CustomerID, &cfg.CustomerName, &cfg.Domain, &cfg.Email,
&cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, &cfg.MinControllerVersion,
&cfg.DRTier, &cfg.ConfigVersion, &createdAt, &updatedAt)
&cfg.DRTier, &cfg.Language, &cfg.ConfigVersion, &createdAt, &updatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
@@ -1541,7 +1644,7 @@ func (s *Store) SetOneTimeSecretTimesForTest(customerID, createdAt, consumedAt s
func (s *Store) ListCustomerConfigs() ([]CustomerConfig, error) {
rows, err := s.db.Query(`
SELECT customer_id, customer_name, domain, email,
retrieval_password, api_key, config_json, status, min_controller_version, dr_tier, config_version, created_at, updated_at
retrieval_password, api_key, config_json, status, min_controller_version, dr_tier, language, config_version, created_at, updated_at
FROM customer_configs ORDER BY customer_id`)
if err != nil {
return nil, err
@@ -1554,7 +1657,7 @@ func (s *Store) ListCustomerConfigs() ([]CustomerConfig, error) {
var createdAt, updatedAt string
if err := rows.Scan(&cfg.CustomerID, &cfg.CustomerName, &cfg.Domain, &cfg.Email,
&cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, &cfg.MinControllerVersion,
&cfg.DRTier, &cfg.ConfigVersion, &createdAt, &updatedAt); err != nil {
&cfg.DRTier, &cfg.Language, &cfg.ConfigVersion, &createdAt, &updatedAt); err != nil {
return nil, err
}
cfg.CreatedAt = parseSQLiteTime(createdAt)
@@ -1605,12 +1708,12 @@ func (s *Store) GetCustomerConfigByAPIKey(apiKey string) (*CustomerConfig, error
var createdAt, updatedAt string
err := s.db.QueryRow(`
SELECT customer_id, customer_name, domain, email,
retrieval_password, api_key, config_json, status, min_controller_version, dr_tier, config_version, created_at, updated_at
retrieval_password, api_key, config_json, status, min_controller_version, dr_tier, language, config_version, created_at, updated_at
FROM customer_configs WHERE api_key = ?`,
apiKey,
).Scan(&cfg.CustomerID, &cfg.CustomerName, &cfg.Domain, &cfg.Email,
&cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, &cfg.MinControllerVersion,
&cfg.DRTier, &cfg.ConfigVersion, &createdAt, &updatedAt)
&cfg.DRTier, &cfg.Language, &cfg.ConfigVersion, &createdAt, &updatedAt)
if err == sql.ErrNoRows {
return nil, nil
}