Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(graphql-cache): load GraphQL SDL at runtime (#7724)

Eric Hayes49418e7e719b
diff --git a/Cargo.lock b/Cargo.lock
index 4d2c1f0706..47c6b095ab 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3451,7 +3451,7 @@ dependencies = [
[[package]]
name = "cache-wasm"
-version = "0.6.41"
+version = "0.6.43"
dependencies = [
"async-lock",
"cache-core",
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index e2acf6ae21..f3addb579c 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const invokeMock = vi.hoisted(() => vi.fn());
const listenMock = vi.hoisted(() => vi.fn());
@@ -43,6 +43,10 @@ describe('createTauriCacheHost', () => {
let eventCallbacks: Map<string, EventCallback>;
const unlisten = vi.fn();
+ afterEach(async () => {
+ await vi.dynamicImportSettled();
+ });
+
beforeEach(() => {
vi.clearAllMocks();
eventCallbacks = new Map();
@@ -62,7 +66,7 @@ describe('createTauriCacheHost', () => {
const host = createTauriCacheHost({ scope: 'scope-1' });
await expect(host.currentStorageGeneration()).resolves.toBe(generation);
expect(invokeMock.mock.calls.map(([command]) => command)).toEqual([
- 'graphql_cache_init',
+ 'graphql_cache_init_with_schema',
'graphql_cache_inspect_mutations',
'graphql_cache_current_storage_generation',
]);
@@ -104,9 +108,10 @@ describe('createTauriCacheHost', () => {
});
expect(result).toEqual({ kind: 'miss' });
- expect(invokeMock).toHaveBeenCalledWith('graphql_cache_init', {
+ expect(invokeMock).toHaveBeenCalledWith('graphql_cache_init_with_schema', {
scope: 'scope-1',
hotCapacity: 42,
+ schemaSdl: expect.stringContaining('type GraphqlUser'),
});
expect(invokeMock).toHaveBeenCalledWith('graphql_cache_read', {
opId: `${host.clientId}:7`,
@@ -120,7 +125,7 @@ describe('createTauriCacheHost', () => {
it('reports asynchronous native initialization failures', async () => {
const onInitializationError = vi.fn();
invokeMock.mockImplementation((command: string) =>
- command === 'graphql_cache_init'
+ command === 'graphql_cache_init_with_schema'
? Promise.reject(new Error('init failed'))
: Promise.resolve(null)
);
@@ -169,7 +174,7 @@ describe('createTauriCacheHost', () => {
})
);
expect(invokeMock.mock.calls.map(([command]) => command)).toEqual([
- 'graphql_cache_init',
+ 'graphql_cache_init_with_schema',
'graphql_cache_inspect_mutations',
]);
host.dispose();
@@ -248,7 +253,7 @@ describe('createTauriCacheHost', () => {
optimistic: false,
};
invokeMock.mockImplementation((command: string) =>
- command === 'graphql_cache_init'
+ command === 'graphql_cache_init_with_schema'
? new Promise<void>((resolve) => {
initialize = resolve;
})
@@ -263,7 +268,7 @@ describe('createTauriCacheHost', () => {
mail: { view: 'INBOX', cursor: 'previous-local-cursor' },
};
const pending = host.entityFilter(args);
- await Promise.resolve();
+ await vi.dynamicImportSettled();
expect(invokeMock).toHaveBeenCalledTimes(1);
initialize();
await expect(pending).resolves.toEqual(page);
@@ -391,6 +396,7 @@ describe('createTauriCacheHost', () => {
const assertion = expect(host.entityFilter(filterArgs)).rejects.toThrow(
'graphql cache ipc timeout: graphql_cache_entity_filter'
);
+ await vi.dynamicImportSettled();
await vi.advanceTimersByTimeAsync(60);
await assertion;
invokeMock.mockResolvedValue({ kind: 'unsupported' });
@@ -896,7 +902,7 @@ describe('createTauriCacheHost', () => {
requestTimeoutMs: 50,
});
invokeMock.mockImplementation((command: string) =>
- command === 'graphql_cache_init' ||
+ command === 'graphql_cache_init_with_schema' ||
command === 'graphql_cache_inspect_mutations'
? Promise.resolve(null)
: new Promise(() => {})
@@ -906,6 +912,7 @@ describe('createTauriCacheHost', () => {
const assertion = expect(read).rejects.toThrow(
'graphql cache ipc timeout: graphql_cache_read'
);
+ await vi.dynamicImportSettled();
await vi.advanceTimersByTimeAsync(60);
await assertion;
} finally {
@@ -917,7 +924,7 @@ describe('createTauriCacheHost', () => {
vi.useFakeTimers();
try {
invokeMock.mockImplementation((command: string) =>
- command === 'graphql_cache_init' ||
+ command === 'graphql_cache_init_with_schema' ||
command === 'graphql_cache_inspect_mutations'
? Promise.resolve(null)
: new Promise(() => {})
@@ -945,6 +952,7 @@ describe('createTauriCacheHost', () => {
settled = true;
}
);
+ await vi.dynamicImportSettled();
await vi.advanceTimersByTimeAsync(60);
expect(settled).toBe(false);
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index 78f9d37c7d..9acebd1460 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -243,10 +243,14 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
unlisten?.();
}
- const ready = (async () => {
- await request<void>('graphql_cache_init', {
+ async function initialize(): Promise<void> {
+ const { default: schemaSdl } = await import(
+ '../../../../../../static_assets/schema.graphql?raw'
+ );
+ await request<void>('graphql_cache_init_with_schema', {
scope: options.scope,
hotCapacity: options.hotCapacity,
+ schemaSdl,
});
// Probe before any enqueue/claim. Older binaries silently ignore new
// metadata arguments, so waiting until a draft fails would lose correlation.
@@ -261,7 +265,8 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
}
throw error;
}
- })();
+ }
+ const ready = initialize();
void (async () => {
try {
await ready;
diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
index 62b478828f..80aa836b7e 100644
--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
@@ -240,6 +240,8 @@ export interface CacheWasmModule {
success: boolean
) => void
): void;
+ /** Installs the schema shipped with this frontend before opening storage. */
+ configureCacheSchema(schemaSdl: string): void;
schemaHash(): string;
/** Read-only binary metadata; optional so fixtures can diagnose stale artifacts. */
cacheBuildInfo?(): unknown;
@@ -327,6 +329,10 @@ export function loadCacheWasm(): Promise<CacheWasmModule> {
if (!(exports.memory instanceof WebAssembly.Memory)) {
throw new Error('cache WASM did not export its linear memory');
}
+ const { default: schemaSdl } = await import(
+ '../../../../../../static_assets/schema.graphql?raw'
+ );
+ mod.configureCacheSchema(schemaSdl);
wasmMemory = exports.memory;
mod.setSlowQueryCallback?.((queryFingerprint, durationMs, success) => {
telemetry.record({
diff --git a/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts b/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts
index 68e9ada8d3..8078d54012 100644
--- a/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/shared-mail-backfill.test.ts
@@ -39,7 +39,7 @@ describe('Shared Mail scope refresh', () => {
it('continues Shared hydration when native entity filtering is unavailable', async () => {
invokeMock.mockReset();
invokeMock.mockImplementation(async (command: string) => {
- if (command === 'graphql_cache_init') return null;
+ if (command === 'graphql_cache_init_with_schema') return null;
if (command === 'graphql_cache_inspect_mutations') return [];
if (command === 'graphql_cache_read')
return { kind: 'hit', data: { user: { id: 'viewer' } } };
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index fc62e2ac71..66fa493b95 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -55,33 +55,67 @@ pub async fn graphql_cache_init<R: Runtime>(
scope: String,
hot_capacity: Option<u32>,
) -> Result<(), String> {
- let mut guard = state
- .0
- .lock()
- .map_err(|_| "graphql cache state poisoned".to_string())?;
- if let Some(existing) = guard.as_ref() {
- if existing.scope == scope {
- return Ok(());
- }
- return Err(format!(
- "graphql cache already initialized for scope {}, got {}",
- existing.scope, scope
- ));
- }
+ // A pre-runtime-schema bundle may return after an OTA rollback. Retain
+ // persisted definitions needed by queued work instead of reverting to only
+ // the metadata embedded in the binary.
+ let schema_sdl = cache_core::meta::BUNDLED_SCHEMA_SDL.to_owned();
+ graphql_cache_init_with_schema(app, state, scope, hot_capacity, schema_sdl).await
+}
+
+/// Parses bundle SDL while retaining native cache execution and native Turso storage.
+/// The dedicated command prevents old binaries from silently ignoring the schema payload.
+#[tauri::command]
+pub async fn graphql_cache_init_with_schema<R: Runtime>(
+ app: AppHandle<R>,
+ state: State<'_, CacheState>,
+ scope: String,
+ hot_capacity: Option<u32>,
+ schema_sdl: String,
+) -> Result<(), String> {
+ let incoming = cache_core::meta::Schema::from_sdl(&schema_sdl).map_err(|e| e.to_string())?;
let dir = app
.path()
.app_data_dir()
.map_err(|e| e.to_string())?
.join("graphql-cache");
- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
- let database =
- TursoFileDatabase::new(dir.join("cache.turso")).map_err(|error| error.to_string())?;
- let storage = database
- .open_or_reset(&scope)
- .map_err(|error| error.to_string())?;
- let handle = EngineHandle::new(storage, hot_capacity);
- *guard = Some(InitializedCache { scope, handle });
- Ok(())
+ let schema_path = dir.join("schema.json");
+ let handle = {
+ let mut guard = state
+ .0
+ .lock()
+ .map_err(|_| "graphql cache state poisoned".to_string())?;
+ if let Some(existing) = guard.as_ref() {
+ if existing.scope != scope {
+ return Err("graphql cache scope mismatch".into());
+ }
+ existing.handle.clone()
+ } else {
+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
+ let schema = match std::fs::read_to_string(&schema_path) {
+ Ok(json) => cache_core::meta::Schema::from_json(&json)
+ .and_then(|old| old.merge(&incoming))
+ .map_err(|e| e.to_string())?,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ cache_core::meta::bundled_schema()
+ .merge(&incoming)
+ .map_err(|e| e.to_string())?
+ }
+ Err(error) => return Err(error.to_string()),
+ };
+ // Validate persisted metadata before opening or modifying user storage.
+ crate::engine::persist_schema(&schema_path, &schema)?;
+ let database =
+ TursoFileDatabase::new(dir.join("cache.turso")).map_err(|e| e.to_string())?;
+ let storage = database.open_or_reset(&scope).map_err(|e| e.to_string())?;
+ let handle = EngineHandle::with_schema(storage, hot_capacity, schema);
+ *guard = Some(InitializedCache {
+ scope,
+ handle: handle.clone(),
+ });
+ handle
+ }
+ };
+ handle.install_schema(&incoming, &schema_path).await
}
/// Returns the current in-memory cache revision as a decimal string.
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index dbdcf7d3d6..3e5e83c139 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -430,10 +430,22 @@ impl EngineHandle {
/// Wraps an opened storage backend. A `hot_capacity` of 0 is treated as
/// unset (engine default).
pub fn new(storage: TursoStorage, hot_capacity: Option<u32>) -> Self {
- let engine = match hot_capacity.filter(|c| *c > 0) {
- Some(cap) => Engine::with_capacity(storage, cap as usize),
- None => Engine::new(storage),
- };
+ Self::with_schema(storage, hot_capacity, cache_core::meta::bundled_schema())
+ }
+
+ /// Constructs the native engine with metadata loaded from its frontend bundle.
+ pub fn with_schema(
+ storage: TursoStorage,
+ hot_capacity: Option<u32>,
+ schema: Arc<cache_core::meta::Schema>,
+ ) -> Self {
+ let engine = Engine::with_schema(
+ storage,
+ hot_capacity
+ .filter(|c| *c > 0)
+ .map_or(cache_core::engine::DEFAULT_HOT_CAPACITY, |c| c as usize),
+ schema,
+ );
EngineHandle {
mail_generation: soup_filter_cache_adapter::mail::new_generation(),
inner: Arc::new(Mutex::new(EngineState {
@@ -478,6 +490,25 @@ impl EngineHandle {
.map_err(|error| error.to_string())
}
+ /// Validates and persists compatible metadata before publishing it to native operations.
+ pub async fn install_schema(
+ &self,
+ schema: &cache_core::meta::Schema,
+ path: &std::path::Path,
+ ) -> Result<(), String> {
+ let mut state = self.inner.lock().await;
+ let merged = state
+ .engine
+ .schema()
+ .merge(schema)
+ .map_err(|e| e.to_string())?;
+ persist_schema(path, &merged)?;
+ state
+ .engine
+ .install_schema(&merged)
+ .map_err(|e| e.to_string())
+ }
+
/// Cache read; registers `op_id` as active when given.
pub async fn read(
&self,
@@ -514,9 +545,10 @@ impl EngineHandle {
keys: Vec<String>,
) -> Result<RecordSelectionResultWire, String> {
let mut state = self.inner.lock().await;
+ let schema = state.engine.schema_snapshot();
let selection = state
.selections
- .get(document, fragment_name)
+ .get(&schema, document, fragment_name)
.map_err(|error| error.to_string())?;
let keys: Vec<_> = keys.into_iter().map(|key| EntityKey(key.into())).collect();
state
@@ -987,3 +1019,25 @@ impl EngineHandle {
#[cfg(test)]
mod test;
+
+/// Atomically persists metadata separately from user records; no database reset occurs.
+pub(crate) fn persist_schema(
+ path: &std::path::Path,
+ schema: &cache_core::meta::Schema,
+) -> Result<(), String> {
+ let bytes = serde_json::to_vec(schema.artifact()).map_err(|e| e.to_string())?;
+ let temporary = path.with_extension("json.tmp");
+ use std::io::Write;
+ let mut file = std::fs::File::create(&temporary).map_err(|e| e.to_string())?;
+ file.write_all(&bytes).map_err(|e| e.to_string())?;
+ file.sync_all().map_err(|e| e.to_string())?;
+ drop(file);
+ std::fs::rename(&temporary, path).map_err(|e| e.to_string())?;
+ #[cfg(unix)]
+ if let Some(parent) = path.parent() {
+ std::fs::File::open(parent)
+ .and_then(|dir| dir.sync_all())
+ .map_err(|e| e.to_string())?;
+ }
+ Ok(())
+}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/soup.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/soup.rs
index 0b3c5f4c55..271140bed8 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/soup.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/soup.rs
@@ -192,8 +192,9 @@ pub(super) async fn write_projections(
data: &Value,
identity: Option<&str>,
) -> Result<Vec<ProjectionMutation>, String> {
- let mut projections = authoritative_projection_mutations(query, operation, data)
- .map_err(|error| error.to_string())?;
+ let mut projections =
+ authoritative_projection_mutations(engine.schema(), query, operation, data)
+ .map_err(|error| error.to_string())?;
// Do not compose the new viewer's partial writes with the old viewer's
// authoritative data. Engine still owns the actual atomic identity reset.
let reuse_stored_identity = match identity {
@@ -207,13 +208,21 @@ pub(super) async fn write_projections(
};
if reuse_stored_identity {
projections.extend(
- notification_projection_updates(engine.storage(), query, operation, variables, data)
- .await
- .map_err(|error| error.to_string())?,
+ notification_projection_updates(
+ engine.schema(),
+ engine.storage(),
+ query,
+ operation,
+ variables,
+ data,
+ )
+ .await
+ .map_err(|error| error.to_string())?,
);
}
projections.extend(
mail::projection_updates_for_write(
+ engine.schema(),
engine.storage(),
query,
operation,
@@ -225,6 +234,7 @@ pub(super) async fn write_projections(
.map_err(|error| error.to_string())?,
);
soup_filter_cache_adapter::properties::augment_authoritative(
+ engine.schema(),
engine.storage(),
query,
operation,
@@ -248,23 +258,45 @@ pub(super) async fn optimistic_projections(
let mut projections = optimistic_projection_mutations(data, created_at_ms);
projections.extend(
optimistic_notification_updates(
- notification_projection_updates(engine.storage(), query, operation, variables, data)
- .await
- .map_err(|error| error.to_string())?,
+ notification_projection_updates(
+ engine.schema(),
+ engine.storage(),
+ query,
+ operation,
+ variables,
+ data,
+ )
+ .await
+ .map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())?,
);
projections.extend(mail::optimistic_updates(
- mail::projection_updates(engine.storage(), query, operation, variables, data)
- .await
- .map_err(|error| error.to_string())?,
+ mail::projection_updates(
+ engine.schema(),
+ engine.storage(),
+ query,
+ operation,
+ variables,
+ data,
+ )
+ .await
+ .map_err(|error| error.to_string())?,
));
projections.extend(
- mail::draft_optimistic_updates(engine.storage(), query, operation, variables, data)
- .await
- .map_err(|error| error.to_string())?,
+ mail::draft_optimistic_updates(
+ engine.schema(),
+ engine.storage(),
+ query,
+ operation,
+ variables,
+ data,
+ )
+ .await
+ .map_err(|error| error.to_string())?,
);
soup_filter_cache_adapter::properties::augment_optimistic(
+ engine.schema(),
engine.storage(),
query,
operation,
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
index 7a41cfd960..f58baf2e05 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
@@ -699,3 +699,58 @@ fn bad_transaction_id_is_an_error() {
.unwrap_err();
assert!(error.contains("invalid optimistic transaction id"));
}
+
+#[test]
+fn native_runtime_schema_persists_across_ota_and_rejects_conflicts_without_data_loss() {
+ block_on(async {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("schema.json");
+ let database = cache_turso::TursoFileDatabase::new(dir.path().join("cache.turso")).unwrap();
+ let handle = EngineHandle::new(database.open_or_reset("scope-1").unwrap(), None);
+ let generation = handle.current_storage_generation().await.unwrap();
+ let sdl = format!(
+ "{}\nextend type GraphqlUser {{ runtimeLabel: String }}",
+ cache_core::meta::BUNDLED_SCHEMA_SDL
+ );
+ let schema = cache_core::meta::Schema::from_sdl(&sdl).unwrap();
+ handle.install_schema(&schema, &path).await.unwrap();
+ let query = "query { user { id runtimeLabel } }";
+ let data = serde_json::json!({"user": {"id": "viewer", "runtimeLabel": "OTA"}});
+ handle
+ .write(WriteRequest {
+ origin_op_id: None,
+ registration: None,
+ query: query.into(),
+ operation_name: None,
+ variables: Variables::new(),
+ data: data.clone(),
+ identity: None,
+ })
+ .await
+ .unwrap();
+ // Older windows/bundles may initialize again without downgrading metadata.
+ handle
+ .install_schema(&cache_core::meta::bundled_schema(), &path)
+ .await
+ .unwrap();
+ let persisted = std::fs::read_to_string(&path).unwrap();
+ let conflict = cache_core::meta::Schema::from_sdl(
+ &sdl.replace("runtimeLabel: String", "runtimeLabel: [String]"),
+ )
+ .unwrap();
+ assert!(handle.install_schema(&conflict, &path).await.is_err());
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), persisted);
+ handle.shutdown().unwrap();
+ let schema = cache_core::meta::Schema::from_json(&persisted).unwrap();
+ let reopened =
+ EngineHandle::with_schema(database.open_or_reset("scope-1").unwrap(), None, schema);
+ assert_eq!(
+ reopened.current_storage_generation().await.unwrap(),
+ generation
+ );
+ assert!(
+ matches!(reopened.read(None, query.into(), None, Variables::new(), vec![]).await.unwrap(), ReadResultWire::Hit { data: actual } if actual == data)
+ );
+ reopened.shutdown().unwrap();
+ });
+}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test/mail.graphql b/apps/web/tauri/graphql_cache_plugin/src/engine/test/mail.graphql
index 64e750c41d..2e2ac8356b 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test/mail.graphql
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test/mail.graphql
@@ -16,6 +16,7 @@ query NativeMailBackfill {
inboxVisible
isSignal
latestInboundMessageTs
+ reminderReturnedAt
updatedAt
properties { id }
mailAllPreview { id subject snippet isDraft senderEmail senderName senderPhotoUrl }
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs
index 7bc608658f..71ebc5890c 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test/soup.rs
@@ -40,7 +40,7 @@ fn row(n: u16) -> Value {
"__typename": "GraphqlSoupEmailThread", "id": id(n), "name": format!("Mail {n}"),
"ownerId": VIEWER, "linkId": id(1000), "isRead": n.is_multiple_of(4),
"inboxVisible": n.is_multiple_of(2), "isSignal": n.is_multiple_of(3), "isFavorited": false,
- "cacheProjection": capsule, "latestInboundMessageTs": TIMESTAMP, "updatedAt": TIMESTAMP, "properties": [],
+ "cacheProjection": capsule, "latestInboundMessageTs": TIMESTAMP, "reminderReturnedAt": null, "updatedAt": TIMESTAMP, "properties": [],
"mailAllPreview": preview(n, 1000),
"mailDraftPreview": n.is_multiple_of(3).then(|| preview(n, 2000)),
"mailSentPreview": n.is_multiple_of(4).then(|| preview(n, 3000)),
@@ -62,7 +62,7 @@ fn filters() -> Value {
"calendarEventFilter": {"literal": {"id": nil}},
"channelFilter": {"literal": {"channelId": nil}},
"channelThreadFilter": {"literal": {"channelId": nil}},
- "reminderFilter": {"literal": {"id": nil}},
+ "crmContactFilter": {"literal": {"id": nil}},
"agentSessionFilter": {"literal": {"id": nil}},
"callFilter": {"literal": {"callId": nil}},
"crmCompanyFilter": {"literal": {"id": nil}},
@@ -414,7 +414,7 @@ fn native_mail_confinement_never_admits_nonempty_deferred_partitions() {
let handle = spawn_handle();
hydrate(&handle);
for (partition, id_field) in [
- ("reminderFilter", "id"),
+ ("crmContactFilter", "id"),
("agentSessionFilter", "id"),
("channelThreadFilter", "channelId"),
] {
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index ad5e38c1f8..0bf7a81ecc 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -152,6 +152,12 @@ Xcode app link must still resolve `init_plugin_call_kit` from the Swift package.
Do not remove Android's `cdylib` output or disable undefined-symbol checking
globally to work around an iOS link failure.
+GraphQL schema SDL is loaded from the frontend bundle through
+`graphql_cache_init_with_schema`; the cache engine and Turso remain native.
+Set `MIN_NATIVE_BUILD` to the first native release containing this command before
+shipping the corresponding OTA bundle. See [runtime schema behavior](../../../../crates/client/README.md#runtime-graphql-schema)
+for compatible additions, queued work, and rollback behavior.
+
GraphQL hydration checkpoints require the native
`graphql_cache_current_storage_generation` command. When shipping this frontend
through the bundle updater, set `MIN_NATIVE_BUILD` to the first native build that
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 5cd7a28c4e..d9c20e573f 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -270,6 +270,7 @@ pub fn run() {
#[cfg(target_os = "macos")]
macos_notification_permission::request_macos_notification_permission,
graphql_cache_plugin::commands::graphql_cache_init,
+ graphql_cache_plugin::commands::graphql_cache_init_with_schema,
graphql_cache_plugin::commands::graphql_cache_current_revision,
graphql_cache_plugin::commands::graphql_cache_current_storage_generation,
graphql_cache_plugin::commands::graphql_cache_read,
diff --git a/crates/client/README.md b/crates/client/README.md
index b4a59bdf3c..35149b39bd 100644
--- a/crates/client/README.md
+++ b/crates/client/README.md
@@ -18,6 +18,36 @@ pinned there): `apps/web/tauri/graphql_cache_plugin`, path-depending on
`cargo test -p graphql_cache_plugin` (on NixOS use the `tauri-linux` dev shell —
Tauri's Linux desktop stack needs its WebKitGTK/DBus system libraries).
+## Runtime GraphQL schema
+
+Desktop and mobile keep the cache engine and Turso storage in the native binary.
+The frontend bundle supplies the original `static_assets/schema.graphql` SDL as
+text. Native startup and browser workers pass it to the same Rust
+`Schema::from_sdl` parser, which validates it with `apollo-compiler` and derives
+the cache's internal lookup tables. There is no TypeScript schema generator or
+intermediate JSON asset. Browser workers configure SDL through
+`configureCacheSchema` before opening storage.
+
+Native startup calls `graphql_cache_init_with_schema`. This requires one native
+release; set the OTA bundle's `MIN_NATIVE_BUILD` to the first build containing that
+command. Older native binaries cannot accept runtime SDL. The frontend does
+not fall back to the old initialization command.
+
+An engine owns a validated schema snapshot; there is no mutable global schema.
+Compatible additions are merged under the native engine lock, including when an
+OTA reload leaves the process alive. Validated fragment caches include schema
+identity in their keys. Native `graphql-cache/schema.json` retains the compatible
+superset across restarts and rollbacks, so older windows and pending mutations can
+still reference earlier definitions. Schema installation neither resets records
+nor discards queued mutations or changes the durable storage generation.
+
+Persisted metadata format/compatibility epochs must be supported by the installed engine.
+Conflicting field shapes, root types, or entity identities are rejected before
+publishing metadata or opening storage. These changes need an explicit migration;
+a native rebuild alone does not migrate the persisted metadata. Removed definitions
+are deliberately retained. Schema-driven normalization can accept new types, but
+handwritten search/filter projections and new IPC commands still need native code.
+
## Startup and integrity checks
Normal opens validate schema, scope/version metadata, and pending mutation/optimistic
diff --git a/crates/client/cache-core/Cargo.toml b/crates/client/cache-core/Cargo.toml
index 8acb7101cf..0d19cc3d1e 100644
--- a/crates/client/cache-core/Cargo.toml
+++ b/crates/client/cache-core/Cargo.toml
@@ -5,6 +5,7 @@ publish = false
version = "0.1.0"
[dependencies]
+apollo-compiler = { workspace = true }
apollo-parser = { workspace = true }
chrono = { workspace = true }
lru = { workspace = true }
@@ -19,7 +20,6 @@ thiserror = { workspace = true }
uuid = { workspace = true }
[build-dependencies]
-apollo-compiler = { workspace = true }
sha2 = { workspace = true }
[dev-dependencies]
diff --git a/crates/client/cache-core/build.rs b/crates/client/cache-core/build.rs
index 19860b4c8c..81dbc08f4b 100644
--- a/crates/client/cache-core/build.rs
+++ b/crates/client/cache-core/build.rs
@@ -1,284 +1,11 @@
-//! Build-time schema metadata codegen.
-//!
-//! Parses the in-repo SDL schema and emits `$OUT_DIR/schema_meta.rs`: static
-//! lookup tables consumed by `src/meta.rs`.
-//!
-//! Key policy is the **presence-of-id convention**: an output object type
-//! with an `id: ID!` field is a normalized entity keyed by
-//! `__typename:id`; a type without `id` is embedded inline in its parent
-//! record. The schema itself is the policy — there is no client-side key
-//! config to drift. The build still fails on malformed shapes (e.g. a
-//! nullable or non-ID `id`).
-
-// std::env::var is disallowed workspace-wide to force `macro_env_var` for
-// service config; build scripts read cargo-provided vars (CARGO_MANIFEST_DIR,
-// OUT_DIR), which have nothing to do with app secrets.
-#![allow(clippy::disallowed_methods)]
-
-use apollo_compiler::Schema;
-use apollo_compiler::schema::ExtendedType;
+//! Fingerprint the embedded SDL for build diagnostics only.
use sha2::{Digest, Sha256};
-use std::collections::{BTreeMap, BTreeSet};
-use std::fmt::Write as _;
-use std::path::Path;
-
-const SCHEMA_PATH: &str = "../../../static_assets/schema.graphql";
-
fn main() {
- println!("cargo:rerun-if-changed={SCHEMA_PATH}");
-
- let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
- let schema_path = Path::new(&manifest_dir).join(SCHEMA_PATH);
- let schema_text = std::fs::read_to_string(&schema_path)
- .unwrap_or_else(|e| panic!("cannot read {}: {e}", schema_path.display()));
-
- let schema = Schema::parse_and_validate(&schema_text, "schema.graphql")
- .unwrap_or_else(|e| panic!("schema does not validate: {e:?}"));
-
- let query_root = schema
- .schema_definition
- .query
- .as_ref()
- .expect("schema has no query root")
- .name
- .to_string();
- let mutation_root = schema
- .schema_definition
- .mutation
- .as_ref()
- .map(|m| m.name.to_string());
- let subscription_root = schema
- .schema_definition
- .subscription
- .as_ref()
- .map(|subscription| subscription.name.to_string());
-
- // Expose the schema hash for build diagnostics. Persisted cache
- // compatibility is versioned separately so additive schema changes can
- // retain existing normalized records.
- let mut hasher = Sha256::new();
- hasher.update(schema_text.as_bytes());
- let schema_hash = hex_string(&hasher.finalize());
-
- let mut errors: Vec<String> = Vec::new();
- let mut entries: Vec<(String, String)> = Vec::new(); // (type name, TypeMeta literal)
-
- // Interface implementors (reverse map).
- let mut implementors: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
- for (name, ty) in schema.types.iter() {
- if let ExtendedType::Object(obj) = ty {
- for iface in &obj.implements_interfaces {
- implementors
- .entry(iface.name.to_string())
- .or_default()
- .insert(name.to_string());
- }
- }
- }
-
- for (name, ty) in schema.types.iter() {
- let name = name.to_string();
- if name.starts_with("__") {
- continue; // introspection machinery
- }
- match ty {
- ExtendedType::Object(obj) => {
- let is_operation_root = name == query_root
- || Some(&name) == mutation_root.as_ref()
- || Some(&name) == subscription_root.as_ref();
- let key_literal =
- key_literal(&name, is_operation_root, obj.fields.iter(), &mut errors);
- let fields = fields_literal(&schema, obj.fields.iter(), &mut errors);
- entries.push((
- name.clone(),
- type_meta_literal(&name, "Object", &key_literal, &fields, &[]),
- ));
- }
- ExtendedType::Interface(iface) => {
- let key_literal = key_literal(&name, false, iface.fields.iter(), &mut errors);
- let fields = fields_literal(&schema, iface.fields.iter(), &mut errors);
- let possible: Vec<String> = implementors
- .get(&name)
- .map(|s| s.iter().cloned().collect())
- .unwrap_or_default();
- entries.push((
- name.clone(),
- type_meta_literal(&name, "Interface", &key_literal, &fields, &possible),
- ));
- }
- ExtendedType::Union(u) => {
- let possible: Vec<String> = u.members.iter().map(|m| m.name.to_string()).collect();
- entries.push((
- name.clone(),
- type_meta_literal(&name, "Union", "None", "&[]", &possible),
- ));
- }
- // Scalars, enums and input objects need no TypeMeta: field kinds
- // are resolved at codegen and inputs never appear in responses.
- _ => {}
- }
- }
-
- if !errors.is_empty() {
- panic!(
- "schema shape errors:\n - {}\n(fix the schema — see the presence-of-id convention in this build script's docs)",
- errors.join("\n - ")
- );
- }
-
- entries.sort_by(|a, b| a.0.cmp(&b.0)); // binary-searchable
-
- let mut out = String::new();
- writeln!(out, "// @generated by cache-core/build.rs — do not edit.").unwrap();
- writeln!(out, "pub static QUERY_ROOT_TYPE: &str = {query_root:?};").unwrap();
- match &mutation_root {
- Some(name) => writeln!(
- out,
- "pub static MUTATION_ROOT_TYPE: Option<&str> = Some({name:?});"
- )
- .unwrap(),
- None => writeln!(out, "pub static MUTATION_ROOT_TYPE: Option<&str> = None;").unwrap(),
- }
- match &subscription_root {
- Some(name) => writeln!(
- out,
- "pub static SUBSCRIPTION_ROOT_TYPE: Option<&str> = Some({name:?});"
- )
- .unwrap(),
- None => writeln!(
- out,
- "pub static SUBSCRIPTION_ROOT_TYPE: Option<&str> = None;"
- )
- .unwrap(),
- }
- writeln!(out, "pub static SCHEMA_HASH: &str = {schema_hash:?};").unwrap();
- writeln!(out, "pub static TYPES: &[TypeMeta] = &[").unwrap();
- for (_, literal) in &entries {
- writeln!(out, " {literal},").unwrap();
- }
- writeln!(out, "];").unwrap();
-
- let out_path = Path::new(&std::env::var("OUT_DIR").unwrap()).join("schema_meta.rs");
- std::fs::write(out_path, out).unwrap();
-}
-
-/// Presence-of-id convention: a type with an `id` field is keyed by it; the
-/// field must be a non-null, non-list `ID`. Types without `id` are embedded.
-fn key_literal<'a>(
- name: &str,
- is_operation_root: bool,
- fields: impl Iterator<
- Item = (
- &'a apollo_compiler::Name,
- &'a apollo_compiler::schema::Component<apollo_compiler::ast::FieldDefinition>,
- ),
- >,
- errors: &mut Vec<String>,
-) -> String {
- let id_field = fields.into_iter().find(|(fname, _)| fname.as_str() == "id");
- let Some((_, fdef)) = id_field else {
- return "None".into();
- };
- if is_operation_root {
- errors.push(format!(
- "operation root `{name}` must not expose an `id` field"
- ));
- return "None".into();
- }
- match flatten_type(&fdef.ty) {
- Ok((named, false, false, _)) if named == "ID" => r#"Some(&["id"])"#.into(),
- _ => {
- errors.push(format!(
- "`{name}.id` must be `ID!` (non-null, non-list) to satisfy the presence-of-id convention; rename it if it is not this object's identity"
- ));
- "None".into()
- }
- }
-}
-
-fn type_meta_literal(
- name: &str,
- kind: &str,
- key_literal: &str,
- fields_literal: &str,
- possible: &[String],
-) -> String {
- let possible_list = possible
- .iter()
- .map(|p| format!("{p:?}"))
- .collect::<Vec<_>>()
- .join(", ");
- format!(
- "TypeMeta {{ name: {name:?}, kind: TypeKind::{kind}, key_fields: {key_literal}, fields: {fields_literal}, possible_types: &[{possible_list}] }}"
- )
-}
-
-fn fields_literal<'a>(
- schema: &Schema,
- fields: impl Iterator<
- Item = (
- &'a apollo_compiler::Name,
- &'a apollo_compiler::schema::Component<apollo_compiler::ast::FieldDefinition>,
- ),
- >,
- errors: &mut Vec<String>,
-) -> String {
- let mut parts = Vec::new();
- for (fname, fdef) in fields {
- let (named, nullable, list, item_nullable) = match flatten_type(&fdef.ty) {
- Ok(t) => t,
- Err(e) => {
- errors.push(format!("field `{fname}`: {e}"));
- continue;
- }
- };
- let kind = match schema.types.get(named.as_str()) {
- Some(ExtendedType::Object(_))
- | Some(ExtendedType::Interface(_))
- | Some(ExtendedType::Union(_)) => "Composite",
- Some(ExtendedType::Enum(_)) => "Leaf",
- Some(ExtendedType::Scalar(_)) => {
- if matches!(
- named.as_str(),
- "Int" | "Float" | "String" | "Boolean" | "ID"
- ) {
- "Leaf"
- } else {
- "OpaqueScalar" // e.g. JSON
- }
- }
- Some(ExtendedType::InputObject(_)) | None => {
- errors.push(format!("field `{fname}` has non-output type `{named}`"));
- continue;
- }
- };
- parts.push(format!(
- "FieldMeta {{ name: {:?}, ty: FieldType {{ name: {:?}, kind: FieldKind::{kind}, nullable: {nullable}, list: {list}, item_nullable: {item_nullable} }} }}",
- fname.to_string(),
- named,
- ));
- }
- format!("&[{}]", parts.join(", "))
-}
-
-/// Flattens GraphQL type wrapping to (named, nullable, list, item_nullable).
-/// Nested lists are rejected — extend `FieldType` if the schema ever needs
-/// them.
-fn flatten_type(ty: &apollo_compiler::ast::Type) -> Result<(String, bool, bool, bool), String> {
- use apollo_compiler::ast::Type;
- let (inner, nullable, list) = match ty {
- Type::Named(n) => return Ok((n.to_string(), true, false, false)),
- Type::NonNullNamed(n) => return Ok((n.to_string(), false, false, false)),
- Type::List(inner) => (inner, true, true),
- Type::NonNullList(inner) => (inner, false, true),
- };
- match inner.as_ref() {
- Type::Named(n) => Ok((n.to_string(), nullable, list, true)),
- Type::NonNullNamed(n) => Ok((n.to_string(), nullable, list, false)),
- Type::List(_) | Type::NonNullList(_) => Err("nested lists are not supported".into()),
- }
-}
-
-fn hex_string(bytes: &[u8]) -> String {
- bytes.iter().map(|b| format!("{b:02x}")).collect()
+ let path = "../../../static_assets/schema.graphql";
+ println!("cargo:rerun-if-changed={path}");
+ let sdl = std::fs::read(path).expect("read bundled schema");
+ println!(
+ "cargo:rustc-env=CACHE_BUNDLED_SCHEMA_HASH={:x}",
+ Sha256::digest(sdl)
+ );
}
diff --git a/crates/client/cache-core/src/denormalize.rs b/crates/client/cache-core/src/denormalize.rs
index c1fa5ae178..595ad44e4a 100644
--- a/crates/client/cache-core/src/denormalize.rs
+++ b/crates/client/cache-core/src/denormalize.rs
@@ -68,12 +68,14 @@ pub enum ReadOutcome {
/// Attempts to answer `op` from `source`. `deps` accumulates every entity
/// key touched (for dependency tracking), regardless of outcome.
pub fn denormalize(
+ schema: &crate::meta::Schema,
op: &Operation,
variables: &serde_json::Map<String, Json>,
source: &impl RecordSource,
deps: &mut impl DependencyTracker,
) -> Result<ReadOutcome, DenormalizeError> {
denormalize_with_entity_resolvers(
+ schema,
op,
variables,
source,
@@ -84,6 +86,7 @@ pub fn denormalize(
/// Attempts to answer `op` while applying validated read-only entity links.
pub fn denormalize_with_entity_resolvers(
+ schema: &crate::meta::Schema,
op: &Operation,
variables: &serde_json::Map<String, Json>,
source: &impl RecordSource,
@@ -91,8 +94,9 @@ pub fn denormalize_with_entity_resolvers(
entity_resolvers: &EntityResolverLookup,
) -> Result<ReadOutcome, DenormalizeError> {
denormalize_record_with_entity_resolvers(
+ schema,
&EntityKey::root(),
- meta::QUERY_ROOT_TYPE,
+ schema.query_root(),
&op.selection_set,
variables,
source,
@@ -103,6 +107,7 @@ pub fn denormalize_with_entity_resolvers(
/// Projects one normalized record through a fragment selection.
pub fn denormalize_record(
+ schema: &crate::meta::Schema,
key: &EntityKey<'static>,
type_name: &str,
selections: &[Selection],
@@ -111,6 +116,7 @@ pub fn denormalize_record(
deps: &mut impl DependencyTracker,
) -> Result<ReadOutcome, DenormalizeError> {
denormalize_record_with_entity_resolvers(
+ schema,
key,
type_name,
selections,
@@ -121,7 +127,12 @@ pub fn denormalize_record(
)
}
+#[expect(
+ clippy::too_many_arguments,
+ reason = "explicit schema and read dependencies"
+)]
fn denormalize_record_with_entity_resolvers(
+ schema: &crate::meta::Schema,
key: &EntityKey<'static>,
type_name: &str,
selections: &[Selection],
@@ -130,7 +141,7 @@ fn denormalize_record_with_entity_resolvers(
deps: &mut impl DependencyTracker,
entity_resolvers: &EntityResolverLookup,
) -> Result<ReadOutcome, DenormalizeError> {
- ReadSession::new(key, type_name, selections).resume(
+ ReadSession::new(schema, key, type_name, selections).resume(
variables,
source,
deps,
@@ -143,6 +154,7 @@ fn denormalize_record_with_entity_resolvers(
/// completed fields and list positions survive storage hydration rounds.
/// The source must remain an immutable logical snapshot until completion.
pub(crate) struct ReadSession<'a> {
+ schema: &'a crate::meta::Schema,
data: Json,
pending: Vec<PendingRecord<'a>>,
deleted_items: BTreeSet<Vec<ResponsePath<'a>>>,
@@ -175,11 +187,13 @@ struct PendingRecord<'a> {
impl<'a> ReadSession<'a> {
pub(crate) fn new(
+ schema: &'a crate::meta::Schema,
key: &EntityKey<'static>,
type_name: &'a str,
selections: &'a [Selection],
) -> Self {
Self {
+ schema,
data: Json::Null,
pending: vec![PendingRecord {
key: key.clone(),
@@ -205,6 +219,7 @@ impl<'a> ReadSession<'a> {
for pending in std::mem::take(&mut self.pending) {
let retain_output = pending.destination.is_some();
let mut walk = Walk {
+ schema: self.schema,
variables,
source,
deps,
@@ -269,6 +284,7 @@ impl<'a> ReadSession<'a> {
}
struct Walk<'a, 'document, S: RecordSource, D: DependencyTracker> {
+ schema: &'document crate::meta::Schema,
variables: &'a serde_json::Map<String, Json>,
source: &'a S,
deps: &'a mut D,
@@ -337,9 +353,13 @@ impl<'document, S: RecordSource, D: DependencyTracker> Walk<'_, 'document, S, D>
concrete: &str,
selections: &'document [Selection],
) -> Result<Json, DenormalizeError> {
- let fields_plan =
- self.plans
- .fields(selections, concrete, self.variables, self.entity_resolvers)?;
+ let fields_plan = self.plans.fields(
+ self.schema,
+ selections,
+ concrete,
+ self.variables,
+ self.entity_resolvers,
+ )?;
let pending_start = self.pending.len();
let mut out = serde_json::Map::new();
for planned_field in fields_plan.iter() {
@@ -424,7 +444,7 @@ impl<'document, S: RecordSource, D: DependencyTracker> Walk<'_, 'document, S, D>
&mut self,
owner: &EntityKey<'static>,
field: &'document FieldNode,
- ty: &meta::FieldType,
+ ty: &meta::FieldType<'document>,
value: &CacheValue,
) -> Result<Json, DenormalizeError> {
Ok(match value {
@@ -472,6 +492,7 @@ impl<'document, S: RecordSource, D: DependencyTracker> Walk<'_, 'document, S, D>
}
fn collect_fields<'a>(
+ schema: &crate::meta::Schema,
selections: &'a [Selection],
concrete_type: &str,
out: &mut Vec<&'a FieldNode>,
@@ -485,10 +506,10 @@ fn collect_fields<'a>(
} => {
let applies = match type_condition {
None => true,
- Some(cond) => meta::type_matches(concrete_type, cond),
+ Some(cond) => schema.type_matches(concrete_type, cond),
};
if applies {
- collect_fields(selection_set, concrete_type, out);
+ collect_fields(schema, selection_set, concrete_type, out);
}
}
}
diff --git a/crates/client/cache-core/src/denormalize/plan.rs b/crates/client/cache-core/src/denormalize/plan.rs
index eee4e1d9df..670d09787b 100644
--- a/crates/client/cache-core/src/denormalize/plan.rs
+++ b/crates/client/cache-core/src/denormalize/plan.rs
@@ -16,11 +16,11 @@ pub(super) enum FieldSource<'a> {
Missing(Cow<'a, str>),
Stored {
key: Cow<'a, str>,
- ty: meta::FieldType,
+ ty: meta::FieldType<'a>,
},
Entity {
key: EntityKey<'static>,
- ty: meta::FieldType,
+ ty: meta::FieldType<'a>,
storage_key: Cow<'a, str>,
},
}
@@ -39,6 +39,7 @@ pub(crate) struct ReadPlans<'a> {
impl<'a> ReadPlans<'a> {
pub(super) fn fields(
&mut self,
+ schema: &'a crate::meta::Schema,
selections: &'a [Selection],
concrete: &str,
variables: &serde_json::Map<String, Json>,
@@ -52,10 +53,10 @@ impl<'a> ReadPlans<'a> {
return Ok(Arc::clone(fields));
}
let mut nodes = Vec::new();
- collect_fields(selections, concrete, &mut nodes);
+ collect_fields(schema, selections, concrete, &mut nodes);
let fields = nodes
.into_iter()
- .map(|node| compile_field(node, concrete, variables, entity_resolvers))
+ .map(|node| compile_field(schema, node, concrete, variables, entity_resolvers))
.collect::<Result<Arc<[_]>, _>>()?;
types.insert(concrete.to_owned(), Arc::clone(&fields));
Ok(fields)
@@ -63,6 +64,7 @@ impl<'a> ReadPlans<'a> {
}
fn compile_field<'a>(
+ schema: &'a crate::meta::Schema,
node: &'a FieldNode,
concrete: &str,
variables: &serde_json::Map<String, Json>,
@@ -75,10 +77,12 @@ fn compile_field<'a>(
});
}
let metadata =
- meta::field_meta(concrete, &node.name).ok_or_else(|| DenormalizeError::UnknownField {
- type_name: concrete.to_owned(),
- field: node.name.clone(),
- })?;
+ schema
+ .field_meta(concrete, &node.name)
+ .ok_or_else(|| DenormalizeError::UnknownField {
+ type_name: concrete.to_owned(),
+ field: node.name.clone(),
+ })?;
let resolver = entity_resolvers.get(concrete, &node.name);
let arguments = match resolve_args(node, variables) {
Ok(arguments) => arguments,
@@ -91,7 +95,7 @@ fn compile_field<'a>(
Err(error) => return Err(error.into()),
};
let storage_key = match resolved_args_key(node, &arguments) {
- Some(args) => Cow::Owned(field_key(&node.name, Some(&args))),
+ Some(args) => Cow::Owned(field_key(node.name.as_str(), Some(&args))),
None => Cow::Borrowed(node.name.as_str()),
};
let source = match resolver {
@@ -100,9 +104,11 @@ fn compile_field<'a>(
key,
storage_key,
ty: meta::FieldType {
- name: meta::type_meta(&resolver.target_type)
+ name: schema
+ .type_meta(&resolver.target_type)
.expect("compiled resolver target exists")
- .name,
+ .name
+ .as_str(),
..metadata.ty
},
},
diff --git a/crates/client/cache-core/src/denormalize/test.rs b/crates/client/cache-core/src/denormalize/test.rs
index 9eb3add60e..bb82b69ca5 100644
--- a/crates/client/cache-core/src/denormalize/test.rs
+++ b/crates/client/cache-core/src/denormalize/test.rs
@@ -58,12 +58,13 @@ fn thread() -> (EntityKey<'static>, Record) {
#[test]
fn resumes_only_missing_branches_preserving_aliases_nulls_order_and_dependencies() {
- let selection = RecordSelection::parse(
+ let selection = RecordSelection::parse(crate::meta::bundled_schema_ref(),
"fragment Thread on GraphqlSoupEmailThread { id first: messages { id subject } second: messages { id } }",
"Thread",
).unwrap();
let (thread_key, thread) = thread();
let mut session = ReadSession::new(
+ crate::meta::bundled_schema_ref(),
&thread_key,
"GraphqlSoupEmailThread",
selection.selection_set(),
@@ -111,12 +112,13 @@ fn resumes_only_missing_branches_preserving_aliases_nulls_order_and_dependencies
#[test]
fn overwritten_duplicate_selection_cannot_patch_later_output() {
- let selection = RecordSelection::parse(
+ let selection = RecordSelection::parse(crate::meta::bundled_schema_ref(),
"fragment Thread on GraphqlSoupEmailThread { messages { id subject } ... on GraphqlSoupEmailThread { messages { id } } }",
"Thread",
).unwrap();
let (thread_key, thread) = thread();
let mut session = ReadSession::new(
+ crate::meta::bundled_schema_ref(),
&thread_key,
"GraphqlSoupEmailThread",
selection.selection_set(),
@@ -142,6 +144,7 @@ fn overwritten_duplicate_selection_cannot_patch_later_output() {
panic!("all selected records are present");
};
let ReadOutcome::Complete(expected) = denormalize_record(
+ crate::meta::bundled_schema_ref(),
&thread_key,
"GraphqlSoupEmailThread",
selection.selection_set(),
@@ -160,6 +163,7 @@ fn overwritten_duplicate_selection_cannot_patch_later_output() {
#[test]
fn a_field_miss_survives_later_record_hydration() {
let selection = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
"fragment Thread on GraphqlSoupEmailThread { id messages { id subject } }",
"Thread",
)
@@ -169,6 +173,7 @@ fn a_field_miss_survives_later_record_hydration() {
let mut source = CountingSource::default();
source.records.insert(thread_key.clone(), thread);
let mut session = ReadSession::new(
+ crate::meta::bundled_schema_ref(),
&thread_key,
"GraphqlSoupEmailThread",
selection.selection_set(),
@@ -208,7 +213,12 @@ fn resumed_reads_retain_argument_qualified_viewer_fields() {
fields: [("user".into(), CacheValue::Ref(viewer.clone()))].into(),
},
);
- let mut session = ReadSession::new(&root, meta::QUERY_ROOT_TYPE, &operation.selection_set);
+ let mut session = ReadSession::new(
+ crate::meta::bundled_schema_ref(),
+ &root,
+ meta::bundled_schema_ref().query_root(),
+ &operation.selection_set,
+ );
let mut deps = QueryDependencies::default();
let mut plans = ReadPlans::default();
let variables = serde_json::Map::new();
@@ -293,6 +303,7 @@ fn fixture() -> (
) {
let doc = Document::parse(QUERY).unwrap();
let records = normalize(
+ crate::meta::bundled_schema_ref(),
doc.operation(None).unwrap(),
&Default::default(),
&json!({"user": {
@@ -327,6 +338,7 @@ fn deleted_links_are_absent_without_hiding_the_page_including_through_aliases()
.insert(DELETED_FIELD.into(), CacheValue::Bool(true));
let mut deps = BTreeSet::new();
let outcome = denormalize(
+ crate::meta::bundled_schema_ref(),
doc.operation(None).unwrap(),
&Default::default(),
&records,
@@ -346,14 +358,18 @@ fn deleted_links_are_absent_without_hiding_the_page_including_through_aliases()
assert!(deps.contains(&local));
assert!(deps.contains(&target));
- let resolvers = EntityResolverLookup::compile(&[EntityResolver {
- parent_type: "GraphqlUser".into(),
- field_name: "emailThread".into(),
- target_type: "GraphqlSoupEmailThread".into(),
- argument_path: vec!["input".into(), "threadId".into()],
- }])
+ let resolvers = EntityResolverLookup::compile(
+ crate::meta::bundled_schema_ref(),
+ &[EntityResolver {
+ parent_type: "GraphqlUser".into(),
+ field_name: "emailThread".into(),
+ target_type: "GraphqlSoupEmailThread".into(),
+ argument_path: vec!["input".into(), "threadId".into()],
+ }],
+ )
.unwrap();
let resolved = denormalize_with_entity_resolvers(
+ crate::meta::bundled_schema_ref(),
doc.operation(None).unwrap(),
&Default::default(),
&records,
@@ -365,10 +381,12 @@ fn deleted_links_are_absent_without_hiding_the_page_including_through_aliases()
// Explicit record reads still report the deleted entity as unavailable.
let fragment = Document::parse("query { id }").unwrap();
- assert!(matches!(denormalize_record(
+ assert!(
+ matches!(denormalize_record(crate::meta::bundled_schema_ref(),
&local, "GraphqlSoupEmailThread", &fragment.operation(None).unwrap().selection_set,
&Default::default(), &records, &mut BTreeSet::new(),
- ).unwrap(), ReadOutcome::Miss { field, .. } if field == "deleted cache identity"));
+ ).unwrap(), ReadOutcome::Miss { field, .. } if field == "deleted cache identity")
+ );
}
}
@@ -379,6 +397,7 @@ fn unknown_records_and_alias_cycles_still_make_the_read_incomplete() {
let target = EntityKey::entity("GraphqlSoupEmailThread", &["server"]);
records.insert(local.clone(), alias_record(&target));
let outcome = denormalize(
+ crate::meta::bundled_schema_ref(),
doc.operation(None).unwrap(),
&Default::default(),
&records,
@@ -388,6 +407,7 @@ fn unknown_records_and_alias_cycles_still_make_the_read_incomplete() {
assert!(matches!(outcome, ReadOutcome::NeedRecords(keys) if keys.contains(&target)));
records.insert(target, alias_record(&local));
let outcome = denormalize(
+ crate::meta::bundled_schema_ref(),
doc.operation(None).unwrap(),
&Default::default(),
&records,
@@ -406,6 +426,7 @@ fn required_singular_links_cannot_return_null_for_a_deleted_record() {
.fields
.insert(DELETED_FIELD.into(), CacheValue::Bool(true));
let outcome = denormalize(
+ crate::meta::bundled_schema_ref(),
doc.operation(None).unwrap(),
&Default::default(),
&records,
@@ -421,6 +442,7 @@ fn required_singular_links_cannot_return_null_for_a_deleted_record() {
fn resumed_aliases_and_tombstones_preserve_list_positions_and_completed_work() {
for deleted_id in ["hot", "server"] {
let selection = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
"fragment Thread on GraphqlSoupEmailThread { messages { id subject } }",
"Thread",
)
@@ -438,6 +460,7 @@ fn resumed_aliases_and_tombstones_preserve_list_positions_and_completed_work() {
.insert(DELETED_FIELD.into(), CacheValue::Bool(true));
}
let mut session = ReadSession::new(
+ crate::meta::bundled_schema_ref(),
&thread_key,
"GraphqlSoupEmailThread",
selection.selection_set(),
@@ -491,11 +514,13 @@ fn resumed_aliases_and_tombstones_preserve_list_positions_and_completed_work() {
#[test]
fn alias_cycle_detection_survives_storage_hydration() {
let selection = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
"fragment Message on GraphqlSoupEmailMessage { id }",
"Message",
)
.unwrap();
let mut session = ReadSession::new(
+ crate::meta::bundled_schema_ref(),
&key("local"),
"GraphqlSoupEmailMessage",
selection.selection_set(),
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index ad1825cdbe..821644178b 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -349,6 +349,7 @@ const MAX_UNCERTAIN_CALENDAR_EVENTS: usize = 256;
const DOCUMENT_CACHE_CAPACITY: usize = 128;
pub struct Engine<S: Storage> {
+ schema: std::sync::Arc<crate::meta::Schema>,
storage: S,
revision: CacheRevision,
hot: LruCache<EntityKey<'static>, Record>,
@@ -369,7 +370,17 @@ impl<S: Storage> Engine<S> {
}
pub fn with_capacity(storage: S, hot_capacity: usize) -> Self {
+ Self::with_schema(storage, hot_capacity, crate::meta::bundled_schema())
+ }
+
+ /// Creates an engine with immutable metadata supplied by its host.
+ pub fn with_schema(
+ storage: S,
+ hot_capacity: usize,
+ schema: std::sync::Arc<crate::meta::Schema>,
+ ) -> Self {
Engine {
+ schema,
storage,
revision: CacheRevision::ZERO,
hot: LruCache::new(NonZeroUsize::new(hot_capacity).expect("capacity > 0")),
@@ -387,6 +398,25 @@ impl<S: Storage> Engine<S> {
self.revision
}
+ /// Installs a compatible superset without discarding records or queued mutations.
+ pub fn install_schema(
+ &mut self,
+ schema: &crate::meta::Schema,
+ ) -> Result<(), crate::meta::SchemaError> {
+ self.schema = self.schema.merge(schema)?;
+ Ok(())
+ }
+
+ /// Shared immutable snapshot for host plan validation.
+ pub fn schema_snapshot(&self) -> std::sync::Arc<crate::meta::Schema> {
+ std::sync::Arc::clone(&self.schema)
+ }
+
+ /// Metadata used for every operation in this engine instance.
+ pub fn schema(&self) -> &crate::meta::Schema {
+ &self.schema
+ }
+
/// Returns the durable identity of the currently stored cache data.
///
/// A fresh generation is installed when the marker is absent or malformed.
@@ -555,17 +585,18 @@ impl<S: Storage> Engine<S> {
let operation =
document.operation(queued.mutation.request.operation_name.as_deref())?;
let mut updates = identity::remap_updates(
- normalize(operation, &variables, &source.mutation_data)?,
+ normalize(&self.schema, operation, &variables, &source.mutation_data)?,
&source.identity_bindings,
&identities,
);
identity::apply_record_lifecycle(&mut updates, &source.identity_bindings, &identities);
- let patches = deduplicate_patches(&source.link_patches).map_err(|error| {
- EngineError::InvalidQueuedMutation {
- id: queued.id,
- detail: error.to_string(),
- }
- })?;
+ let patches =
+ deduplicate_patches(&self.schema, &source.link_patches).map_err(|error| {
+ EngineError::InvalidQueuedMutation {
+ id: queued.id,
+ detail: error.to_string(),
+ }
+ })?;
let candidates: BTreeSet<EntityKey<'static>> = updates.keys().cloned().collect();
let (candidates, bases) = self
.load_link_patch_bases(candidates, &layers, &updates, &patches)
@@ -577,6 +608,7 @@ impl<S: Storage> Engine<S> {
// recreated from stale recipes during hydration. A newly submitted
// tail remains strict so invalid caller patches cannot be persisted.
apply_link_patches(
+ &self.schema,
&mut effective,
&mut updates,
&patches,
@@ -740,7 +772,7 @@ impl<S: Storage> Engine<S> {
variables: &serde_json::Map<String, Json>,
entity_resolvers: &[EntityResolver],
) -> Result<ReadResult, EngineError<S::Error>> {
- let entity_resolvers = EntityResolverLookup::compile(entity_resolvers)?;
+ let entity_resolvers = EntityResolverLookup::compile(&self.schema, entity_resolvers)?;
self.hydrate_optimistic().await?;
let doc = Self::document(&mut self.docs, query)?;
let op = doc.operation(operation_name)?;
@@ -775,8 +807,9 @@ impl<S: Storage> Engine<S> {
let mut plans = ReadPlans::default();
let mut session = ReadSession::new(
+ &self.schema,
&EntityKey::root(),
- crate::meta::QUERY_ROOT_TYPE,
+ self.schema.query_root(),
&op.selection_set,
);
let outcome = loop {
@@ -983,6 +1016,7 @@ impl<S: Storage> Engine<S> {
(
key.clone(),
ReadSession::new(
+ &self.schema,
key,
key.typename().unwrap_or_default(),
selection.selection_set(),
@@ -1268,6 +1302,7 @@ impl<S: Storage> Engine<S> {
} = input;
self.hydrate_optimistic().await?;
let entity_resolvers = EntityResolverLookup::compile(
+ &self.schema,
registration.map_or(&[][..], |registration| registration.entity_resolvers),
)?;
let doc = Self::document(&mut self.docs, query)?;
@@ -1281,7 +1316,8 @@ impl<S: Storage> Engine<S> {
));
}
let is_query = op.kind == OperationKind::Query;
- let normalized = normalize_with_dependencies(op, variables, data, &entity_resolvers)?;
+ let normalized =
+ normalize_with_dependencies(&self.schema, op, variables, data, &entity_resolvers)?;
let mut updates = normalized.updates;
if !retain_pages {
crate::page_retention::omit_hydration_pages(&mut updates);
@@ -1450,7 +1486,7 @@ impl<S: Storage> Engine<S> {
)),
));
}
- project_hydration_response(op, data)?
+ project_hydration_response(&self.schema, op, data)?
};
let (write_result, search_changed_buckets) = self
.write_network(
@@ -1695,7 +1731,7 @@ impl<S: Storage> Engine<S> {
Some((removed_id, false)) => MutationUpsertKind::ReplacedPending { removed_id },
};
- let patches = deduplicate_patches(link_patches)?;
+ let patches = deduplicate_patches(&self.schema, link_patches)?;
let revalidations = deduplicate_revalidations(
revalidations
.iter()
@@ -2328,7 +2364,7 @@ impl<S: Storage> Engine<S> {
};
let doc = Self::document(&mut self.docs, query)?;
let op = doc.operation(operation_name)?;
- let mut updates = match normalize(op, variables, data) {
+ let mut updates = match normalize(&self.schema, op, variables, data) {
Ok(updates) => updates,
Err(error) if identity_errors.is_empty() => return Err(error.into()),
Err(error) => {
@@ -2401,7 +2437,7 @@ impl<S: Storage> Engine<S> {
// and recovered by the returned revalidations.
let mut effective = bases.clone();
merge_updates_into_effective(&mut effective, &updates);
- apply_link_patches(&mut effective, &mut updates, &recipes, true)?;
+ apply_link_patches(&self.schema, &mut effective, &mut updates, &recipes, true)?;
let (durable_changed, entries) = stage_updates(&bases, updates);
let reconciliation = self
.stage_shadow_reconciliation(transaction, &projections, &identities)
@@ -2581,7 +2617,7 @@ impl<S: Storage> Engine<S> {
// loop from retrying it.
let missing: BTreeSet<_> = patches
.iter()
- .flat_map(|patch| missing_patch_records(&effective, patch))
+ .flat_map(|patch| missing_patch_records(&self.schema, &effective, patch))
.chain(patches.iter().filter_map(|patch| {
let inserted = patch.operation.inserted_entity_key()?;
(!effective.contains_key(inserted)).then(|| inserted.clone())
@@ -2638,14 +2674,14 @@ impl<S: Storage> Engine<S> {
let operation = Self::document(&mut self.docs, &inspection.query)?
.operation(inspection.operation_name.as_deref())?
.clone();
- let prepared = prepare(&operation, &inspection.path)?;
+ let prepared = prepare(&self.schema, &operation, &inspection.path)?;
let mut candidates = BTreeSet::from([EntityKey::root()]);
let variants = loop {
let bases = self.load_bases(&candidates).await?;
let effective =
present_records(effective_records(&bases, &self.optimistic, &candidates));
- match resolve_owner(&effective, &operation, &inspection.path)? {
+ match resolve_owner(&self.schema, &effective, &operation, &inspection.path)? {
OwnerResolution::Owner(owner) => break recover_variants(&owner, &prepared)?,
OwnerResolution::Absent => return Ok(Vec::new()),
OwnerResolution::NeedRecord(key) if !candidates.contains(&key) => {
diff --git a/crates/client/cache-core/src/engine/test.rs b/crates/client/cache-core/src/engine/test.rs
index 6118de4dfa..c15bb30b6b 100644
--- a/crates/client/cache-core/src/engine/test.rs
+++ b/crates/client/cache-core/src/engine/test.rs
@@ -283,7 +283,7 @@ fn fragment_reads_keep_hot_and_cold_linked_records_in_the_working_set() {
Record::default(),
);
}
- let selection = RecordSelection::parse(
+ let selection = RecordSelection::parse(crate::meta::bundled_schema_ref(),
"fragment Thread on GraphqlSoupEmailThread { id messages(offset: 0, limit: 1) { id subject } }",
"Thread",
).unwrap();
diff --git a/crates/client/cache-core/src/engine/test/hydration_search_changes.rs b/crates/client/cache-core/src/engine/test/hydration_search_changes.rs
index af74a3fe06..3ac5728d64 100644
--- a/crates/client/cache-core/src/engine/test/hydration_search_changes.rs
+++ b/crates/client/cache-core/src/engine/test/hydration_search_changes.rs
@@ -48,9 +48,12 @@ fn nested_task_completion_hydration_invalidates_task_searches() {
panic!("task subtype must stay embedded in its document");
};
assert_eq!(subtype["isCompleted"], CacheValue::Bool(false));
- let selection =
- RecordSelection::parse(include_str!("task_completion.graphql"), "TaskCompletion")
- .unwrap();
+ let selection = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
+ include_str!("task_completion.graphql"),
+ "TaskCompletion",
+ )
+ .unwrap();
if cold {
engine = Engine::new(engine.into_storage());
}
diff --git a/crates/client/cache-core/src/entity_resolver.rs b/crates/client/cache-core/src/entity_resolver.rs
index 528b9a39fd..5a55bcbd44 100644
--- a/crates/client/cache-core/src/entity_resolver.rs
+++ b/crates/client/cache-core/src/entity_resolver.rs
@@ -6,7 +6,7 @@
//! currently generated in Rust; a nonexistent or non-scalar runtime path is
//! therefore handled safely as a cache miss by denormalization.
-use crate::meta::{self, FieldKind, TypeKind};
+use crate::meta::{FieldKind, TypeKind};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use thiserror::Error;
@@ -75,22 +75,25 @@ pub struct EntityResolverLookup {
impl EntityResolverLookup {
/// Validates descriptors against generated output schema metadata.
- pub fn compile(resolvers: &[EntityResolver]) -> Result<Self, EntityResolverError> {
+ pub fn compile(
+ schema: &crate::meta::Schema,
+ resolvers: &[EntityResolver],
+ ) -> Result<Self, EntityResolverError> {
let mut by_parent = BTreeMap::<String, BTreeMap<String, EntityResolver>>::new();
for resolver in resolvers {
- let parent = meta::type_meta(&resolver.parent_type)
+ let parent = schema
+ .type_meta(&resolver.parent_type)
.ok_or_else(|| EntityResolverError::UnknownParent(resolver.parent_type.clone()))?;
if parent.kind != TypeKind::Object {
return Err(EntityResolverError::ParentNotObject(
resolver.parent_type.clone(),
));
}
- let field =
- meta::field_meta(&resolver.parent_type, &resolver.field_name).ok_or_else(|| {
- EntityResolverError::UnknownField {
- parent: resolver.parent_type.clone(),
- field: resolver.field_name.clone(),
- }
+ let field = schema
+ .field_meta(&resolver.parent_type, &resolver.field_name)
+ .ok_or_else(|| EntityResolverError::UnknownField {
+ parent: resolver.parent_type.clone(),
+ field: resolver.field_name.clone(),
})?;
if field.ty.kind != FieldKind::Composite || field.ty.list {
return Err(EntityResolverError::NotSingularComposite {
@@ -99,20 +102,22 @@ impl EntityResolverLookup {
});
}
- let target = meta::type_meta(&resolver.target_type)
+ let target = schema
+ .type_meta(&resolver.target_type)
.ok_or_else(|| EntityResolverError::UnknownTarget(resolver.target_type.clone()))?;
if target.kind != TypeKind::Object {
return Err(EntityResolverError::TargetNotObject(
resolver.target_type.clone(),
));
}
- if target.key_fields != Some(&["id"][..]) {
+ if target.key_fields.as_deref() != Some(&["id".to_owned()][..]) {
return Err(EntityResolverError::TargetNotKeyable(
resolver.target_type.clone(),
));
}
- let declared = meta::type_meta(field.ty.name)
+ let declared = schema
+ .type_meta(field.ty.name)
.expect("generated composite field type has generated metadata");
let compatible = match declared.kind {
TypeKind::Object => declared.name == target.name,
diff --git a/crates/client/cache-core/src/link_patch.rs b/crates/client/cache-core/src/link_patch.rs
index f9cba2b71a..05bdf5640d 100644
--- a/crates/client/cache-core/src/link_patch.rs
+++ b/crates/client/cache-core/src/link_patch.rs
@@ -4,7 +4,6 @@
//! with durable optimistic mutations and replayed after a restart.
use crate::document::{Document, FieldNode, OperationKind, Selection};
-use crate::meta;
use crate::normalize::RecordUpdates;
use crate::query_path::{
selected_field as find_selected_field, selected_storage_key as resolve_selected_storage_key,
@@ -272,6 +271,7 @@ pub enum LinkPatchError {
/// Removes exact duplicate recipes while retaining the first occurrence and
/// preserving caller order for conflicting operations.
pub fn deduplicate_patches(
+ schema: &crate::meta::Schema,
patches: &[OptimisticLinkPatch],
) -> Result<Vec<OptimisticLinkPatch>, LinkPatchError> {
if patches.len() > MAX_PATCHES {
@@ -283,7 +283,7 @@ pub fn deduplicate_patches(
let mut seen = BTreeSet::new();
let mut out = Vec::with_capacity(patches.len());
for patch in patches {
- validate_recipe(patch)?;
+ validate_recipe(schema, patch)?;
let encoded = serde_json::to_value(patch).expect("link patch serializes");
if seen.insert(canonical_json(&encoded)) {
out.push(patch.clone());
@@ -292,11 +292,14 @@ pub fn deduplicate_patches(
Ok(out)
}
-fn validate_recipe(patch: &OptimisticLinkPatch) -> Result<(), LinkPatchError> {
+fn validate_recipe(
+ schema: &crate::meta::Schema,
+ patch: &OptimisticLinkPatch,
+) -> Result<(), LinkPatchError> {
if patch.path.is_empty() || patch.path.len() > MAX_PATH_DEPTH {
return Err(LinkPatchError::InvalidDepth(patch.path.len()));
}
- validate_entrypoint(patch)?;
+ validate_entrypoint(schema, patch)?;
validate_entity_key(patch.operation.entity_key())?;
for segment in &patch.path {
if let LinkPathSegment::ListItem { list_item } = segment
@@ -375,10 +378,11 @@ fn validate_embedded_link_fields(
}
fn validate_entrypoint(
+ schema: &crate::meta::Schema,
patch: &OptimisticLinkPatch,
) -> Result<serde_json::Map<String, Json>, LinkPatchError> {
if let Some(root) = &patch.record_root {
- root.validate(patch)?;
+ root.validate(schema, patch)?;
return Ok(serde_json::Map::new());
}
let document = Document::parse(&patch.query)
@@ -429,18 +433,25 @@ fn is_json_scalar(value: &Json) -> bool {
/// mode is used during hydration and successful settlement, where stale query
/// fields must never be recreated.
pub fn apply_link_patches(
+ schema: &crate::meta::Schema,
effective: &mut HashMap<EntityKey<'static>, Record>,
updates: &mut RecordUpdates,
patches: &[OptimisticLinkPatch],
skip_not_applicable: bool,
) -> Result<(), LinkPatchError> {
- let patches = deduplicate_patches(patches)?;
+ let patches = deduplicate_patches(schema, patches)?;
// Work on clones so strict validation is all-or-nothing.
let mut staged_effective = effective.clone();
let mut staged_updates = updates.clone();
for patch in &patches {
- if let Err(error) = apply_one(&mut staged_effective, &mut staged_updates, updates, patch) {
+ if let Err(error) = apply_one(
+ schema,
+ &mut staged_effective,
+ &mut staged_updates,
+ updates,
+ patch,
+ ) {
if skip_not_applicable {
continue;
}
@@ -453,12 +464,13 @@ pub fn apply_link_patches(
}
fn apply_one(
+ schema: &crate::meta::Schema,
effective: &mut HashMap<EntityKey<'static>, Record>,
updates: &mut RecordUpdates,
response_updates: &RecordUpdates,
patch: &OptimisticLinkPatch,
) -> Result<(), LinkPatchError> {
- let resolved = resolve_target(effective, patch)?;
+ let resolved = resolve_target(schema, effective, patch)?;
let upsert = upsert::resolve(&patch.operation, &resolved, response_updates)?;
if let Some(inserted) = upsert
.as_ref()
@@ -746,10 +758,11 @@ struct ResolvedEmbeddedLink {
/// update. Engines use this to hydrate graph links from cold storage before
/// applying the update.
pub fn missing_patch_records(
+ schema: &crate::meta::Schema,
effective: &HashMap<EntityKey<'static>, Record>,
patch: &OptimisticLinkPatch,
) -> Vec<EntityKey<'static>> {
- match resolve_target(effective, patch) {
+ match resolve_target(schema, effective, patch) {
Err(LinkPatchError::MissingParent(key)) => vec![key],
Ok(target) if target.match_field.is_some() => upsert::missing_records(effective, &target),
_ => Vec::new(),
@@ -757,12 +770,13 @@ pub fn missing_patch_records(
}
fn resolve_target(
+ schema: &crate::meta::Schema,
effective: &HashMap<EntityKey<'static>, Record>,
patch: &OptimisticLinkPatch,
) -> Result<ResolvedTarget, LinkPatchError> {
- let variables = validate_entrypoint(patch)?;
+ let variables = validate_entrypoint(schema, patch)?;
if let Some(root) = &patch.record_root {
- return root.resolve(effective, patch);
+ return root.resolve(schema, effective, patch);
}
let document = Document::parse(&patch.query)
.map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))?;
@@ -770,9 +784,10 @@ fn resolve_target(
.operation(patch.operation_name.as_deref())
.map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))?;
resolve_from_record(
+ schema,
effective,
&EntityKey::root(),
- meta::QUERY_ROOT_TYPE,
+ schema.query_root(),
&operation.selection_set,
&variables,
&patch.path,
@@ -780,7 +795,12 @@ fn resolve_target(
)
}
+#[expect(
+ clippy::too_many_arguments,
+ reason = "recursive traversal carries schema and selection context"
+)]
fn resolve_from_record(
+ schema: &crate::meta::Schema,
effective: &HashMap<EntityKey<'static>, Record>,
owner: &EntityKey<'static>,
type_name: &str,
@@ -799,7 +819,7 @@ fn resolve_from_record(
.get(owner)
.ok_or_else(|| LinkPatchError::MissingParent(owner.clone()))?;
let concrete = record.typename().unwrap_or(type_name);
- let selected = selected_field(selections, concrete, response_key)?;
+ let selected = selected_field(schema, selections, concrete, response_key)?;
let storage_key = selected_storage_key(selected, variables)?;
let value = record
.fields
@@ -808,8 +828,9 @@ fn resolve_from_record(
parent: owner.0.to_string(),
field: storage_key.clone(),
})?;
- let named_type = selected_type(concrete, selected)?;
+ let named_type = selected_type(schema, concrete, selected)?;
resolve_from_value(
+ schema,
effective,
variables,
ValueCursor {
@@ -835,6 +856,7 @@ struct ValueCursor<'a> {
}
fn resolve_from_value(
+ schema: &crate::meta::Schema,
effective: &HashMap<EntityKey<'static>, Record>,
variables: &serde_json::Map<String, Json>,
cursor: ValueCursor<'_>,
@@ -847,12 +869,14 @@ fn resolve_from_value(
field_key: cursor.anchor_field,
path: cursor.relative_path,
match_field: upsert::resolve_field(
+ schema,
cursor.selections,
cursor.type_name,
variables,
operation,
)?,
embedded_link: resolve_embedded_link_fields(
+ schema,
cursor.selections,
cursor.type_name,
variables,
@@ -863,6 +887,7 @@ fn resolve_from_value(
if let CacheValue::Ref(key) = cursor.value {
return resolve_from_record(
+ schema,
effective,
key,
cursor.type_name,
@@ -887,7 +912,7 @@ fn resolve_from_value(
_ => None,
})
.unwrap_or(cursor.type_name);
- let selected = selected_field(cursor.selections, concrete, response_key)?;
+ let selected = selected_field(schema, cursor.selections, concrete, response_key)?;
let storage_key = selected_storage_key(selected, variables)?;
let child = object.get(&storage_key).ok_or(LinkPatchError::WrongShape)?;
let mut child_path = cursor.relative_path;
@@ -895,6 +920,7 @@ fn resolve_from_value(
field: storage_key.clone(),
});
resolve_from_value(
+ schema,
effective,
variables,
ValueCursor {
@@ -902,7 +928,7 @@ fn resolve_from_value(
owner: cursor.owner,
anchor_field: cursor.anchor_field,
relative_path: child_path,
- type_name: selected_type(concrete, selected)?,
+ type_name: selected_type(schema, concrete, selected)?,
selections: &selected.selection_set,
},
&path[1..],
@@ -916,8 +942,12 @@ fn resolve_from_value(
maximum: MAX_TRAVERSED_LIST,
});
}
- let selector =
- selected_field(cursor.selections, cursor.type_name, &list_item.where_field)?;
+ let selector = selected_field(
+ schema,
+ cursor.selections,
+ cursor.type_name,
+ &list_item.where_field,
+ )?;
let selector_key = selected_storage_key(selector, variables)?;
let mut matches = Vec::new();
for (index, value) in items.iter().enumerate() {
@@ -952,6 +982,7 @@ fn resolve_from_value(
},
});
resolve_from_value(
+ schema,
effective,
variables,
ValueCursor {
@@ -971,6 +1002,7 @@ fn resolve_from_value(
}
fn resolve_embedded_link_fields(
+ schema: &crate::meta::Schema,
selections: &[Selection],
concrete: &str,
variables: &serde_json::Map<String, Json>,
@@ -996,20 +1028,24 @@ fn resolve_embedded_link_fields(
};
let selector_key = selected_storage_key(
- selected_field(selections, concrete, &list_item.where_field)?,
+ selected_field(schema, selections, concrete, &list_item.where_field)?,
+ variables,
+ )?;
+ let resolved_link_field = selected_storage_key(
+ selected_field(schema, selections, concrete, link_field)?,
variables,
)?;
- let resolved_link_field =
- selected_storage_key(selected_field(selections, concrete, link_field)?, variables)?;
let resolved_count_field = selected_storage_key(
- selected_field(selections, concrete, count_field)?,
+ selected_field(schema, selections, concrete, count_field)?,
variables,
)?;
let mut resolved_insert_fields = HashMap::new();
if let Some(insert_fields) = insert_fields {
for (field, value) in insert_fields {
- let storage_key =
- selected_storage_key(selected_field(selections, concrete, field)?, variables)?;
+ let storage_key = selected_storage_key(
+ selected_field(schema, selections, concrete, field)?,
+ variables,
+ )?;
if resolved_insert_fields.contains_key(&storage_key) {
return Err(LinkPatchError::ConflictingInsertField(storage_key));
}
@@ -1053,11 +1089,12 @@ fn resolve_embedded_link_fields(
}
fn selected_field<'a>(
+ schema: &crate::meta::Schema,
selections: &'a [Selection],
concrete: &str,
response_key: &str,
) -> Result<&'a FieldNode, LinkPatchError> {
- find_selected_field(selections, concrete, response_key).ok_or_else(|| {
+ find_selected_field(schema, selections, concrete, response_key).ok_or_else(|| {
LinkPatchError::UnselectedField {
type_name: concrete.to_string(),
field: response_key.to_string(),
@@ -1073,8 +1110,12 @@ fn selected_storage_key(
.map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))
}
-fn selected_type(concrete: &str, field: &FieldNode) -> Result<&'static str, LinkPatchError> {
- resolve_selected_type(concrete, field).ok_or_else(|| LinkPatchError::UnselectedField {
+fn selected_type<'schema>(
+ schema: &'schema crate::meta::Schema,
+ concrete: &str,
+ field: &FieldNode,
+) -> Result<&'schema str, LinkPatchError> {
+ resolve_selected_type(schema, concrete, field).ok_or_else(|| LinkPatchError::UnselectedField {
type_name: concrete.to_string(),
field: field.response_key.clone(),
})
@@ -1293,7 +1334,7 @@ mod tests {
};
*link_field = "key".into();
assert_eq!(
- deduplicate_patches(&[direct_conflict]).unwrap_err(),
+ deduplicate_patches(&crate::meta::bundled_schema(), &[direct_conflict]).unwrap_err(),
LinkPatchError::ConflictingManagedField {
first: "key".into(),
second: "key".into(),
@@ -1323,7 +1364,12 @@ mod tests {
list_item.where_field = "selector".into();
*link_field = "link".into();
assert_eq!(
- resolve_target(&effective, &resolved_conflict).unwrap_err(),
+ resolve_target(
+ &crate::meta::bundled_schema(),
+ &effective,
+ &resolved_conflict
+ )
+ .unwrap_err(),
LinkPatchError::ConflictingManagedField {
first: "key".into(),
second: "key".into(),
@@ -1355,7 +1401,7 @@ mod tests {
]);
assert_eq!(
- resolve_target(&effective, &duplicate).unwrap_err(),
+ resolve_target(&crate::meta::bundled_schema(), &effective, &duplicate).unwrap_err(),
LinkPatchError::ConflictingInsertField("nextCursor".into())
);
}
@@ -1376,6 +1422,7 @@ mod tests {
]);
let mut updates = RecordUpdates::new();
apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
&[
@@ -1445,6 +1492,7 @@ mod tests {
let mut updates = RecordUpdates::new();
assert_eq!(
apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
std::slice::from_ref(&ghost),
@@ -1460,7 +1508,14 @@ mod tests {
// and leaves the base untouched for the revalidation to repair.
let mut effective = base;
let mut updates = RecordUpdates::new();
- apply_link_patches(&mut effective, &mut updates, &[ghost], true).unwrap();
+ apply_link_patches(
+ &crate::meta::bundled_schema(),
+ &mut effective,
+ &mut updates,
+ &[ghost],
+ true,
+ )
+ .unwrap();
assert_eq!(effective.get(&parent), Some(&initial));
assert!(updates.is_empty());
@@ -1468,6 +1523,7 @@ mod tests {
// must never require its target to still exist.
let mut updates = RecordUpdates::new();
apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
&[patch(
@@ -1498,33 +1554,57 @@ mod tests {
let mut updates = RecordUpdates::new();
let urgent = upsert_bin_patch("urgent");
apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
&[urgent.clone(), urgent.clone()],
false,
)
.unwrap();
- apply_link_patches(&mut effective, &mut updates, &[urgent], false).unwrap();
+ apply_link_patches(
+ &crate::meta::bundled_schema(),
+ &mut effective,
+ &mut updates,
+ &[urgent],
+ false,
+ )
+ .unwrap();
let completed = upsert_bin_patch("completed");
apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
std::slice::from_ref(&completed),
false,
)
.unwrap();
- apply_link_patches(&mut effective, &mut updates, &[completed], false).unwrap();
+ apply_link_patches(
+ &crate::meta::bundled_schema(),
+ &mut effective,
+ &mut updates,
+ &[completed],
+ false,
+ )
+ .unwrap();
let source = remove_bin_patch("in-progress");
apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
std::slice::from_ref(&source),
false,
)
.unwrap();
- apply_link_patches(&mut effective, &mut updates, &[source], false).unwrap();
+ apply_link_patches(
+ &crate::meta::bundled_schema(),
+ &mut effective,
+ &mut updates,
+ &[source],
+ false,
+ )
+ .unwrap();
let CacheValue::Object(grouped) = &effective[&parent].fields["groupSoup"] else {
panic!()
@@ -1585,6 +1665,7 @@ mod tests {
]);
let mut updates = RecordUpdates::new();
let result = apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
&[
@@ -1639,6 +1720,7 @@ mod tests {
let mut updates = RecordUpdates::new();
assert_eq!(
apply_link_patches(
+ &crate::meta::bundled_schema(),
&mut effective,
&mut updates,
&[patch(
diff --git a/crates/client/cache-core/src/link_patch/record_root.rs b/crates/client/cache-core/src/link_patch/record_root.rs
index a09feaa336..62e7e3ad82 100644
--- a/crates/client/cache-core/src/link_patch/record_root.rs
+++ b/crates/client/cache-core/src/link_patch/record_root.rs
@@ -21,7 +21,11 @@ pub struct RecordRoot {
}
impl RecordRoot {
- pub(super) fn validate(&self, patch: &OptimisticLinkPatch) -> Result<(), LinkPatchError> {
+ pub(super) fn validate(
+ &self,
+ schema: &crate::meta::Schema,
+ patch: &OptimisticLinkPatch,
+ ) -> Result<(), LinkPatchError> {
validate_entity_key(self.entity_key.borrowed())?;
if patch.operation_name.is_some()
|| serde_json::from_str::<Value>(&patch.variables_json).map_err(invalid)?
@@ -38,7 +42,7 @@ impl RecordRoot {
));
}
let selection =
- RecordSelection::parse(&patch.query, &self.fragment_name).map_err(invalid)?;
+ RecordSelection::parse(schema, &patch.query, &self.fragment_name).map_err(invalid)?;
if !selection
.type_names()
.iter()
@@ -53,17 +57,19 @@ impl RecordRoot {
pub(super) fn resolve(
&self,
+ schema: &crate::meta::Schema,
effective: &HashMap<EntityKey<'static>, Record>,
patch: &OptimisticLinkPatch,
) -> Result<ResolvedTarget, LinkPatchError> {
let selection =
- RecordSelection::parse(&patch.query, &self.fragment_name).map_err(invalid)?;
+ RecordSelection::parse(schema, &patch.query, &self.fragment_name).map_err(invalid)?;
if let Some(typename) = effective.get(&self.entity_key).and_then(Record::typename)
&& typename != self.type_name()
{
return Err(invalid("cached record type does not match its key"));
}
resolve_from_record(
+ schema,
effective,
&self.entity_key,
self.type_name(),
diff --git a/crates/client/cache-core/src/link_patch/record_root/test.rs b/crates/client/cache-core/src/link_patch/record_root/test.rs
index 88c6ec0a11..aa98a5bfec 100644
--- a/crates/client/cache-core/src/link_patch/record_root/test.rs
+++ b/crates/client/cache-core/src/link_patch/record_root/test.rs
@@ -28,7 +28,11 @@ fn recipe() -> OptimisticLinkPatch {
fn record_recipes_roundtrip_and_do_not_become_network_queries() {
let patch = recipe();
assert_eq!(
- deduplicate_patches(&[patch.clone(), patch.clone()]).unwrap(),
+ deduplicate_patches(
+ crate::meta::bundled_schema_ref(),
+ &[patch.clone(), patch.clone()]
+ )
+ .unwrap(),
vec![patch.clone()]
);
assert_eq!(
@@ -85,7 +89,7 @@ fn invalid_roots_and_fragments_are_rejected_before_enqueue() {
patch.record_root.as_mut().unwrap().fragment_name = "Missing".into();
cases.push(patch);
for patch in cases {
- assert!(deduplicate_patches(&[patch]).is_err());
+ assert!(deduplicate_patches(crate::meta::bundled_schema_ref(), &[patch]).is_err());
}
}
@@ -94,12 +98,12 @@ fn resolution_rejects_missing_fields_and_cached_type_mismatches() {
let patch = recipe();
let root = patch.record_root.as_ref().unwrap();
assert!(matches!(
- root.resolve(&HashMap::new(), &patch),
+ root.resolve(crate::meta::bundled_schema_ref(), &HashMap::new(), &patch),
Err(LinkPatchError::MissingParent(_))
));
let mut effective = HashMap::from([(root.entity_key.clone(), Record::default())]);
assert!(matches!(
- root.resolve(&effective, &patch),
+ root.resolve(crate::meta::bundled_schema_ref(), &effective, &patch),
Err(LinkPatchError::MissingField { .. })
));
effective.get_mut(&root.entity_key).unwrap().fields.insert(
@@ -107,7 +111,7 @@ fn resolution_rejects_missing_fields_and_cached_type_mismatches() {
crate::value::CacheValue::String("GraphqlSoupChat".into()),
);
assert!(matches!(
- root.resolve(&effective, &patch),
+ root.resolve(crate::meta::bundled_schema_ref(), &effective, &patch),
Err(LinkPatchError::InvalidEntrypoint(_))
));
}
diff --git a/crates/client/cache-core/src/link_patch/upsert.rs b/crates/client/cache-core/src/link_patch/upsert.rs
index 77bd4bed6c..849de335d4 100644
--- a/crates/client/cache-core/src/link_patch/upsert.rs
+++ b/crates/client/cache-core/src/link_patch/upsert.rs
@@ -6,6 +6,7 @@ use super::*;
mod test;
pub(super) fn resolve_field(
+ schema: &crate::meta::Schema,
selections: &[Selection],
type_name: &str,
variables: &serde_json::Map<String, Json>,
@@ -14,7 +15,7 @@ pub(super) fn resolve_field(
let LinkOperation::UpsertByField { where_field, .. } = operation else {
return Ok(None);
};
- let selected = selected_field(selections, type_name, where_field)?;
+ let selected = selected_field(schema, selections, type_name, where_field)?;
if !selected.selection_set.is_empty() {
return Err(LinkPatchError::WrongShape);
}
diff --git a/crates/client/cache-core/src/meta.rs b/crates/client/cache-core/src/meta.rs
index d61f4193ac..d84f436fa3 100644
--- a/crates/client/cache-core/src/meta.rs
+++ b/crates/client/cache-core/src/meta.rs
@@ -1,198 +1,340 @@
-//! Schema metadata: static tables generated at build time from
-//! `static_assets/schema.graphql` (see `build.rs`).
-//!
-//! The cache never parses SDL at runtime — everything type-related is
-//! resolved through these tables.
+//! Immutable runtime schema metadata, supplied by the frontend bundle.
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::sync::{Arc, LazyLock};
-/// Kind of a composite (selectable) type.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+/// Composite output type classification.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TypeKind {
+ /// A concrete output object.
Object,
+ /// A union of concrete output objects.
Union,
+ /// An interface implemented by concrete objects.
Interface,
}
-
-/// What a field's named type resolves to, decided at codegen time.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+/// Storage interpretation of a field.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FieldKind {
- /// Object / union / interface — value is a link (ref) or embedded object.
+ /// A selectable object, interface, or union.
Composite,
- /// Built-in scalar or enum — stored as a plain leaf value.
+ /// A built-in scalar or enum.
Leaf,
- /// Custom scalar (e.g. `JSON`) — stored as an opaque JSON blob.
+ /// A custom scalar stored as opaque JSON.
OpaqueScalar,
}
-
-/// Flattened GraphQL wrapping type. Nested lists are rejected at codegen.
+/// Borrowed field shape used by cache walks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct FieldType {
- /// The named (inner) type.
- pub name: &'static str,
+pub struct FieldType<'a> {
+ /// GraphQL name.
+ pub name: &'a str,
+ /// Output or storage classification.
pub kind: FieldKind,
- /// Nullability of the outermost wrapper.
+ /// Whether the outer value may be null.
pub nullable: bool,
+ /// Whether the field contains a list.
pub list: bool,
- /// Only meaningful when `list` is true.
+ /// Whether list elements may be null.
pub item_nullable: bool,
}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct FieldMeta {
- pub name: &'static str,
- pub ty: FieldType,
+/// Owned field shape in the metadata artifact.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct OwnedFieldType {
+ /// GraphQL name.
+ pub name: String,
+ /// Output or storage classification.
+ pub kind: FieldKind,
+ /// Whether the outer value may be null.
+ pub nullable: bool,
+ /// Whether the field contains a list.
+ pub list: bool,
+ /// Whether list elements may be null.
+ pub item_nullable: bool,
}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+/// Owned field definition.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct OwnedFieldMeta {
+ /// GraphQL name.
+ pub name: String,
+ /// Declared return shape.
+ pub ty: OwnedFieldType,
+}
+/// Borrowed field definition.
+#[derive(Debug, Clone, Copy)]
+pub struct FieldMeta<'a> {
+ /// GraphQL name.
+ pub name: &'a str,
+ /// Declared return shape.
+ pub ty: FieldType<'a>,
+}
+/// Output type and its normalization policy.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypeMeta {
- pub name: &'static str,
+ /// GraphQL name.
+ pub name: String,
+ /// Output or storage classification.
pub kind: TypeKind,
- /// `Some(fields)` when the type is a normalized entity; `None` when it is
- /// embedded inline in its parent record. Derived from the schema's
- /// `id: ID!` convention.
- pub key_fields: Option<&'static [&'static str]>,
- /// Field definitions (objects/interfaces only; empty for unions).
- pub fields: &'static [FieldMeta],
- /// Union members / interface implementors (empty for plain objects).
- pub possible_types: &'static [&'static str],
+ /// Entity identity fields; absent for embedded objects.
+ pub key_fields: Option<Vec<String>>,
+ /// Declared fields on this output type.
+ pub fields: Vec<OwnedFieldMeta>,
+ /// Concrete union members or interface implementors.
+ pub possible_types: Vec<String>,
}
-
-include!(concat!(env!("OUT_DIR"), "/schema_meta.rs"));
-
-/// Looks up a composite type by name. `TYPES` is sorted by name at codegen.
-pub fn type_meta(name: &str) -> Option<&'static TypeMeta> {
- TYPES
- .binary_search_by(|t| t.name.cmp(name))
- .ok()
- .map(|i| &TYPES[i])
+/// Versioned internal persistence format for merged schema lookup tables.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct SchemaArtifact {
+ /// Persistence format understood by the engine.
+ pub format_version: u32,
+ /// Persisted record semantics required by this schema.
+ pub compatibility_epoch: u32,
+ /// Query operation root.
+ pub query_root: String,
+ /// Optional mutation operation root.
+ pub mutation_root: Option<String>,
+ /// Optional subscription operation root.
+ pub subscription_root: Option<String>,
+ /// Composite output definitions.
+ pub types: Vec<TypeMeta>,
}
-
-/// Looks up a field on a composite type.
-pub fn field_meta(type_name: &str, field: &str) -> Option<&'static FieldMeta> {
- let t = type_meta(type_name)?;
- t.fields.iter().find(|f| f.name == field)
+/// Validated immutable snapshot owned by an engine.
+#[derive(Debug)]
+pub struct Schema {
+ artifact: SchemaArtifact,
+ hash: String,
}
-
-/// True when an object of concrete type `concrete` matches a fragment type
-/// condition `condition` (exact match, union membership, or interface
-/// implementation).
-pub fn type_matches(concrete: &str, condition: &str) -> bool {
- if concrete == condition {
- return true;
+/// Invalid or unsupported schema metadata. Loading never modifies storage.
+#[derive(Debug, thiserror::Error)]
+#[error("invalid cache schema: {0}")]
+pub struct SchemaError(String);
+impl Schema {
+ /// Decode persisted metadata before opening its cache.
+ pub fn from_json(json: &str) -> Result<Arc<Self>, SchemaError> {
+ let artifact: SchemaArtifact =
+ serde_json::from_str(json).map_err(|e| SchemaError(e.to_string()))?;
+ Self::from_artifact(artifact)
}
- match type_meta(condition) {
- Some(meta) => meta.possible_types.contains(&concrete),
- None => false,
+ /// Validate metadata and compute its canonical identity.
+ pub fn from_artifact(mut artifact: SchemaArtifact) -> Result<Arc<Self>, SchemaError> {
+ if artifact.format_version != 1
+ || artifact.compatibility_epoch != crate::codec::CACHE_SCHEMA_COMPATIBILITY_EPOCH
+ {
+ return Err(SchemaError(
+ "unsupported format or compatibility epoch; a native update is required".into(),
+ ));
+ }
+ artifact.types.sort_by(|a, b| a.name.cmp(&b.name));
+ for ty in &mut artifact.types {
+ ty.fields.sort_by(|a, b| a.name.cmp(&b.name));
+ ty.possible_types.sort();
+ }
+ let schema = Self {
+ artifact,
+ hash: String::new(),
+ };
+ schema.validate()?;
+ let bytes = serde_json::to_vec(&schema.artifact).map_err(|e| SchemaError(e.to_string()))?;
+ let hash = format!("{:x}", Sha256::digest(bytes));
+ Ok(Arc::new(Self { hash, ..schema }))
}
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn query_root_is_present() {
- let root = type_meta(QUERY_ROOT_TYPE).expect("query root type");
- assert_eq!(root.kind, TypeKind::Object);
- assert!(root.key_fields.is_none());
- assert!(root.fields.iter().any(|f| f.name == "user"));
-
- // The viewer object is keyed by presence-of-id.
- let user = type_meta("GraphqlUser").expect("user type");
- assert_eq!(user.key_fields, Some(&["id"][..]));
- assert!(user.fields.iter().any(|f| f.name == "soup"));
+ /// Combines compatible bundle versions, retaining definitions needed by queued work.
+ /// Shape and identity changes require an explicit engine/storage migration.
+ pub fn merge(&self, incoming: &Schema) -> Result<Arc<Self>, SchemaError> {
+ if self.artifact.query_root != incoming.artifact.query_root
+ || self.artifact.mutation_root != incoming.artifact.mutation_root
+ || self.artifact.subscription_root != incoming.artifact.subscription_root
+ {
+ return Err(SchemaError(
+ "operation roots changed; native migration required".into(),
+ ));
+ }
+ let mut artifact = self.artifact.clone();
+ for ty in &incoming.artifact.types {
+ let Some(existing) = artifact.types.iter_mut().find(|t| t.name == ty.name) else {
+ artifact.types.push(ty.clone());
+ continue;
+ };
+ if existing.kind != ty.kind || existing.key_fields != ty.key_fields {
+ return Err(SchemaError(format!(
+ "type {} changed identity or kind",
+ ty.name
+ )));
+ }
+ for field in &ty.fields {
+ if let Some(previous) = existing.fields.iter().find(|f| f.name == field.name) {
+ if previous != field {
+ return Err(SchemaError(format!(
+ "field {}.{} changed shape",
+ ty.name, field.name
+ )));
+ }
+ } else {
+ existing.fields.push(field.clone());
+ }
+ }
+ for name in &ty.possible_types {
+ if !existing.possible_types.contains(name) {
+ existing.possible_types.push(name.clone());
+ }
+ }
+ }
+ Self::from_artifact(artifact)
}
-
- #[test]
- fn mutation_root_is_present() {
- let name = MUTATION_ROOT_TYPE.expect("schema has a mutation root");
- let root = type_meta(name).expect("mutation root type");
- assert_eq!(root.kind, TypeKind::Object);
- assert!(root.key_fields.is_none());
- assert!(root.fields.iter().any(|f| f.name == "setEntityProperty"));
+ fn validate(&self) -> Result<(), SchemaError> {
+ let fail = |message: &str| Err(SchemaError(message.into()));
+ for pair in self.artifact.types.windows(2) {
+ if pair[0].name == pair[1].name {
+ return fail("duplicate type");
+ }
+ }
+ for root in std::iter::once(self.query_root())
+ .chain(self.mutation_root())
+ .chain(self.subscription_root())
+ {
+ let Some(ty) = self.type_meta(root) else {
+ return fail("missing operation root");
+ };
+ if ty.kind != TypeKind::Object
+ || ty.key_fields.is_some()
+ || ty.fields.iter().any(|f| f.name == "id")
+ {
+ return fail("invalid operation root");
+ }
+ }
+ for ty in &self.artifact.types {
+ if ty.name.is_empty() {
+ return fail("empty type name");
+ }
+ if ty.fields.windows(2).any(|p| p[0].name == p[1].name) {
+ return fail("duplicate field");
+ }
+ if ty.possible_types.windows(2).any(|p| p[0] == p[1]) {
+ return fail("duplicate possible type");
+ }
+ let id = ty.fields.iter().find(|f| f.name == "id");
+ if let Some(id) = id
+ && (id.ty.name != "ID"
+ || id.ty.nullable
+ || id.ty.list
+ || id.ty.kind != FieldKind::Leaf)
+ {
+ return fail("entity id must be ID!");
+ }
+ if ty
+ .key_fields
+ .as_ref()
+ .map(|keys| keys.iter().map(String::as_str).collect::<Vec<_>>())
+ != id.map(|_| vec!["id"])
+ {
+ return fail("invalid entity key policy");
+ }
+ if ty.kind == TypeKind::Union && !ty.fields.is_empty() {
+ return fail("union has fields");
+ }
+ if ty.kind == TypeKind::Object && !ty.possible_types.is_empty() {
+ return fail("object has possible types");
+ }
+ for name in &ty.possible_types {
+ if !self
+ .type_meta(name)
+ .is_some_and(|t| t.kind == TypeKind::Object)
+ {
+ return fail("invalid possible type");
+ }
+ }
+ for field in &ty.fields {
+ if field.name.is_empty() || field.ty.name.is_empty() {
+ return fail("empty field or return type");
+ }
+ if (field.ty.kind == FieldKind::Composite)
+ != self.type_meta(&field.ty.name).is_some()
+ {
+ return fail("invalid composite field reference");
+ }
+ }
+ }
+ Ok(())
}
-
- #[test]
- fn subscription_root_is_present() {
- let name = SUBSCRIPTION_ROOT_TYPE.expect("schema has a subscription root");
- let root = type_meta(name).expect("subscription root type");
- assert_eq!(root.kind, TypeKind::Object);
- assert!(root.key_fields.is_none());
- assert!(root.fields.iter().any(|field| field.name == "soupUpdates"));
+ /// Identity used to reject mixed bundle schemas in a shared native engine.
+ pub fn hash(&self) -> &str {
+ &self.hash
}
-
- #[test]
- fn interface_possible_types() {
- let entity = type_meta("GraphqlSoupEntity").expect("entity interface");
- assert_eq!(entity.kind, TypeKind::Interface);
- assert!(entity.possible_types.contains(&"GraphqlSoupDocument"));
- assert!(entity.possible_types.contains(&"GraphqlSoupForeignEntity"));
- assert!(entity.possible_types.contains(&"GraphqlSoupCalendarEvent"));
- assert!(entity.possible_types.contains(&"GraphqlSoupAgentSession"));
- assert!(entity.possible_types.contains(&"GraphqlSoupInitiative"));
- assert!(entity.possible_types.contains(&"GraphqlSoupDatabaseRow"));
- assert!(entity.possible_types.contains(&"GraphqlSoupCrmContact"));
- assert_eq!(entity.possible_types.len(), 14);
- assert!(type_matches("GraphqlSoupDocument", "GraphqlSoupEntity"));
- assert!(type_matches("GraphqlSoupInitiative", "GraphqlSoupEntity"));
- assert!(!type_matches("GraphqlSoupItem", "GraphqlSoupEntity"));
+ /// Canonical metadata for persistence and diagnostics.
+ pub fn artifact(&self) -> &SchemaArtifact {
+ &self.artifact
}
-
- #[test]
- fn presence_of_id_convention_applied() {
- assert_eq!(
- type_meta("GraphqlSoupDocument").unwrap().key_fields,
- Some(&["id"][..])
- );
- // Renamed from `messageId` so the convention keys it.
- assert_eq!(
- type_meta("GraphqlSoupChannelMessage").unwrap().key_fields,
- Some(&["id"][..])
- );
- // Property assignments have globally unique database ids and are
- // normalized independently from their shared definitions.
- assert_eq!(
- type_meta("GraphqlProperty").unwrap().key_fields,
- Some(&["id"][..])
- );
- assert!(field_meta("GraphqlProperty", "propertyDefinitionId").is_some());
- // No id field → embedded.
- assert_eq!(type_meta("SoupPage").unwrap().key_fields, None);
- assert_eq!(
- type_meta("GraphqlSoupChannelParticipant")
- .unwrap()
- .key_fields,
- None
- );
+ /// Query root name.
+ pub fn query_root(&self) -> &str {
+ &self.artifact.query_root
}
-
- #[test]
- fn field_shapes() {
- // properties: [GraphqlProperty!]!
- let f = field_meta("GraphqlSoupDocument", "properties").unwrap();
- assert_eq!(f.ty.name, "GraphqlProperty");
- assert_eq!(f.ty.kind, FieldKind::Composite);
- assert!(!f.ty.nullable && f.ty.list && !f.ty.item_nullable);
-
- // viewedAt: String (nullable leaf)
- let f = field_meta("GraphqlSoupDocument", "viewedAt").unwrap();
- assert_eq!(f.ty.kind, FieldKind::Leaf);
- assert!(f.ty.nullable && !f.ty.list);
-
- // sourceMetadata: JSON! (opaque scalar); metadata is now the shared
- // structured interface field.
- let f = field_meta("GraphqlSoupForeignEntity", "sourceMetadata").unwrap();
- assert_eq!(f.ty.kind, FieldKind::OpaqueScalar);
- assert!(!f.ty.nullable);
-
- // items: [GraphqlSoupEntity!]! (composite link to the entity interface)
- let f = field_meta("SoupPage", "items").unwrap();
- assert_eq!(f.ty.kind, FieldKind::Composite);
- assert_eq!(f.ty.name, "GraphqlSoupEntity");
- assert!(f.ty.list);
+ /// Optional mutation root name.
+ pub fn mutation_root(&self) -> Option<&str> {
+ self.artifact.mutation_root.as_deref()
}
-
- #[test]
- fn schema_hash_present() {
- assert_eq!(SCHEMA_HASH.len(), 64);
+ /// Optional subscription root name.
+ pub fn subscription_root(&self) -> Option<&str> {
+ self.artifact.subscription_root.as_deref()
+ }
+ /// Looks up a composite type.
+ pub fn type_meta(&self, name: &str) -> Option<&TypeMeta> {
+ self.artifact
+ .types
+ .binary_search_by(|t| t.name.as_str().cmp(name))
+ .ok()
+ .map(|i| &self.artifact.types[i])
+ }
+ /// Borrows a field shape without allocating.
+ pub fn field_meta(&self, type_name: &str, field: &str) -> Option<FieldMeta<'_>> {
+ let fields = &self.type_meta(type_name)?.fields;
+ let f = &fields[fields
+ .binary_search_by(|f| f.name.as_str().cmp(field))
+ .ok()?];
+ Some(FieldMeta {
+ name: &f.name,
+ ty: FieldType {
+ name: &f.ty.name,
+ kind: f.ty.kind,
+ nullable: f.ty.nullable,
+ list: f.ty.list,
+ item_nullable: f.ty.item_nullable,
+ },
+ })
+ }
+ /// Tests concrete membership in a fragment condition.
+ pub fn type_matches(&self, concrete: &str, condition: &str) -> bool {
+ concrete == condition
+ || self
+ .type_meta(condition)
+ .is_some_and(|t| t.possible_types.iter().any(|name| name == concrete))
}
}
+/// SDL embedded for legacy callers and tests; production hosts supply bundle SDL.
+pub const BUNDLED_SCHEMA_SDL: &str = include_str!("../../../../static_assets/schema.graphql");
+/// Fingerprint of the SDL embedded in this build, for diagnostics.
+pub const SCHEMA_HASH: &str = env!("CACHE_BUNDLED_SCHEMA_HASH");
+static BUNDLED_SCHEMA: LazyLock<Arc<Schema>> =
+ LazyLock::new(|| Schema::from_sdl(BUNDLED_SCHEMA_SDL).expect("valid bundled schema"));
+mod sdl;
+/// Embedded fixture/default for Rust callers. Production hosts supply bundle SDL.
+pub fn bundled_schema_ref() -> &'static Schema {
+ &BUNDLED_SCHEMA
+}
+/// Embedded schema for legacy Rust callers and tests.
+pub fn bundled_schema() -> Arc<Schema> {
+ Arc::clone(&BUNDLED_SCHEMA)
+}
+/// Legacy lookup against the embedded schema.
+pub fn type_meta(name: &str) -> Option<&'static TypeMeta> {
+ BUNDLED_SCHEMA.type_meta(name)
+}
+/// Legacy field lookup against the embedded schema.
+pub fn field_meta(type_name: &str, field: &str) -> Option<FieldMeta<'static>> {
+ BUNDLED_SCHEMA.field_meta(type_name, field)
+}
+/// Legacy fragment matching against the embedded schema.
+pub fn type_matches(concrete: &str, condition: &str) -> bool {
+ BUNDLED_SCHEMA.type_matches(concrete, condition)
+}
+#[cfg(test)]
+mod test;
diff --git a/crates/client/cache-core/src/meta/sdl.rs b/crates/client/cache-core/src/meta/sdl.rs
new file mode 100644
index 0000000000..75bde4b923
--- /dev/null
+++ b/crates/client/cache-core/src/meta/sdl.rs
@@ -0,0 +1,140 @@
+//! Parse bundle SDL into the cache's owned lookup tables.
+//! Objects with `id: ID!` are entities; objects without `id` are embedded.
+//! The shared metadata validator rejects other id shapes and keyed operation roots.
+use super::*;
+use apollo_compiler::ast::{FieldDefinition, Type};
+use apollo_compiler::schema::{Component, ExtendedType};
+use apollo_compiler::{Name, Schema as GraphqlSchema};
+
+impl Schema {
+ /// Parse and validate GraphQL SDL before installing any schema or opening storage.
+ pub fn from_sdl(sdl: &str) -> Result<Arc<Self>, SchemaError> {
+ let schema = GraphqlSchema::parse_and_validate(sdl, "schema.graphql")
+ .map_err(|error| SchemaError(error.to_string()))?;
+ let query_root = schema
+ .schema_definition
+ .query
+ .as_ref()
+ .ok_or_else(|| SchemaError("missing query root".into()))?
+ .name
+ .to_string();
+ let mut types = Vec::new();
+ for (name, ty) in &schema.types {
+ if name.starts_with("__") {
+ continue;
+ }
+ let (kind, fields, possible_types) = match ty {
+ ExtendedType::Object(object) => (
+ TypeKind::Object,
+ fields(&schema, object.fields.iter())?,
+ Vec::new(),
+ ),
+ ExtendedType::Interface(interface) => (
+ TypeKind::Interface,
+ fields(&schema, interface.fields.iter())?,
+ schema
+ .types
+ .iter()
+ .filter_map(|(object_name, ty)| match ty {
+ ExtendedType::Object(object)
+ if object.implements_interfaces.contains(name) =>
+ {
+ Some(object_name.to_string())
+ }
+ _ => None,
+ })
+ .collect(),
+ ),
+ ExtendedType::Union(union) => (
+ TypeKind::Union,
+ Vec::new(),
+ union
+ .members
+ .iter()
+ .map(|member| member.name.to_string())
+ .collect(),
+ ),
+ _ => continue,
+ };
+ let key_fields = fields
+ .iter()
+ .any(|field| field.name == "id")
+ .then(|| vec!["id".into()]);
+ types.push(TypeMeta {
+ name: name.to_string(),
+ kind,
+ key_fields,
+ fields,
+ possible_types,
+ });
+ }
+ Self::from_artifact(SchemaArtifact {
+ format_version: 1,
+ compatibility_epoch: crate::codec::CACHE_SCHEMA_COMPATIBILITY_EPOCH,
+ query_root,
+ mutation_root: schema
+ .schema_definition
+ .mutation
+ .as_ref()
+ .map(|root| root.name.to_string()),
+ subscription_root: schema
+ .schema_definition
+ .subscription
+ .as_ref()
+ .map(|root| root.name.to_string()),
+ types,
+ })
+ }
+}
+
+fn fields<'a>(
+ schema: &GraphqlSchema,
+ definitions: impl Iterator<Item = (&'a Name, &'a Component<FieldDefinition>)>,
+) -> Result<Vec<OwnedFieldMeta>, SchemaError> {
+ definitions
+ .map(|(name, definition)| {
+ let (inner, nullable, list) = match &definition.ty {
+ Type::Named(_) => (&definition.ty, true, false),
+ Type::NonNullNamed(_) => (&definition.ty, false, false),
+ Type::List(inner) => (inner.as_ref(), true, true),
+ Type::NonNullList(inner) => (inner.as_ref(), false, true),
+ };
+ let (named, item_nullable) = match inner {
+ Type::Named(named) => (named, list),
+ Type::NonNullNamed(named) => (named, false),
+ _ => {
+ return Err(SchemaError(format!(
+ "nested lists are not supported: {name}"
+ )));
+ }
+ };
+ let kind = match schema.types.get(named) {
+ Some(
+ ExtendedType::Object(_) | ExtendedType::Interface(_) | ExtendedType::Union(_),
+ ) => FieldKind::Composite,
+ Some(ExtendedType::Enum(_)) => FieldKind::Leaf,
+ Some(ExtendedType::Scalar(_)) => {
+ if matches!(
+ named.as_str(),
+ "Int" | "Float" | "String" | "Boolean" | "ID"
+ ) {
+ FieldKind::Leaf
+ } else {
+ FieldKind::OpaqueScalar
+ }
+ }
+ _ => return Err(SchemaError(format!("invalid output type: {named}"))),
+ };
+ Ok(OwnedFieldMeta {
+ name: name.to_string(),
+ ty: OwnedFieldType {
+ name: named.to_string(),
+ kind,
+ nullable,
+ list,
+ item_nullable,
+ },
+ })
+ })
+ .collect()
+}
diff --git a/crates/client/cache-core/src/meta/test.rs b/crates/client/cache-core/src/meta/test.rs
new file mode 100644
index 0000000000..996647a3d9
--- /dev/null
+++ b/crates/client/cache-core/src/meta/test.rs
@@ -0,0 +1,247 @@
+use super::*;
+
+#[test]
+fn query_root_is_present() {
+ let root = type_meta(bundled_schema_ref().query_root()).expect("query root type");
+ assert_eq!(root.kind, TypeKind::Object);
+ assert!(root.key_fields.is_none());
+ assert!(root.fields.iter().any(|f| f.name == "user"));
+
+ // The viewer object is keyed by presence-of-id.
+ let user = type_meta("GraphqlUser").expect("user type");
+ assert_eq!(user.key_fields, Some(vec!["id".to_owned()]));
+ assert!(user.fields.iter().any(|f| f.name == "soup"));
+}
+
+#[test]
+fn mutation_root_is_present() {
+ let name = bundled_schema_ref()
+ .mutation_root()
+ .expect("schema has a mutation root");
+ let root = type_meta(name).expect("mutation root type");
+ assert_eq!(root.kind, TypeKind::Object);
+ assert!(root.key_fields.is_none());
+ assert!(root.fields.iter().any(|f| f.name == "setEntityProperty"));
+}
+
+#[test]
+fn subscription_root_is_present() {
+ let name = bundled_schema_ref()
+ .subscription_root()
+ .expect("schema has a subscription root");
+ let root = type_meta(name).expect("subscription root type");
+ assert_eq!(root.kind, TypeKind::Object);
+ assert!(root.key_fields.is_none());
+ assert!(root.fields.iter().any(|field| field.name == "soupUpdates"));
+}
+
+#[test]
+fn interface_possible_types() {
+ let entity = type_meta("GraphqlSoupEntity").expect("entity interface");
+ assert_eq!(entity.kind, TypeKind::Interface);
+ assert!(
+ entity
+ .possible_types
+ .contains(&"GraphqlSoupDocument".to_owned())
+ );
+ assert!(
+ entity
+ .possible_types
+ .contains(&"GraphqlSoupForeignEntity".to_owned())
+ );
+ assert!(
+ entity
+ .possible_types
+ .contains(&"GraphqlSoupCalendarEvent".to_owned())
+ );
+ assert!(
+ entity
+ .possible_types
+ .contains(&"GraphqlSoupCrmContact".to_owned())
+ );
+ assert!(
+ entity
+ .possible_types
+ .contains(&"GraphqlSoupAgentSession".to_owned())
+ );
+ assert!(
+ entity
+ .possible_types
+ .contains(&"GraphqlSoupInitiative".to_owned())
+ );
+ assert!(
+ entity
+ .possible_types
+ .contains(&"GraphqlSoupDatabaseRow".to_owned())
+ );
+ assert_eq!(entity.possible_types.len(), 14);
+ assert!(type_matches("GraphqlSoupDocument", "GraphqlSoupEntity"));
+ assert!(type_matches("GraphqlSoupInitiative", "GraphqlSoupEntity"));
+ assert!(!type_matches("GraphqlSoupItem", "GraphqlSoupEntity"));
+}
+
+#[test]
+fn presence_of_id_convention_applied() {
+ assert_eq!(
+ type_meta("GraphqlSoupDocument").unwrap().key_fields,
+ Some(vec!["id".to_owned()])
+ );
+ // Renamed from `messageId` so the convention keys it.
+ assert_eq!(
+ type_meta("GraphqlSoupChannelMessage").unwrap().key_fields,
+ Some(vec!["id".to_owned()])
+ );
+ // Property assignments have globally unique database ids and are
+ // normalized independently from their shared definitions.
+ assert_eq!(
+ type_meta("GraphqlProperty").unwrap().key_fields,
+ Some(vec!["id".to_owned()])
+ );
+ assert!(field_meta("GraphqlProperty", "propertyDefinitionId").is_some());
+ // No id field → embedded.
+ assert_eq!(type_meta("SoupPage").unwrap().key_fields, None);
+ assert_eq!(
+ type_meta("GraphqlSoupChannelParticipant")
+ .unwrap()
+ .key_fields,
+ None
+ );
+}
+
+#[test]
+fn field_shapes() {
+ // properties: [GraphqlProperty!]!
+ let f = field_meta("GraphqlSoupDocument", "properties").unwrap();
+ assert_eq!(f.ty.name, "GraphqlProperty");
+ assert_eq!(f.ty.kind, FieldKind::Composite);
+ assert!(!f.ty.nullable && f.ty.list && !f.ty.item_nullable);
+
+ // viewedAt: String (nullable leaf)
+ let f = field_meta("GraphqlSoupDocument", "viewedAt").unwrap();
+ assert_eq!(f.ty.kind, FieldKind::Leaf);
+ assert!(f.ty.nullable && !f.ty.list);
+
+ // sourceMetadata: JSON! (opaque scalar); metadata is now the shared
+ // structured interface field.
+ let f = field_meta("GraphqlSoupForeignEntity", "sourceMetadata").unwrap();
+ assert_eq!(f.ty.kind, FieldKind::OpaqueScalar);
+ assert!(!f.ty.nullable);
+
+ // items: [GraphqlSoupEntity!]! (composite link to the entity interface)
+ let f = field_meta("SoupPage", "items").unwrap();
+ assert_eq!(f.ty.kind, FieldKind::Composite);
+ assert_eq!(f.ty.name, "GraphqlSoupEntity");
+ assert!(f.ty.list);
+}
+
+#[test]
+fn schema_hash_present() {
+ assert_eq!(SCHEMA_HASH.len(), 64);
+}
+
+#[test]
+fn rejects_unsupported_versions_duplicates_and_dangling_types() {
+ let mut artifact = bundled_schema_ref().artifact().clone();
+ artifact.format_version += 1;
+ assert!(Schema::from_artifact(artifact).is_err());
+ let mut artifact = bundled_schema_ref().artifact().clone();
+ artifact.types.push(artifact.types[0].clone());
+ assert!(Schema::from_artifact(artifact).is_err());
+ let mut artifact = bundled_schema_ref().artifact().clone();
+ let field = artifact
+ .types
+ .iter_mut()
+ .flat_map(|t| &mut t.fields)
+ .find(|f| f.ty.kind == FieldKind::Composite)
+ .unwrap();
+ field.ty.name = "MissingRuntimeType".into();
+ assert!(Schema::from_artifact(artifact).is_err());
+}
+
+#[test]
+fn merge_rejects_shape_changes_without_mutating_active_metadata() {
+ let old = bundled_schema();
+ let mut artifact = old.artifact().clone();
+ let ty = artifact
+ .types
+ .iter_mut()
+ .find(|t| t.name == "GraphqlUser")
+ .unwrap();
+ let field = ty.fields.iter_mut().find(|f| f.name != "id").unwrap();
+ field.ty.nullable = !field.ty.nullable;
+ let incoming = Schema::from_artifact(artifact).unwrap();
+ let hash = old.hash().to_owned();
+ assert!(old.merge(&incoming).is_err());
+ assert_eq!(old.hash(), hash);
+}
+
+#[test]
+fn runtime_sdl_resolves_extensions_interfaces_unions_and_field_shapes() {
+ let schema = Schema::from_sdl(
+ r#"
+ scalar JSON
+ enum Status { OPEN CLOSED }
+ interface Node { id: ID! }
+ interface Named implements Node { id: ID! name: String! }
+ type Item implements Node & Named { id: ID! name: String! status: Status! data: JSON }
+ type Embedded { value: String }
+ union Result = Item | Embedded
+ type Query { results: [Result!]! nodes: [Node] }
+ extend type Item { labels: [String!] details: Embedded }
+ "#,
+ )
+ .unwrap();
+ assert!(schema.type_matches("Item", "Node"));
+ assert!(schema.type_matches("Item", "Named"));
+ assert!(schema.type_matches("Embedded", "Result"));
+ assert_eq!(
+ schema.type_meta("Item").unwrap().key_fields,
+ Some(vec!["id".into()])
+ );
+ assert!(schema.type_meta("Embedded").unwrap().key_fields.is_none());
+ let labels = schema.field_meta("Item", "labels").unwrap().ty;
+ assert!(labels.list && labels.nullable && !labels.item_nullable);
+ let nodes = schema.field_meta("Query", "nodes").unwrap().ty;
+ assert!(nodes.list && nodes.nullable && nodes.item_nullable);
+ let results = schema.field_meta("Query", "results").unwrap().ty;
+ assert!(results.list && !results.nullable && !results.item_nullable);
+ assert_eq!(
+ schema.field_meta("Item", "status").unwrap().ty.kind,
+ FieldKind::Leaf
+ );
+ assert_eq!(
+ schema.field_meta("Item", "data").unwrap().ty.kind,
+ FieldKind::OpaqueScalar
+ );
+ assert_eq!(
+ schema.field_meta("Item", "details").unwrap().ty.kind,
+ FieldKind::Composite
+ );
+ let persisted = serde_json::to_string(schema.artifact()).unwrap();
+ assert_eq!(Schema::from_json(&persisted).unwrap().hash(), schema.hash());
+}
+
+#[test]
+fn runtime_sdl_rejects_invalid_graphql_and_unsupported_cache_shapes() {
+ for sdl in [
+ "type Query {",
+ "type Query { value: Missing }",
+ "type Query { value: String value: Int }",
+ "interface Node { id: ID! } type Item implements Node { id: String! } type Query { item: Item }",
+ "type Query { values: [[String]] }",
+ "type Query { id: ID! }",
+ "type Query { item: Item } type Item { id: ID }",
+ "type Query { item: Item } type Item { id: String! }",
+ ] {
+ assert!(Schema::from_sdl(sdl).is_err(), "accepted {sdl}");
+ }
+}
+
+#[test]
+fn runtime_sdl_identity_ignores_formatting_and_definition_order() {
+ let first = Schema::from_sdl("type Query { a: String b: Item } type Item { id: ID! }").unwrap();
+ let second =
+ Schema::from_sdl("# new bundle\ntype Item { id: ID! } type Query { b: Item, a: String }")
+ .unwrap();
+ assert_eq!(first.hash(), second.hash());
+}
diff --git a/crates/client/cache-core/src/normalize.rs b/crates/client/cache-core/src/normalize.rs
index 969b33e2cc..345448e5a4 100644
--- a/crates/client/cache-core/src/normalize.rs
+++ b/crates/client/cache-core/src/normalize.rs
@@ -5,7 +5,7 @@ use crate::document::{
FieldNode, MissingVariable, Operation, OperationKind, Selection, resolve_args, resolve_args_key,
};
use crate::entity_resolver::EntityResolverLookup;
-use crate::meta::{self, FieldKind, TypeKind};
+use crate::meta::{FieldKind, TypeKind};
use crate::value::{CacheValue, EntityKey, Record, field_key};
use serde_json::Value as Json;
use std::collections::BTreeMap;
@@ -79,21 +79,30 @@ struct WriteContext<'a, 'resolver> {
/// nested entities are normalized as usual, but operation-root fields are
/// discarded. Those roots are transient cache entry points, never read back.
pub fn normalize(
+ schema: &crate::meta::Schema,
op: &Operation,
variables: &serde_json::Map<String, Json>,
data: &Json,
) -> Result<RecordUpdates, NormalizeError> {
- Ok(normalize_with_dependencies(op, variables, data, &EntityResolverLookup::default())?.updates)
+ Ok(normalize_with_dependencies(
+ schema,
+ op,
+ variables,
+ data,
+ &EntityResolverLookup::default(),
+ )?
+ .updates)
}
/// Normalizes a response and captures the records a cache read would depend on.
pub(crate) fn normalize_with_dependencies(
+ schema: &crate::meta::Schema,
op: &Operation,
variables: &serde_json::Map<String, Json>,
data: &Json,
entity_resolvers: &EntityResolverLookup,
) -> Result<NormalizeResult, NormalizeError> {
- let root_type = operation_root_type(op)?;
+ let root_type = operation_root_type(schema, op)?;
let Json::Object(data) = data else {
return Err(NormalizeError::Shape {
type_name: root_type.to_string(),
@@ -110,6 +119,7 @@ pub(crate) fn normalize_with_dependencies(
};
let root_key = (op.kind == OperationKind::Query).then(EntityKey::root);
write_object_fields(
+ schema,
&op.selection_set,
root_type,
data,
@@ -134,10 +144,11 @@ pub(crate) fn normalize_with_dependencies(
/// Projects fields not marked `@cacheOnly` directly from a network response.
/// Cache-only branches are not traversed or cloned.
pub fn project_hydration_response(
+ schema: &crate::meta::Schema,
op: &Operation,
data: &Json,
) -> Result<Option<Json>, NormalizeError> {
- let root_type = operation_root_type(op)?;
+ let root_type = operation_root_type(schema, op)?;
let Json::Object(data) = data else {
return Err(NormalizeError::Shape {
type_name: root_type.to_string(),
@@ -145,20 +156,26 @@ pub fn project_hydration_response(
detail: "response data is not an object",
});
};
- Ok(project_object_fields(&op.selection_set, root_type, data)?.map(Json::Object))
+ Ok(project_object_fields(schema, &op.selection_set, root_type, data)?.map(Json::Object))
}
-fn operation_root_type(op: &Operation) -> Result<&'static str, NormalizeError> {
+fn operation_root_type<'schema>(
+ schema: &'schema crate::meta::Schema,
+ op: &Operation,
+) -> Result<&'schema str, NormalizeError> {
match op.kind {
- OperationKind::Query => Ok(meta::QUERY_ROOT_TYPE),
- OperationKind::Mutation => meta::MUTATION_ROOT_TYPE
+ OperationKind::Query => Ok(schema.query_root()),
+ OperationKind::Mutation => schema
+ .mutation_root()
.ok_or_else(|| NormalizeError::UnknownType("(mutation root)".to_string())),
- OperationKind::Subscription => meta::SUBSCRIPTION_ROOT_TYPE
+ OperationKind::Subscription => schema
+ .subscription_root()
.ok_or_else(|| NormalizeError::UnknownType("(subscription root)".to_string())),
}
}
fn project_object_fields(
+ schema: &crate::meta::Schema,
selections: &[Selection],
type_name: &str,
data: &serde_json::Map<String, Json>,
@@ -168,7 +185,7 @@ fn project_object_fields(
_ => type_name,
};
let mut fields = Vec::new();
- collect_fields(selections, concrete, &mut fields);
+ collect_fields(schema, selections, concrete, &mut fields);
let mut projected = serde_json::Map::new();
for field in fields {
if field.cache_only {
@@ -181,13 +198,15 @@ fn project_object_fields(
projected.insert(field.response_key.clone(), value.clone());
continue;
}
- let field_meta = meta::field_meta(concrete, &field.name).ok_or_else(|| {
+ let field_meta = schema.field_meta(concrete, &field.name).ok_or_else(|| {
NormalizeError::UnknownField {
type_name: concrete.to_string(),
field: field.name.clone(),
}
})?;
- if let Some(value) = project_value(field, field_meta.ty.name, field_meta.ty.kind, value)? {
+ if let Some(value) =
+ project_value(schema, field, field_meta.ty.name, field_meta.ty.kind, value)?
+ {
projected.insert(field.response_key.clone(), value);
}
}
@@ -195,6 +214,7 @@ fn project_object_fields(
}
fn project_value(
+ schema: &crate::meta::Schema,
field: &FieldNode,
named_type: &str,
kind: FieldKind,
@@ -202,7 +222,10 @@ fn project_value(
) -> Result<Option<Json>, NormalizeError> {
match (kind, value) {
(FieldKind::Composite, Json::Object(object)) => {
- Ok(project_object_fields(&field.selection_set, named_type, object)?.map(Json::Object))
+ Ok(
+ project_object_fields(schema, &field.selection_set, named_type, object)?
+ .map(Json::Object),
+ )
}
(FieldKind::Composite, Json::Array(items)) => {
if !field.selection_set.iter().any(selection_returns_data) {
@@ -213,7 +236,7 @@ fn project_value(
let item = match item {
Json::Null => Json::Null,
Json::Object(object) => {
- project_object_fields(&field.selection_set, named_type, object)?
+ project_object_fields(schema, &field.selection_set, named_type, object)?
.map_or_else(|| Json::Object(serde_json::Map::new()), Json::Object)
}
_ => {
@@ -256,6 +279,7 @@ fn merge_into(records: &mut RecordUpdates, key: EntityKey<'static>, record: Reco
/// Flattens fragments applicable to `concrete_type` and visits each field.
fn collect_fields<'a>(
+ schema: &crate::meta::Schema,
selections: &'a [Selection],
concrete_type: &str,
out: &mut Vec<&'a FieldNode>,
@@ -269,10 +293,10 @@ fn collect_fields<'a>(
} => {
let applies = match type_condition {
None => true,
- Some(cond) => meta::type_matches(concrete_type, cond),
+ Some(cond) => schema.type_matches(concrete_type, cond),
};
if applies {
- collect_fields(selection_set, concrete_type, out);
+ collect_fields(schema, selection_set, concrete_type, out);
}
}
}
@@ -283,6 +307,7 @@ fn collect_fields<'a>(
/// record's or embedded object's field map), normalizing children into
/// `records`.
fn write_object_fields(
+ schema: &crate::meta::Schema,
selections: &[Selection],
type_name: &str,
data: &serde_json::Map<String, Json>,
@@ -308,17 +333,19 @@ fn write_object_fields(
);
let mut fields = Vec::new();
- collect_fields(selections, concrete, &mut fields);
+ collect_fields(schema, selections, concrete, &mut fields);
for f in fields {
if f.name == "__typename" {
continue; // handled above
}
let fmeta =
- meta::field_meta(concrete, &f.name).ok_or_else(|| NormalizeError::UnknownField {
- type_name: concrete.to_string(),
- field: f.name.clone(),
- })?;
+ schema
+ .field_meta(concrete, &f.name)
+ .ok_or_else(|| NormalizeError::UnknownField {
+ type_name: concrete.to_string(),
+ field: f.name.clone(),
+ })?;
let args = resolve_args_key(f, context.variables)?;
let storage_key = field_key(&f.name, args.as_deref());
if let Some(owner) = owner {
@@ -336,12 +363,20 @@ fn write_object_fields(
continue;
};
- let cache_value = write_value(f, fmeta.ty.name, fmeta.ty.kind, value, owner, context)
- .map_err(|detail| NormalizeError::Shape {
- type_name: concrete.to_string(),
- field: f.name.clone(),
- detail,
- })??;
+ let cache_value = write_value(
+ schema,
+ f,
+ fmeta.ty.name,
+ fmeta.ty.kind,
+ value,
+ owner,
+ context,
+ )
+ .map_err(|detail| NormalizeError::Shape {
+ type_name: concrete.to_string(),
+ field: f.name.clone(),
+ detail,
+ })??;
if let Some(resolver) = context.dependencies.entity_resolvers.get(concrete, &f.name) {
let expected_key = resolve_args(f, context.variables)
@@ -365,6 +400,7 @@ fn write_object_fields(
/// detail); inner carries nested structured errors.
#[allow(clippy::type_complexity)]
fn write_value(
+ schema: &crate::meta::Schema,
field: &FieldNode,
named_type: &str,
kind: FieldKind,
@@ -377,7 +413,7 @@ fn write_value(
Json::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
- match write_value(field, named_type, kind, item, owner, context)? {
+ match write_value(schema, field, named_type, kind, item, owner, context)? {
Ok(v) => out.push(v),
Err(e) => return Ok(Err(e)),
}
@@ -403,7 +439,7 @@ fn write_value(
FieldKind::OpaqueScalar => Ok(CacheValue::opaque(value)),
FieldKind::Leaf => return Err("expected scalar, got object"),
FieldKind::Composite => {
- match normalize_object(field, named_type, obj, owner, context) {
+ match normalize_object(schema, field, named_type, obj, owner, context) {
Ok(v) => Ok(v),
Err(e) => return Ok(Err(e)),
}
@@ -415,13 +451,15 @@ fn write_value(
/// Normalizes a composite response object: either into its own record
/// (keyable → `Ref`) or an embedded object value.
fn normalize_object(
+ schema: &crate::meta::Schema,
field: &FieldNode,
named_type: &str,
obj: &serde_json::Map<String, Json>,
owner: Option<&EntityKey<'static>>,
context: &mut WriteContext<'_, '_>,
) -> Result<CacheValue, NormalizeError> {
- let named_meta = meta::type_meta(named_type)
+ let named_meta = schema
+ .type_meta(named_type)
.ok_or_else(|| NormalizeError::UnknownType(named_type.to_string()))?;
let concrete: &str = match obj.get("__typename") {
@@ -433,14 +471,15 @@ fn normalize_object(
});
}
};
- let concrete_meta = meta::type_meta(concrete)
+ let concrete_meta = schema
+ .type_meta(concrete)
.ok_or_else(|| NormalizeError::UnknownType(concrete.to_string()))?;
- match concrete_meta.key_fields {
+ match &concrete_meta.key_fields {
Some(key_fields) => {
let mut key_values = Vec::with_capacity(key_fields.len());
for kf in key_fields {
- let v = match obj.get(*kf) {
+ let v = match obj.get(kf) {
Some(Json::String(s)) => s.clone(),
Some(Json::Number(n)) => n.to_string(),
_ => {
@@ -458,6 +497,7 @@ fn normalize_object(
);
let mut record = Record::default();
write_object_fields(
+ schema,
&field.selection_set,
concrete,
obj,
@@ -471,6 +511,7 @@ fn normalize_object(
None => {
let mut embedded = BTreeMap::new();
write_object_fields(
+ schema,
&field.selection_set,
concrete,
obj,
diff --git a/crates/client/cache-core/src/query_inspection.rs b/crates/client/cache-core/src/query_inspection.rs
index 7fb8349c52..4fe58e50e7 100644
--- a/crates/client/cache-core/src/query_inspection.rs
+++ b/crates/client/cache-core/src/query_inspection.rs
@@ -4,7 +4,7 @@
//! without exposing normalized entity or field keys to host callers.
use crate::document::{ArgValue, FieldNode, Operation, OperationKind, Selection, resolve_args_key};
-use crate::meta::{self, FieldKind};
+use crate::meta::FieldKind;
use crate::query_path::{
possible_selected_fields, selected_field, selected_storage_key, selected_type,
};
@@ -110,6 +110,7 @@ pub(crate) enum OwnerResolution<'records, 'selection> {
/// Validates the query-rooted path and variable recoverability constraints.
pub(crate) fn prepare(
+ schema: &crate::meta::Schema,
operation: &Operation,
path: &[String],
) -> Result<PreparedInspection, QueryInspectionError> {
@@ -121,11 +122,11 @@ pub(crate) fn prepare(
}
let mut selections = operation.selection_set.as_slice();
- let mut type_name = meta::QUERY_ROOT_TYPE;
+ let mut type_name = schema.query_root();
let mut final_variables = BTreeSet::new();
for (index, response_key) in path.iter().enumerate() {
let mut fields = Vec::new();
- possible_selected_fields(selections, type_name, response_key, &mut fields);
+ possible_selected_fields(schema, selections, type_name, response_key, &mut fields);
let field = match fields.as_slice() {
[] => {
return Err(QueryInspectionError::UnselectedField {
@@ -150,7 +151,7 @@ pub(crate) fn prepare(
return Err(QueryInspectionError::VariablePrefix(response_key.clone()));
}
- let Some(metadata) = meta::field_meta(type_name, &field.name) else {
+ let Some(metadata) = schema.field_meta(type_name, &field.name) else {
return Err(QueryInspectionError::UnselectedField {
type_name: type_name.to_string(),
field: response_key.clone(),
@@ -183,20 +184,23 @@ pub(crate) fn prepare(
/// Resolves the record/object that owns the final selected field.
pub(crate) fn resolve_owner<'records, 'selection>(
+ schema: &crate::meta::Schema,
records: &'records HashMap<EntityKey<'static>, Record>,
operation: &'selection Operation,
path: &[String],
) -> Result<OwnerResolution<'records, 'selection>, QueryInspectionError> {
resolve_record_owner(
+ schema,
records,
EntityKey::root(),
- meta::QUERY_ROOT_TYPE,
+ schema.query_root(),
&operation.selection_set,
path,
)
}
fn resolve_record_owner<'records, 'selection>(
+ schema: &crate::meta::Schema,
records: &'records HashMap<EntityKey<'static>, Record>,
key: EntityKey<'records>,
declared_type: &str,
@@ -207,10 +211,11 @@ fn resolve_record_owner<'records, 'selection>(
return Ok(OwnerResolution::NeedRecord(key));
};
let concrete = record.typename().unwrap_or(declared_type);
- resolve_fields_owner(records, &record.fields, concrete, selections, path)
+ resolve_fields_owner(schema, records, &record.fields, concrete, selections, path)
}
fn resolve_fields_owner<'records, 'selection>(
+ schema: &crate::meta::Schema,
records: &'records HashMap<EntityKey<'static>, Record>,
fields: &'records BTreeMap<String, CacheValue>,
concrete: &str,
@@ -218,7 +223,7 @@ fn resolve_fields_owner<'records, 'selection>(
path: &[String],
) -> Result<OwnerResolution<'records, 'selection>, QueryInspectionError> {
let response_key = &path[0];
- let Some(field) = selected_field(selections, concrete, response_key) else {
+ let Some(field) = selected_field(schema, selections, concrete, response_key) else {
return Ok(OwnerResolution::Absent);
};
if path.len() == 1 {
@@ -230,13 +235,15 @@ fn resolve_fields_owner<'records, 'selection>(
let Some(value) = fields.get(&storage_key) else {
return Ok(OwnerResolution::Absent);
};
- let next_type =
- selected_type(concrete, field).ok_or_else(|| QueryInspectionError::UnselectedField {
+ let next_type = selected_type(schema, concrete, field).ok_or_else(|| {
+ QueryInspectionError::UnselectedField {
type_name: concrete.to_string(),
field: response_key.clone(),
- })?;
+ }
+ })?;
match value {
CacheValue::Ref(key) => resolve_record_owner(
+ schema,
records,
key.borrowed(),
next_type,
@@ -251,7 +258,14 @@ fn resolve_fields_owner<'records, 'selection>(
_ => None,
})
.unwrap_or(next_type);
- resolve_fields_owner(records, object, concrete, &field.selection_set, &path[1..])
+ resolve_fields_owner(
+ schema,
+ records,
+ object,
+ concrete,
+ &field.selection_set,
+ &path[1..],
+ )
}
CacheValue::Null => Ok(OwnerResolution::Absent),
_ => Err(QueryInspectionError::WrongShape),
diff --git a/crates/client/cache-core/src/query_inspection/test.rs b/crates/client/cache-core/src/query_inspection/test.rs
index 0eaa554ffb..a507d28bf6 100644
--- a/crates/client/cache-core/src/query_inspection/test.rs
+++ b/crates/client/cache-core/src/query_inspection/test.rs
@@ -21,6 +21,7 @@ fn concrete_union_member_outside_selected_fragment_is_absent() {
let records = HashMap::new();
let result = resolve_fields_owner(
+ crate::meta::bundled_schema_ref(),
&records,
&fields,
"GraphqlSoupChannel",
diff --git a/crates/client/cache-core/src/query_path.rs b/crates/client/cache-core/src/query_path.rs
index 8dde8bd2a0..55498c833e 100644
--- a/crates/client/cache-core/src/query_path.rs
+++ b/crates/client/cache-core/src/query_path.rs
@@ -1,7 +1,6 @@
//! Shared GraphQL response-path helpers used by query-rooted cache APIs.
use crate::document::{FieldNode, MissingVariable, Selection, resolve_args_key};
-use crate::meta;
use crate::value::{FieldKey, field_key};
use serde_json::Value as Json;
@@ -11,6 +10,7 @@ use serde_json::Value as Json;
/// patches retain their existing first-match behavior, while inspection
/// performs a separate ambiguity check before traversal.
pub(crate) fn selected_field<'a>(
+ schema: &crate::meta::Schema,
selections: &'a [Selection],
concrete: &str,
response_key: &str,
@@ -24,9 +24,9 @@ pub(crate) fn selected_field<'a>(
selection_set,
} if type_condition
.as_deref()
- .is_none_or(|condition| meta::type_matches(concrete, condition)) =>
+ .is_none_or(|condition| schema.type_matches(concrete, condition)) =>
{
- if let Some(field) = selected_field(selection_set, concrete, response_key) {
+ if let Some(field) = selected_field(schema, selection_set, concrete, response_key) {
return Some(field);
}
}
@@ -41,6 +41,7 @@ pub(crate) fn selected_field<'a>(
/// Unlike [`selected_field`], this treats abstract type overlaps as possible
/// so inspection can reject ambiguous paths before consulting cache data.
pub(crate) fn possible_selected_fields<'a>(
+ schema: &crate::meta::Schema,
selections: &'a [Selection],
type_name: &str,
response_key: &str,
@@ -55,23 +56,23 @@ pub(crate) fn possible_selected_fields<'a>(
selection_set,
} if type_condition
.as_deref()
- .is_none_or(|condition| types_overlap(type_name, condition)) =>
+ .is_none_or(|condition| types_overlap(schema, type_name, condition)) =>
{
- possible_selected_fields(selection_set, type_name, response_key, out);
+ possible_selected_fields(schema, selection_set, type_name, response_key, out);
}
Selection::Fragment { .. } => {}
}
}
}
-fn types_overlap(left: &str, right: &str) -> bool {
- if left == right || meta::type_matches(left, right) || meta::type_matches(right, left) {
+fn types_overlap(schema: &crate::meta::Schema, left: &str, right: &str) -> bool {
+ if left == right || schema.type_matches(left, right) || schema.type_matches(right, left) {
return true;
}
- let Some(left) = meta::type_meta(left) else {
+ let Some(left) = schema.type_meta(left) else {
return false;
};
- let Some(right) = meta::type_meta(right) else {
+ let Some(right) = schema.type_meta(right) else {
return false;
};
left.possible_types
@@ -89,6 +90,12 @@ pub(crate) fn selected_storage_key(
}
/// Returns the named schema type selected by `field` on `concrete`.
-pub(crate) fn selected_type(concrete: &str, field: &FieldNode) -> Option<&'static str> {
- meta::field_meta(concrete, &field.name).map(|metadata| metadata.ty.name)
+pub(crate) fn selected_type<'schema>(
+ schema: &'schema crate::meta::Schema,
+ concrete: &str,
+ field: &FieldNode,
+) -> Option<&'schema str> {
+ schema
+ .field_meta(concrete, &field.name)
+ .map(|metadata| metadata.ty.name)
}
diff --git a/crates/client/cache-core/src/record_selection.rs b/crates/client/cache-core/src/record_selection.rs
index 1a1aabe0c3..8d6ec780c1 100644
--- a/crates/client/cache-core/src/record_selection.rs
+++ b/crates/client/cache-core/src/record_selection.rs
@@ -7,7 +7,7 @@
pub mod cache;
use crate::document::{ArgValue, Document, DocumentError, FieldNode, Selection};
-use crate::meta::{self, FieldKind, TypeKind};
+use crate::meta::{FieldKind, TypeKind};
use crate::value::EntityKey;
use serde::{Deserialize, Serialize};
use serde_json::Value as Json;
@@ -26,21 +26,26 @@ pub struct RecordSelection {
impl RecordSelection {
/// Parses and validates a named fragment document.
- pub fn parse(document: &str, fragment_name: &str) -> Result<Self, RecordSelectionError> {
+ pub fn parse(
+ schema: &crate::meta::Schema,
+ document: &str,
+ fragment_name: &str,
+ ) -> Result<Self, RecordSelectionError> {
let document = Document::parse(document)?;
for fragment in &document.fragments {
- concrete_type_names(&fragment.type_condition)?;
- validate_selections(&fragment.selection_set, &fragment.type_condition)?;
+ concrete_type_names(schema, &fragment.type_condition)?;
+ validate_selections(schema, &fragment.selection_set, &fragment.type_condition)?;
}
let fragment = document.fragment(fragment_name)?;
- let type_names = concrete_type_names(&fragment.type_condition)?;
+ let type_names = concrete_type_names(schema, &fragment.type_condition)?;
if type_names.is_empty() {
return Err(RecordSelectionError::NoConcreteTypes(
fragment.type_condition.clone(),
));
}
for type_name in &type_names {
- let metadata = meta::type_meta(type_name)
+ let metadata = schema
+ .type_meta(type_name)
.ok_or_else(|| RecordSelectionError::UnknownType(type_name.clone()))?;
if metadata.kind != TypeKind::Object || metadata.key_fields.is_none() {
return Err(RecordSelectionError::NotNormalized(type_name.clone()));
@@ -109,8 +114,12 @@ pub enum RecordSelectionError {
InvalidKey,
}
-fn concrete_type_names(type_name: &str) -> Result<Vec<String>, RecordSelectionError> {
- let metadata = meta::type_meta(type_name)
+fn concrete_type_names(
+ schema: &crate::meta::Schema,
+ type_name: &str,
+) -> Result<Vec<String>, RecordSelectionError> {
+ let metadata = schema
+ .type_meta(type_name)
.ok_or_else(|| RecordSelectionError::UnknownType(type_name.to_string()))?;
let mut names = match metadata.kind {
TypeKind::Object => vec![type_name.to_string()],
@@ -126,21 +135,23 @@ fn concrete_type_names(type_name: &str) -> Result<Vec<String>, RecordSelectionEr
}
fn validate_selections(
+ schema: &crate::meta::Schema,
selections: &[Selection],
parent_type: &str,
) -> Result<(), RecordSelectionError> {
for selection in selections {
match selection {
- Selection::Field(field) => validate_field(field, parent_type)?,
+ Selection::Field(field) => validate_field(schema, field, parent_type)?,
Selection::Fragment {
type_condition,
selection_set,
} => match type_condition {
- None => validate_selections(selection_set, parent_type)?,
+ None => validate_selections(schema, selection_set, parent_type)?,
Some(condition) => {
- let parent_types: BTreeSet<_> =
- concrete_type_names(parent_type)?.into_iter().collect();
- let condition_types = concrete_type_names(condition)?;
+ let parent_types: BTreeSet<_> = concrete_type_names(schema, parent_type)?
+ .into_iter()
+ .collect();
+ let condition_types = concrete_type_names(schema, condition)?;
if !condition_types
.iter()
.any(|type_name| parent_types.contains(type_name))
@@ -150,7 +161,7 @@ fn validate_selections(
parent: parent_type.to_string(),
});
}
- validate_selections(selection_set, condition)?;
+ validate_selections(schema, selection_set, condition)?;
}
},
}
@@ -158,7 +169,11 @@ fn validate_selections(
Ok(())
}
-fn validate_field(field: &FieldNode, parent_type: &str) -> Result<(), RecordSelectionError> {
+fn validate_field(
+ schema: &crate::meta::Schema,
+ field: &FieldNode,
+ parent_type: &str,
+) -> Result<(), RecordSelectionError> {
for (_, value) in &field.arguments {
if let Some(variable) = referenced_variable(value) {
return Err(RecordSelectionError::UnboundVariable(variable.to_string()));
@@ -174,7 +189,7 @@ fn validate_field(field: &FieldNode, parent_type: &str) -> Result<(), RecordSele
});
}
- let metadata = meta::field_meta(parent_type, &field.name).ok_or_else(|| {
+ let metadata = schema.field_meta(parent_type, &field.name).ok_or_else(|| {
RecordSelectionError::UnknownField {
type_name: parent_type.to_string(),
field: field.name.clone(),
@@ -187,7 +202,7 @@ fn validate_field(field: &FieldNode, parent_type: &str) -> Result<(), RecordSele
field: field.name.clone(),
})
}
- FieldKind::Composite => validate_selections(&field.selection_set, metadata.ty.name),
+ FieldKind::Composite => validate_selections(schema, &field.selection_set, metadata.ty.name),
FieldKind::Leaf | FieldKind::OpaqueScalar if !field.selection_set.is_empty() => {
Err(RecordSelectionError::InvalidFieldShape {
type_name: parent_type.to_string(),
diff --git a/crates/client/cache-core/src/record_selection/cache.rs b/crates/client/cache-core/src/record_selection/cache.rs
index c1875ed3e5..04f74079f4 100644
--- a/crates/client/cache-core/src/record_selection/cache.rs
+++ b/crates/client/cache-core/src/record_selection/cache.rs
@@ -7,7 +7,7 @@ const CAPACITY: usize = 128;
/// Reuses successful fragment plans by document text and fragment name.
pub struct RecordSelectionCache {
- plans: LruCache<(String, String), Arc<RecordSelection>>,
+ plans: LruCache<(String, String, String), Arc<RecordSelection>>,
}
impl Default for RecordSelectionCache {
@@ -22,14 +22,15 @@ impl RecordSelectionCache {
/// Returns a validated plan, parsing only on a cache miss.
pub fn get(
&mut self,
+ schema: &crate::meta::Schema,
document: String,
fragment: String,
) -> Result<Arc<RecordSelection>, RecordSelectionError> {
- let key = (document, fragment);
+ let key = (document, fragment, schema.hash().to_owned());
if let Some(selection) = self.plans.get(&key) {
return Ok(Arc::clone(selection));
}
- let selection = Arc::new(RecordSelection::parse(&key.0, &key.1)?);
+ let selection = Arc::new(RecordSelection::parse(schema, &key.0, &key.1)?);
self.plans.put(key, Arc::clone(&selection));
Ok(selection)
}
diff --git a/crates/client/cache-core/src/record_selection/cache/test.rs b/crates/client/cache-core/src/record_selection/cache/test.rs
index 0f7f0c8410..83315d0d2f 100644
--- a/crates/client/cache-core/src/record_selection/cache/test.rs
+++ b/crates/client/cache-core/src/record_selection/cache/test.rs
@@ -5,19 +5,46 @@ fn plans_are_reused_but_both_document_and_fragment_are_part_of_identity() {
let mut selections = RecordSelectionCache::default();
let document =
"fragment A on GraphqlSoupDocument { id } fragment B on GraphqlSoupDocument { name }";
- let first = selections.get(document.into(), "A".into()).unwrap();
- let again = selections.get(document.into(), "A".into()).unwrap();
+ let first = selections
+ .get(
+ crate::meta::bundled_schema_ref(),
+ document.into(),
+ "A".into(),
+ )
+ .unwrap();
+ let again = selections
+ .get(
+ crate::meta::bundled_schema_ref(),
+ document.into(),
+ "A".into(),
+ )
+ .unwrap();
assert!(Arc::ptr_eq(&first, &again));
- let other = selections.get(document.into(), "B".into()).unwrap();
+ let other = selections
+ .get(
+ crate::meta::bundled_schema_ref(),
+ document.into(),
+ "B".into(),
+ )
+ .unwrap();
assert!(!Arc::ptr_eq(&first, &other));
let changed = selections
.get(
+ crate::meta::bundled_schema_ref(),
"fragment A on GraphqlSoupDocument { name }".into(),
"A".into(),
)
.unwrap();
assert!(!Arc::ptr_eq(&first, &changed));
- assert!(selections.get(document.into(), "Missing".into()).is_err());
+ assert!(
+ selections
+ .get(
+ crate::meta::bundled_schema_ref(),
+ document.into(),
+ "Missing".into()
+ )
+ .is_err()
+ );
assert_eq!(selections.plans.len(), 3);
}
@@ -25,18 +52,40 @@ fn plans_are_reused_but_both_document_and_fragment_are_part_of_identity() {
fn eviction_is_bounded_and_keeps_recent_plans() {
let mut selections = RecordSelectionCache::default();
let document = |i| format!("fragment F{i} on GraphqlSoupDocument {{ id }}");
- let first = selections.get(document(0), "F0".into()).unwrap();
+ let first = selections
+ .get(crate::meta::bundled_schema_ref(), document(0), "F0".into())
+ .unwrap();
for i in 1..CAPACITY {
- selections.get(document(i), format!("F{i}")).unwrap();
+ selections
+ .get(
+ crate::meta::bundled_schema_ref(),
+ document(i),
+ format!("F{i}"),
+ )
+ .unwrap();
}
assert!(Arc::ptr_eq(
&first,
- &selections.get(document(0), "F0".into()).unwrap()
+ &selections
+ .get(crate::meta::bundled_schema_ref(), document(0), "F0".into())
+ .unwrap()
));
selections
- .get(document(CAPACITY), format!("F{CAPACITY}"))
+ .get(
+ crate::meta::bundled_schema_ref(),
+ document(CAPACITY),
+ format!("F{CAPACITY}"),
+ )
.unwrap();
assert_eq!(selections.plans.len(), CAPACITY);
- assert!(selections.plans.contains(&(document(0), "F0".into())));
- assert!(!selections.plans.contains(&(document(1), "F1".into())));
+ assert!(selections.plans.contains(&(
+ document(0),
+ "F0".into(),
+ crate::meta::bundled_schema_ref().hash().to_owned()
+ )));
+ assert!(!selections.plans.contains(&(
+ document(1),
+ "F1".into(),
+ crate::meta::bundled_schema_ref().hash().to_owned()
+ )));
}
diff --git a/crates/client/cache-core/src/record_selection/test.rs b/crates/client/cache-core/src/record_selection/test.rs
index 1dece9bb3c..004d888eb7 100644
--- a/crates/client/cache-core/src/record_selection/test.rs
+++ b/crates/client/cache-core/src/record_selection/test.rs
@@ -3,6 +3,7 @@ use super::*;
#[test]
fn accepts_fragment_only_object_document() {
let selection = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
r#"
fragment SoupItemFields on GraphqlSoupDocument {
documentId: id
@@ -20,6 +21,7 @@ fn accepts_fragment_only_object_document() {
#[test]
fn accepts_normalized_union_selection() {
let selection = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
r#"
fragment SoupEntities on GraphqlSoupEntity {
__typename
@@ -45,14 +47,19 @@ fn accepts_normalized_union_selection() {
#[test]
fn rejects_embedded_root_and_unbound_variables() {
- let embedded =
- RecordSelection::parse("fragment Page on SoupPage { nextCursor }", "Page").unwrap_err();
+ let embedded = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
+ "fragment Page on SoupPage { nextCursor }",
+ "Page",
+ )
+ .unwrap_err();
assert!(matches!(
embedded,
RecordSelectionError::NotNormalized(ref name) if name == "SoupPage"
));
let variable = RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
r#"fragment UserSoup on GraphqlUser {
soup(input: $input) { nextCursor }
}"#,
@@ -68,17 +75,26 @@ fn rejects_embedded_root_and_unbound_variables() {
#[test]
fn rejects_unknown_fragment_and_type() {
assert!(matches!(
- RecordSelection::parse("fragment Item on GraphqlSoupDocument { id }", "Missing"),
+ RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
+ "fragment Item on GraphqlSoupDocument { id }",
+ "Missing"
+ ),
Err(RecordSelectionError::Document(
DocumentError::UnknownFragment(_)
))
));
assert!(matches!(
- RecordSelection::parse("fragment Item on MissingType { id }", "Item"),
+ RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
+ "fragment Item on MissingType { id }",
+ "Item"
+ ),
Err(RecordSelectionError::UnknownType(_))
));
assert!(matches!(
RecordSelection::parse(
+ crate::meta::bundled_schema_ref(),
"fragment Item on GraphqlSoupDocument { id } fragment Unused on MissingType { id }",
"Item",
),
diff --git a/crates/client/cache-core/tests/email_draft_optimistic.rs b/crates/client/cache-core/tests/email_draft_optimistic.rs
index 0f99bfe937..967556abd4 100644
--- a/crates/client/cache-core/tests/email_draft_optimistic.rs
+++ b/crates/client/cache-core/tests/email_draft_optimistic.rs
@@ -616,6 +616,7 @@ fn identity_binding_keeps_newer_edits_readable_across_commit_and_restart() {
"newer body"
);
let selection = cache_core::record_selection::RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
"fragment Draft on GraphqlSoupEmailMessage { id bodyHtmlSanitized }",
"Draft",
)
diff --git a/crates/client/cache-core/tests/identity_commit.rs b/crates/client/cache-core/tests/identity_commit.rs
index cd8fe38957..2f5a44cb37 100644
--- a/crates/client/cache-core/tests/identity_commit.rs
+++ b/crates/client/cache-core/tests/identity_commit.rs
@@ -545,6 +545,7 @@ fn cross_inbox_draft_settlement_preserves_source_thread_and_rebases_queued_edits
let mut engine = Engine::new(engine.into_storage());
let selection = cache_core::record_selection::RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
"fragment Draft on GraphqlSoupEmailMessage { id subject }",
"Draft",
)
diff --git a/crates/client/cache-core/tests/property_assignment_optimistic.rs b/crates/client/cache-core/tests/property_assignment_optimistic.rs
index fa79958bc7..4a7665d26b 100644
--- a/crates/client/cache-core/tests/property_assignment_optimistic.rs
+++ b/crates/client/cache-core/tests/property_assignment_optimistic.rs
@@ -177,7 +177,12 @@ fn cold_parent_needs_no_query_root_or_cached_page_for_enqueue_and_replay() {
let mut engine = Engine::new(storage);
let txn = enqueue(&mut engine, "urgent", 1).await;
let mut engine = Engine::new(engine.into_storage());
- let selection = RecordSelection::parse(FRAGMENT, "AssignmentParent").unwrap();
+ let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
+ FRAGMENT,
+ "AssignmentParent",
+ )
+ .unwrap();
let key = EntityKey("GraphqlSoupDocument:task-1".into());
let records = engine
.read_records_by_keys(&selection, std::slice::from_ref(&key))
@@ -244,7 +249,12 @@ fn pending_assignment_replays_after_its_original_page_is_evicted() {
pending
);
let mut engine = Engine::new(engine.into_storage());
- let selection = RecordSelection::parse(FRAGMENT, "AssignmentParent").unwrap();
+ let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
+ FRAGMENT,
+ "AssignmentParent",
+ )
+ .unwrap();
let keys = [EntityKey("GraphqlSoupDocument:task-1".into())];
let records = engine
.read_records_by_keys(&selection, &keys)
diff --git a/crates/client/cache-core/tests/record_selection.rs b/crates/client/cache-core/tests/record_selection.rs
index ac794c3169..d0822e4cab 100644
--- a/crates/client/cache-core/tests/record_selection.rs
+++ b/crates/client/cache-core/tests/record_selection.rs
@@ -88,7 +88,12 @@ fn projects_cold_links_and_skips_incomplete_explicit_keys() {
.await
.unwrap();
let mut engine = Engine::with_capacity(storage, 1);
- let selection = RecordSelection::parse(ITEM_FRAGMENT, "SoupItemFields").unwrap();
+ let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
+ ITEM_FRAGMENT,
+ "SoupItemFields",
+ )
+ .unwrap();
let selected = engine
.read_records_by_keys(
@@ -126,9 +131,12 @@ fn explicit_key_projection_preserves_rank_order_without_scanning() {
.await
.unwrap();
let mut engine = Engine::new(storage);
- let selection =
- RecordSelection::parse("fragment Item on GraphqlSoupDocument { id name }", "Item")
- .unwrap();
+ let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
+ "fragment Item on GraphqlSoupDocument { id name }",
+ "Item",
+ )
+ .unwrap();
let selected = engine
.read_records_by_keys(
@@ -194,6 +202,7 @@ fn reads_schema_incomplete_objects_in_explicit_input_order() {
.unwrap();
let mut engine = Engine::new(storage);
let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
r#"fragment Entity on GraphqlSoupEntity {
__typename
... on GraphqlSoupDocument { id name }
@@ -264,6 +273,7 @@ fn merges_optimistic_updates_with_cold_linked_bases() {
.unwrap();
let mut engine = Engine::with_capacity(storage, 1);
let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
r#"fragment Item on GraphqlSoupDocument {
id
properties { id propertyDefinitionId displayName }
@@ -328,6 +338,7 @@ fn includes_optimistic_only_records() {
block_on(async {
let mut engine = Engine::new(InMemoryStorage::new());
let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
"fragment Property on GraphqlProperty { id displayName }",
"Property",
)
diff --git a/crates/client/cache-core/tests/roundtrip.rs b/crates/client/cache-core/tests/roundtrip.rs
index 44763301ce..bffd342ba3 100644
--- a/crates/client/cache-core/tests/roundtrip.rs
+++ b/crates/client/cache-core/tests/roundtrip.rs
@@ -136,7 +136,13 @@ fn response_data() -> Json {
fn write(records: &mut BTreeMap<EntityKey<'static>, Record>, doc: &Document, data: &Json) {
let op = doc.operation(Some("Soup")).unwrap();
- let updates = normalize(op, &variables(), data).unwrap();
+ let updates = normalize(
+ cache_core::meta::bundled_schema_ref(),
+ op,
+ &variables(),
+ data,
+ )
+ .unwrap();
for (key, record) in updates {
records.entry(key).or_default().merge(record);
}
@@ -204,7 +210,14 @@ fn round_trip_reproduces_response() {
let op = doc.operation(Some("Soup")).unwrap();
let mut deps = BTreeSet::new();
- let outcome = denormalize(op, &variables(), &records, &mut deps).unwrap();
+ let outcome = denormalize(
+ cache_core::meta::bundled_schema_ref(),
+ op,
+ &variables(),
+ &records,
+ &mut deps,
+ )
+ .unwrap();
let ReadOutcome::Complete(data) = outcome else {
panic!("expected complete read, got {outcome:?}");
};
@@ -257,7 +270,13 @@ fn entity_update_visible_through_other_query() {
}
});
let op = rename_doc.operation(Some("Doc")).unwrap();
- let updates = normalize(op, &variables(), &rename_data).unwrap();
+ let updates = normalize(
+ cache_core::meta::bundled_schema_ref(),
+ op,
+ &variables(),
+ &rename_data,
+ )
+ .unwrap();
let mut changed = Vec::new();
for (key, record) in updates {
let entry = records.entry(key.clone()).or_default();
@@ -271,8 +290,14 @@ fn entity_update_visible_through_other_query() {
// Original query now sees the new name everywhere.
let op = doc.operation(Some("Soup")).unwrap();
let mut deps = BTreeSet::new();
- let ReadOutcome::Complete(data) = denormalize(op, &variables(), &records, &mut deps).unwrap()
- else {
+ let ReadOutcome::Complete(data) = denormalize(
+ cache_core::meta::bundled_schema_ref(),
+ op,
+ &variables(),
+ &records,
+ &mut deps,
+ )
+ .unwrap() else {
panic!("expected complete read");
};
assert_eq!(
@@ -292,7 +317,14 @@ fn different_args_are_a_miss() {
unreachable!()
};
let mut deps = BTreeSet::new();
- let outcome = denormalize(op, &other_vars, &records, &mut deps).unwrap();
+ let outcome = denormalize(
+ cache_core::meta::bundled_schema_ref(),
+ op,
+ &other_vars,
+ &records,
+ &mut deps,
+ )
+ .unwrap();
assert!(
matches!(&outcome, ReadOutcome::Miss { entity, field }
if entity.0 == "GraphqlUser:user-1" && field == r#"soup({"input":{"limit":50}})"#),
@@ -311,7 +343,14 @@ fn missing_records_reported_for_batch_fetch() {
let op = doc.operation(Some("Soup")).unwrap();
let mut deps = BTreeSet::new();
- let outcome = denormalize(op, &variables(), &records, &mut deps).unwrap();
+ let outcome = denormalize(
+ cache_core::meta::bundled_schema_ref(),
+ op,
+ &variables(),
+ &records,
+ &mut deps,
+ )
+ .unwrap();
let ReadOutcome::NeedRecords(missing) = outcome else {
panic!("expected NeedRecords, got {outcome:?}");
};
diff --git a/crates/client/cache-core/tests/runtime_schema.rs b/crates/client/cache-core/tests/runtime_schema.rs
new file mode 100644
index 0000000000..9b0f3bc750
--- /dev/null
+++ b/crates/client/cache-core/tests/runtime_schema.rs
@@ -0,0 +1,109 @@
+use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};
+use cache_core::meta::{BUNDLED_SCHEMA_SDL, Schema, bundled_schema};
+use cache_core::record_selection::RecordSelection;
+use cache_core::store::InMemoryStorage;
+use cache_core::value::EntityKey;
+use serde_json::json;
+
+fn new_schema() -> std::sync::Arc<Schema> {
+ let sdl = format!(
+ "{BUNDLED_SCHEMA_SDL}\nextend type GraphqlUser {{ runtimeLabel: String }}\nextend type {} {{ setRuntimeLabel: GraphqlUser! }}",
+ bundled_schema().mutation_root().unwrap()
+ );
+ Schema::from_sdl(&sdl).unwrap()
+}
+
+#[test]
+fn installed_binary_accepts_new_fields_and_replays_them_after_bundle_rollback() {
+ pollster::block_on(async {
+ let old = bundled_schema();
+ let new = new_schema();
+ let variables = serde_json::Map::new();
+ let query = "query { user { id runtimeLabel } }";
+ let mutation = "mutation { setRuntimeLabel { id runtimeLabel } }";
+ let data = json!({"user": {"id": "viewer", "runtimeLabel": "server"}});
+ let mut engine = Engine::with_schema(InMemoryStorage::new(), 10, old.clone());
+ assert!(
+ engine
+ .write_query(None, query, None, &variables, &data, None)
+ .await
+ .is_err()
+ );
+ let generation = engine.current_storage_generation().await.unwrap();
+ engine.install_schema(&new).unwrap();
+ engine
+ .write_query(None, query, None, &variables, &data, None)
+ .await
+ .unwrap();
+ assert!(
+ matches!(engine.read_query(None, query, None, &variables).await.unwrap(), ReadResult::Hit { data: actual } if actual == data)
+ );
+ let fragment = RecordSelection::parse(
+ engine.schema(),
+ "fragment F on GraphqlUser { id runtimeLabel }",
+ "F",
+ )
+ .unwrap();
+ assert_eq!(
+ engine
+ .read_records_by_keys(&fragment, &[EntityKey::entity("GraphqlUser", &["viewer"])])
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ let optimistic = json!({"setRuntimeLabel": {"id": "viewer", "runtimeLabel": "pending"}});
+ engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ client_metadata: None,
+ identity_bindings: &[],
+ uuid: "01900000-0000-7000-8000-000000000001",
+ query: mutation,
+ operation_name: None,
+ variables: &variables,
+ data: &optimistic,
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 1,
+ },
+ )
+ .await
+ .unwrap();
+ let saved_schema = serde_json::to_string(engine.schema().artifact()).unwrap();
+ let storage = engine.into_storage();
+ // Persisted metadata retains definitions needed by newer queued work even
+ // when the next bundle is older. No global metadata or leaked strings.
+ let schema = Schema::from_json(&saved_schema)
+ .unwrap()
+ .merge(&old)
+ .unwrap();
+ let mut reopened = Engine::with_schema(storage, 10, schema);
+ assert_eq!(
+ reopened.current_storage_generation().await.unwrap(),
+ generation
+ );
+ let read = reopened
+ .read_query(None, query, None, &variables)
+ .await
+ .unwrap();
+ assert!(
+ matches!(read, ReadResult::Hit { data } if data["user"]["runtimeLabel"] == "pending")
+ );
+ assert!(
+ reopened
+ .schema()
+ .field_meta("GraphqlUser", "runtimeLabel")
+ .is_some()
+ );
+ // A separate old engine must not accidentally use the new schema.
+ let mut isolated = Engine::with_schema(InMemoryStorage::new(), 10, old);
+ assert!(
+ isolated
+ .write_query(None, query, None, &variables, &data, None)
+ .await
+ .is_err()
+ );
+ });
+}
diff --git a/crates/client/cache-core/tests/subscription.rs b/crates/client/cache-core/tests/subscription.rs
index 715f0c233a..2eb93a668d 100644
--- a/crates/client/cache-core/tests/subscription.rs
+++ b/crates/client/cache-core/tests/subscription.rs
@@ -45,6 +45,7 @@ fn subscription_normalization_persists_entities_but_not_the_root() {
assert_eq!(operation.kind, OperationKind::Subscription);
let updates = normalize(
+ cache_core::meta::bundled_schema_ref(),
operation,
&serde_json::Map::new(),
&updated_document("Updated"),
diff --git a/crates/client/cache-turso/tests/draft_identity.rs b/crates/client/cache-turso/tests/draft_identity.rs
index c3e3684b25..190e5743a9 100644
--- a/crates/client/cache-turso/tests/draft_identity.rs
+++ b/crates/client/cache-turso/tests/draft_identity.rs
@@ -116,6 +116,7 @@ async fn read(
id: &str,
) -> Vec<cache_core::record_selection::SelectedRecord> {
let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
"fragment Draft on GraphqlSoupEmailMessage { id threadId bodyHtmlSanitized }",
"Draft",
)
@@ -129,6 +130,7 @@ async fn read(
async fn preview_visible(engine: &mut Engine<TursoStorage>) -> bool {
let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
"fragment Preview on GraphqlMailPreviewMessage { id subject }",
"Preview",
)
diff --git a/crates/client/cache-turso/tests/engine_turso.rs b/crates/client/cache-turso/tests/engine_turso.rs
index 8de57572b1..0ba4a9036c 100644
--- a/crates/client/cache-turso/tests/engine_turso.rs
+++ b/crates/client/cache-turso/tests/engine_turso.rs
@@ -140,6 +140,7 @@ fn query_identity_cold_tier_selection_and_clear_run_over_turso() {
);
let selection = RecordSelection::parse(
+ cache_core::meta::bundled_schema_ref(),
"fragment Property on GraphqlProperty { id displayName }",
"Property",
)
diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.toml
index 17a6b58579..bf97e89056 100644
--- a/crates/client/cache-wasm/Cargo.toml
+++ b/crates/client/cache-wasm/Cargo.toml
@@ -2,10 +2,8 @@
edition = "2024"
name = "cache-wasm"
publish = false
-# Rebuild for reminder return timestamps in the local Mail index.
-# Rebuild with the calendar range index and the compatibility epoch 4 storage name.
-# Expose calendarRange, calendarCommit, and uncertain calendar events on enqueue.
-version = "0.6.41"
+# Rebuild to parse frontend-supplied GraphQL SDL directly.
+version = "0.6.43"
[features]
default = []
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index ce5b0374ea..b11e77ca3b 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -571,12 +571,39 @@ fn storage_version(unversioned: &str, identity: &str) -> Option<(u32, u32, u32)>
parts.next().is_none().then_some((epoch, format, storage))
}
+thread_local! {
+ static RUNTIME_SCHEMA: std::cell::RefCell<Option<std::sync::Arc<cache_core::meta::Schema>>> = const { std::cell::RefCell::new(None) };
+}
+
+/// Parses bundle SDL once per worker, before opening its engine.
+#[wasm_bindgen(js_name = configureCacheSchema)]
+pub fn configure_cache_schema(schema_sdl: &str) -> Result<(), JsValue> {
+ let schema = cache_core::meta::Schema::from_sdl(schema_sdl).map_err(err_js)?;
+ RUNTIME_SCHEMA.with(|slot| {
+ let mut slot = slot.borrow_mut();
+ if let Some(existing) = slot.as_ref() {
+ if existing.hash() != schema.hash() {
+ return Err(err_js("schema changed within a running cache worker"));
+ }
+ } else {
+ *slot = Some(schema);
+ }
+ Ok(())
+ })
+}
+
fn build_engine(storage: TursoStorage, hot_capacity: Option<u32>) -> BrowserEngine {
let storage = wrap_storage(storage);
- match hot_capacity {
- Some(capacity) => Engine::with_capacity(storage, capacity as usize),
- None => Engine::new(storage),
- }
+ let schema = RUNTIME_SCHEMA.with(|slot| {
+ slot.borrow_mut()
+ .get_or_insert_with(cache_core::meta::bundled_schema)
+ .clone()
+ });
+ Engine::with_schema(
+ storage,
+ hot_capacity.map_or(cache_core::engine::DEFAULT_HOT_CAPACITY, |c| c as usize),
+ schema,
+ )
}
fn validate_hot_capacity(hot_capacity: Option<u32>) -> Result<(), JsValue> {
@@ -1321,9 +1348,10 @@ impl CacheEngine {
future_to_promise(async move {
let mut state = state.lock().await;
state.ensure_callable()?;
+ let schema = state.engine_mut()?.schema_snapshot();
let selection = state
.selections
- .get(document, fragment_name)
+ .get(&schema, document, fragment_name)
.map_err(err_js)?;
let keys: Vec<String> = parse_vec(keys)?;
let keys: Vec<_> = keys.into_iter().map(|key| EntityKey(key.into())).collect();
@@ -1498,14 +1526,19 @@ impl CacheEngine {
let op_id = ops.borrow_mut().intern(&registration.op_id);
(op_id, registration.entity_resolvers)
});
- let mut projections =
- authoritative_projection_mutations(&query, operation_name.as_deref(), &data)
- .map_err(err_js)?;
+ let mut projections = authoritative_projection_mutations(
+ &state.engine_mut()?.schema_snapshot(),
+ &query,
+ operation_name.as_deref(),
+ &data,
+ )
+ .map_err(err_js)?;
let reuse_stored_identity =
state.can_reuse_stored_identity(identity.as_deref()).await?;
if reuse_stored_identity {
projections.extend(
notification_projection_updates(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1518,6 +1551,7 @@ impl CacheEngine {
}
projections.extend(
soup_filter_cache_adapter::mail::projection_updates_for_write(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1529,6 +1563,7 @@ impl CacheEngine {
.map_err(|error| state.mail_projection_error(error))?,
);
let projections = soup_filter_cache_adapter::properties::augment_authoritative(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1582,14 +1617,19 @@ impl CacheEngine {
state.ensure_callable()?;
let variables = parse_variables(variables)?;
let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;
- let mut projections =
- authoritative_projection_mutations(&query, operation_name.as_deref(), &data)
- .map_err(err_js)?;
+ let mut projections = authoritative_projection_mutations(
+ &state.engine_mut()?.schema_snapshot(),
+ &query,
+ operation_name.as_deref(),
+ &data,
+ )
+ .map_err(err_js)?;
let reuse_stored_identity =
state.can_reuse_stored_identity(identity.as_deref()).await?;
if reuse_stored_identity {
projections.extend(
notification_projection_updates(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1602,6 +1642,7 @@ impl CacheEngine {
}
projections.extend(
soup_filter_cache_adapter::mail::projection_updates_for_write(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1613,6 +1654,7 @@ impl CacheEngine {
.map_err(|error| state.mail_projection_error(error))?,
);
let projections = soup_filter_cache_adapter::properties::augment_authoritative(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1697,6 +1739,7 @@ impl CacheEngine {
projection_mutations.extend(
optimistic_notification_updates(
notification_projection_updates(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1710,6 +1753,7 @@ impl CacheEngine {
);
projection_mutations.extend(soup_filter_cache_adapter::mail::optimistic_updates(
soup_filter_cache_adapter::mail::projection_updates(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1721,6 +1765,7 @@ impl CacheEngine {
));
projection_mutations.extend(
soup_filter_cache_adapter::mail::draft_optimistic_updates(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1731,6 +1776,7 @@ impl CacheEngine {
.map_err(|error| state.mail_projection_error(error))?,
);
let projection_mutations = soup_filter_cache_adapter::properties::augment_optimistic(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1956,11 +2002,16 @@ impl CacheEngine {
};
let vars = parse_variables(variables)?;
let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;
- let mut projections =
- authoritative_projection_mutations(&query, operation_name.as_deref(), &data)
- .map_err(err_js)?;
+ let mut projections = authoritative_projection_mutations(
+ &state.engine_mut()?.schema_snapshot(),
+ &query,
+ operation_name.as_deref(),
+ &data,
+ )
+ .map_err(err_js)?;
projections.extend(
notification_projection_updates(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1972,6 +2023,7 @@ impl CacheEngine {
);
projections.extend(
soup_filter_cache_adapter::mail::projection_updates(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
@@ -1982,6 +2034,7 @@ impl CacheEngine {
.map_err(|error| state.mail_projection_error(error))?,
);
let projections = soup_filter_cache_adapter::properties::augment_authoritative(
+ &state.engine_mut()?.schema_snapshot(),
state.engine_mut()?.storage(),
&query,
operation_name.as_deref(),
diff --git a/crates/soup_filter_cache_adapter/src/channels/test.rs b/crates/soup_filter_cache_adapter/src/channels/test.rs
index 295dbd3d3f..59efaf3820 100644
--- a/crates/soup_filter_cache_adapter/src/channels/test.rs
+++ b/crates/soup_filter_cache_adapter/src/channels/test.rs
@@ -41,7 +41,13 @@ fn filters(channel: Value) -> Value {
json!({"documentFilter":{"literal":{"id":nil}},"projectFilter":{"literal":{"projectIdSelf":nil}},"chatFilter":{"literal":{"chatId":nil}},"calendarEventFilter":{"literal":{"id":nil}},"emailFilter":{"tree":{"literal":{"threadId":nil}}},"channelThreadFilter":{"literal":{"threadId":nil}},"callFilter":{"literal":{"callId":nil}},"crmCompanyFilter":{"literal":{"id":nil}},"foreignEntityFilter":{"literal":{"id":nil}},"channelFilter":channel})
}
async fn write<S: PredicateIndexStorage>(engine: &mut Engine<S>, query: &str, data: &Value) {
- let projections = authoritative_projection_mutations(query, None, data).unwrap();
+ let projections = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ query,
+ None,
+ data,
+ )
+ .unwrap();
engine
.write_query_with_registration_and_projections(
None,
@@ -74,7 +80,13 @@ async fn keys<S: PredicateIndexStorage>(engine: &mut Engine<S>, filter: Value) -
#[test]
fn canonical_channel_fields_and_aliased_team_id_form_v4_snapshots() {
- let projections = authoritative_projection_mutations(QUERY, None, &data(vec![row(1)])).unwrap();
+ let projections = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ QUERY,
+ None,
+ &data(vec![row(1)]),
+ )
+ .unwrap();
let [ProjectionMutation::Replace(document)] = projections.as_slice() else {
panic!("complete channel")
};
@@ -113,7 +125,7 @@ fn channel_aliases_preserve_identity_and_reject_conflicting_nullable_facts() {
aliased["capsule"] = aliased["cacheProjection"].take();
aliased.as_object_mut().unwrap().remove("cacheProjection");
assert!(
- matches!(authoritative_projection_mutations(&query, None, &data(vec![aliased])).unwrap().as_slice(), [ProjectionMutation::Replace(document)] if document.record_key == key(1))
+ matches!(authoritative_projection_mutations(cache_core::meta::bundled_schema_ref(), &query, None, &data(vec![aliased])).unwrap().as_slice(), [ProjectionMutation::Replace(document)] if document.record_key == key(1))
);
let duplicate = QUERY.replace(
@@ -123,9 +135,14 @@ fn channel_aliases_preserve_identity_and_reject_conflicting_nullable_facts() {
let mut conflict = row(1);
conflict["otherTeam"] = json!(id(11));
assert!(matches!(
- authoritative_projection_mutations(&duplicate, None, &data(vec![conflict]))
- .unwrap()
- .as_slice(),
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ &duplicate,
+ None,
+ &data(vec![conflict])
+ )
+ .unwrap()
+ .as_slice(),
[ProjectionMutation::MarkIncomplete { .. }]
));
}
@@ -144,8 +161,13 @@ fn organization_ids_preserve_the_signed_64_bit_projection_domain() {
assert_eq!(organization(&value), Ok(Some(organization_id)));
let mut channel = row(1);
channel["organizationId"] = value.clone();
- let updates =
- authoritative_projection_mutations(QUERY, None, &data(vec![channel])).unwrap();
+ let updates = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ QUERY,
+ None,
+ &data(vec![channel]),
+ )
+ .unwrap();
let [ProjectionMutation::Replace(document)] = updates.as_slice() else {
panic!("complete i64 organization snapshot: {organization_id}")
};
@@ -206,9 +228,14 @@ fn partial_and_invalid_channel_snapshots_do_not_invent_completeness() {
incomplete.as_object_mut().unwrap().remove(field);
assert!(
matches!(
- authoritative_projection_mutations(QUERY, None, &data(vec![incomplete]))
- .unwrap()
- .as_slice(),
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ QUERY,
+ None,
+ &data(vec![incomplete])
+ )
+ .unwrap()
+ .as_slice(),
[ProjectionMutation::MarkIncomplete { .. }]
),
"{field}"
@@ -223,9 +250,14 @@ fn partial_and_invalid_channel_snapshots_do_not_invent_completeness() {
let mut malformed = row(1);
malformed[field] = invalid;
assert!(matches!(
- authoritative_projection_mutations(QUERY, None, &data(vec![malformed]))
- .unwrap()
- .as_slice(),
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ QUERY,
+ None,
+ &data(vec![malformed])
+ )
+ .unwrap()
+ .as_slice(),
[ProjectionMutation::MarkIncomplete { .. }]
));
}
@@ -233,9 +265,14 @@ fn partial_and_invalid_channel_snapshots_do_not_invent_completeness() {
nullable["channelTeamId"] = Value::Null;
nullable["organizationId"] = Value::Null;
assert!(matches!(
- authoritative_projection_mutations(QUERY, None, &data(vec![nullable]))
- .unwrap()
- .as_slice(),
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ QUERY,
+ None,
+ &data(vec![nullable])
+ )
+ .unwrap()
+ .as_slice(),
[ProjectionMutation::Replace(_)]
));
}
@@ -347,6 +384,7 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
// A child notification update edits only its primary channel's membership.
let notification = json!({"updateNotifications":[{"id":id(101),"state":"DONE"}]});
let updates = notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
NOTIFICATION,
None,
diff --git a/crates/soup_filter_cache_adapter/src/database_rows/test.rs b/crates/soup_filter_cache_adapter/src/database_rows/test.rs
index 4bbb4754a4..ac2bf30353 100644
--- a/crates/soup_filter_cache_adapter/src/database_rows/test.rs
+++ b/crates/soup_filter_cache_adapter/src/database_rows/test.rs
@@ -18,11 +18,25 @@ const DEAL_3: &str = "70000000-0000-0000-0000-000000000003";
const CONTACT: &str = "70000000-0000-0000-0000-000000000004";
async fn write<S: PredicateIndexStorage>(engine: &mut Engine<S>, data: &Value) {
- let core = crate::authoritative_projection_mutations(QUERY, None, data).unwrap();
- let projections =
- augment_authoritative(engine.storage(), QUERY, None, &Map::new(), data, true, core)
- .await
- .unwrap();
+ let core = crate::authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ QUERY,
+ None,
+ data,
+ )
+ .unwrap();
+ let projections = augment_authoritative(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ QUERY,
+ None,
+ &Map::new(),
+ data,
+ true,
+ core,
+ )
+ .await
+ .unwrap();
engine
.write_query_with_registration_and_projections(
None,
diff --git a/crates/soup_filter_cache_adapter/src/lib.rs b/crates/soup_filter_cache_adapter/src/lib.rs
index b2db6d5b81..6d528f2a57 100644
--- a/crates/soup_filter_cache_adapter/src/lib.rs
+++ b/crates/soup_filter_cache_adapter/src/lib.rs
@@ -5,7 +5,7 @@
//! Cache crates receive only the generic query and projection IR produced here.
use cache_core::document::{Document, FieldNode, OperationKind, Selection};
-use cache_core::meta::{self, FieldKind};
+use cache_core::meta::FieldKind;
use cache_core::predicate::{ProjectionIncompleteKind, ProjectionMutation};
use graphql_soup_filter_input::materialize_graphql_filter;
use indexmap::IndexMap;
@@ -144,6 +144,7 @@ pub fn reconciliation_baseline_entry(
/// membership from an existing complete projection. A missing base remains
/// explicitly incomplete.
pub fn authoritative_projection_mutations(
+ schema: &cache_core::meta::Schema,
query: &str,
operation_name: Option<&str>,
data: &serde_json::Value,
@@ -154,11 +155,11 @@ pub fn authoritative_projection_mutations(
.operation(operation_name)
.map_err(|error| SoupFilterCacheAdapterError(error.to_string()))?;
let root_type = match operation.kind {
- OperationKind::Query => meta::QUERY_ROOT_TYPE,
- OperationKind::Mutation => meta::MUTATION_ROOT_TYPE.ok_or_else(|| {
+ OperationKind::Query => schema.query_root(),
+ OperationKind::Mutation => schema.mutation_root().ok_or_else(|| {
SoupFilterCacheAdapterError("GraphQL schema has no mutation root".to_owned())
})?,
- OperationKind::Subscription => meta::SUBSCRIPTION_ROOT_TYPE.ok_or_else(|| {
+ OperationKind::Subscription => schema.subscription_root().ok_or_else(|| {
SoupFilterCacheAdapterError("GraphQL schema has no subscription root".to_owned())
})?,
};
@@ -171,6 +172,7 @@ pub fn authoritative_projection_mutations(
let mut mutations = IndexMap::new();
let mut has_unbound_incomplete_entity = false;
walk_authoritative_object(
+ schema,
&operation.selection_set,
root_type,
root,
@@ -192,6 +194,7 @@ pub fn authoritative_projection_mutations(
}
fn walk_authoritative_object(
+ schema: &cache_core::meta::Schema,
selections: &[Selection],
declared_type: &str,
object: &serde_json::Map<String, serde_json::Value>,
@@ -203,7 +206,7 @@ fn walk_authoritative_object(
.and_then(serde_json::Value::as_str)
.unwrap_or(declared_type);
let mut fields = Vec::new();
- collect_applicable_fields(selections, concrete_type, &mut fields);
+ collect_applicable_fields(schema, selections, concrete_type, &mut fields);
if let Some(partition) = projection_partition(concrete_type) {
let (mut projection_object, valid_selection) = if partition
@@ -220,7 +223,7 @@ fn walk_authoritative_object(
(object.clone(), true)
};
projection_object.remove("notifications");
- if let Some(snapshot) = notifications::selected_snapshot(object, &fields) {
+ if let Some(snapshot) = notifications::selected_snapshot(schema, object, &fields) {
projection_object.insert("notifications".into(), snapshot);
}
let mut projection_fields = fields
@@ -303,7 +306,7 @@ fn walk_authoritative_object(
let Some(value) = object.get(&field.response_key) else {
continue;
};
- let Some(field_meta) = meta::field_meta(concrete_type, &field.name) else {
+ let Some(field_meta) = schema.field_meta(concrete_type, &field.name) else {
continue;
};
if field_meta.ty.kind != FieldKind::Composite {
@@ -311,6 +314,7 @@ fn walk_authoritative_object(
}
match value {
serde_json::Value::Object(child) => walk_authoritative_object(
+ schema,
&field.selection_set,
field_meta.ty.name,
child,
@@ -321,6 +325,7 @@ fn walk_authoritative_object(
for child in children {
if let serde_json::Value::Object(child) = child {
walk_authoritative_object(
+ schema,
&field.selection_set,
field_meta.ty.name,
child,
@@ -336,6 +341,7 @@ fn walk_authoritative_object(
}
fn collect_applicable_fields<'a>(
+ schema: &cache_core::meta::Schema,
selections: &'a [Selection],
concrete_type: &str,
fields: &mut Vec<&'a FieldNode>,
@@ -348,9 +354,9 @@ fn collect_applicable_fields<'a>(
selection_set,
} if type_condition
.as_deref()
- .is_none_or(|condition| meta::type_matches(concrete_type, condition)) =>
+ .is_none_or(|condition| schema.type_matches(concrete_type, condition)) =>
{
- collect_applicable_fields(selection_set, concrete_type, fields);
+ collect_applicable_fields(schema, selection_set, concrete_type, fields);
}
Selection::Fragment { .. } => {}
}
diff --git a/crates/soup_filter_cache_adapter/src/mail.rs b/crates/soup_filter_cache_adapter/src/mail.rs
index fec685f4bf..39f6d4ca1c 100644
--- a/crates/soup_filter_cache_adapter/src/mail.rs
+++ b/crates/soup_filter_cache_adapter/src/mail.rs
@@ -216,6 +216,7 @@ struct DraftState {
/// Apply complete draft contributions without fabricating server capsules.
/// This is shared by browser and desktop and independent of cached query pages.
pub async fn draft_optimistic_updates<S: Storage>(
+ schema: &cache_core::meta::Schema,
storage: &S,
query: &str,
operation: Option<&str>,
@@ -244,7 +245,7 @@ pub async fn draft_optimistic_updates<S: Storage>(
let record_key = RecordKey::new(key.to_string()).map_err(error)?;
let parsed = Document::parse(query).map_err(error)?;
let op = parsed.operation(operation).map_err(error)?;
- let records = normalize(op, variables, data).map_err(error)?;
+ let records = normalize(schema, op, variables, data).map_err(error)?;
let Some(record) = records.get(&key).filter(|record| {
FIELDS
.iter()
@@ -323,13 +324,14 @@ pub enum ProjectionError<S: std::error::Error + 'static> {
/// Canonical preview edges are independent of the source query's view/filter.
/// A missing v2 field cannot borrow completeness from an older projection.
pub async fn projection_updates<S: Storage>(
+ schema: &cache_core::meta::Schema,
storage: &S,
query: &str,
operation: Option<&str>,
variables: &Map<String, Value>,
data: &Value,
) -> Result<Vec<ProjectionMutation>, ProjectionError<S::Error>> {
- projection_updates_for_write(storage, query, operation, variables, data, true).await
+ projection_updates_for_write(schema, storage, query, operation, variables, data, true).await
}
/// Prepare Mail facts without consulting the old user's records when the write
@@ -337,6 +339,7 @@ pub async fn projection_updates<S: Storage>(
/// partial incoming rows remain incomplete instead of borrowing old metadata.
/// The cache engine, not this adapter, performs the actual identity reset.
pub async fn projection_updates_for_write<S: Storage>(
+ schema: &cache_core::meta::Schema,
storage: &S,
query: &str,
operation: Option<&str>,
@@ -370,7 +373,7 @@ pub async fn projection_updates_for_write<S: Storage>(
}
let parsed = Document::parse(query).map_err(error)?;
let op = parsed.operation(operation).map_err(error)?;
- let updates = normalize(op, variables, data)
+ let updates = normalize(schema, op, variables, data)
.map_err(error)?
.into_iter()
.filter(|(key, record)| {
diff --git a/crates/soup_filter_cache_adapter/src/mail/test.rs b/crates/soup_filter_cache_adapter/src/mail/test.rs
index 136c35867f..8e3a88a6d3 100644
--- a/crates/soup_filter_cache_adapter/src/mail/test.rs
+++ b/crates/soup_filter_cache_adapter/src/mail/test.rs
@@ -72,9 +72,16 @@ fn seed() -> Value {
}
async fn write<S: Storage>(engine: &mut Engine<S>, query: &str, data: &Value) {
let vars = Map::new();
- let projections = projection_updates(engine.storage(), query, None, &vars, data)
- .await
- .unwrap();
+ let projections = projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ query,
+ None,
+ &vars,
+ data,
+ )
+ .await
+ .unwrap();
engine
.write_query_with_registration_and_projections(
None,
@@ -294,9 +301,16 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
let data = json!({"user":{"id":VIEWER,"soup":{"items":[{"__typename":"GraphqlSoupEmailThread","id":id(1),"isRead":true}]}}});
let vars = Map::new();
let mutations = optimistic_updates(
- projection_updates(engine.storage(), PARTIAL, None, &vars, &data)
- .await
- .unwrap(),
+ projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ PARTIAL,
+ None,
+ &vars,
+ &data,
+ )
+ .await
+ .unwrap(),
);
let [OptimisticProjectionMutation::Patch { exact, .. }] = mutations.as_slice() else {
panic!()
@@ -388,10 +402,17 @@ fn identity_switch_does_not_read_old_mail_bases_but_keeps_incoming_snapshots() {
let vars = Map::new();
let mut partial = json!({"user":{"id":"new-viewer","soup":{"items":[{"__typename":"GraphqlSoupEmailThread","id":id(1),"isRead":true}]}}});
let reads = engine.storage().record_get_count();
- let projections =
- projection_updates_for_write(engine.storage(), PARTIAL, None, &vars, &partial, false)
- .await
- .unwrap();
+ let projections = projection_updates_for_write(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ PARTIAL,
+ None,
+ &vars,
+ &partial,
+ false,
+ )
+ .await
+ .unwrap();
assert_eq!(
engine.storage().record_get_count(),
reads,
@@ -407,10 +428,17 @@ fn identity_switch_does_not_read_old_mail_bases_but_keeps_incoming_snapshots() {
// Same-identity incremental writes still resolve against the existing base.
partial["user"]["id"] = json!(VIEWER);
- let projections =
- projection_updates_for_write(engine.storage(), PARTIAL, None, &vars, &partial, true)
- .await
- .unwrap();
+ let projections = projection_updates_for_write(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ PARTIAL,
+ None,
+ &vars,
+ &partial,
+ true,
+ )
+ .await
+ .unwrap();
assert!(matches!(
projections.as_slice(),
[ProjectionMutation::Patch { .. }]
@@ -424,10 +452,17 @@ fn identity_switch_does_not_read_old_mail_bases_but_keeps_incoming_snapshots() {
.truncate(1);
incoming["user"]["soup"]["items"][0]["isRead"] = json!(true);
let reads = engine.storage().record_get_count();
- let projections =
- projection_updates_for_write(engine.storage(), QUERY, None, &vars, &incoming, false)
- .await
- .unwrap();
+ let projections = projection_updates_for_write(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ QUERY,
+ None,
+ &vars,
+ &incoming,
+ false,
+ )
+ .await
+ .unwrap();
assert_eq!(engine.storage().record_get_count(), reads);
assert!(
matches!(projections.as_slice(), [ProjectionMutation::Replace(_)]),
@@ -463,9 +498,16 @@ fn oversized_normalized_keys_are_skipped_without_losing_valid_rows() {
let mut invalid = row(1);
invalid["id"] = json!("x".repeat(predicate_index::MAX_EXACT_VALUE_BYTES + 1));
let data = json!({"user":{"id":VIEWER,"soup":{"items":[invalid, row(4)]}}});
- let updates = projection_updates(&InMemoryStorage::new(), QUERY, None, &Map::new(), &data)
- .await
- .unwrap();
+ let updates = projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ &InMemoryStorage::new(),
+ QUERY,
+ None,
+ &Map::new(),
+ &data,
+ )
+ .await
+ .unwrap();
let [ProjectionMutation::Replace(document)] = updates.as_slice() else {
panic!("only the valid row should be projected")
};
@@ -531,9 +573,16 @@ async fn cleared_inbox_timestamp<S: PredicateIndexStorage>(storage: S) {
"__typename":TYPE,"id":id(4),"cacheProjection":capsule(4, false),
"reminderReturnedAt":null,"latestInboundMessageTs":null
}]}}});
- let updates = projection_updates(engine.storage(), QUERY, None, &Map::new(), &partial)
- .await
- .unwrap();
+ let updates = projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ QUERY,
+ None,
+ &Map::new(),
+ &partial,
+ )
+ .await
+ .unwrap();
assert!(matches!(
updates.as_slice(),
[ProjectionMutation::MarkIncomplete { .. }]
diff --git a/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs b/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs
index 2fdf2c13ed..d89be5d69e 100644
--- a/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs
+++ b/crates/soup_filter_cache_adapter/src/mail/test/drafts.rs
@@ -64,6 +64,7 @@ async fn offline_lifecycle<S: PredicateIndexStorage>(storage: S) {
.clone();
let mut projections = optimistic_updates(
projection_updates(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
SAVE,
Some("SaveEmailDraft"),
@@ -75,6 +76,7 @@ async fn offline_lifecycle<S: PredicateIndexStorage>(storage: S) {
);
projections.extend(
draft_optimistic_updates(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
SAVE,
Some("SaveEmailDraft"),
@@ -85,6 +87,7 @@ async fn offline_lifecycle<S: PredicateIndexStorage>(storage: S) {
.unwrap(),
);
let projections = crate::properties::augment_optimistic(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
SAVE,
Some("SaveEmailDraft"),
@@ -185,6 +188,7 @@ fn absent_thread_revalidation_revokes_stale_mail_membership() {
let variables = json!({"threadId":thread_id}).as_object().unwrap().clone();
let data = json!({"user":{"id":VIEWER,"emailThread":null}});
let projections = projection_updates(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
query,
Some("EmailThreadPage"),
diff --git a/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs b/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs
index 1ef9df1d24..3fe1f3dffe 100644
--- a/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs
+++ b/crates/soup_filter_cache_adapter/src/mail/test/optimistic.rs
@@ -49,9 +49,16 @@ async fn replacement_removals<S: PredicateIndexStorage>(storage: S) {
}
}
let vars = Map::new();
- let updates = projection_updates(engine.storage(), QUERY, None, &vars, &data)
- .await
- .unwrap();
+ let updates = projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ QUERY,
+ None,
+ &vars,
+ &data,
+ )
+ .await
+ .unwrap();
assert!(matches!(
updates.as_slice(),
[ProjectionMutation::Replace(_)]
@@ -140,9 +147,16 @@ async fn optional_sorts<S: PredicateIndexStorage>(storage: S) {
// must be cleared even though the unrelated SENT sort is absent.
data["user"]["soup"]["items"][0]["mailDraftPreview"] = Value::Null;
let vars = Map::new();
- let updates = projection_updates(engine.storage(), QUERY, None, &vars, &data)
- .await
- .unwrap();
+ let updates = projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ QUERY,
+ None,
+ &vars,
+ &data,
+ )
+ .await
+ .unwrap();
assert_eq!(updates.len(), 3);
assert!(
updates
@@ -216,9 +230,16 @@ fn full_optimism_does_not_create_completeness_without_authority() {
pollster::block_on(async {
let mut data = seed();
data["user"]["soup"]["items"] = json!([row(6)]);
- let updates = projection_updates(&InMemoryStorage::new(), QUERY, None, &Map::new(), &data)
- .await
- .unwrap();
+ let updates = projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ &InMemoryStorage::new(),
+ QUERY,
+ None,
+ &Map::new(),
+ &data,
+ )
+ .await
+ .unwrap();
let mutations = optimistic_updates(updates);
let key = RecordKey::new(format!("{TYPE}:{}", id(6))).unwrap();
for authority in [
diff --git a/crates/soup_filter_cache_adapter/src/notifications.rs b/crates/soup_filter_cache_adapter/src/notifications.rs
index c626aa0d1b..93fd0db9ce 100644
--- a/crates/soup_filter_cache_adapter/src/notifications.rs
+++ b/crates/soup_filter_cache_adapter/src/notifications.rs
@@ -16,6 +16,7 @@ mod test;
/// Resolve edge and child aliases from the actual selection, not arbitrary payload fields.
pub(super) fn selected_snapshot(
+ schema: &cache_core::meta::Schema,
object: &serde_json::Map<String, serde_json::Value>,
fields: &[&FieldNode],
) -> Option<serde_json::Value> {
@@ -28,6 +29,7 @@ pub(super) fn selected_snapshot(
Some(values) => {
let mut child_fields = Vec::new();
collect_applicable_fields(
+ schema,
&field.selection_set,
"GraphqlNotification",
&mut child_fields,
@@ -292,6 +294,7 @@ async fn retain_complete_parents<S: Storage>(
/// stored in an optimistic layer: replay edits only this notification's
/// contribution, even after another layer fails.
pub async fn notification_projection_updates<S: Storage>(
+ schema: &cache_core::meta::Schema,
storage: &S,
query: &str,
operation_name: Option<&str>,
@@ -303,7 +306,7 @@ pub async fn notification_projection_updates<S: Storage>(
let operation = document
.operation(operation_name)
.map_err(|e| SoupFilterCacheAdapterError(e.to_string()))?;
- let updates = normalize(operation, variables, data)
+ let updates = normalize(schema, operation, variables, data)
.map_err(|e| SoupFilterCacheAdapterError(e.to_string()))?;
let updates = updates
.into_iter()
diff --git a/crates/soup_filter_cache_adapter/src/notifications/test.rs b/crates/soup_filter_cache_adapter/src/notifications/test.rs
index 3359bffa11..2f8c8277f6 100644
--- a/crates/soup_filter_cache_adapter/src/notifications/test.rs
+++ b/crates/soup_filter_cache_adapter/src/notifications/test.rs
@@ -41,11 +41,24 @@ fn variables() -> serde_json::Map<String, Value> {
}
async fn write<S: Storage>(engine: &mut Engine<S>, query: &str, data: &Value) {
let vars = variables();
- let mut projections = authoritative_projection_mutations(query, None, data).unwrap();
+ let mut projections = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ query,
+ None,
+ data,
+ )
+ .unwrap();
projections.extend(
- notification_projection_updates(engine.storage(), query, None, &vars, data)
- .await
- .unwrap(),
+ notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ query,
+ None,
+ &vars,
+ data,
+ )
+ .await
+ .unwrap(),
);
engine
.write_query_with_registration_and_projections(
@@ -107,9 +120,16 @@ async fn mark_done<S: Storage>(engine: &mut Engine<S>, id: &str, uuid: &str) ->
let data = json!({"updateNotifications":[{"__typename":"GraphqlNotification", "id":id, "state":"DONE"}]});
let vars = variables();
let updates = optimistic_notification_updates(
- notification_projection_updates(engine.storage(), UPDATE, None, &vars, &data)
- .await
- .unwrap(),
+ notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ UPDATE,
+ None,
+ &vars,
+ &data,
+ )
+ .await
+ .unwrap(),
)
.unwrap();
assert_eq!(updates.len(), 1);
@@ -213,10 +233,16 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
.await;
let token = claim(&mut engine, second).await;
let data = json!({"updateNotifications":[notification(B,"DONE")]});
- let projections =
- notification_projection_updates(engine.storage(), UPDATE, None, &variables(), &data)
- .await
- .unwrap();
+ let projections = notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ UPDATE,
+ None,
+ &variables(),
+ &data,
+ )
+ .await
+ .unwrap();
engine
.commit_optimistic_write_with_projections(
second,
@@ -343,6 +369,7 @@ async fn unhydrated_parents<S: PredicateIndexStorage>(storage: S) {
for state in ["DONE", "UNSEEN", "INVALID"] {
let data = json!({"updateNotifications":[{"__typename":"GraphqlNotification", "id":A, "state":state}]});
let updates = notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
UPDATE,
None,
@@ -419,7 +446,13 @@ fn unhydrated_notification_parents_real_turso() {
}
async fn nonmatching_parent_projections<S: Storage>(mut storage: S) {
- let mutations = authoritative_projection_mutations(SNAPSHOT, None, &snapshot(vec![])).unwrap();
+ let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SNAPSHOT,
+ None,
+ &snapshot(vec![]),
+ )
+ .unwrap();
let [ProjectionMutation::Replace(document)] = mutations.as_slice() else {
panic!("complete base")
};
@@ -536,7 +569,13 @@ fn optimistic_notification_conversion_preserves_member_edits_and_invalidation()
#[test]
fn optimistic_notification_conversion_rejects_unsupported_mutations() {
- let mutations = authoritative_projection_mutations(SNAPSHOT, None, &snapshot(vec![])).unwrap();
+ let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SNAPSHOT,
+ None,
+ &snapshot(vec![]),
+ )
+ .unwrap();
let [ProjectionMutation::Replace(document)] = mutations.as_slice() else {
panic!("complete snapshot")
};
@@ -570,7 +609,13 @@ fn optimistic_notification_conversion_rejects_unsupported_mutations() {
#[test]
fn snapshot_completeness_aliases_and_primary_scope() {
let data = snapshot(vec![notification(A, "UNSEEN"), notification(B, "SEEN")]);
- let mutations = authoritative_projection_mutations(SNAPSHOT, None, &data).unwrap();
+ let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SNAPSHOT,
+ None,
+ &data,
+ )
+ .unwrap();
let [ProjectionMutation::Replace(document)] = mutations.as_slice() else {
panic!("complete snapshot")
};
@@ -582,9 +627,14 @@ fn snapshot_completeness_aliases_and_primary_scope() {
.unwrap()
.remove(missing);
assert!(matches!(
- authoritative_projection_mutations(SNAPSHOT, None, &data)
- .unwrap()
- .as_slice(),
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SNAPSHOT,
+ None,
+ &data
+ )
+ .unwrap()
+ .as_slice(),
[ProjectionMutation::MarkIncomplete { .. }]
));
}
@@ -594,15 +644,25 @@ fn snapshot_completeness_aliases_and_primary_scope() {
.unwrap()
.remove("notifications");
assert!(matches!(
- authoritative_projection_mutations(SNAPSHOT, None, &omitted)
- .unwrap()
- .as_slice(),
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SNAPSHOT,
+ None,
+ &omitted
+ )
+ .unwrap()
+ .as_slice(),
[ProjectionMutation::MarkIncomplete { .. }]
));
let mut secondary = notification(A, "UNSEEN");
secondary["entityId"] = json!(B);
- let mutations =
- authoritative_projection_mutations(SNAPSHOT, None, &snapshot(vec![secondary])).unwrap();
+ let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SNAPSHOT,
+ None,
+ &snapshot(vec![secondary]),
+ )
+ .unwrap();
let [ProjectionMutation::Replace(document)] = mutations.as_slice() else {
panic!("complete secondary edge")
};
@@ -623,8 +683,20 @@ fn snapshot_completeness_aliases_and_primary_scope() {
}
entity.insert("notifs".into(), rows);
assert_eq!(
- authoritative_projection_mutations(alias_query.as_str(), None, &alias_data).unwrap(),
- authoritative_projection_mutations(SNAPSHOT, None, &data).unwrap()
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ alias_query.as_str(),
+ None,
+ &alias_data
+ )
+ .unwrap(),
+ authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SNAPSHOT,
+ None,
+ &data
+ )
+ .unwrap()
);
}
@@ -635,6 +707,7 @@ fn backfill_accepts_large_notification_sets_without_losing_members() {
.collect();
let backfill = SNAPSHOT.replace("query Snapshot", "query SoupBackfill");
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
&backfill,
Some("SoupBackfill"),
&snapshot(notifications),
@@ -699,10 +772,17 @@ fn seen_and_reopen_identity_only_optimism_do_not_guess_state() {
.await;
let data = json!({"updateNotifications":[{"__typename":"GraphqlNotification","id":A}]});
assert!(
- notification_projection_updates(engine.storage(), UPDATE, None, &variables(), &data)
- .await
- .unwrap()
- .is_empty()
+ notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ UPDATE,
+ None,
+ &variables(),
+ &data
+ )
+ .await
+ .unwrap()
+ .is_empty()
);
let keys = vec![format!("GraphqlNotification:{A}")];
let updates = notification_deletion_updates(engine.storage(), &keys, true)
diff --git a/crates/soup_filter_cache_adapter/src/notifications/test/large.rs b/crates/soup_filter_cache_adapter/src/notifications/test/large.rs
index 98da820810..a11b921015 100644
--- a/crates/soup_filter_cache_adapter/src/notifications/test/large.rs
+++ b/crates/soup_filter_cache_adapter/src/notifications/test/large.rs
@@ -24,9 +24,16 @@ async fn large_set_lifecycle<S: PredicateIndexStorage>(storage: S) {
"__typename": "GraphqlNotification", "id": member_id(id), "state": "DONE"
})).collect::<Vec<_>>()});
let vars = variables();
- let edits = notification_projection_updates(engine.storage(), UPDATE, None, &vars, &data)
- .await
- .unwrap();
+ let edits = notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ UPDATE,
+ None,
+ &vars,
+ &data,
+ )
+ .await
+ .unwrap();
let [ProjectionMutation::PatchExact { remove, insert, .. }] = edits.as_slice() else {
panic!("bulk updates compose the parent once");
};
@@ -91,9 +98,16 @@ async fn large_set_lifecycle<S: PredicateIndexStorage>(storage: S) {
let token = claim(&mut engine, single).await;
let settled = json!({"updateNotifications":[notification(A, "DONE")]});
- let edits = notification_projection_updates(engine.storage(), UPDATE, None, &vars, &settled)
- .await
- .unwrap();
+ let edits = notification_projection_updates(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ UPDATE,
+ None,
+ &vars,
+ &settled,
+ )
+ .await
+ .unwrap();
engine
.commit_optimistic_write_with_projections(
single, token, UPDATE, None, &vars, &settled, edits,
diff --git a/crates/soup_filter_cache_adapter/src/properties.rs b/crates/soup_filter_cache_adapter/src/properties.rs
index 450b529c10..d3df8a47e0 100644
--- a/crates/soup_filter_cache_adapter/src/properties.rs
+++ b/crates/soup_filter_cache_adapter/src/properties.rs
@@ -113,7 +113,12 @@ fn extend_document(
/// Upgrade legacy core/Mail mutations and maintain property-only writes atomically.
/// An absent property snapshot cannot establish completeness; it may only retain
/// same-identity property proof already present in the current profile.
+#[expect(
+ clippy::too_many_arguments,
+ reason = "explicit schema, storage, and authoritative write context"
+)]
pub async fn augment_authoritative<S: cache_core::predicate::PredicateIndexStorage>(
+ schema: &cache_core::meta::Schema,
storage: &S,
query: &str,
operation: Option<&str>,
@@ -123,6 +128,7 @@ pub async fn augment_authoritative<S: cache_core::predicate::PredicateIndexStora
mutations: Vec<ProjectionMutation>,
) -> Result<Vec<ProjectionMutation>, ProjectionError<S::Error>> {
let changes = prepare(
+ schema,
storage,
query,
operation,
diff --git a/crates/soup_filter_cache_adapter/src/properties/optimistic.rs b/crates/soup_filter_cache_adapter/src/properties/optimistic.rs
index 9520b98ad6..0f3971e3d9 100644
--- a/crates/soup_filter_cache_adapter/src/properties/optimistic.rs
+++ b/crates/soup_filter_cache_adapter/src/properties/optimistic.rs
@@ -21,6 +21,7 @@ fn upgrade(mut mutation: OptimisticProjectionMutation) -> OptimisticProjectionMu
/// Prepare property-specific optimistic patches without snapshotting unrelated
/// properties from older layers. The existing queue owns commit/rollback/replay.
pub async fn augment_optimistic<S: PredicateIndexStorage>(
+ schema: &cache_core::meta::Schema,
storage: &S,
query: &str,
operation: Option<&str>,
@@ -28,7 +29,7 @@ pub async fn augment_optimistic<S: PredicateIndexStorage>(
data: &Value,
mutations: Vec<OptimisticProjectionMutation>,
) -> Result<Vec<OptimisticProjectionMutation>, ProjectionError<S::Error>> {
- let changes = prepare(storage, query, operation, variables, data, true).await?;
+ let changes = prepare(schema, storage, query, operation, variables, data, true).await?;
let keys: Vec<_> = mutations
.iter()
.map(|mutation| mutation.record_key().clone())
diff --git a/crates/soup_filter_cache_adapter/src/properties/prepare.rs b/crates/soup_filter_cache_adapter/src/properties/prepare.rs
index 133d2a50b7..429eaf780e 100644
--- a/crates/soup_filter_cache_adapter/src/properties/prepare.rs
+++ b/crates/soup_filter_cache_adapter/src/properties/prepare.rs
@@ -210,6 +210,7 @@ fn snapshot(
}
fn mutation_owners(
+ schema: &cache_core::meta::Schema,
query: &str,
operation: Option<&str>,
variables: &Map<String, Value>,
@@ -223,8 +224,9 @@ fn mutation_owners(
}
let mut fields = Vec::new();
crate::collect_applicable_fields(
+ schema,
&op.selection_set,
- cache_core::meta::MUTATION_ROOT_TYPE.unwrap_or(""),
+ schema.mutation_root().unwrap_or(""),
&mut fields,
);
for field in fields {
@@ -249,7 +251,12 @@ fn mutation_owners(
continue;
};
let mut selections = Vec::new();
- crate::collect_applicable_fields(&field.selection_set, "GraphqlProperty", &mut selections);
+ crate::collect_applicable_fields(
+ schema,
+ &field.selection_set,
+ "GraphqlProperty",
+ &mut selections,
+ );
let Some(id) = selections
.iter()
.find(|f| f.name == "id")
@@ -322,6 +329,7 @@ async fn owners<S: PredicateIndexStorage>(
}
pub(super) async fn prepare<S: PredicateIndexStorage>(
+ schema: &cache_core::meta::Schema,
storage: &S,
query: &str,
operation: Option<&str>,
@@ -331,7 +339,7 @@ pub(super) async fn prepare<S: PredicateIndexStorage>(
) -> Result<BTreeMap<RecordKey, Changes>, ProjectionError<S::Error>> {
let document = Document::parse(query).map_err(error)?;
let op = document.operation(operation).map_err(error)?;
- let updates: BTreeMap<_, _> = normalize(op, variables, data)
+ let updates: BTreeMap<_, _> = normalize(schema, op, variables, data)
.map_err(error)?
.into_iter()
.collect();
@@ -366,7 +374,7 @@ pub(super) async fn prepare<S: PredicateIndexStorage>(
.snapshot = Some(snapshot(properties, &updates));
}
}
- let routed = mutation_owners(query, operation, variables, data)?;
+ let routed = mutation_owners(schema, query, operation, variables, data)?;
for (key, parent) in &routed {
if updates
.get(key)
diff --git a/crates/soup_filter_cache_adapter/src/properties/test.rs b/crates/soup_filter_cache_adapter/src/properties/test.rs
index 0a26507f49..995c9c2096 100644
--- a/crates/soup_filter_cache_adapter/src/properties/test.rs
+++ b/crates/soup_filter_cache_adapter/src/properties/test.rs
@@ -73,10 +73,17 @@ fn favorites_membership_changes_optimistically_and_rolls_back_without_a_new_quer
"__typename":"SoupUpdated","item":{"__typename":"GraphqlSoupProject","id":id(100),"isFavorited":false}
}]}}});
let core = crate::optimistic_projection_mutations(&removal, 0);
- let projections =
- augment_optimistic(engine.storage(), FAVORITE, None, &vars, &removal, core)
- .await
- .unwrap();
+ let projections = augment_optimistic(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ FAVORITE,
+ None,
+ &vars,
+ &removal,
+ core,
+ )
+ .await
+ .unwrap();
let queued = engine
.enqueue_optimistic_mutation_with_projections(
None,
@@ -157,16 +164,31 @@ async fn write<S: PredicateIndexStorage>(
data: &Value,
identity: &str,
) {
- let core = crate::authoritative_projection_mutations(query, None, data).unwrap();
+ let core = crate::authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ query,
+ None,
+ data,
+ )
+ .unwrap();
let reuse = engine
.current_identity()
.await
.unwrap()
.as_deref()
.is_none_or(|bound| bound == identity);
- let projections = augment_authoritative(engine.storage(), query, None, vars, data, reuse, core)
- .await
- .unwrap();
+ let projections = augment_authoritative(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ query,
+ None,
+ vars,
+ data,
+ reuse,
+ core,
+ )
+ .await
+ .unwrap();
engine
.write_query_with_registration_and_projections(
None,
@@ -312,9 +334,17 @@ fn independent_property_optimism_survives_rollback_and_commits() {
for (definition, option) in [(1, 12), (2, 23)] {
let vars = json!({"input":{"entityType":"PROJECT","entityId":id(100),"propertyDefinitionId":id(definition)}}).as_object().unwrap().clone();
let data = json!({"setEntityProperty":property(definition, option)});
- let projections = augment_optimistic(engine.storage(), SET, None, &vars, &data, vec![])
- .await
- .unwrap();
+ let projections = augment_optimistic(
+ cache_core::meta::bundled_schema_ref(),
+ engine.storage(),
+ SET,
+ None,
+ &vars,
+ &data,
+ vec![],
+ )
+ .await
+ .unwrap();
let uuid = format!("00000000-0000-7000-8000-{definition:012}");
let queued = engine
.enqueue_optimistic_mutation_with_projections(
@@ -386,6 +416,7 @@ fn independent_property_optimism_survives_rollback_and_commits() {
.unwrap()
.unwrap();
let projections = augment_authoritative(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
SET,
None,
@@ -449,6 +480,7 @@ fn property_optimism_only_patches_the_modified_definition() {
write(&mut engine, QUERY, &Map::new(), &data(), VIEWER).await;
let vars = json!({"input": {"entityType":"PROJECT", "entityId":id(100), "propertyDefinitionId":id(1)}}).as_object().unwrap().clone();
let changes = augment_optimistic(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
SET,
None,
diff --git a/crates/soup_filter_cache_adapter/src/test.rs b/crates/soup_filter_cache_adapter/src/test.rs
index 9bc823889e..1d8ccd2a37 100644
--- a/crates/soup_filter_cache_adapter/src/test.rs
+++ b/crates/soup_filter_cache_adapter/src/test.rs
@@ -183,6 +183,7 @@ fn authoritative_direct_fields_without_projection_schema_field_become_v4_patch()
}
}"#;
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
query,
Some("LegacySoup"),
&serde_json::json!({
@@ -213,6 +214,7 @@ fn authoritative_direct_fields_without_projection_schema_field_become_v4_patch()
fn partial_queries_preserve_v4_authority_and_mark_missing_v4() {
let id = "00000000-0000-0000-0000-000000000001";
let base_mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_SUBSCRIPTION,
Some("Supplement"),
&supplement_subscription_data(selected_document(
@@ -240,6 +242,7 @@ fn partial_queries_preserve_v4_authority_and_mark_missing_v4() {
}
}"#;
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
query,
Some("SoupNotifications"),
&serde_json::json!({
@@ -324,6 +327,7 @@ fn empty_query_patch_does_not_overwrite_an_earlier_field_patch() {
}
}"#;
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
query,
Some("RepeatedSoupEntity"),
&serde_json::json!({
@@ -473,6 +477,7 @@ fn selected_document_supplement_composes_direct_and_server_owned_facts() {
let id = "00000000-0000-0000-0000-000000000001";
let encoded = document_supplement(id, false);
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_SUBSCRIPTION,
Some("Supplement"),
&supplement_subscription_data(selected_document(
@@ -497,6 +502,7 @@ fn selected_document_supplement_composes_direct_and_server_owned_facts() {
}));
let attached = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_SUBSCRIPTION,
Some("Supplement"),
&supplement_subscription_data(selected_document(
@@ -533,6 +539,7 @@ fn selected_document_supplement_composes_importance_and_status_facts() {
let status_a = uuid::Uuid::from_u128(11);
let status_b = uuid::Uuid::from_u128(12);
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_SUBSCRIPTION,
Some("Supplement"),
&supplement_subscription_data(selected_document(
@@ -571,6 +578,7 @@ fn document_subtype_postings_are_composed_from_graphql_typenames() {
] {
let id = format!("00000000-0000-0000-0000-{suffix:012}");
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_SUBSCRIPTION,
Some("Supplement"),
&supplement_subscription_data(selected_document(
@@ -603,6 +611,7 @@ fn selected_project_and_chat_null_supplements_are_valid_direct_only_v4_hydration
} } }
}"#;
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
query,
Some("SoupBackfill"),
&serde_json::json!({
@@ -673,6 +682,7 @@ fn missing_malformed_or_mismatched_document_supplements_remain_incomplete() {
),
] {
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_SUBSCRIPTION,
Some("Supplement"),
&supplement_subscription_data(item),
@@ -709,6 +719,7 @@ fn backfill_rejects_invalid_supplements_and_missing_direct_document_fields() {
missing_owner,
] {
let error = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_BACKFILL,
Some("SoupBackfill"),
&serde_json::json!({ "user": { "soup": { "items": [item] } } }),
@@ -721,6 +732,7 @@ fn backfill_rejects_invalid_supplements_and_missing_direct_document_fields() {
}
let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_BACKFILL,
Some("SoupBackfill"),
&serde_json::json!({
@@ -786,8 +798,13 @@ fn partial_mutation_payloads_patch_v4_without_fabricating_server_facts() {
}]
}
});
- let mutations =
- authoritative_projection_mutations(query, Some("PartialRename"), &data).unwrap();
+ let mutations = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ query,
+ Some("PartialRename"),
+ &data,
+ )
+ .unwrap();
let [
ProjectionMutation::Patch {
profile,
@@ -1393,3 +1410,39 @@ fn soup_flat_v3_supplement_goldens_lock_viewer_relative_wire() {
);
}
}
+
+#[test]
+fn runtime_schema_traverses_new_fields_for_existing_entity_projections() {
+ let baseline = cache_core::meta::bundled_schema();
+ let mut artifact = baseline.artifact().clone();
+ let query_root = artifact.query_root.clone();
+ artifact
+ .types
+ .iter_mut()
+ .find(|ty| ty.name == query_root)
+ .unwrap()
+ .fields
+ .push(cache_core::meta::OwnedFieldMeta {
+ name: "runtimeDocument".into(),
+ ty: cache_core::meta::OwnedFieldType {
+ name: "GraphqlSoupDocument".into(),
+ kind: cache_core::meta::FieldKind::Composite,
+ nullable: true,
+ list: false,
+ item_nullable: false,
+ },
+ });
+ let schema = cache_core::meta::Schema::from_artifact(artifact).unwrap();
+ let query = "query { runtimeDocument { id name } }";
+ let data = serde_json::json!({"runtimeDocument": {"id": "00000000-0000-4000-8000-000000000001", "name": "OTA document"}});
+ assert!(
+ authoritative_projection_mutations(&baseline, query, None, &data)
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ !authoritative_projection_mutations(&schema, query, None, &data)
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/soup_filter_cache_adapter/src/test/file_type.rs b/crates/soup_filter_cache_adapter/src/test/file_type.rs
index 9c69b1f3dd..641a9ce031 100644
--- a/crates/soup_filter_cache_adapter/src/test/file_type.rs
+++ b/crates/soup_filter_cache_adapter/src/test/file_type.rs
@@ -153,9 +153,15 @@ async fn seed<S: PredicateIndexStorage>(engine: &mut Engine<S>) {
.replace("fileType", "fileType isFavorited properties { id }");
let data = json!({"user":{"id":"viewer","soup":{"items":(0..FILE_TYPES.len()).map(item).collect::<Vec<_>>()}}});
let vars = serde_json::Map::new();
- let projections =
- authoritative_projection_mutations(&query, Some("SoupBackfill"), &data).unwrap();
+ let projections = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ &query,
+ Some("SoupBackfill"),
+ &data,
+ )
+ .unwrap();
let projections = crate::properties::augment_authoritative(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
&query,
Some("SoupBackfill"),
@@ -236,6 +242,7 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
}}]}]}});
// Start from pdf, then change its membership only in the pending layer.
let projections = crate::properties::augment_optimistic(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
RENAME,
Some("Rename"),
@@ -290,9 +297,15 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
engine = reopened;
assert_updated_type(&mut engine, &json!("pdf")).await;
- let projections =
- authoritative_projection_mutations(RENAME, Some("Rename"), &data).unwrap();
+ let projections = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ RENAME,
+ Some("Rename"),
+ &data,
+ )
+ .unwrap();
let projections = crate::properties::augment_authoritative(
+ cache_core::meta::bundled_schema_ref(),
engine.storage(),
RENAME,
Some("Rename"),
@@ -327,9 +340,13 @@ async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
fn every_soup_profile_compiles_file_type_negation_with_sql_null_semantics() {
let data =
json!({"user":{"soup":{"items":(0..FILE_TYPES.len()).map(item).collect::<Vec<_>>()}}});
- let documents =
- authoritative_projection_mutations(SUPPLEMENT_BACKFILL, Some("SoupBackfill"), &data)
- .unwrap();
+ let documents = authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
+ SUPPLEMENT_BACKFILL,
+ Some("SoupBackfill"),
+ &data,
+ )
+ .unwrap();
for compile in [
item_filter_index::compile_soup_flat_v1,
item_filter_index::compile_soup_flat_v2,
@@ -389,6 +406,7 @@ fn malformed_file_type_data_is_still_rejected_but_unknown_filter_inputs_are_not_
item["fileType"] = file_type;
assert!(
authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_BACKFILL,
Some("SoupBackfill"),
&json!({"user":{"soup":{"items":[item]}}})
@@ -400,6 +418,7 @@ fn malformed_file_type_data_is_still_rejected_but_unknown_filter_inputs_are_not_
missing.as_object_mut().unwrap().remove("fileType");
assert!(
authoritative_projection_mutations(
+ cache_core::meta::bundled_schema_ref(),
SUPPLEMENT_BACKFILL,
Some("SoupBackfill"),
&json!({"user":{"soup":{"items":[missing]}}})