gnomonlearn
Docs/Graph/RFC-0038

RFC-0038 · Graph Client

Versioned draft snapshot

RFCs, reference catalogs, and evidence reflect Spec 3b2e3e7a114fb826b1445d39a48756b8fff629cd. Counts and pending/status notes belong to that snapshot. Read the dated project update for later progress.

Source repositories are private during staging. Links marked “repository access required” need access to the linked repository.

Status Draft corpus. Reference catalogs and RDF projections have generation drift checks; Gnomon proofs and projection semantics remain unverified for release.

View the generated reference catalog →

Read design questions and decisions →


Reference catalog: the diagnostics, linked-RFC graph, defined terms, and normative-rule index for this RFC are in the reference catalog, generated from the structured Lean module. This document carries the prose: design rationale, entity-shape definitions in context, and migration notes.


1. Purpose

The Graph Client is the read/write surface that application code, templates, operations, and the install engine use to interact with the graph. It is the layer that sits between the typed-but-low-level backend services (RFC-0037) and the higher-level constructs (templates, operations, modules).

The Graph Client provides:

  • A fluent, namespaced API organized by entity type (client.resources.get(id), client.statements.query(filters)).
  • A read/write split: the readonly client surface exposes only queries; the transactional client surface adds mutations.
  • A transaction primitive (client.transaction(callback)) that bundles writes into atomic units coordinated through the underlying TransactionService (RFC-0037 §4.8).
  • A pagination contract (Cursor<T>) and a fluent query builder (client.query().from(...).where(...).traverse(...)).
  • Batch helpers for high-throughput multi-entity creation.
  • A session-scoped context that carries the active principal (RFC-0048) and tenant binding to the backend.

This RFC specifies the target client contract using the legacy graph-client package as a migration baseline. The existing client provides several namespaces and transaction helpers, but does not yet expose client.query() and its query builder does not execute queries. It does not redefine the data model (RFC-0036) or the backend services (RFC-0037); it composes them into an application-facing API.


2. Definitions

TermMeaning
GraphClientThe composed readonly client. Carries no transaction; reads observe last-committed state.
TransactionalGraphClientThe composed write-capable client. Bound to a single open transaction; reads observe in-transaction state.
GraphContextThe bundle of { backend, session } passed to every query implementation.
Query namespaceOne of resources, statements, lists, sets, permissions, workspace.
CursorA pagination handle (Cursor<T>) returned by query operations; supports forward iteration and HMAC-secured stateless continuation.
Query builderThe fluent API surface for composing multi-step traversal queries.
Batch operationA bulk write that creates many entities through a single backend round-trip.

3. Client Composition

3.1 Readonly vs. Transactional

The client surface is parameterized by writability:

GraphClient {
  resources:   ResourceQueries<readonly>
  statements:  StatementQueries<readonly>
  permissions: PermissionQueries
  lists:       ListQueries<readonly>
  sets:        SetQueries<readonly>
  workspace:   WorkspaceQueries<readonly>
  query():     GraphQueryBuilder
  transaction<T>(callback: (tx: TransactionalGraphClient) => Promise<T>): Promise<T>
  isolatedTransaction<T>(callback: (tx: TransactionalGraphClient) => Promise<T>): Promise<T>
}

TransactionalGraphClient {
  resources:   ResourceQueries<transactional>
  statements:  StatementQueries<transactional>
  permissions: PermissionQueries
  lists:       ListQueries<transactional>
  sets:        SetQueries<transactional>
  workspace:   WorkspaceQueries<readonly>      // workspace remains read-only
  query():     GraphQueryBuilder
}

GraphClient is the entry point — applications obtain one via the builder (§3.3) and use it for all reads. To write, they call client.transaction(cb), which creates a TransactionalGraphClient, runs the callback, and commits or rolls back.

TransactionalGraphClient is never directly constructible by application code. It exists only inside a transaction() or isolatedTransaction() callback; its lifetime is bound to the open transaction or rollback boundary.

3.2 GraphContext

Every query in the client receives a GraphContext:

GraphContext {
  backend:  GraphBackend          // RFC-0037
  session:  Session?              // RFC-0048
}

The session field carries the active principal and tenant binding. Implementations MUST propagate the session into the backend’s tenant context (RFC-0037 §5.4) before executing any read or write. A client constructed without a session represents an unauthenticated context; backends MAY accept this for a narrow set of public reads (RFC-0048 §anonymous principal) and MUST reject all writes.

3.3 The builder

Clients are constructed via a fluent builder:

graphClientBuilder()
  .backend(backend)               // required
  .session(session)               // optional but recommended
  .build()                        // returns GraphClient

The builder MUST throw at build() time if backend is unset (M38010). A second entry point is provided for direct construction from a context:

GraphClient.create(context)

Both forms produce the same readonly GraphClient.

3.4 Nested transactions

client.transaction(cb) opens a new transaction unless one is already active in the surrounding context, in which case the callback executes in the existing transaction. This composes naturally with templates (RFC-0039) and operations (RFC-0043), which open transactions of their own.

The implementation contract is:

async transaction<T>(callback): Promise<T> {
  if (await backend.transactions.isInTransaction()) {
    return callback(new TransactionalGraphClient(context))
  }
  await backend.transactions.begin()
  try {
    const result = await callback(new TransactionalGraphClient(context))
    await backend.transactions.commit()
    return result
  } catch (e) {
    await backend.transactions.rollback()
    throw e
  }
}

A re-entrant transaction() call inside an existing transaction MUST NOT issue an additional begin() / commit(); the outer transaction owns the lifecycle.

client.isolatedTransaction(callback) provides an explicit rollback boundary without changing that joining behavior:

  • With no active transaction, it begins a transaction, commits on callback success, and rolls back on callback failure. Savepoint support is not required.
  • With an active caller transaction, it requires all three savepoint operations, creates a savepoint before the callback, releases it on success, and rolls back to it and releases it on callback failure. It MUST reject before invoking the callback if savepoint support is incomplete.
  • A successful nested callback has completed its local boundary; it has not committed the caller’s transaction. The caller retains commit and rollback authority.
  • After successful rollback and release, the original callback error is rethrown unchanged. Boundary inspection, begin, commit, savepoint, release, or rollback failures raise IsolatedTransactionLifecycleError with their causes. Failed cleanup retains both the callback error and cleanup error; callers MUST propagate this fatal error instead of treating it as a recoverable callback failure.

The exported structural GraphClient type includes the new method. Custom implementations and facades must implement or forward it. A transaction shared across multiple operations requires the same backend transaction context; independently acquired client leases do not implicitly share a transaction.


4. Query Surfaces

4.1 ResourceQueries

Readonly:

ReadonlyResourceQueries {
  get(id: bigint): Promise<Resource | null>
  getByExternalId(kind: string, externalId: string): Promise<Resource | null>
  query(): Promise<Cursor<Resource>>
  query(pageSize: number): Promise<Cursor<Resource>>
  query(filters: ResourceQueryFilters): Promise<Cursor<Resource>>
  query(filters: ResourceQueryFilters, pageSize: number): Promise<Cursor<Resource>>
  query(token: string, pageSize?: number): Promise<CursorPage<Resource>>   // continuation token
}

Transactional adds:

TransactionalResourceQueries extends ReadonlyResourceQueries {
  create(input: ResourceInput): Promise<bigint>
  update(id: bigint, data: Map<String, Any>, merge?: boolean): Promise<boolean>   // merge defaults to true
  delete(id: bigint): Promise<boolean>                                            // soft delete
}

The merge parameter on update() defaults to true at the client surface, which is the inverse of the backend’s false default (RFC-0037 §4.1). The client’s choice favors safety: most callers want to update a few fields without obliterating the rest. Authors who want the replace semantics explicitly pass merge: false.

4.2 StatementQueries

Readonly:

ReadonlyStatementQueries {
  get(id: bigint): Promise<Statement | null>
  query(): Promise<Cursor<Statement>>
  query(filters: StatementQueryFilters): Promise<Cursor<Statement>>
  query(filters: StatementQueryFilters, pageSize: number): Promise<Cursor<Statement>>
  query(token: string, pageSize?: number): Promise<CursorPage<Statement>>
}

Transactional adds:

TransactionalStatementQueries extends ReadonlyStatementQueries {
  create(input: StatementInput): Promise<bigint>
  createMany(inputs: StatementInput[]): Promise<bigint[]>
  update(id: bigint, data: Map<String, Any>, merge?: boolean): Promise<boolean>
  invalidate(id: bigint): Promise<boolean>     // sets validTo = now()
}

invalidate() is the bitemporal-aware close of an edge (RFC-0036 §4.2); it does not soft-delete. Use delete() (which is exposed via the underlying backend Delete discriminant) only for hard-removal scenarios; the client surface deliberately omits a delete(id) method for statements to encourage the bitemporal pattern.

4.3 ListQueries and SetQueries

The lists and sets namespaces wrap the backend’s CollectionService (RFC-0037 §4.4). They expose readonly queries (get(id), query(...)) plus, in transactional mode, mutation methods that operate on the underlying collection ID.

The client surface returns GraphList and GraphSet — wrapper objects that expose collection-specific methods (size, members, at(position), contains(member), add(member), remove, etc.) on top of the backend service.

The full GraphList/GraphSet API is defined in @savvi-studio/graph-client/collections and is exposed as a single normative interface in this RFC §4.6.

4.4 PermissionQueries (read-only)

PermissionQueries {
  get(params: PermissionCheckParams): Promise<PermissionResult>
  forSubject(params: SubjectPermissionsParams): Promise<SubjectPermission[]>
}

Permission results are post-policy-evaluation (RFC-0042). The client MUST NOT cache permission results across calls; the backend’s PermissionCache (RFC-0036 §6.2) handles caching internally.

4.5 WorkspaceQueries (read-only)

ReadonlyWorkspaceQueries {
  get(resourceId: bigint): Promise<WorkspaceEntity | null>
  resources(): Promise<Cursor<WorkspaceEntity>>
  resources(filters: WorkspaceQueryFilters): Promise<Cursor<WorkspaceEntity>>
  count(filters?: WorkspaceQueryFilters): Promise<bigint>
  contains(resourceId: bigint): Promise<boolean>
}

Workspace queries are read-only at this layer; workspace creation belongs to the install engine (RFC-0041). RFC-0045 defines tenant-mode configuration and RFC-0051 defines PostgreSQL RLS binding; the complete tenancy model remains deferred.

4.6 Collection wrappers

GraphList and GraphSet are returned by lists.get(id) / sets.get(id) and from query results. They wrap a collection ID and expose collection-aware methods backed by the CollectionService:

GraphList {
  id:        bigint
  size():    Promise<number>
  members(): Promise<bigint[]>
  at(position: number): Promise<bigint | null>
  // transactional only:
  add(memberId: bigint):                            Promise<boolean>
  insert(memberId: bigint, position: number):       Promise<boolean>
  remove(memberIdOrPosition: bigint | number):      Promise<boolean>
  clear():                                          Promise<boolean>
  delete():                                         Promise<boolean>
}

GraphSet {
  id:        bigint
  size():    Promise<number>
  members(): Promise<bigint[]>
  contains(memberId: bigint): Promise<boolean>
  // transactional only:
  add(memberId: bigint):     Promise<boolean>
  remove(memberId: bigint):  Promise<boolean>
  clear():                   Promise<boolean>
  delete():                  Promise<boolean>
}

add() on a Set MUST be idempotent: calling add(m) twice MUST NOT result in duplicate membership. add() on a List appends to the end; insert() places at a specific position.


5. Pagination

5.1 Cursor surface

Every query returning a collection returns a Cursor<T>:

Cursor<T> {
  // Iteration
  [Symbol.asyncIterator](): AsyncIterator<T>

  // Eager collection (small result sets only)
  toArray(): Promise<T[]>

  // Token-based stateless pagination
  toToken(): string                       // HMAC-secured continuation token
}

CursorPage<T> {
  items:      T[]
  nextToken:  string | null
  hasMore:    boolean
}

Forward iteration (for await) is the recommended consumption pattern. toArray() is provided for convenience and MUST throw or warn (M38020) when the underlying result set exceeds an implementation-defined safety limit (default: 10 000 entries).

5.2 Stateless continuation tokens

Token-based pagination is the canonical form for cursor handoff across HTTP requests. A continuation token is an HMAC-secured string that encodes the cursor state. Pagination calls in the form:

client.resources.query(token: string, pageSize?: number): Promise<CursorPage<Resource>>

return a CursorPage<T> directly (not a Cursor<T>). The client MUST verify the HMAC before honoring a token; tampered or expired tokens MUST be rejected with M38030.

The HMAC key is derived from the runtime’s configured signing secret (RFC-0046). Rotation of the signing secret invalidates outstanding tokens; this is intentional and tokens MUST be treated as short-lived (default 1 hour).

5.3 Filters

Each query namespace defines its own filter type (ResourceQueryFilters, StatementQueryFilters, WorkspaceQueryFilters). All extend the common pagination shape:

paginationOptions {
  cursor:  string?            // continuation token
  limit:   number?            // backend-defined default and max
  orderBy: string?
}

Filter fields beyond pagination are namespace-specific (RFC-0037 §4 lists them). Implementations MUST tolerate unknown filter keys silently (forward compatibility); they MUST NOT throw.


6. Query Builder

The fluent query builder (client.query()) composes multi-step graph traversals:

GraphQueryBuilder {
  from(kind: string): this                                  // start from a resource kind
  where(predicate: string, targetId: bigint): this          // filter by predicate edge
  traverse(predicate: string, options?: TraverseOptions): this
  limit(count: number): this
  offset(count: number): this
  execute(pageSize?: number): Promise<Cursor<Resource>>
  fetchAll(): Promise<Resource[]>                           // memory-resident result
}

Execution semantics:

  • from(kind) — establishes the starting set: all (non-soft-deleted) resources of the given kind.
  • where(predicate, targetId) — narrows the set to resources that have the given outgoing predicate to targetId.
  • traverse(predicate, options) — replaces the result set with the resources reachable via the predicate (with maxDepth, direction).
  • limit / offset — cap and skip on the final result set.
  • execute() — returns a Cursor<Resource> for streaming consumption.
  • fetchAll() — eagerly materializes; MUST emit M38020 (warning) for results larger than the safety limit.

The builder MUST be a thin wrapper over the underlying TraversalService (RFC-0037 §4.5) and ResourceService (§4.1). Implementations MAY optimize execution (e.g., push-down to a single SQL query for the Postgres backend) but MUST preserve the observable semantics above.


7. Batch Operations

The client exposes batch helpers for high-throughput multi-entity creation:

client.batch.createResources(inputs: ResourceInput[], options?: BatchOptions): Promise<bigint[]>
client.batch.createStatements(inputs: StatementInput[], options?: BatchOptions): Promise<bigint[]>

BatchOptions:

BatchOptions {
  chunkSize:        number?       // default backend-defined; legacy default 500
  continueOnError:  boolean?      // default false
  onProgress:       (chunk: number, total: number) => void?
}

Behavior:

  • Atomicity — when continueOnError: false (default), the entire batch MUST be transactional. Either all inputs succeed or none do.
  • Partial success — when continueOnError: true, errors are collected and returned alongside successes. The BatchResult shape is:
    BatchResult {
      success: bigint[]
      failed:  Array<{ index: number, error: Error }>
    }
    In partial-success mode, the client surface returns the success array; callers needing the failed items MUST use the lower-level batch primitive directly.
  • Chunking — large batches are transparently split into chunks of chunkSize. Chunks are sequential, not parallel, to preserve write order.

Batch operations are only available on the transactional client.


8. Session and Tenant Context

8.1 Session propagation

The GraphContext.session field is the principal identity carrier. On every query, the client MUST:

  1. Set the backend’s tenant context (RFC-0037 §5.4) from the session’s tenant binding.
  2. Attach the principal id to the write payload as creatorId for new entities.
  3. Clear the tenant context on transaction end (commit, rollback, or unhandled error).

A client without a session represents an anonymous context. Anonymous reads are permitted only when both the API surface (RFC-0033) and the backend tenant policy allow them; otherwise queries MUST throw M38040.

8.2 Identity merge

When a client write asserts a Resource via getByExternalId(kind, ext) then upserts (template idempotency, RFC-0039), the identity merge contract from RFC-0007 applies. The client MUST surface merge-conflict errors as M38050 and MUST NOT silently overwrite a Resource that has been merged from a different external system.

8.3 Audit trail

Every write through the transactional client MUST produce an audit log entry (RFC-0047). The client is responsible for capturing:

  • Operation name (caller-supplied or inferred)
  • Principal id (from session)
  • Tenant id (from session)
  • Entity kind and id
  • Action type (create, update, delete, invalidate)
  • Pre-image hash and post-image hash for diffing
  • Correlation id

Audit emission is opaque to the application; the client MUST NOT permit suppression.


9. Invariants

  1. The client is constructed only via the builder or GraphClient.create(context) (§3.3); direct construction is not permitted.
  2. The transactional client exists only inside a transaction(callback) or isolatedTransaction(callback) scope (§3.4); references that escape the callback are no longer valid.
  3. Re-entrant transaction() calls participate in the existing transaction; they MUST NOT begin a nested one (§3.4).
  4. Every read MUST observe the active session’s tenant binding (§8.1).
  5. Every write MUST attach the active principal as creatorId (§8.1).
  6. Continuation tokens MUST be HMAC-validated; tampered tokens MUST be rejected with M38030 (§5.2).
  7. Batch operations are atomic by default; partial success requires explicit opt-in (§7).
  8. The PermissionQueries namespace is read-only and post-evaluation; writes MUST go through policy declarations (RFC-0042), not directly through the client.
  9. update() defaults merge to true at the client surface (§4.1), inverting the backend default for safety.
  10. Audit emission is mandatory and not suppressible (§8.3).

10. Compatibility and Migration

10.1 From legacy graph-client

This RFC maps the legacy client files to the target contract:

Legacy fileThis RFC
index.ts (GraphClient, TransactionalGraphClient, builder)§3
queries/resources.ts§4.1
queries/statements.ts§4.2
queries/collections.ts, collections/GraphList.ts, collections/GraphSet.ts§4.3, §4.6
queries/permissions.ts§4.4
queries/workspace.ts§4.5
queries/builder.ts§6
queries/batch.ts, batch/*.ts§7

The readonly and transactional implementations are migration baselines. Conformance to the full contract, including the executable query builder, HMAC continuation tokens, session binding, and mandatory audit emission, requires separate tests and implementation work.

10.2 Naming

The legacy code uses client.lists, client.sets, and client.workspace; this RFC preserves those names. client.query() is the proposed builder entry point and is distinct from client.resources.query(). The current client class does not expose it.

10.3 Behavior changes

This RFC introduces the following behavioral changes and unimplemented obligations relative to the legacy implementation:

  • update() merge default flips to true at the client surface (legacy: false). Migration: callers that relied on replacement semantics must pass merge: false explicitly. Callers that intended merge semantics get the safer behavior automatically.
  • Audit emission is mandatory (§8.3). The legacy client emits audit only when wired through the audit middleware; this RFC requires it unconditionally. Backends that do not have audit infrastructure MUST install a logging stub before going live.
  • The §6 query builder needs a client.query() entry point and executable execute() / fetchAll() paths. The legacy builder currently throws for both execution methods.
  • The §5.2 HMAC continuation-token contract and §8.1 session binding require end-to-end conformance tests before they are advertised as supported behavior.

Diagnostics

The diagnostic catalog for this RFC is authored in the structured Lean module and rendered in reference catalog § Diagnostics. Inline mentions in the prose above (e.g., “rejected with MNNxxx”) cross-link to the catalog at render time.

Linked References

The cross-RFC dependency graph is rendered in reference catalog § Linked References. Out-of-KG pointers to legacy code or external resources, when present, remain in this document under “Source-tree references” below.