#7545·surrealdb

surrealdb-parser: PeekableLexer::peek reads uninitialized memory when peek offsets are requested out of order

Author: YZL0v3ZZCreated Sep 27, 2026Updated Sep 27, 2026
Labelstriage

What component does this affect?

SurrealDB Server

Describe the bug

surrealdb-parser stores its lookahead tokens in a ring buffer of four MaybeUninit<Result<Token, LexError>> slots. PeekableLexer::peek::<OFFSET> (surrealdb/parser/src/peekable.rs, lines 65 to 105) is responsible for guaranteeing that the slot at read + OFFSET has been initialized, lexing whichever tokens are still missing. The bounds of the refill loop, however, are inverted, so the loop is skipped precisely when it is needed.

Ring buffer layout and initialization

surrealdb/parser/src/peekable.rs, lines 8 to 13:

rust
pub struct PeekableLexer<'source, const SIZE: usize> {
	lexer: Lexer<'source, BaseTokenKind>,
	peek: [MaybeUninit<Result<Token, LexError>>; SIZE],
	read: u8,
	write: u8,
}

surrealdb/parser/src/peekable.rs, lines 34 to 41:

rust
pub fn new(lexer: Lexer<'source, BaseTokenKind>) -> Self {
	PeekableLexer {
		lexer,
		peek: [const { MaybeUninit::uninit() }; SIZE],
		read: 0,
		write: 0,
	}
}

MASK is defined as SIZE - 1 (peekable.rs:32), and the parser instantiates the buffer with four slots (surrealdb/parser/src/parse/mod.rs:209):

rust
pub struct Parser<'source, 'ast> {
	lex: PeekableLexer<'source, 4>,
	last_span: Span,
	ast: &'ast mut Ast,
	...
}

Every slot therefore starts uninitialized, and both cursors start at zero.

The peek implementation

surrealdb/parser/src/peekable.rs, lines 65 to 105:

rust
pub fn peek<const OFFSET: u8>(&mut self) -> Option<Result<Token, LexError>> {
	const {
		assert!(
			(OFFSET as usize) < SIZE,
			"peek offset must be less then size of the peek buffer"
		)
	};

	if OFFSET == 0 {
		if self.read != self.write {
			Some(unsafe {
				self.peek.get_unchecked_mut((self.read & Self::MASK) as usize).assume_init()
			})
		} else {
			let x = self.lex_token()?;
			unsafe {
				*self.peek.get_unchecked_mut((self.write & Self::MASK) as usize) =
					MaybeUninit::new(x)
			};
			self.write = self.write.wrapping_add(1);
			Some(x)
		}
	} else {
		let write = self.write & Self::MASK;
		let read = self.read.wrapping_add(OFFSET) & Self::MASK;

		let write = if write < read {
			write + SIZE as u8
		} else {
			write
		};

		for _ in write..=read {
			let x = self.lex_token()?;
			self.peek[(self.write & Self::MASK) as usize] = MaybeUninit::new(x);
			self.write = self.write.wrapping_add(1);
		}

		Some(unsafe { self.peek[read as usize].assume_init() })
	}
}

The OFFSET == 0 branch is correct: an empty buffer is filled with exactly one token, and a non-empty buffer returns the initialized slot at read. In the OFFSET != 0 branch, by contrast, the bounds of the refill loop are inverted: whenever the producer has not yet reached the target slot and the two masked indices differ, the range write..=read is left empty, either because the adjustment write + SIZE places its start after its end or because its start already follows its end; the function then calls assume_init() on a slot for which no MaybeUninit::new has ever executed. On a freshly constructed parser the ring is entirely uninitialized, so a single call to peek1() or peek2() suffices to reach uninitialized memory. An exhaustive traversal of the ring buffer states confirms that 48 combinations of read, write and OFFSET exhibit the defect, among them the following representative cases:

read write OFFSET producer slot target slot refill iterations
0 0 1 0 1 0
0 0 2 0 2 0
0 1 2 1 2 0
1 1 1 1 2 0

The loop behaves correctly only when exactly one token is missing and the producer already occupies the target slot, which is the situation that the crate's own grammar happens to produce at each of its peek sites.

Steps to reproduce

To allow the behaviour to be confirmed directly, the reproduction consists of a single integration test file which relies exclusively on the public safe API of the crate.

Save the following file as surrealdb/parser/tests/peekable_uninit_read.rs.

Full reproduction test file
rust
//! PoC: uninitialized read in `surrealdb-parser`'s peek ring buffer.
//!
//! `Parser::peek1`/`Parser::peek2` are public safe methods and [`Parse`] is a
//! public trait that users may implement. When a `Parse` implementation peeks an
//! offset before every smaller offset has been peeked, `PeekableLexer::peek`
//! executes `MaybeUninit::assume_init` on a slot that was never written.
//!
//! Check with Miri:
//!   cargo +nightly-2026-03-21 miri test -p surrealdb-parser --test peekable_uninit_read

use surrealdb_parser::parse::ParseResult;
use surrealdb_parser::{Config, Parse, Parser};

/// Peeks offset 1 on a fresh parser: slot 1 is never written.
struct Peek1First;

impl Parse for Peek1First {
	async fn parse(parser: &mut Parser<'_, '_>) -> ParseResult<Self> {
		let _ = parser.peek1()?;
		Ok(Peek1First)
	}
}

/// Peeks offset 2 on a fresh parser: slots 1 and 2 are never written.
struct Peek2First;

impl Parse for Peek2First {
	async fn parse(parser: &mut Parser<'_, '_>) -> ParseResult<Self> {
		let _ = parser.peek2()?;
		Ok(Peek2First)
	}
}

/// Peeks offset 0 then jumps to offset 2: slot 2 is never written.
struct PeekSkippingOne;

impl Parse for PeekSkippingOne {
	async fn parse(parser: &mut Parser<'_, '_>) -> ParseResult<Self> {
		let _ = parser.peek()?;
		let _ = parser.peek2()?;
		Ok(PeekSkippingOne)
	}
}

/// Control: offsets 0, 1, 2 in ascending order fill exactly one slot per call.
struct AscendingPeeks;

impl Parse for AscendingPeeks {
	async fn parse(parser: &mut Parser<'_, '_>) -> ParseResult<Self> {
		let _ = parser.peek()?;
		let _ = parser.peek1()?;
		let _ = parser.peek2()?;
		Ok(AscendingPeeks)
	}
}

#[test]
fn peek1_on_empty_buffer_reads_uninitialized_slot() {
	let _ = Parser::enter_parse::<Peek1First>("alpha beta gamma", Config::default());
}

#[test]
fn peek2_on_empty_buffer_reads_uninitialized_slot() {
	let _ = Parser::enter_parse::<Peek2First>("alpha beta gamma", Config::default());
}

#[test]
fn skipping_one_offset_reads_uninitialized_slot() {
	let _ = Parser::enter_parse::<PeekSkippingOne>("alpha beta gamma", Config::default());
}

#[test]
fn control_ascending_peeks_are_initialized() {
	let _ = Parser::enter_parse::<AscendingPeeks>("alpha beta gamma", Config::default());
}

Run the tests without Miri first:

Plain cargo test output: all four tests pass
$ cargo +nightly-2026-03-21 test -p surrealdb-parser --test peekable_uninit_read
running 4 tests
test peek1_on_empty_buffer_reads_uninitialized_slot ... ok
test control_ascending_peeks_are_initialized ... ok
test peek2_on_empty_buffer_reads_uninitialized_slot ... ok
test skipping_one_offset_reads_uninitialized_slot ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

All four tests pass, since an uninitialized read is silent in a native build; the defect is consequently invisible to the unit tests, to the fuzzing target and to the language test corpus.

Then run the same tests under Miri:

Miri output: undefined behaviour at peekable.rs:103
$ cargo +nightly-2026-03-21 miri test -p surrealdb-parser --test peekable_uninit_read
running 4 tests
test control_ascending_peeks_are_initialized ... ok
test peek1_on_empty_buffer_reads_uninitialized_slot ... error: Undefined Behavior: constructing invalid value at .<enum-tag>: encountered uninitialized memory, but expected an integer
 --> surrealdb/parser/src/peekable.rs:103:17
  |
  = note: Undefined Behavior occurred here
  = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
  = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
  = note: stack backtrace:
          0: surrealdb_parser::peekable::PeekableLexer::<'_, 4>::peek::<1>
              at surrealdb/parser/src/peekable.rs:103:18: 103:56
          1: surrealdb_parser::Parser::<'_, '_>::peek1
              at surrealdb/parser/src/parse/mod.rs:532:9: 532:29
          2: <Peek1First as surrealdb_parser::Parse>::parse::{closure#0}
              at surrealdb/parser/tests/peekable_uninit_read.rs:19:11: 19:25
          3: surrealdb_parser::Parser::<'_, '_>::parse::<Peek1First>::{closure#0}
              at surrealdb/parser/src/parse/mod.rs:754:18: 754:23
          ...
         11: surrealdb_parser::Parser::<'_, '_>::enter_parse_reuse::<Peek1First>
              at surrealdb/parser/src/parse/mod.rs:270:21: 270:34
         12: surrealdb_parser::Parser::<'_, '_>::enter_parse::<Peek1First>
              at surrealdb/parser/src/parse/mod.rs:228:14: 228:75

error: aborting due to 1 previous error

Frames 4 through 10, omitted above for brevity, belong to the cooperative reblessive stack that drives the async parse future and contain nothing relevant to the defect. Because Miri terminates the process at the first undefined operation, the two remaining offset variants do not report separately; both execute the same assume_init and are redundant with the reported case. The ascending order control test passes under Miri, which demonstrates that the failure depends on the call order rather than on the crate being unusable.

The reported stack confirms the analysis: peek::<1> is reached from Parser::peek1, itself invoked by the safe Parse implementation through the public enter_parse entry point, with the uninitialized read occurring at peekable.rs:103.

Expected behaviour

A call to peek1(), peek2() or, more generally, peek::<OFFSET> is expected either to lex the missing tokens or to report a well defined error, and under no circumstances to read memory that has not been initialized; a fresh parser, an exhausted lexer and a sequence of peek calls issued out of order ought all to remain free of undefined behaviour. Should the intended design require offsets to be requested in ascending order, that requirement would need to be documented and enforced, for instance by returning an error before the read, rather than by relying on memory that was never initialized.

SurrealDB version

surreal 3.3.0-nightly for linux on x86_64

Contact Details

[email protected]

Could this be a bug with your application?

  • I confirm this is a bug with SurrealDB, not with my own application

Is there an existing issue for this?

  • I confirm that I have searched the existing issues

Code of Conduct

  • I agree to follow this project's Code of Conduct