Skip to content

[MOD-17631] Add safe global_config crate - #10915

Merged
memark merged 4 commits into
masterfrom
memark-global-config-wrapper
Aug 17, 2026
Merged

memark merged 4 commits into
masterfrom
memark-global-config-wrapper

Conversation

@memark

@memark memark commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Describe the changes in the pull request

  1. Current: Rust code that needs a RediSearch setting reads the RSGlobalConfig extern static directly, which is unsafe at every call site. Ten such reads had grown across four crates, each carrying its own safety argument — and several of those arguments contradicted src/config.c, claiming fields were fixed at load time when CONFIG SET can in fact change them while queries run.
  2. Change: a global_config crate owns the read, exposing one accessor per setting. The accessors are generated from a macro, so a new field inherits the shared safety argument instead of acquiring its own.
  3. Outcome: internal-only — no user-visible change. It replaces ten hand-written safety arguments with one, and gives future Rust code a safe way to read config without adding an eleventh.

Which additional issues this PR fixes

  1. MOD-17631

Main objects this PR modified

  1. global_config — new crate in c_wrappers/, one accessor per RSGlobalConfig field.
  2. query_eval_ffi::eval_config — was three separate unsafe reads, now resolves the settings an evaluation needs into its own snapshot.
  3. iterators_ffi — intersection and the geo/numeric inverted-index readers.
  4. reducers, redis_mock — one read each, migrated.

Mark if applicable

  • This PR introduces API changes
  • This PR introduces serialization changes

Release Notes

  • This PR requires release notes
  • This PR does not require release notes

Worth a reviewer's attention

There is deliberately no whole-struct accessor. Returning RSConfig by value looks like it buys inter-field consistency, but the copy is not atomic, so it never did — and it hands every caller an owned defaultScorer pointer that CONFIG SET DEFAULT_SCORER can free, whether or not the caller wanted that field. An operation that needs several settings to agree resolves them into its own snapshot up front, which is what eval_config does.

The reads are unsynchronised, matching what the C readers of the same fields already do: a read can race with a CONFIG SET write, and closing that needs the C side to store the fields atomically. The accessors are safe rather than unsafe on that basis — they change no C behavior, and marking them unsafe would state a precondition no caller can uphold. The module docs say this outright rather than claiming a guarantee that does not hold.

default_scorer is the one accessor written out by hand rather than generated. It returns Option<NonNull<c_char>>, putting the unset case in the type instead of leaving every caller to null-check, and its doc carries the hazard no pointer type can express: the string can be freed while a caller still holds the pointer, so a caller that needs the name must copy it.

@memark memark changed the title [MOD-17631] Wrap reads of RSGlobalConfig in a safe global_config crate [MOD-17631] Add safe global_config crate Aug 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 39f00656e3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

pub fn get() -> ffi::RSConfig {
// SAFETY: `RSGlobalConfig` is a statically initialised C global that lives for the whole
// process, and `RSConfig` is `Copy`, so the value is read out without forming a reference.
unsafe { ffi::RSGlobalConfig }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid whole-config unsynchronized reads

Because this copies the entire C RSConfig, every global_config::get().numericCompress/maxAggregateResults call now also performs an unsynchronized read of pointer fields such as defaultScorer. If a worker thread is building a numeric/aggregate iterator while another client runs FT.CONFIG SET DEFAULT_SCORER, set_default_scorer_config can free and rewrite that pointer while this safe function is reading it, expanding the previous field-specific race into unrelated settings and making safe Rust able to hit undefined behavior. Please keep the read scoped to the requested field, or lock/atomically snapshot the config instead of copying the whole struct.

AGENTS.md reference: AGENTS.md:L294-L295

Useful? React with 👍 / 👎.

@daxhuiberts daxhuiberts Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I agree with Codex here. Two things:

  1. We're unnecessarily copying the config here (Probably to prevent a data race?)
  2. But a data race can still happen when a mutable global static is accessed (or copied) without synchronization.

The C code is/was already UB, but we're carrying the UB over to safe Rust now as well. Safe Rust code should not contain any UB, else the premise of Rust goes out the window. I'm not sure what would be the best way to solve this, because this would likely mean ensuring the mutations on the C side should be fixed as well.

This problem comes up now much more than before now that we interface with existing C code more often (as I do with the Terms and Dict wrappers as well). Getting safe sound UB free abstractions around existing C code is nearly impossible. This is the annoying part of interfacing with UB filled C code in Rust and sadly I don't have the answer.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I hear you. Would it solve anything with individual fields exposed instead of the entire config?

What I'm trying to do is just get rid of all the unsafe blocks reading config in different crates. Their safety comments greatly vary, as you can see in the diff tab. But I'm certainly open to the possibility that this isn't really possible.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

At least I think the copying doesn't add anything and returning a lifetimed ref would work as well, as they would have the same UB. Albeit a lifetimed ref could probably have a larger window for a data race to occur, in it's current use the window is still small.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Changed the PR to just return individual fields instead.

@codecov

codecov Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 22.22222% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.19%. Comparing base (1847e3f) to head (611be9e).
⚠️ Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
...disearch_rs/c_entrypoint/query_eval_ffi/src/lib.rs 0.00% 6 Missing ⚠️
.../redisearch_rs/c_wrappers/global_config/src/lib.rs 50.00% 3 Missing ⚠️
...ypoint/iterators_ffi/src/inverted_index/numeric.rs 0.00% 2 Missing ⚠️
..._rs/c_entrypoint/iterators_ffi/src/intersection.rs 0.00% 1 Missing ⚠️
...entrypoint/iterators_ffi/src/inverted_index/geo.rs 0.00% 1 Missing ⚠️
src/redisearch_rs/redis_mock/src/globals.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #10915      +/-   ##
==========================================
- Coverage   83.17%   82.19%   -0.99%     
==========================================
  Files         611      636      +25     
  Lines       81136    82247    +1111     
  Branches    36374    37485    +1111     
==========================================
+ Hits        67485    67599     +114     
- Misses      13304    14301     +997     
  Partials      347      347              
Flag Coverage Δ
flow 84.38% <ø> (-0.01%) ⬇️
unit 55.76% <22.22%> (-0.61%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb7d69a702

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +47 to +49
pub fn $name() -> $ty {
// SAFETY: see this module's *Safety of these reads*.
unsafe { ffi::RSGlobalConfig.$field }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Do not mark racy config loads safe

Fresh evidence after the earlier whole-struct comment: this version removed the struct copy, but each new accessor is still a safe function that performs a non-atomic load from RSGlobalConfig. When a query/background worker calls numeric_compress() or default_scorer() while another client runs FT.CONFIG SET for the same field, the C setter writes the same storage concurrently; safe Rust code can then trigger undefined behavior from a data race. Please make these accessors unsafe with the race as a caller precondition, or route the fields through synchronization/atomics before exposing a safe API.

AGENTS.md reference: AGENTS.md:L294-L295

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

While I agree it's not perfect, it's not worse than what we currently have. It's basically a collecting of all the related unsafe blocks into one crate. As per the slack thread, it seems difficult to achieve anything better without redoing things on the C side.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I agree with you.

Maybe we should have a 'safe, with known UB' tag on those methods :) But that is for the safety discussion.

@memark
memark requested review from daxhuiberts and gdesmott August 14, 2026 11:07
@memark

memark commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator Author

Would you look at the scorer-related changes? @gdesmott

daxhuiberts
daxhuiberts previously approved these changes Aug 14, 2026

@daxhuiberts daxhuiberts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One minor comment addition I think is worth adding.

Comment on lines +28 to +29
//! This crate exists to replace the C readers of the same fields rather than to change what
//! they do; closing the race needs the C side to store the fields atomically.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

'... needs the C side to store the fields atomically' ...and both the C and Rust side to load them atomically.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Updated in 07c3561.

@daxhuiberts

Copy link
Copy Markdown
Collaborator

I'm going to need ffi::RSGlobalConfig.hideUserDataFromLog for the terms scanner. Can you already add that as well?

@memark

memark commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator Author

I'm going to need ffi::RSGlobalConfig.hideUserDataFromLog for the terms scanner. Can you already add that as well?

Added in separately in #10924 just to try the stacked PR. 😆

memark and others added 4 commits August 14, 2026 15:30
Rust code that wants a RediSearch setting has to read the RSGlobalConfig
extern static, which is unsafe at every call site. Six such reads had grown
across four crates, each carrying its own safety argument, and those arguments
disagreed with src/config.c: numericCompress, prioritizeIntersectUnionChildren
and maxAggregateResults are all registered without
REDISMODULE_CONFIG_IMMUTABLE, so CONFIG SET can change them while queries run,
yet the comments claimed the fields were fixed at load time.

The new crate holds the read in one place. It hands back RSConfig by value
rather than a reference, because a &'static RSConfig would assert that nothing
writes the static while it lives, which CONFIG SET violates from client threads.
The copy is a plain unsynchronised load, matching what the C readers of the same
fields do; it can tear against a concurrent write, and removing that race needs
the C side to store the fields atomically.

Returning the whole struct also lets a caller that needs several settings take
one snapshot instead of one read per field, so an operation cannot observe a
setting changing halfway through. query_eval_ffi::eval_config does exactly that.

Co-Authored-By: Claude Opus 5 <[email protected]>
Review of the wrapper turned up three claims that overstate what a by-value
snapshot buys. `get`'s SAFETY comment established liveness and the absence of a
reference but not the third precondition for reading a `static mut`, that no
other thread writes it — which is exactly the one that does not hold, as the
doc comment directly above it already said. The comment now names the race
instead of leaving the two in contradiction.

For the same reason a snapshot cannot make an operation immune to a concurrent
`CONFIG SET`: the struct copy is not atomic, so it narrows the window rather
than closing it. `eval_config` additionally called itself the single point
where the evaluator reads the global config, which `resolve_scorer` disproves
two functions further down.

Also mark `get` `#[inline]`, so that a caller wanting one field does not pay
for an out-of-line call returning the whole struct in builds without LTO.

Co-Authored-By: Claude Opus 5 <[email protected]>
`global_config::get()` returned the whole `RSConfig`. The copy is not atomic,
so it did not make the fields it returned agree with one another, while
copying a large struct and handing back owned pointers no caller had asked
for — among them `defaultScorer`, which `FT.CONFIG SET DEFAULT_SCORER` frees.

Replace it with one accessor per field, generated from a macro so a new field
cannot be added without the shared safety argument covering it.

`default_scorer` is written out rather than generated: it returns
`Option<NonNull<c_char>>`, putting the unset case in the type instead of
leaving every caller to null-check, and its doc carries the hazard no pointer
type can express — the string can be freed while a caller still holds it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@memark
memark force-pushed the memark-global-config-wrapper branch from 07c3561 to 611be9e Compare August 14, 2026 13:30
@sonarqubecloud

Copy link
Copy Markdown

@gdesmott

Copy link
Copy Markdown
Collaborator

Would you look at the scorer-related changes? @gdesmott

Looks good to me!

@memark

memark commented Aug 17, 2026

Copy link
Copy Markdown
Collaborator Author

@daxhuiberts If you're happy as well please approve.

@memark
memark requested a review from daxhuiberts August 17, 2026 10:00
@memark
memark added this pull request to the merge queue Aug 17, 2026
Merged via the queue into master with commit b1031e3 Aug 17, 2026
196 of 203 checks passed
@memark
memark deleted the memark-global-config-wrapper branch August 17, 2026 12:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants