class
Backtrack
local bt = Grammar.backtrack(ctx, vocab, sampler, {
seq_id = session.seq_id,
pos = session.n_past,
})
bt:checkpoint("tbl") -- save seq KV at this pos
bt:forward(function(p) return p:find("%s") end) -- gen until space
bt:constrain("tbl", function(text) -- validate; rollback if false
return db:has_table(text:match("(%w+)$"))
end)
local result = bt:run()
Functions
Backtrack.new
Create a Backtrack session.
Backtrack:_gen_one
Backtrack:_save_snapshot
Backtrack:_restore_to
Backtrack:checkpoint
Register a grammar symbol checkpoint. Saves a KV snapshot at the current position and associates it with a name.
Backtrack:forward
Generate tokens until a predicate returns true or max_tokens reached.
Backtrack:backward
Backtrack to the last checkpoint for a symbol and resample.
Backtrack:text
Return the full generated text so far.
Backtrack:is_done
Return whether generation is complete.
Backtrack:last_checkpoint
Return the last checkpoint index for a symbol.
Backtrack:n_tokens
Number of tokens generated so far.
Backtrack:constrain
Apply a semantic constraint at the current position (CRANE pattern). If the validator fails on the current text, rolls back to the last checkpoint for `symbol` and re-runs `forward` (using `opts.forward_pred` and `opts.max_forward`) before re-validating. This mirrors how `run()` uses constrain: checkpoint → forward → constrain, so retries must repeat the forward pass to produce a complete new candidate.
Backtrack:run
Run a complete constrained generation loop with automatic backtracking.