numbox.utils
The rest of numbox depends on the modules of numbox.utils. A program can also use several of these modules directly.
make_structref() defines a numba StructRef in one call.
cres() compiles a function into a value that jitted code can take as an argument, an
instance of DeriveWAP. lowlevel, meminfo, cstrings and pysqlite_bridge
pass pointers between Python, jitted code and C libraries. preprocessing, digest and fingerprint let numbox
cache the code that it generates at run time and distinguish one version of that code from another. timer times
calls made from Python.
numbox.utils.highlevel
Dynamically defining StructRef
Defining a numba
StructRef, a
mutable structure that Python code and jitted code share by reference, requires writing a lot of boilerplate code.
make_structref() defines a StructRef type in one call, and the code it generates supports
caching. It needs a type class: an empty subclass of numba’s StructRef, registered with numba’s @register. numba
uses the type class as the class of the struct’s numba type. If the type class is defined in the script that you run,
every run after the first fails, as shown below. Define the type
class in a separate module that your program imports instead, such as type_classes.py:
from numba.experimental.structref import register
from numba.core.types import StructRef
@register
class DataStructTypeClass(StructRef):
pass
Then define the struct in a different module, main.py:
from numba.core.types import float32, unicode_type
from numpy import isclose
from numbox.utils.highlevel import make_structref
from type_classes import DataStructTypeClass
def derive_output(struct_):
if struct_.control == "double":
return struct_.value * 2
else:
return struct_.value
data_struct = make_structref(
"DataStruct",
{"value": float32, "control": unicode_type},
DataStructTypeClass,
struct_methods={
"derive_output": derive_output
}
)
if __name__ == "__main__":
data_1 = data_struct(3.14, "double")
data_2 = data_struct(2.17, "something else")
assert isclose(data_1.derive_output(), 6.28)
assert isclose(data_2.derive_output(), 2.17)
make_structref returns the struct’s class, here data_struct. Calling the class builds a struct, in Python or in
jitted code. Each function in struct_methods becomes a method that Python and jitted code can call, and the method
receives the struct as its first argument. In a third file, run.py, a cached jitted function builds a struct and
calls its method:
from numba import njit
from main import data_struct
@njit(cache=True)
def use(value):
return data_struct(value, "double").derive_output()
print(use(3.14)) # 6.28000020980835
The fields may also be given as a sequence of names, such as ("value", "control"). numba then infers the field types
from the arguments of each call to the class, so two calls can build structs whose fields have different types. Each
struct needs a type class of its own: a second make_structref call with the same class, in the same process, raises
KeyError: "duplicate registration for <class 'type_classes.DataStructTypeClass'>".
If the second run fails with “No conversion”
The type class must be defined in a module that the script imports, not in the script itself. numba pickles the struct’s
numba type into its cache, along with the compiled constructor. The pickler stores a class from the running script by
value. In the next run, numba therefore loads a copy of the type class from the cache, not the class that the script has
just defined. The two classes have the same name, but numba cannot convert one to the other, and every run after the
first fails at the make_structref call:
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No conversion from numba.DataStructTypeClass(('value', float32), ('control', unicode_type)) to
numba.DataStructTypeClass(('value', float32), ('control', unicode_type)) for '$26return_value.5', defined at None
File ".../numbox-structref/DataStruct_b62da08f4520823e.py", line 45:
def make_datastruct(value, control):
return DataStruct(value, control)
^
The No conversion error means that the cached constructor returns a struct of the copied class. numbox writes each
struct’s generated code to a file of its own, the struct’s cache anchor, which the message quotes (where the
generated code is written). Move the type class to an imported module, as
type_classes.py above, and then delete the struct’s cache files, which still hold the copy. Their names start with
the anchor’s name, here DataStruct_b62da08f4520823e. They are in the __pycache__ directory beside the anchor or,
when NUMBA_CACHE_DIR is set, in a directory under it whose name starts with numbox-structref_.
If a method cannot find a global name
A method’s source is copied into the generated code, which runs in a namespace of its own, not in the method’s module. A
module or a function that the method reads as a global, such as np or a jitted helper, is therefore not defined in
that namespace. The first call of the method fails with a TypingError whose text includes
NameError: name 'np' is not defined. Pass each such global to make_structref in its ns argument, as in
ns={"np": np}. The values in ns that a method reads become part of the method’s fingerprint, which the section
on numbox.utils.fingerprint describes. A new value therefore changes the generated code, which is compiled again.
After you edit a struct’s method
make_structref detects the edit: the next run generates new code and compiles it. A cached jitted function in
another file that calls the method, such as use in run.py, does not detect the edit. Its cache entry holds the
compiled code of the method, and numba checks the entry only against the caller’s own file
(numba’s caching limitations). The caller then returns
the result of the old method, and numba gives no warning. After you edit a method, delete the cache files of each cached
caller in another file. numba names them after the caller’s module, the function’s name, the line of its first decorator
and the Python version: for use, run.use-6.py312.nbi and run.use-6.py312.1.nbc under Python 3.12. The
configurations page describes where numba writes them.
Compiling a function into a value
A cached jitted function that takes a dispatcher as an argument compiles again in every run, as the section on
numbox.utils.derive_wap below explains. cres() avoids that. It compiles a function for
one signature when it is decorated, as njit does when it is given a signature. It returns a first-class function
value instead of a dispatcher, and a cached function that takes the value as an argument loads from the cache in the
next run. The same section shows how jitted code calls such a value and in which cases an exception raised in it
propagates to the caller. A derive is the function that computes the value of a node in a numbox calculation graph, and
a cres value can serve as one (work page).
A binding is a jitted function that calls one function of a C library. cres_if_available()
builds one for a C function that older versions of the library lack. It takes the library, as the ctypes.CDLL handle
that numbox.core.bindings.utils.load_lib returns, and the signature of the decorated function. If the library has a
symbol named after the decorated function, it returns what cres returns; if not, it returns a stub that raises
NotImplementedError when called. numbox’s own bindings use the decorator proxy()
instead. It compiles a function once, at import, so that every jitted caller calls the one compiled copy, and its
variant proxy_if_available makes the same check (optional C symbols).
Functions that define numba StructRef types in one call and compile functions into first-class function values.
make_structref() generates the code of a StructRef type with its constructor, field getters and methods, writes
the code to a cache anchor and compiles it, so that numba can cache the struct. cres() compiles a function for
one signature into a DeriveWAP, and cres_if_available() does the same if a C
library has the function’s symbol. The module also computes the process-stable identities of numba types and
signatures that numbox puts into the names of generated code.
- numbox.utils.highlevel.cres(sig, **kwargs)[source]
Compile the decorated function for the signature
sigand return it as a first-class function value.sigmust be one numbaSignature, such asfloat64(float64); anything else raisesValueError. The keyword arguments are passed tonjit, and the function compiles when it is decorated. The result is aDeriveWAP, not a dispatcher, so a cached jitted function that takes it as an argument loads from the cache in the next process. An exception raised in its body propagates to a jitted caller, asnumbox.utils.derive_wapexplains.
- numbox.utils.highlevel.cres_if_available(lib, sig, **kwargs)[source]
Return what
cres(sig, **kwargs)returns iflibhas a symbol named after the function; else return a stub.libis thectypes.CDLLhandle of a C library, asnumbox.core.bindings.utils.load_libreturns it. Use the decorator for a binding of a C function that older versions of the library lack. The stub is a plain Python function with the decorated function’s name. A call of the stub from Python raisesNotImplementedErrorinstead of failing with an LLVM link error, and jitted code that calls the stub fails to compile.
- numbox.utils.highlevel.determine_field_index(struct_ty, field_name)[source]
Return the position of the field
field_namein the structref typestruct_ty, or raiseValueError.
- numbox.utils.highlevel.hash_type(ty: Type) str[source]
Return a SHA-256 hex digest of the numba type
tythat is the same in every process.A Record type is hashed by its
str, a dispatcher type by the fingerprint of its Python function, and any other type by numba’s mangled name for it.
- numbox.utils.highlevel.make_structref(struct_name: str, struct_fields: Iterable[str] | dict[str, Type], struct_type_class: type | Type, *, struct_methods: dict[str, Callable] | None = None, jit_options: dict | None = None, ns: dict | None = None)[source]
Define a StructRef type named
struct_namewith the fieldsstruct_fields, and return its class.struct_fieldsis a dict of field names to numba types, or a sequence of field names whose types numba infers from the arguments of each call to the class.struct_type_classis an empty subclass of numba’sStructRefregistered with numba’s@register, and each struct needs one of its own. The class must not be namedstruct_namefollowed byType, such asPointTypefor a struct namedPoint, because the generated code assigns that name to the struct’s numba type. If code that uses the struct is to be cached, define the type class in a module that the program imports, not in the script that runs. numba pickles the struct’s type into its cache, and a class from the running script does not match the cached copy in the next run. A StructRef written by hand has the same requirement. For the same reason,make_structrefcannot define the type class in the code that it generates.struct_methodsmaps method names to functions. Each function becomes a method that Python code and jitted code can call, and it receives the struct as its first argument. A method must not define a nested function, because numbox renames everydefin the method’s source. numba may inline a method into a jitted caller regardless of whatjit_optionsspecifies about inlining, and a cached caller holds the method’s compiled code in either case. After an edit to a method, a cached caller in another file can therefore continue to run the old code, as it would with a StructRef written by hand.nsmaps names to the globals that the methods read, such as a module or a jitted helper, because the methods run in a namespace of their own. numbox overrides an entry ofnswhose name is also a global of this module or one of the names that the generated code uses, such asfieldsorjit_options.jit_optionsdefaults to numbox’s default jit options.numbox writes the generated code to a cache anchor under numba’s cache directory, not to
highlevel.py, and compiles it under the anchor’s file name. numba quotes code from the anchor in its messages, so numbox writes the anchor even with caching disabled, and in that case it ignores a failed write. With caching enabled, numbox writes the anchor and then asks numba whether it can cache a function of the anchor; numba can answer only when the file exists on disk. If the write fails or numba cannot cache in that location, the struct compiles without a cache after one warning, and an anchor that was written remains on disk. If a method, or annsvalue that a method reads, has no fingerprint, the struct compiles without a cache and without a warning. The utils page explains the anchors in its section on the cache-anchor mechanism.
- numbox.utils.highlevel.make_structref_code_txt(struct_name: str, struct_fields: Iterable[str] | dict[str, Type], struct_type_class: type | Type, struct_methods: dict[str, Callable] | None = None, user_ns: dict | None = None)[source]
Return
(code, fields_types, cacheable): the source thatmake_structref()compiles for a struct.The arguments are those of
make_structref(), withuser_nsfor itsns.fields_typesis the list of the field types, or None ifstruct_fieldsholds only names.cacheableis False if a method, or annsvalue that a method reads, has no fingerprint.
numbox.utils.derive_wap
A first-class function value is numba’s form of a compiled function as data: jitted code can take one as an argument, read one from a global variable, and call it.
cres() returns such a value, and so does the .as_func attribute of a function
decorated with proxy() (passing the function as a value).
Both are instances of DeriveWAP. WAP stands for numba’s wrapper address protocol:
WrapperAddressProtocol is numba’s base class for the Python objects that jitted code can call as first-class
functions. numbox assigns a DeriveWAP the numba type DeriveFunctionType, a
subclass of numba’s own FunctionType. This page calls numba’s type the plain FunctionType.
An exception raised in the body of a DeriveWAP propagates out of a call in jitted code, as it does out of a call to
an ordinary @njit function. The file ops.py defines a cres value whose body raises ValueError for a
negative input:
from numba import float64
from numbox.utils.highlevel import cres
@cres(float64(float64), cache=True)
def checked_sqrt(x):
if x < 0.0:
raise ValueError("negative input")
return x ** 0.5
A second file, callers.py, passes the value to a cached jitted function:
from numba import njit
from ops import checked_sqrt
@njit(cache=True)
def apply(f, x):
return f(x)
print(apply(checked_sqrt, 4.0)) # 2.0
try:
apply(checked_sqrt, -1.0)
except ValueError as error:
print(error) # negative input
apply loads from the cache in the next run, because the value’s numba type,
DeriveFunctionType[float64(float64)], is the same in every process. The type of a dispatcher includes the memory
address of the Python function it wraps, and that address differs from one process to the next. A cached apply
that is passed a dispatcher therefore misses the cache in every run, compiles again and adds a cache entry each time.
How the value carries its entry point
numba stores a first-class function value as three addresses. The first is the function’s numba entry point, the start
of its code in numba’s own calling convention. The second is its C entry point, a wrapper of the kind that @cfunc
builds, and the third is the address of the Python object. When the value holds a numba entry point, a call from jitted
code goes through it, and an exception raised in the body propagates to the caller. Without one, the call goes through
the C entry point, which cannot propagate an exception. numba then prints the exception to stderr as ignored, and the
call returns zero (numba issue 8246).
numba records the numba entry point only for a dispatcher. A DeriveWAP records the numba entry point of the function
that cres or @proxy compiled. When Python code passes the value to a jitted function as an argument, numbox sets
the value’s numba entry point to the recorded address. When jitted code reads the value as a constant, numbox declares
the numba entry point by its symbol name instead, as described below.
For a cres value, get_func_tuple() shows that the numba entry point is set. numba’s own
_get_jit_address returns 0 for the same value, because it resolves an address only for a dispatcher.
Where an exception is still dropped
A call drops the exception whenever the value reaches jitted code without a numba entry point. That happens in three cases:
a
@cfunc, passed as a function value;a
CompileResultWAP, numba’s own function value for a compile result, as inCompileResultWAP(njit(sig)(f).get_compile_result(sig)), withCompileResultWAPfromnumba.core.types.function_type;a
DeriveWAPpassed from Python to a parameter declared with the plainFunctionType, as in@njit(float64(FunctionType(float64(float64)), float64))withFunctionTypefromnumba.types. numba converts the value to the plainFunctionTypeduring the call from Python. The converted value holds the C entry point but no numba entry point.
In the last case, the exception propagates if numba infers the parameter’s type, or if the signature declares the
parameter as DeriveFunctionType(float64(float64)). Inside jitted code, by contrast, a DeriveWAP passed to a
parameter of the plain FunctionType still holds its numba entry point. numba stores values of both types as the same
three addresses, so numbox converts the value there without changing it. For a @cfunc, compile the function with
cres instead. For a CompileResultWAP, call rewrap_derive() from Python to convert
the value to a DeriveWAP. make_work() calls rewrap_derive for every derive that it
receives from Python. A tuple that mixes DeriveWAP values with other function values is subject to further limits,
which the work page lists.
Holding the value as a module-level constant
numba reads a module-level variable as a compile-time constant, so jitted code can also call the value as a global. A
third file, constant.py, shows this form:
from numba import njit
from ops import checked_sqrt
@njit(cache=True)
def twice(x):
return checked_sqrt(x) + checked_sqrt(x)
print(twice(4.0)) # 4.0
This form gives a direct call, which LLVM can inline, and an exception raised in the body propagates as it does through
an argument. numba caches twice too. numbox declares the body’s numba entry point by its symbol name and links the
body’s compiled code into twice, so twice holds no address that changes between processes. numba itself refuses
to cache a caller that holds one of numba’s own function values as a constant, and it warns that the caller uses dynamic
globals.
The cost is that the cache entry of twice holds its own copy of the body. The copy can go stale, as the cached
caller of a struct’s method does (after you edit a struct’s method). After you
edit checked_sqrt in ops.py, twice may keep running the old body. Delete the cache files of twice after
every edit of the body, here constant.twice-6.py312.nbi and constant.twice-6.py312.1.nbc. Unless the inlining
matters, pass the value as an argument instead: apply calls whichever value it is passed, so it always runs the
current body. The proxy page covers the same form for .as_func (holding the function as a module-level
constant).
First-class function values whose exceptions propagate to the jitted code that calls them.
numba can call a first-class function value through two entry points. A call through the numba entry point
propagates an exception to the caller. A call through the C entry point, the kind of wrapper that @cfunc builds,
discards the exception: numba writes it to stderr as unraisable, and the call returns zero
(numba issue 8246). numba records the numba entry point only for a
dispatcher. DeriveWAP is a function value that records the numba entry point of a compiled function. Its
numba type, DeriveFunctionType, sets that entry point when Python passes the value to jitted code and when
jitted code reads the value as a constant. cres() returns such values, and
rewrap_derive() converts numba’s own CompileResultWAP into one. A value passed from Python to a parameter
declared with the plain FunctionType loses its numba entry point when numba unboxes it, as
DeriveFunctionType.can_convert_to() explains.
A value propagates its exception only through a call that takes the numba entry point when the value has one. numba
makes such a call when it calls a function value itself
(numba.core.lowering.Lower.__call_first_class_function_pointer). A call that always takes the C entry point
discards the exception, however the value was built. Code that calls a function value inside an @intrinsic must
therefore read the value’s jit_addr and, if it is set, emit call_conv.call_function followed by
return_status_propagate. numbox.core.work.work._call_derive is such code. It takes the numba entry point
without a test for a DeriveFunctionType, and it tests jit_addr at run time for a plain FunctionType, which
numba sets for a dispatcher passed as an argument. The work page describes, in its section on exception handling, when
the exception of a derive propagates.
- class numbox.utils.derive_wap.DeriveFunctionType(*args, **kwargs)[source]
Bases:
FunctionTypeThe numba type of a
DeriveWAP: a first-class function type whose values always hold a numba entry point.numbox’s
_call_deriverecognizes this type when it compiles a call, and it calls a value of the type through the numba entry point, with no test at run time.- can_convert_to(typingctx, other)[source]
Return a safe conversion to the plain
FunctionTypeof the same signature, and None for any other type.The conversion allows a
DeriveWAPto be passed to a parameter declared with the plainFunctionType. Whether its exception then propagates depends on where the value comes from. Inside jitted code, the cast inlower_cast_derive_to_function_type()leaves the value unchanged, so it keeps its numba entry point. From Python, numba unboxes the value as the plainFunctionType, which sets no numba entry point, so a call of the value discards its exception. One call site can therefore propagate an exception or discard it, depending on where the value comes from.
- class numbox.utils.derive_wap.DeriveWAP(cres)[source]
Bases:
CompileResultWAPA first-class function value for one compile result that records the numba entry point as well as the C one.
numba’s
CompileResultWAPrecords only the C entry point, through which an exception cannot propagate. The constructor raisesValueErrorif the compile result’s library returns no address for the numba entry point.
- numbox.utils.derive_wap.rewrap_derive(derive)[source]
Upgrade
deriveto aDeriveWAPif it is aCompileResultWAP, so that its exceptions propagate.A value that
cres()compiled is already aDeriveWAPand is returned unchanged. Any other value, includingNone, is also returned unchanged, so a caller can apply the function to every derive. ACompileResultWAPbuilt with numba directly would keep only the C entry point, and the compile result that it carries suffices for the upgrade.The upgraded wrapper is stored on the original object, and a second call returns the same wrapper. The storage is required, not an optimization.
py_addrholds the wrapper’s address without a reference, so a new wrapper for each call would be freed when the caller returned, and everyWorkbuilt from it would point to freed memory. Stored on the original, the wrapper is not freed while the caller holds the original object.
numbox.utils.preprocessing
Several numbox functions generate Python source at run time and compile it:
make_structref(), compile_kernel(), the work
builder for each Derived node, and the SQLite registrations
register_aggregate(),
register_window() and
register_tvf(). numba caches a function only if it can find the function’s source
file. @njit(cache=True) on a function g compiled from a string raises
RuntimeError: cannot cache function 'g': no locator available for file '<string>'.
numbox therefore writes each piece of generated code to an anchor of its own. It compiles the code in memory under the
anchor’s file name, so numba finds the file and stores the compiled code in cache files named after the anchor.
make_structref and the SQLite registrations write the anchor even with caching disabled, because numba quotes the
code from it in its messages. compile_kernel and the work builder write one only when caching is enabled. @proxy
works differently. numbox compiles the code that it generates for a proxied function as though that code were part of
your own file. That is why the function’s first decorator must be on line 8 of its file or later
(where the function may start).
Where the generated code is written
The anchors are under NUMBA_CACHE_DIR when that variable is set, and otherwise under numba’s user cache directory,
which the configurations page gives for each platform (where numba writes the cache).
Each kind of code has a subdirectory of its own there: numbox-structref, numbox-compile-kernel,
numbox-derive, numbox-sqlite-udaf and numbox-sqlite-tvf. An anchor’s name ends in a digest that covers the
generated code and the functions of yours that the code calls. A new version of the generated code, or of a function of
yours that it calls, therefore has an anchor of its own. For the struct of the example above, the anchor is a file such
as numbox-structref/DataStruct_b62da08f4520823e.py.
numba names the cache files of the functions in an anchor after the anchor, as in
DataStruct_b62da08f4520823e.make_datastruct-43.py312.nbi. They are in the __pycache__ directory beside the
anchor. When NUMBA_CACHE_DIR is set, they are in a directory under it instead, whose name starts with the name of
the anchor’s subdirectory, such as numbox-structref_38dbc719b23e....
numba quotes generated code from its anchor in its messages. A typing error in a struct’s method therefore names a file
such as numbox-structref/DataStruct_6ed7f92aca43a51f.py and a line in it. Open the file to read the code around
that line; the source of your methods is near its end.
make_graph() writes no anchor for the kernel it generates. It compiles the kernel under
a name that contains a digest, as though the kernel were part of numbox’s own module numbox.core.work.builder. numba
therefore caches the kernel beside that module. Its cache files have names such as
builder._make_<digest>-2.py312.nbi, in the __pycache__ directory beside builder.py or, when
NUMBA_CACHE_DIR is set, in a directory under it whose name starts with work_. If numba cannot write there, as in
a read-only installation, the kernel compiles without a cache after a warning whose remedy is the one for numbox’s own
modules (where numba writes the cache).
numbox never deletes an anchor, so the anchor and the cache files of every version of the generated code remain on disk. You can delete them between runs (numba’s notes on clearing the cache). numbox writes an anchor again when it needs one, and numba compiles again whatever it can no longer load from the cache.
If numbox warns that numba cannot cache generated code
With caching enabled, numbox writes the anchor and asks numba whether it can cache a function of that file before the code is compiled. If either step fails, the code compiles without a cache, after one warning such as this one:
RuntimeWarning: numba cannot cache DataStruct_b62da08f4520823e.py here ([Errno 13] Permission denied:
'.../numbox-structref/DataStruct_b62da08f4520823e.py.tmp-c483cpcq'); it compiles without a cache. Set
NUMBA_CACHE_DIR to a writable directory, or compile without a cache to silence this warning: "cache" off in the jit
options this code was given, or in its cache argument where it takes one, or NUMBOX_JIT_OPTIONS='{"cache": false}'
where the options are the package's
It means that numbox could not write the anchor, so the struct works but compiles again in every process. The
parenthesized text is the underlying error; the list below gives the right NUMBA_CACHE_DIR for each:
If the path is too long for the file system, set
NUMBA_CACHE_DIRto a shorter path.If the directory’s path is not valid UTF-8, set
NUMBA_CACHE_DIRto a UTF-8 path. numba hashes the path as UTF-8 to name a directory of its own.If the file system does not accept names as long as the ones numba writes for this code, set
NUMBA_CACHE_DIRto a directory on a file system that does.For any other error, such as the permission error above, set
NUMBA_CACHE_DIRto a directory that you can write.
The derives of the work builder fall back to compiling without a cache in the same cases, but numbox gives no warning
for them. To silence the warning, compile the code without a cache: pass jit_options={"cache": False} to
make_structref or to make_graph, or cache=False to compile_kernel.
NUMBOX_JIT_OPTIONS='{"cache": false}' disables caching in numbox’s default jit options, the numba options that
numbox compiles with. That silences the warning for every numbox function that compiles under those options, the SQLite
registrations included, since they take no options of their own.
Names longer than 40 bytes
The names of an anchor and of its cache files contain the names of the struct and of its fields and methods. Most file
systems allow a name of at most 255 bytes, and a long struct name would overflow that. numbox therefore shortens a name
longer than 40 bytes in UTF-8 before it puts the name into these file names. It keeps as many whole characters as fit in
31 bytes, and it adds an underscore and eight hexadecimal digits of a digest of the whole name, as
bounded_stem() computes. A struct named
MeasurementsFromTheSecondCalibrationRunOfTheDetector has an anchor such as
MeasurementsFromTheSecondCalibr_67d21543_d1964660f30366df.py. Its first suffix, _67d21543, comes from shortening
the name; the second, _d1964660f30366df, is the code digest that ends every anchor’s name. The struct’s
__name__, __qualname__ and repr keep the full name, and the struct caches like any other.
Cache-anchor mechanism
Each version of the generated code needs a file of its own, because numba’s cache cannot distinguish between some versions. numba checks each cache entry against a stamp of its source file, so an edit to a file of yours invalidates the entries of the functions in it. It names the cache files after the source file, the function’s qualified name and the line of its first decorator. It keys each entry in those files on the function’s signature, the target machine, and hashes of the function’s bytecode and closure values.
That key hashes the function’s bytecode but not the tables of constants and names kept beside it, nor the function’s default values. An edit that changes only a literal, a default value or a name can therefore leave the key unchanged. Python 3.14 writes the integers 0 to 255 into the bytecode itself, so on 3.14 an edit that changes such an integer does change the key.
If one shared file held every version of a struct’s code, that file would never change, so its stamp would never invalidate an entry. Two versions that differ only by such an edit would then have the same cache files and the same key. The second would load the binary compiled for the first. The digest in the anchor’s name prevents this: each version of the code has a file of its own, so it also has cache files of its own.
This is also how a new value in ns changes the generated code. The generated struct code gives each method a
compiled helper, a jitted function that the method calls. numbox names the helper after the method and the method’s
fingerprint. A change outside the method’s source, such as a new value in ns, therefore changes the helper’s name.
The new name changes the generated code, and numbox writes the new code to a new anchor.
Cache anchors, the files to which numbox writes the code that it generates at run time so that numba can cache it.
numba caches a function only if it can find the function’s source file. Its key for a cache entry covers the
function’s bytecode but not the constants or names that the bytecode refers to. numbox therefore writes each piece of
generated code to an anchor whose name ends in a digest of the code, and it compiles the code under that file name.
Two versions of the code that differ only in a literal or a name then have anchors, and cache files, of their own.
The anchors are under NUMBA_CACHE_DIR or numba’s user cache directory. Before cached code compiles, numbox asks
numba whether it can cache a function of the anchor. If numba cannot cache it, the code compiles without a cache after
one warning that names the remedy. The utils page explains the anchors in its section on the cache-anchor mechanism.
- numbox.utils.preprocessing.bounded_stem(name: str) str[source]
Return
nameshortened to at most 40 bytes of UTF-8, for use in a file name.A name of 40 bytes or fewer is returned unchanged; nearly every name is that short. A longer name is truncated to the whole characters that fit in 31 bytes, followed by an underscore and the first eight hexadecimal digits of the SHA-256 of the whole name. The length is measured in UTF-8, as file systems measure it, so a character of another script counts for up to four bytes.
numbox puts the names of a struct, its fields and its methods, and of the functions it generates code for, into the names of the anchors and of numba’s cache files. Most file systems allow a name of at most 255 bytes, and numba’s names repeat the anchor’s name and add the function’s name. Without this bound, a struct name of about 93 characters would make them too long.
numbox.utils.digest
digest() returns a hash of 16 hexadecimal digits for a subject and a list of functions. The
subject is an object whose repr identifies the code that you generate, such as a type or a tuple of types. Use the
hash to name a cache entry or a generated file for code that you build around functions passed in by a user. numbox does
so for SQLite’s aggregate, window and table-valued functions. The hash changes when the subject’s repr changes, when
the fingerprint of one of the functions changes, when numbox’s default jit options change, or when numba’s version
changes. The section on numbox.utils.fingerprint below describes what a fingerprint covers. A dispatcher in the list
is hashed together with the options it compiles under:
from numba import njit
from numbox.utils.digest import digest
def plus_one(x):
return x + 1
print(len(digest("state", [plus_one]))) # 16
fast = digest("state", [njit(fastmath=True)(plus_one)])
print(fast == digest("state", [njit(plus_one)])) # False: the options differ
For a Python function or a dispatcher, the hash is the same in every process. digest computes a weaker fingerprint
for a function that reads a value without a fingerprint. The
SQLite registrations then do not detect some edits, as explained
below.
If the digest differs in every process
A functools.partial, a builtin and a callable object have no code for the fingerprint to read, so digest hashes
a pickle of the object instead. The pickle is the same in every process when the object’s class is defined in an
imported module. When the class is defined in the script that you run, the pickle holds the class itself. It also holds
an identifier that cloudpickle, the pickler that numba uses, draws at random in each process. The pickle then differs in
every process, and so does the digest. A cache named after the digest therefore misses on every run. Define such a class
in a module that the script imports.
A short hash that names generated code after the subject it serves and the user functions it calls.
digest() hashes the repr of a subject, such as a type, with the fingerprints of a list of functions. It also
folds numbox’s default jit options and the versions of numba and numbox. Two functions with the same source but
different closure values or globals have different hashes, whereas a hash of the bare code object would be the same for
both. numbox names the anchors of the SQLite aggregate, window and table-valued functions with the hash. Any cache that
combines a type or an identifier with user callbacks can use it the same way.
- numbox.utils.digest.digest(subject, fns)[source]
Return a hash of 16 hexadecimal digits that changes when
subjector one of the functionsfnschanges.The hash covers
repr(subject), numba’s version, numbox’s version, numbox’s default jit options and each entry offns. numbox’s version is the empty string in a checkout or an editable install, so in those cases the hash does not change with the version. A released package holds its version, and the hash folds it. Each entry offnsis folded as follows:a dispatcher or a
@vectorizefunction: the fingerprint of its Python function and the options it compiles under. If the Python function has no fingerprint, the options are folded with the weaker fingerprint below for a dispatcher, and with a cloudpickle of the object for a@vectorizefunction;a Python function: its fingerprint, or the weaker fingerprint if the function reads a value that has none;
any other callable, such as a
functools.partial, a builtin or a callable object: a cloudpickle of it.
For a Python function or a dispatcher, the hash is the same in every process. The weaker fingerprint puts the name of a value’s type in place of each value without a fingerprint, and it leaves out module attributes, so an edit to such a value or attribute leaves the hash unchanged. A cloudpickle can differ in every process, as it does for an object whose class is defined in the script that runs.
numbox.utils.fingerprint
numbox fingerprints the Python functions that you pass to it, to determine whether code that it generated and cached
earlier still matches them. It does so for struct methods, compile_kernel formulas, the work builder’s derives and
the body of a @proxy function, and digest does so for the callbacks of the SQLite registrations. A fingerprint
is a text that describes a function. numbox hashes it into the name of the generated code, so a new fingerprint produces
new code, which is compiled again. The fingerprint of a function is built from:
its module and qualified name;
its bytecode, its literals and the names it uses, and the same for each function or comprehension defined inside it;
its default values and the values in its closure;
the value of each global that it reads by name;
the value of each module attribute that it reads, such as
cfg.SCALE, when the value is a number, a string, an array or another kind of data, or a dispatcher;for each function or dispatcher among these values, that function’s own fingerprint, and the options that a dispatcher compiles under.
An edit to any of these changes the fingerprint. Such edits include those that leave numba’s own key unchanged: a new
literal or default value, a renamed attribute or global, and a new value of a global. Renaming a local variable or
moving the function to another line does not change the fingerprint. Most other edits change it, even an edit to the
docstring, which changes nothing that the function computes. The following example uses digest to show the effect of
two edits on the fingerprint:
from numbox.utils.digest import digest
def scale(x):
factor = 2.0
return factor * x
before = digest("example", [scale])
def scale(x):
k = 2.0 # a local variable renamed, on other lines: the same fingerprint
return k * x
print(digest("example", [scale]) == before) # True
def scale(x):
k = 3.0 # a new literal: a new fingerprint
return k * x
print(digest("example", [scale]) == before) # False
When a function reads a value without a fingerprint
Some values have no form that means the same thing in another process, so numbox cannot fingerprint them. The ones that
jitted code reads most often are a numba type used as a global, such as float64 or intp, numba’s prange, a
class and a NumPy dtype. A builtin function imported by name, such as sqrt after from math import sqrt, has
none, and neither has an @intrinsic. No jitted helper of numbox.utils.lowlevel, such as array_data_p,
load_at, store_at or get_str_from_p_as_int, has a fingerprint. numbox’s bindings, such as strlen, do, so
a function that calls a binding keeps its fingerprint. A jitted function that reads a value without a fingerprint has
none itself.
When a struct method, a compile_kernel formula or a derive reads such a value, numbox cannot distinguish one version
of the function from another. The code that depends on the function then compiles without an on-disk cache: it compiles
again in every process and never runs a stale version, and numbox gives no warning. Look for the struct’s cache files to
find out whether it compiles without a cache. A struct that compiles without a cache has none named after its anchor. To
keep such a struct cached, do not import a value that never changes, such as a numba type or a builtin function, by
name. Reach it through its module instead, as in math.sqrt after import math or numba.float64 after
import numba. The fingerprint leaves out a module attribute whose value is not data, so the method then reads no
value without a fingerprint, and it has a fingerprint of its own.
The fingerprint leaves out a value that a module provides only through a module-level __getattr__. A change to such
a value therefore does not change the fingerprint. Delete the cache files of the code that depends on such a value after
it changes. For a @proxy function, numbox computes from such a fingerprint the name under which callers reach the
compiled body. The proxy page explains what happens when the body reads a value without a fingerprint
(if numbox warns of an alias collision).
If a SQLite function keeps returning old results
A SQLite aggregate, window or table-valued function can keep running code compiled from an earlier version of its
callbacks. This happens when a callback reads a value without a fingerprint: digest then computes a weaker
fingerprint for the callback. The weaker fingerprint still covers the callback’s code and the values of the globals it
reads by name. It puts the name of each value’s type in place of a value without a fingerprint, though, and it leaves
out every module attribute. A later change to such a value, or to a module attribute that the callback reads, therefore
leaves the anchor’s name unchanged. The registration then loads the code compiled before the change, and numbox gives no
warning.
For a SQLite callback, the weaker fingerprint is the common case. A step callback receives the number of SQL arguments
as argc and the address of SQLite’s array of pointers to the argument values as argv_pp, as the docstring of
register_aggregate() lists. The usual way to read the arguments,
carray(_cast_int_to_void_p(argv_pp), (argc,), dtype=np.intp), calls numbox’s _cast_int_to_void_p, an
@intrinsic, before numba’s carray makes an array of the address. digest therefore always computes the weaker
fingerprint for a callback that reads its arguments this way.
Read the values that a callback depends on as names in the callback’s own module, as in from config import SCALE,
not as module attributes such as config.SCALE, which the weaker fingerprint leaves out. This is the reverse of the
advice for a full fingerprint, where reaching a value through its module keeps a struct cached. Delete the
registration’s anchor and its cache files after a change that the weaker fingerprint does not cover, such as an edit to
a helper without a fingerprint. The anchor is numbox-sqlite-udaf/udaf_<name>_<digest>.py for an aggregate,
numbox-sqlite-udaf/wudaf_<name>_<digest>.py for a window function and numbox-sqlite-tvf/tvf_<name>_<digest>.py
for a table-valued function. Its cache files start with the same name
(where the generated code is written).
Fingerprints of Python functions and values: texts that describe them and are the same in every process.
numbox hashes fingerprints into the names of the code that it generates and caches, so that a change to a user’s
function produces new code. _fingerprint_function folds a function’s module and qualified name, and its code
objects with their bytecode, constants and names. It also folds the function’s default values and closure values, the
values of the globals that it reads, and the data and dispatchers that it reads as module attributes. It descends into
the functions and dispatchers among those values, and it stops at a cycle. Two functions with the same source but
different captured values therefore have different fingerprints, whereas a hash of the bare code object would be the
same for both. _canon_value returns the text for one value and raises _Unfingerprintable for a value that has
no text that means the same thing in another process. The caller decides how to proceed in that case: some callers
compile the code without a cache, and @proxy and digest name the code with
_fingerprint_function_best_effort, which never raises. make_structref, compile_kernel, the work builder,
@proxy and digest use the module, which also resolves the jit options that their names fold.
numbox.utils.lowlevel
This module holds the small helpers that numbox uses to work with raw memory, most of them jitted functions that Python
code can call as well. load_at() and store_at() read and write
a value of a numba type at an address held as an intp. load_unaligned() and
store_unaligned() do the same at an address that may be misaligned.
array_data_p() returns the address of an array’s data as an intp, the type that
numbox’s bindings take for a pointer:
import numpy as np
from numba import int32
from numbox.utils.lowlevel import array_data_p, load_at, store_at
a = np.zeros(2, dtype=np.int32)
p = array_data_p(a)
store_at(p + 4, int32(7))
print(a, load_at(p + 4, int32)) # [0 7] 7
Called on a value, a numba type converts it, so int32(7) is a 32-bit integer and store_at writes four bytes.
get_str_from_p_as_int() copies a NUL-terminated C string into a str, one character per
byte. For the UTF-8 bytes of "caf\u00e9", it returns the five characters 'caf\xc3\xa9'. For a returned string
s, s.encode("latin-1").decode("utf-8") recovers the text. cast() reinterprets a
structref as another structref type over the same memory. get_func_tuple() returns the
three addresses that a first-class function value holds, which the section on numbox.utils.derive_wap describes. The
functions that take a context and a builder, such as extract_struct_member(), are for code
that you write inside an @intrinsic.
Helpers for raw memory in jitted code: addresses held as integers, loads and stores, and casts between structrefs.
Most helpers are jitted functions that Python code can call too, usually built on an @intrinsic of the same name
with a leading underscore. An address is an intp, the integer type that numbox’s bindings take for a pointer. The
helpers check neither that an address points to live memory nor that the memory has the layout of the given type;
the caller must ensure both for as long as the address is used. The functions that take a context and a builder,
such as extract_struct_member(), are for code inside an @intrinsic.
None of the jitted helpers has a fingerprint, because each one calls an @intrinsic or reads a numba type. If a
struct method, a compile_kernel formula or a derive calls one of them by its name, the code that numbox generates
for it compiles without an on-disk cache. digest computes the weaker fingerprint that the utils page describes for
a SQLite callback that calls one of them.
- numbox.utils.lowlevel.array_data_p(arr)[source]
Return the address of the data of the NumPy array
arras anintp, the type of a pointer in the bindings.Python code and jitted code can call it. The address takes no reference, so it is valid only while
arris alive. IfNUMBA_DISABLE_JIT=1is set, the function runs as Python and returns anumpy.int64, which ctypes functions such asctypes.memmovereject.
- numbox.utils.lowlevel.cast(source, dest_ty)[source]
Return the structref
sourceas a value of the structref typedest_ty, over the same memory.The data is not converted, so the fields of
dest_tymust match the leading fields of the memory thatsourcerefers to; a type with no fields, such asVoidType, always matches. The result holds a reference of its own.
- numbox.utils.lowlevel.deref_payload(p, ty)[source]
Return the data of the structref
pread as the numba typety, with a reference of its own.The data is read from its start without conversion, so
tymust match the layout of the data or of its leading part, such as the type of the structref’s first field.
- numbox.utils.lowlevel.extract_struct_member(context: BaseContext, builder: IRBuilder, struct_fe_ty: StructRef, struct_obj, member_name: str, incref: bool = False)[source]
Emit a load of the field
member_nameof the structrefstruct_obj, of the numba typestruct_fe_ty.The function is for code inside an
@intrinsic.member_nameis a Python string known when the code is generated, and a name that is not a field raisesKeyError. The loaded value is borrowed from the structref and must not outlive it. Ifincrefis True, it holds a new reference instead, as a value that an intrinsic returns must hold.
- numbox.utils.lowlevel.get_func_p_as_int_from_func_struct(func_)[source]
Return the address of the C entry point of the first-class function value
func_, as anintp.
- numbox.utils.lowlevel.get_func_p_from_func_struct(builder: IRBuilder, func_struct)[source]
Emit the extraction of the C entry point, the first of the three addresses, from a first-class function value.
The function is for code inside an
@intrinsic.func_structis the LLVM value of the function value, and the result is ani8*.
- numbox.utils.lowlevel.get_func_tuple(func)[source]
Return the three addresses that the first-class function value
funcholds, as a tuple ofintp.The addresses are its C entry point, its Python object and its numba entry point. The numba entry point is 0 if the value has none, as for a
@cfunc;numbox.utils.derive_wapdescribes the two entry points.
- numbox.utils.lowlevel.get_ll_func_sig(context: BaseContext, func_ty: FunctionType)[source]
Return the LLVM function type whose return and argument types are the data types of the signature of
func_ty.The function is for code inside an
@intrinsic. numbox casts the C entry point of a first-class function value to this type before it calls the entry point.
- numbox.utils.lowlevel.get_str_from_p_as_int(p)[source]
Return a copy of the NUL-terminated C string at the address
pas astr, with one character per byte.Each byte becomes the character of the same code, 0 to 255, as Latin-1 decoding gives. The UTF-8 bytes of a non-ASCII text are therefore returned undecoded; for a returned string
s,s.encode("latin-1").decode("utf-8")gives the text. The function reads at mostMAX_STR_LENGTHbytes,2**31 - 1, and returns what it has read if it finds no NUL before that.
- numbox.utils.lowlevel.get_unicode_data_p(s)[source]
Return the address of the character data of the string
s, as anintp, without a copy.The string stores one, two or four bytes per character, as its widest character needs, followed by a NUL, so the bytes are the text’s UTF-8 only for ASCII text;
numbox.utils.cstrings.c_string()makes a UTF-8 copy. The address is valid only whilesis alive. A string that numba types as optional, such as"A" * n, raises a bareAssertionError. numba’s unicode structure is defined in https://github.com/numba/numba/blob/release0.61/numba/cpython/unicode.py#L83.
- numbox.utils.lowlevel.load_at(p, ty)[source]
Return the value of the numba type
tystored at the addressp, anintpor auintp.The caller must ensure that
ppoints to live memory that holds a value in the LLVM layout ofty, aligned for that type;load_unaligned()reads from an address that may be misaligned. An address of another integer type raisesTypingError.
- numbox.utils.lowlevel.load_unaligned(p, ty)[source]
Return the value of the type
tyat the addresspasload_at()does, without assuming any alignment.The load is correct at a misaligned address, such as a field of a packed structured dtype, where
load_at()has undefined behavior.
- numbox.utils.lowlevel.populate_structref(context, builder, signature, structref_type_, structref_, args, ordered_args_names, decref_old=False)[source]
Emit the stores of
argsinto the fields named byordered_args_namesof the structrefstructref_.The function is for code inside an
@intrinsic.structref_type_is the structref’s numba type, and each argument is cast from its type insignature.argsto the type of its field, which takes a new reference to it. Withdecref_old=True, the old value of each field is released after the new value is referenced. Leave it False for a structref that_newhas just allocated, because its fields hold no values to release. The code follows numba’sstruct_setattr_implinnumba.experimental.structref.define_attributes.
- numbox.utils.lowlevel.store_at(p, v)[source]
Store
vat the addressp, anintpor auintp, in the LLVM layout of the numba type ofv.The numba type of
vdetermines how many bytes are written. A Pythonintis anint64, so the function writes eight bytes for it. To write fewer, convertvfirst:store_at(p, int32(value))writes four bytes. The caller must ensure thatppoints to writable memory with room for the value, aligned for its type;store_unaligned()writes to an address that may be misaligned. An address of another integer type raisesTypingError.
- numbox.utils.lowlevel.store_unaligned(p, v)[source]
Store
vat the addresspasstore_at()does, without assuming any alignment.The store is correct at a misaligned address, such as a field of a packed structured dtype, where
store_at()has undefined behavior.
- numbox.utils.lowlevel.tuple_of_struct_ptrs_as_int(tup)[source]
Return the MemInfo addresses of the structrefs in the tuple
tup, as a tuple ofintp.The addresses take no reference, so they are valid only while the structrefs are alive.
- numbox.utils.lowlevel.uniformize_tuple_of_structs(tup, uniform_ty=numba.VoidTypeClass())[source]
Return the structrefs of
tupas a tuple of the one structref typeuniform_ty, by defaultVoidType.The function casts each element as
cast()does, over the same memory, and each result holds a reference of its own. An element that is not a structref raisesAssertionErrorwhen the function is compiled.
numbox.utils.meminfo
Passing a reference through a pointer
Some code can hold a structref only as an integer. A C library that keeps a void * for its caller is one example,
and the slot that holds the state of numbox’s SQLite aggregates is another. export_meminfo()
returns the address of the structref’s MemInfo, numba’s reference-counted header for its memory, as an intp.
export_meminfo also takes a reference, which keeps the structref alive.
borrow_structref(), called from jitted code or from Python, converts the address back to a
structref of the type that you pass to it. release_meminfo() releases the reference that
export_meminfo took. The following example uses main.py from the highlevel section:
from numba import njit, typeof
from main import data_struct
from numbox.utils.meminfo import borrow_structref, export_meminfo, get_nrt_refcount, release_meminfo
d = data_struct(3.14, "double")
DataStructType = typeof(d)
@njit
def read_value(p):
return borrow_structref(DataStructType, p).value
p = export_meminfo(d)
print(get_nrt_refcount(d)) # 2: one reference for d, one for p
print(read_value(p)) # 3.140000104904175
release_meminfo(p)
print(get_nrt_refcount(d)) # 1
The structref stays alive while the exported reference is held, even after Python releases its own reference.
borrow_structref adds a reference for the structref that it returns. numba releases that reference when the
structref goes out of scope, so a borrow does not change the reference count. Release each exported address once, and do
not use it afterward, because the structref’s memory may then be freed. export_meminfo also accepts a NumPy array,
and the address then keeps the array alive until it is released. borrow_structref can rebuild a structref from an
address, but it cannot rebuild an array.
After upgrading from numbox 0.7.5 or earlier on numba 0.65 or earlier
Delete, once, the cache files of each cache=True function that calls export_meminfo with an array and was
compiled before the upgrade. numba ignores cache files that another version of numba wrote, so the step is needed only
while numba stays at the same version. Such a function keeps loading its old code from the cache, because numba’s key
for it leaves out the code of the functions it calls. In that old code, export_meminfo takes no reference. An
optimization pass of numba 0.65 and earlier, removerefctpass, removed the reference count change from
export_meminfo. The pass removes every reference count change from a function that seems not to need one. The
address that export_meminfo returns to its caller then no longer keeps the array alive, and the array’s memory can
be freed while the address is in use. numbox 0.7.6 and later mark export_meminfo so that the pass does not remove
its reference count change. numba 0.66 removed the pass.
Helpers that pass a structref through an integer address and read the reference count of its MemInfo.
A MemInfo is numba’s reference-counted header for the memory of a structref or an array. export_meminfo()
returns the address of a structref’s MemInfo as an intp and takes a reference, borrow_structref() builds a
structref from such an address, and release_meminfo() releases the reference. structref_meminfo() returns
the addresses of a structref’s MemInfo and data, and get_nrt_refcount() reads the reference count.
- numbox.utils.meminfo.borrow_structref(struct_type, p)[source]
Return a structref of the type
struct_typeover the MemInfo at the addressp.Python code and jitted code can call it. The structref holds a reference of its own, which numba releases when the structref is no longer used, so a borrow leaves the reference count unchanged.
pmust come fromexport_meminfo()and must not have been released yet.struct_typemust be the type of the exported structref, which is not checked.
- numbox.utils.meminfo.export_meminfo(s)[source]
Return the address of the MemInfo of
sas anintp, and take a reference that keepssalive.Python code and jitted code can call it.
sis a structref or a NumPy array. Pass each address torelease_meminfo()exactly once, and do not use it afterward, because the memory may then be freed.
- numbox.utils.meminfo.get_nrt_refcount(s)[source]
Return the reference count of the MemInfo of the structref
s, which numba’sincrefanddecrefchange.The function reads the first field,
refct, of numba’sMemInfostructure from the address thatstructref_meminfo()returns, so Python code can call it but jitted code cannot. The count is not meaningful for a NumPy array that Python passes in, because numba creates a MemInfo for the call alone. The layout of the structure is:struct MemInfo { size_t refct; NRT_dtor_function dtor; void *dtor_info; void *data; size_t size; /* only used for NRT allocated memory */ NRT_ExternalAllocator *external_allocator; };
The structure is defined in numba’s nrt.cpp.
- numbox.utils.meminfo.release_meminfo(p)[source]
Release the reference that
export_meminfo()took for the addressp.Python code and jitted code can call it. The memory is freed if no other reference remains, so
pmust not be used afterward.
- numbox.utils.meminfo.structref_meminfo(s)[source]
Return the addresses of the MemInfo of the structref
sand of its data, as a tuple of twointp.The addresses take no reference, so they are valid only while
sis alive. numba creates a MemInfo for the call alone when Python passes a NumPy array, so for an array the first address is no longer valid when the call returns.
numbox.utils.cstrings
Allocating C strings for the bindings layer
numbox’s bindings, such as those in numbox.core.bindings.libc and numbox.core.bindings.sqlite, take every text
argument as an intp pointer to a NUL-terminated C string. From Python, c_string()
creates such a string. It copies the UTF-8 encoding of a str into a new C buffer, yields the buffer’s address, and
frees the buffer when the with block ends:
from numbox.core.bindings.libc import strlen
from numbox.utils.cstrings import c_string
with c_string("caf\u00e9") as p:
print(strlen(p)) # 5: U+00E9 takes two bytes in UTF-8
The address is valid only inside the block. For several strings at once, open them in one with statement, as in
with c_string("pear") as a, c_string("apple") as b:. When their number is known only at run time, enter each one
into a contextlib.ExitStack. c_string
raises ValueError for a string that contains a NUL character, because the C string would end at that character.
get_unicode_data_p() also returns an address for a str, without making a copy. That
address points into the string’s own memory, where CPython stores one, two or four bytes per character, as the widest
character of the string needs. The bytes there are the text’s UTF-8 only for ASCII text. CPython stores "caf\u00e9"
with one byte per character, so its last character is the single Latin-1 byte 0xE9, not the two UTF-8 bytes
0xC3 0xA9.
From jitted code
c_string works only in Python. numba does not compile a with statement that uses c_string as its context
manager. It raises UnsupportedBytecodeError with the message
The 'with (context manager) as (variable):' construct is not supported. For jitted code, encode the text in Python,
add a NUL byte, and pass the bytes as a uint8 array. array_data_p() gives the array’s
address inside the jitted function:
import numpy as np
from numba import njit
from numbox.core.bindings.libc import strlen
from numbox.utils.lowlevel import array_data_p
@njit
def c_length(buf):
return strlen(array_data_p(buf))
buf = np.frombuffer("caf\u00e9".encode("utf-8") + b"\0", dtype=np.uint8)
print(c_length(buf)) # 5
NUL-terminated UTF-8 C strings, created from Python strings, for numbox’s bindings.
numbox’s bindings, such as those in numbox.core.bindings.libc and numbox.core.bindings.sqlite, take every
text argument as an intp address of a NUL-terminated C string. c_string() copies the UTF-8 encoding of a
str into a new C buffer and yields the buffer’s address for the duration of a with block.
numbox.utils.lowlevel.get_unicode_data_p() returns the address of a string’s own data without a copy. CPython
stores one, two or four bytes per character there, so those bytes are the text’s UTF-8 only for ASCII text.
c_string works only in Python: numba raises UnsupportedBytecodeError for a with statement that uses it as
the context manager, and numba cannot use the ctypes buffer either. For jitted code, encode the text in Python, add a
NUL byte, store the bytes in a NumPy uint8 array, and take the array’s address in the jitted code with
numbox.utils.lowlevel.array_data_p().
- numbox.utils.cstrings.c_string(s)[source]
Yield the
intpaddress of a new NUL-terminated C string that holds the UTF-8 encoding ofs.The C buffer exists until the
withblock ends. The generator then drops its reference to the buffer and ctypes frees it, so the address must not be used after the block.ValueErroris raised ifscontains a NUL character, because the C string would end there; CPython’ssqlite3.connectrefuses such a file name in the same way. Several strings can be open at once, in onewithstatement or, when their number is known only at run time, through acontextlib.ExitStack:from contextlib import ExitStack from numbox.core.bindings.libc import strlen from numbox.utils.cstrings import c_string with c_string("pear") as p: print(strlen(p)) # 4 with ExitStack() as stack: pointers = [stack.enter_context(c_string(word)) for word in ["pear", "apple"]] print([strlen(p) for p in pointers]) # [4, 5]
c_stringworks only in Python; the module docstring describes how to pass a string to jitted code.
numbox.utils.pysqlite_bridge
Bridging Python sqlite3 connections to the bindings layer
numbox’s SQLite bindings take a connection as the sqlite3 * handle of SQLite’s C API. A connection that Python’s
sqlite3 module opens keeps that handle in a private field of its C
structure. extract_connection_ptr() reads the field with ctypes and returns the
handle as an int, so Python code and the bindings can use one connection:
import sqlite3
from numbox.core.bindings.sqlite.conn import sqlite3_changes
from numbox.utils.pysqlite_bridge import extract_connection_ptr
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE t(x INTEGER)")
conn.execute("INSERT INTO t VALUES (1), (2), (3)")
db_p = extract_connection_ptr(conn)
print(sqlite3_changes(db_p)) # 3, the rows that the last INSERT changed
conn owns the handle. The handle is a plain int, so it holds no reference to conn. Keep conn open and
referenced for as long as any code uses the handle: after conn.close(), or once conn is garbage-collected, the
handle points to freed memory.
numbduck is a related package that makes DuckDB’s C API callable from jitted code. Its
pybridge module reads a DuckDB connection’s
handle the same way, and extract_connection_ptr follows its approach.
If extract_connection_ptr raises RuntimeError
Before it reads the field, the function checks with libraries_coordinated() that
numbox’s bindings and Python’s sqlite3 module report the same SQLite version. The two can use different copies of
SQLite on macOS, where the system’s copy is mapped into every process and can take precedence over the copy that
Python uses. A handle from one copy passed to the other can crash the process, so the function raises RuntimeError
instead, and the message names both versions. The module docstring below gives the remedy, which is to load Python’s
copy first with DYLD_INSERT_LIBRARIES.
After reading the handle, the function checks it by calling sqlite3_errmsg, and it raises RuntimeError unless
the call returns not an error. For a closed connection, the function raises RuntimeError with the message
extracted null sqlite3* from sqlite3.Connection before that call. The function also raises RuntimeError for a
live connection whose last statement failed. After a failed SELEC 1, the message is
extracted connection pointer failed validation: b'near "SELEC": syntax error'. The function works again once a
statement on the connection succeeds. The function raises TypeError for an argument that is not a
sqlite3.Connection.
Functions that read the sqlite3 * handle of a Python sqlite3.Connection for numbox’s SQLite bindings.
numbox’s SQLite bindings take a connection as the sqlite3 * handle of SQLite’s C API, and a connection that
Python’s sqlite3 module opens stores that handle in its C structure. extract_connection_ptr() reads it with
ctypes, as the pybridge module of numbduck
reads the handle of a DuckDB connection. The handle is safe to use only if numbox’s bindings and Python’s sqlite3
module use the same SQLite, which libraries_coordinated() checks by comparing the versions they report.
macOS caveat
On macOS, the system’s SQLite is in the dyld shared cache,
whose structure Apple’s DyldSharedCache.h defines, and the cache is mapped
into every process at launch. LLVM’s JIT linker resolves the sqlite3_* symbols with dlsym(RTLD_DEFAULT), which
returns the first match in load order: the system’s copy. Python’s _sqlite3 module can use another SQLite. A
python.org framework build links SQLite statically, and a Homebrew or conda-forge build links its own shared library.
A handle from one copy passed to the other can produce wrong results or crash the process.
The workaround is to make the process load Python’s SQLite library first:
DYLD_INSERT_LIBRARIES=/path/to/your/libsqlite3.dylib python my_script.py
The library is usually at one of these paths:
Homebrew on Apple Silicon:
/opt/homebrew/opt/sqlite/lib/libsqlite3.dylibHomebrew on Intel:
/usr/local/opt/sqlite/lib/libsqlite3.dylibconda-forge:
$CONDA_PREFIX/lib/libsqlite3.dylib
A python.org framework build has no shared library of its SQLite to insert. Inserting another library, such as Homebrew’s, satisfies the check only if that library reports the same version as the SQLite linked into Python.
On Linux, numbox’s bindings load the library that ctypes.util.find_library("sqlite3") finds, which is usually the
system’s library. A Python whose sqlite3 module links that library, as a Linux distribution’s Python does, needs no
workaround. A Python that includes its own SQLite, as the builds that uv installs do, can report another version, and
extract_connection_ptr() then raises RuntimeError.
- numbox.utils.pysqlite_bridge.extract_connection_ptr(conn)[source]
Return the
sqlite3 *handle of the Pythonsqlite3.Connectionconn, as anint.The handle is borrowed:
connowns it, and theintholds no reference toconn. The caller must keepconnopen and referenced for as long as any code, whether jitted or not, uses the handle. Afterconn.close(), or onceconnis garbage-collected, the handle points to freed memory, and a use of it is a use-after-free. The rule is the one thatSQLITE_STATICsets forbind_textandbind_blob: borrowed memory must outlive every use.TypeErroris raised ifconnis not asqlite3.Connection. Before it reads the handle, the function checks withlibraries_coordinated()that numbox’s bindings and Python’ssqlite3module use the same SQLite, and it raisesRuntimeErrorif they do not. It reads thedbfield of the connection’s C structure through_PysqliteConnectionand raisesRuntimeErrorfor a NULL handle, which a closed connection has. It then checks the handle by callingsqlite3_errmsg(), which must returnnot an error. Because of that check, the function also raisesRuntimeErrorfor a live connection whose most recent statement failed, until a statement on the connection succeeds.
- numbox.utils.pysqlite_bridge.libraries_coordinated()[source]
Return True if numbox’s bindings and Python’s
sqlite3module report the same SQLite version.The function compares the version that
sqlite3_libversion()returns through numbox’s bindings withsqlite3.sqlite_version, the version of the library that Python’s module uses. Different versions mean different copies of SQLite, as on macOS without the workaround in the module docstring.extract_connection_ptr()then raises instead of passing a handle from one copy to the other. Two copies of the same version count as coordinated.
numbox.utils.timer
The timer decorator, an instance of Timer, times calls made from Python, as the module
docstring below describes. It works on a jitted function too. The first call of a jitted function includes numba’s
compilation, and Timer.times keeps only the last call’s time, so read it after a later call. The wrapper that
timer returns is a plain Python function, not a dispatcher, so jitted code cannot call it. A call from jitted code
to a timed function named total fails with numba’s
Untyped global name 'total': Cannot determine Numba type of <class 'function'>.
Wall-clock timing of function calls made from Python.
Decorating a function with timer records each call’s duration in Timer.times under the function’s name and
logs it at INFO on the numbox.utils.timer logger. Importing this module configures no logging, so the log records
do not appear until the application enables INFO for that logger, for instance with
logging.basicConfig(level=logging.INFO).
- class numbox.utils.timer.Timer(precision=3)[source]
Bases:
objectA decorator that times each call of a function from Python and records the duration in
Timer.times.timesis one dict that everyTimershares. It maps a function’s__name__to the duration of its last call in seconds, so two timed functions with the same name share an entry. Each call is also logged at INFO, with the duration formatted toprecisiondigits after the decimal point. A call that raises is neither recorded nor logged. The decorator returns a plain Python function named_, which jitted code cannot call.- times = {}