6.12 Namespaces and Package Loading
6.12.1 Motivation
An R package is a collection of code and data. library(tidyverse) loads it and makes its functions available, which means R has to find the installed package, know where each function is stored, and decide which function wins when two packages define the same name.
The namespace system handles all three. Each package has a namespace, a mapping of names to objects, so one package’s foo does not collide with another’s, and functions from different packages can still call each other through what they import.
Loading a package means making its code available in its namespace and registering its functions. For packages with compiled code, loading also means dynamically linking a C library and registering native symbols. Much of this machinery keeps process-wide state, and that is where the threading hazards come from.
6.12.2 Mental model
A namespace is an environment. Specifically, it is a list-like object mapping names to values. When you call a function foo from package bar, R looks for foo in the bar namespace. It finds the function object. It evaluates the call.
Every loaded package has a namespace. When you call library(tidyverse), the tidyverse namespace is loaded, and tidyverse in turn attaches dplyr, tidyr and its other core packages, so select(), pivot_longer() and the rest become accessible. Their names live in their respective package namespaces, not in the global environment.
library(dplyr)
# dplyr is now loaded.
# The select function lives in the dplyr namespace.
# select is also attached to the search path.
# You can call select(data, name_of_column).Package namespaces are not usually printed or modified by user code. But they are the mechanism that makes packages work.
6.12.3 Mechanism
Package structure
A package is a directory with a standard structure. It contains:
- R/ directory: R source files. Each file is read and executed in the package namespace.
- man/ directory: documentation files.
- src/ directory: C, C++, or Fortran source files. These are compiled to a shared library.
- NAMESPACE file: declares which functions are exported, which are imported from other packages.
- DESCRIPTION file: package metadata, dependencies, version.
When the package is installed, R processes these files. The R files are sourced into a namespace once, byte-compiled, and saved as a lazy-load database (R/<pkg>.rdb and R/<pkg>.rdx). C source files are compiled to a shared library, stored in the installed package’s libs/ directory (libs/x64/ on Windows).
When the package is loaded, R lazy-loads that database into the namespace, loads the shared library, and registers its native routines. Loading the library is dynamic linking.
Loading and namespace binding
loadNamespace(), in src/library/base/R/namespace.R, does the work, in this order.
First, it checks the registry of loaded namespaces. If the package is already there, it returns that namespace after an optional version check.
Second, it reads the parsed NAMESPACE file saved at install time (Meta/nsInfo.rds), creates the namespace environment, and registers it.
Third, it loads the packages listed as imports and copies the imported bindings into the namespace’s imports environment.
Fourth, it loads the R code. A small loader script lazy-loads the database, so each function becomes a promise in the namespace and is read from disk on first use. Then it registers the package’s S3 methods.
Fifth, if the package has compiled code, it loads the shared library with library.dynam(), which calls the package’s R_init_<pkg> routine. That is where symbol registration happens.
Sixth, it runs the package’s .onLoad hook, then processes the exports and seals the namespace.
library() adds a last step: it attaches the package. Attaching puts a new environment, package:dplyr for dplyr, on the search path, holding the exported bindings, and runs .onAttach.
library(dplyr)
# 1. Return at once if the dplyr namespace is already loaded.
# 2. Read Meta/nsInfo.rds; create and register the namespace.
# 3. Load the imported packages; fill the imports environment.
# 4. Lazy-load the R code; register S3 methods.
# 5. Load libs/dplyr.so (dplyr.dll on Windows); its init routine registers routines.
# 6. Run .onLoad; process exports; seal the namespace.
# Then library() attaches package:dplyr to the search path.Symbol registration
Symbol registration is the critical step for compiled code.
When a package has C code, that code is compiled to a shared library (a .so file on Linux, .dll on Windows). The library contains compiled functions. Without registration, R looks a routine up by name in the library at call time. Registration tells R up front which functions are meant to be called from R and how many arguments each takes, and R_useDynamicSymbols(dll, FALSE) turns the by-name lookup off.
A symbol is a named location in a compiled library. It is a function address. Registering a routine maps a name to that address. The table lives in the library’s DllInfo record, in R’s C-level list of loaded libraries (Rdynload.c). With useDynLib(mypackage, .registration = TRUE) in NAMESPACE, loadNamespace() also creates an R object for each registered routine in the namespace, so package code can call .Call(C_sum, x) with no lookup by name at all.
A typical registration looks like this.
// In src/registration.c
SEXP R_sum(SEXP x); // defined in another file in src/
static const R_CallMethodDef callMethods[] = {
{"C_sum", (DL_FUNC) &R_sum, 1},
{NULL, NULL, 0}
};
void R_init_mypackage(DllInfo *dll) {
R_registerRoutines(dll, NULL, callMethods, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}The R_init_mypackage function is called when the library is loaded. It registers the C function R_sum under the name C_sum. R code can then call .Call("C_sum", x, PACKAGE = "mypackage"), or .Call(C_sum, x) when NAMESPACE uses .registration = TRUE.
Process-global state
Packages often maintain process-global state. This is mutable data that persists across function calls. It is often a cache, a connection pool, or a configuration setting.
// Global cache (BAD PRACTICE).
struct cache { SEXP entries; };
SEXP get_from_cache(struct cache *c, SEXP key);
static struct cache *g_cache = NULL;
SEXP C_init_cache(void) {
g_cache = malloc(sizeof(struct cache));
return R_NilValue;
}
SEXP C_get_cached(SEXP key) {
// Use g_cache.
return get_from_cache(g_cache, key);
}The global variable g_cache is shared by every call into the library. If one thread calls C_init_cache while another calls C_get_cached, they race on g_cache, and a cache that is written while it is read can be corrupted.
This pattern is common in CRAN packages, which were written for a runtime with one R thread.
Packages with compiled code often maintain mutable global state (caches, connection pools, configuration). This state is not protected by locks and is not thread-safe.
6.12.4 Internal mechanics
The package search path
When R evaluates an expression, it looks up names in environments. It starts with the current environment. If a name is not found, it searches the parent environment, and so on up the chain of enclosing environments. For code typed at the prompt, that chain reaches the global environment at once. For a package function, it passes through the package’s namespace, its imports, and the base namespace first.
After the global environment, R searches the attached packages, most recently attached first. Each attached package is an environment, package:<name>, that holds the package’s exports. It is not the namespace itself.
library(dplyr)
library(tidyr)
search()
# [1] ".GlobalEnv" "package:tidyr" "package:dplyr"
# [4] "package:stats" "package:graphics" "package:grDevices"
# [7] "package:utils" "package:datasets" "package:methods"
# [10] "Autoloads" "package:base"If tidyr and dplyr both define a function with the same name, tidyr’s is found first. This is called masking. The function from tidyr masks the function from dplyr.
Dynamic linking
When a package is loaded, R uses dlopen (or the equivalent on Windows) to open the shared library. The library is linked into the running process. Functions in the library can now be called.
Symbol registration is part of dynamic linking. R calls the package’s initialization function (R_init_packagename). This function registers symbols. After registration, R code can call the native functions via .C, .Call, .External or .Fortran.
Several libraries can define a symbol with the same name. Where the platform supports it, R opens package libraries with local symbol scope (dyn.load(local = TRUE) is the default), so one library’s foo does not resolve another library’s calls. When .Call names a routine by string without PACKAGE, R searches the loaded libraries from the most recently loaded back (R_FindSymbol in Rdynload.c). A PACKAGE argument or a registered routine object avoids the search.
Package initialization runs once per session. loadNamespace() returns a namespace that is already registered without running .onLoad again, and dyn.load() of a library that is already loaded only moves it to the front of R’s list, without calling R_init_<pkg> again (AddDLL in Rdynload.c).
Namespace vs. environment differences
A namespace is an environment, but with special behavior. Its parent is the package’s imports environment, whose parent is the base namespace, whose parent is the global environment, so package code finds its own definitions and its imports before anything a user defines. Namespaces are not on the search path; asNamespace() and ::: reach them.
When loading finishes, loadNamespace() seals the namespace. It locks the namespace environment and its bindings, and the imports environment with them, so nothing can add names to it, and existing bindings are locked until unlockBinding() is called on them. This is what keeps users from accidentally modifying package internals.
6.12.5 Concurrency implications
The apartment model creates a threading hazard around packages.
R-level package state and C-level package state behave differently. A namespace, and everything a package keeps in R objects, lives on the heap of the interpreter that loaded it. A shared library is loaded once per process, because dlopen is process-wide, so its C globals are one copy for every interpreter.
Two interpreters that call into the library at the same time race on those globals, and the state can be corrupted.
A package’s shared library is loaded once per process, and its C globals are shared by every interpreter that calls it. Nothing in R puts a lock around them.
R-level state is the easier case, and ggplot2 shows it. Its current theme lives in an environment inside its namespace (ggplot_global$theme_current), and theme_set() assigns into it. A design in which interpreters shared one namespace would have two workers race on that assignment. With one namespace per interpreter, each worker has its own theme.
# Main interpreter.
library(ggplot2)
# Package is loaded. Its theme lives in ggplot_global, in the namespace.
# Worker 1, in an interpreter that shares the namespace.
theme_set(theme_minimal())
# Assigns into ggplot_global$theme_current.
# Worker 2, at the same time.
theme_set(theme_void())
# Races with worker 1 on the same environment.The alternative: reload per-interpreter
One solution is to load packages independently in each interpreter. Each interpreter has its own copy of the package’s R code and its own namespace. Mutable R-level state is not shared, though the shared library still is.
This is safe for R-level state, and it costs load time and memory in every worker.
The other solution is to document that packages with global state are not thread-safe and leave users to serialize their calls themselves. That is tedious and error-prone.
Marking the shared libraries that are safe to use from several interpreters, and confining unmarked ones to one interpreter, keeps unsafe native code out of workers without reloading anything. threaded-r does this for native libraries (below). Whether enough CRAN packages can carry the mark for workers to be useful is untested.
6.12.6 Namespaces in GNU R
GNU R loads packages once per process. There is one global registry of loaded packages. When library(foo) is called, R checks the registry. If the package is already loaded, it is attached to the search path. If not, it is loaded, registered, and attached.
Packages are rarely unloaded in normal operation. unloadNamespace() exists, but most sessions keep every package until they exit.
Symbol registration happens when the package library is loaded. Native functions are registered once.
GNU R loads each package once per process. All code in the process shares the same package namespace and any process-global state it maintains.
6.12.7 Namespaces in threaded-r
threaded-r keeps GNU R’s package loading code but moves the namespace registry, R_NamespaceRegistry, into each interpreter’s state, so each interpreter loads its own namespaces into its own heap. The shared library is the part it cannot split. dlopen is process-wide, so the table of loaded libraries stays process-global, and a library’s C globals are shared.
To keep those globals safe, a library has to declare itself safe for several interpreters from its own R_init_<pkg>, through R_RegisterThreadedCapability. Libraries that have not done so are confined to one interpreter, the first to load one (in practice the main interpreter), and other interpreters are refused them. loadNamespace() and attachNamespace() also run under one process-wide lock (patch 0101), so two interpreters never load packages at the same moment.
In threaded-r, each interpreter has its own namespace registry. A package’s shared library is loaded once per process, and only libraries that declare themselves capable are shared between interpreters.
One possible future design: packages can register a thread-local storage callback. When an interpreter is created, it calls the package to allocate interpreter-local state. When the interpreter is destroyed, it calls the package to clean up. This is modeled on TLS (thread-local storage) in C.
Packages can register initialization and cleanup callbacks that run per-interpreter. Each interpreter has its own copy of package-global state.
6.12.8 Package loading in r-in-rust
r-in-rust is written from scratch, with no SEXPREC in it, and it does load CRAN packages. Its C API crates present R’s function-accessor headers, so a package’s compiled code links against calls, not against a layout. CRAN mime installs from source and loads. In the census of 2026-08-18, 28 of the 30 most downloaded compiled packages installed and all 28 loaded. The ledger suspects a file-system flake behind the StanHeaders failure and gives no sign of a fault at the C boundary, and rstan needs StanHeaders.
On the R side, rrs has its own implementation of R’s package system: namespaces with an imports environment, a NAMESPACE parser, dependencies and load hooks, local source installs, an RDS reader, and loading of packages that GNU R installed, byte-compiled lazy-load database included (docs/p27/status.md). It reads that database eagerly into the namespace, not as promises. A package’s compiled code is still one shared library per process, with whatever C globals it has, so rrs faces the same native-state question as threaded-r.
6.12.9 The hard part
Namespaces and symbol registration work fine in single-threaded R.
In multithreaded R, several problems emerge.
First, registration happens at load time, and the table of loaded libraries in Rdynload.c is a plain global array. Two interpreters loading packages at once can corrupt it.
Second, compiled package code is shared. Unless that code is thread-safe, calling it from multiple interpreters is unsafe.
Third, package-global C state is shared and unprotected. Modifying it from multiple interpreters causes data races.
Fourth, unloading. unloadNamespace() runs the package’s .onUnload, which typically calls library.dynam.unload(). Even in GNU R this is fragile, since R keeps no count of who else uses a library, and with several interpreters one of them could unload a library another is still running.
6.12.10 Open questions
threaded-r serializes package loading behind one process-wide lock. Is a lock per package enough, so that interpreters loading different packages do not wait for each other?
threaded-r trusts a library’s own declaration that it is safe to share. Can that declaration be checked instead of trusted, for example by scanning a library for writable globals?
Further reading
Writing R Extensions, Section 5.4, “Registering native routines”: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Registering-native-routines
Writing R Extensions, Section 1.5, “Package namespaces”: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Package-namespaces
R Internals, Section 1.2.2, “Namespaces”: https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Namespaces
Where this appears
- threaded-r Each interpreter loads its own namespaces, but a package’s shared library is loaded once per process, so its C globals are shared.
- r-in-rust (rrs) rrs has its own implementation of R’s package system, namespaces included, and loads packages that GNU R installed.