def _truncate_by_utf8_octets(s: str, maximum_utf8_octets: int) -> str:
    """Truncate a string so it's no longer than the given number of octets when
    encoded as UTF-8.

    This takes care to avoid truncating in the middle of a multi-byte code point.
    So the output is always valid Unicode.

    However, it may split up multi-code-point sequences
    that a human would inituitively see as a single character.
    For example, it's possible to encode "é" as two code points:

    1. U+0061 Latin Small Letter E
    2. U+0306 Combining Acute Accent

    And this may truncate in between them, leaving an unaccented "e" in the output.
    (If we care to fix this, we should look into preserving grapheme clusters:
    https://unicode.org/reports/tr29/)
    """
    encoded = s.encode("utf-8")[:maximum_utf8_octets]
    return encoded.decode(
        "utf-8",
        # Silently discard any trailing junk left over
        # from truncating in the middle of a code point.
        errors="ignore",
    )