|
9 | 9 |
|
10 | 10 | import hashlib |
11 | 11 | from dataclasses import dataclass, field |
| 12 | +from enum import Enum |
12 | 13 | from typing import Any |
13 | 14 |
|
14 | 15 | from .scalar import ( |
@@ -362,3 +363,125 @@ def decode_generic_delta(text: str) -> GenericDeltaPayload: |
362 | 363 | else: |
363 | 364 | raise ValueError(f"delta_invalid: unknown delta section {name!r}") |
364 | 365 | return d |
| 366 | + |
| 367 | + |
| 368 | +# --- producer-side re-anchor session helper (SPEC Section 10a.8) --- |
| 369 | +# |
| 370 | +# GenericDeltaSession manages the re-anchor cadence for a stream of |
| 371 | +# generic-profile updates. It is thin sugar over the primitives: each ``next`` |
| 372 | +# emits either a compact delta or, on its chosen cadence, a full re-anchor, |
| 373 | +# updating its held base. It introduces NO new wire syntax: every payload it |
| 374 | +# emits is exactly what ``encode_generic_full`` or ``encode_generic_delta`` |
| 375 | +# produce, and the decoder accepts them cadence-agnostically. N and the size |
| 376 | +# guard are the helper's knobs; they are never wire fields. (Section 10a.8 is |
| 377 | +# non-normative producer policy.) |
| 378 | + |
| 379 | + |
| 380 | +# The working default cadence for FixedN (SPEC Section 10a.8). |
| 381 | +DEFAULT_REANCHOR_N = 15 |
| 382 | + |
| 383 | + |
| 384 | +class ReanchorMode(Enum): |
| 385 | + """Selects the session's cadence policy.""" |
| 386 | + |
| 387 | + FIXED_N = 0 # re-anchor every N turns |
| 388 | + SIZE_GUARD = 1 # re-anchor once cumulative delta reaches the full payload's size |
| 389 | + |
| 390 | + |
| 391 | +@dataclass |
| 392 | +class ReanchorPolicy: |
| 393 | + """Selects when a :class:`GenericDeltaSession` re-anchors. |
| 394 | +
|
| 395 | + Construct it with :func:`fixed_n` or :func:`size_guard`. |
| 396 | + """ |
| 397 | + |
| 398 | + mode: ReanchorMode = ReanchorMode.FIXED_N |
| 399 | + n: int = 0 # turns between anchors; FixedN only |
| 400 | + |
| 401 | + |
| 402 | +def fixed_n(n: int) -> ReanchorPolicy: |
| 403 | + """Re-anchor every ``n`` turns. ``n <= 0`` falls back to ``DEFAULT_REANCHOR_N``.""" |
| 404 | + if n <= 0: |
| 405 | + n = DEFAULT_REANCHOR_N |
| 406 | + return ReanchorPolicy(mode=ReanchorMode.FIXED_N, n=n) |
| 407 | + |
| 408 | + |
| 409 | +def size_guard() -> ReanchorPolicy: |
| 410 | + """Re-anchor once the cumulative delta bytes since the last anchor reach the |
| 411 | + current full payload's byte size: it re-anchors more under heavy churn, rarely |
| 412 | + under light churn, and bounds the delta spent between anchors to about one full |
| 413 | + payload. Production-recommended. |
| 414 | + """ |
| 415 | + return ReanchorPolicy(mode=ReanchorMode.SIZE_GUARD) |
| 416 | + |
| 417 | + |
| 418 | +def _byte_len(s: str) -> int: |
| 419 | + """UTF-8 byte length, matching Go's ``len(string)`` (bytes, not code points).""" |
| 420 | + return len(s.encode("utf-8")) |
| 421 | + |
| 422 | + |
| 423 | +class GenericDeltaSession: |
| 424 | + """Holds the current base and re-anchor state for a producer loop. |
| 425 | +
|
| 426 | + Not safe for concurrent use. Call :meth:`current_full` to get the initial |
| 427 | + full payload to transmit, then :meth:`next` for each subsequent state. |
| 428 | + """ |
| 429 | + |
| 430 | + def __init__(self, base: GenericSet, tool: str, policy: ReanchorPolicy) -> None: |
| 431 | + if policy.mode == ReanchorMode.FIXED_N and policy.n <= 0: |
| 432 | + policy = ReanchorPolicy(mode=policy.mode, n=DEFAULT_REANCHOR_N) |
| 433 | + self._base = base |
| 434 | + self._tool = tool |
| 435 | + self._policy = policy |
| 436 | + self._turn = 0 |
| 437 | + self._cum = 0 # cumulative delta bytes since the last anchor |
| 438 | + |
| 439 | + @property |
| 440 | + def turn(self) -> int: |
| 441 | + """The number of :meth:`next` calls so far (the initial full is turn 0).""" |
| 442 | + return self._turn |
| 443 | + |
| 444 | + def current_full(self) -> str: |
| 445 | + """Return the full payload for the current base (:func:`encode_generic_full`). |
| 446 | +
|
| 447 | + Send this first to establish the base; it is also a valid manual re-anchor. |
| 448 | + """ |
| 449 | + return encode_generic_full(self._base, self._tool) |
| 450 | + |
| 451 | + def _reanchor(self, nxt: GenericSet) -> str: |
| 452 | + wire = encode_generic_full(nxt, self._tool) |
| 453 | + self._base = nxt |
| 454 | + self._cum = 0 |
| 455 | + return wire |
| 456 | + |
| 457 | + def next(self, nxt: GenericSet) -> tuple[str, bool]: |
| 458 | + """Advance the session by one turn to ``nxt``. |
| 459 | +
|
| 460 | + Returns ``(wire, is_full)``: the wire to transmit and whether it is a full |
| 461 | + re-anchor (``True``) or a delta (``False``). A schema change forces a full |
| 462 | + (Section 10a.7). The held base becomes ``nxt`` either way. The wire is |
| 463 | + byte-identical to calling ``encode_generic_full`` / ``encode_generic_delta`` |
| 464 | + directly. May raise on duplicate identity / no key (propagated from |
| 465 | + :func:`diff_generic_sets`). |
| 466 | + """ |
| 467 | + self._turn += 1 |
| 468 | + |
| 469 | + # Schema change (or a fresh key) cannot be expressed as a delta -> full. |
| 470 | + if nxt.key != self._base.key or list(self._base.fields) != list(nxt.fields): |
| 471 | + return self._reanchor(nxt), True |
| 472 | + |
| 473 | + d = diff_generic_sets(self._base, nxt) |
| 474 | + delta_wire = encode_generic_delta(d) |
| 475 | + |
| 476 | + if self._policy.mode == ReanchorMode.SIZE_GUARD: |
| 477 | + reanchor = self._cum + _byte_len(delta_wire) >= _byte_len( |
| 478 | + encode_generic_full(nxt, self._tool) |
| 479 | + ) |
| 480 | + else: # FIXED_N |
| 481 | + reanchor = self._turn % self._policy.n == 0 |
| 482 | + |
| 483 | + if reanchor: |
| 484 | + return self._reanchor(nxt), True |
| 485 | + self._base = nxt |
| 486 | + self._cum += _byte_len(delta_wire) |
| 487 | + return delta_wire, False |
0 commit comments