Skip to content

Name a refused value's type as btclib reads it (closes #3128) - #3141

Merged
fametrano merged 2 commits into
mainfrom
type-name-refusals-3128
Nov 17, 2026
Merged

fametrano merged 2 commits into
mainfrom
type-name-refusals-3128

Conversation

@fametrano

@fametrano fametrano commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

A refusal of a value's type printed type(value).__name__, which the caller's class decides: a class can be named by a key's hex, and a metaclass can answer any name or raise. Every refusal now names the type through utils._type_name, which reads the name through type's own descriptor, copies it to an exact str, and prints it only where it is a short ASCII identifier or a class btclib defines; any other name is described by its length. _message_text reads a length through _length, the built-in base type's own __len__, and int_from_json_number raises its refusals after the except block, so the caller's exception is neither their cause nor their context.

What this breaks: a long or non-identifier type name reads "a type whose name has N characters"; a class whose metaclass answers __name__ is named by its own name; _message_text gives no length for a value of none of _length's built-in types, nor for one whose type name it does not print; int_from_json_number's refusals no longer carry the error int() raised, as __cause__ or as __context__.

Evidence

Gate on 4f22f1d Command Exit
Coverage lane uv run --locked --no-default-groups --group test pytest -n 3: 26198 passed, 100% 0
No-bindings lane uv sync --exact --no-default-groups --group harness, then pytest -n 3 --cov-fail-under=0: 20805 passed 0
Coverage union coverage combine, coverage report: 100% 0
Docs sphinx-build -n -W -b html docs/source, on 3550093; 4f22f1d changes only test docstrings, which no page renders 0
Hooks pre-commit run --show-diff-on-failure --files the 45 files, SKIP=markdownlint-cli2,prettier 0
Sign-off check_sign_off.py 20c35b6b..4f22f1d3; control c1786962edc1 exits 1 0

Decision

The four hand-written reprs (PrvKeyData, PubKeyData, ScriptPubKey, Witness) keep type(self).__name__, and the census exempts them by class: a repr names its own object's class, as the reprs the dataclass decorator generates do with __qualname__, so the name is not a refused argument. The maintainer decided this on ISS #3128 (option 1). Rejected: (2) the four reprs through _type_name too, which would leave them differing from the generated reprs; (3) every repr, generated ones included, through _type_name, which means overriding each generated repr.

Closes #3128

🤖 Generated with Claude Code

A refusal of a value's type printed type(value).__name__, which the
caller's class decides: a class can be named by a key's hex, and a
metaclass can answer any name for __name__ or raise from it. Every
refusal now names the type through utils._type_name. It reads the name
through type's own descriptor, copies it to an exact str, and prints it
where it is an ASCII identifier of at most _MAX_QUOTED_NAME_LENGTH
characters or the name of a class btclib defines. Any other name is
described by its length.

_message_text reads a length through _length: the __len__ of the
built-in type the value derives from, so a subclass's own __len__
decides no length _message_text prints.

int_from_json_number raised its refusals from the error int() raised,
which a subclass's own __int__ can fill with the value. It now raises
them after the except block, so that error is neither their cause nor
their context.

tests/refused_type_name_test.py feeds each shape to the refusals the
issue names and checks the chain with assert_secret_free. Its census
fails on an attribute read of __name__ or __qualname__ in src/btclib,
except in the hand-written reprs, which name their own object's class
as the reprs the dataclass decorator generates do, and on either name
written as a string but the one utils reads type's descriptor with.

What this breaks: a refusal names a type whose name is longer than
_MAX_QUOTED_NAME_LENGTH characters, or is no ASCII identifier, as "a
type whose name has N characters", unless btclib defines a class of
that name; on CPython, builtin_function_or_method and method-wrapper
are such names. A class whose metaclass answers __name__ is named by
the class's own name. _message_text describes a value of none of the
built-in types _length reads without a length, where its own __len__
gave one, and a value whose type name is not printed without its own
length.
int_from_json_number's refusals carry no __cause__ and no __context__.
A caller matching those texts, or reading that cause, updates its match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Ferdinando Ametrano <ferdinando@ametrano.net>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T16:48:25.494585Z 4f22f1d New commits
🔒 Security Review ✅ Completed 2026-11-17T16:50:11.677471Z 4f22f1d New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Improvements
    • Error messages for invalid input types now use consistent, safer descriptions across the library, including clearer handling of unusual type names and values with custom length behavior.
    • Conversion refusal errors no longer expose the underlying conversion exception as a chained cause.
    • Validation rules and accepted inputs remain unchanged; these updates affect how certain errors are presented.

The PR adds shared helpers for formatting type names and supported container lengths in refusal messages. It applies them across btclib validation paths and changes int_from_json_number to raise conversion refusals without chaining the caught exception.

Changes: Refusal message formatting

Layer / File(s) Summary
Type-name and length formatting
src/btclib/utils.py, tests/refused_type_name_test.py, tests/refused_strings_test.py, tests/utils_test.py
utils.py adds _type_name and _length for refusal descriptions. int_from_json_number raises conversion refusals outside the exception handler. Tests cover type names, lengths, exception chaining, and use of type-name attributes.
Core and block validation messages
src/btclib/b32.py, src/btclib/block/*, src/btclib/bms.py, src/btclib/consensus.py, src/btclib/ellswift.py, src/btclib/hashes.py, src/btclib/network.py, src/btclib/policy.py, src/btclib/utreexo.py
These validation errors now use _type_name to report invalid types. Their validation conditions and exception classes remain unchanged.
Peer-to-peer validation messages
src/btclib/p2p/*
Peer-to-peer validation errors now use _type_name to report invalid types. Their validation conditions and exception behavior remain unchanged.
Script and transaction validation messages
src/btclib/script/*, src/btclib/tx/*
Script, Taproot, witness, and transaction validation errors now use _type_name to report invalid types. Their validation conditions and exception outcomes remain unchanged.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related issues

  • btclib-org/btclib#3139: The issue describes another refusal path where a metaclass can affect the exception raised. The PR changes refusal text formatting but does not change _has_type.

Possibly related PRs

Merge Risk: Minimal · up to 4f22f

Refusal messages now name a refused value's type through a guarded helper, so a class or metaclass can no longer inject its own name or secret into an error. Validation behavior is unchanged, and the reported tests cover the new behavior. No merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Name a refused value's type as btclib reads it (closes #3128)" matches the main change. The diff replaces direct type(value).__name__ reads in refusal messages with the shared `utils._typ…
Linked Issues check Passed Issue #3128 is the only active directly linked issue, so its coding requirements apply. (1) Refusals must not print a type name as the class or metaclass answers it. The whole-PR summary shows assert_…
Out of Scope Changes check Passed All changed files in the whole-PR diff (merge base 20c35b6 to head 4f22f1d) are refusal-message changes that route type names through utils._type_name, or changes that support them: utils.py helpers…
Description check Passed The description is specific and related to the changeset. It explains that refusal messages now name types through utils._type_name, that _message_text reads lengths through _length, and that int_from…
Full details: Title check

Explanation

The title "Name a refused value's type as btclib reads it (closes #3128)" matches the main change. The diff replaces direct type(value).__name__ reads in refusal messages with the shared utils._type_name helper, which is the change the description and objectives report. It names the change clearly and references the linked issue. The title does not mention the _length or int_from_json_number changes, which are secondary. The title does not follow the organization's standard in the title_check_requirements, which is only a link, so this check passes on relevance alone.

Full details: Linked Issues check

Explanation

Issue #3128 is the only active directly linked issue, so its coding requirements apply. (1) Refusals must not print a type name as the class or metaclass answers it. The whole-PR summary shows assert_type, bytes_from_octets, int_from_json_number, validated_network_name and the other listed raw reads now call utils._type_name. The head of src/btclib/utils.py confirms this in bytes_from_octets and str_from_string. (2) int_from_json_number's 'not a whole number' refusal must chain nothing from the caller's exception. The change summary says it is raised after the except block, which matches the pattern used in str_from_string at head. The int_from_json_number body was past the read limit, so this specific point rests on the summary. (3) A census must catch raw type(...).name reads. tests/refused_type_name_test.py adds an AST census of src/btclib. The four hand-written reprs (PrvKeyData, PubKeyData, ScriptPubKey, Witness) keep type(self).name. They are reprs, not refusals, and the PR cites the maintainer's option 1 decision on #3128. The head commit since the previous review, '4f22f1d3', only changes the census docstring per its subject line. It does not change any refusal requirement. Unresolved: the int_from_json_number body and the incremental diff were not read directly.

Full details: Out of Scope Changes check

Explanation

All changed files in the whole-PR diff (merge base 20c35b6 to head 4f22f1d) are refusal-message changes that route type names through utils._type_name, or changes that support them: utils.py helpers (_type_name, _length, _message_text, int_from_json_number ordering), the same substitution across listed modules, test expectation updates in tests/refused_strings_test.py and tests/utils_test.py, and the new tests/refused_type_name_test.py census. Each connects to issue #3128. The incremental change at head (census docstring wording, per commit subject) supports the same census. No unrelated functional change appears in the summary. The utils.py body past the read limit was not fully inspected, so this verdict relies on the change summary for those lines.

Full details: Description check

Explanation

The description is specific and related to the changeset. It explains that refusal messages now name types through utils._type_name, that _message_text reads lengths through _length, and that int_from_json_number raises refusals after the except block. It also lists the behavior changes, the four hand-written reprs that keep type(self).name, and the validation evidence.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3550093 and 4f22f1d.

Files selected for processing: 1

  • tests/refused_type_name_test.py

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

@fametrano

fametrano commented Nov 17, 2026 •

Copy link
Copy Markdown
Member Author

Findings on 4f22f1d: 0 open.

Round Head Reviewer Verdict
1 4dcc081 dedicated reviewer (Claude Code) CHANGES REQUESTED
2 3550093 dedicated reviewer (Claude Code) CLEARED
3 3550093 fresh reviewer (Codex) CLEARED
4 3550093 review bot (GitHub) ACK
4 3550093 Codex (GitHub) findings
4 3550093 CodeRabbit (GitHub) no actionable comments
5 3550093 Codex (GitHub), re-read findings
6 4f22f1d dedicated reviewer (Claude Code) CLEARED
7 4f22f1d fresh reviewer (Codex), delta CLEARED
# Raised by On Where Outcome Checked on
1 dedicated reviewer 4dcc081 tests/refused_type_name_test.py:143 accepted, 3550093 3550093
2 dedicated reviewer 4dcc081 tests/refused_type_name_test.py:13 accepted, 3550093 3550093
3 dedicated reviewer 4dcc081 commit message accepted, 3550093 3550093
4 dedicated reviewer 4dcc081 src/btclib/utils.py:432 accepted, 3550093 3550093
5 dedicated reviewer 4dcc081 src/btclib/utils.py:486 accepted, 3550093 3550093
6 dedicated reviewer 4dcc081 tests/refused_type_name_test.py:156 declined: parity with the sibling's text 3550093
7 fresh reviewer (Codex) 3550093 commit message accepted, to correct in the squash; body corrected 3550093
8 Codex (GitHub) 3550093 tests/refused_type_name_test.py:313 declined: a check of a count, not a stated one 4f22f1d
9 Codex (GitHub) 3550093 tests/refused_type_name_test.py:15 accepted, 4f22f1d 4f22f1d
1. Two assertions of the new test hold on CPython only, and PyPy 3.11 runs them in the os-* sweeps.

Class: a test asserting CPython-only behaviour that a PyPy cell runs.

tests/refused_type_name_test.py at 4dcc081, lines 143 and 158:

    assert type(vars(type)["__name__"].__get__(kind, type)) is _Name
    assert type(object().__str__).__name__ == "method-wrapper"

PyPy stores a str-subclass class name as an exact str and names that type method. 3550093 asserts the name's value and uses type("a-b", (), {}); the module passes on PyPy 3.11 and CPython 3.11, 3.14t and 3.15, and still fails on CPython where _type_name stops copying.

2. Three census docstrings claimed more reach than the census has.

Class: a docstring claiming more reach than the code has.

tests/refused_type_name_test.py from line 13 at 4dcc081:

of the chain (issue #3128). The census at the end keeps every other read
of a type's name out of `src/btclib`.

The census missed a type formatted whole (f"{type(x)}", repr, str) and a second string read in utils.py. 3550093 narrows the three sentences to what it reads and pins the one string in utils.py.

3. The commit message said a subclass's __len__ decides no length a refusal prints.

Class: a claim wider than the code it describes.

False outside _message_text (block/block_filter.py:420 prints len() of a caller's list). 3550093 says "decides no length _message_text prints"; the rest is ISS #3138.

4. `_message_text`'s docstring said a value is described by its length where `_length` gives one.

Class: a docstring narrower than the code's behaviour.

A value whose type name _type_name does not print gets no length. 3550093 says so, and the commit message's "What this breaks" lists it.

5. `_type_name`'s docstring said `_name_text` quotes only ASCII identifiers.

Class: a false comparison with a neighbouring helper.

_name_text quotes any str up to 16 characters. 3550093 reads "the most _name_text quotes of a name".

6. "a type whose name has 1 characters".

Class: wording.

Declined: the text is the sibling's, bip32-descriptors' _refusal._type_name, kept for parity.

7. The commit message says int_from_json_number's refusals carry no __context__.

Class: a claim wider than the code it describes.

Commit message of 3550093:

int_from_json_number's refusals carry no __cause__ and no __context__.

Called inside a caller's own except, the caller's exception is still their context, as it should be. The branch removes int()'s error from both. The body now says so; the squash message narrows the sentence the same way.

8. The census's tree assertion counts the string reads in utils.py.

Class: a check read as a stated count.

tests/refused_type_name_test.py from line 313 at 3550093:

    assert {name: len(read[1]) for name, read in reads.items() if read[1]} == {
        "utils.py": 1
    }

Declined: AGENTS.md's rule is about prose that states a count and goes stale; this line fails the suite when the count changes. Without it, a second string read appended to utils.py passed the census (finding 2).

9. Two docstrings stated how many string reads utils.py holds.

Class: a count of what a file holds, stated in prose.

tests/refused_type_name_test.py from line 13 at 3550093:

of the chain (issue #3128). The census at the end reads `src/btclib` for
an attribute read of `__name__` or `__qualname__`, and for either name
written as a string, which `utils` writes once. A type formatted whole,

Accepted: 4f22f1d writes "which only utils writes, to read type's own descriptor", and "a string of it only in utils" at line 304; a third count the writer found ("The one shape it spares") reads "What it spares".

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 3550093

No blocking or non-blocking findings.

Not checked: the AST census and cases in tests/refused_type_name_test.py were not run, since no interpreter is at hand. Grep agrees with what they assert. In src/btclib, __name__ and __qualname__ are read only in the four hand-written reprs and in the one vars(type)["__name__"] in utils.py. The classes with names longer than 16 characters are exactly _LONG_TYPE_NAMES.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 35500932da

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/refused_type_name_test.py Resolved
@fametrano

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 35500932da

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/refused_type_name_test.py Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 35500932da

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Two docstrings of tests/refused_type_name_test.py said how many string
reads of a type's name utils.py holds, and a third how many shapes the
census spares, against AGENTS.md's rule never to state how many of
anything a file holds. They now name the exception: only utils writes
the name as a string, to read type's own descriptor, and the census
spares type(self).__name__ in a class's own __repr__. The assertion
that pins utils.py to that read is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Ferdinando Ametrano <ferdinando@ametrano.net>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 4f22f1d

No blocking or non-blocking findings.

Not checked: tests/refused_type_name_test.py was not run, since no interpreter is at hand. The delta from 3550093 could not be fetched as a git diff. It was read instead from the docstrings of that module in the merged tree, which state no count.

@fametrano
fametrano merged commit f021c6a into main Nov 17, 2026
24 checks passed
@fametrano
fametrano deleted the type-name-refusals-3128 branch November 17, 2026 16:53
fametrano added a commit to PedroH0309/btclib that referenced this pull request Nov 18, 2026
main's int_from_json_number raises its refusals after the except block
(PR btclib-org#3141), and the branch reads float, Decimal and
Fraction through their base methods. The resolution keeps both: the
branch's reads inside the try, main's refusals after it, named by
_type_name.

Signed-off-by: Ferdinando Ametrano <ferdinando@ametrano.net>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A refusal of a type names the class as it names itself, so a class named by a key prints it

1 participant