Skip to content

feat(context): Add priority_select for budget-aware section selection - #7216

Open
patelchaitany wants to merge 3 commits into
feast-dev:masterfrom
patelchaitany:context/02-priority-select
Open

patelchaitany wants to merge 3 commits into
feast-dev:masterfrom
patelchaitany:context/02-priority-select

Conversation

@patelchaitany

@patelchaitany patelchaitany commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does / why we need it:

Adds priority_select(), the second piece of feast.context (after TokenBudget, #6824): it decides which parts of a prompt survive a token budget. Prompt assembly is a packing problem — a user profile, a watch history and a catalogue of candidates rarely fit together in a context window — and this is the mechanism that chooses what gives.

selection = priority_select(
    [
        ("critical", system_instructions),
        ("high", f"User profile: {profile}"),
        ("medium", f"Recent history: {history}"),
        ("low", f"Device: {device}"),
    ],
    TokenBudget.of(4096),
)
prompt = selection.render()

Sections are considered most important first, and dropped least important first. Priority is an IntEnum with four levels (critical > high > medium > low); a section accepts one of them or its case-insensitive name. Ties keep declaration order. A section too large to fit is dropped and the scan continues, so a small low-priority section is still kept after a large high-priority one was refused. A critical section is never dropped: if it does not fit, RequiredSectionError is raised rather than quietly returning a prompt with its instructions missing. That error subclasses TokenBudgetExceededError, so callers already guarding prompt assembly keep catching one type.

The rendered prompt is what gets charged. Counting sections alone and then joining them with "\n\n" overshoots the allowance, which is exactly the sort of drift that turns into a 400 from a model server. Charging a separator per joint is not enough on its own either: a tokenizer can split a section's tail differently once a separator follows it. Under cl100k_base, "Hello!\r\n", "\n\n" and "World" cost four tokens apart but five joined. So priority_select first weighs each section plus one separator per joint, then measures the rendered prompt as a whole and drops the least important kept section while it overflows. The budget is charged for exactly what Selection.render() returns.

The result is a value, not a list of strings. Selection reports what was kept, what was dropped, and the budget left over — the last of which matters when a caller wants to spend the remainder elsewhere. It iterates over the kept content and stringifies to the rendered prompt, so it still drops straight into a join or a template:

selection.contents      # ("You are...", "User profile: ...")
selection.dropped       # (Section("Device: ...", Priority.LOW),)
selection.is_complete   # False — something was left out
selection.budget        # TokenBudget(41/4096 tokens used, ...)

Kept sections come back in declaration order by default, so the prompt reads as it was written; order=SectionOrder.PRIORITY returns them most important first instead. Sections given blank content are ignored rather than rendered as a doubled separator.

Determinism. Selection is a pure function of the sections and the budget — no clocks, no iteration over unordered collections, no mutation of the budget passed in. The same OnDemandFeatureView therefore drops the same sections during training as it does at serving time.

One change outside the new file: TokenBudgetExceededError gained a keyword-only message override so RequiredSectionError can name the offending section while keeping the same type and attributes. It is additive and backwards compatible. Nothing in Feast imports feast.context yet, so the change remains inert.

Which issue(s) this PR fixes:

No GitHub issue. Tracked internally as RHOAIENG-80116.

Checks

  • I've made sure the tests are passing.
  • My commits are signed off (git commit -s)
  • My PR title follows conventional commits format

Testing Strategy

  • Unit tests
  • Integration tests
  • Manual tests
  • Testing is not required for this change

sdk/python/tests/unit/context/test_priority_select.py — 50 tests with tiktoken installed, 49 passing and 1 skipped without it. Covers priority parsing and ordering (including rejection of a bare number between levels), section normalization from tuples, dropping order, critical sections listed last, keeping a smaller section after refusing a larger one, budget accounting (the charge equals the rendered prompt's cost, and a section is dropped when the joined prompt costs more than its pieces), an already-consumed budget, blank and empty input, and the error's shortfall reporting. One exact-tokenizer test asserts a rendered prompt fits a 64-token cl100k_base budget. ruff check, ruff format --check and mypy are clean.


Devin Review

Decides which parts of a prompt survive a token budget. Sections carry a
priority; selection keeps them from critical down until the allowance is
spent, dropping the least important first and never dropping a critical
one. The result carries the kept sections, the dropped ones and the
budget left over, and renders to the assembled text.

The budget is charged for the separator between kept sections, so the
rendered prompt fits the allowance rather than overshooting it once the
pieces are joined.

Selection is a pure function of the sections and the budget, so an
OnDemandFeatureView drops the same sections offline and online.

Part of RHOAIENG-80116. Stacked on the TokenBudget PR.

Signed-off-by: Chaitany Patel <patelchaitany93@gmail.com>
@patelchaitany
patelchaitany requested a review from a team as a code owner November 23, 2026 09:58

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 1 potential issue.

2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +259 to +265
for position, section in by_importance:
cost = remaining.count_tokens(section.content)
if kept:
cost += separator_tokens
if remaining.fits_tokens(cost):
remaining = remaining.consume_tokens(cost)
kept.append((position, section))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Rendered prompts exceed their token budget

priority_select can accept sections that fit separately but exceed the budget when joined. cl100k_base can split a section’s trailing punctuation and line break into more tokens after the default separator is appended. A model request built from the returned prompt can be rejected for exceeding its limit.

Learn more

TokenBudget.count_tokens counts the text passed to it using the configured tokenizer. With Cl100kBaseTokenizer, joining pieces can change which tokens the tokenizer chooses, and the total can increase. Selection.render returns the joined text without checking its token count. The returned budget therefore can report that the prompt fits even when it does not.

Example: Call priority_select([("critical", "Hello.\r\n"), ("high", "World")], TokenBudget.of(4, fallback=False)). With the default separator, the selector charges 2 + 1 + 1 = 4 and keeps both sections. The rendered "Hello.\r\n\n\nWorld" takes five cl100k_base tokens.

Recommended fix: Count each tentative joined prompt in the requested render order and compare that count with the original budget’s remaining allowance. Keep scanning candidates in priority order, then charge the final rendered count against the original budget so any prior consumption is preserved. Add a regression test with fallback=False using the default separator and the CRLF boundary.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@codecov-commenter

codecov-commenter commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 54.20%. Comparing base (a291a0f) to head (5fa5b6c).
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #7216      +/-   ##
==========================================
+ Coverage   54.10%   54.20%   +0.09%     
==========================================
  Files         467      468       +1     
  Lines       58940    59065     +125     
  Branches     8688     8706      +18     
==========================================
+ Hits        31890    32015     +125     
  Misses      24892    24892              
  Partials     2158     2158              
Flag Coverage Δ
go-feature-server 30.96% <ø> (ø)
python-unit 55.80% <100.00%> (+0.10%) ⬆️
Files with missing lines Coverage Δ
sdk/python/feast/context/__init__.py 100.00% <100.00%> (ø)
sdk/python/feast/context/errors.py 88.88% <100.00%> (+1.93%) ⬆️
sdk/python/feast/context/priority_select.py 100.00% <100.00%> (ø)

Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update a291a0f...5fa5b6c. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Counted one at a time, sections can cost less than the prompt they make:
a tokenizer may split a section's tail differently once a separator
follows it. Under cl100k_base, "Hello!\r\n", "\n\n" and "World" cost four
tokens apart but five joined, so a selection could render over budget.

After the per-section pass, measure the rendered prompt as a whole, drop
the least important kept section while it overflows (raising
RequiredSectionError if only critical sections remain), and charge the
budget for exactly what Selection.render() returns.

Signed-off-by: Chaitany Patel <patelchaitany93@gmail.com>

@franciscojavierarceo franciscojavierarceo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

we need to check the rendered prompt before rejecting critical sections that can fit together.

if remaining.fits_tokens(cost):
remaining = remaining.consume_tokens(cost)
kept.append((position, section))
elif section.is_required:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this raises before checking the rendered cost when separately counted sections overestimate it. for example, priority_select([('critical', 'a'), ('critical', 'b')], TokenBudget(max_tokens=1, tokenizer=ApproximateTokenizer())) rejects the second section, although the rendered a\n\nb is four characters and costs one token with that tokenizer. valid critical prompts therefore fail with RequiredSectionError. we should measure the tentative joined prompt in the requested order against the original remaining allowance before rejecting a critical section, and cover this case with a tight, already-consumed budget too.

…ection

Counted apart, sections can cost more than the prompt they make, since
each rounds up on its own. With the four-characters-a-token estimate and
a one-token budget, "a", "\n\n" and "b" count as three tokens, yet
"a\n\nb" costs one, so two critical sections that fit were refused with
RequiredSectionError.

Before refusing a critical section, render the sections kept so far with
it in the requested order and measure that against what remains of the
budget the caller passed in. Raise only if the joined prompt does not fit.

Signed-off-by: Chaitany Patel <patelchaitany93@gmail.com>

This branch has not been deployed

No deployments
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.

3 participants