Skip to main content

iap_messenger

PyPI version PyPI - License

The IA Parc inference plugin allows developers to easily integrate their inference pipeline into IA Parc's production module.

Installation

pip install iaparc-inference

Usage

  • If your inference pipeline support batching:

    from iap_messenger import MsgListener, Message
    
    # Define a callback to query your inference pipeline
    # To load your model only once it is recommended to use a class:
    class MyModel:
        def __init__(self, model_path: str):
            ## Load your model in pytorch, tensorflow or any other backend
        
        def batch_query(msgs: list[Message]) -> list[Message]:
            ''' execute your pipeline on a batch input
                Note:   "parameters" is an optional argument.
                        It can be used to handle URL's query parameters
                        It's a list of key(string)/value(string) dictionaries
            '''
    
    if __name__ == '__main__':
        # Initiate your model class
        my_model = MyModel("path/to/my/model")
    
        # Initiate IAParc listener
        listener = MsgListener(my_model.batch_query)
        # Start the listener
        listener.run()
    
  • If your inference pipeline do not support batching:

    from iap_messenger import MsgListener, Message
    
    # Define a callback to query your inference pipeline
    # To load your model only once it is recommended to use a class:
    class MyModel:
        def __init__(self, model_path: str):
            ## Load your model in pytorch, tensorflow or any other backend
        
        def single_query(msg: Message) -> Message:
            ''' execute your pipeline on a single input
                Note:   "parameters" is an optional argument.
                        It can be used to handle URL's query parameters
                        It's a key(string)/value(string) dictionary
            '''
    
    if __name__ == '__main__':
        # Initiate your model class
        my_model = MyModel("path/to/my/model")
    
        # Initiate IAParc listener
        listener = MsgListener(my_model.single_query, batch=1)  # Note that batch size is forced to 1 here
        # Start the listener
        listener.run()
    

Message consumption and replicas

Each input link is served by one durable JetStream consumer named {queue}-{link}, shared by every replica of the worker. Since the IAP_CONSUMER_MODE release the consumer is a pull consumer: a replica only fetches a message (or a batch) when it is free, so nothing ever waits in the buffer of a busy or dead replica while another one is idle, and a crash only leaves the batch in flight to be redelivered after ack_wait. Older versions used a push consumer with a queue group, where the server spreads messages across replicas at random and up to max_ack_pending messages could sit in a dead pod until ack_wait expired.

Variable Default Role
IAP_CONSUMER_MODE auto auto uses pull unless the existing consumer is a push consumer that still has subscribers bound (workers of a push-only version), in which case it joins it in push mode. pull forces the migration: the push consumer is deleted and recreated as pull, and bound push subscribers stop receiving messages until restarted. push keeps the historical behaviour. The mode chosen for each link is logged at startup.
IAP_MAX_REPLY_RETRIES 3 Deliveries during which a message whose reply could not be published (NATS unreachable past the send retries) is handed back with a NAK and processed again, instead of being acked and its result lost. Past it the message is acked. Costs a second run of the callback, not the request.
IAP_ACK_WAIT_SECONDS 300 JetStream ack_wait. Long callbacks are kept alive with in_progress heartbeats, so this only bounds two things: how long a NATS outage may last before in-flight work is redelivered, and how long a message held by a crashed replica waits before another one gets it.
IAP_PULL_IDLE_TIMEOUT_SECONDS 30 Longest an idle pull fetch blocks. After each idle timeout the worker checks that its consumer still exists and rebuilds the subscription if the API recreated the stream.
IAP_SHUTDOWN_DDL_GRACE_SECONDS 30 On shutdown, how long to keep serving large replies from the local DDL store so the next component can still fetch them.
IAP_MAX_IN_FLIGHT 1 Messages (or batches) of one input whose callbacks run at once in a replica; also the max_in_flight argument of MsgListener. Keep 1 for a model that computes one task at a time. Raise it only when the backend schedules concurrent work itself (e.g. a vLLM engine): each message still keeps its own heartbeat and is acked only when its callback returns, so a crash redelivers all of them. A replica fetches only while a slot is free.

Concurrent callbacks without losing messages

A callback must return only once its work is done: the message is acked when it returns. Returning at once and finishing in a background task (to overlap requests on an engine that batches internally) acks every message before its result exists, and a crash then loses them all for good. Make the callback wait for its result instead (an async def awaiting the work suits this), and set IAP_MAX_IN_FLIGHT to the number of requests the backend should overlap. A sync callback also works: each one runs in its own thread, so it must be safe to call concurrently.

Upgrading a pipeline from push to pull

The stream is a WorkQueue, which refuses two consumers on the same subjects, so a pipeline is either all push or all pull for a given link. auto makes a rolling update safe: new pods join the push consumer while old pods are bound to it, nothing is delivered twice and no old pod breaks. Once every pod of the queue runs a pull-capable version, the migration happens on its own the next time no pod is bound (scale to zero, NATS restart), or immediately with a rollout restart after setting IAP_CONSUMER_MODE=pull. Note that after a NATS restart, a pod of the old version reconnecting to a consumer that has just been migrated fails to subscribe and exits; the rollout replaces it.

Graceful shutdown

On SIGTERM (or SIGINT) the listener stops fetching, lets the task or batch in flight (every one of them with IAP_MAX_IN_FLIGHT above 1) complete and acks it, hands back with a NAK any message already pushed to the process but not started (push mode), waits up to IAP_SHUTDOWN_DDL_GRACE_SECONDS for large replies to be fetched downstream, then exits with code 0. Set the pod's terminationGracePeriodSeconds above the longest inference plus that grace, otherwise Kubernetes kills the pod mid-task and the message is redelivered after ack_wait. A second signal exits at once.

Large payloads (DDL)

Payloads above 8 MB never travel through NATS: the sender keeps them in its local DDL store and the message only carries a uuid@host:port pointer that the recipient resolves over ZMQ. Environment variables:

Variable Role
POD_IP Enables DDL (the address advertised to recipients). Without it, payloads fall back to the NATS object store.
ZMQ_PORT DDL server port (default 5555).
DDL_STORAGE Directory for the blob store. Strongly recommended in production: blobs then never transit through the multiprocessing.Manager pipe. Mount it on a disk-backed emptyDir — a medium: Memory volume is counted against the container's memory limit.

The reply format is negotiated per request: a client that can read a two-frame reply ([status], [payload]) asks with the MP: prefix and the server then hands the stored bytes to ZMQ without copying them; any older peer keeps getting the historical single frame. No configuration and no deployment order are required — mixed versions of workers and inferences-api interoperate.

Features

  • Dynamic batching
  • Autoscalling
  • Support both synchronous and asynchronous queries
  • Data agnostic

License

This project is licensed under the Apache License Version 2.0 - see the Apache LICENSE file for details.

Metadata

Release files for iap-messenger 2.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for iap-messenger 2.2.0
File Size Uploaded
iap_messenger-2.2.0.tar.gz 156.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for iap-messenger 2.2.0
File Interpreter ABI Platform
iap_messenger-2.2.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.10 abi3 Linux glibc 2.17+ x86-64 Details

Total release size: 844.8 kB

Release files / iap_messenger-2.2.0.tar.gz

Download URL iap_messenger-2.2.0.tar.gz
Size 156.7 kB
Tags Source
SHA-256 checksum
How to use checksums
6d7cd3789c813150a3a4d4e8b352e224b17708e8d913cb3a0d8bdc1446f7ad0b
BLAKE2b-256 checksum
How to use checksums
6a927b33f310d65dc3486b707d1db6eeb2ee4d92be0fd60263a929fcd3d47c9b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.22

Release files / iap_messenger-2.2.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL iap_messenger-2.2.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 688.1 kB
Tags CPython 3.10 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
829f02a78c0d06cc004b04b78e115aeeea95eed8226ef539da638efac282efae
BLAKE2b-256 checksum
How to use checksums
34d4ceb899df9652d61f1a7e1cfd769e0340af5d1c7b7f0acdbcd16633208823
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.22

Release history Release notifications | RSS feed

This release

2.2.0 This release

2 release files

2.1.1

2 release files

2.1.0

2 release files

2.0.3

2 release files

2.0.2

2 release files

2.0.1

2 release files

2.0.0

2 release files

1.6.2

2 release files

1.6.1

2 release files

1.6.0

2 release files

1.5.10

2 release files

1.5.9

2 release files

1.5.8

2 release files

1.5.7

2 release files

1.5.6

2 release files

1.5.5

2 release files

1.5.4

2 release files

1.5.3

2 release files

1.5.2

2 release files

1.5.1

2 release files

1.5.0

2 release files

1.4.3

2 release files

1.4.2

2 release files

1.4.1

2 release files

1.4.0

2 release files

1.3.3

2 release files

1.3.2

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.7

2 release files

1.2.6

2 release files

1.2.5

2 release files

1.2.4

2 release files

1.2.3

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.7

2 release files

1.1.6

2 release files

1.1.5

2 release files

1.1.4

2 release files

1.1.3

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page