core.serialization module
Serialization helpers for Redis Stream payloads and Hash fields.
- core.serialization.normalize_void_egregores(value)
Return a bounded, ordered, distinct VOID egregore transport list.
The aliases are resolved before the inbound envelope is built. This helper protects the Redis boundary from malformed or oversized values without changing the resolver’s first-mention ordering.
- class core.serialization.InboundEnvelopeModel(**data)
Bases:
BaseModelPydantic schema for the gateway-to-inference inbound message envelope.
The validated, runtime-checked contract for a message as it crosses the inbound Redis Stream: sender/channel/content fields plus the microservice transport extras (routing decision, alias set, unified user id, reaction summary).
validate_inbound_envelope()builds this from a raw dict to reject malformed payloads at the boundary;InboundEnvelopeis the lighterTypedDictview of the same shape used for static typing.- Parameters:
channel_key (str)
platform (str)
channel_id (str)
user_id (str)
username (str)
display_name (str | None)
content (str)
message_id (str)
timestamp (float)
reply_to (str | None)
room_name (str | None)
is_dm (bool)
is_private_codex_dm (bool)
guild_id (str | None)
trace_id (str)
event_kind (str)
ingress_fingerprint (str)
enqueued_at (float)
is_addressed (bool)
unified_user_id (str | None)
reactions (str)
needle_shard (bool)
babystar_playpen (bool)
babystar_room (str)
babystar_room_context (str)
babystar_room_name (str)
babystar_multiplayer (bool)
babystar_reply_author (str)
babystar_reply_excerpt (str)
babystar_party_context (str)
gock_hypervisor (bool)
gock_group_id (str)
gock_room (str)
gock_egregore (str)
gock_auth_method (str)
gock_wallet_address (str)
gock_discord_user_id (str)
gock_token_balance_raw (str)
gock_token_decimals (int)
gock_gate_passed (bool)
gock_gate_checked_at (float)
gock_party_context (str)
gock_chart_query (str)
void_chain_verified (bool)
void_trigger_id (str)
void_trigger_tx_hash (str)
void_trigger_log_index (int)
void_lau_address (str)
void_dss_address (str)
void_soul_id (str)
void_reply_onchain (bool)
- is_addressed: bool
Whether the bot was explicitly addressed. Checked by InboundStreamConsumer to decide whether to acquire the per-channel distributed lock.
- needle_shard: bool
True when the message originated from the Needle Shard web client. Restored into IncomingMessage.extra by the inference worker; forces NCM/CSDR headers on for shard chats. 🕷️
- babystar_playpen: bool
hard-locked Babystar egregore, timebender/loopcast tool merge, forced headers + cadence. 🍼
- Type:
True for Babystar Playpen web chats
- babystar_game_state: Dict[str, Any]
Client-side tummy/bladder/diaper state injected for narrative sync.
- babystar_party_context: str
Bounded recent multiplayer transcript, explicitly treated as untrusted.
- gock_token_balance_raw: str
Latest server-read GOCK balance in raw integer units, serialized as text.
- gock_market_snapshots: List[Dict[str, Any]]
Typed DexScreener snapshots fetched by the server for this turn.
- gock_universe_snapshots: List[Dict[str, Any]]
Bounded PULSAr universe lookups for addresses pasted this turn.
- gock_ecosystem_context: List[Dict[str, Any]]
Sanitized ATROPA corpus matches with source provenance.
- class core.serialization.OutboundEnvelopeModel(**data)
Bases:
BaseModelPydantic schema for the inference-to-gateway outbound response envelope.
The validated contract for a response leaving the inference worker on the outbound Redis Stream: target
channel_id/platform, atypetag (message/file/buttons/reaction/…), the optional per-type payload fields, and the idempotencymessage_keyplus tracing metadata. Validated byvalidate_outbound_envelope();OutboundEnvelopeis theTypedDictview of the same shape.- Parameters:
- core.serialization.validate_inbound_envelope(raw)
Validate and normalize a raw inbound envelope through its Pydantic model.
Constructs an
InboundEnvelopeModelfromraw(which enforces required fields, types, and defaults for the gateway-to-inference stream contract) and returns it as a plain dict, so a malformed payload is rejected at the boundary rather than failing deeper in processing. Pure with respect to external state; the only side effect is raising on invalid input.Used as a schema guard before trusting a stream payload; in this repo it is exercised by the PEL-leak adversarial tests (
tests/adversarial/test_pel_leak_protection.py).
- core.serialization.validate_outbound_envelope(raw)
Validate and normalize a raw outbound envelope through its Pydantic model.
Constructs an
OutboundEnvelopeModelfromraw(enforcing the inference-to-gateway response contract: requiredchannel_id/platform/trace_id/processed_atplus the optional per-type payload fields) and returns it as a plain dict, catching a malformed response before it reaches the outbound stream. The only side effect is raising on invalid input.A schema guard for the response path; no internal caller was found in this repo (it complements
validate_inbound_envelope()as the outbound counterpart and is available to validators/tests).
- class core.serialization.InboundEnvelope
Bases:
TypedDictTypedDict shape of an inbound message envelope for static typing.
The structural, annotation-only view of an inbound stream payload (routing, sender, content, context, and tracing groups), mirroring
InboundEnvelopeModelwithout runtime validation. Used to type dict-shaped envelopes throughout the inference path; verified bytests/core/test_envelopes.py.
- class core.serialization.OutboundEnvelope
Bases:
TypedDictTypedDict shape of an outbound response envelope for static typing.
The structural, annotation-only view of an outbound stream payload (routing, typed payload, and metadata groups), mirroring
OutboundEnvelopeModelwithout runtime validation. Used to type the response dicts the worker publishes; verified bytests/core/test_envelopes.py.
- core.serialization.serialize_stream_payload(data)
Serialize a dict into a flat {field: msgpack_bytes} map for XADD.
Redis Streams store field-value pairs. We pack the entire payload into a single ‘data’ field to avoid flattening nested structures. When the payload already has a trace ID, the transport sidecar reuses it so stream diagnostics and the decoded envelope refer to the same operation. Payloads without application-level tracing retain a generated transport-only ID.
- core.serialization.deserialize_stream_payload(raw)
Unpack a Redis Stream entry’s packed
datafield back into a dict.The inverse of
serialize_stream_payload(): pulls the singledatafield (tolerating bothbytesandstrkeys, since redis-py may return either depending ondecode_responses) andmsgpack-unpacks it into the original Python dict. The transport metadata fields (ts,trace_id,schema_version) are intentionally ignored. Pure, with no I/O.Called on the read side of every stream by the consumers and dead-letter handler —
core/stream_consumer.py,core/outbound_consumer.py, andcore/dlq.py— and by the serialization/end-to-end tests.
- core.serialization.serialize_hash_field(value)
Encode a Python value as a JSON string for storage in a Redis Hash field.
Redis Hash values are flat strings, so structured data (dicts, lists) must be JSON-encoded first. Uses
default=strso otherwise non-serializable values (e.g.datetime,UUID) degrade to their string form instead of raising. Pairs withdeserialize_hash_field()on read. Pure, with no I/O.A general hash-field codec helper; in this repo it is exercised directly by the serialization tests (
tests/core/test_serialization.py).
- core.serialization.deserialize_hash_field(raw, fallback=None)
Decode a JSON string read from a Redis Hash field back into a Python value.
The inverse of
serialize_hash_field():json.loadsthe stored string, but returnsfallbackunchanged whenrawisNone(the common case of a missing hash field viahget) so callers need not special-case absent keys. Pure, with no I/O.A general hash-field codec helper; in this repo it is exercised directly by the serialization tests (
tests/core/test_serialization.py).- Parameters:
- Returns:
The decoded value, or
fallbackwhen the field was absent.- Return type:
- Raises:
json.JSONDecodeError – If
rawis a non-Nonebut invalid JSON string.