Эх сурвалжийг харах

feat(webui): a Schema panel on the collection view

Completes #62. Verified in a browser against a real 2.17.2 database rather
than only compiled: the panel renders, Suggest prefills, a save in audit mode
reports its violations, and clicking a violating document id lands in the
editor on the offending field ("age": "not-an-int").

Three things are deliberate:

Suggest PREFILLS and never applies, and the toast says so - "Nothing has been
applied - review it and save" - because the server refuses to apply a
suggestion for the same reason: lengths and ranges are described rather than
enforced, so arming one unseen would create something that looks stricter
than what it checks. A sampled suggestion says so too, since a field absent
from a sample may still exist in the data.

The mode selector defaults to "Choose for me" rather than picking a side.
The server applies enforce-when-empty and audit-when-populated and reports
which rule it used as mode_defaulted; choosing in the UI would put one rule
in two places and let them drift. The toast repeats the server's choice.

violations are RENDERED, not toasted, because a list of up to ten document
ids is something an operator reads and clicks - each one links into Documents
with the row open. And they show on SUCCESS too: audit mode arms the schema
while rows violate, which is the entire point of audit and would otherwise be
invisible. armed:false gets the loudest styling in the panel, because the
mode badge above it would otherwise read as protection that is not there.

One refinement found by running it rather than reading it: the panel only
fetches the schema when the collection GET already said has_schema is true.
Asking to be told 404 was a wasted round trip AND a red console entry on
every schema-less collection - noise a developer would eventually chase. The
404 branch stays as the fallback for a stale has_schema. Console is now clean
on both states.

Also records that database 2.18.0 is released, with the typed_range_filters
capability name, and restates upstream's clarification: a PAIR of numeric
bounds always excluded nulls and absent rows on every version, since a null
sorts below every number and fails the gte half. Only a single bound
over-matched. The pair-of-bounds advice in these docs was right as written.
fszontagh 1 сар өмнө
parent
commit
35d3bfbd57

+ 1 - 1
api/llms.txt

@@ -74,7 +74,7 @@ Arbitrary JSON CRUD under a `kind=json` collection.
   - **THE TRAP THAT FOLLOWS, and it is a real one: a version-like value is a NUMBER or a STRING depending on how many dots it happens to have.** A client written and tested against `2026.1.3` works, ships, and silently returns nothing the day the value becomes `2027.1`. Double-quote it and the problem does not exist.
   - `productVersion:eq:'2026.1'` matches nothing: JSON has no single-quoted strings, so the value is the literal six-plus characters `'2026.1'` INCLUDING the quote marks.
   - The operators are `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `contains`, `exists`, `regex`, `search`. **It is `ne`, not `neq`** - an unknown operator is refused 400 `bad_filter` naming it, which is deliberate: a mistyped operator must never be guessed at.
-  **COMPARISONS ORDER ACROSS TYPES, SO A RANGE CAN MATCH A VALUE OF A DIFFERENT KIND - AND THIS CHANGES IN DATABASE 2.18.0.** It was never specified; it is being fixed. From 2.18.0 a range operator (`gt`/`gte`/`lt`/`lte`) matches only number-to-number or string-to-string, so a null, a boolean, an object, an array or a type mismatch never satisfies one on either side, and a null or boolean BOUND matches nothing (5 and 5.0 are both numbers, so they still compare). **`eq`/`ne` are NOT changing** - they keep JSON equality, so `eq null` still matches an explicit null and `ne 2024` still matches null, true and strings while still excluding an absent field. `exists` is unchanged. It is a SERVER-side change, so it takes effect when the database is upgraded and the client version is irrelevant; pin `smartbotic-database (>= 2.18.0)` when you want it. Until then, the behaviour below is what you get. Values order by TYPE: `null` < boolean < number < string. An ABSENT field is different again: every range operator, and `ne`, return FALSE for it. Measured on 2.17.2 over rows holding null, absent, `2024`, `2030`, `"1900"` (a string) and `true`:
+  **COMPARISONS ORDER ACROSS TYPES, SO A RANGE CAN MATCH A VALUE OF A DIFFERENT KIND - AND THIS CHANGES IN DATABASE 2.18.0.** It was never specified; it is being fixed. From 2.18.0 a range operator (`gt`/`gte`/`lt`/`lte`) matches only number-to-number or string-to-string, so a null, a boolean, an object, an array or a type mismatch never satisfies one on either side, and a null or boolean BOUND matches nothing (5 and 5.0 are both numbers, so they still compare). **`eq`/`ne` are NOT changing** - they keep JSON equality, so `eq null` still matches an explicit null and `ne 2024` still matches null, true and strings while still excluding an absent field. `exists` is unchanged. **2.18.0 is RELEASED.** It is a SERVER-side change, so it takes effect when the database is upgraded and the client version is irrelevant; pin `smartbotic-database (>= 2.18.0)` when you want it, and a client from 2.18.0 on can probe the capability name `typed_range_filters`. Note a PAIR of numeric bounds (`gte X` AND `lte Y`) already excluded nulls and absent rows before this change, on every version - a null sorts below every number, so it fails the `gte` half. Only a SINGLE `lt`/`lte` bound over-matched nulls and booleans, and a single `gt`/`gte` bound over-matched strings. Until then, the behaviour below is what you get. Values order by TYPE: `null` < boolean < number < string. An ABSENT field is different again: every range operator, and `ne`, return FALSE for it. Measured on 2.17.2 over rows holding null, absent, `2024`, `2030`, `"1900"` (a string) and `true`:
   ```
   year:lte:2025  ->  null, true, 2024          <- null and a BOOLEAN pass a numeric upper bound
   year:lte:1900  ->  null, true

+ 19 - 0
webui/src/api/client.ts

@@ -7,6 +7,7 @@ import type {
   FunctionSummary,
   FunctionsListResponse, FunctionDetail, FunctionRun, InvokeEnvelope, InvokeRequest,
   ProjectFunctionSettings, ProjectFunctionSettingsPatch,
+  CollectionSchema, SchemaChangeResult, SchemaSuggestion, SchemaMode,
 } from '@/types'
 import { ApiError } from '@/types'
 import { serverUrl } from '@/api/base'
@@ -82,6 +83,24 @@ export const api = {
     request<{ values: IndexValue[] }>(
       `${P(project)}/collections/${enc(coll)}/indexes/${enc(field)}/values?limit=${limit}${order ? `&order=${order}` : ''}`),
 
+  // collection schema (database 2.16.0+; every route answers 501
+  // `server_unsupported` on an older one)
+  getCollectionSchema: (project: string, coll: string) =>
+    request<CollectionSchema>(`${P(project)}/collections/${enc(coll)}/schema`),
+  setCollectionSchema: (project: string, coll: string, schema: unknown, mode?: SchemaMode) =>
+    request<SchemaChangeResult>(`${P(project)}/collections/${enc(coll)}/schema`,
+      // `mode` is omitted rather than defaulted client-side on purpose: the
+      // SERVER picks enforce for an empty collection and audit for a populated
+      // one, and it reports which rule applied as `mode_defaulted`. Choosing
+      // here would duplicate that rule in two places and let them drift.
+      { method: 'PUT', body: JSON.stringify(mode ? { schema, mode } : { schema }) }),
+  removeCollectionSchema: (project: string, coll: string) =>
+    request<{ removed: boolean }>(`${P(project)}/collections/${enc(coll)}/schema`,
+      { method: 'DELETE' }),
+  suggestCollectionSchema: (project: string, coll: string, sampleLimit?: number) =>
+    request<SchemaSuggestion>(
+      `${P(project)}/collections/${enc(coll)}/schema/suggest${sampleLimit ? `?sample_limit=${sampleLimit}` : ''}`),
+
   // documents
   findDocuments: (project: string, coll: string, qs = '') =>
     request<FindResult>(`${P(project)}/collections/${enc(coll)}/documents${qs}`),

+ 391 - 0
webui/src/components/SchemaPanel.tsx

@@ -0,0 +1,391 @@
+import { useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useNavigate } from 'react-router-dom'
+import { FileJson, Wand2, Trash2, AlertTriangle, ShieldAlert, Check } from 'lucide-react'
+import { api } from '@/api/client'
+import { JsonEditor } from '@/components/JsonEditor'
+import { ApiError } from '@/types'
+import type { SchemaMode, SchemaRowViolation } from '@/types'
+import { useToastStore } from '@/stores/toastStore'
+
+/// The optional per-collection JSON Schema (database 2.16.0+).
+///
+/// Three things in here are deliberate rather than incidental:
+///
+/// 1. `hasSchema === undefined` means the DATABASE has no schema support at
+///    all, which is a different statement from "this collection has no
+///    schema". The panel renders nothing in that case rather than offering a
+///    control that would answer 501 - but it says so when expanded from the
+///    collection, instead of silently disappearing.
+/// 2. Suggest PREFILLS the editor and never applies. The server refuses to
+///    apply a suggestion too (`applied: false`), because lengths and ranges
+///    are described rather than enforced, so arming one unseen would create
+///    something that looks stricter than what it checks.
+/// 3. A refused enforce shows the violating document ids as LINKS into
+///    Documents. The Documents page keeps `collection` and `open` in the URL,
+///    so "which row broke this" is one click rather than a copied id.
+export function SchemaPanel({
+  project,
+  collection,
+  hasSchema,
+}: {
+  project: string
+  collection: string
+  /// undefined = this database has no collection schemas (pre-2.16.0)
+  hasSchema?: boolean
+}) {
+  const push = useToastStore((s) => s.push)
+  const queryClient = useQueryClient()
+  const navigate = useNavigate()
+
+  const [draft, setDraft] = useState<string>('')
+  const [editing, setEditing] = useState(false)
+  const [valid, setValid] = useState(true)
+  const [mode, setMode] = useState<SchemaMode | ''>('')
+  const [busy, setBusy] = useState(false)
+  // The counts and examples from the last refused or audited change. Kept in
+  // state rather than shown as a toast: a list of ten document ids is
+  // something an operator reads and clicks, not something that should vanish.
+  const [violations, setViolations] = useState<{
+    rowsChecked: number
+    violatingRows: number
+    examples: SchemaRowViolation[]
+    refused: boolean
+  } | null>(null)
+
+  // A pre-2.16.0 database cannot answer any of these routes, so do not ask.
+  const supported = hasSchema !== undefined
+
+  const { data, isLoading } = useQuery({
+    queryKey: ['collection-schema', project, collection],
+    queryFn: async () => {
+      try {
+        return await api.getCollectionSchema(project, collection)
+      } catch (e) {
+        // 404 `no_schema` is the ordinary "none set" answer, not a failure.
+        if (e instanceof ApiError && e.code === 'no_schema') return null
+        throw e
+      }
+    },
+    // Only ASK when the collection GET already said there is one. `has_schema`
+    // is on that response, so fetching to be told 404 is both a wasted round
+    // trip and a red entry in the browser console on every schema-less
+    // collection - noise a developer will eventually chase. The 404 branch
+    // above stays as the belt-and-braces path for a stale `has_schema` (set
+    // elsewhere, or removed between the two calls).
+    enabled: supported && hasSchema === true,
+  })
+
+  if (!supported) return null
+
+  function describe(e: unknown): string {
+    return e instanceof ApiError ? e.message : 'Request failed'
+  }
+
+  /// Pull the counts out of a refusal so they can be rendered rather than
+  /// flattened into a toast message.
+  function captureViolations(e: unknown, refused: boolean) {
+    if (!(e instanceof ApiError) || e.code !== 'schema_violation') return false
+    const d = (e.details ?? {}) as {
+      rows_checked?: number
+      violating_rows?: number
+      examples?: SchemaRowViolation[]
+    }
+    setViolations({
+      rowsChecked: d.rows_checked ?? 0,
+      violatingRows: d.violating_rows ?? 0,
+      examples: d.examples ?? [],
+      refused,
+    })
+    return true
+  }
+
+  async function suggest() {
+    setBusy(true)
+    try {
+      const s = await api.suggestCollectionSchema(project, collection)
+      setDraft(JSON.stringify(s.schema, null, 2))
+      setEditing(true)
+      setViolations(null)
+      // Said out loud, because the whole risk of this button is someone
+      // believing it applied something.
+      push(
+        s.complete
+          ? `Suggested from ${s.rows_scanned.toLocaleString()} row(s). Nothing has been applied - review it and save.`
+          : `Suggested from a SAMPLE of ${s.rows_scanned.toLocaleString()} row(s), so a field absent here may still exist. Nothing applied.`,
+        'info',
+      )
+    } catch (e) {
+      push(describe(e), 'error')
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  async function save() {
+    let parsed: unknown
+    try {
+      parsed = JSON.parse(draft)
+    } catch {
+      push('The schema is not valid JSON.', 'error')
+      return
+    }
+    setBusy(true)
+    setViolations(null)
+    try {
+      const r = await api.setCollectionSchema(project, collection, parsed, mode || undefined)
+      // violating_rows above zero on SUCCESS means audit mode armed the schema
+      // over data that does not conform. That is the point of audit and it is
+      // invisible if only failures are reported, so it is surfaced here too.
+      if (r.violating_rows > 0) {
+        setViolations({
+          rowsChecked: r.rows_checked,
+          violatingRows: r.violating_rows,
+          examples: r.examples ?? [],
+          refused: false,
+        })
+      }
+      const how = r.mode_defaulted ? ` (${r.mode} chosen for you)` : ''
+      push(`Schema saved in ${r.mode} mode${how}.`, 'success')
+      setEditing(false)
+      await queryClient.invalidateQueries({ queryKey: ['collection-schema', project, collection] })
+      await queryClient.invalidateQueries({ queryKey: ['collection', project, collection] })
+    } catch (e) {
+      if (captureViolations(e, true)) {
+        push('Refused: existing rows do not satisfy this schema. See the list below.', 'error')
+      } else {
+        push(describe(e), 'error')
+      }
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  async function remove() {
+    setBusy(true)
+    try {
+      await api.removeCollectionSchema(project, collection)
+      push('Schema removed. Writes are no longer validated.', 'success')
+      setEditing(false)
+      setDraft('')
+      setViolations(null)
+      await queryClient.invalidateQueries({ queryKey: ['collection-schema', project, collection] })
+      await queryClient.invalidateQueries({ queryKey: ['collection', project, collection] })
+    } catch (e) {
+      push(describe(e), 'error')
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  return (
+    <section className="rounded-lg border border-slate-700/40 bg-slate-800/30 overflow-hidden">
+      <header className="flex items-center justify-between px-3 py-2 border-b border-slate-700/40">
+        <h3 className="flex items-center gap-2 text-sm font-medium text-slate-200">
+          <FileJson className="w-4 h-4 text-slate-400" />
+          Schema
+          {data && (
+            <span
+              className={`px-1.5 py-0.5 rounded text-[11px] font-medium ${
+                data.mode === 'enforce'
+                  ? 'bg-emerald-500/15 text-emerald-300'
+                  : 'bg-amber-500/15 text-amber-300'
+              }`}
+            >
+              {data.mode}
+            </span>
+          )}
+        </h3>
+        <div className="flex items-center gap-2">
+          <button
+            onClick={suggest}
+            disabled={busy}
+            title="Build a schema from the existing rows. Does not apply it."
+            className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium text-indigo-300 bg-indigo-500/10 hover:bg-indigo-500/20 disabled:opacity-50 transition"
+          >
+            <Wand2 className="w-3.5 h-3.5" />
+            Suggest
+          </button>
+          {data && (
+            <button
+              onClick={remove}
+              disabled={busy}
+              title="Remove the schema; writes stop being validated"
+              className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium text-red-300 bg-red-500/10 hover:bg-red-500/20 disabled:opacity-50 transition"
+            >
+              <Trash2 className="w-3.5 h-3.5" />
+              Remove
+            </button>
+          )}
+        </div>
+      </header>
+
+      <div className="p-3 space-y-3">
+        {/* A stored schema that no longer compiles validates NOTHING. Loudest
+            thing in the panel, because the badge above would otherwise read as
+            protection that is not there. */}
+        {data && !data.armed && (
+          <p className="flex items-start gap-2 text-xs text-red-300 bg-red-500/10 border border-red-500/30 rounded px-2 py-1.5">
+            <ShieldAlert className="w-4 h-4 shrink-0 mt-px" />
+            <span>
+              <strong>Not armed.</strong> The stored schema no longer compiles, so nothing is being
+              validated. Writes that would violate it are being accepted. Save a corrected schema or
+              remove it.
+            </span>
+          </p>
+        )}
+
+        {isLoading && <p className="text-xs text-slate-500">Loading…</p>}
+
+        {!isLoading && !data && !editing && (
+          <p className="text-xs text-slate-500">
+            No schema. Writes are not validated. Use <strong>Suggest</strong> to draft one from the
+            existing rows, or{' '}
+            <button onClick={() => { setDraft('{\n  "type": "object"\n}'); setEditing(true) }}
+                    className="text-indigo-300 hover:underline">
+              start from scratch
+            </button>
+            .
+          </p>
+        )}
+
+        {data && !editing && (
+          <>
+            <dl className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
+              <dt className="text-slate-500">Mode</dt>
+              <dd className="text-slate-300">{data.mode}</dd>
+              {data.mode === 'audit' ? (
+                <>
+                  <dt className="text-slate-500">Violating writes let through</dt>
+                  <dd className="text-amber-300">{data.audit_violations.toLocaleString()}</dd>
+                </>
+              ) : (
+                <>
+                  <dt className="text-slate-500">Writes refused</dt>
+                  <dd className="text-slate-300">{data.refusals.toLocaleString()}</dd>
+                </>
+              )}
+            </dl>
+            <pre className="text-[11px] font-mono text-slate-300 bg-slate-900/50 rounded p-2 max-h-56 overflow-auto">
+              {JSON.stringify(data.schema, null, 2)}
+            </pre>
+            <button
+              onClick={() => { setDraft(JSON.stringify(data.schema, null, 2)); setEditing(true) }}
+              className="text-xs text-indigo-300 hover:underline"
+            >
+              Edit
+            </button>
+          </>
+        )}
+
+        {editing && (
+          <div className="space-y-2">
+            <JsonEditor value={draft} onChange={setDraft} onValidityChange={setValid} height={300} />
+            <div className="flex items-center gap-3 flex-wrap">
+              <label className="text-xs text-slate-400">
+                Mode{' '}
+                <select
+                  value={mode}
+                  onChange={(e) => setMode(e.target.value as SchemaMode | '')}
+                  className="ml-1 bg-slate-900/60 border border-slate-700/60 rounded px-1.5 py-1 text-xs text-slate-200"
+                >
+                  {/* The SERVER picks when this is empty, and tells us which
+                      rule it used. Duplicating "enforce if empty, audit if
+                      populated" here would put one rule in two places. */}
+                  <option value="">Choose for me</option>
+                  <option value="enforce">enforce - refuse non-conforming writes</option>
+                  <option value="audit">audit - count them and let them through</option>
+                </select>
+              </label>
+              <button
+                onClick={save}
+                disabled={busy || !valid}
+                className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium text-emerald-300 bg-emerald-500/10 hover:bg-emerald-500/20 disabled:opacity-50 transition"
+              >
+                <Check className="w-3.5 h-3.5" />
+                Save
+              </button>
+              <button
+                onClick={() => { setEditing(false); setViolations(null) }}
+                className="text-xs text-slate-400 hover:text-slate-200"
+              >
+                Cancel
+              </button>
+              {!valid && <span className="text-xs text-red-400">Not valid JSON</span>}
+            </div>
+            <p className="text-[11px] text-slate-500">
+              On an <strong>empty</strong> collection the default is <code>enforce</code>; on a{' '}
+              <strong>populated</strong> one it is <code>audit</code>, because enforce refuses the
+              whole change if any existing row does not conform.
+            </p>
+          </div>
+        )}
+
+        {/* The counts and the offending rows. Rendered rather than toasted:
+            these are what an operator acts on. */}
+        {violations && (
+          <div
+            className={`rounded border px-2 py-1.5 space-y-1 ${
+              violations.refused
+                ? 'border-red-500/30 bg-red-500/10'
+                : 'border-amber-500/30 bg-amber-500/10'
+            }`}
+          >
+            <p className="flex items-start gap-2 text-xs text-slate-200">
+              <AlertTriangle
+                className={`w-4 h-4 shrink-0 mt-px ${
+                  violations.refused ? 'text-red-300' : 'text-amber-300'
+                }`}
+              />
+              <span>
+                {violations.refused ? (
+                  <>
+                    <strong>Not applied.</strong> {violations.violatingRows.toLocaleString()} of{' '}
+                    {violations.rowsChecked.toLocaleString()} existing row(s) do not conform. Fix
+                    them, or save in <code>audit</code> mode to arm it anyway and count them.
+                  </>
+                ) : (
+                  <>
+                    <strong>Armed in audit mode.</strong>{' '}
+                    {violations.violatingRows.toLocaleString()} of{' '}
+                    {violations.rowsChecked.toLocaleString()} existing row(s) do not conform. They
+                    are being counted, not refused.
+                  </>
+                )}
+              </span>
+            </p>
+            {violations.examples.length > 0 && (
+              <ul className="space-y-0.5 pl-6">
+                {violations.examples.map((v) => (
+                  <li key={v.id} className="text-[11px] text-slate-400">
+                    <button
+                      onClick={() =>
+                        navigate(
+                          `/documents?collection=${encodeURIComponent(collection)}&open=${encodeURIComponent(v.id)}`,
+                        )
+                      }
+                      className="font-mono text-indigo-300 hover:underline"
+                    >
+                      {v.id}
+                    </button>
+                    {' — '}
+                    {v.message}
+                    {v.fields.length > 0 && (
+                      <span className="text-slate-500"> ({v.fields.join(', ')})</span>
+                    )}
+                  </li>
+                ))}
+                {violations.violatingRows > violations.examples.length && (
+                  <li className="text-[11px] text-slate-500">
+                    …and {(violations.violatingRows - violations.examples.length).toLocaleString()}{' '}
+                    more (the server reports at most ten examples)
+                  </li>
+                )}
+              </ul>
+            )}
+          </div>
+        )}
+      </div>
+    </section>
+  )
+}

+ 6 - 0
webui/src/pages/Collections.tsx

@@ -12,6 +12,7 @@ import { Modal } from '@/components/Modal'
 import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { IndexPanel } from '@/components/IndexPanel'
 import { RelationsEnforcedPanel } from '@/components/RelationsEnforcedPanel'
+import { SchemaPanel } from '@/components/SchemaPanel'
 import { ApiError } from '@/types'
 import type { CollectionMeta } from '@/types'
 
@@ -337,6 +338,11 @@ function CollectionDetailDrawer({ project, name, onClose }: DetailDrawerProps) {
           {/* Indexes */}
           <IndexPanel project={project} collection={data.name} />
 
+          {/* JSON Schema (database 2.16.0+; the panel renders nothing when
+              `has_schema` is absent, which means this database has no schemas
+              at all rather than this collection having none) */}
+          <SchemaPanel project={project} collection={data.name} hasSchema={data.has_schema} />
+
           {/* Relation enforcement (only when this collection is a parent) */}
           <RelationsEnforcedPanel project={project} collection={data.name}
                                   enforced={data.relations_enforced} />

+ 44 - 0
webui/src/types/index.ts

@@ -6,6 +6,50 @@ export interface CollectionMeta {
   /// Readable since client 2.11.4. Absent means the server could not determine
   /// it, which is never the same as "disabled".
   relations_enforced?: boolean
+  /// Whether a JSON Schema is set. ABSENT when the database predates 2.16.0 and
+  /// has no schemas at all - which is a different statement from "this
+  /// collection has no schema", so it must not be rendered as false.
+  has_schema?: boolean
+}
+
+export type SchemaMode = 'enforce' | 'audit'
+
+export interface SchemaRowViolation {
+  id: string
+  message: string
+  /// Dotted and indexed paths: `addr.zip`, `tags[2]`.
+  fields: string[]
+}
+
+export interface CollectionSchema {
+  schema: Record<string, unknown>
+  mode: SchemaMode
+  /// audit mode: non-conforming writes LET THROUGH since the schema was armed.
+  audit_violations: number
+  /// enforce mode: writes refused since the schema was armed.
+  refusals: number
+  /// false means the stored schema no longer compiles and NOTHING is being
+  /// validated. Worse than having no schema, because it reads as protection.
+  armed: boolean
+}
+
+export interface SchemaChangeResult {
+  mode: SchemaMode
+  /// Whether the server picked the mode, rather than the caller.
+  mode_defaulted: boolean
+  rows_checked: number
+  /// Non-zero on SUCCESS in audit mode: armed, and the data does not conform.
+  violating_rows: number
+  examples: SchemaRowViolation[]
+}
+
+export interface SchemaSuggestion {
+  schema: Record<string, unknown>
+  rows_scanned: number
+  /// false = built from a sample, so a field absent from it may still exist.
+  complete: boolean
+  /// Always false. The server never applies what it suggests.
+  applied: boolean
 }
 export type KeyOp = 'read' | 'list' | 'search' | 'insert' | 'update' | 'delete'
 export interface KeyScopeRule {