Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 59 additions & 22 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
RECALL facts WHERE object.error.code = "rate_limited"
```

`record_tool_call` round-trips a tool'"'"'s `input` as parsed JSON, so Python
`record_tool_call` round-trips a tool's `input` as parsed JSON, so Python
and Node hosts already received the structure — it was specifically the CAL
path that could not see inside. A field name may now be a dotted path of up
to 8 segments (it accepted one dot before, which did not reach the shape a
Expand Down Expand Up @@ -79,18 +79,36 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
paved road is still to store the shape you want to read: two fields rather
than one payload, which makes the value filterable as well as renderable.

- **World-time validity is queryable and renderable** (#206). `valid_from`,
`valid_to`, `system_valid_from` and `system_valid_to` are `GrainCommon`
fields on every grain type — serialized since 1.0, read by the loop's
`staleness` analyzer, and present in every JSON payload — but they were
absent from CAL's filterable set, so the one read that makes a validity
window worth writing answered `CAL-E060`. They now filter and sort on every
type with the usual comparators and `IS NULL`, resolve in templates
(`{{grain.valid_to | date}}`), and appear in `DESCRIBE FIELDS`. "What is
currently valid" is a query:

```sql
RECALL facts WHERE namespace = "desk"
AND (valid_to IS NULL OR valid_to > 1788866000000)
```

This is what a waiver, a delegation, an out-of-office or a price valid until
a date needs. Every host previously over-fetched and post-filtered, which
also defeated `BUDGET` — the budget was spent on grains about to be
discarded.

### Fixed

- **An `ASSEMBLE` source can carry its own pipeline, and no longer drops a
nested assembly'"'"'s grains.** Sources had no pipeline at all, so a source
nested assembly's grains.** Sources had no pipeline at all, so a source
could not be ranked, bounded or summarised in place. Separately,
`assemble.rs` carried a **second copy** of `extract_grains` that had drifted
from the executor'"'"'s: it saw only the `Grains` payload, so a nested
from the executor's: it saw only the `Grains` payload, so a nested
`Assembled` result silently contributed nothing to the enclosing assembly.
There is now one extractor.

### Fixed

- **A `WHERE` predicate on a field the grain does not carry no longer matches
everything** (#207). `object` is a real field name in general — Fact,
Observation and Goal all declare it — but means nothing for a Skill, and the
Expand Down Expand Up @@ -121,27 +139,46 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
too, so the whole filter surface speaks one unit; `format_epoch` keeps its
public seconds signature.

### Added
- **`ASSEMBLE` says what its budget dropped** (#208). `ASSEMBLE` applies a
token budget whether or not the caller writes one — 4000 by default, ceiling
16000 — and when it bound it discarded the tail of each source in silence.
The payload actively hid it: `total_available` reported the **post**-budget
count, so `grains.len() == total_available` held for a truncated assembly
exactly as it did for a complete one. Measured on a real memory, 229
matching grains came back as 80 with `warnings: None`.

- **World-time validity is queryable and renderable** (#206). `valid_from`,
`valid_to`, `system_valid_from` and `system_valid_to` are `GrainCommon`
fields on every grain type — serialized since 1.0, read by the loop's
`staleness` analyzer, and present in every JSON payload — but they were
absent from CAL's filterable set, so the one read that makes a validity
window worth writing answered `CAL-E060`. They now filter and sort on every
type with the usual comparators and `IS NULL`, resolve in templates
(`{{grain.valid_to | date}}`), and appear in `DESCRIBE FIELDS`. "What is
currently valid" is a query:
A budget that drops grains now emits **`CAL-W017`**, naming the sources and
the counts, and saying whether the budget was written or defaulted:

```sql
RECALL facts WHERE namespace = "desk"
AND (valid_to IS NULL OR valid_to > 1788866000000)
```
CAL-W017: the default BUDGET 4000 tokens dropped 130 of 200 grains from
source(s) [e] — this assembly is a window, not the whole match.
```

This is what a waiver, a delegation, an out-of-office or a price valid until
a date needs. Every host previously over-fetched and post-filtered, which
also defeated `BUDGET` — the budget was spent on grains about to be
discarded.
`total_available` is now the **pre**-budget count, so the drop is computable
rather than announced only in prose; each source's `grain_count` still
reports what survived. `docs/cal-reference.md` states the default and the
ceiling where `BUDGET` is documented — neither number appeared there, so "no
`BUDGET` clause" read as "no budget".

The default itself was kept rather than removed: an unbudgeted assembly that
returned everything could overflow the context window it is being composed
for, which is the worse failure. Silence was the defect, not the number.

Why it matters: a host composing a prompt from an assembly had no way to
detect that its rules, its policies or its recent turns were trimmed — it
would publish a number produced from a truncated prompt and never know.
`RECALL` has announced the same kind of cut as `CAL-W015` since 1.5.1.

- **The console shows CAL warnings.** Every other surface honoured the
"silence means the query did what you asked" contract — the bindings and the
MCP tool return `warnings`, the CLI prints them to stderr — but the console
received them from `POST /api/cal` and dropped them on the floor. That was
the worst place for it: this is the surface a person reads an answer from,
and a warning is exactly the news that the answer is a window rather than
the whole match. All seventeen (`CAL-W001`–`W017`) now appear above the
result on the Query page, in plain language, with the `CAL-Wnnn` code shown
only in Developer mode.

## [1.7.3] — 2026-09-07

Expand Down
1 change: 1 addition & 0 deletions ERROR_CODES.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ and are the source of truth. Ranges:
| `CAL-W014` | A `WITH` option parsed and ran but cannot change the result on this statement (e.g. `score_breakdown` on `RECALL`) |
| `CAL-W015` | A post-retrieval stage (`ORDER BY`, a type-specific `WHERE` filter, `COUNT`) widened its scan to `max_limit` and still filled it — the answer is the top-k of a window, not of the memory |
| `CAL-W016` | A pipeline stage was attached to a payload it cannot act on (e.g. `ORDER BY` on a multi-source `ASSEMBLE`) and was skipped |
| `CAL-W017` | An `ASSEMBLE` token budget dropped grains its sources had already retrieved, naming the sources and the counts — including when the 4000-token default applied because no `BUDGET` clause was written |

`CAL-E116` is the "needs an external LLM, not implemented" error for
`WITH hyde` / `WITH llm_rerank` — Areev takes no LLM dependency by policy.
Expand Down
8 changes: 7 additions & 1 deletion crates/areev-cal/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,13 @@ the audit hash.
`*`-bearing namespaces except `*` itself (`parse_grant_parts`). E2E:
`tests/ns_scope_cal_tests.rs`.
- `assemble.rs` — `AssembleEngine`: multi-source ASSEMBLE, dedup, 2000-grain
cap, per-source budget weights, chars/4 token estimate.
cap, per-source budget weights, chars/4 token estimate. **The budget applies
written or not** (`DEFAULT_BUDGET_TOKENS` 4000, parser ceiling 16000), and a
budget that drops grains emits `CAL-W017` naming the sources, the counts, and
whether the default applied (#208). `total_available` is the PRE-budget
count — reporting the trimmed one made a truncated assembly arithmetically
indistinguishable from a complete one. If you add a path that discards grains
here, it warns or it is the same bug again.
- `render.rs` — THE per-grain renderer every surface shares: semantic
`sml`, the documented `markdown` assertion line, `text`, registry-driven
`toon`, the `json` envelope, per-type summaries, and the one `chars/4`
Expand Down
46 changes: 44 additions & 2 deletions crates/areev-cal/src/assemble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,12 +229,25 @@ impl<'a> AssembleEngine<'a> {
};

// 4. Allocate budget.
//
// Note the default: an ASSEMBLE with no BUDGET clause is still
// budgeted. That stays (an unbudgeted assembly could otherwise
// overflow the context window it is being composed for — the worse
// failure), but it is now *reported*, because "no BUDGET clause"
// reads as "no budget" and used to behave as neither.
let budget_defaulted = stmt.budget.is_none();
let budget_tokens = stmt
.budget
.as_ref()
.map(|b| b.tokens)
.unwrap_or(DEFAULT_BUDGET_TOKENS);

// How many grains the sources actually retrieved, before any of this
// spends them. `total_available` is reported from here rather than
// from the trimmed set: a caller cannot compute what a budget removed
// from a number the budget already reduced.
let available_pre_budget: usize = source_results.iter().map(|(_, g)| g.len()).sum();

let labels: Vec<&str> = source_results.iter().map(|(l, _)| l.as_str()).collect();

// ── PIN: satisfy the non-degradable sources first ────────────────
Expand Down Expand Up @@ -296,6 +309,9 @@ impl<'a> AssembleEngine<'a> {
let mut meta: Vec<SourceMeta> = Vec::new();
let mut remaining_budget = budget_tokens;
let mut dropped = 0usize; // grains the budget forced us to omit
// The labels behind that number: "149 grains went" is not actionable
// on a four-source assembly without knowing which section lost them.
let mut dropped_labels: Vec<String> = Vec::new();

for (i, (label, mut grains)) in source_results.into_iter().enumerate() {
// A pinned source was already costed in full and reserved off the
Expand Down Expand Up @@ -327,9 +343,14 @@ impl<'a> AssembleEngine<'a> {
// — which is the opposite of what a budget is for.
let (keep, tokens_used) = self.budget_prefix(&grains, effective_allocation);
let budget_omitted = grains.split_off(keep);
if !budget_omitted.is_empty() {
dropped_labels.push(label.clone());
}
dropped += budget_omitted.len();
let mut omitted = budget_omitted;
if let Some(cap_tail) = capped_omitted.remove(&label) {
// The post-dedup cap already warned for itself above; this
// only folds its tail into the omitted set for ELEMENT_OMIT.
dropped += cap_tail.len();
omitted.extend(cap_tail);
}
Expand All @@ -352,15 +373,36 @@ impl<'a> AssembleEngine<'a> {
// §8): overflow = the token budget forced grains to be dropped.
store.note_assembly_budget(dropped > 0);

// Say what the budget cut. RECALL has announced the same kind of cut
// as CAL-W015 since 1.5.1 — an assembly making it silently is how a
// host ends up composing a prompt from 79 of 229 grains and
// publishing a number it produced.
if !dropped_labels.is_empty() {
warnings.push(
super::errors::CalWarning::AssembleBudgetDropped {
labels: dropped_labels,
dropped,
available: available_pre_budget,
budget: budget_tokens,
defaulted: budget_defaulted,
}
.to_string(),
);
}

// 6. Build result.
let count = final_grains.len();
Ok(CalResultPayload::Assembled {
grains: final_grains,
sources: meta,
total_tokens,
budget_limit: Some(budget_tokens),
progressive: false,
total_available: Some(count),
// PRE-budget (#208). This used to report the trimmed count, which
// made a truncated assembly arithmetically indistinguishable from
// a complete one — `grains.len() == total_available` held either
// way. The per-source `grain_count` still reports what survived,
// so the drop is computable rather than announced only in prose.
total_available: Some(available_pre_budget),
})
}

Expand Down
56 changes: 55 additions & 1 deletion crates/areev-cal/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1488,6 +1488,35 @@ pub enum CalWarning {
payload: &'static str,
why: &'static str,
},

/// CAL-W017 — An `ASSEMBLE` token budget dropped grains a source had
/// already retrieved.
///
/// `ASSEMBLE` applies a budget whether or not the caller wrote one
/// (`DEFAULT_BUDGET_TOKENS`, 4000), and when it binds it discards the
/// tail of each source in silence. The payload actively hid it:
/// `total_available` reported the *post*-budget count, so a truncated
/// answer was indistinguishable from a full one. The same cut on
/// `RECALL` has announced itself as `CAL-W015` since 1.5.1 — a host
/// composing a prompt from an assembly has to be able to tell that its
/// rules, its policies or its recent turns were trimmed, or it will
/// publish a number produced from a truncated prompt and never know.
///
/// `defaulted` distinguishes the two cases the caller cares about most:
/// a budget they wrote (raise it) from one they never asked for (write
/// one, or narrow the source).
AssembleBudgetDropped {
/// Source labels the budget cut, in FROM-clause order.
labels: Vec<String>,
/// Grains discarded across those sources.
dropped: usize,
/// Grains the sources retrieved before the budget was applied.
available: usize,
/// The budget that bound, in tokens.
budget: u32,
/// True when no `BUDGET` clause was written and the default applied.
defaulted: bool,
},
}

impl CalWarning {
Expand All @@ -1509,6 +1538,7 @@ impl CalWarning {
Self::WithOptionInert { .. } => "CAL-W014",
Self::ScanBounded { .. } => "CAL-W015",
Self::PipelineStageInert { .. } => "CAL-W016",
Self::AssembleBudgetDropped { .. } => "CAL-W017",
}
}

Expand All @@ -1529,7 +1559,8 @@ impl CalWarning {
| Self::ContradictionScanBounded { .. }
| Self::WithOptionInert { .. }
| Self::ScanBounded { .. }
| Self::PipelineStageInert { .. } => None,
| Self::PipelineStageInert { .. }
| Self::AssembleBudgetDropped { .. } => None,
}
}
}
Expand Down Expand Up @@ -1638,6 +1669,29 @@ impl std::fmt::Display for CalWarning {
"CAL-W016: {stage} has no effect on a {payload} result — {why}. The stage was skipped; the result is the same as without it."
)
}
Self::AssembleBudgetDropped {
labels,
dropped,
available,
budget,
defaulted,
} => {
let clause = if *defaulted {
"the default BUDGET"
} else {
"BUDGET"
};
let advice = if *defaulted {
" No BUDGET clause was written, so the 4000-token default applied — write one (ceiling 16000 tokens), or narrow the source."
} else {
" Raise the budget (ceiling 16000 tokens), or narrow the source."
};
write!(
f,
"CAL-W017: {clause} {budget} tokens dropped {dropped} of {available} grains from source(s) [{}] — this assembly is a window, not the whole match.{advice}",
labels.join(", ")
)
}
}
}
}
Expand Down
Loading