* 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>
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.
- 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
* 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
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.
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>
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.
- 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])`.
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.
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.
* 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
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
All of these tests also exist in test_capability.py. The only difference is the
way the .capnp file is loaded. But that could be tested with much less code.
* Integrate the KJ event loop into Python's asyncio event loop
Fix#256
This PR attempts to remove the slow and expensive polling behavior for asyncio
in favor of proper linking of the KJ event loop to the asyncio event loop.
* Don't memcopy buffer
* Improve promise cancellation and prepare for timer implementation
* Add attribution for asyncProvider.cpp
* Implement timeout
* Cleanup
* First round of simplifications
* Add more a_wait functions and a shutdown function
* Fix edge-cases with loop shutdown
* Clean up calculator examples
* Cleanup
* Cleanup
* Reformat
* Fix warnings
* Reformat again
* Compatibility with macos
* Inline the asyncio loop in some places where this is feasible
* Add todo
* Fix
* Remove synchronous wait
* Wrap fd listening callbacks in a class
* Remove poll_forever
* Remove the thread-local/thread-global optimization
This will not matter much soon anyway, and simplifies things
* Share promise code by using fused types
* Improve refcounting of python objects in promises
We replace many instances of PyObject* by Own<PyRefCounter> for more automatic
reference management.
* Code wrapPyFunc in a similar way to wrapPyFuncNoArg
* Refactor capabilityHelper, fix several memory bugs for promises and add __await__
* Improve promise ownership, reduce memory leaks
Promise wrappers now hold a Own<Promise<Own<PyRefCounter>>> object. This might
seem like excessive nesting of objects (which to some degree it is, but with
good reason):
- The outer Own is needed because Cython cannot allocate objects without a
nullary constructor on the stack (Promise doesn't have a nullary constructor).
Additionally, I believe it would be difficult or impossible to detect when a
promise is cancelled/moved if we use a bare Promise.
- Every promise returns a Owned PyRefCounter. PyRefCounter makes sure that a
reference to the returned object keeps existing until the promise is fulfilled
or cancelled. Previously, this was attempted using attach, which is redundant
and makes reasoning about PyINCREF and PyDECREF very difficult.
- Because a promise holds a Own<Promise<...>>, when we perform any kind of
action on that promise (a_wait, then, ...), we have to explicitly move() the
ownership around. This will leave the original promise with a NULL-pointer,
which we can easily detect as a cancelled promise.
Promises now only hold references to their 'parents' when strictly needed. This
should reduce memory pressure.
* Simplify and test the promise joining functionality
* Attach forgotten parent
* Catch exceptions in add_reader and friends
* Further cleanup of memory leaks
* Get rid of a_wait() in examples
* Cancel all fd read operations when the python asyncio loop is closed
* Formatting
* Remove support for capnp < 7000
* Bring asyncProvider.cpp more in line with upstream async-io-unix.c++
It was originally copied from the nodejs implementation, which in turn copied
from async-io-unix.c++. But that copy is pretty old.
* Fix a bug that caused file descriptors to never be closed
* Implement AsyncIoStream based on Python transports and protocols
* Get rid of asyncProvider
All asyncio now goes through _AsyncIoStream
* Formatting
* Add __dict__ to PyAsyncIoStreamProtocol for python 3.7
* Reintroduce strange ipv4/ipv6 selection code to make ci happy
* Extra pause_reading()
* Work around more python bugs
* Be careful to only close transport when this is still possible
* Move pause_reading() workaround
- Full cleanup of all the docs
- General sphinx housekeeping
- Updated all the old/bad links
- More reliable tests
- Updated Changelog
- Removed dead/deprecated code
- Added documentation generation test
- Includes some test stabilization
- Fixes manylinux2010 build issues (linker flag order due to old gcc)
- More rigorous python setup.py clean
- Requires capnproto v0.8.0 or greater
- Including system libcapnp include path for import (e.g. import
stream_capnp)
- Bundle libcapnp .capnp files when not using system libcapnp
- Removing more distutils usage. Now using pkg-config to determine the
system version of libcapnp (mainly for Linux, but should work on macOS
with brew)
- Removed dead code
Resolves issues #215#216#217
Lots of fixes for Issue #218 (all sorts of retry methods needed for
GitHub Actions)