Skip to content

Message system: group block repeats by name and pool the per-message data graph#305

Merged
RyeMutt merged 5 commits into
developfrom
rye/message-block-grouping
Jun 11, 2026
Merged

Message system: group block repeats by name and pool the per-message data graph#305
RyeMutt merged 5 commits into
developfrom
rye/message-block-grouping

Conversation

@RyeMutt

@RyeMutt RyeMutt commented Jun 11, 2026

Copy link
Copy Markdown
Member

Summary

Restructures LLMsgData, the per-message block/variable data model shared by the template message reader and builder, fixing a reachable data-corruption defect and removing all steady-state heap allocation from both the UDP decode and send paths.

Block repeats grouped by name (corruption fix)

The old model keyed each block repeat in a std::map<char*, LLMsgBlkData*> by name + repeat_index pointer arithmetic over the prehashed string table. String-table names are contiguous 64-byte rows, so past ~64 repeats the synthesized keys walked into the adjacent name''s storage; with two block names in range, keys aliased — overwriting (and leaking) blocks and corrupting decoded data. ImprovedTerseObjectUpdate-class messages reach ~180 repeats after zerocode expansion, so this was reachable from normal inbound traffic.

Each block name now owns an ordered vector of its repeat instances (BlockGroup), kept in template order. No synthesized keys, no per-block map nodes, and getBlock(name, i) recovers repeat i directly. As a side effect the builder''s MBT_MULTIPLE overflow check now fires at exactly the limit (the old check read the previous repeat''s index and was off by one — and checked the wrong block entirely when calls interleaved block names); overpacking was already fatal at build time, so nothing could have depended on the laxness.

Pooled, reusable data graph (decode + send)

LLMsgData now recycles its blocks through an internal free pool: reset() returns every block to the pool keeping all vector capacity, and allocBlock() reuses them. The reader and builder keep their LLMsgData alive across messages instead of delete+new per packet, so after warmup a steady-state decode (object updates every frame) and send (AgentUpdate every frame) allocate nothing. Stale-state access is gated as before: every reader getter bails on mReceiveSize == -1 and every builder entry point on a null mCurrentSMessageTemplate.

Empty-variable guards in the LLSD copy path

LLSDMessageBuilder::copyFromMessageData unconditionally read the last payload byte of MVT_VARIABLE fields to detect NUL termination; for an empty field (no payload, getData() null since the inline-storage change) that was a null [-1] access, and addBinaryData''s &v[0] on a size-0 vector was likewise out of contract. Both are now guarded on size, and buildBlock''s MULTIPLE-underfill error names the block from the template rather than dereferencing a possibly-null block pointer.

Tests

New TUT coverage in lltemplatemessagebuilder_test and llsdmessagebuilder_test:

  • 200-repeat variable block alongside an adjacent single block round-trips intact (the old keying corrupts this)
  • one pooled reader alternating 5- and 2-repeat messages — no stale blocks or values leak between decodes
  • one pooled builder alternating 5- and 2-block messages, round-tripped
  • empty MVT_VARIABLE field copies to LLSD as an empty value instead of reading out of bounds

All green in RelWithDebInfo and Debug: lltemplatemessagebuilder 50/50, llsdmessagebuilder 47/47, llsdmessagereader 21/21, message 1/1.

🤖 Generated with Claude Code

RyeMutt and others added 4 commits June 11, 2026 04:26
LLMsgData kept each decoded/built block in a std::map keyed by the block
name's string-table pointer plus the repeat index (name + blocknum).
String-table names are contiguous 64-byte rows, so name + i for i past
~64 walked into the adjacent name's storage; two block names within
range plus enough repeats aliased keys, overwriting (and leaking) blocks
and corrupting data. ImprovedTerseObjectUpdate-class messages reach ~180
repeats after zerocode expansion, so this was reachable from inbound
traffic -- the long-standing "should really change to a vector" TODO.

Give each block name an ordered vector of its repeat instances, with the
groups themselves held in first-seen (template) order. getBlock(name, i)
recovers repeat i by position, so no pointer outside a real object is
ever formed and the per-repeat map node is gone. buildBlock() indexes
repeats directly instead of walking ++map_iter and assuming the
synthesized keys sort adjacently; both copyFromMessageData() paths
iterate groups x repeats. The builder still tracks its instance count on
the group header (mBlockNumber) to preserve the declared-but-empty
placeholder semantics newMessage()/buildBlock() rely on.

LLMsgBlkData stays heap-allocated and pointer-stable so the cached
mCurrentSDataBlock / cur_data_block / mbci pointers can't dangle across a
vector growth; pooling those objects is a separate follow-up.

Drop dead LLMsgData::addDataFast (no callers, carried its own copy of the
synthesized-pointer logic). Reader getSize() now uses the find-based
const getBlock() template overload so a missing block can't insert into
the template.

Add a regression test: a variable block repeated 200 times alongside a
second block, round-tripped, verifying every repeat and the neighbor are
intact.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Rye <rye@alchemyviewer.org>
The template reader freed and reallocated its whole working data set every
packet -- new LLMsgData plus a new LLMsgBlkData (each eagerly reserving a
variable vector) per block repeat, all torn down again at clearMessage().
Under object-update load that is the hottest allocation path in the viewer
(ImprovedTerseObjectUpdate-class messages carry ~180 repeats).

Keep the reader's LLMsgData alive across packets and reset it in place
instead. reset() recycles every block into an internal free pool and clears
the groups while keeping all vector capacity; allocBlock() hands blocks back
out from the pool (reinit clears the prior variable data, freeing any heap
payloads). After warmup a steady-state decode performs no heap allocation.
clearMessage() now recycles rather than deletes; every getter already gates
on mReceiveSize == -1, so the reset-but-alive object is never read stale.

LLMsgBlkData stays heap-allocated and pointer-stable, so cached
mCurrentRMessageData / cur_data_block pointers within a decode are unaffected.

Add a reuse-path test: alternate a 5-repeat and a 2-repeat message through
one reader, verifying counts and values each pass so no stale block or value
leaks across the differing repeat counts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Rye <rye@alchemyviewer.org>
LLTemplateMessageBuilder reallocated its working data set on every
newMessage() -- a fresh LLMsgData plus one LLMsgBlkData per template
block, freed again at clearMessage(). AgentUpdate and friends go out
every frame, so this mirrors the inbound decode allocation churn.

Reuse the builder's LLMsgData the same way the reader now does: reset it
in place in newMessage() (and clearMessage()) instead of delete+new, and
draw block instances from its pool via allocBlock(). Use is gated by
mCurrentSMessageTemplate, which clearMessage() nulls, so the
reset-but-alive object is never touched between messages.

Add a test that drives one builder through alternating 5- and 2-block
messages, round-tripping each, so a reused build can't inherit blocks or
values from the previous one. Bump the group's max-tests headroom.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Rye <rye@alchemyviewer.org>
An empty MVT_VARIABLE field stores no payload, and since the inline-
storage change getData() returns null for it, so copyFromMessageData's
unconditional read of the last byte (checking for a terminating NUL)
became a null[-1] access; addBinaryData's &v[0] on a size-0 vector was
likewise out of contract. Guard both on size, and have buildBlock's
MBT_MULTIPLE underfill error name the block from the template instead
of dereferencing a block-data pointer that can be null there.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@RyeMutt, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 11 minutes and 17 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2f1de91f-a2b2-4cf2-b24c-5617c1265273

📥 Commits

Reviewing files that changed from the base of the PR and between ef7be00 and 1ea1758.

📒 Files selected for processing (3)
  • indra/llmessage/llsdmessagebuilder.cpp
  • indra/llmessage/lltemplatemessagebuilder.cpp
  • indra/llmessage/tests/llsdmessagebuilder_test.cpp
📝 Walkthrough

Walkthrough

This PR refactors message template block storage from a map-based design to a grouping-and-pooling model with recycled block allocation. LLMsgData replaces std::map<char*, LLMsgBlkData*> with BlockGroup structs in a vector, adds pooled lifecycle methods (reset, allocBlock, getBlock), and removes the addDataFast API. Template builder and reader code transitions to indexed block retrieval and block reuse across messages. LLSD message builder is updated for the new structure and includes safe empty-payload handling.

Changes

Message Template Pooling and Grouping

Layer / File(s) Summary
Data structure and pool lifecycle
indra/llmessage/llmessagetemplate.h, indra/llmessage/llmessagetemplate.cpp
LLMsgVarDataMap adds clear() and LLMsgBlkData adds reinit() for container reuse. LLMsgData redesigned with BlockGroup (name + vector of repeat blocks) stored in a vector, maintains mBlockPool for recycled allocation, and adds reset()/allocBlock()/getBlock()/empty() APIs. Removes addDataFast() implementation and declaration.
Template builder pooling and indexed access
indra/llmessage/lltemplatemessagebuilder.cpp
Builder reuses mCurrentSMessageData across newMessage()/clearMessage() instead of deleting/reallocating. Block allocation via allocBlock() and retrieval via getBlock(name, index). nextBlock() enforces MBT_MULTIPLE limits using header block count; buildBlock() and isMessageFull() derive repeat counts from header block and iterate repeats by index.
Template reader pooling and field access
indra/llmessage/lltemplatemessagereader.cpp
Reader reuses mCurrentRMessageData across decodes via reset/recycle. Field access (getData, getNumberOfBlocks, getSize overloads) retrieves blocks via getBlock() instead of map hashing. Decoding allocates repeats via allocBlock() in canonical order; completeness checked with empty().
LLSD builder safe payload handling
indra/llmessage/llsdmessagebuilder.cpp
addBinaryData() skips memcpy when size ≤ 0. copyFromMessageData() refactored to iterate BlockGroup/mBlocks directly. MVT_VARIABLE conversion safely handles empty payloads by checking size > 0 before probing for null termination.
Validation tests for pooling and edge cases
indra/llmessage/tests/lltemplatemessagebuilder_test.cpp, indra/llmessage/tests/llsdmessagebuilder_test.cpp
Test group upper bound increased to 60. New tests validate empty MVT_VARIABLE handling, high repeat counts (200×), reader pooling across multiple messages, and builder state reset between messages.

🎯 4 (Complex) | ⏱️ ~60 minutes

c/cpp, llmessage

🐰 Carrots of reuse, pools of delight,
Blocks grouped together, no map in sight!
Pooled allocation, memory so bright,
Templates now recycle, performance takes flight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.04% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the two main changes: grouping block repeats by name and pooling per-message data for reuse.
Description check ✅ Passed The description includes clear summary, detailed explanations of the changes and their benefits, test coverage information, and verification that all tests pass.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@indra/llmessage/lltemplatemessagebuilder.cpp`:
- Around line 760-776: The current copyFromMessageData iterates every block and
every var, which copies template scaffolding; instead locate the header block
for each group (the first LLMsgBlkData in LLMsgData::BlockGroup mBlocks) read
its repeat count and drive nextBlock(...) that many times, and when copying vars
skip any LLMsgVarData with getSize() < 0 so placeholder vars are not copied;
update references in copyFromMessageData to use the header block's repeat count
(e.g., headerBlock->mRepeatCount or headerBlock->getRepeatCount()) and only call
addData(...) for vars whose getSize() >= 0.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e1d75459-1e4f-4c31-96fd-e7b6cdc3c01b

📥 Commits

Reviewing files that changed from the base of the PR and between ce11b86 and ef7be00.

📒 Files selected for processing (7)
  • indra/llmessage/llmessagetemplate.cpp
  • indra/llmessage/llmessagetemplate.h
  • indra/llmessage/llsdmessagebuilder.cpp
  • indra/llmessage/lltemplatemessagebuilder.cpp
  • indra/llmessage/lltemplatemessagereader.cpp
  • indra/llmessage/tests/llsdmessagebuilder_test.cpp
  • indra/llmessage/tests/lltemplatemessagebuilder_test.cpp
💤 Files with no reviewable changes (1)
  • indra/llmessage/llmessagetemplate.cpp

Comment thread indra/llmessage/lltemplatemessagebuilder.cpp
Builder-owned LLMsgData carries a size -1 placeholder for each variable
of an opened block until addData() fills it, and a placeholder has no
payload at all, so both copyFromMessageData() implementations would read
through a null data pointer if handed such data. No production path does
(every copyToBuilder source is reader-decoded data, which fills every
variable), but the guard is one branch. Block-level walking is unchanged
on purpose: pre-added header blocks were emitted by the old map walk
too, and the hand-built data convention in the LLSD builder tests
expects blocks with a zero repeat count to be copied.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@RyeMutt RyeMutt merged commit e8df2f0 into develop Jun 11, 2026
23 of 26 checks passed
@RyeMutt RyeMutt deleted the rye/message-block-grouping branch June 11, 2026 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant