Commit Graph

218 Commits

Author SHA1 Message Date
Adeeb Shihadeh
899416423f Remove unused APIs 2026-09-21 19:26:21 -07:00
Adeeb Shihadeh
5befba15f3 Minimal pycapnp 2026-09-21 18:57:37 -07:00
Trey Moen
a0cb5cdf06 fix: check field type via C++ schema in from_dict to avoid a reference cycle (#407)
from_dict called self.schema.fields for str values, which builds
_StructSchemaField wrappers that reference the schema, so every
message built via kwargs stayed alive until a GC pass. Follow-up to
#401, which only skipped the lookup for non-str values.
2026-09-21 17:26:44 -07:00
leoherz.liu
8b56bb8140 Fix: get_data_as_view retaion the backing reader/builder even after the view is released, leading to memory leakage (#406)
* fix: return empty memoryview for uninitialized DATA fields

Use a module-level sentinel when Cap'n Proto reports a NULL pointer with
zero size so PyBuffer_FillInfo receives a valid address for unset fields.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: release buffer info if memoryview construction fails

PyBuffer_FillInfo pins `self` via buf.obj; call PyBuffer_Release on failure
so that reference is not leaked. This is safe for sentinel-backed empty views:
PyBuffer_Release only decrements buf.obj and does not free buf.buf.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs: clarify lifetime rules for zero-copy buffer views

Document borrowing semantics, mutation hazards, and empty DATA field
behavior for get_data_as_view and to_segment_views.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: pin DATA field views via shared buffer exporter

Replace PyMemoryView_FromBuffer with a _BorrowedBufferView holder and
PyMemoryView_FromObject so get_data_as_view() correctly pins the struct
reader/builder for the memoryview lifetime. Generalize the same exporter
for to_segment_views() and add regression tests for packed payload release.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: bigtailfox <leoherz.liu@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 21:06:36 -07:00
leoherz.liu
40189f91fc Add to_segment_views for zero-copy serialization (#405)
Co-authored-by: bigtailfox <leoherz.liu@gmail.com>
2026-07-03 16:45:34 -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
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
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
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
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
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
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
ed461ed2f5 added binary support in dictionaries via base64 encoding 2025-09-06 11:37:18 -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
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
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
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
Lasse Blaauwbroek
ef5e039067 Support _DynamicListReader in _setDynamicField
See the test for an explanation.

Note that I'm not sure what the purpose of `_setDynamicFieldWithField` and
`_setDynamicFieldStatic` is. It does not appear to be used. I've kept them for
now (they are a public API), but perhaps this can be removed.
2023-11-08 07:02:09 -08:00
Lasse Blaauwbroek
aafec2281e Make reraise_kj_exception available to downstream
I'm using Pycapnp in a project, where we compile `.capnp` files directly to
Cython instead of using the dynamic interface (for speed). For this, we need
access to the `reraise_kj_exception` C function defined by Pycapnp. This is not
possible, because Cython does not automatically make this function available to
downstream users.

My previous solution, in #301, was rather flawed. The  file `capabilityHelper.cpp`, where
`reraise_kj_exception` is defined, was bundled into the distribution, so that
this file could be included in downstream libraries. This turns out to be a
terrible idea, because it redefines a bunch of other things like
`ReadPromiseAdapter`. For reasons not entirely clear to me, this leads to
segmentation faults. This PR revers #301.

Instead, in this PR I've made `reraise_kj_exception` a Cython-level function,
that can be used by downstream libraries. The C-level variant has been renamed
to `c_reraise_kj_exception`.
2023-11-05 13:58:13 -08:00
Fabio Rossetto
42665a61c9 Properly join list of methods in _DynamicCapabilityClient
This was already fixed in c9bea05f44, but the fix does not seem to work.
This commit uses a set union, which should be more robust. It also adds
a couple of assertions to verify that it indeed works.
2023-11-01 19:03:11 -07:00
lewinb-corp
c9bea05f44 DynamicCapabilityClient: fix crash due to wrong types
In the last commit touching this line, a ')' was put in the wrong place, leading to errors like this one:

```
  File "capnp/lib/capnp.pyx", line 2172, in capnp.lib.capnp._DynamicCapabilityClient.__dir__
TypeError: unsupported operand type(s) for +: 'set' and 'tuple'
```
2023-10-23 10:48:47 -07:00
Lasse Blaauwbroek
ca8d120901 Handle exceptions from server callbacks
In its current form, when a server callback throws an exception, it is
completely swallowed. Only when the asyncio loop is being shut down might one
possibly see that error. On top of that, the connection is never closed, causing
any clients to hang, and a memory leak in the server.

This is a proposed fix that reports the exception to the asyncio exception
handler. It also makes sure that the connection is always closed, even if the
callback doesn't close it explicitly.

Note that the design of AsyncIoStream is directly based on the design of
Python's asyncio streams: https://docs.python.org/3/library/asyncio-stream.html
These streams appear to have exactly the same flaw. I've reported this here:
https://github.com/python/cpython/issues/110894. Since I don't really know what
I'm doing, it might be worth seeing what kind of solution they might come up
with and model our solution after theirs.
2023-10-22 23:29:47 -07:00
Mike Laiosa
09f7cd0d08 Unlock the GIL for all capnp functions that do IO
IO might block, and its rude to block while holding the GIL, since that
prevents other threads from running.
2023-10-16 13:51:27 -07:00
Lasse Blaauwbroek
a30fd77a1c Fix retransmit bug for large messages causing message corruption
Logic bug: We are looping over segments sent by the C++ library and sending them
over a python transport. If the last message is larger than the transport pause
threshold, this causes the transport to pause us. In that case, we forget to
increment the current write_index, causing us to retransmit the same message in
an infinite loop.

This is a serious bug, because it causes messages to become corrupted.
2023-10-16 11:06:49 -07:00
Tobias Ahrens
302a96d84d Update documentation to async code (#331) (#332)
* Update documentation to async code (#331)

This commit updates the documentation to the latest changes added
with pycapnp 2.0.0.

* Remove non existing classes/functions from the reference documentation
* Adapt the quickstart to the latest changes. Mainly to new rpc handling,
  that now exlusively is done through asyncio.

* DOC: Add section about send and receive messages over a socket

Since #313 it is possible to read and write messages over a socket.
This commit adds a small section for read and write in the quickstart.
2023-10-16 11:05:27 -07:00
Lasse Blaauwbroek
1446386636 Make a server fail early when the KJ loop is not running 2023-10-15 08:10:54 -07:00
Lasse Blaauwbroek
cc088211dc Delete and update some Python 3.7-specific todo notes
When I wrote some of these, I was wrong about the affected versions. Upgraded
them to v3.9
2023-10-13 07:55:57 -07:00
Lasse Blaauwbroek
b22763f3c6 Fix 'AttributeError: '_UnixSelectorEventLoop' object has no attribute 'call_soon'
See haata/pycapnp#1 for a discussion. The cause of this bug is still unknown to
me. But it likely has been fixed in Python 3.10. For some crazy reason, you can
just keep retrying the offending call, and the attribute will magically
'reappear'.
2023-10-13 06:47:25 -07:00
Tobias Ahrens
bb15822850 Fixes for capnp 1.0 (#1)
* add capnp_api.h to gitignore

* Change type of read_min_bytes from size to int

Not sure why this was not causing issues before or if that
is the right fix ... but it seems to be fine :)

* Adapt python_requires to >=3.8

This was overlooked when 3.7 was deprecated. The ci no longer
works with python 3.7 and cibuildwheel uses python_requires ...

* Replace deprecated find_module with find_spec (importlib)

find_module was deprecated with python 3.4 and python 3.12
removed it (https://docs.python.org/3.12/whatsnew/3.12.html#importlib).

The new command is find_spec and only required a few adaptions
2023-10-11 11:28:24 -07:00
Jacob Alexander
313d0d4c6d Prepare for v2.0.0b1 release
- Update CHANGELOG.md
- Update to bundled capnproto-1.0.1
  * Compiles with capnproto-0.8.0 and higher
- *Breaking Change* Remove allow_cancellation (see
  https://capnproto.org/news/2023-07-28-capnproto-1.0.html)
  * This is tricky to handle for older versions of capnproto. Instead of
    dealing with lots of complication, removing it entirely.
- Fix some documentation after the build backend support was added
- Update tox.ini to support 3.8 to 3.12
- Update cibuildwheel to 2.16.1
  * Adds Python 3.12 supports and implicitly deprecates EOL 3.7 (though it's
    still built)
2023-10-03 12:29:48 -07:00
Lasse Blaauwbroek
e13a0c9254 Experiment: Wrap all capnp code in a context-manager to avoid segfaults (#317)
* Experiment: Wrap all capnp code in a context-manager

* Fix segfault in on_disconnect
2023-10-03 09:04:51 -07:00
Rowan Reeve
a5c29a74d2 Schema loading from the wire
Cap'n Proto provides a schema loader, which can be used to dynamically
load schemas during runtime. To port this functionality to pycapnp,
a new class is provided `C_SchemaLoader`, which exposes the Cap'n
Proto C++ interface, and `SchemaLoader`, which is part of the pycapnp
library.

The specific use case for this is when a capnp message contains
a Node.Reader: The schema for a yet unseen message can be loaded
dynamically, allowing the future message to be properly processed.

If the message is a struct containing other structs, all the schemas for
every struct must be loaded to correctly parse the message. See
https://github.com/DaneSlattery/capnp_generic_poc for a
proof-of-concept.

Add docs and cleanup

Add more docs

Reduce changes

Fix flake8 formatting

Fix get datatype
2023-06-12 14:10:13 +02:00
Lasse Blaauwbroek
1e94f2e321 Remove the option to create servers through _new_server.
Inheritance is required now to create a server
2023-06-11 04:09:03 +02:00
Lasse Blaauwbroek
83d610c116 Remove some more c++ helper functions 2023-06-11 03:50:54 +02:00
Lasse Blaauwbroek
0483596da1 Miscellaneous 2023-06-09 22:05:12 +02:00
Lasse Blaauwbroek
d6261b6d79 Manually handle deallocation of some objects for the benefit of p3.7
Python 3.7 seems to have trouble dealocating objects in a timely fashion. We
rely on this, because the c++ destructors need to run before the kj event loop
is closed. Hence, we do it manually.
2023-06-09 22:05:12 +02:00
Lasse Blaauwbroek
74ebaff4e3 Make older python versions work 2023-06-09 22:05:05 +02:00
Lasse Blaauwbroek
770be41b6d Bugfix: Attach server to on_disconnect to prevent early closing 2023-06-08 08:11:23 +02:00
Lasse Blaauwbroek
7a8175ed84 Get rid of VoidPromise and (almost) Promise
We only retain RemotePromise for its pipelining capabilities.
2023-06-08 08:02:07 +02:00
Lasse Blaauwbroek
da6a07efd5 No more need for promise joining 2023-06-08 05:34:04 +02:00
Lasse Blaauwbroek
20868d7db0 Get rid of dead code 2023-06-08 04:13:59 +02:00
Lasse Blaauwbroek
4b5c4211f1 Force server methods to be async and client calls to use await 2023-06-08 03:56:57 +02:00
Lasse Blaauwbroek
a69bc72a0b Remove a bunch of unused code 2023-06-08 02:42:04 +02:00
Lasse Blaauwbroek
97bdeaea12 Disable option to run capnp without asyncio 2023-06-08 02:27:38 +02:00
Lasse Blaauwbroek
6e011cfe78 Get rid of capnp timer functionality.
The asyncio timer should now be used
2023-06-07 20:55:43 +02:00