Bulk Operations & Reliability¶
See the Bulk Operations guide for the contract and safety invariants.
Bulk publishing¶
BulkPublishOptions
dataclass
¶
Bounds for one publish_many / iter_publish operation.
Every bound is explicit; none is a tuning recommendation. The defaults are conservative starting points — measure before changing them.
Attributes:
| Name | Type | Description |
|---|---|---|
max_in_flight |
int
|
Maximum envelopes submitted to the transport but not
yet settled (async broker). Without an |
max_buffer_bytes |
int
|
Maximum sum of in-flight body bytes. An envelope
larger than this can never be admitted and is reported
|
admission_timeout |
float
|
Seconds to wait for an in-flight/byte slot before
reporting an item |
confirm_timeout |
float | None
|
Per-item confirm wait override (async broker). A
timeout reports |
overall_timeout |
float | None
|
Whole-operation deadline. On expiry admission stops;
never-submitted items are |
drain_grace |
float
|
Seconds to wait for in-flight items after the overall
deadline before classifying them |
max_items |
int
|
Upper bound on |
Source code in src/rabbitkit/core/bulk.py
BulkPublishItem
dataclass
¶
Outcome of ONE input envelope.
Keyed by index (position in the caller's input), never solely by
message_id — input IDs may legitimately repeat. attempt_id is a
fresh UUID per submission so an UNKNOWN item can be reconciled against a
downstream inbox even when the same message_id was published twice.
Source code in src/rabbitkit/core/bulk.py
Attributes¶
ok: bool
property
¶
True only for CONFIRMED. UNKNOWN is never ok.
duration: float | None
property
¶
Seconds from submission to settlement, when both are known.
safe_to_resubmit: bool
property
¶
True when resubmitting cannot duplicate a broker-held message
(NOT_SENT / INVALID after fixing the input). UNKNOWN is
deliberately False — it needs stable IDs plus deduplication.
BulkPublishResult
dataclass
¶
Input-ordered per-item outcomes for one publish_many call.
Source code in src/rabbitkit/core/bulk.py
Attributes¶
resubmittable: tuple[BulkPublishItem, ...]
property
¶
Items that were definitively never sent (safe to resubmit).
failed: tuple[BulkPublishItem, ...]
property
¶
Everything that is not CONFIRMED — including UNKNOWN.
Methods:¶
raise_for_status() -> BulkPublishResult
¶
Raise :class:BulkPublishError unless every item is CONFIRMED.
BulkPublishError
¶
Bases: Exception
Raised by :meth:BulkPublishResult.raise_for_status when not every
item is CONFIRMED. Carries the full result for reconciliation.
Source code in src/rabbitkit/core/bulk.py
BulkPublishStatus
¶
Bases: str, Enum
Actionable per-item state of a bulk publish (broker.publish_many).
Stricter than :class:PublishStatus and deliberately preserves
uncertainty: SENT, a confirm timeout, and a mid-publish exception all
become UNKNOWN (the publish may have reached the broker) rather than
a success or a definite failure. See :mod:rabbitkit.core.bulk.
Source code in src/rabbitkit/core/types.py
PublishPreparer
¶
Transport-independent preparation for one envelope.
input → envelope validation → frozen copy → final byte/header checks.
Middleware/serialization run later, inside the broker's publish chain,
exactly once per attempt. Everything here happens BEFORE admission so a
bad item never consumes an in-flight slot.
The prepared envelope is a copy whose headers dict is snapshotted —
a caller mutating its original dict after publish_many returns (or
while it is still running) cannot alter what is on the wire.
Source code in src/rabbitkit/core/bulk.py
Methods:¶
prepare(index: int, raw: Any) -> tuple[MessageEnvelope | None, BulkPublishItem | None]
¶
Return (envelope, None) when admissible, else (None, INVALID item).
Source code in src/rabbitkit/core/bulk.py
classify_publish_outcome(outcome: PublishOutcome | None) -> tuple[BulkPublishStatus, str]
¶
Map a transport PublishOutcome onto the bulk vocabulary.
Precedence rules (safety invariant 2):
RETURNEDwins over everything — an unroutable message is not a successful routed publication even though the broker also confirms it.SENT(confirms disabled) isUNKNOWN, not confirmed.TIMEOUTandUNKNOWNareUNKNOWN— the frame may have reached the broker.NOT_SENTisNOT_SENT— the transport proved nothing left.ERRORwith reasonexchange_not_foundisUNROUTABLE(the broker refused to route it); any otherERRORisUNKNOWNunless the error proves nothing was submitted (backpressure drop, broker not started) or that the input itself was invalid (oversized body /ValueError/TypeErrorfrom validation).None(a duck-typed publish fn returned nothing) isUNKNOWN.
The transport's own reason code is kept when it has one.
Source code in src/rabbitkit/core/bulk.py
Selected settlement¶
SettlementReport
dataclass
¶
Input-ordered per-item report for one ack_many/nack_many call.
Source code in src/rabbitkit/core/settlement.py
SettlementItem
dataclass
¶
Source code in src/rabbitkit/core/settlement.py
SettlementReportError
¶
Bases: Exception
Raised by :meth:SettlementReport.raise_for_status when any item was
not dispatched (already-settled items are tolerated — they are no-ops).
Source code in src/rabbitkit/core/settlement.py
SettlementItemStatus
¶
Bases: str, Enum
Per-item outcome of ack_many / nack_many.
DISPATCHED = handed to the transport (a local wire-write boundary).
RabbitMQ never acknowledges a consumer ack, so no member here can mean
"broker confirmed".
Source code in src/rabbitkit/core/types.py
SettlementAction
¶
Bases: str, Enum
Which consumer settlement a bulk call / coordinator command performs.
Source code in src/rabbitkit/core/types.py
plan_selected_settlement(messages: Iterable[Any], *, runtime: str, fail_fast: bool = True) -> SettlementPlan
¶
Validate a selected-settlement input before any I/O.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Iterable[Any]
|
Caller-supplied deliveries (must be |
required |
runtime
|
str
|
|
required |
fail_fast
|
bool
|
When True and ANY item is invalid/stale/duplicate, nothing
is approved: every otherwise-valid item is reported
|
True
|
Source code in src/rabbitkit/core/settlement.py
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 | |
Safe coalescing¶
SettlementCoordinator
¶
Channel-wide delivery ledger with provably safe ack coalescing.
One coordinator per channel generation. EVERY delivery on that channel
must be :meth:register-ed before its handler runs; if that ownership
cannot be guaranteed (another consumer shares the channel and does not
register), coalescing is unsafe — construct with coalesce=False.
Decision rule for a cumulative ack: let P be the longest prefix of
the ledger (ascending tag order) in which every entry is SUCCESS.
If |P| >= 2 emit ack(max(P), multiple=True); |P| == 1 is a
plain individual ack. max(P) must also lie below the generation's
first gap -- the lowest delivery tag that was never registered (refused
by max_pending, consumed by someone else on the channel, or skipped
by the caller). The broker settles EVERY unacked tag up to max(P), so
a gap below it would be acknowledged without ever being processed. Tags
above a gap are acked individually; :meth:invalidate (a new channel,
where tags restart at 1) clears the gap. Tags below the first registered
one count as a gap too: the coordinator must own the channel from
delivery tag 1. Any SUCCESS entry AFTER the first non-success
entry is acked individually (never buffered past max_hold). NACK /
REJECT intents are always individual and are emitted in tag order
interleaved with acks, so a later prefix decision can never leap over
an unsettled reject.
Thread-safe: every method takes the internal lock. Command emission is the adapter's job and must happen on the transport owner (sync I/O thread / event loop).
Source code in src/rabbitkit/core/settlement.py
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 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 | |
Attributes¶
pending: int
property
¶
Registered but not yet emitted (any state).
ack_ready: int
property
¶
Deliveries approved for an ack but not yet emitted.
frontier: int
property
¶
Highest tag a cumulative ack could cover right now (0 = none).
This is the end of the leading all-SUCCESS run, NOT the highest completed tag — that difference is the whole point of the coordinator (invariant I1).
gap_count: int
property
¶
Blocking deliveries sitting below an ack-ready one — i.e. how many stragglers are stranding otherwise-settleable work.
oldest_pending_age: float
property
¶
Seconds since the oldest still-unsettled delivery was registered (0.0 when the ledger is empty). The signal for a stuck handler holding the frontier back.
stats: dict[str, float]
property
¶
Snapshot for metrics/debugging. coalescing_ratio is
deliveries settled per AMQP frame sent — 1.0 means no coalescing.
gap_floor: int
property
¶
Lowest delivery tag of this generation that was never registered (0 = none). No cumulative ack will reach it or anything above it.
Methods:¶
register(delivery_tag: int) -> None
¶
Register a delivery BEFORE its handler runs. Tags must be strictly increasing within a generation (AMQP guarantees this per channel), so a redelivered message — which always arrives with a NEW, higher tag — registers cleanly while the old tag can never be re-registered.
Raises :class:LedgerFullError when max_pending is reached. The
refused tag is not recorded, so the next registration sees it as a
gap and cumulative acks stop short of it for this generation.
A tag that skips ahead (delivery_tag > last + 1) records a gap at
last + 1 for the same reason: the skipped deliveries are unacked
at the broker and unknown to the ledger.
Source code in src/rabbitkit/core/settlement.py
mark_success(delivery_tag: int) -> None
¶
Handler succeeded: the delivery is ack-safe. Idempotent.
mark_retry_pending(delivery_tag: int) -> None
¶
Handler failed and the retry/terminal path now owns this delivery.
It is NOT settleable through the coordinator; it blocks any
cumulative ack above it until :meth:release (settled elsewhere).
Source code in src/rabbitkit/core/settlement.py
mark_failed(delivery_tag: int) -> None
¶
Handler failed with no settlement decision: block the frontier and
never emit anything. The delivery stays unacked, so the broker
redelivers it when the channel closes. It can still be settled
explicitly with :meth:mark_nack / :meth:mark_reject, but never
acked.
Source code in src/rabbitkit/core/settlement.py
mark_cancelled(delivery_tag: int) -> None
¶
Handler was cancelled (shutdown, timeout): same treatment as
:meth:mark_failed — blocks the frontier, never acked.
Source code in src/rabbitkit/core/settlement.py
release(delivery_tag: int) -> None
¶
Remove a delivery that was settled OUTSIDE the coordinator (e.g. by the retry middleware's own ack after a confirmed handoff, or a MANUAL handler). Unknown tags are ignored (idempotent).
Source code in src/rabbitkit/core/settlement.py
prepare(*, force_individual: bool = False) -> SettlementBatch
¶
Plan the commands that are safe to emit now, WITHOUT settling them.
The covered tags are reserved: they stay in the ledger, a second
prepare() will not re-plan them, and nothing above them may be
cumulatively acked while their wire outcome is unknown. Resolve the
batch with :func:emit_batch, or by hand via
:meth:commit_command / :meth:fail_command / :meth:release_commands.
Every command MUST be emitted in the order given, and a command must never be emitted after an earlier one failed.
Source code in src/rabbitkit/core/settlement.py
commit_command(batch: SettlementBatch, command: SettlementCommand) -> None
¶
The frame reached the broker: settle its tags for good.
A no-op when the generation moved on under us (the channel was rebuilt mid-batch), because those tags are already gone and the broker will redeliver them.
Source code in src/rabbitkit/core/settlement.py
fail_command(batch: SettlementBatch, command: SettlementCommand, error: BaseException) -> bool
¶
The frame did NOT reach the broker, or we cannot tell.
The covered tags become UNRESOLVED: they leave the ledger and are never re-emitted, because re-sending a settlement whose first attempt may have landed is how you turn an ambiguity into a protocol error. Leaving them unacknowledged is always safe -- the broker redelivers them when the channel goes away.
Returns True when the generation was invalidated, which the caller must treat as "this channel can no longer be used for coalescing". That happens for a failed NACK or REJECT: the tag may still be unacknowledged at the broker, so ANY later cumulative ack above it would silently acknowledge the very delivery we meant to requeue. An ACK that fails is not dangerous in the same way -- a later cumulative ack sweeping it up produces exactly the intended outcome.
Source code in src/rabbitkit/core/settlement.py
release_commands(batch: SettlementBatch, commands: Sequence[SettlementCommand]) -> None
¶
These commands were never attempted: un-reserve their tags.
They go back to being ordinary ledger entries and will be planned
again on the next :meth:prepare. Nothing reached the wire, so this
is always safe.
Source code in src/rabbitkit/core/settlement.py
plan(*, force_individual: bool = False) -> list[SettlementCommand]
¶
Plan AND immediately settle every command in the ledger.
This is the pure-planning primitive. It assumes the caller emits every
returned command, in order, and that they all succeed -- so it is only
appropriate for tests, for TestBroker, and for callers that supply
their own ordering and failure guarantees.
For anything that touches a real channel use :meth:prepare plus
:func:emit_batch, which stops on the first failure instead of
letting a cumulative ack follow a nack that never landed.
Source code in src/rabbitkit/core/settlement.py
invalidate() -> tuple[int, ...]
¶
Reconnect / channel rebuild: drop the WHOLE ledger and bump the generation. Returns the dropped tags for logging. Old tags must never be replayed onto the replacement channel — the broker will redeliver every unacked message on it anyway (invariants I2, I5).
Source code in src/rabbitkit/core/settlement.py
drain_plan() -> list[SettlementCommand]
¶
Shutdown: plan AND settle everything already approved.
Individual frames only — at shutdown there is no reason to wait for a
prefix. Every blocking delivery is left UNACKED for redelivery; this
never acks merely to empty the ledger (invariant I6). Same caveat as
:meth:plan: use :meth:prepare_drain for a real channel.
Source code in src/rabbitkit/core/settlement.py
prepare_drain() -> SettlementBatch
¶
SettlementCommand
dataclass
¶
One wire command the transport adapter must issue, in order.
covers lists every delivery tag this command settles (for a
cumulative ack that is the whole approved prefix) so adapters and tests
can account for each tag exactly once.
Source code in src/rabbitkit/core/settlement.py
DeliveryState
¶
Bases: str, Enum
Ledger state of one delivery inside a SettlementCoordinator.
A delivery being finished is not the same as being safe to ack. Only
SUCCESS may advance the cumulative-ack frontier; only SUCCESS /
NACK / REJECT are emitted at all::
OUTSTANDING ──┬─> SUCCESS ack-safe, advances the frontier
├─> NACK emitted individually, then settled
├─> REJECT emitted individually, then settled
├─> RETRY_PENDING ─┐ owned elsewhere, blocks the frontier
├─> FAILED │ blocks the frontier, never emitted
└─> CANCELLED │ blocks the frontier, never emitted
└─> SUCCESS / NACK / REJECT
SUCCESS is reachable only from OUTSTANDING or RETRY_PENDING:
a delivery whose handler failed or was cancelled can never be acked
(invariant I3). FAILED and CANCELLED deliveries are left unacked
so the broker redelivers them; release() drops them from the ledger
when something else settled them.
Source code in src/rabbitkit/core/types.py
CoordinatorError
¶
Bases: RuntimeError
Invalid use of :class:SettlementCoordinator. Base class for the
specific errors below; catching it catches all of them.
UnknownDeliveryError
¶
Bases: CoordinatorError
A delivery tag that was never registered on this generation.
Silently ignoring it would let a caller bug corrupt the frontier, so it
is always loud. A tag from an OLDER generation (the channel was rebuilt
under you) raises :class:StaleGenerationError instead.
Source code in src/rabbitkit/core/settlement.py
StaleGenerationError
¶
Bases: CoordinatorError
A delivery tag from a previous channel generation.
The channel it arrived on is gone; the broker will redeliver the message on the new one with a NEW tag. Emitting anything for the old tag would settle an unrelated message (invariants I2, I5).
Source code in src/rabbitkit/core/settlement.py
ContradictorySettlementError
¶
Bases: CoordinatorError
A settlement decision that contradicts one already recorded.
Repeating the SAME decision is an idempotent no-op; changing it (ack → nack, nack → ack, acking something that FAILED) is never silently accepted (invariant I4).
Source code in src/rabbitkit/core/settlement.py
LedgerFullError
¶
Bases: CoordinatorError
max_pending reached — the ledger refuses to grow further.
Raised by :meth:SettlementCoordinator.register, so the caller applies
backpressure (stop consuming / lower prefetch). The delivery stays
unacked and the broker redelivers it when the channel closes. Bounds
NEVER cause an unsafe ack (invariant I7): the refused tag becomes a
gap, and no cumulative ack on this generation will ever reach past it
(deliveries above it are acked individually).
Source code in src/rabbitkit/core/settlement.py
CoalescingAcker
¶
Safe cumulative acking for ONE channel generation (plan §8.3).
Every delivery on the channel must be :meth:register-ed before its
handler runs, then reported via :meth:complete / :meth:fail /
:meth:retry_pending / :meth:release. flush() asks the
:class:~rabbitkit.core.settlement.SettlementCoordinator for the
commands that are provably safe and emits them through the three
callables — ack_fn(tag, multiple), nack_fn(tag, requeue),
reject_fn(tag, requeue) — which must marshal onto the transport
owner (see :class:BatchAcker's notes on pika thread safety).
One acker per channel. The emit callables are bound to one channel
and delivery tags are a per-channel counter, so feeding two channels'
tags into one acker would ack the wrong messages. Pass channel_key
(the channel object itself is the natural key — all pika/aio-pika
channels are identity-hashable) and that convention becomes an enforced
invariant: a delivery from any other channel raises
:class:ChannelMismatchError at :meth:register time, before it can
corrupt the ledger. An unbound acker binds to the first channel_key
it is given. :class:CoalescingAckerGroup does this for you.
on_reconnect() invalidates the ledger; old tags are never replayed.
Pass marshal whenever flush_interval_ms > 0. The interval
timer is a threading.Timer, so without it the emit callables run on
a background thread instead of the transport owner. That is not merely
unsupported, it fails SILENTLY: loop.create_task() from a foreign
thread only raises under asyncio debug mode, so in production the task
is queued without waking the loop — a busy loop happens to pick it up, an
idle one never does. At prefetch=1 the loop goes idle waiting for the
next delivery that the un-emitted ack would have unlocked, and the
consumer deadlocks.
marshal takes a zero-argument callable and runs it on the transport
owner; both standard entry points match that signature directly, so it is
one argument, not a wrapper around each callable::
# asyncio / aio-pika
acker = CoalescingAcker(..., marshal=loop.call_soon_threadsafe)
# pika
acker = CoalescingAcker(..., marshal=connection.add_callback_threadsafe)
With marshal set, the whole interval flush — planning and emission —
runs on the owner, so ordinary channel.basic_ack(...) /
loop.create_task(...) callables are safe. Size-triggered and manual
flushes already run on the caller's thread and are unaffected.
flush_interval_ms=0 disables the timer entirely; then no marshalling
is needed because every flush is one you drive yourself.
Source code in src/rabbitkit/highload/batch.py
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 | |
Attributes¶
channel_key: Any
property
¶
The channel this acker is bound to, or None while unbound.
metrics: dict[str, float]
property
¶
Coordinator instrumentation for this channel: registered,
pending, outstanding, ack_ready, frontier,
settled, coalesced, frames_sent, coalescing_ratio,
gap_count, oldest_pending_age, invalidations,
dropped_on_invalidate.
generation: int
property
¶
The current channel generation.
It advances on :meth:on_reconnect, and also when a failed
nack/reject forces the acker to abandon coalescing on this channel.
Methods:¶
register(delivery_tag: int, *, channel_key: Any = None) -> None
¶
Register a delivery BEFORE its handler runs.
Pass channel_key (normally the channel object the delivery
arrived on) to have the one-acker-per-channel rule enforced: an
unbound acker binds to it, a bound acker raises
:class:ChannelMismatchError on anything else. Omitting it keeps the
legacy, unchecked behavior.
Source code in src/rabbitkit/highload/batch.py
retry_pending(delivery_tag: int) -> None
¶
The retry middleware owns this delivery now; it blocks coalescing
above it until :meth:release.
abandon(delivery_tag: int) -> None
¶
The handler failed with no settlement decision (FAILED).
Blocks the frontier and is NEVER acked — the delivery stays unacked
so the broker redelivers it when the channel closes. Use this instead
of leaving the tag OUTSTANDING so the ledger records that nobody
is still working on it.
Source code in src/rabbitkit/highload/batch.py
cancel(delivery_tag: int) -> None
¶
The handler was cancelled (shutdown, timeout) — CANCELLED.
Same treatment as :meth:abandon: blocks the frontier, never acked.
Source code in src/rabbitkit/highload/batch.py
on_reconnect() -> tuple[int, ...]
¶
Channel rebuilt: drop every pending tag (never replay them).
Source code in src/rabbitkit/highload/batch.py
CoalescingFlushReport
dataclass
¶
What a flush PLANNED versus what actually reached the broker.
commands is the plan. emitted is the subset whose frames the
transport accepted; only those tags are settled. not_attempted were
deliberately withheld after a failure, because a cumulative ack must
never follow a settlement that did not land.
Source code in src/rabbitkit/highload/batch.py
CoalescingAckerGroup
¶
One :class:CoalescingAcker per channel, created on demand.
rabbitkit gives every subscriber queue its own channel, and delivery tags are a PER-CHANNEL counter — so a consumer with several queues needs several ledgers::
Channel A → CoalescingAcker A → SettlementCoordinator A
Channel B → CoalescingAcker B → SettlementCoordinator B
This group keeps that isolation for you: factory(channel) builds a
fully wired acker (its ack_fn/nack_fn/reject_fn bound to THAT
channel — only you know how to reach your transport), the group caches it
per channel, and every per-delivery call carries the channel so a
cross-channel mistake raises :class:ChannelMismatchError instead of
acking the wrong messages.
Channels are used as dict keys (all pika/aio-pika channel objects are
identity-hashable). The group holds a strong reference to each channel it
settles on, so call :meth:on_reconnect when one is rebuilt (or
:meth:reset when the whole connection is) to drop it.
Correctness does NOT depend on you making that call: a rebuilt channel is
a different object, so the next :meth:for_channel builds a fresh acker
with an empty ledger and the stale one is never consulted again. Calling
it releases the retired acker (and its channel reference) promptly and
keeps the metrics honest.
Wiring :meth:reset to the transport's on_reconnect hook is safe.
The hook fires once per rebuilt connection (publisher and consumer, on
both brokers, also for a broker-closed connection), after aio-pika has
restored the consumers, so restored channels may already be delivering
when it runs. :meth:reset therefore drops only the ledgers of channels
that are closed and leaves live ones alone. Dropping a live ledger would
leave its deliveries unacked on a channel the broker still considers
healthy, so they would never be redelivered.
Usage::
def build(channel: Any) -> CoalescingAcker:
return CoalescingAcker(
ack_fn=lambda t, m: loop.create_task(channel.basic_ack(t, multiple=m)),
nack_fn=lambda t, r: loop.create_task(channel.basic_nack(t, requeue=r)),
reject_fn=lambda t, r: loop.create_task(channel.basic_reject(t, requeue=r)),
config=BatchAckConfig(batch_size=50, flush_interval_ms=200),
channel_key=channel,
marshal=loop.call_soon_threadsafe, # required with an interval timer
)
group = CoalescingAckerGroup(factory=build)
@broker.subscriber(queue="orders", ack_policy=AckPolicy.MANUAL)
async def handle(body: bytes, msg: RabbitMessage) -> None:
channel = msg.raw_message.channel
group.register(channel, msg.delivery_tag)
...
group.complete(channel, msg.delivery_tag)
Source code in src/rabbitkit/highload/batch.py
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 | |
Attributes¶
channels: int
property
¶
Number of channels with a live acker.
pending: int
property
¶
Registered-but-unsettled deliveries across every channel.
metrics: dict[str, float]
property
¶
Per-channel metrics summed across the group (coalescing_ratio
is recomputed from the totals, not averaged).
Methods:¶
for_channel(channel: Any) -> CoalescingAcker
¶
Return (creating on first use) the acker that owns channel.
Source code in src/rabbitkit/highload/batch.py
register(channel: Any, delivery_tag: int) -> None
¶
Register a delivery BEFORE its handler runs, on channel's ledger.
abandon(channel: Any, delivery_tag: int) -> None
¶
cancel(channel: Any, delivery_tag: int) -> None
¶
flush(reason: FlushReason = FlushReason.MANUAL) -> GroupFlushReport
¶
Flush every channel's acker; never let one channel's failure skip the others (each acker records its own errors in its report).
Source code in src/rabbitkit/highload/batch.py
on_reconnect(channel: Any) -> tuple[int, ...]
¶
One channel was rebuilt: drop its ledger and retire its acker.
Returns the dropped delivery tags (the broker redelivers them). The
replacement channel is a different object, so the next
:meth:for_channel builds a fresh acker for it. Unknown channels are
a no-op, so this is safe to call from a reconnect hook that does not
track which channels were in use.
Source code in src/rabbitkit/highload/batch.py
reset() -> int
¶
The connection was rebuilt: drop the ledger of every channel that is CLOSED. Returns the total number of dropped tags.
A channel that is still open keeps its ledger. The reconnect hook
fires after aio-pika has already restored the consumers, and once
per connection (publisher and consumer), so by the time it runs a
restored channel may already be delivering. Dropping that live
ledger stranded its deliveries: their complete() found no
ledger, nothing was ever acked, and the broker never redelivered
them because the channel stayed open. A live channel's ledger is
valid, so keeping it is always correct; a closed channel's tags are
redelivered by the broker. A key that reports no liveness at all
(not a pika/aio-pika channel) is dropped, as before.
Source code in src/rabbitkit/highload/batch.py
close() -> GroupFlushReport
¶
Close every acker (draining what is approved) and clear the group.
Source code in src/rabbitkit/highload/batch.py
GroupFlushReport
dataclass
¶
Aggregate of one :meth:CoalescingAckerGroup.flush across channels.
Source code in src/rabbitkit/highload/batch.py
ChannelMismatchError
¶
Bases: RuntimeError
A delivery from a different channel was handed to a bound
:class:CoalescingAcker.
Delivery tags are a PER-CHANNEL counter: tag 7 on channel A and tag 7 on
channel B are different messages. Mixing two channels in one ledger makes
a cumulative ack computed from channel A's prefix settle channel B's
messages — silent, wrong, and unrecoverable. Bind the acker (constructor
channel_key= or the first register(..., channel_key=...)) and this
is caught at registration instead.
Source code in src/rabbitkit/highload/batch.py
Reliability profiles & preflight¶
ReliabilityProfile
¶
apply_profile(config: RabbitConfig, profile: ReliabilityProfile | str) -> RabbitConfig
¶
Return a copy of config satisfying profile's config-level requirements.
Raises :class:ConfigValidationError if the caller pinned a
contradictory value (e.g. confirm_delivery=False under CRITICAL) —
a profile never silently overrides an explicit choice — and, under
CRITICAL, when consumer.processing_timeout is not set (it has no
safe default).
CRITICAL fills in: confirms, persistence, mandatory, body limit
(<= 256 KiB), max_in_flight_bytes (:data:CRITICAL_MAX_IN_FLIGHT_BYTES
unless set), strip_reserved_headers, a RetryConfig when there is
none (keeping your ladder when there is) with quorum delay queues
dead-lettering at-least-once, a quorum DLQ, terminal_action=dead_letter
and trust_retry_header=False, and safety.dead_letter_with_metadata. It requires a heartbeat (heartbeat=0
raises) and leaves the reconnect budget and TLS to you. Per-route requirements (quorum source
queues declared at-least-once, no ACK_FIRST, retry not disabled) are
the routes' to meet: check them with :func:validate_profile /
:func:preflight after registering the subscribers.
STANDARD fills in confirms, persistence and mandatory only.
Source code in src/rabbitkit/core/profiles.py
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 | |
validate_profile(config: RabbitConfig, profile: ReliabilityProfile | str, *, routes: Sequence[Any] = ()) -> list[ProfileViolation]
¶
Return every requirement of profile that config (and routes) violate.
Empty list == compliant. Local checks only — see :func:preflight for
broker-side verification.
Source code in src/rabbitkit/core/profiles.py
critical_config(base: RabbitConfig | None = None) -> RabbitConfig
¶
Shorthand for apply_profile(base or RabbitConfig(), CRITICAL).
base must set consumer.processing_timeout (see :func:apply_profile).
Source code in src/rabbitkit/core/profiles.py
standard_config(base: RabbitConfig | None = None) -> RabbitConfig
¶
Shorthand for apply_profile(base or RabbitConfig(), STANDARD).
ProfileViolation
dataclass
¶
One profile requirement the configuration does not meet.
Source code in src/rabbitkit/core/profiles.py
preflight(config: RabbitConfig, profile: ReliabilityProfile | str, *, routes: Sequence[Any] = (), management_client: Any | None = None, vhost: str = '/') -> PreflightReport
¶
Verify profile prerequisites locally and, when a read-only management
client is provided, on the broker. Broker-side checks are reported
UNVERIFIED (with the reason) when no client is given or a lookup
fails — never silently VERIFIED.
management_client needs only get_queue(name, vhost) returning the
management API's queue JSON (RabbitManagementClient fits).
Source code in src/rabbitkit/core/profiles.py
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 | |
PreflightReport
dataclass
¶
Source code in src/rabbitkit/core/profiles.py
PreflightCheck
dataclass
¶
PreflightStatus
¶
Bases: str, Enum
Outcome of one preflight check. UNVERIFIED is reported, never hidden.
Source code in src/rabbitkit/core/types.py
policy_templates(queue_names: Sequence[str], *, retry: RetryConfig | None = None, profile: ReliabilityProfile | str = ReliabilityProfile.CRITICAL, delivery_limit: int | None = None, max_length: int | None = None, vhost: str = '/') -> list[PolicyTemplate]
¶
Render reviewed policy definitions for queue_names and their retry chain.
For the CRITICAL profile every source queue and DLQ gets
dead-letter-strategy: at-least-once (which RabbitMQ requires to be
paired with overflow: reject-publish) and a delivery-limit
backstop (defaults to retry.max_retries + 1 when retry is given,
else 5). Delay queues get only overflow: reject-publish — TTL expiry
is their whole job and they must never drop on overflow. STANDARD
renders just the overflow guard. Nothing here is applied automatically.
Source code in src/rabbitkit/core/profiles.py
PolicyTemplate
dataclass
¶
One RabbitMQ policy in management-API shape (PUT /api/policies/{vhost}/{name}).
Source code in src/rabbitkit/core/profiles.py
Retry hardening¶
RetryHandoffConfig
dataclass
¶
Bounded behavior when the RETRY PUBLISH itself fails (plan §5.2).
A handler failure and a failure to hand the message to its delay queue
are different events. When the delay-queue publish is returned,
nacked, times out, or the connection drops, RetryMiddleware never
acks the source (it nack-requeues it) — but without a brake that is a
hot redelivery loop against a broken destination. This config bounds
that loop:
backoff_initial/backoff_max/jittershape a capped exponential delay applied per consecutive handoff failure (async handlersawait asyncio.sleep; the sync path never sleeps on the I/O thread — it reports the backoff through theon_handoff_failurehook so the broker/worker can pause admission instead).max_consecutive_failuresandrecovery_deadlinedefine when the tracker reportsexhaustedso an owner can stop the consumer and let the broker redeliver instead of spinning.
Source code in src/rabbitkit/core/config.py
RetryHandoffTracker
¶
Thread-safe consecutive-failure tracker for one route.
record_failure() returns the backoff (seconds) the caller should
apply before letting the next redelivery through. record_success()
resets the streak. The tracker never sleeps itself.
Source code in src/rabbitkit/core/retry_handoff.py
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 | |
Attributes¶
is_paused: bool
property
¶
True while degraded or exhausted (drives the retry_handoff_paused gauge).
Methods:¶
record_failure() -> float
¶
Register one handoff failure; return the backoff to apply (seconds).
Source code in src/rabbitkit/core/retry_handoff.py
record_success() -> None
¶
A handoff succeeded: the streak ends; the deadline clock resets.
Source code in src/rabbitkit/core/retry_handoff.py
reset() -> None
¶
Forget everything (e.g. after a deliberate consumer restart).
Source code in src/rabbitkit/core/retry_handoff.py
HandoffState
¶
Bases: str, Enum
Retry-handoff tracker state (see :mod:rabbitkit.core.retry_handoff).
Source code in src/rabbitkit/core/types.py
ErrorSanitizer
¶
Turn an exception into a :class:SanitizedError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
str
|
One of :data: |
'sanitized'
|
max_summary_len
|
int
|
Hard cap on the summary (after redaction). |
256
|
max_code_len
|
int
|
Hard cap on the code. |
64
|
patterns
|
Sequence[Pattern[str]] | None
|
Regexes whose matches are replaced by |
None
|
allowed_codes
|
frozenset[str] | None
|
Optional allowlist of exception class names. A code
outside it is reported as |
None
|
Source code in src/rabbitkit/core/sanitizer.py
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 | |
SanitizedError
dataclass
¶
Allowlisted, bounded description of a failure.
Attributes:
| Name | Type | Description |
|---|---|---|
category |
str
|
|
code |
str
|
Exception class name, restricted to |
summary |
str
|
Redacted, length-capped message text (empty under |