Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
84a291c
settings: the URL check's docstring names an ASCII scheme, judged aft…
wshallwshall Dec 1, 2026
4c62e43
docs: CONFIGURATION.md's backup and DR path rows state the URL check'…
wshallwshall Dec 1, 2026
7578fe5
tests: pin the anchor check's refusal of a PEM block with no data, in…
wshallwshall Dec 1, 2026
a7a5379
dr_backup: the config walk adds each file from a handle opened throug…
wshallwshall Dec 1, 2026
12fa88b
docs: the include_config row says what a link swap still reaches in t…
wshallwshall Dec 1, 2026
96cd0fe
dr_backup: a config file the walk accepted fails or is added by name …
wshallwshall Dec 1, 2026
1608d20
docs: the include_config row states one rule for a config file the wa…
wshallwshall Dec 1, 2026
5066161
dr_backup: a config file whose Windows final path cannot be read is a…
wshallwshall Dec 1, 2026
a375420
dr_backup: the config walk's reader closes a descriptor once, and the…
wshallwshall Dec 1, 2026
1eebfa0
docs: the include_config row says a file whose final path Windows can…
wshallwshall Dec 1, 2026
3469af8
dr_backup: a read or write that fails on a config file's handle names…
wshallwshall Dec 1, 2026
a9dbd4d
docs: the include_config row places the ancestor residual by platform…
wshallwshall Dec 1, 2026
df7a6a7
dr_backup: the config walk re-checks held folders after the open (BAC…
wshallwshall Dec 1, 2026
58fd4ff
docs: the include_config row names the re-check and its residuals (BA…
wshallwshall Dec 1, 2026
bc63960
dr_backup: a root hold the volume does not support asks the volume (B…
wshallwshall Dec 2, 2026
16a28c0
docs: the include_config row names the root hold and each remedy (BAC…
wshallwshall Dec 2, 2026
d83236b
dr_backup: a name swapped for a folder before the open by name is pas…
wshallwshall Dec 2, 2026
214ff76
docs: the include_config row says the three codes are a reading, not …
wshallwshall Dec 2, 2026
6f7b00c
dr_backup: the open by name passes over a descriptor that reached a f…
wshallwshall Dec 2, 2026
d3c8ff3
file: the confined open's docstring gives its re-check residuals as a…
wshallwshall Dec 2, 2026
34d775c
dr_backup: a final path a volume with no drive letter cannot give nam…
wshallwshall Dec 2, 2026
a4b7ed7
dr_backup: a root hold the volume refuses names the config dir, after…
wshallwshall Dec 2, 2026
dd9f38e
dr_backup: a config refusal puts its cause and remedy before the name…
wshallwshall Dec 2, 2026
b2d7103
docs: the include_config row names the order of each refusal's text (…
wshallwshall Dec 2, 2026
89b3861
dr_backup: repair round 1 on the config refusals (BACKLOG #6573)
wshallwshall Dec 2, 2026
7ec73d8
docs: the include_config row gives the final-path remedy as a conditi…
wshallwshall Dec 2, 2026
0fc8356
dr_backup: repair round 2 on the config refusals (BACKLOG #6573)
wshallwshall Dec 2, 2026
8ac775b
docs: the include_config row screens a name only after a hold refused…
wshallwshall Dec 2, 2026
da0571f
tests: the length test builds Windows' own text where mypy can see th…
wshallwshall Dec 2, 2026
f58c78a
store: every backend refuses reference keys some backend cannot hold …
wshallwshall Dec 1, 2026
20b3e3d
docs: reference-set key rules on every backend, and the SetState surr…
wshallwshall Dec 1, 2026
64e91a9
reference keys: review round 1 fixes, preview and rename keep the rul…
wshallwshall Dec 1, 2026
f0a7edf
docs: reference-set key rules after review round 1 (BACKLOG #6613)
wshallwshall Dec 1, 2026
77fa5a3
reference keys: review round 2 fixes (BACKLOG #6613)
wshallwshall Dec 1, 2026
20a74d0
docs: reference-set key rules after review round 2 (BACKLOG #6613)
wshallwshall Dec 1, 2026
a95af89
Rename the NUL-key test's store file off a Windows reserved device na…
wshallwshall Dec 2, 2026
746bb5c
Name the Windows release that opens NUL.<ext> as the device (BACKLOG …
wshallwshall Dec 2, 2026
487a8c6
Merge branch 'main' into b20053-6573e
wshallwshall Dec 2, 2026
696839a
Config backup: an unreachable share at the first screen fails the bac…
wshallwshall Dec 2, 2026
de6f637
Config backup: the held-dir remedy is a sharing violation's only, giv…
wshallwshall Dec 2, 2026
91580d2
Config backup docs: a stat failure on an unreachable share is no long…
wshallwshall Dec 2, 2026
3e75f94
docs: include_config row names the two unreachable codes and the unre…
wshallwshall Dec 2, 2026
edb52ab
Merge commit '3e75f941363152edc378c2983c19eb5173dd5aa0' into repair-3…
wshallwshall Dec 2, 2026
8a2967d
Merge remote-tracking branch 'origin/main' into repair-3541-m1
wshallwshall Dec 2, 2026
2280c03
Reference key refusals name the remedy, and any CipherError names a f…
wshallwshall Dec 3, 2026
fc69c72
Reference key remedies keep lookups working, and the state cache docs…
wshallwshall Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/6613-setstate-entry-correction.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- **Correction to the 0.5.3 entry on `SetState` key refusals.** It said each refusal names the
field and its length. Each names the field and the rule, never the value; only a refusal for
length also gives the length in UTF-16 code units. (`BACKLOG #6613`)
17 changes: 17 additions & 0 deletions changelog.d/6613.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
- **Every store backend refuses a reference snapshot holding two keys that differ only by trailing
spaces, or a key holding NUL or a surrogate; a set name ending in a space or holding NUL or a
surrogate is refused at load and at rename.** These rules still accept a lone key with a trailing
space and an over-long key; SQL Server's key and name widths stay its own check. SQLite and
Postgres now refuse, before the snapshot's transaction, two keys that differ only by trailing
spaces, as SQL Server already did, and every backend refuses a key holding U+0000 (NUL), which
Postgres text cannot store, or a surrogate code point, which no backend stores. Each of
these key refusals is a `ReferenceSnapshotRefused` (the collision is its subclass
`ReferenceKeyCollision`), naming the set, the keys by 0-based ordinal and the remedy, never a key, and logged whole; the last-good
snapshot stays active and the sync fails every interval until the source changes. A dry run and
`check` skip such a file-backed set with a warning naming the same set, rule and ordinals. A
`Reference(...)` name that ends in a space or holds U+0000 or a surrogate is refused at load on
every backend, and so is a rename to such a name, since SQL Server compares `npi` and `npi ` as
one name. A SQL Server open now also reports a non-binary collation on the `reference` and
`reference_version` key columns, at WARNING, and repairs nothing.
`SetState`'s refusal of a surrogate code point now says so rather than "lone surrogate", since
half of a pair is refused too, and `StateKeyError` is exported from `messagefoundry`. (`BACKLOG #6613`)
27 changes: 24 additions & 3 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -708,19 +708,21 @@ def anonymize(msg):
is an **upsert by `(namespace, key)`** the engine applies **inside the routed→outbound handoff
transaction**. `Send`-only Handlers are unchanged — fully **backward compatible**.
- **Keys are exact, and bounded.** `namespace` and `key` must be non-empty strings that do not end
in a space (U+0020) and contain no NUL (U+0000) and no lone surrogate (U+D800 to U+DFFF). Each is
in a space (U+0020) and contain no NUL (U+0000) and no surrogate code point (U+D800 to U+DFFF),
whether lone or half of a pair held as two code points. Each is
at most 256 UTF-16 code units, and the two together at most 450. `SetState(...)` raises
`StateKeyError` (a `WiringError`) at construction otherwise, on every store backend, and the error
names the field, never its value. Why: SQL Server ignores trailing spaces when it compares keys,
so `k` and `k ` would otherwise be one stored row there and two everywhere else; Postgres text
cannot hold NUL; no backend stores a lone surrogate; and SQL Server's `state` columns are
cannot hold NUL; no backend stores a surrogate code point; and SQL Server's `state` columns are
`NVARCHAR(256)` under a clustered primary key capped at 900 bytes. A field read from a fixed-width
sender can carry padding: strip it before keying on it, for example
`(msg["PID-3.1"] or "").rstrip(" ")`. Case and accents are compared exactly on SQLite, on
Postgres, and on a SQL Server database whose `state` table this release or a later one created. A
SQL Server `state` table created earlier keeps the database's default collation, which may fold
case (BACKLOG #1588); the engine logs a WARNING at every open of a table whose key columns are not
binary, naming the collation and the remedy, and repairs nothing (BACKLOG #4917).
binary, naming the collation and the remedy, and repairs nothing (BACKLOG #4917). The
warning itself does not stop the open.
- **Exactly-once / re-run safety.** Because the write commits in the **same transaction** as the
outbound rows, a crash before commit leaves **no** state (atomic with the handoff) and the attempt
that commits applies the write **exactly once per message** — this preserves the staged pipeline's
Expand Down Expand Up @@ -811,6 +813,25 @@ crash-re-run — the same accepted caveat as a code-set hot-reload).
seconds, default `30`, `0` = no limit) bounds each call, the execute and each fetch, and a result
that does not fit its columns, at least a missing or doubled column, a NULL key or a duplicate key, fails the sync rather than replacing the last-good snapshot; see
[`CONNECTIONS.md`](CONNECTIONS.md) §*A `DatabaseRef` statement passes the same gate, and a row ceiling*.
- **Keys and set names are exact.** Every store backend refuses a snapshot holding two keys that
differ only by trailing spaces (U+0020), which SQL Server compares as equal, a key holding NUL
(U+0000), which Postgres text cannot store, or a key holding a surrogate code point (U+D800 to
U+DFFF), which no backend stores, before the snapshot's transaction (BACKLOG #4917, #6613). The
sync then fails and alerts every interval until the source changes, and the last-good snapshot
stays active. The log line names the set and the keys by 0-based ordinal, their position among
the keys the source yielded, never a key; an ordinal is not a file line number. The line also
names the remedy, at the source: for two keys that differ only by trailing spaces, remove one of
the two and strip the spaces from the one kept; for NUL or a lone surrogate, strip it or remove
that key; for a surrogate pair, write it as its one character or remove that key. Keep only one of
any two keys that leaves equal. A lone key with a trailing space is not refused. A dry run and
`messagefoundry check` skip such a file-backed set, with a warning naming the same
set, rule and ordinals, since the next sync refuses it; an engine that synced the set before keeps serving its last-good snapshot meanwhile. A
`Reference(...)` name that ends in a space or holds NUL or a surrogate code point is refused at
load, on every backend, and so is a rename to such a name. SQL Server compares `npi` and `npi `
as one name, so a set renamed from one to the other across a reload would share the old set's
stored rows there. SQL Server also bounds a key at 450 UTF-16 code units and a set name at 256,
and reports a non-binary collation on the `reference` and `reference_version` key columns at
open, at WARNING, repairing nothing.
- **Sync.** The engine's `ReferenceSyncRunner` materializes each set once at startup (before listeners
serve, so `reference(...)` resolves on the first message) and every `refresh_seconds`. A source
failure is **isolated**: it's logged + alerted and the **last-good snapshot is kept** (the write
Expand Down
7 changes: 7 additions & 0 deletions docs/adr/0006-external-data-lookups.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,13 @@ first-ever reference-row key-rotation tests on all three backends.
Server `write_reference_snapshot` now refuses such a snapshot before its transaction with
`ReferenceKeyCollision`, naming the two keys by ordinal only. The sync still fails and alerts
every interval, and the last-good snapshot stays active, as it did when the INSERT failed.
**AMENDED 2026-12-01 (BACKLOG #6613):** the refusal moved to
`store/reference_keys.py`, which SQLite and Postgres call too, so a set breaking that rule
fails the same way on every backend; the column widths above stay SQL Server's own. It also
refuses a key holding U+0000, which Postgres text cannot store, or a surrogate code point, which
no backend stores, as a `ReferenceSnapshotRefused`, the collision's base class. A set name that
ends in a space or holds either is refused at load. A SQL Server open warns, repairing nothing,
when the `reference` or `reference_version` key columns are not binary.
- **Encryption at rest.** Values are `cipher.encrypt(json.dumps(v))` (`mfenc`), covered by **both**
`reencrypt_to_active` (key rotation) **and** `_encrypt_existing_rows` (the no-key→key migration
pass). The migration pass is required because "born encrypted" is false: under a no-key deployment
Expand Down
3 changes: 3 additions & 0 deletions messagefoundry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
SetState,
Sftp,
Soap,
StateKeyError,
Tcp,
Timer,
code_set,
Expand Down Expand Up @@ -185,6 +186,7 @@
"Send": "messagefoundry.config.wiring",
"SetMeta": "messagefoundry.config.wiring",
"SetState": "messagefoundry.config.wiring",
"StateKeyError": "messagefoundry.config.wiring",
"Sftp": "messagefoundry.config.wiring",
"Soap": "messagefoundry.config.wiring",
"Tcp": "messagefoundry.config.wiring",
Expand Down Expand Up @@ -263,6 +265,7 @@ def __dir__() -> list[str]:
"split_by_obr",
"Send",
"SetState",
"StateKeyError",
"SetMeta",
"state_get",
"response_get",
Expand Down
6 changes: 6 additions & 0 deletions messagefoundry/config/impact.py
Original file line number Diff line number Diff line change
Expand Up @@ -3334,6 +3334,12 @@ def _validate_new_name(config_dir: Path, target_kind: str, new: str) -> None:
f"the new name {new!r} is not a valid connection name: it must match "
f"{CONNECTION_NAME_PATTERN}"
)
# A renamed reference set must still load: Registry.add_reference refuses a set name ending in a
# space (BACKLOG #6613). U+0000 is a control character, refused above.
if target_kind == "reference" and new.endswith(" "):
raise WiringError(
f"the new name {new!r} is not a valid set name: it must not end with a space"
)
if target_kind in _FILE_BACKED_KINDS:
# Reuse the exact traversal/drive/containment rules the codeset writer enforces on a file stem.
from messagefoundry.config.code_sets import CODESETS_DIR_NAME
Expand Down
41 changes: 34 additions & 7 deletions messagefoundry/config/wiring.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,11 @@ def handle(msg):
is_connection_name,
reference_record_name,
)
from messagefoundry.controlchars import scrub_control_chars, scrub_log_argument
from messagefoundry.controlchars import (
has_lone_surrogate,
scrub_control_chars,
scrub_log_argument,
)
from messagefoundry.credential import QUALIFIED_CERT_NAME, unmatchable_san_reason
from messagefoundry.exception_origin import (
exception_chain,
Expand Down Expand Up @@ -6029,8 +6033,9 @@ def __post_init__(self) -> None:
if "\x00" in text:
raise StateKeyError(f"SetState {name} must not contain U+0000 (NUL)")
# NVARCHAR counts UTF-16 code units. ASCII is one unit per char, so the usual MRN-style
# key skips the encode. A strict encode refuses a lone surrogate (U+D800..U+DFFF): no
# backend stores one, and the backend's bind would raise it inside the handoff, a
# key skips the encode. A strict encode refuses any surrogate code point (U+D800..U+DFFF),
# a lone one or half of a pair held as two code points: no backend stores either, and
# the backend's bind would raise it inside the handoff, a
# store error the runner retries rather than a content fault it dead-letters. A key
# already over the limit in code points is refused unencoded: each is at least a unit,
# so a huge content-derived key costs no copy.
Expand All @@ -6040,16 +6045,17 @@ def __post_init__(self) -> None:
elif len(text) > STATE_KEY_MAX_UNITS:
field_units, at_least = len(text), "at least "
else:
lone_surrogate = False
surrogate = False
try:
field_units = len(text.encode("utf-16-le")) // 2
except UnicodeEncodeError:
# Raised outside the handler: the encode error's `.object` is the whole key, so
# it must not ride the chain as __context__ (nor would `from None` stop that).
lone_surrogate = True
if lone_surrogate:
surrogate = True
if surrogate:
raise StateKeyError(
f"SetState {name} must not contain a lone surrogate (U+D800..U+DFFF)"
f"SetState {name} must not contain a surrogate code point (U+D800..U+DFFF);"
" write a character beyond U+FFFF as one code point"
)
if field_units > STATE_KEY_MAX_UNITS:
raise StateKeyError(
Expand Down Expand Up @@ -7620,6 +7626,27 @@ def add_handler(self, name: str, fn: HandlerFn, accepts: HandlerAccepts | None =
self.handler_accepts[name] = accepts

def add_reference(self, spec: ReferenceSpec) -> None:
# BACKLOG #6613: SQL Server pads a trailing space when it compares a set name (the `state`
# comment in store/sqlserver.py's _SCHEMA says why), so a set renamed from `npi` to `npi `
# across a reload would share the old set's stored rows there, where SQLite and Postgres
# keep them apart. This refusal comes first, so case_twins' trailing-space fold no longer
# sees a reference set name. Postgres text cannot hold U+0000, and no backend stores a
# surrogate code point. Refused on every backend, as SetState refuses such a key. A name
# that is not a string is left to graph_problems, as before.
if isinstance(spec.name, str):
if spec.name.endswith(" "):
raise WiringError(
f"reference set {spec.name!r}: a set name must not end with a space"
)
if "\x00" in spec.name:
raise WiringError(
f"reference set {spec.name!r}: a set name must not contain U+0000 (NUL)"
)
if has_lone_surrogate(spec.name):
raise WiringError(
f"reference set {spec.name!r}: a set name must not contain a surrogate code"
" point (U+D800..U+DFFF)"
)
self._add(self.references, spec.name, spec, "reference set")

def add_lookup(self, spec: DatabaseLookupSpec) -> None:
Expand Down
23 changes: 20 additions & 3 deletions messagefoundry/pipeline/dryrun.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@
from messagefoundry.pipeline.sandbox import SandboxMode, SandboxSession, run_sandboxed
from messagefoundry.store import MessageStatus
from messagefoundry.store.metadata import encode_reference_value
from messagefoundry.store.reference_keys import (
ReferenceSnapshotRefused,
refuse_unstorable_reference_keys,
)

__all__ = [
"DeliveryPreview",
Expand Down Expand Up @@ -680,6 +684,8 @@ def transform_one(
#: The ``(set name, file path)`` pairs whose skip :func:`dry_run_reference_view` has already logged
#: in this process; the path too, so another config's set of the same name still logs. A test resets it.
_skipped_reference_sets_logged: set[tuple[str, str]] = set()
#: The same, for a set whose keys every store backend refuses (BACKLOG #6613).
_refused_reference_sets_logged: set[tuple[str, str]] = set()


class _PreviewReferenceSet(Mapping[str, Any]):
Expand Down Expand Up @@ -715,8 +721,9 @@ def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]:
engine's reference cache returns (BACKLOG #1174): a TOML date is an ISO string in both. Each
read decodes its own copy, as the engine's does (:class:`_PreviewReferenceSet`). A
set the store would refuse to encode is omitted, as the live sync would refuse to commit it. So is
a set whose file did not load (vault BACKLOG #3340); both log a warning naming it, the second once
per set per process.
a set whose keys break a rule every store backend refuses (BACKLOG #6613), and a set whose file
did not load (vault BACKLOG #3340). Each logs a warning naming it; the last two log once per set
per process.

Every call reads every file again. A caller previewing many messages against one graph, as
``check`` does, builds the view once and passes it to :func:`dry_run` as ``reference_view``
Expand All @@ -729,9 +736,19 @@ def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]:
if not isinstance(path, str): # an env() ref — unresolved in a pure dry-run
continue
try:
rows = load_code_set(path)
refuse_unstorable_reference_keys(spec.name, rows)
view[spec.name] = _PreviewReferenceSet(
{k: encode_reference_value(v) for k, v in load_code_set(path).items()}
{k: encode_reference_value(v) for k, v in rows.items()}
)
except ReferenceSnapshotRefused as exc:
# BACKLOG #6613: every backend's write refuses this set, so the live sync never commits
# this content. Its text names the set, the rule and key ordinals, never a key, as the
# sync logs it. Once per set per process, as for a file that did not load below.
if (spec.name, path) not in _refused_reference_sets_logged:
_refused_reference_sets_logged.add((spec.name, path))
log.warning("dry-run: reference set skipped: %s", exc)
continue
except CodeSetError:
# A missing, malformed or unreadable file. Say so, or a later read of the set reports it
# missing with nothing to say why. The set name only, never the loader's text: that can
Expand Down
17 changes: 9 additions & 8 deletions messagefoundry/pipeline/reference_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
from messagefoundry.store import Store
from messagefoundry.store.base import (
DEFAULT_STORE_ACQUIRE_TIMEOUT,
ReferenceKeyCollision,
ReferenceSnapshotRefused,
acquire_pooled,
)
from messagefoundry.transports.base import NegativeAckError, count_setting, float_setting
Expand Down Expand Up @@ -121,14 +121,14 @@ class ReferenceColumnMismatch(ReferenceSyncError):
column name twice.

The message holds the set's name and which check failed, never a column's name, so
``_sync_one`` logs it whole, as it does ``ReferenceKeyCollision``."""
``_sync_one`` logs it whole, as it does ``ReferenceSnapshotRefused``."""


class ReferenceKeyRefused(ReferenceSyncError):
"""A ``DatabaseRef`` statement returned a NULL key, or two rows with one key.

The message holds the set's name and row ordinals, never a key, so ``_sync_one`` logs it
whole, as it does ``ReferenceKeyCollision``."""
whole, as it does ``ReferenceSnapshotRefused``."""


#: The SQLSTATE a statement that ran past its ODBC query timeout fails with.
Expand Down Expand Up @@ -904,7 +904,7 @@ async def _sync_one(self, spec: ReferenceSpec, *, generation: int | None = None)
abandoned=self._abandoned_calls,
)
except (ReferenceColumnMismatch, ReferenceKeyRefused) as exc:
# Logged whole, as ReferenceKeyCollision is below: the text holds the set's name and,
# Logged whole, as ReferenceSnapshotRefused is below: the text holds the set's name and,
# by refusal, the column setting, or the row ordinals, never a column name or a key.
log.error("%s (not synced)", exc)
raise
Expand All @@ -930,10 +930,11 @@ async def _sync_one(self, spec: ReferenceSpec, *, generation: int | None = None)
await self._store.write_reference_snapshot(
name=spec.name, version=version, rows=rows
)
except ReferenceKeyCollision as exc:
# BACKLOG #4917: sync_all logs only the class. This text holds the set's name and
# two ordinals, never a key, so it is logged whole: the ordinals find the rows in
# the source.
except ReferenceSnapshotRefused as exc:
# BACKLOG #4917, #6613: sync_all logs only the class. This text holds the set's
# name, the rule and key ordinals, never a key, so it is logged whole. An ordinal
# is the key's 0-based position among the keys the source yielded, in its order,
# not a file line number.
log.error("%s (not synced)", exc)
raise
# Only after the store returned, so a refused write claims nothing.
Expand Down
Loading
Loading