From 310bcd5ed2969bf0efbeba916a5c1e8c4cde73ef Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:03:52 +0000 Subject: [PATCH] id-core: per-namespace configured bare-string shorthand (Refs #10261) Slice A9119-shorthand-policy, design A-9119.1 (S4.29-S4.33). Adds array_shorthand.rs: a ShorthandPolicy {default_slot, prefix_fill: Null, text_encoding: Utf8} expands a bare string to default_slot null slots then its UTF-8 bytes. Policies are set per namespace and overridden per server; a server override wins only on its own server, an unset policy is missing_shorthand_policy with no fallback index, and content-core namespaces refuse shorthand. Tests compare generated configuration operations against a reference model. Co-Authored-By: Claude Opus 5.5 --- pkgs/id/crates/id-core/src/array_shorthand.rs | 231 ++++++++++++ .../crates/id-core/tests/array_shorthand.rs | 334 ++++++++++++++++++ 2 files changed, 565 insertions(+) create mode 100644 pkgs/id/crates/id-core/src/array_shorthand.rs create mode 100644 pkgs/id/crates/id-core/tests/array_shorthand.rs diff --git a/pkgs/id/crates/id-core/src/array_shorthand.rs b/pkgs/id/crates/id-core/src/array_shorthand.rs new file mode 100644 index 0000000000..ec67fa7017 --- /dev/null +++ b/pkgs/id/crates/id-core/src/array_shorthand.rs @@ -0,0 +1,231 @@ +//! Per-namespace configured bare-string shorthand for array addresses. +//! +//! Slice A9119-shorthand-policy (issue #10261), design +//! `part-a-addressing/versioned-design.md` A-9119.1, statements +//! S4.29–S4.33. +//! +//! A bare UTF-8 string such as `name` is shorthand for an array address. +//! How it expands is configuration, never a constant: +//! +//! ```text +//! { default_slot: index, prefix_fill: null, text_encoding: UTF8 } +//! ``` +//! +//! With `default_slot = 2` the string `name` expands to +//! `[null, null, utf8("name")]`, but 2 is only an example: nothing here +//! knows a default index. A policy is set per namespace and may be +//! overridden per server; the server override wins only where one is +//! configured. With neither, expansion fails as +//! `missing_shorthand_policy` and never falls back to any index. +//! +//! Shorthand only names array addresses, so a namespace bound to the +//! content core refuses it as `shorthand_requires_array_core`. + +use std::collections::BTreeMap; +use std::fmt; + +use crate::array_address::ArrayAddress; +use crate::namespace_definition::{CoreKind, NamespaceDefinition, NamespaceId, RegistryId}; + +/// What fills the slots before the default slot. The design admits only +/// null. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum PrefixFill { + /// Every earlier slot is a null slot. + Null, +} + +/// How the bare string becomes slot bytes. The design admits only +/// UTF-8. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum TextEncoding { + /// The string's own UTF-8 bytes, unchanged. + Utf8, +} + +/// One namespace's shorthand configuration. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ShorthandPolicy { + default_slot: usize, + prefix_fill: PrefixFill, + text_encoding: TextEncoding, +} + +impl ShorthandPolicy { + /// A policy placing the string at `default_slot`, with null prefix + /// fill and UTF-8 text, the only fill and encoding V2 admits. + pub const fn new(default_slot: usize) -> Self { + Self { + default_slot, + prefix_fill: PrefixFill::Null, + text_encoding: TextEncoding::Utf8, + } + } + + /// The zero-based slot the string goes in. + pub const fn default_slot(self) -> usize { + self.default_slot + } + + /// What fills the earlier slots. + pub const fn prefix_fill(self) -> PrefixFill { + self.prefix_fill + } + + /// How the string becomes bytes. + pub const fn text_encoding(self) -> TextEncoding { + self.text_encoding + } + + /// Expand `text` under this policy: `default_slot` prefix slots, then + /// the encoded string. The result has exactly `default_slot + 1` + /// slots. A policy whose slot cannot be allocated fails as + /// `expansion_too_large` rather than aborting; there is no fixed + /// maximum index. + pub fn expand(self, text: &str) -> Result { + let len = self + .default_slot + .checked_add(1) + .ok_or(ShorthandError::ExpansionTooLarge)?; + let mut slots: Vec>> = Vec::new(); + slots + .try_reserve_exact(len) + .map_err(|_reserve| ShorthandError::ExpansionTooLarge)?; + let fill = match self.prefix_fill { + PrefixFill::Null => None, + }; + slots.resize(self.default_slot, fill); + let bytes = match self.text_encoding { + TextEncoding::Utf8 => text.as_bytes().to_vec(), + }; + slots.push(Some(bytes)); + Ok(ArrayAddress::new(slots)) + } +} + +/// Why a bare string could not be expanded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ShorthandError { + /// Neither the server nor the namespace configures a policy. + MissingShorthandPolicy { + /// The namespace that has no policy. + namespace: NamespaceId, + }, + /// The namespace is bound to the content core, which has no slots. + ShorthandRequiresArrayCore { + /// The namespace that is not array-addressed. + namespace: NamespaceId, + }, + /// The configured slot index cannot be allocated. + ExpansionTooLarge, +} + +impl ShorthandError { + /// The stable class name. + pub const fn class(&self) -> &'static str { + match self { + Self::MissingShorthandPolicy { .. } => "missing_shorthand_policy", + Self::ShorthandRequiresArrayCore { .. } => "shorthand_requires_array_core", + Self::ExpansionTooLarge => "expansion_too_large", + } + } +} + +impl fmt::Display for ShorthandError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingShorthandPolicy { namespace } + | Self::ShorthandRequiresArrayCore { namespace } => { + write!(f, "{}: {}", self.class(), namespace.as_str()) + } + Self::ExpansionTooLarge => f.write_str(self.class()), + } + } +} + +impl std::error::Error for ShorthandError {} + +/// Shorthand configuration: per-namespace defaults and per-server +/// overrides. Everything is unset until configured. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ShorthandConfig { + namespace_defaults: BTreeMap, + server_overrides: BTreeMap<(RegistryId, NamespaceId), ShorthandPolicy>, +} + +impl ShorthandConfig { + /// An empty configuration: every namespace is unset. + pub fn new() -> Self { + Self::default() + } + + /// Set the namespace's own policy, returning the one it replaces. + pub fn set_namespace_default( + &mut self, + namespace: NamespaceId, + policy: ShorthandPolicy, + ) -> Option { + self.namespace_defaults.insert(namespace, policy) + } + + /// Unset the namespace's own policy, returning it. + pub fn clear_namespace_default(&mut self, namespace: &NamespaceId) -> Option { + self.namespace_defaults.remove(namespace) + } + + /// Set one server's override for a namespace, returning the one it + /// replaces. + pub fn set_server_override( + &mut self, + server: RegistryId, + namespace: NamespaceId, + policy: ShorthandPolicy, + ) -> Option { + self.server_overrides.insert((server, namespace), policy) + } + + /// Remove one server's override for a namespace, returning it. + pub fn clear_server_override( + &mut self, + server: &RegistryId, + namespace: &NamespaceId, + ) -> Option { + self.server_overrides + .remove(&(server.clone(), namespace.clone())) + } + + /// The policy in force for `namespace` on `server`: that server's + /// override where one is configured, otherwise the namespace's own + /// policy, otherwise `missing_shorthand_policy`. Another server's + /// override never applies. + pub fn policy_for( + &self, + server: &RegistryId, + namespace: &NamespaceId, + ) -> Result { + self.server_overrides + .get(&(server.clone(), namespace.clone())) + .or_else(|| self.namespace_defaults.get(namespace)) + .copied() + .ok_or_else(|| ShorthandError::MissingShorthandPolicy { + namespace: namespace.clone(), + }) + } + + /// Expand `text` for a namespace defined by `definition`, on + /// `server`. The namespace must be array-addressed and have a policy + /// in force. + pub fn expand( + &self, + server: &RegistryId, + definition: &NamespaceDefinition, + text: &str, + ) -> Result { + if definition.core != CoreKind::Array { + return Err(ShorthandError::ShorthandRequiresArrayCore { + namespace: definition.namespace.clone(), + }); + } + self.policy_for(server, &definition.namespace)?.expand(text) + } +} diff --git a/pkgs/id/crates/id-core/tests/array_shorthand.rs b/pkgs/id/crates/id-core/tests/array_shorthand.rs new file mode 100644 index 0000000000..cdf7593813 --- /dev/null +++ b/pkgs/id/crates/id-core/tests/array_shorthand.rs @@ -0,0 +1,334 @@ +//! Model tests for configured bare-string shorthand (slice +//! A9119-shorthand-policy, issue #10261; design A-9119.1, S4.29–S4.33). +//! +//! Oracle: **model** — the expansion function is compared with a +//! configured-index reference over generated configuration operations. +//! Every expansion and every error matches the model; an unset policy is +//! `missing_shorthand_policy` with no fallback index; a server override +//! beats the namespace default only on the server where it is configured; +//! and only array-core namespaces accept shorthand. +//! +//! The crate-root export of `array_shorthand`, `namespace_definition` and +//! `array_address` belongs to slice 9110-02, so until that lands this +//! test includes them by path; `id_shape` and `canonical_cbor` are +//! already exported and are re-exported under the names the modules use. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod id_shape { + pub use id_core::id_shape::*; +} + +mod canonical_cbor { + pub use id_core::canonical_cbor::*; +} + +#[path = "../src/array_address.rs"] +#[allow(dead_code)] +mod array_address; + +#[path = "../src/namespace_definition.rs"] +#[allow(dead_code)] +mod namespace_definition; + +#[path = "../src/array_shorthand.rs"] +mod array_shorthand; + +use array_address::ArrayAddress; +use array_shorthand::{PrefixFill, ShorthandConfig, ShorthandError, ShorthandPolicy, TextEncoding}; +use namespace_definition::{CoreKind, NamespaceDefinition, NamespaceId, RegistryId, Token}; +use proptest::prelude::*; + +const NAMESPACES: [&str; 3] = ["wiki", "people", "blobs"]; +const SERVERS: [&str; 2] = ["alpha", "beta"]; + +fn ns(name: &str) -> NamespaceId { + NamespaceId::new(name).unwrap() +} + +fn server(name: &str) -> RegistryId { + RegistryId::server(name).unwrap() +} + +fn definition(name: &str, core: CoreKind) -> NamespaceDefinition { + NamespaceDefinition { + namespace: ns(name), + core, + handler: Token::new("handler", "store").unwrap(), + encoding_profile: Token::new("encoding", "text").unwrap(), + read_policy: Token::new("read", "anyone").unwrap(), + write_policy: Token::new("write", "owner").unwrap(), + shorthand_policy: Token::new("shorthand", "configured").unwrap(), + schema_version: 1, + } +} + +fn slots(address: &ArrayAddress) -> Vec>> { + address.slots().to_vec() +} + +#[test] +fn design_example_slot_two_expands_with_null_prefix() { + // Slot 2 is the design's example configuration, not a default. + let mut config = ShorthandConfig::new(); + config.set_namespace_default(ns("wiki"), ShorthandPolicy::new(2)); + let got = config + .expand( + &server("alpha"), + &definition("wiki", CoreKind::Array), + "name", + ) + .unwrap(); + assert_eq!(slots(&got), vec![None, None, Some(b"name".to_vec())]); +} + +#[test] +fn unset_policy_is_an_error_not_a_fallback() { + let config = ShorthandConfig::new(); + let error = config + .expand( + &server("alpha"), + &definition("wiki", CoreKind::Array), + "name", + ) + .unwrap_err(); + assert_eq!(error.class(), "missing_shorthand_policy"); + assert_eq!( + error, + ShorthandError::MissingShorthandPolicy { + namespace: ns("wiki") + } + ); + assert_eq!(error.to_string(), "missing_shorthand_policy: wiki"); + // A policy on one namespace does not leak to another. + let mut config = ShorthandConfig::new(); + config.set_namespace_default(ns("people"), ShorthandPolicy::new(0)); + assert_eq!( + config + .policy_for(&server("alpha"), &ns("wiki")) + .unwrap_err() + .class(), + "missing_shorthand_policy" + ); +} + +#[test] +fn server_override_wins_only_where_configured() { + let mut config = ShorthandConfig::new(); + config.set_namespace_default(ns("wiki"), ShorthandPolicy::new(1)); + config.set_server_override(server("alpha"), ns("wiki"), ShorthandPolicy::new(3)); + assert_eq!( + config.policy_for(&server("alpha"), &ns("wiki")).unwrap(), + ShorthandPolicy::new(3) + ); + assert_eq!( + config.policy_for(&server("beta"), &ns("wiki")).unwrap(), + ShorthandPolicy::new(1) + ); + // An override alone configures only its own server. + config.clear_namespace_default(&ns("wiki")); + assert_eq!( + config.policy_for(&server("alpha"), &ns("wiki")).unwrap(), + ShorthandPolicy::new(3) + ); + assert_eq!( + config + .policy_for(&server("beta"), &ns("wiki")) + .unwrap_err() + .class(), + "missing_shorthand_policy" + ); + // A handle registry is a different context from a server with the + // same text. + assert_eq!( + config + .policy_for(&RegistryId::handle("alpha").unwrap(), &ns("wiki")) + .unwrap_err() + .class(), + "missing_shorthand_policy" + ); +} + +#[test] +fn content_core_namespaces_refuse_shorthand() { + let mut config = ShorthandConfig::new(); + config.set_namespace_default(ns("blobs"), ShorthandPolicy::new(0)); + let error = config + .expand( + &server("alpha"), + &definition("blobs", CoreKind::Content), + "x", + ) + .unwrap_err(); + assert_eq!(error.class(), "shorthand_requires_array_core"); +} + +#[test] +fn policy_shape_is_null_fill_and_utf8() { + let policy = ShorthandPolicy::new(5); + assert_eq!(policy.default_slot(), 5); + assert_eq!(policy.prefix_fill(), PrefixFill::Null); + assert_eq!(policy.text_encoding(), TextEncoding::Utf8); + // Slot 0 is the string alone; the empty string is empty bytes, not null. + assert_eq!( + slots(&ShorthandPolicy::new(0).expand("").unwrap()), + vec![Some(Vec::new())] + ); + // Text bytes are the exact UTF-8, with no normalization. + let text = "e\u{301}雪"; + assert_eq!( + slots(&ShorthandPolicy::new(1).expand(text).unwrap()), + vec![None, Some(text.as_bytes().to_vec())] + ); +} + +#[test] +fn an_unallocatable_slot_is_an_error_not_an_abort() { + assert_eq!( + ShorthandPolicy::new(usize::MAX) + .expand("x") + .unwrap_err() + .class(), + "expansion_too_large" + ); + assert_eq!( + ShorthandPolicy::new(usize::MAX / 2) + .expand("x") + .unwrap_err() + .class(), + "expansion_too_large" + ); +} + +/// One configuration step or query. +#[derive(Debug, Clone)] +enum Op { + SetDefault(usize, usize), + ClearDefault(usize), + SetOverride(usize, usize, usize), + ClearOverride(usize, usize), + Expand(usize, usize, String, bool), +} + +fn op_strategy() -> impl Strategy { + let ns_index = 0..NAMESPACES.len(); + let server_index = 0..SERVERS.len(); + let slot = 0_usize..12; + prop_oneof![ + (ns_index.clone(), slot.clone()).prop_map(|(n, s)| Op::SetDefault(n, s)), + ns_index.clone().prop_map(Op::ClearDefault), + (server_index.clone(), ns_index.clone(), slot) + .prop_map(|(v, n, s)| Op::SetOverride(v, n, s)), + (server_index.clone(), ns_index.clone()).prop_map(|(v, n)| Op::ClearOverride(v, n)), + (server_index, ns_index, "\\PC{0,8}", any::()) + .prop_map(|(v, n, t, array)| Op::Expand(v, n, t, array)), + ] +} + +/// The reference: plain association lists and a hand-built expansion. +#[derive(Default)] +struct Model { + defaults: Vec<(usize, usize)>, + overrides: Vec<((usize, usize), usize)>, +} + +impl Model { + fn set(list: &mut Vec<(K, usize)>, key: K, slot: usize) -> Option { + let old = Self::clear(list, &key); + list.push((key, slot)); + old + } + + fn clear(list: &mut Vec<(K, usize)>, key: &K) -> Option { + let index = list.iter().position(|(k, _)| k == key)?; + Some(list.remove(index).1) + } + + fn expand( + &self, + server: usize, + namespace: usize, + text: &str, + array: bool, + ) -> Result>>, &'static str> { + if !array { + return Err("shorthand_requires_array_core"); + } + let slot = self + .overrides + .iter() + .find(|(key, _)| *key == (server, namespace)) + .map(|(_, slot)| *slot) + .or_else(|| { + self.defaults + .iter() + .find(|(key, _)| *key == namespace) + .map(|(_, slot)| *slot) + }) + .ok_or("missing_shorthand_policy")?; + let mut out = vec![None; slot]; + out.push(Some(text.as_bytes().to_vec())); + Ok(out) + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn configuration_operations_match_the_reference_model( + ops in proptest::collection::vec(op_strategy(), 0..40), + ) { + let mut config = ShorthandConfig::new(); + let mut model = Model::default(); + for op in ops { + match op { + Op::SetDefault(n, s) => { + let got = config.set_namespace_default(ns(NAMESPACES[n]), ShorthandPolicy::new(s)); + let want = Model::set(&mut model.defaults, n, s); + prop_assert_eq!(got.map(ShorthandPolicy::default_slot), want); + } + Op::ClearDefault(n) => { + let got = config.clear_namespace_default(&ns(NAMESPACES[n])); + let want = Model::clear(&mut model.defaults, &n); + prop_assert_eq!(got.map(ShorthandPolicy::default_slot), want); + } + Op::SetOverride(v, n, s) => { + let got = config.set_server_override( + server(SERVERS[v]), + ns(NAMESPACES[n]), + ShorthandPolicy::new(s), + ); + let want = Model::set(&mut model.overrides, (v, n), s); + prop_assert_eq!(got.map(ShorthandPolicy::default_slot), want); + } + Op::ClearOverride(v, n) => { + let got = config.clear_server_override(&server(SERVERS[v]), &ns(NAMESPACES[n])); + let want = Model::clear(&mut model.overrides, &(v, n)); + prop_assert_eq!(got.map(ShorthandPolicy::default_slot), want); + } + Op::Expand(v, n, text, array) => { + let core = if array { CoreKind::Array } else { CoreKind::Content }; + let got = config + .expand(&server(SERVERS[v]), &definition(NAMESPACES[n], core), &text) + .map(|address| slots(&address)) + .map_err(|error| error.class()); + prop_assert_eq!(got, model.expand(v, n, &text, array)); + } + } + } + } + + /// Expansion is pure: the string is always the last slot, at exactly + /// the configured index, and every earlier slot is null. + #[test] + fn expansion_places_the_string_at_the_configured_index( + slot in 0_usize..64, + text in "\\PC{0,16}", + ) { + let got = ShorthandPolicy::new(slot).expand(&text).unwrap(); + prop_assert_eq!(got.len(), slot + 1); + prop_assert!(got.slots()[..slot].iter().all(Option::is_none)); + prop_assert_eq!(got.slots()[slot].as_deref(), Some(text.as_bytes())); + } +}