Module adcp.compat.versions

Translation between consecutive AdCP minor releases.

Application payloads use the packaged release. Only protocol boundaries use older schemas. Unknown extension data is opaque; known newer fields are projected using both schemas, with a value-free record for every loss.

Functions

def convert_payload(tool: str,
payload: dict[str, Any],
*,
direction: Direction,
source_version: str,
target_version: str,
request: dict[str, Any] | None = None,
loss_log_level: int = 30,
require_valid_target: bool = True) ‑> ConversionResult
Expand source code
def convert_payload(
    tool: str,
    payload: dict[str, Any],
    *,
    direction: Direction,
    source_version: str,
    target_version: str,
    request: dict[str, Any] | None = None,
    loss_log_level: int = logging.WARNING,
    require_valid_target: bool = True,
) -> ConversionResult:
    """Chain adjacent minor conversions without modifying the caller's data.

    The 3.1/3.0 lifecycle envelope is translated semantically. Additive
    changes use the bundled schemas, including nested arrays and unions.
    New tasks without an older equivalent fail before transport.

    Every loss is logged at ``loss_log_level``. ``direction`` says nothing
    about which side of the wire is converting, so callers choose the level:
    a buyer losing a seller's data keeps ``WARNING``, while a seller dropping
    newer fields for an older buyer expects those losses and logs them at
    ``DEBUG`` (see :func:`log_conversion_summary`).

    A downgrade raises :class:`ADCPVersionConversionError` rather than return
    a payload the older schema refuses. ``require_valid_target=False`` skips
    only that final check, for callers reconstructing a peer's own evidence
    rather than sending a payload; projection repairs still apply.
    """
    converted = _convert_payload(
        tool,
        payload,
        direction=direction,
        source_version=source_version,
        target_version=target_version,
        request=request,
        require_valid_target=require_valid_target,
    )
    for loss in converted.losses:
        logger.log(
            loss_log_level,
            "AdCP conversion %s -> %s dropped %s (%s)",
            loss.source_version,
            loss.target_version,
            loss.pointer,
            loss.reason,
        )
    return converted

Chain adjacent minor conversions without modifying the caller's data.

The 3.1/3.0 lifecycle envelope is translated semantically. Additive changes use the bundled schemas, including nested arrays and unions. New tasks without an older equivalent fail before transport.

Every loss is logged at loss_log_level. direction says nothing about which side of the wire is converting, so callers choose the level: a buyer losing a seller's data keeps WARNING, while a seller dropping newer fields for an older buyer expects those losses and logs them at DEBUG (see :func:log_conversion_summary()).

A downgrade raises :class:ADCPVersionConversionError rather than return a payload the older schema refuses. require_valid_target=False skips only that final check, for callers reconstructing a peer's own evidence rather than sending a payload; projection repairs still apply.

def log_conversion_summary(tool: str,
losses: tuple[ConversionLoss, ...],
*,
source_version: str,
target_version: str,
level: int = 20) ‑> None
Expand source code
def log_conversion_summary(
    tool: str,
    losses: tuple[ConversionLoss, ...],
    *,
    source_version: str,
    target_version: str,
    level: int = logging.INFO,
) -> None:
    """Log one line summarizing a conversion's losses, if it had any.

    Array indexes collapse to ``*`` so a response repeating the same drop
    on every item lists the pointer once, e.g.
    ``/products/*/included_signals/*/demographic_predicate``.
    """
    if not losses:
        return
    pointers = list(dict.fromkeys(_ARRAY_INDEX.sub("/*", loss.pointer) for loss in losses))
    shown = ", ".join(pointers[:_SUMMARY_POINTER_LIMIT])
    if len(pointers) > _SUMMARY_POINTER_LIMIT:
        shown += f", ... (+{len(pointers) - _SUMMARY_POINTER_LIMIT} more)"
    logger.log(
        level,
        "AdCP conversion of %s %s -> %s dropped %d field(s): %s",
        tool,
        source_version,
        target_version,
        len(losses),
        shown,
    )

Log one line summarizing a conversion's losses, if it had any.

Array indexes collapse to * so a response repeating the same drop on every item lists the pointer once, e.g. /products/*/included_signals/*/demographic_predicate.

def negotiate_version(supported: list[str], *, maximum: str) ‑> str
Expand source code
def negotiate_version(supported: list[str], *, maximum: str) -> str:
    """Select the highest common release, bounded by this call's pin.

    Prereleases match exactly (except explicitly supported aliases). Never
    infer compatibility with an unadvertised release or another major.
    """
    from adcp._version import is_adcp_version_at_least

    maximum = _release(maximum)
    available = {_release(version) for version in get_supported_adcp_versions()}
    common = [
        version
        for version in supported
        if isinstance(version, str)
        and _release(version) in available
        and is_adcp_version_at_least(maximum, _release(version))
    ]
    if not common:
        raise ADCPFeatureUnsupportedError(["No common AdCP version with this seller"])
    selected = common[0]
    for candidate in common[1:]:
        candidate_release, selected_release = _release(candidate), _release(selected)
        if (
            candidate_release != selected_release
            and is_adcp_version_at_least(candidate_release, selected_release)
        ) or (candidate_release == selected_release and candidate == candidate_release):
            selected = candidate
    # Retain a seller's advertised alias for old sellers with exact matching.
    return selected

Select the highest common release, bounded by this call's pin.

Prereleases match exactly (except explicitly supported aliases). Never infer compatibility with an unadvertised release or another major.

Classes

class ADCPVersionConversionError (*, pointer: str, source_version: str, target_version: str, reason: str)
Expand source code
class ADCPVersionConversionError(ADCPFeatureUnsupportedError):
    """A payload cannot be represented without inventing state or changing a clear."""

    def __init__(
        self, *, pointer: str, source_version: str, target_version: str, reason: str
    ) -> None:
        self.pointer = pointer
        self.source_version = source_version
        self.target_version = target_version
        self.reason = reason
        super().__init__(
            [f"Cannot convert AdCP {source_version} to {target_version} at {pointer}: {reason}"]
        )

A payload cannot be represented without inventing state or changing a clear.

Initialize feature unsupported error.

Args
-----=
unsupported_features
Features that are not supported.
declared_features
Features the seller does declare.
agent_id
Optional agent ID for context.
agent_uri
Optional agent URI for context.

Ancestors

Inherited members

class ConversionLoss (pointer: str,
source_version: str,
target_version: str,
reason: str = 'field_unavailable')
Expand source code
@dataclass(frozen=True)
class ConversionLoss:
    """One discarded field/item; values are deliberately never retained."""

    pointer: str
    source_version: str
    target_version: str
    reason: str = "field_unavailable"

One discarded field/item; values are deliberately never retained.

Instance variables

var pointer : str
var reason : str
var source_version : str
var target_version : str
class ConversionResult (payload: dict[str, Any],
losses: tuple[ConversionLoss, ...] = (),
creative_dialect: str | None = None,
identity_migrations: tuple[dict[str, Any], ...] = ())
Expand source code
@dataclass(frozen=True)
class ConversionResult:
    payload: dict[str, Any]
    losses: tuple[ConversionLoss, ...] = ()
    creative_dialect: str | None = None
    identity_migrations: tuple[dict[str, Any], ...] = ()

    def metadata(self) -> list[dict[str, Any]]:
        return [asdict(loss) for loss in self.losses]

ConversionResult(payload: 'dict[str, Any]', losses: 'tuple[ConversionLoss, …]' = (), creative_dialect: 'str | None' = None, identity_migrations: 'tuple[dict[str, Any], …]' = ())

Instance variables

var creative_dialect : str | None
var identity_migrations : tuple[dict[str, typing.Any], ...]
var losses : tuple[ConversionLoss, ...]
var payload : dict[str, typing.Any]

Methods

def metadata(self) ‑> list[dict[str, typing.Any]]
Expand source code
def metadata(self) -> list[dict[str, Any]]:
    return [asdict(loss) for loss in self.losses]