cortex.core¶
core ¶
Core module for Cortex framework.
Attributes¶
SyncMessageCallback
module-attribute
¶
A blocking callback invoked on the receive thread — must not return a coroutine.
Classes¶
AsyncExecutor ¶
Bases: BaseExecutor
Runs an async callable in a tight loop, yielding to the event loop.
Used by :class:cortex.core.subscriber.Subscriber to drive its
receive → decode → dispatch loop. Exceptions are logged and the loop
continues; only :class:asyncio.CancelledError stops it.
Example
Source code in src/cortex/core/executor.py
BaseExecutor ¶
Bases: ABC
Abstract base class for async executors.
Provides common interface for starting, stopping, and running async callback functions.
Source code in src/cortex/core/executor.py
RateExecutor ¶
Bases: BaseExecutor
Runs an async callable at a target rate in Hz.
Uses time.perf_counter for scheduling. If a callback overruns the
nominal period, next_exec_time stays on the fixed grid (only
+ interval per invocation); the loop then sleeps 0 until the clock
catches up, so missed ticks are not skipped. This matches the
historical neurosim ZMQNODE constant-rate executor behavior and is
appropriate for simulation stepping.
Example
Source code in src/cortex/core/executor.py
Node ¶
User-facing composition unit that owns publishers, subscribers, and timers.
A node bundles a shared :class:zmq.asyncio.Context, a collection of
:class:cortex.core.publisher.Publisher and
:class:cortex.core.subscriber.Subscriber instances created through it,
and any number of periodic timer callbacks.
:meth:run starts every subscriber receive loop and every timer as
asyncio tasks and gathers them until cancelled. Use as an async
context manager so that :meth:close runs on exit and cleans up
sockets, tasks, and the shared ZMQ context.
Example
class CameraNode(Node):
def __init__(self):
super().__init__("camera_node")
self.pub = self.create_publisher("/camera/image", ImageMessage)
self.create_timer(1 / 30, self.publish_image)
async def publish_image(self):
self.pub.publish(ImageMessage(data=capture_image()))
async def main():
async with CameraNode() as node:
await node.run()
Source code in src/cortex/core/node.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 | |
Attributes¶
stop_event
property
¶
Shared threading.Event set when the node is stopping.
Sync code that opts into the node's lifecycle (publisher threads,
I/O loops, anything spawned via :meth:spawn_thread) should poll
node.stop_event.is_set() and exit promptly when it goes True.
Async code should not need this — it gets cancellation through the
normal asyncio task lifecycle.
Functions¶
create_publisher ¶
create_publisher(
topic_name: str,
message_type: type[Message],
queue_size: int = 10,
mode: PublisherMode = "async",
) -> Publisher
Create a publisher for a topic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_name
|
str
|
Name of the topic. |
required |
message_type
|
type[Message]
|
Type of messages to publish. |
required |
queue_size
|
int
|
Output queue size. |
10
|
mode
|
PublisherMode
|
|
'async'
|
Returns:
| Type | Description |
|---|---|
Publisher
|
Publisher instance |
Source code in src/cortex/core/node.py
create_subscriber ¶
create_subscriber(
topic_name: str,
message_type: type[Message],
callback: MessageCallback
| SyncMessageCallback
| None = None,
queue_size: int = 10,
wait_for_topic: bool = True,
topic_timeout: float = 30.0,
mode: SubscriberMode = "async",
strict_fingerprint: bool | None = None,
cpu_affinity: list[int] | None = None,
sched_priority: int | None = None,
) -> Subscriber | ThreadedSubscriber
Create a subscriber for a topic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_name
|
str
|
Name of the topic. |
required |
message_type
|
type[Message]
|
Type of messages expected. |
required |
callback
|
MessageCallback | SyncMessageCallback | None
|
Function to call when messages arrive. |
None
|
queue_size
|
int
|
Input queue size (ignored when |
10
|
wait_for_topic
|
bool
|
Whether to wait for the topic to be available. |
True
|
topic_timeout
|
float
|
Timeout for waiting for topic, in seconds. |
30.0
|
mode
|
SubscriberMode
|
|
'async'
|
strict_fingerprint
|
bool | None
|
When True, a fingerprint mismatch between
the topic and |
None
|
cpu_affinity
|
list[int] | None
|
Sync mode only. Pin the receive thread to the given CPU set (Linux only; ignored elsewhere). |
None
|
sched_priority
|
int | None
|
Sync mode only. Run the receive thread under
|
None
|
Returns:
| Type | Description |
|---|---|
Subscriber | ThreadedSubscriber
|
|
Subscriber | ThreadedSubscriber
|
|
Source code in src/cortex/core/node.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
spawn_thread ¶
spawn_thread(
target: Callable[..., None],
*args,
name: str | None = None,
**kwargs,
) -> threading.Thread
Start an OS thread owned by this node.
target is invoked as target(stop_event, *args, **kwargs) —
the first positional argument is always the node's shared
threading.Event. The thread is started immediately, registered
for run() keepalive (so the asyncio side won't fall through),
and joined deterministically by :meth:close.
This is the canonical way to drive sync-mode publishers, custom polling loops, or any blocking I/O the node should manage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Callable[..., None]
|
The thread body. Must accept the stop event as its first positional arg. |
required |
*args
|
Forwarded to |
()
|
|
name
|
str | None
|
Thread name; defaults to |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
Thread
|
class: |
Example
def control_loop(stop, pub, rate_hz):
interval = 1.0 / rate_hz
next_t = time.perf_counter()
while not stop.is_set():
...
pub.publish(WheelCommand(...))
next_t += interval
time.sleep(max(0, next_t - time.perf_counter()))
pub = node.create_publisher(..., mode="sync")
node.spawn_thread(control_loop, pub, 1000.0)
await node.run() # blocks until Ctrl+C; close() joins the thread
Source code in src/cortex/core/node.py
create_timer ¶
Create a periodic timer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
float
|
Timer period in seconds |
required |
callback
|
AsyncCallback
|
Async function to call on each timer tick |
required |
Source code in src/cortex/core/node.py
run
async
¶
Run the node, processing messages and timers.
This is the main async entry point for the node. Sync subscribers are started on their own OS threads and run independently of the asyncio event loop.
Source code in src/cortex/core/node.py
stop ¶
Stop the node.
Source code in src/cortex/core/node.py
close
async
¶
Close the node and release all resources.
Source code in src/cortex/core/node.py
get_publisher ¶
get_subscriber ¶
spin ¶
Block the calling thread until the node is stopped.
Sync counterpart to :meth:run. Use this when the node owns only
sync work — sync subscribers, threads spawned via
:meth:spawn_thread, or nothing more than a publisher driven from
the calling thread itself. No asyncio loop is created.
Raises RuntimeError if the node has async timers or async
subscribers, since those need :meth:run to be scheduled. Ctrl+C
is delivered as :class:KeyboardInterrupt and propagates so the
caller can decide whether to swallow it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float | None
|
Optional cap (seconds) on how long to block. |
None
|
Example
Source code in src/cortex/core/node.py
close_sync ¶
Sync counterpart to :meth:close.
Tears down sockets, joins spawned threads, and terms zmq contexts
without ever entering an asyncio loop. Safe to call from a plain
def main() — including from inside __exit__ when the node
is used as a regular with context manager.
Will refuse to run if the node has async timers/subscribers; for
those, use await node.close().
Source code in src/cortex/core/node.py
Publisher ¶
Sends typed messages on a topic over a ZMQ PUB socket.
On construction the publisher binds its own IPC socket, registers the
(topic, address, fingerprint) triple with the discovery daemon, and
becomes ready. :meth:publish is synchronous and non-blocking by default
— if the send queue is full the message is dropped and False is
returned.
Always create via :meth:Node.create_publisher; that path shares the
node's async context and tracks the publisher for clean shutdown.
Note
zmq.PUB sockets are not thread-safe. Do not call
:meth:publish concurrently from multiple threads or tasks on the
same :class:Publisher instance.
Example
Source code in src/cortex/core/publisher.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
Attributes¶
is_registered
property
¶
Check if publisher is registered with discovery daemon.
last_publish_time
property
¶
Get the timestamp of the last published message.
Functions¶
publish ¶
Serialize and send message on this topic.
Uses the frame-aware transport path so large NumPy / PyTorch buffers ride as separate ZMQ frames (zero-copy handoff).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
Instance whose class matches :attr: |
required |
flags
|
int
|
ZMQ send flags. Default :data: |
NOBLOCK
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
full ( |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in src/cortex/core/publisher.py
close ¶
Close the publisher and unregister from discovery.
Source code in src/cortex/core/publisher.py
Subscriber ¶
Bases: SubscriberBase
Async subscriber: receives typed messages on a topic from a ZMQ SUB socket.
On construction, the subscriber performs a non-blocking lookup against
the discovery daemon. If the topic already has a publisher it connects
immediately; otherwise it defers and retries with an async polling
wait inside :meth:run.
When constructed with a callback the subscriber drives its own
receive loop (one task, one callback at a time — see
:class:cortex.core.executor.AsyncExecutor). Without a callback the
subscriber is passive and the caller polls via :meth:receive.
Always create via :meth:Node.create_subscriber.
Source code in src/cortex/core/subscriber.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
MessageFingerprintError ¶
SubscriberBase ¶
Discovery + connection scaffolding shared by all subscriber implementations.
Subclasses are responsible only for the I/O loop. They set
:attr:_topic_info via :meth:_lookup_blocking (or the async variant
used by the asyncio subscriber) and then open whatever socket they
prefer against :attr:_topic_info.address.
Source code in src/cortex/core/subscriber_base.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
SubscriberStats
dataclass
¶
Per-subscriber counters; updated by the receive loop.
Source code in src/cortex/core/subscriber_base.py
ThreadedSubscriber ¶
Bases: SubscriberBase
Synchronous SUB-side receive loop running on a dedicated OS thread.
Lifecycle:
- Construction blocks on a discovery lookup (with optional wait), opens
a fresh sync
zmq.Context, and connects the SUB socket. Construction does not start the worker thread. - :meth:
startspins up the thread; the thread blocks inpoller.poll(timeout_ms)between messages so shutdown is prompt. - :meth:
stopsignals the thread and joins it (with a 1 s default grace period); :meth:closecalls :meth:stopand tears down zmq.
The class is reentrant-safe in the trivial sense that start /
stop / close are idempotent. zmq.SUB itself is single-
threaded; do not call :meth:receive from another thread while the
worker is running.
Source code in src/cortex/core/sync_subscriber.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
Functions¶
start ¶
Spin up the receive thread (idempotent).
Source code in src/cortex/core/sync_subscriber.py
stop ¶
Signal the worker and join it (idempotent).
Source code in src/cortex/core/sync_subscriber.py
close ¶
Stop the worker and tear down zmq state (idempotent).