Commit Graph

918 Commits

Author SHA1 Message Date
Jacob Alexander
5c1f6b2fe9 Prepare for v2.2.4 release
- Update CHANGELOG.md
2026-07-03 00:55:29 -07:00
ed-tsn
e2aaef8b6c Fix memory leak in _DynamicCapabilityClient._send_helper() (#398)
The heap-allocated Request object was never freed after send().
  Each RPC call leaked ~72 bytes, growing linearly with usage.

  Added del request after request.send() to free the Request once
  the RemotePromise has been constructed.
2026-07-03 00:08:47 -07:00
Jacob Alexander
6aa1849da6 Update docs and docs ci job to use uv 2026-07-02 23:48:12 -07:00
Jacob Alexander
4b2f92e9d1 Small ruff fixes 2026-07-02 17:53:36 -07:00
Jacob Alexander
9594d43e77 Fix uv sync / uv venv with pytest
uv sync
source .venv/bin/activate
cd test
python -m pytest .

- Update default bundled capnproto to 1.4.0
- Cleanup pyproject.toml
- Remove Pipfile and requirements.txt
2026-07-01 23:47:26 -07:00
Jacob Alexander
277483b963 Fix SIGSEGV on malformed Text field
C++ helper c_reraise_kj_exception() (capnp/helpers/capabilityHelper.cpp)
unconditionally dereferences the PyObject* returned by wrap_kj_exception_for_reraise()
(capnp/lib/capnp.pyx). For a specific class of malformed input -- a Cap'n Proto Text
field whose NUL terminator is corrupt -- the wrapper returns NULL, and the subsequent
"obj->ob_type" access dereferences NULL (offset 0x8) inside the C extension, producing
a deterministic, UNCATCHABLE SIGSEGV. libcapnp itself detects the corruption correctly
and would raise a catchable KjException for the sibling code path; only this reraise
helper crashes.

The malformed bytes reach the crash through the documented public API
Type.from_bytes(...) + lazy field access -- exactly how pycapnp consumers deserialize
untrusted Cap'n Proto messages received over the network / RPC / from files. A single
flipped byte in an attacker-controlled message takes down the consuming process; the
crash cannot be caught with try/except, so no graceful degradation is possible.
2026-07-01 23:06:40 -07:00
Jacob Alexander
6f70b8d737 ci: build libcapnp for the target arch on macOS
The macos-15 runner is arm64. Previously, cp38 was the first Python in
the cibuildwheel matrix, and because the cp38 macOS installer is
x86_64-only, cibuildwheel ran the build under \`arch -x86_64\`, which
also caused CMake to build libcapnp as x86_64. Subsequent Python
versions then reused that cached x86_64 libcapnp.

After dropping cp38, cp39 is built first and CMake auto-detects the
host arch (arm64), producing an arm64 libkj/libcapnp. The x86_64 wheel
then silently links via \`-undefined dynamic_lookup\` (the linker just
ignores arm64 archive members) and fails at dlopen time with
"symbol not found in flat namespace ... AsyncIoStream::getsockopt".

Set CMAKE_OSX_ARCHITECTURES to the matrix arch on macOS so libcapnp is
always built for the wheel's target architecture.
2026-05-30 11:59:52 -07:00
Jacob Alexander
9b65eded52 ci: speed up wheel builds, defer exotic arches to release tags
- Build aarch64 wheels on native ubuntu-24.04-arm runners instead of
  QEMU emulation (massive speedup on every push/PR).
- Move ppc64le and s390x QEMU builds into a separate job that only
  runs on refs/tags/v* and skips tests (still extremely slow under
  emulation, but no longer gates regular CI).
- Drop EOL CPython 3.8 builds, which also removes the macOS
  x86_64-only-installer warning.
- Include arch in artifact names to make them easier to identify.
2026-05-30 11:59:52 -07:00
Jacob Alexander
641554808e ci: bump actions to Node 24 runtimes and clean up cibuildwheel config
- Bump actions/upload-artifact to v6, actions/setup-python to v6,
  actions/checkout to v5, and docker/setup-qemu-action to v4 so all
  actions run on Node 24 (Node 20 is deprecated on GitHub runners).
- Bump pypa/cibuildwheel to v3.4.1 so its bundled actions/setup-python
  also runs on Node 24.
- Drop CIBW_SKIP=pp*: PyPy is no longer enabled by default in
  cibuildwheel 3.x, so the selector matched nothing and triggered an
  "Invalid skip selector" warning.
- Add CIBW_TEST_SKIP for cp38 macOS arm64 to silence the cibuildwheel
  warning that the arm64 slice of cp38 universal2 wheels can't be tested
  (the cp38 installer is x86_64-only).
2026-05-30 11:59:52 -07:00
Jacob Alexander
e94fae1cfe Prepare for v2.2.3 release
- Update CHANGELOG.md
2026-05-30 11:59:52 -07:00
Jacob Alexander
fb3408f81d release-pypi.sh: add --test flag for dry-run uploads to TestPyPI
Passes --repository testpypi to twine upload, prints the target index
before the confirmation prompt, and documents the new flag in the README
along with a link to the TestPyPI guide.
2026-05-30 11:59:52 -07:00
Jacob Alexander
55e056e990 Add scripts/release-pypi.sh for downloading CI artifacts and uploading to PyPI
Automates the post-tag release flow: resolve the latest successful Build
workflow run for a given tag (or take an explicit run ID), download the
cibw-* artifacts via gh, flatten wheels/sdists into a dist_<ver>/ directory,
and upload via twine from a dedicated .venv-release/ virtualenv.

Also documents the release flow in README.md.
2026-05-30 11:59:52 -07:00
Jacob Alexander
88fe25372d ci: deploy docs to gh-pages on tagged releases
Trigger the Docs workflow on version tags (v*) and add a deploy job
that publishes the built Sphinx HTML to the gh-pages branch using
peaceiris/actions-gh-pages. PRs and branch pushes still build (and
now upload an artifact) but do not deploy.
2026-05-30 11:59:52 -07:00
Jacob Alexander
162fddbcf6 Replace black and flake8 with ruff for linting and formatting
- Remove .flake8; add [tool.ruff] and [tool.ruff.format] config in pyproject.toml
  (line-length 120, excludes, ignore list, per-file-ignores, mccabe complexity)
- Update GitHub workflow lint job to run `ruff check .` and `ruff format --check .`
- Swap black and flake8 for ruff in requirements.txt and Pipfile
- Change capnp/__init__.py to ruff-style noqa comment
- Move max-complexity into [tool.ruff.lint.mccabe], lint options into [tool.ruff.lint]
- Add per-file-ignores for capnp/__init__.py (F401, F403, F405), remove inline noqa
- Run ruff format across codebase (24 files) for consistent style
2026-05-30 11:59:52 -07:00
Atsushi Abe
a27c849021 fix: skip schema lookup when value is not a str (#401)
Since 84674909 (#351, "added binary support in dictionaries via base64
encoding"), `_DynamicStructBuilder.from_dict` does a
`self.schema.fields.get(key)` lookup for every key in the input dict.
The lookup was added so that `str` values destined for a `Data` field
can be base64-decoded, but the lookup itself runs unconditionally, even
when the value is `bool`, `int`, `dict`, `list`, `bytes`, etc.
2026-05-30 11:59:21 -07:00
Brian Xu
76a41c8efe refine documentation for PyCustomMessageBuilder (#395)
* refine document for py custom message builder

* refine example

* refine example
2026-01-31 13:15:56 -08:00
Liam Murphy
aa90ab6844 Fix test failures on Python 3.14 (#394)
* Fix test failures on Python 3.14

As documented at
https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop,
`get_event_loop` now fails if there is no active event loop. Since there
will never already be one at the top level of a file anyway, explicitly
create a new one every time.

* Reformat with black 2026 style
2026-01-26 07:09:49 -08:00
Jacob Alexander
93ba29f916 Prepare for v2.2.2 release
- Update CHANGELOG.md
2026-01-16 20:30:01 -08:00
Jacob Alexander
c9541f98b3 Update macOS builds from 13 to 15 (#393)
- See https://github.com/actions/runner-images/issues/13046
- macOS 15 will be the last release that supports intel macs and
  supported until August 2027
2026-01-16 07:30:50 -08:00
Brian Xu
9237ba123a Revert Data fields to bytes and add get_data_as_view for zero-copy access (#390)
* get data field with view

* refine tc

* refine based on flake check

* run black again

* rebase upstream master

* add comment to tc

* refine raise exception
2026-01-15 21:40:22 -08:00
André Cruz
9754258d46 Fix use-after-free in async write causing corruption with large payloads (#392)
In _PyAsyncIoStreamProtocol.write_loop(), memoryview objects pointing to
C++ message memory were passed directly to transport.write(). Since
transport.write() is non-blocking and only queues data for later
transmission, the memoryview could reference freed memory after
fulfill() was called.

This caused message corruption when pipelining RPC calls with payloads
larger than ~4000 bytes, as the C++ message memory would be freed before
asyncio had a chance to transmit the data.

The fix copies the data to Python bytes objects before passing to
transport.write(), ensuring the data remains valid until asyncio
transmits it.

Includes regression test that verifies large payload integrity with both
sequential and pipelined RPC calls.
2026-01-15 16:35:50 -08:00
Jacob Alexander
d349dfbd39 Prepare for v2.2.1 release
- Update CHANGELOG.md
2025-10-21 15:48:51 -07:00
Brian Xu
c14fd7036a Make message.to_dict() return bytes for DATA type field (#386)
* change to_dict return bytes for DATA type

* reformat

* reformat

* add includes .h

---------

Co-authored-by: Brian Xu <brian.xu1@bytedance.com>
2025-09-30 07:48:10 -07:00
Jacob Alexander
a99ca72902 Fix formatting/syntax issues with docs 2025-09-12 07:53:16 -07:00
Jacob Alexander
9704c9b6bf Prepare for v2.20 release
- Update CHANGELOG.md
2025-09-12 07:41:35 -07:00
Brian Xu
84674909a2 Support python custom message builder and make Data field's type return MemoryView (#380)
This PR is for resolving the following issue:
[issue](https://github.com/capnproto/pycapnp/issues/379)

1. Created `_PyCustomMessageBuilder` extends `MessageBuilder`, enabling the ability to customise the `SegmentAllocate` method in Python. This allows allocation and data population within shared memory, and supports zero-copy inter-process data transfer by passing segment offsets.

2. Fields of type `Data` now support being set with a `memoryview`. When retrieving a `Data` field from a `DynamicStructBuilder`, it will return a writable `memoryview`, allowing users to modify the data directly. This enables memory to be pre-allocated and content to be modified in later, eliminating an extra copy. When retrieving a `Data` field from a `DynamicStructReader`, it will return a read-only `memoryview`, allowing user to read data without memory copy.

* add memoryview and custom builder

* support set dynamic field

* add curSize

* add initialSize and lastSize

* change StringPtr name

* add test case

* refine test case

* convert func to py callable object

* add initial value

* refine example

* add copy as_reader and new_message, make structReader's data field return RO memoryView

* rebase master and bugfix

* reformat flake8

* refine test case

* refine test cases for blob

* remove unused import for flake8

* run black .

---------

Co-authored-by: Brian Xu <brian.xu1@bytedance.com>
2025-09-10 06:48:58 -07:00
Yevhenii Kizim
62682977cb add schema for tests 2025-09-06 19:14:58 -07:00
Yevhenii Kizim
144acbea7a Add structure-free read_multiple_bytes_packed
Motivation: A server sends data packages that consist of multiple
serialized capnproto messages of different structures. Every message is
guaranteed to have the same first field, which works as a message header
containing information about the message structure type.
The scheme comprises the `UnknownMessage` structure that allows parsing
the header only.

Solution: provide a public interface that iterates buffer with
AnyPointer readers to cast a message to `UnknownMessage` first and then
to a specific structure type.
2025-09-06 19:14:58 -07:00
Dominik Andreas
237fa7dd4b add test/blob_test.capnp 2025-09-06 11:37:18 -07:00
Dominik Andreas
ed461ed2f5 added binary support in dictionaries via base64 encoding 2025-09-06 11:37:18 -07:00
Jacob Alexander
3a3adfb5f1 Prepare for v2.1.0 release
- Update CHANGELOG.md
2025-09-04 07:30:46 -07:00
Lee J. O'Riordan
ab6b6bca90 modify wildcard to disable free threaded py314 also 2025-09-03 23:17:36 -07:00
Lee J. O'Riordan
19acf378d6 Disable Py3.14 in favour of released Py only 2025-09-03 23:17:36 -07:00
Lee J. O'Riordan
4a70b3ed73 Update wheelbuilding on GH actions 2025-09-03 23:17:36 -07:00
Tino Wagner
ef0f46a1c9 Fix deprecation warning when importing a schema
`load_module` has been deprecated since Python 3.4. A warning is issued
in recent releases:

> ImportWarning: _Loader.exec_module() not found; falling back to load_module()

See: https://docs.python.org/3/library/importlib.html#importlib.abc.Loader.load_module
2025-09-03 07:36:06 -07:00
Lasse Blaauwbroek
a89eb0dee6 Upgrade cibuildwheel and surrounding CI infra 2025-05-12 15:54:19 -07:00
Lasse Blaauwbroek
4d5cc20764 Avoid storm of 'warning: moving a temporary object prevents copy elision'
Sometimes, Cython seems to insert too many move() functions. This is not a
problem, but the logs are full of them. We avoid this by first assigning values
to an intermediate value
2025-05-12 15:54:19 -07:00
Lasse Blaauwbroek
b8e51dcaf8 Generate a new certificate that is compatible with strict x509 checking
This is now checked by default in Python 3.13
2025-05-12 15:54:19 -07:00
Lasse Blaauwbroek
db129685e6 Make license information SPDX-compatible (as recommended by the build system) 2025-05-12 15:54:19 -07:00
Lasse Blaauwbroek
1d88b6e346 Remove usage of deprecated kj::mvCapture functions 2025-05-12 15:54:19 -07:00
Lasse Blaauwbroek
983719fde9 Upgrade Cython to version 3
While looking at #333, I hypothesized that upgrading Cython might solve the
issue. It didn't. But upgrading should still happen at some point. This is my
work in progress on that. The tests pass, but there are two main things missing:

Problem (1):
Starting with Cython 3, you can only do `except+` or `except
+reraise_kj_exception` on `extern` functions coming from C++. (This makes sense,
and the way things were declared in Pycapnp wasn't too good.) As a result, I had
to remove a lot of these declaration. This results in some segmentation faults,
because Cython no longer detects C++ exceptions and converts them to Python
exceptions in some places.

To solve this, all `extern` declarations in `.pxd` files have to be examined and
`except +reraise_kj_exception` clauses need to be added to anything that might
throw. Previously, this was done really inconsistently. The lazy solution would
be to just add the clause everywhere, but I'm not sure what the performance
implications are.

Problem (2):
The compilation output of `python setup.py build_ext --inplace` is now full of messages like these:
```
capnp/lib/capnp.cpp: In function ‘PyObject* __pyx_f_5capnp_3lib_5capnp_18_DynamicListReader__get(__pyx_obj_5capnp_3lib_5capnp__DynamicListReader*, int64_t, int)’:
capnp/lib/capnp.cpp:4871:51: warning: moving a temporary object prevents copy elision [-Wpessimizing-move]
 4871 |   #define __PYX_STD_MOVE_IF_SUPPORTED(x) std::move(x)
      |                                          ~~~~~~~~~^~~
capnp/lib/capnp.cpp:20944:59: note: in expansion of macro ‘__PYX_STD_MOVE_IF_SUPPORTED’
20944 |   __pyx_t_2 = __pyx_f_5capnp_3lib_5capnp_to_python_reader(__PYX_STD_MOVE_IF_SUPPORTED((( ::capnp::DynamicValue::Reader)__pyx_t_7)), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 419, __pyx_L1_error)
      |                                                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~
capnp/lib/capnp.cpp:4871:51: note: remove ‘std::move’ call
 4871 |   #define __PYX_STD_MOVE_IF_SUPPORTED(x) std::move(x)
      |                                          ~~~~~~~~~^~~
capnp/lib/capnp.cpp:20944:59: note: in expansion of macro ‘__PYX_STD_MOVE_IF_SUPPORTED’
20944 |   __pyx_t_2 = __pyx_f_5capnp_3lib_5capnp_to_python_reader(__PYX_STD_MOVE_IF_SUPPORTED((( ::capnp::DynamicValue::Reader)__pyx_t_7)), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 419, __pyx_L1_error)
      |                                                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~
```
There are to many `move` calls inserted. I'm not sure if this is a Cython issue,
or if we are somehow annotating things wrong. Might be worth asking the Cython
people.

I'm not planning on working on this further in the short term. If someone wants
to take over on this, feel free.
2025-05-12 15:54:19 -07:00
Karl Velicka
59a639fa97 Include _custom_build in sdist
This fixes build issues for installations that cannot use wheels
published on PyPI. Issue #364 would be fixed by this.

Python build tools like `python -m build` first build a source
distribuiton (sdist) and then use it (and only it) to build a binary
wheel from. This doesn't work if one of the build scripts isn't in the
sdist however, which was the case prior to this patch.
2024-09-25 07:29:27 -07:00
Yian Chen
78dd54e641 address flake8 format check 2024-04-11 19:01:59 -07:00
Jacob Alexander
1fb168796d Prepare for v2.0.0 release
- Update CHANGELOG.md
2024-01-19 08:35:01 -08:00
Jacob Alexander
1f2349ab45 Update README.md
Cap'n'proto has transitioned to GitHub Mailing Lists
2023-11-25 11:10:25 -08:00
Jacob Alexander
84830d6357 Prepare for v2.0.0b2 release
- Update CHANGELOG.md
2023-11-25 11:04:29 -08:00
Lasse Blaauwbroek
3aade70bfa Some fixes to the magic import system
- Stop adding the directory of every .capnp file to the import path. If a .capnp
  file wants to import a file in its own directory, it should use a relative
  import. Fixes #278
- Stop using /usr/include/capnp as an import path. This is incorrect. It should
  only be /usr/include.
- Stop allowing additional paths to be specified for magic imports. This leads
  to inconsistencies. More specifically, the way that a nested import like
  `ma.mb.mc_capnp` gets imported by python, is to first import `ma`, then import
  `ma.mb`, and finally `ma.mb.mc_capnp`. Pycapnp's magic importing is only
  involved in the last step. So any additional paths specified don't work for
  nested imports. It is very confusing to only have this for non-nested imports.
  Users with folder layouts that don't follow pythons import paths can still use
  `capnp.load(.., .., imports=[blah])`.
2023-11-25 08:16:38 -08:00
Lasse Blaauwbroek
b6ea909e9a Corner case for cancelled server methods that raise exceptions
When a server method is cancelled, but it nonetheless raises an exception (other
than `CancelledError`), this exception cannot be reported to the caller (because
it has cancelled that call).

The only place where it can go is to the asyncio exception handler...
2023-11-09 09:10:39 -08:00
Lasse Blaauwbroek
0ec4d0b778 Allow cancellation of all capability contexts 2023-11-08 07:09:10 -08:00
Lasse Blaauwbroek
49bda5ccae Fix re-raising of KjException
- The `KjException._to_python()` function neglected to check if the wrapper was
  set when attempting to convert to `AttributeError`, leading to exceptions while
  raising an exception.
- The syntax `raise A, B, C` hasn't existed since Python 3. The only reason it
  works is because Cython supports it. Lets get rid of it.
- There was an attempt to convert a certain kind of `KjException` to an
  `AttributeError`. However, the original exception remains in the context when
  the new exception is raised. This is confusing. We get rid of the original
  exception by doing `raise e._to_python() from None`.
2023-11-08 07:04:27 -08:00