Offline GCP IAM Assistant With Local Gemma 4 and SQLite: Five Benchmarks and What Actually Broke

Regulated Canadian teams keep asking whether a useful AI assistant can run completely offline with zero external API calls. To test that on a domain with zero tolerance for invented strings, I benchmarked a local 4-bit Gemma 4 E4B model (4.8 GB Metal VRAM, 5.4 GB RAM on an Apple M5 Pro) against 14,435 canonical GCP IAM permissions and 2,420 predefined roles stored in SQLite.

Across five controlled runs on a 45-question golden set, fixing retrieval (structure-aware chunking plus dual SQLite FTS5) drove overall hard fails to 0.00% and role recall to 93.33%, while base Gemma took 13.71s median latency. A behavioral LoRA that preserved a short 1 to 2 sentence thought block cut median latency 6.8x down to 2.02s and held exact permission recall at 90.00%, at the cost of a 4.44% residual hard-fail rate.

The Setup: Zero-Tolerance Offline Eval

Everything ran locally on an Apple M5 Pro (48 GB unified memory) with zero external API calls. The source corpus is an 8.0 GiB local SQLite crawl (315,051 URLs, 296,974 completed), filtered to 988 IAM pages (42.07 MB) and deduplicated to 901 unique documents in the hybrid index, including 356 /iam/docs/roles-permissions/* service pages. From those tables, a deterministic extractor built the ground-truth catalog: 14,435 canonical permissions, 2,420 predefined roles, and 14,274 custom-role support entries.

All five runs used the exact same model (mlx-community/gemma-4-E4B-it-4bit, temp=0.0, max_tokens=1536), the same embedding model (BAAI/bge-small-en-v1.5, 384-dim on MPS), top_k = 5, the same SYSTEM_PROMPT, and the same 45-question golden set (15 exact permission lookups, 15 least-privilege role selections, and 15 unanswerable/fake-entity refusal checks). A programmatic scorer verified every emitted permission, roles/* ID, and citation against the ground-truth catalog.

[User Question]
       │
       ├──▶ [chunks_fts_exact: per-token quoted FTS5 (tokenchars '._/-')]
       ├──▶ [chunks_fts_text: Porter BM25 + authoritative table slice]
       └──▶ [BAAI/bge-small-en-v1.5: 384-dim cosine similarity on MPS]
                                  │
                                  ▼
                [Weighted RRF Fusion (rrf_k=60, top_k=5)]
                                  │
                                  ▼
         [Local Gemma 4 E4B 4-bit via MLX (Base or LoRA Adapter)]
                                  │
                                  ▼
       [Zero-Tolerance Scorer vs. 14,435 Permissions / 2,420 Roles]

Five Controlled Runs: The Numbers

MetricExp A: Naive VectorExp B: Hybrid v1Exp B2: Hybrid v2Exp C: LoRA (iter 100 / 200)Exp C2: Thought LoRA (iter 80)
Exact Permission Recall (%)78.3390.0090.0081.67 / 71.6790.00
Exact Permission Match (%)66.6776.6786.6766.67 / 56.6780.00
Role Recall (%)70.0086.6793.3386.67 / 86.6786.67
Forbidden Perm Violation (%)6.676.676.670.00 / 0.003.33
Correct Refusal Rate (%)100.0100.0100.093.33 / 93.3393.33
Doc Citation Accuracy (%)53.3376.6790.0076.67 / 63.3376.67
Overall Hard Fail Rate (%)2.222.220.008.89 / 6.674.44
Latency P50 / P95 (s)11.49 / 18.8711.59 / 15.9413.71 / 27.421.33 / 5.73 | 1.22 / 2.032.02 / 8.48
Training Time (s)000~315s / ~627s~413s

Two patterns stand out immediately:

  1. Retrieval sets the hard ceiling (Exp A -> B -> B2): Structure-aware chunking plus stripping repetitive Service agent roles Warning boilerplate cut total chunks by 54% (42,349 -> 19,480) and cut MPS index build time 3.6x (362.87s -> 99.96s). Upgrading retrieval scoring alone in Experiment B2 (zero index rebuild) drove Overall Hard Fail Rate to 0.00%, Role Recall to 93.33%, and Doc Citation Accuracy to 90.00%.
  2. Fine-tuning buys latency, not missing facts (Exp C -> C2): Experiment C (360 zero-leakage synthetic examples, 0.047% trainable params, rank=8, 200 iters) suppressed Gemma 4's spontaneous thinking completely for a 9.5x speedup (11.59s -> 1.22s P50) and 0.00% forbidden violations, but caused role-vs-permission conflation and template leakage (6.67% to 8.89% hard fail). Experiment C2 (rank=8, scale=4.0, 16 layers, 80 iters, ~413s) preserved a 1 to 2 sentence <|channel>thought (~20 to 50 tokens), recovering 90.00% Exact Permission Recall and 80.00% Exact Match at 2.02s P50 (6.8x faster than B2), while leaving 2/45 (4.44%) residual hard fails (perm-04, trick-11).

Three Real Failure Modes (What Actually Broke)

  1. Mid-row Markdown table slicing (role-01): In Cloud Storage IAM docs, each predefined role and its entire permission list sit on a single Markdown table row (median 2,517 chars, max 18,936 chars). Experiment A's 1,200-char windows sliced right through the middle of a row, severing the role header from its permissions and causing Gemma to bind storage.objects.get and storage.objects.list to roles/storage.expressModeServiceOutput instead of roles/storage.objectViewer. Experiment B2 fixed it (100% recall and match).
  2. Duplicate REST /delete pages drowning canonical roles (perm-08): Asked for the permission to delete a GCP project, pure dense vectors ranked docs.cloud.google.com/iam/docs/reference/rest/v1/organizations.roles/delete and cloud.google.com/iam/reference/rest/v1/organizations.roles/delete in Top-5 slots 1 and 2, pushing resourcemanager.projects.delete out of context. Experiment B2's content_hash dedup and authoritative table BM25 slice fixed it.
  3. Service-agent mega-roles hijacking multi-permission FTS5 (role-12): In Experiment B, joining two exact permissions with OR ("bigquery.jobs.create" OR "bigquery.tables.getData") caused giant cross-service roles that happen to hold both strings (roles/looker.serviceAgent, roles/enterpriseknowledgegraph.serviceAgent, roles/dlp.projectdriver) to outrank roles/bigquery.jobUser and roles/bigquery.dataViewer. Experiment B2 eliminated service-agent hijacking with per-token FTS5 fan-out and a 0.35 downweight on serviceAgent and jobfunctions roles.

When to Use Each Stack

StackBest ForMeasured Accuracy / Hard FailsLatencyInfrastructure FootprintMain Risk
Base Gemma 4 + Hybrid SQLite v2Air-gapped security audits and compliance checks where correctness beats speed0.00% hard fail, 93.33% role recall, 90.00% doc citations13.71s P50 / 27.42s P954.8 GB VRAM, 5.4 GB RAM, 63 MiB indexSlow multi-second thinking traces on every turn
Concise-Thought LoRA (Exp C2) + Hybrid v2Interactive local developer assistants with strict latency budgets4.44% hard fail, 90.00% exact perm recall, 80.00% exact match2.02s P50 / 8.48s P95Same footprint + tiny rank=8 LoRA (~6m 53s to train)Residual 2/45 slips on trick refusals and rare role echoes
Regional Canadian Cloud API + Hybrid RAGMulti-user enterprise teams needing frontier reasoning inside Canadian residencyNot benchmarked here; depends on host modelNetwork-boundRegional VPC + private endpoints (northamerica-northeast1 / Canada Central)Egress governance, per-token spend, and cloud ops

Appendix: Under-the-Hood Mechanics

  1. Cross-host 1-byte diffs defeating content_hash dedup: cloud.google.com and docs.cloud.google.com returned 1,901 raw /iam/ rows that differed by roughly 1 byte, bypassing pure hash deduplication until lowercase URL-path dedup ran first (973 unique /iam/ docs, 988 with product IAM pages), followed by content_hash dedup (901 unique docs) to strip REST path aliases.
  2. SQLite FTS5 dot-quoting trap: Default unicode61 splits storage.objects.get on . and /, blurring it with storage.objects.list. Switching to unicode61 tokenchars '._/-' fixes tokenization, but unquoted storage.objects.get then raises fts5: syntax error near ".", requiring double-quoted tokens across dual FTS5 tables (exact + porter).
  3. Gemma 4's spontaneous <|channel>thought channel: Even with enable_thinking=False and no <|think|> token injected, gemma-4-E4B-it-4bit entered <|channel>thought on 44 of 45 multi-source RAG prompts. At max_tokens=384, 0/44 finished thinking; prefilling <|channel>thought\n<channel|> failed too (Gemma printed a plain-text Thought Process: plus a stray <channel|>). Allowing native generation up to max_tokens=1536 and parsing past <channel|> fixed truncation (0/45 empty answers).
  4. Gemma 4 chat_template.jinja silently stripping training thoughts: Gemma 4's Jinja template runs strip_thinking() on every role == 'model' message without tool_calls, so mlx_lm.lora's built-in ChatDataset silently deleted all <|channel>thought...<channel|> tokens before training. Preserving concise thoughts in Experiment C2 required a custom ThoughtChatDataset that renders the prompt prefix and directly encodes the completion with special token IDs (<|channel>=100, <channel|>=101, <turn|>=106).
  5. Checkpoint overfit past iter 100 and scale: 20.0 repetition loops: In Experiment C, training from iter 100 to iter 200 dropped Exact Permission Recall by 10 percentage points (81.67% -> 71.67%) even though val_loss looked flat (0.011 -> 0.007), and drove template-echo garbling ("is not present" loops on trick-11). In the first C2 attempt, repeated imperative checklist lines in thoughts plus scale: 20.0 across 8 layers triggered a 70x greedy repetition loop that never closed <channel|>. Switching to varied 1 to 2 sentence natural thoughts and scale: 4.0 across 16 layers eliminated loops (0/45).
  6. Authoritative-table boost trade-off (role_def vs product_iam): Boosting role_def (1.25) over product_iam (1.00) in Experiment B2 eliminated hard fails across the board, with one subtle side effect on perm-01 and perm-03: roles/storage.legacyBucketReader displaced /storage/docs/access-control/iam-permissions, because role tables list permissions without explaining action-level preconditions (such as object overwrite requiring both create and delete).