of_fix 0.1.0

Low-allocation FIX tag-value codec primitives for Orderflow execution adapters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
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
# `of_fix`

[![Crates.io](https://img.shields.io/crates/v/of_fix.svg)](https://crates.io/crates/of_fix)
[![Docs.rs](https://docs.rs/of_fix/badge.svg)](https://docs.rs/of_fix)
[![CI](https://github.com/gregorian-09/orderflow/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/gregorian-09/orderflow/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](https://opensource.org/license/mit)

`of_fix` is the reusable FIX tag-value codec and deterministic session
foundation for Orderflow execution adapters. It is intentionally separate from
`of_execution_adapters` so FIX wire handling, validation, profiles, session
coordination, and certification tooling can evolve without coupling protocol
state to one broker adapter or network stack.

## First Release: 0.1.0

`of_fix` starts at `0.1.0` in the broader Orderflow `0.5.0` development line.
Its public surface is additive: the original codec APIs remain unchanged, and
the transport-independent session engine composes those primitives.

Included now:

- borrowed tag-value field views;
- caller-owned parse scratch buffers;
- FIX `BodyLength(9)` validation;
- FIX `CheckSum(10)` validation;
- typed FIX versions and common `MsgType(35)` constants;
- static dictionary/profile validation for required and disallowed tags;
- borrowed Session Reject and BusinessMessageReject parsers for counterparty
  diagnostics;
- reusable `FixDecoder` and `FixEncoder` facades;
- session-state and sequence-tracking primitives;
- deterministic `FixSessionEngine` coordination for Logon/Logout, heartbeat,
  TestRequest, component identity, gap detection, ResendRequest,
  SequenceReset, duplicate handling, and custom application messages;
- caller-driven monotonic timers, fixed-size TestReqID storage, typed session
  actions/errors, and allocation-free session metrics;
- resend-range detection for inbound sequence gaps;
- sequence-reset guardrails that reject decreasing next expected sequence;
- borrowed session identity and sequence snapshot primitives for persistence;
- owned sequence snapshot types and an atomic file-backed sequence snapshot
  store for durable restart/reconnect state;
- bounded in-memory resend-store primitives for replay/gap-fill planning;
- append-only file-backed durable resend-message persistence that rebuilds the
  bounded in-memory resend planner after restart;
- bounded in-memory transcript capture primitives for certification/audit
  workflows;
- possible-duplicate replay encoding with `PossDupFlag(43)` and
  `OrigSendingTime(122)`;
- typed session/admin builders for Logon, Heartbeat, TestRequest,
  ResendRequest, SequenceReset gap fill, and Logout;
- typed order-entry builders for NewOrderSingle, OrderCancelRequest,
  OrderCancelReplaceRequest, OrderStatusRequest, OrderMassCancelRequest, and
  OrderMassStatusRequest, including optional `Account(1)` on single-order
  entry/cancel/replace messages and optional `StopPx(99)` on single-order
  entry/replace messages;
- common tag constants and extraction helpers;
- caller-owned encode buffers that fill `BodyLength` and `CheckSum`;
- debug rendering with `|` delimiters outside the live hot path.

Not included yet:

- TCP/TLS transport;
- credentials, authentication extensions, or a wall-clock/scheduler;
- automatic transmission of replay/gap-fill plans from a resend store;
- nested repeating-group dictionaries and automatic dictionary generation;
- venue certification harness;
- OMS execution mapping.

## Low-Latency Design

The codec is designed for execution hot paths:

- parse from `&[u8]`, not `String`;
- expose borrowed value slices instead of allocating field strings;
- use caller-provided `&mut [FixFieldView]` scratch for parse output;
- avoid `HashMap<Tag, String>` as the primary representation;
- validate `BodyLength` and `CheckSum` directly over the raw byte buffer;
- keep profile rules as static borrowed slices;
- expose reject diagnostics as borrowed views;
- track inbound/outbound sequence numbers with plain integer state;
- coordinate session lifecycle without sockets, locks, background tasks, or
  per-timer allocation;
- snapshot sequence counters without tying the codec to a storage backend;
- persist sequence snapshots outside the per-message hot path with explicit
  sync policy and checksum validation;
- retain outbound resend frames behind explicit message/byte bounds;
- append original outbound frames to a durable resend log with monotonic
  sequence validation and checksum-chain protection;
- plan replay versus gap-fill actions into caller-owned buffers;
- capture transcript metadata with bounded optional raw retention and a
  deterministic rolling hash;
- rewrite replayed frames without a generic object model;
- build session/admin messages into reusable buffers without `format!`;
- build order-entry messages from borrowed identifiers, symbols, quantities,
  prices, and timestamps;
- encode into caller-owned `Vec<u8>` buffers;
- keep debug rendering opt-in and outside hot paths.

## Public API Meaning

`FixFieldView`, `FixMessageView`, `FixTag`, and the decoder facade represent a
borrowed view over one validated FIX frame. They avoid allocating field names
or values and are valid only while the source bytes remain alive. Encoder
functions write into caller-owned buffers and calculate `BodyLength(9)` and
`CheckSum(10)` as part of final frame construction.

`FixDictionary` and profile rules validate message-specific required, optional,
and disallowed tags. Session identity, header, sequence, and action types model
administrative protocol state independently from a socket. The session engine
consumes inbound views and emits explicit actions such as send, resend, gap
fill, reject, ready, or disconnect for the host transport to carry out.

Sequence trackers, snapshots, resend stores, replay plans, and transcript
capture are restart and certification surfaces. They make gaps, duplicate
messages, possible-duplicate replay, and persistence boundaries observable;
they do not create a scheduler or transmit bytes. Order builders provide typed
FIX entry messages, while the execution adapter remains responsible for
mapping those messages to the OMS.

`FixRepeatingGroupDefinition` describes one flat repeating group: its count
tag, the delimiter tag that begins every entry, and the tags allowed within an
entry. `FixMessageView::repeating_group` interprets that definition over the
already parsed field array. The returned `FixRepeatingGroupView` and
`FixRepeatingGroup` values borrow the original message and use caller-owned
`FixRepeatingGroupEntry` scratch for boundaries; they do not allocate or copy
tag values. This supports venue party, allocation, instrument-leg, and
routing groups on a latency-sensitive path while keeping ownership explicit.

The matching `encode_message_with_repeating_group` function and
`FixEncoder::encode_with_repeating_group` method generate the count field and
validate each entry before writing it. They append one flat group after the
ordinary body fields and retain the existing `BodyLength(9)` and `CheckSum(10)`
behavior. Nested groups, automatic data-dictionary loading, and venue
certification scenarios remain responsibilities of a profile or adapter
layer.

## Repeating Group Support

FIX repeating groups are a count field followed by a sequence of entries. Each
entry starts with a delimiter field; subsequent fields belong to that entry
until the next delimiter or the end of the group. For example, a party group
may be represented by `NoPartyIDs(453)`, followed by entries beginning with
`PartyID(448)` and containing `PartyIDSource(447)` and `PartyRole(452)`.

`of_fix` represents this structure with a small explicit definition rather
than a general-purpose object tree. The definition is borrowed and can be
declared as static profile data:

```rust
use of_fix::{
    encode_message_with_repeating_group, parse_message, FixFieldView,
    FixRepeatingGroupDefinition, FixRepeatingGroupEntry, FixTag,
};

const PARTY_FIELDS: &[FixTag] = &[FixTag(448), FixTag(447), FixTag(452)];
let party_group = FixRepeatingGroupDefinition::new(
    FixTag(453), // NoPartyIDs
    FixTag(448), // PartyID: first field of each entry
    PARTY_FIELDS,
);
let first_party = [
    (FixTag(448), b"CLEARING-A".as_slice()),
    (FixTag(447), b"D".as_slice()),
    (FixTag(452), b"1".as_slice()),
];
let second_party = [
    (FixTag(448), b"CLEARING-B".as_slice()),
    (FixTag(447), b"D".as_slice()),
    (FixTag(452), b"3".as_slice()),
];
let groups = [&first_party[..], &second_party[..]];

let mut raw = Vec::with_capacity(256);
encode_message_with_repeating_group(
    &mut raw,
    b"FIX.4.4",
    b"D",
    &[(FixTag::CL_ORD_ID, b"ORD-42".as_slice())],
    party_group,
    &groups,
)?;

let mut fields = [FixFieldView::empty(); 32];
let message = parse_message(&raw, &mut fields)?;
let mut entry_scratch = [FixRepeatingGroupEntry::empty(); 2];
let parties = message.repeating_group(party_group, &mut entry_scratch)?;
assert_eq!(parties.len(), 2);
assert_eq!(
    parties.get(0).and_then(|entry| entry.get(FixTag(448))),
    Some(b"CLEARING-A".as_slice())
);
# Ok::<(), Box<dyn std::error::Error>>(())
```

The decoder first reads the count and checks that the supplied scratch has at
least that many entries. It then verifies every delimiter and every tag in
each entry. A missing count, invalid count, insufficient scratch, missing
delimiter, or group tag found outside the declared entries returns
`FixGroupError`. Group fields must remain contiguous: a later allowed group tag
after an unrelated field is rejected rather than silently reinterpreted.
Field values still borrow the source frame, so the frame must remain alive while
callers inspect the group.

The encoder applies the same structural contract in the opposite direction.
An empty group is valid and emits a zero count. An entry must be non-empty,
must start with the delimiter, and may contain only tags in `field_tags`.
Values are checked for SOH before any bytes are written. The encoder owns the
count tag and rejects a duplicate count tag in ordinary fields, repeated
delimiters inside an entry, and tags `8`, `9`, `35`, and `10` inside group
entries. Because the group is appended after ordinary body fields, a venue
profile that requires a different field ordering should build its complete
ordered field slices above this primitive or add a dedicated typed builder.

This first API supports flat groups intentionally. Nested groups require a
recursive schema and more involved boundary validation; they should be added
as a separate additive API rather than changing the meaning of the existing
definition or view types.

### Repeating-Group Failure Modes

The strict group contract is intentional. It prevents a venue-specific field
from being silently interpreted as a different group entry:

| Operation | Failure | Meaning |
| --- | --- | --- |
| Decode | `MissingCountTag` or `InvalidCount` | The declared entry count cannot be trusted. |
| Decode | `ScratchTooSmall` | The caller must provide one boundary slot per declared entry. |
| Decode | `MissingDelimiter` | An entry does not start where the profile says it must. |
| Decode | `UnexpectedField` | A permitted group tag appears after the contiguous group boundary. |
| Encode | `DuplicateRepeatingGroupCountTag` | The generated count would be ambiguous with a caller field. |
| Encode | `MissingRepeatingGroupDelimiter` | An entry is empty or starts with the wrong tag. |
| Encode | `RepeatedRepeatingGroupDelimiter` | One entry would be decoded as multiple entries. |
| Encode | `InvalidRepeatingGroupField` | The entry contains a tag outside the profile definition. |

The encoder checks the group definition and group entries before clearing the
output buffer. This makes structural profile errors observable without
partially replacing a previously encoded frame. Applications should treat
these errors as profile/configuration failures, correct the venue definition
or field ordering, and retry with a new message rather than relaxing the
decoder.

## Decode Example

```rust
use of_fix::{encode_message, parse_message, FixFieldView, FixTag};

let mut raw = Vec::new();
encode_message(
    &mut raw,
    b"FIX.4.4",
    b"0",
    &[(FixTag::MSG_SEQ_NUM, b"1".as_slice())],
)?;

let mut scratch = [FixFieldView::empty(); 8];
let msg = parse_message(&raw, &mut scratch)?;

assert_eq!(msg.get(FixTag::MSG_TYPE), Some(b"0".as_slice()));
assert_eq!(msg.msg_type(), Some(b"0".as_slice()));
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Session Engine Example

The engine writes administrative frames into a reusable caller-owned buffer.
The host owns TCP/TLS, timestamp formatting, persistence, and actual sends.

```rust
use of_fix::{
    encode_logon, parse_message, FixFieldView, FixOwnedSessionId,
    FixSessionAction, FixSessionEngine, FixSessionEngineConfig, FixSessionHeader,
    FixSessionState, FixVersion,
};

let config = FixSessionEngineConfig::new(30)?;
let id = FixOwnedSessionId::new(FixVersion::Fix44, b"BUY_SIDE".to_vec(), b"BROKER".to_vec())?;
let mut session = FixSessionEngine::new(config, id);
let mut outbound = Vec::with_capacity(512);

session.on_transport_connecting()?;
let action = session.on_transport_connected(
    1_000_000_000,
    b"20260810-12:00:00.000",
    &mut outbound,
)?;
assert!(matches!(action, FixSessionAction::Send { .. }));

// A transport test harness supplies the counterparty Logon frame.
let mut inbound = Vec::with_capacity(512);
encode_logon(
    &mut inbound,
    FixVersion::Fix44,
    FixSessionHeader::new(
        b"BROKER",
        b"BUY_SIDE",
        1,
        b"20260810-12:00:00.001",
    ),
    30,
    false,
)?;
let mut scratch = [FixFieldView::empty(); 24];
let logon = parse_message(&inbound, &mut scratch)?;
let action = session.on_inbound(
    &logon,
    1_000_001_000,
    b"20260810-12:00:00.001",
    &mut outbound,
)?;
assert_eq!(action, FixSessionAction::Ready { sequence: 1 });
assert_eq!(session.state(), FixSessionState::Ready);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Encode Example

```rust
use of_fix::{encode_message, FixTag};

let mut out = Vec::new();
encode_message(
    &mut out,
    b"FIX.4.4",
    b"D",
    &[(FixTag::MSG_SEQ_NUM, b"1".as_slice())],
)?;

assert!(out.starts_with(b"8=FIX.4.4\x019="));
# Ok::<(), of_fix::FixEncodeError>(())
```

## Profile Validation Example

```rust
use of_fix::{
    encode_message, parse_message, FixDictionary, FixFieldView, FixMessageRule,
    FixMsgType, FixTag, FixVersion,
};

static REQUIRED: &[FixTag] = &[FixTag::CL_ORD_ID, FixTag::SYMBOL, FixTag::SIDE];
static RULES: &[FixMessageRule<'static>] = &[FixMessageRule::new(
    FixMsgType::NEW_ORDER_SINGLE,
    REQUIRED,
    &[],
)];

let dictionary = FixDictionary::new(FixVersion::Fix44, RULES);

let mut raw = Vec::new();
encode_message(
    &mut raw,
    b"FIX.4.4",
    b"D",
    &[
        (FixTag::CL_ORD_ID, b"ORD-1".as_slice()),
        (FixTag::SYMBOL, b"BTCUSDT".as_slice()),
        (FixTag::SIDE, b"1".as_slice()),
    ],
)?;

let mut scratch = [FixFieldView::empty(); 16];
let msg = parse_message(&raw, &mut scratch)?;
dictionary.validate(&msg)?;
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Reject Parsing Example

```rust
use of_fix::{encode_message, parse_message, parse_session_reject, FixFieldView, FixTag};

let mut raw = Vec::new();
encode_message(
    &mut raw,
    b"FIX.4.4",
    b"3",
    &[
        (FixTag::REF_SEQ_NUM, b"12".as_slice()),
        (FixTag::REF_TAG_ID, b"55".as_slice()),
        (FixTag::REF_MSG_TYPE, b"D".as_slice()),
        (FixTag::SESSION_REJECT_REASON, b"1".as_slice()),
        (FixTag::TEXT, b"missing symbol".as_slice()),
    ],
)?;

let mut scratch = [FixFieldView::empty(); 16];
let msg = parse_message(&raw, &mut scratch)?;
let reject = parse_session_reject(&msg)?;

assert_eq!(reject.ref_seq_num(), 12);
assert_eq!(reject.ref_tag_id(), Some(FixTag::SYMBOL));
assert_eq!(reject.ref_msg_type(), Some(b"D".as_slice()));
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Sequence Tracking Example

```rust
use of_fix::{FixSequenceAction, FixSequenceTracker};

let mut tracker = FixSequenceTracker::new();

assert_eq!(
    tracker.observe_inbound(1, false)?,
    FixSequenceAction::Accept { seq_no: 1 },
);

assert!(matches!(
    tracker.observe_inbound(4, false)?,
    FixSequenceAction::Gap { expected: 2, received: 4, .. },
));
# Ok::<(), of_fix::FixSequenceError>(())
```

## Sequence Snapshot Example

```rust
use of_fix::{FixSequenceTracker, FixSessionId, FixVersion};

let session = FixSessionId::new(FixVersion::Fix44, b"CLIENT", b"BROKER")?;
let tracker = FixSequenceTracker::from_next(12, 34);

let snapshot = tracker.snapshot(session, b"20260717")?;
let restored = FixSequenceTracker::from_snapshot(&snapshot);

assert_eq!(restored.next_inbound(), 12);
assert_eq!(restored.next_outbound(), 34);
# Ok::<(), of_fix::FixEncodeError>(())
```

## Sequence Persistence Example

`FileFixSequenceSnapshotStore` persists the latest FIX sequence snapshot as a
small checksum-validated binary file. It is meant for session startup,
reconnect, and end-of-day handoff logic, not for every inbound/outbound FIX
message. Hot session code should update `FixSequenceTracker` in memory and save
snapshots at explicit durability points chosen by the host.

```rust
use of_fix::{
    FileFixSequenceSnapshotStore, FixSequenceSnapshotStore,
    FixSequenceStoreConfig, FixSequenceTracker, FixSessionId, FixVersion,
};

let root = std::env::temp_dir().join(format!(
    "orderflow-fix-sequence-readme-{}",
    std::process::id()
));
let _ = std::fs::remove_dir_all(&root);

let mut store = FileFixSequenceSnapshotStore::open(
    FixSequenceStoreConfig::new(&root).with_sync_on_save(false),
)?;
let session = FixSessionId::new(FixVersion::Fix44, b"CLIENT", b"BROKER")?;
let tracker = FixSequenceTracker::from_next(42, 77);
let snapshot = tracker.snapshot(session, b"20260726")?;

let manifest = store.save_snapshot(&snapshot)?;
assert_eq!(manifest.next_inbound, 42);

let loaded = store.load_latest()?.expect("snapshot");
assert!(loaded.validate_checksum());
let restored = FixSequenceTracker::from_snapshot(&loaded.as_borrowed()?);
assert_eq!(restored.next_outbound(), 77);
# let _ = std::fs::remove_dir_all(root);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Session Admin Builder Example

```rust
use of_fix::{encode_logon, FixSessionHeader, FixVersion};

let header = FixSessionHeader::new(
    b"CLIENT",
    b"BROKER",
    1,
    b"20260717-12:00:00.000",
);

let mut out = Vec::with_capacity(256);
encode_logon(&mut out, FixVersion::Fix44, header, 30, true)?;

assert!(out.starts_with(b"8=FIX.4.4\x019="));
# Ok::<(), of_fix::FixEncodeError>(())
```

## Order Builder Example

```rust
use of_fix::{
    encode_new_order_single, FixNewOrderSingle, FixOrdType, FixOrderSide,
    FixSessionHeader, FixTimeInForce, FixVersion,
};

let header = FixSessionHeader::new(
    b"CLIENT",
    b"BROKER",
    7,
    b"20260717-12:00:05.000",
);

let order = FixNewOrderSingle::new(
    b"ORD-1",
    b"BTCUSDT",
    FixOrderSide::Buy,
    b"20260717-12:00:05.000",
    b"1.25",
    FixOrdType::Limit,
)
.with_price(b"65000.5")
.with_time_in_force(FixTimeInForce::Day);

let mut out = Vec::with_capacity(512);
encode_new_order_single(&mut out, FixVersion::Fix44, header, order)?;
# Ok::<(), of_fix::FixEncodeError>(())
```

## Resend Planning Example

```rust
use of_fix::{
    FixResendAction, FixResendRange, FixResendStore, FixResendStoreConfig,
    FixSentMessageKind,
};

let mut store = FixResendStore::new(FixResendStoreConfig::new(128, 64 * 1024));
store.record_sent(1, FixSentMessageKind::Application, b"raw-new-order")?;
store.record_sent(2, FixSentMessageKind::Administrative, b"raw-heartbeat")?;
store.record_sent(3, FixSentMessageKind::Application, b"raw-cancel")?;

let mut actions = Vec::new();
let summary = store.plan_resend_range(
    FixResendRange {
        begin_seq_no: 1,
        end_seq_no: 3,
    },
    &mut actions,
);

assert_eq!(summary.replay_messages(), 2);
assert_eq!(
    actions,
    vec![
        FixResendAction::Replay {
            seq_no: 1,
            raw: b"raw-new-order".as_slice(),
        },
        FixResendAction::GapFill {
            begin_seq_no: 2,
            end_seq_no: 2,
        },
        FixResendAction::Replay {
            seq_no: 3,
            raw: b"raw-cancel".as_slice(),
        },
    ]
);
# Ok::<(), of_fix::FixResendStoreError>(())
```

## Durable Resend Store Example

`FileFixDurableResendStore` records original outbound FIX frames in an
append-only binary log. On restart, the host can reload the durable records into
`FixResendStore` and keep using the same resend planner. Retransmitted
`PossDupFlag(43)=Y` messages should not be appended as new original sends.

```rust
use of_fix::{
    FileFixDurableResendStore, FixDurableResendMessageStore,
    FixDurableResendStoreConfig, FixResendAction, FixResendRange,
    FixResendStore, FixResendStoreConfig, FixSentMessageKind,
};

let path = std::env::temp_dir().join(format!(
    "orderflow-fix-resend-readme-{}.log",
    std::process::id()
));
let _ = std::fs::remove_file(&path);

let mut durable = FileFixDurableResendStore::open(
    FixDurableResendStoreConfig::new(&path).with_sync_on_record(false),
)?;
durable.record_sent(1, FixSentMessageKind::Application, b"raw-new-order")?;
durable.record_sent(2, FixSentMessageKind::Administrative, b"raw-heartbeat")?;
drop(durable);

let durable = FileFixDurableResendStore::open(
    FixDurableResendStoreConfig::new(&path).with_sync_on_record(false),
)?;
let mut replay = FixResendStore::new(FixResendStoreConfig::new(128, 64 * 1024));
let report = durable.load_into(&mut replay)?;
assert_eq!(report.records, 2);

let mut actions = Vec::new();
replay.plan_resend_range(
    FixResendRange {
        begin_seq_no: 1,
        end_seq_no: 2,
    },
    &mut actions,
);
assert_eq!(
    actions,
    vec![
        FixResendAction::Replay {
            seq_no: 1,
            raw: b"raw-new-order".as_slice(),
        },
        FixResendAction::GapFill {
            begin_seq_no: 2,
            end_seq_no: 2,
        },
    ]
);
# let _ = std::fs::remove_file(path);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Transcript Capture Example

```rust
use of_fix::{
    encode_heartbeat, parse_message, FixFieldView, FixSessionHeader,
    FixTranscriptCapture, FixTranscriptConfig, FixTranscriptDirection,
    FixVersion,
};

let header = FixSessionHeader::new(
    b"CLIENT",
    b"BROKER",
    42,
    b"20260717-12:00:00.000",
);

let mut raw = Vec::new();
encode_heartbeat(&mut raw, FixVersion::Fix44, header, None)?;

let mut scratch = [FixFieldView::empty(); 16];
let message = parse_message(&raw, &mut scratch)?;

let mut transcript =
    FixTranscriptCapture::new(FixTranscriptConfig::new(128, 64 * 1024, true));
transcript.record_message(
    FixTranscriptDirection::Outbound,
    1_784_275_200_000_000_000,
    &message,
)?;

let metrics = transcript.metrics();
assert_eq!(metrics.captured_records(), 1);
assert_eq!(metrics.retained_records(), 1);
assert_ne!(metrics.rolling_hash(), 0);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Possible-Duplicate Replay Example

```rust
use of_fix::{
    encode_heartbeat, encode_poss_dup_replay, parse_message, FixFieldView,
    FixSessionHeader, FixTag, FixVersion,
};

let header = FixSessionHeader::new(
    b"CLIENT",
    b"BROKER",
    42,
    b"20260717-12:00:00.000",
);

let mut original = Vec::new();
encode_heartbeat(&mut original, FixVersion::Fix44, header, None)?;

let mut scratch = [FixFieldView::empty(); 16];
let source = parse_message(&original, &mut scratch)?;

let mut replay = Vec::new();
encode_poss_dup_replay(&mut replay, &source, b"20260717-12:00:05.000")?;

let mut replay_scratch = [FixFieldView::empty(); 20];
let replayed = parse_message(&replay, &mut replay_scratch)?;

assert_eq!(replayed.msg_seq_num(), Some(42));
assert_eq!(replayed.get(FixTag::POSS_DUP_FLAG), Some(b"Y".as_slice()));
assert_eq!(
    replayed.get(FixTag::ORIG_SENDING_TIME),
    Some(b"20260717-12:00:00.000".as_slice())
);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Validation Semantics

`parse_message` rejects frames when:

- required tags `8`, `9`, or `10` are missing;
- fields are malformed;
- tags are non-numeric;
- the provided scratch buffer is too small;
- `BodyLength(9)` does not match the byte count from the body start through
  the delimiter before tag `10`;
- `CheckSum(10)` is not exactly three digits or does not equal the modulo-256
  byte sum before the checksum field.

This is deliberately strict for production execution paths. If a counterparty
requires a relaxed policy, that should live in a profile layer above this codec.

`FixDictionary` adds an optional second validation phase after the wire frame is
valid. It checks the parsed `BeginString(8)` against a configured
`FixVersion`, locates a `FixMessageRule` by raw `MsgType(35)`, then verifies
required and disallowed tags using borrowed field views. It does not allocate,
does not perform transport/session validation, and does not imply venue
certification.

Repeating-group structure is validated separately through
`FixMessageView::repeating_group`. A `FixDictionary` rule still validates the
message-level required and disallowed tags; it does not infer group structure,
because count, delimiter, and ordering requirements vary between FIX
versions and venue profiles.

`parse_session_reject` and `parse_business_message_reject` expose borrowed
views over Reject `<3>` and BusinessMessageReject `<j>` diagnostics. They parse
numeric reason fields and referenced sequence/tag values, but they do not
allocate strings, classify venue severity, or decide whether trading should
stop. Session engines and adapter profiles should turn these diagnostics into
health, metrics, and fail-closed policies.

`FixSequenceTracker` adds deterministic sequence bookkeeping for session
engines and adapters. It accepts expected inbound sequence numbers, reports
missing ranges as `FixSequenceAction::Gap`, treats lower `PossDupFlag=Y`
messages as duplicates, flags unmarked lower sequence numbers as too-low, and
assigns outbound sequence numbers monotonically.

`FixSessionId` and `FixSequenceSnapshot` provide borrowed, storage-neutral
state snapshots. They do not write files or choose durability policy; WAL,
checkpoint, or database layers can serialize the session id, trading day, and
next inbound/outbound counters according to their own latency and durability
requirements.

`FixSessionEngine` composes the codec, admin builders, and sequence tracker. It
validates begin string and component identity, negotiates the configured
heartbeat interval, drives heartbeat/TestRequest timers from caller timestamps,
emits ResendRequest on gaps, applies SequenceReset, performs graceful Logout,
and reports application/custom messages only after session readiness. It does
not retain out-of-order frames; the transport host must redeliver a triggering
frame after gap recovery. It also does not own a resend store, so a
`PeerResendRequested` action remains an explicit handoff to the configured
in-memory/durable resend policy.

`FixResendStore` retains original outbound FIX frames behind explicit message
and byte budgets. It produces caller-owned resend plans with replay actions for
retained application/reject messages and gap-fill actions for administrative,
missing, aged, or evicted ranges. It is not durable storage and does not
transmit responses; a session engine remains responsible for encoding
SequenceReset gap fills, setting `PossDupFlag(43)`/`OrigSendingTime(122)` on
replayed messages where required by profile, and enforcing counterparty policy.

`FixTranscriptCapture` records certification/audit transcript metadata with
optional bounded raw frame retention. It updates cumulative counters and a
deterministic rolling hash even when raw bytes are not retained. It does not
write files, redact secrets, script certification scenarios, or generate
counterparty reports; those policies belong in host tooling built on top of the
capture records.

`encode_poss_dup_replay` handles the common replay rewrite step for retained
messages. It takes a validated borrowed source message, preserves its original
sequence number and application fields, writes `PossDupFlag(43)=Y`, replaces
`SendingTime(52)` with the current send time, writes `OrigSendingTime(122)`,
and recomputes `BodyLength(9)` and `CheckSum(10)`. It does not decide which
messages are replayable or send them on a socket.

The session/admin builders are intentionally small protocol helpers. They write
the common standard header fields and the required admin body fields into the
same strict encoder path used by `encode_message`; `FixSessionEngine` composes
them with deterministic timers but still does not manage sockets, durable
resend stores, or authentication extensions.

The order-entry builders provide common message shapes for NewOrderSingle,
OrderCancelRequest, OrderCancelReplaceRequest, OrderStatusRequest,
OrderMassCancelRequest, and OrderMassStatusRequest. They do not decide whether
a limit price is required, whether a field can be changed on replace, how
quantities are rounded, whether a mass-cancel or mass-status scope is enabled
at a venue, or which party groups, clearing instructions, or custom tags a
venue requires. Those checks belong in profile/certification layers above the
codec.