[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69A7C1H3WHRY82ZTVS9CQDW":3,"skill-same:01M69A7C1H3WHRY82ZTVS9CQDW":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":53,"linkOnly":54,"markdownContent":55,"markdownBody":56,"frontMatter":57,"refName":58,"commitSha":59,"skillDirectory":60,"forksCount":61,"repositoryHtmlUrl":62,"repositoryHomepageUrl":17,"ownerHtmlUrl":63,"ownerBlogUrl":64,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M69A7C1H3WHRY82ZTVS9CQDW","horizondb-idiosyncrasies","Azure HorizonDB 特性与故障排查","Work with Azure HorizonDB (preview) — its AI\u002Fembedding features, extension allow-listing, AGE\u002Fpgvector\u002Fpg_durable quirks, and the connection\u002FTLS gotchas discovered while bringing up the horizon-facts incubator. Use when connecting to a HorizonDB cluster, enabling extensions, writing AGE Cypher, wiring in-DB embeddings via pg_durable df.http(), or debugging \"extension not allow-listed\" \u002F \"access to library not allowed\" \u002F \"self-signed certificate\" \u002F Cypher syntax errors.","使用 Azure HorizonDB（预览版）——其 AI\u002F嵌入功能、扩展允许清单、AGE\u002Fpgvector\u002Fpg_durable 怪癖，以及在启动 horizon-facts 孵化项目时发现的连接\u002FTLS 陷阱。适用于连接 HorizonDB 集群、启用扩展、编写 AGE Cypher、通过 pg_durable df.http() 接入数据库内嵌入，或调试“扩展未在允许清单中”\u002F“不允许访问该库”\u002F“自签名证书”\u002FCypher 语法错误等情形。","microsoft\u002FPilotSwarm","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69A6RNK492A5JSNBTXANKX5",16,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fhorizondb-idiosyncrasies\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BS1P4QM1G70C9FKMTZ88VK","数据库管理","SCENARIO","使用场景",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BTGTEHKD89NSZ5CT4Y5AGV","数据工程师","PROFESSION","适用职业",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],"horizondb idiosyncrasies","listing","writing","when","wiring","features","errors","embedding","df","db","self","preview","up","syntax","work","access","certificate","cypher","tls","library","embeddings","debugging","2026-11-10 10:12:30",false,"---\nname: horizondb-idiosyncrasies\ndescription: Work with Azure HorizonDB (preview) — its AI\u002Fembedding features, extension allow-listing, AGE\u002Fpgvector\u002Fpg_durable quirks, and the connection\u002FTLS gotchas discovered while bringing up the horizon-facts incubator. Use when connecting to a HorizonDB cluster, enabling extensions, writing AGE Cypher, wiring in-DB embeddings via pg_durable df.http(), or debugging \"extension not allow-listed\" \u002F \"access to library not allowed\" \u002F \"self-signed certificate\" \u002F Cypher syntax errors.\n---\n\n# HorizonDB Idiosyncrasies\n\nAzure HorizonDB is a managed, preview Postgres-17 service (a.k.a. OrionDB\ninternally). It bundles AI\u002Fgraph\u002Fvector\u002Fdurable-execution extensions but locks\nthem behind an allow-list and several managed-PG restrictions that differ from\nvanilla Postgres. This skill captures the verified facts and the workarounds.\n\n> Reference implementation: `incubator\u002Fhorizon-facts\u002F` — a HorizonDB-only\n> enhanced facts interface. Its integration suite (`test\u002Fintegration\u002F`) runs\n> live against a HorizonDB cluster and exercises every capability below.\n\n## Quick reference\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `self-signed certificate in certificate chain` | pg v8 treats `sslmode=require` as `verify-full` | append `uselibpqcompat=true` to the connection string |\n| `extension \"X\" is not allow-listed for \"azure_pg_admin\" users` | empty\u002Finsufficient `azure.extensions` on the parameter group | add X to `azure.extensions` on a custom parameter group, attach it to the cluster's pool |\n| `access to library \"age\" is not allowed` | `age` is in `shared_preload_libraries`; explicit `LOAD 'age'` is forbidden | tolerate that error — the library is already preloaded |\n| `syntax error at or near \"WHERE\"` from `cypher_parser.c` | AGE doesn't support `any(x IN list WHERE pred)` | use `size([x IN list WHERE pred]) > 0` |\n| `schema \"...\" already exists` creating an AGE graph | graph name collides with an existing schema (`create_graph` makes a schema) | give the graph a name distinct from every other schema |\n| `relation \"\u003Clabel>\" already exists` (`42P07`) **or** `duplicate key … \"pg_class_relname_nsp_index\"` (`23505`) under concurrent graph writes | AGE creates a label's backing table lazily on first `CREATE`\u002F`MERGE`; concurrent first-references race the DDL (two detection points) | re-run the same idempotent statement — the label now exists (see §3 concurrency) |\n| `cannot cast type agtype to jsonb` | `agtype` has no jsonb cast | `RETURN` scalars\u002F`label()`\u002F`type()`, parse client-side |\n| `ECONNRESET` \u002F `Connection terminated unexpectedly` mid-workload | HorizonDB resets idle pooled TLS connections | guard + bounded retry on a **fresh** connection (§1.1) |\n| AGE writes are 600 ms–2 s each under concurrency | small connection pool → ops queue (connection-queue wait, not query cost) | raise `poolMax` for the parallelism (default now 16, `HORIZON_POOL_MAX`); per-connection AGE setup; fewer round-trips per upsert (§3 performance) |\n\n## 1. Connection & TLS\n\nHorizonDB requires SSL. The cluster's certificate chain is **not** in Node's\ndefault trust store, and modern `pg` (v8+) \u002F `pg-connection-string` treat\n`sslmode=require` as `verify-full`, so a plain `?sslmode=require` URL fails with:\n\n```\nCONN FAIL: self-signed certificate in certificate chain\n```\n\n**Fix:** append `uselibpqcompat=true`, which restores libpq semantics where\n`require` means *encrypt but don't verify the CA*:\n\n```\npostgresql:\u002F\u002FUSER:PW@\u003Ccluster>.\u003Cid>.\u003Cregion>.horizondb.azure.com:5432\u002Fpostgres?sslmode=require&uselibpqcompat=true\n```\n\nFor production trust verification, install the Azure CA bundle and use\n`sslmode=verify-full` with an explicit `ca`. For dev\u002Ftest against preview\nclusters, `uselibpqcompat=true` is the pragmatic path. The horizon-facts test\nharness normalizes this automatically — see `normalizeDbUrl()` in\n`incubator\u002Fhorizon-facts\u002Ftest\u002Fintegration\u002F_db.mjs`.\n\n### 1.1 Idle pooled connections get reset — guard + retry on a fresh connection\n\nHorizonDB (preview) intermittently drops **idle pooled TLS connections**. Under a\nsustained workload this surfaces two ways:\n\n- an **uncaught** `error` event on a checked-out client (`ECONNRESET`) — this\n  crashes a long-running Node process unless you attach a pool\u002Fclient `error`\n  handler;\n- a **rejected** query (`ENOTCONN` \u002F `EPIPE` \u002F `Connection terminated\n  unexpectedly`) from `pool.query`.\n\nNeither partially commits, so re-running on a **fresh** connection is safe.\nPattern (see `incubator\u002Fhorizon-facts\u002Fsrc\u002Fdb-retry.ts`):\n\n- `pool.on(\"error\", …)` and a process-level guard that swallow **only** this\n  transient socket class;\n- a bounded retry (`withDbRetry`) that re-acquires a connection and re-runs.\n\n**Keep two retry classifiers distinct** — they target different recovery actions:\n\n| Classifier | Matches | Retry action |\n| --- | --- | --- |\n| `isTransientDbError` | `ECONNRESET`\u002F`ENOTCONN`\u002F`EPIPE`\u002F`Connection terminated` + pg `08xxx`\u002F`57P0x` | re-run on a **fresh** connection |\n| `isLabelCreationRaceError` | `42P07` **or** `23505` on a `pg_catalog` index (`pg_class_*`\u002F`pg_type_*`\u002F`pg_namespace_*`) | re-run the **same** statement (AGE label race, §3) |\n\nDo **not** lump the label race into the connection regex, and do **not** retry a\nbare `23505` — a unique violation on a *user* constraint is a real error; only\nthe **system-catalog** index variant is the label race.\n\n## 2. Extension allow-list (the #1 blocker)\n\nHorizonDB rejects `CREATE EXTENSION` unless the extension name is in the\n`azure.extensions` server parameter, even for the admin user:\n\n```\nERROR: extension \"vector\" is not allow-listed for \"azure_pg_admin\" users\n        in Azure Database for PostgreSQL  (SQLSTATE 0A000)\n```\n\nThe **default parameter group** (`default_pg17`) ships with `azure.extensions`\n**empty** — only `plpgsql` is installed. The extensions exist on the image\n(check `pg_available_extensions`), they're just not allowed yet.\n\n### Available AI\u002Fgraph extensions (PG17 image, verified 2026-06)\n\n| Extension | Version | Purpose |\n| --- | --- | --- |\n| `vector` (pgvector) | 0.8.0 | embedding storage + HNSW ANN |\n| `age` (Apache AGE) | 1.6.0 | property graph + Cypher |\n| `pg_durable` | 0.2.1 | durable execution + `df.http()` for in-DB HTTP |\n| `pg_textsearch` | 1.3.0-dev | ranked lexical search |\n| `azure_ai` | 2.2.1 | native in-DB model inference (Azure-managed) |\n| `pg_diskann` | 0.7.1 | disk-based ANN index (azure.extensions ONLY — NOT preloadable) |\n\n### Enabling extensions\n\nYou **cannot** set `azure.extensions` per-session. You must create a custom\n**parameter group** (settings group), set the allow-list (and\n`shared_preload_libraries` for preload-required extensions), and attach it to\nthe cluster's **pool**. Attaching restarts the server once (about 10 s down)\nwhen `shared_preload_libraries` changes.\n\n**Preload requirements:** `age` and `pg_durable` must be in\n`shared_preload_libraries`. `vector` and `pg_textsearch` only need to be in\n`azure.extensions`. `pg_diskann` is `azure.extensions`-ONLY — it is **rejected**\nin `shared_preload_libraries` (HorizonDB's allowed preload set is fixed and does\nnot include it), yet works without preloading.\n\n#### API 2026-10-01-preview: pools own compute and the settings group\n\nThe deploy module (`deploy\u002Fproviders\u002Fazure\u002Fservices\u002Fhorizondb\u002Fbicep\u002Fmain.bicep`\nplus `ensureHorizonDbParameterGroup` in `deploy\u002Fscripts\u002Flib\u002Fhorizondb.mjs`)\nuses API `2026-10-01-preview`. Its rules, each found by a failed deploy:\n\n| Rule | What happens otherwise |\n| --- | --- |\n| Compute (`computeModel`, `nodeCount`) and `parameterGroup` live on `clusters\u002F{c}\u002Fpools\u002F{pool}`, not on the cluster | the cluster PUT ignores them |\n| A new pool accepts only the built-in group `\u002Fsubscriptions\u002F{s}\u002Fproviders\u002FMicrosoft.HorizonDb\u002Flocations\u002F{region}\u002FparameterGroups\u002Fdefault_pg17`; attach the custom group with a pool PATCH afterwards | pool create is rejected |\n| `clusters\u002F{c}\u002Fauthentications\u002FpasswordMethod` needs an existing pool | `Pool 'DefaultPool' was not found` |\n| `administratorLogin` can be sent once; later PUTs send only the password (a reset) | `administratorLogin cannot be specified because an administrator is already configured` |\n| PUT the settings group before the cluster, not in parallel: a PUT to a group that a pool uses keeps the cluster `Updating` for about a minute | cluster PUT fails with `ClusterNotReady` |\n| Read the host name from `clusters\u002F{c}\u002Fendpoints\u002F{c}` (role ReadWrite). New clusters use `{c}.rw.{id}.{region}.horizondb.azure.com` | the old API's `fullyQualifiedDomainName` does not resolve for new clusters |\n| One pool request may change only one property group (`nodeCount` + `highAvailability`, or `parameterGroup`). Pools of clusters migrated from the old API can show no `highAvailability` and no group, so a full pool PUT changes two groups. The deploy module PUTs the pool only to create it | `The request changes multiple Pool property groups ... Submit a separate request for each property group` |\n| Settings groups can be updated (PUT\u002FPATCH); connected pools pick up the change | (API 2026-01-20-preview rejected updates with `ParameterGroupUpdateNotSupported`) |\n\n**Attach timing.** A pool PATCH takes about two minutes. During that time the\npool GET still shows the **previous** group as `Succeeded` \u002F `InSync`; the\nserver restarts about a minute in, and the GET shows the new group only when\nthe operation ends. Send **one** PATCH, then wait until the GET shows the new\ngroup with `syncStatus: InSync` (or follow the `Azure-AsyncOperation` URL).\n\n**The first PATCH soon after a pool is created can be dropped:** it ends\n`Succeeded`, no restart happens, and the pool stays on the built-in group.\nSeen twice, each time within a minute of the pool's create and login writes.\nA second PATCH then attached normally. `ensureHorizonDbParameterGroup`\nresends the PATCH when the GET still shows another group four minutes later\n(at most three PATCHes).\n\n`syncStatus` values: `Applying`, `InSync`, `PendingReboot` (static settings\nwait for `POST ...\u002Fpools\u002F{pool}\u002Frestart`), `FailedToApply`. With\n`applyMethod: Immediate` the service applied `shared_preload_libraries`\nwithout a manual restart in testing; the deploy still handles `PendingReboot`.\n\n#### Via ARM (az rest)\n\n```bash\nSUB=\u003Csubscription-id>; RG=\u003Cresource-group>; API=2026-10-01-preview\nCLUSTER=\u003Ccluster-name>; PG=\u003Ccluster>-ext; REGION=\u003Cregion>\n\n# 1. Create or update the settings group. Only the listed values are stored\n#    as overrides (valueSource UserOverride); the rest are service defaults.\ncat > \u002Ftmp\u002Fpg-body.json \u003C\u003CEOF\n{\n  \"location\": \"$REGION\",\n  \"properties\": {\n    \"description\": \"Enable AI\u002Fgraph extensions\",\n    \"postgreSqlVersion\": \"17\",\n    \"parameters\": [\n      { \"name\": \"azure.extensions\",          \"value\": \"age,azure_ai,pg_diskann,pg_durable,pg_textsearch,vector\" },\n      { \"name\": \"shared_preload_libraries\",  \"value\": \"age,pg_durable,pg_textsearch\" }\n    ]\n  }\n}\nEOF\naz rest --method put \\\n  --url \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F$SUB\u002FresourceGroups\u002F$RG\u002Fproviders\u002FMicrosoft.HorizonDb\u002FparameterGroups\u002F$PG?api-version=$API\" \\\n  --headers \"Content-Type=application\u002Fjson\" --body @\u002Ftmp\u002Fpg-body.json\n\n# 2. Attach it to the pool (one restart). Then poll the pool GET until it\n#    shows this group with syncStatus InSync (about two minutes).\naz rest --method patch \\\n  --url \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F$SUB\u002FresourceGroups\u002F$RG\u002Fproviders\u002FMicrosoft.HorizonDb\u002Fclusters\u002F$CLUSTER\u002Fpools\u002FDefaultPool?api-version=$API\" \\\n  --headers \"Content-Type=application\u002Fjson\" \\\n  --body \"{\\\"properties\\\":{\\\"parameterGroup\\\":{\\\"parameterGroupResourceId\\\":\\\"\u002Fsubscriptions\u002F$SUB\u002FresourceGroups\u002F$RG\u002Fproviders\u002FMicrosoft.HorizonDb\u002FparameterGroups\u002F$PG\\\",\\\"applyMethod\\\":\\\"Immediate\\\"}}}\"\n```\n\nNotes:\n- The platform **re-injects its own system preload libs** (`azure`,\n  `orion_storage`, `pg_availability`, `pg_qs`, `pgms_stats`,\n  `pgms_wait_sampling`, and on newer builds `pgaadauth`, `horizondb_ext`) on\n  top of yours — you only list the extras.\n- List the built-in groups with\n  `GET \u002Fsubscriptions\u002F{s}\u002Fproviders\u002FMicrosoft.HorizonDb\u002Flocations\u002F{region}\u002FparameterGroups?api-version=2026-10-01-preview`.\n- Extension versions depend on the server build. Clusters created at different\n  times can run different builds (for example `age` 1.7.0 on one and 1.8.0 on\n  a newer one); check `pg_available_extensions` on the cluster you test.\n\n### Verify after restart\n\n```js\nawait pool.query(`show shared_preload_libraries`);      \u002F\u002F includes age,pg_durable,pg_textsearch\nawait pool.query(`CREATE EXTENSION IF NOT EXISTS vector`);\nawait pool.query(`CREATE EXTENSION IF NOT EXISTS age`);\nawait pool.query(`CREATE EXTENSION IF NOT EXISTS pg_durable`);\n\u002F\u002F df.http() should now exist:\nawait pool.query(`select proname from pg_proc\n                  where proname='http' and pronamespace::regnamespace::text='df'`);\n```\n\n## 3. Apache AGE quirks\n\n### Don't `LOAD 'age'` when it's preloaded\n\nOn vanilla Postgres you must `LOAD 'age'` per session. On HorizonDB `age` is in\n`shared_preload_libraries`, so it's already loaded and an explicit `LOAD` is\n**rejected**:\n\n```\nERROR: access to library \"age\" is not allowed\n```\n\nMake the load tolerant — attempt it (for portability to vanilla PG) but swallow\nthat one error:\n\n```ts\nasync function loadAge(client: any): Promise\u003Cvoid> {\n  try { await client.query(`LOAD 'age'`); }\n  catch (err: any) {\n    if (!\u002Faccess to library \"age\" is not allowed\u002Fi.test(String(err?.message ?? \"\"))) throw err;\n    \u002F\u002F already preloaded via shared_preload_libraries — nothing to do\n  }\n}\n```\n\nStill run `SET search_path = ag_catalog, \"$user\", public` on every AGE session.\n\n### Graph name must differ from every schema name\n\n`SELECT create_graph('g')` creates a **Postgres schema** named `g`. If you also\nhave a facts\u002Fdata schema named `g`, you get `schema \"g\" already exists`. Always\nuse distinct names (e.g. data schema `hf_test_\u003Cr>`, graph `hf_graph_\u003Cr>`).\n\n### Cypher: no `any(... WHERE ...)`\n\nAGE 1.6.0's Cypher parser rejects the list predicate `any(x IN list WHERE pred)`\nwith `syntax error at or near \"WHERE\"` (`cypher_parser.c`). Use the\nlist-comprehension + `size()` form instead:\n\n```cypher\n-- BROKEN on AGE:\nWHERE any(a IN e.aliases WHERE toLower(a) CONTAINS 'tgl')\n-- WORKS:\nWHERE size([a IN e.aliases WHERE toLower(a) CONTAINS 'tgl']) > 0\n```\n\n`UNWIND ... WITH x WHERE ...` also works. When in doubt, probe syntax against a\nthrowaway graph before committing to a query shape.\n\n### Other AGE limitations to design around\n\n- Avoid `startNode()` \u002F `endNode()` \u002F `UNWIND` over variable-length paths. For\n  neighbourhood edges, collect node keys first, then match edges with\n  `WHERE a.entity_key IN [...] AND b.entity_key IN [...]`.\n- Cypher cannot be parameterized through pg bind params — values are inlined\n  into the `cypher('graph', $$ ... $$)` literal. Use a strict escaping helper\n  (see `cypherStr` \u002F `cypherStrList` \u002F `cypherNum` in horizon-facts `sql-util.ts`)\n  and never interpolate untrusted text without it.\n- `agtype` has **no cast to `jsonb`** (`cannot cast type agtype to jsonb`). Don't\n  return a whole node\u002Fedge and cast it — `RETURN` the scalars you need, or\n  `label(x)` \u002F `type(r)`, and parse the agtype scalars client-side.\n\n### AGE concurrency: lazy label creation races (SQLSTATE 42P07)\n\nAGE creates a label's backing **table** *lazily* — on the first `CREATE`\u002F`MERGE`\nthat references a label that doesn't exist yet. That internal check-then-`CREATE\nTABLE` is **not atomic and not serialized**. Any concurrent writer (a\nconnection-per-call pool, or an LLM agent issuing parallel tool calls) that\nraces the *first* reference to the same label hits the collision in **one of two\nforms**, depending on where the duplicate is detected:\n\n```\nrelation \"GraphNode\" already exists                                  -- 42P07 duplicate_table\nduplicate key value violates unique constraint \"pg_class_relname_nsp_index\"  -- 23505 unique_violation\n```\n\nThe `42P07` form is caught at the relation level; the `23505` form fires when two\n`CREATE TABLE` for the same label race into the **`pg_class` system catalog**\nbefore either registered. **Both are the same race** and both **abort the whole\nstatement** (the MERGE\u002FCREATE persisted nothing). Errors are **front-loaded** —\nthey cluster on the first touch of each label, then disappear once the backing\ntables exist.\n\n> ⚠️ The `23505` form is easy to miss: the \"already exists\" text is in\n> `err.detail`, **not** `err.message` (the message is \"duplicate key value …\").\n> A message-only regex will silently let it through. Key off the SQLSTATE +\n> the catalog constraint name (`pg_class_*` \u002F `pg_type_*` \u002F `pg_namespace_*`).\n\n**Do not \"fix\" this in a migration by pre-creating labels.** In an open graph the\nlabel set (node kinds, edge predicates) is owned by the *application\u002Fagent layer*,\nnot infrastructure — it's unbounded and unknowable at migrate time. Pre-creating\na fixed set only masks the case you thought of.\n\n**Correct, label-agnostic fix:** the statement is idempotent, so on the label\nrace, **re-run the same statement** — the label now exists and the re-run\nsucceeds. Match **both** manifestations, and for `23505` retry **only** when the\nviolated constraint is a system catalog index (never a user constraint):\n\n```ts\nconst CATALOG_RACE_CONSTRAINT = \u002Fpg_(class|type|namespace)_\u002Fi;\nfunction isLabelCreationRaceError(err: any): boolean {\n  if (String(err?.code) === \"42P07\") return true;                     \u002F\u002F duplicate_table\n  if (String(err?.code) === \"23505\") {                                \u002F\u002F unique_violation…\n    const c = String(err?.constraint ?? \"\"), m = String(err?.message ?? \"\");\n    if (CATALOG_RACE_CONSTRAINT.test(c) || CATALOG_RACE_CONSTRAINT.test(m)) return true;  \u002F\u002F …on a pg_catalog index\n  }\n  return \u002Falready exists\u002Fi.test(String(err?.message ?? \"\"));\n}\n```\n\nImplement it at the single point where Cypher is executed, so it covers every\nlabel automatically:\n\n```ts\n\u002F\u002F in the one cypher(client, query) helper:\nconst { rows } = await withDbRetry(\n  \"graph_label_race\",\n  () => client.query(sql),\n  { isRetryable: isLabelCreationRaceError });   \u002F\u002F 42P07 OR 23505-on-catalog\n```\n\nSafe because each `cypher()` call is its own autocommit statement (a prior\nfailure doesn't poison the connection) and all graph writes are idempotent MERGE.\n\n> **Ask of AGE\u002FHorizonDB:** make first-reference label creation atomic\n> (advisory-lock or true `CREATE TABLE IF NOT EXISTS` semantics) so callers don't\n> have to retry DDL races on the hot path.\n\n### AGE concurrency: no unique constraints → MERGE can duplicate\n\nAGE vertices\u002Fedges have **no unique indexes\u002Fconstraints**, so a naive\n`MERGE (f:Fact {scope_key}) MERGE (e)-[:EVIDENCED_BY]->(f)` can, under\nconcurrency, create **duplicate** `:Fact` anchors; a later MERGE then binds every\nduplicate and multiplies edges. Use read-decide-write instead: check whether the\nedge already exists, bind exactly one anchor (`WITH … LIMIT 1`), and only create\nwhen none exists (see `linkEvidenceAnchor` in `graph-queries.ts`).\n\n### AGE performance: write latency = round-trips × RTT\n\nOn a remote cluster, AGE write latency is dominated by the **number of round\ntrips**, not query cost. Measured in a 119-fact agent harvest:\n\n| op | p50 | why |\n| --- | --- | --- |\n| `graph_upsert_edge` | ~610 ms | endpoint check + existing-edge read + create\u002Freinforce = 3+ statements |\n| `graph_upsert_node` | ~730 ms | existence read + create\u002Fupdate + per-evidence anchor link |\n| single stored proc (`facts_set_crawled`) | ~67 ms | one round trip |\n\nA single round trip to the remote cluster is ~45–100 ms, so a multi-statement\nupsert is a half-second of pure latency. **The agent-driven harvest is too noisy\nto measure tuning changes** (every run issues a different number of calls with\ndifferent concurrency; unrelated ops like `facts_similar` swing 5× between runs\nfrom DB contention). Use a **deterministic microbenchmark** instead — see\n`incubator\u002Fhorizon-facts\u002Feval\u002Fbench-graph.mjs`, which drives a fixed set of\nupserts directly (no LLM) and reports clean p50\u002Fp95 plus the RTT and\n`age-prep` primitives.\n\nThree compounding causes and their fixes, **biggest lever first**:\n\n1. **Connection-pool starvation (the dominant cost).** The harvester fires graph\n   tool calls in **parallel**, but a small pool serializes them — the measured\n   per-op p50 is then mostly **connection-queue wait**, not work. Deterministic\n   sweep (80 nodes + 80 edges, concurrency 8):\n\n   | `poolMax` | node wall | node p50 | edge wall |\n   | --- | --- | --- | --- |\n   | 3 (old default) | 6017 ms | 407 ms | 4517 ms |\n   | 8 | 3415 ms | 224 ms | 1997 ms |\n   | 16 | 1506 ms | 97 ms | 2669 ms |\n\n   Pool 3→8 is **~45–55% faster**; 3→16 is **~75% faster** on nodes. The\n   \"round-trips\u002Fop\" estimate (`p50 \u002F RTT`) collapses from ~9 to ~2 as the pool\n   grows — proving the apparent \"9 round trips\" was queue wait; the real work is\n   ~2 round trips (existence-check + create). **Fix:** size the pool for the\n  expected parallelism. horizon-facts now defaults `poolMax` to **16** (was 3),\n   overridable via `HORIZON_POOL_MAX` — bounded by the cluster's\n   `max_connections`.\n\n### Migration locking: keep the global lock narrow\n\nThe Horizon facts migrator uses a per-schema advisory lock for ordinary schema\nmigrations. Only database-global DDL (for example `CREATE EXTENSION` and AGE\n`ag_catalog.create_graph`) should take the global Horizon DDL lock, and it\nshould be transaction-scoped (`pg_try_advisory_xact_lock`) so an idle pooled\nconnection cannot retain it after the protected transaction ends. Do not wrap the\nentire per-schema migration run in a session-level global lock; concurrent SDK\n`--with-horizondb` tests create many isolated `ps_test_facts_*` schemas and a\nbroad global lock becomes a suite-wide bottleneck or stale-lock failure.\n\n2. **Per-checkout session setup.** Running `LOAD 'age'` (a wasted *failed* round\n   trip when preloaded) + `SET search_path` on every graph-op checkout adds ~2\n   round trips (measured `age-prep` p50 ≈ 93 ms). **Fix:** do AGE session setup\n   **once per physical connection** — horizon-facts caches prepared connections\n   in a `WeakSet\u003Cclient>` in `GraphQueries` (a reset connection yields a new\n   client object → re-prepared automatically). Measured **~17–18% faster** per\n   op. A pg-pool `connect`-event handler is the equivalent if you don't hold a\n   client wrapper:\n\n   ```ts\n   pool.on(\"connect\", (client) => {\n     client.query(\"LOAD 'age'\").catch(() => {});              \u002F\u002F tolerate preloaded\n     client.query(`SET search_path = ag_catalog, \"$user\", public`).catch(() => {});\n   });\n   ```\n\n3. **Multi-statement upserts.** Collapse existence-check + write into a single\n   `MERGE … ON CREATE SET … ON MATCH SET …` where it's race-safe, and batch\n   independent upserts. Fewer statements = fewer round trips.\n\n> **Ask of AGE:** the `cypher()` SRF wrapper carries per-call overhead; a way to\n> issue multiple graph mutations per round trip (or a lighter write path) would\n> materially help write-heavy workloads.\n\n## 4. AI \u002F embeddings — two paths\n\nHorizonDB offers **two** ways to generate embeddings in-database. Pick based on\nwhat your cluster allows and where the model lives.\n\n### Path A — `pg_durable` `df.http()` (external endpoint) ✅ verified working\n\n`pg_durable` exposes `df.http(url, method, body, headers jsonb, timeout_seconds)`\nfor durable HTTP calls from inside the database. This is the supported in-DB HTTP\nprimitive on HorizonDB — **`pgsql-http` (the `http` extension) is NOT available**;\nonly `azure_ai` and `pg_durable` ship.\n\n`incubator\u002Fhorizon-facts\u002Fsql\u002F006_embeddings_http.sql` + `src\u002Fhttp-embedding.ts`\nimplement this end-to-end (verified against the live cluster, embedding real\n1536-dim vectors). The hard-won mechanics:\n\n**1. `df.http()` is a durable FUTURE, not a synchronous call.** It returns a\nnode descriptor (`{\"node_type\":\"HTTP\",...}`), not the response. You run it via\n`df.start(fut, label, database)` → instance id, then poll\n`df.wait_for_completion(iid, timeout)` and read `df.result(iid)`:\n\n```sql\nv_iid := df.start(df.http(url,'POST',body,headers,30), 'hz-embed', NULL);\nCOMMIT;                                  -- ⚠️ see (2)\nPERFORM df.wait_for_completion(v_iid, 40);\nv_res := df.result(v_iid);               -- text JSON, see (3)\n```\n\n**2. Must COMMIT between start and wait → use a PROCEDURE, not a function.** The\n`pg_durable` worker runs the instance in its OWN connection and can't see the\ninstance row until the enqueuing transaction commits. So you cannot\n`df.start` + `df.wait_for_completion` inside one SQL function (functions can't\ncommit and would deadlock until timeout). Drive it from a **plpgsql PROCEDURE**\nthat `COMMIT`s after `df.start`. A `FOR row IN SELECT … LOOP … COMMIT … END LOOP`\nwith commits inside works on HorizonDB's PG17.\n\n**3. `df.result()` shape:** text JSON with keys\n`{ok, body, status, headers, duration_ms}`. `body` is the raw response string.\nFor an AOAI embeddings response:\n`(((df.result(iid)::jsonb->>'body')::jsonb->'data'->0->'embedding')::text)::vector`.\nCheck `(res::jsonb->>'ok')::boolean` first.\n\n**4. `df.http()` enforces an Azure egress ALLOW-LIST.** Only approved Azure\nservice domains are permitted. The Azure AI Foundry **unified** host\n`*.services.ai.azure.com` is **BLOCKED** — the instance fails with\n`\"... is not in the allowed endpoint list. Only requests to approved Azure\nservice domains are permitted.\"` The **classic Azure OpenAI host\n`*.openai.azure.com`** points at the same deployment and **IS allowed**.\n`setupHttpEmbedding` auto-rewrites the host (`toAllowlistedAzureHost`). The\n`cognitiveservices.azure.com` host also works. (The Node fallback uses Node\nfetch and works with either host.)\n\n**5. Grant HTTP usage:** `SELECT df.grant_usage(current_user, true, false);`\n(the `true` = include_http). Idempotent.\n\n**6. Recurring \u002F cron embedder via `df.loop` (sub-minute cadence).** pg_durable\nexposes futures combinators — `df.seq(a,b)` (THEN), `df.loop(body)`,\n`df.sleep(seconds)`, `df.sql(query)`, `df.race`, `df.if*`, plus `df.cancel`,\n`df.signal`, `df.wait_for_schedule(cron_expr)`. They serialize to a node tree\n(`{\"node_type\":\"LOOP\",\"left_node\":{...}}`) and you launch with `df.start`. For a\n**self-perpetuating recurring job** at a fixed interval, wrap a sleep+work\nsequence in a loop:\n\n```sql\n-- every N seconds, embed any changed facts (the loop is pure scheduling; the\n-- per-fact df.http embedding lives in the CALLed procedure → \"nested\" durability)\nSELECT df.start(\n  df.loop(df.seq(df.sleep(5::bigint), df.sql('CALL \"schema\".embed_new_facts_durable(128, NULL)'))),\n  'hz-embed-cron:schema', NULL);\n```\n\n- `df.wait_for_schedule` takes a real cron expression but only **minute**\n  granularity — for sub-minute ticks (e.g. every 5s) you MUST use `df.sleep`.\n- A loop calling a procedure that itself starts `df.http` instances works fine\n  (verified): the loop ticks, the proc runs nested durable HTTP per fact, the\n  pg_durable worker handles both. The loop instance stays `pending`\u002F`running`.\n- Track\u002Fstop by a **stable label** (e.g. `hz-embed-cron:\u003Cschema>`): look it up in\n  `df.instances` (PK column is `id`, plus `label`, `status`, `created_at`;\n  terminal statuses are `completed`\u002F`cancelled`\u002F`failed`, active are\n  `pending`\u002F`running`). Make `start` idempotent by reusing any non-terminal\n  instance with that label; `stop` = `df.cancel(id, reason)`.\n\n**7. Embedding is a PROVIDER-INTERNAL lifecycle, not a contract method.**\nPilotSwarm only knows the `EnhancedFactStore` interface; its sole embedding\nresponsibility is passing the endpoint config. *How\u002Fwhen* embeddings are produced\nis the provider's private business. The HorizonDB provider exposes only a\nlifecycle on `HorizonFactStore` (`src\u002Fhorizon-store.ts`):\n- `configureEmbedder(endpoint)` — write\u002Freplace the `embedding_config` row (with\n  the df.http allow-list host rewrite).\n- `startEmbedder({ intervalSeconds = 5, batch = 128 })` — launch the durable\n  df.loop cron; idempotent; returns `EmbedderStatus { running, instanceId?, status? }`.\n- `stopEmbedder()` — `df.cancel` the loop.\n- `embedderStatus()` — derived `{ running }` (no df leakage in the shape).\n\nCallers **never** trigger embedding or wait on a df instance — they write facts\nand observe the **outcome** (vector present \u002F semantic search returns the fact).\n\nThe two `@internal` methods `_embedPendingNode()` and `_embedNewFactsInDbOnce()`\nare **NOT production paths** — they are sanity checks for the df.http path:\n`_embedPendingNode` posts the *identical* request df.http builds (same headers\u002F\nbody, read from `embedding_config`) via Node fetch, so it validates the request\nshape against a Node-reachable stub; `_embedNewFactsInDbOnce` is a one-shot\nsynchronous trigger of the same procedure the cron CALLs. Both are exercised only\nby the **provider's own** integration tests (`test\u002Fintegration\u002Fhttp-embeddings.test.mjs`),\nwhich legitimately assert on df internals because they test the *mechanism*.\nPilotSwarm-level tests must stay outcome-only and never reference df.\n\nOther constraints:\n- Store the source-content hash alongside the vector so re-embeds only happen\n  when content changes (`last_embedded_hash IS DISTINCT FROM content_hash`).\n- `df.instances` (with your `label`) is the audit trail that a durable HTTP call\n  actually ran; it's global, not schema-scoped.\n- Inspect failures via `df.instance_nodes(iid, 1)` → the node `status`\u002F`result`.\n\n### Path B — `azure_ai` (Azure-managed inference)\n\n`azure_ai` is HorizonDB's native model-management\u002Finference extension. It wires\nembeddings\u002Fcompletions to Azure-managed model endpoints from inside the DB\n(no external HTTP plumbing). Cluster-side feature gating (`aiModelManagement`)\nmay need to be enabled before it works. Prefer this when you want managed,\nin-region inference and don't want to operate your own endpoint.\n\n### Path C — Node-side fallback (`embedPending()`)\n\nFor bootstrapping, clusters without a working in-DB HTTP path, or local tests,\nembed from the application: read pending facts, call the embeddings endpoint\nfrom Node, write `vector(dim)` back. Reference: `embedPending()` \u002F\n`http-embedding.ts` in horizon-facts. Still requires `vector` to be allow-listed\nso the `embedding vector(dim)` column and HNSW index exist.\n\n## 5. pgvector notes\n\n- `CREATE EXTENSION vector` after allow-listing; `vector` 0.8.0 supports `hnsw`\n  and `ivfflat` AMs out of the box.\n- HNSW index: `USING hnsw (embedding vector_cosine_ops)`.\n- **DiskANN is a SEPARATE extension (`pg_diskann`), not pgvector core.** On the\n  cluster it shows in `pg_available_extensions` (0.7.1). It is **NOT installed by\n  default** and must be allow-listed in `azure.extensions`. **IMPORTANT: unlike\n  Azure Flexible Server, HorizonDB does NOT require (and REJECTS) `pg_diskann` in\n  `shared_preload_libraries`** — the allowed preload set is fixed\n  (`age, auto_explain, azure_storage, pg_cron, pg_durable, pg_partman_bgw,\n  pg_prewarm, pg_stat_statements, pg_textsearch, pgaudit, wal2json`); adding\n  `pg_diskann` there fails the parameter group with `ParameterValueInvalid`. Put\n  `pg_diskann` in `azure.extensions` ONLY — it works without preload (verified\n  2026-06 on `waldemort-cms-2`: `CREATE EXTENSION pg_diskann` + `USING diskann\n  (embedding vector_cosine_ops)` both succeed). It shares the `vector_cosine_ops`\n  opclass and the `\u003C=>` operator with HNSW, so query code is identical.\n  horizon-facts selects the AM via `annIndex: \"diskann\"|\"hnsw\"|\"auto\"` (env\n  `HORIZON_ANN_INDEX`); `auto` (default) tries diskann and falls back to hnsw\n  when it isn't allow-listed (`ensureAnnIndex` in `migrations.ts`).\n- A jsonb array text `\"[...]\"` casts directly to `vector` — handy when parsing\n  an embeddings HTTP response: `(emb_json::text)::vector`.\n- Embedding dimension must match the endpoint's model exactly, or inserts fail.\n\n## 6. Networking \u002F firewall\n\n- HorizonDB firewall rules live under\n  `clusters\u002F{cluster}\u002Fpools\u002F{pool}\u002FfirewallRules`. With API\n  `2026-10-01-preview`, `GET clusters\u002F{cluster}\u002Fpools` lists the pools (the\n  default one is `DefaultPool`) and the firewall rule collection can be listed.\n  Add one rule per client IPv4; never open a broad range.\n- Connections still require the TLS handling from §1 once the firewall is open.\n\n## 7. Working checklist for a fresh cluster\n\n1. Add a firewall rule for your IP on the pool (§6).\n2. Connect with `?sslmode=require&uselibpqcompat=true`; confirm `select version()`.\n3. Create a settings group with `azure.extensions` and\n   `shared_preload_libraries` for the extensions you need, attach it to the\n   pool, and wait until the pool GET shows it as `InSync` (§2).\n4. `CREATE EXTENSION` for `vector`, `age`, `pg_durable`, `pg_textsearch` as needed.\n5. For AGE: tolerant `LOAD 'age'`, set `search_path`, distinct graph vs schema\n   names, avoid `any(... WHERE ...)`.\n6. For embeddings: choose `df.http()` (external endpoint reachable from cluster),\n   `azure_ai` (managed), or Node-side `embedPending()`; run generation as a\n   `pg_durable` activity; hash-guard re-embeds.\n\n## See also\n\n- `incubator\u002Fhorizon-facts\u002FREADME.md` — capability overview + design rules\n- `incubator\u002Fhorizon-facts\u002FCRAWLER-SPEC.md` — embedding pipeline + AGE graph contract\n- `incubator\u002Fhorizon-facts\u002Ftest\u002Fintegration\u002F` — live HorizonDB tests for all of the above\n- repo memory `horizondb-incubator-2026-06-02.md` — the original bring-up notes\n","# HorizonDB Idiosyncrasies\n\nAzure HorizonDB is a managed, preview Postgres-17 service (a.k.a. OrionDB\ninternally). It bundles AI\u002Fgraph\u002Fvector\u002Fdurable-execution extensions but locks\nthem behind an allow-list and several managed-PG restrictions that differ from\nvanilla Postgres. This skill captures the verified facts and the workarounds.\n\n> Reference implementation: `incubator\u002Fhorizon-facts\u002F` — a HorizonDB-only\n> enhanced facts interface. Its integration suite (`test\u002Fintegration\u002F`) runs\n> live against a HorizonDB cluster and exercises every capability below.\n\n## Quick reference\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `self-signed certificate in certificate chain` | pg v8 treats `sslmode=require` as `verify-full` | append `uselibpqcompat=true` to the connection string |\n| `extension \"X\" is not allow-listed for \"azure_pg_admin\" users` | empty\u002Finsufficient `azure.extensions` on the parameter group | add X to `azure.extensions` on a custom parameter group, attach it to the cluster's pool |\n| `access to library \"age\" is not allowed` | `age` is in `shared_preload_libraries`; explicit `LOAD 'age'` is forbidden | tolerate that error — the library is already preloaded |\n| `syntax error at or near \"WHERE\"` from `cypher_parser.c` | AGE doesn't support `any(x IN list WHERE pred)` | use `size([x IN list WHERE pred]) > 0` |\n| `schema \"...\" already exists` creating an AGE graph | graph name collides with an existing schema (`create_graph` makes a schema) | give the graph a name distinct from every other schema |\n| `relation \"\u003Clabel>\" already exists` (`42P07`) **or** `duplicate key … \"pg_class_relname_nsp_index\"` (`23505`) under concurrent graph writes | AGE creates a label's backing table lazily on first `CREATE`\u002F`MERGE`; concurrent first-references race the DDL (two detection points) | re-run the same idempotent statement — the label now exists (see §3 concurrency) |\n| `cannot cast type agtype to jsonb` | `agtype` has no jsonb cast | `RETURN` scalars\u002F`label()`\u002F`type()`, parse client-side |\n| `ECONNRESET` \u002F `Connection terminated unexpectedly` mid-workload | HorizonDB resets idle pooled TLS connections | guard + bounded retry on a **fresh** connection (§1.1) |\n| AGE writes are 600 ms–2 s each under concurrency | small connection pool → ops queue (connection-queue wait, not query cost) | raise `poolMax` for the parallelism (default now 16, `HORIZON_POOL_MAX`); per-connection AGE setup; fewer round-trips per upsert (§3 performance) |\n\n## 1. Connection & TLS\n\nHorizonDB requires SSL. The cluster's certificate chain is **not** in Node's\ndefault trust store, and modern `pg` (v8+) \u002F `pg-connection-string` treat\n`sslmode=require` as `verify-full`, so a plain `?sslmode=require` URL fails with:\n\n```\nCONN FAIL: self-signed certificate in certificate chain\n```\n\n**Fix:** append `uselibpqcompat=true`, which restores libpq semantics where\n`require` means *encrypt but don't verify the CA*:\n\n```\npostgresql:\u002F\u002FUSER:PW@\u003Ccluster>.\u003Cid>.\u003Cregion>.horizondb.azure.com:5432\u002Fpostgres?sslmode=require&uselibpqcompat=true\n```\n\nFor production trust verification, install the Azure CA bundle and use\n`sslmode=verify-full` with an explicit `ca`. For dev\u002Ftest against preview\nclusters, `uselibpqcompat=true` is the pragmatic path. The horizon-facts test\nharness normalizes this automatically — see `normalizeDbUrl()` in\n`incubator\u002Fhorizon-facts\u002Ftest\u002Fintegration\u002F_db.mjs`.\n\n### 1.1 Idle pooled connections get reset — guard + retry on a fresh connection\n\nHorizonDB (preview) intermittently drops **idle pooled TLS connections**. Under a\nsustained workload this surfaces two ways:\n\n- an **uncaught** `error` event on a checked-out client (`ECONNRESET`) — this\n  crashes a long-running Node process unless you attach a pool\u002Fclient `error`\n  handler;\n- a **rejected** query (`ENOTCONN` \u002F `EPIPE` \u002F `Connection terminated\n  unexpectedly`) from `pool.query`.\n\nNeither partially commits, so re-running on a **fresh** connection is safe.\nPattern (see `incubator\u002Fhorizon-facts\u002Fsrc\u002Fdb-retry.ts`):\n\n- `pool.on(\"error\", …)` and a process-level guard that swallow **only** this\n  transient socket class;\n- a bounded retry (`withDbRetry`) that re-acquires a connection and re-runs.\n\n**Keep two retry classifiers distinct** — they target different recovery actions:\n\n| Classifier | Matches | Retry action |\n| --- | --- | --- |\n| `isTransientDbError` | `ECONNRESET`\u002F`ENOTCONN`\u002F`EPIPE`\u002F`Connection terminated` + pg `08xxx`\u002F`57P0x` | re-run on a **fresh** connection |\n| `isLabelCreationRaceError` | `42P07` **or** `23505` on a `pg_catalog` index (`pg_class_*`\u002F`pg_type_*`\u002F`pg_namespace_*`) | re-run the **same** statement (AGE label race, §3) |\n\nDo **not** lump the label race into the connection regex, and do **not** retry a\nbare `23505` — a unique violation on a *user* constraint is a real error; only\nthe **system-catalog** index variant is the label race.\n\n## 2. Extension allow-list (the #1 blocker)\n\nHorizonDB rejects `CREATE EXTENSION` unless the extension name is in the\n`azure.extensions` server parameter, even for the admin user:\n\n```\nERROR: extension \"vector\" is not allow-listed for \"azure_pg_admin\" users\n        in Azure Database for PostgreSQL  (SQLSTATE 0A000)\n```\n\nThe **default parameter group** (`default_pg17`) ships with `azure.extensions`\n**empty** — only `plpgsql` is installed. The extensions exist on the image\n(check `pg_available_extensions`), they're just not allowed yet.\n\n### Available AI\u002Fgraph extensions (PG17 image, verified 2026-06)\n\n| Extension | Version | Purpose |\n| --- | --- | --- |\n| `vector` (pgvector) | 0.8.0 | embedding storage + HNSW ANN |\n| `age` (Apache AGE) | 1.6.0 | property graph + Cypher |\n| `pg_durable` | 0.2.1 | durable execution + `df.http()` for in-DB HTTP |\n| `pg_textsearch` | 1.3.0-dev | ranked lexical search |\n| `azure_ai` | 2.2.1 | native in-DB model inference (Azure-managed) |\n| `pg_diskann` | 0.7.1 | disk-based ANN index (azure.extensions ONLY — NOT preloadable) |\n\n### Enabling extensions\n\nYou **cannot** set `azure.extensions` per-session. You must create a custom\n**parameter group** (settings group), set the allow-list (and\n`shared_preload_libraries` for preload-required extensions), and attach it to\nthe cluster's **pool**. Attaching restarts the server once (about 10 s down)\nwhen `shared_preload_libraries` changes.\n\n**Preload requirements:** `age` and `pg_durable` must be in\n`shared_preload_libraries`. `vector` and `pg_textsearch` only need to be in\n`azure.extensions`. `pg_diskann` is `azure.extensions`-ONLY — it is **rejected**\nin `shared_preload_libraries` (HorizonDB's allowed preload set is fixed and does\nnot include it), yet works without preloading.\n\n#### API 2026-10-01-preview: pools own compute and the settings group\n\nThe deploy module (`deploy\u002Fproviders\u002Fazure\u002Fservices\u002Fhorizondb\u002Fbicep\u002Fmain.bicep`\nplus `ensureHorizonDbParameterGroup` in `deploy\u002Fscripts\u002Flib\u002Fhorizondb.mjs`)\nuses API `2026-10-01-preview`. Its rules, each found by a failed deploy:\n\n| Rule | What happens otherwise |\n| --- | --- |\n| Compute (`computeModel`, `nodeCount`) and `parameterGroup` live on `clusters\u002F{c}\u002Fpools\u002F{pool}`, not on the cluster | the cluster PUT ignores them |\n| A new pool accepts only the built-in group `\u002Fsubscriptions\u002F{s}\u002Fproviders\u002FMicrosoft.HorizonDb\u002Flocations\u002F{region}\u002FparameterGroups\u002Fdefault_pg17`; attach the custom group with a pool PATCH afterwards | pool create is rejected |\n| `clusters\u002F{c}\u002Fauthentications\u002FpasswordMethod` needs an existing pool | `Pool 'DefaultPool' was not found` |\n| `administratorLogin` can be sent once; later PUTs send only the password (a reset) | `administratorLogin cannot be specified because an administrator is already configured` |\n| PUT the settings group before the cluster, not in parallel: a PUT to a group that a pool uses keeps the cluster `Updating` for about a minute | cluster PUT fails with `ClusterNotReady` |\n| Read the host name from `clusters\u002F{c}\u002Fendpoints\u002F{c}` (role ReadWrite). New clusters use `{c}.rw.{id}.{region}.horizondb.azure.com` | the old API's `fullyQualifiedDomainName` does not resolve for new clusters |\n| One pool request may change only one property group (`nodeCount` + `highAvailability`, or `parameterGroup`). Pools of clusters migrated from the old API can show no `highAvailability` and no group, so a full pool PUT changes two groups. The deploy module PUTs the pool only to create it | `The request changes multiple Pool property groups ... Submit a separate request for each property group` |\n| Settings groups can be updated (PUT\u002FPATCH); connected pools pick up the change | (API 2026-01-20-preview rejected updates with `ParameterGroupUpdateNotSupported`) |\n\n**Attach timing.** A pool PATCH takes about two minutes. During that time the\npool GET still shows the **previous** group as `Succeeded` \u002F `InSync`; the\nserver restarts about a minute in, and the GET shows the new group only when\nthe operation ends. Send **one** PATCH, then wait until the GET shows the new\ngroup with `syncStatus: InSync` (or follow the `Azure-AsyncOperation` URL).\n\n**The first PATCH soon after a pool is created can be dropped:** it ends\n`Succeeded`, no restart happens, and the pool stays on the built-in group.\nSeen twice, each time within a minute of the pool's create and login writes.\nA second PATCH then attached normally. `ensureHorizonDbParameterGroup`\nresends the PATCH when the GET still shows another group four minutes later\n(at most three PATCHes).\n\n`syncStatus` values: `Applying`, `InSync`, `PendingReboot` (static settings\nwait for `POST ...\u002Fpools\u002F{pool}\u002Frestart`), `FailedToApply`. With\n`applyMethod: Immediate` the service applied `shared_preload_libraries`\nwithout a manual restart in testing; the deploy still handles `PendingReboot`.\n\n#### Via ARM (az rest)\n\n```bash\nSUB=\u003Csubscription-id>; RG=\u003Cresource-group>; API=2026-10-01-preview\nCLUSTER=\u003Ccluster-name>; PG=\u003Ccluster>-ext; REGION=\u003Cregion>\n\n# 1. Create or update the settings group. Only the listed values are stored\n#    as overrides (valueSource UserOverride); the rest are service defaults.\ncat > \u002Ftmp\u002Fpg-body.json \u003C\u003CEOF\n{\n  \"location\": \"$REGION\",\n  \"properties\": {\n    \"description\": \"Enable AI\u002Fgraph extensions\",\n    \"postgreSqlVersion\": \"17\",\n    \"parameters\": [\n      { \"name\": \"azure.extensions\",          \"value\": \"age,azure_ai,pg_diskann,pg_durable,pg_textsearch,vector\" },\n      { \"name\": \"shared_preload_libraries\",  \"value\": \"age,pg_durable,pg_textsearch\" }\n    ]\n  }\n}\nEOF\naz rest --method put \\\n  --url \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F$SUB\u002FresourceGroups\u002F$RG\u002Fproviders\u002FMicrosoft.HorizonDb\u002FparameterGroups\u002F$PG?api-version=$API\" \\\n  --headers \"Content-Type=application\u002Fjson\" --body @\u002Ftmp\u002Fpg-body.json\n\n# 2. Attach it to the pool (one restart). Then poll the pool GET until it\n#    shows this group with syncStatus InSync (about two minutes).\naz rest --method patch \\\n  --url \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F$SUB\u002FresourceGroups\u002F$RG\u002Fproviders\u002FMicrosoft.HorizonDb\u002Fclusters\u002F$CLUSTER\u002Fpools\u002FDefaultPool?api-version=$API\" \\\n  --headers \"Content-Type=application\u002Fjson\" \\\n  --body \"{\\\"properties\\\":{\\\"parameterGroup\\\":{\\\"parameterGroupResourceId\\\":\\\"\u002Fsubscriptions\u002F$SUB\u002FresourceGroups\u002F$RG\u002Fproviders\u002FMicrosoft.HorizonDb\u002FparameterGroups\u002F$PG\\\",\\\"applyMethod\\\":\\\"Immediate\\\"}}}\"\n```\n\nNotes:\n- The platform **re-injects its own system preload libs** (`azure`,\n  `orion_storage`, `pg_availability`, `pg_qs`, `pgms_stats`,\n  `pgms_wait_sampling`, and on newer builds `pgaadauth`, `horizondb_ext`) on\n  top of yours — you only list the extras.\n- List the built-in groups with\n  `GET \u002Fsubscriptions\u002F{s}\u002Fproviders\u002FMicrosoft.HorizonDb\u002Flocations\u002F{region}\u002FparameterGroups?api-version=2026-10-01-preview`.\n- Extension versions depend on the server build. Clusters created at different\n  times can run different builds (for example `age` 1.7.0 on one and 1.8.0 on\n  a newer one); check `pg_available_extensions` on the cluster you test.\n\n### Verify after restart\n\n```js\nawait pool.query(`show shared_preload_libraries`);      \u002F\u002F includes age,pg_durable,pg_textsearch\nawait pool.query(`CREATE EXTENSION IF NOT EXISTS vector`);\nawait pool.query(`CREATE EXTENSION IF NOT EXISTS age`);\nawait pool.query(`CREATE EXTENSION IF NOT EXISTS pg_durable`);\n\u002F\u002F df.http() should now exist:\nawait pool.query(`select proname from pg_proc\n                  where proname='http' and pronamespace::regnamespace::text='df'`);\n```\n\n## 3. Apache AGE quirks\n\n### Don't `LOAD 'age'` when it's preloaded\n\nOn vanilla Postgres you must `LOAD 'age'` per session. On HorizonDB `age` is in\n`shared_preload_libraries`, so it's already loaded and an explicit `LOAD` is\n**rejected**:\n\n```\nERROR: access to library \"age\" is not allowed\n```\n\nMake the load tolerant — attempt it (for portability to vanilla PG) but swallow\nthat one error:\n\n```ts\nasync function loadAge(client: any): Promise\u003Cvoid> {\n  try { await client.query(`LOAD 'age'`); }\n  catch (err: any) {\n    if (!\u002Faccess to library \"age\" is not allowed\u002Fi.test(String(err?.message ?? \"\"))) throw err;\n    \u002F\u002F already preloaded via shared_preload_libraries — nothing to do\n  }\n}\n```\n\nStill run `SET search_path = ag_catalog, \"$user\", public` on every AGE session.\n\n### Graph name must differ from every schema name\n\n`SELECT create_graph('g')` creates a **Postgres schema** named `g`. If you also\nhave a facts\u002Fdata schema named `g`, you get `schema \"g\" already exists`. Always\nuse distinct names (e.g. data schema `hf_test_\u003Cr>`, graph `hf_graph_\u003Cr>`).\n\n### Cypher: no `any(... WHERE ...)`\n\nAGE 1.6.0's Cypher parser rejects the list predicate `any(x IN list WHERE pred)`\nwith `syntax error at or near \"WHERE\"` (`cypher_parser.c`). Use the\nlist-comprehension + `size()` form instead:\n\n```cypher\n-- BROKEN on AGE:\nWHERE any(a IN e.aliases WHERE toLower(a) CONTAINS 'tgl')\n-- WORKS:\nWHERE size([a IN e.aliases WHERE toLower(a) CONTAINS 'tgl']) > 0\n```\n\n`UNWIND ... WITH x WHERE ...` also works. When in doubt, probe syntax against a\nthrowaway graph before committing to a query shape.\n\n### Other AGE limitations to design around\n\n- Avoid `startNode()` \u002F `endNode()` \u002F `UNWIND` over variable-length paths. For\n  neighbourhood edges, collect node keys first, then match edges with\n  `WHERE a.entity_key IN [...] AND b.entity_key IN [...]`.\n- Cypher cannot be parameterized through pg bind params — values are inlined\n  into the `cypher('graph', $$ ... $$)` literal. Use a strict escaping helper\n  (see `cypherStr` \u002F `cypherStrList` \u002F `cypherNum` in horizon-facts `sql-util.ts`)\n  and never interpolate untrusted text without it.\n- `agtype` has **no cast to `jsonb`** (`cannot cast type agtype to jsonb`). Don't\n  return a whole node\u002Fedge and cast it — `RETURN` the scalars you need, or\n  `label(x)` \u002F `type(r)`, and parse the agtype scalars client-side.\n\n### AGE concurrency: lazy label creation races (SQLSTATE 42P07)\n\nAGE creates a label's backing **table** *lazily* — on the first `CREATE`\u002F`MERGE`\nthat references a label that doesn't exist yet. That internal check-then-`CREATE\nTABLE` is **not atomic and not serialized**. Any concurrent writer (a\nconnection-per-call pool, or an LLM agent issuing parallel tool calls) that\nraces the *first* reference to the same label hits the collision in **one of two\nforms**, depending on where the duplicate is detected:\n\n```\nrelation \"GraphNode\" already exists                                  -- 42P07 duplicate_table\nduplicate key value violates unique constraint \"pg_class_relname_nsp_index\"  -- 23505 unique_violation\n```\n\nThe `42P07` form is caught at the relation level; the `23505` form fires when two\n`CREATE TABLE` for the same label race into the **`pg_class` system catalog**\nbefore either registered. **Both are the same race** and both **abort the whole\nstatement** (the MERGE\u002FCREATE persisted nothing). Errors are **front-loaded** —\nthey cluster on the first touch of each label, then disappear once the backing\ntables exist.\n\n> ⚠️ The `23505` form is easy to miss: the \"already exists\" text is in\n> `err.detail`, **not** `err.message` (the message is \"duplicate key value …\").\n> A message-only regex will silently let it through. Key off the SQLSTATE +\n> the catalog constraint name (`pg_class_*` \u002F `pg_type_*` \u002F `pg_namespace_*`).\n\n**Do not \"fix\" this in a migration by pre-creating labels.** In an open graph the\nlabel set (node kinds, edge predicates) is owned by the *application\u002Fagent layer*,\nnot infrastructure — it's unbounded and unknowable at migrate time. Pre-creating\na fixed set only masks the case you thought of.\n\n**Correct, label-agnostic fix:** the statement is idempotent, so on the label\nrace, **re-run the same statement** — the label now exists and the re-run\nsucceeds. Match **both** manifestations, and for `23505` retry **only** when the\nviolated constraint is a system catalog index (never a user constraint):\n\n```ts\nconst CATALOG_RACE_CONSTRAINT = \u002Fpg_(class|type|namespace)_\u002Fi;\nfunction isLabelCreationRaceError(err: any): boolean {\n  if (String(err?.code) === \"42P07\") return true;                     \u002F\u002F duplicate_table\n  if (String(err?.code) === \"23505\") {                                \u002F\u002F unique_violation…\n    const c = String(err?.constraint ?? \"\"), m = String(err?.message ?? \"\");\n    if (CATALOG_RACE_CONSTRAINT.test(c) || CATALOG_RACE_CONSTRAINT.test(m)) return true;  \u002F\u002F …on a pg_catalog index\n  }\n  return \u002Falready exists\u002Fi.test(String(err?.message ?? \"\"));\n}\n```\n\nImplement it at the single point where Cypher is executed, so it covers every\nlabel automatically:\n\n```ts\n\u002F\u002F in the one cypher(client, query) helper:\nconst { rows } = await withDbRetry(\n  \"graph_label_race\",\n  () => client.query(sql),\n  { isRetryable: isLabelCreationRaceError });   \u002F\u002F 42P07 OR 23505-on-catalog\n```\n\nSafe because each `cypher()` call is its own autocommit statement (a prior\nfailure doesn't poison the connection) and all graph writes are idempotent MERGE.\n\n> **Ask of AGE\u002FHorizonDB:** make first-reference label creation atomic\n> (advisory-lock or true `CREATE TABLE IF NOT EXISTS` semantics) so callers don't\n> have to retry DDL races on the hot path.\n\n### AGE concurrency: no unique constraints → MERGE can duplicate\n\nAGE vertices\u002Fedges have **no unique indexes\u002Fconstraints**, so a naive\n`MERGE (f:Fact {scope_key}) MERGE (e)-[:EVIDENCED_BY]->(f)` can, under\nconcurrency, create **duplicate** `:Fact` anchors; a later MERGE then binds every\nduplicate and multiplies edges. Use read-decide-write instead: check whether the\nedge already exists, bind exactly one anchor (`WITH … LIMIT 1`), and only create\nwhen none exists (see `linkEvidenceAnchor` in `graph-queries.ts`).\n\n### AGE performance: write latency = round-trips × RTT\n\nOn a remote cluster, AGE write latency is dominated by the **number of round\ntrips**, not query cost. Measured in a 119-fact agent harvest:\n\n| op | p50 | why |\n| --- | --- | --- |\n| `graph_upsert_edge` | ~610 ms | endpoint check + existing-edge read + create\u002Freinforce = 3+ statements |\n| `graph_upsert_node` | ~730 ms | existence read + create\u002Fupdate + per-evidence anchor link |\n| single stored proc (`facts_set_crawled`) | ~67 ms | one round trip |\n\nA single round trip to the remote cluster is ~45–100 ms, so a multi-statement\nupsert is a half-second of pure latency. **The agent-driven harvest is too noisy\nto measure tuning changes** (every run issues a different number of calls with\ndifferent concurrency; unrelated ops like `facts_similar` swing 5× between runs\nfrom DB contention). Use a **deterministic microbenchmark** instead — see\n`incubator\u002Fhorizon-facts\u002Feval\u002Fbench-graph.mjs`, which drives a fixed set of\nupserts directly (no LLM) and reports clean p50\u002Fp95 plus the RTT and\n`age-prep` primitives.\n\nThree compounding causes and their fixes, **biggest lever first**:\n\n1. **Connection-pool starvation (the dominant cost).** The harvester fires graph\n   tool calls in **parallel**, but a small pool serializes them — the measured\n   per-op p50 is then mostly **connection-queue wait**, not work. Deterministic\n   sweep (80 nodes + 80 edges, concurrency 8):\n\n   | `poolMax` | node wall | node p50 | edge wall |\n   | --- | --- | --- | --- |\n   | 3 (old default) | 6017 ms | 407 ms | 4517 ms |\n   | 8 | 3415 ms | 224 ms | 1997 ms |\n   | 16 | 1506 ms | 97 ms | 2669 ms |\n\n   Pool 3→8 is **~45–55% faster**; 3→16 is **~75% faster** on nodes. The\n   \"round-trips\u002Fop\" estimate (`p50 \u002F RTT`) collapses from ~9 to ~2 as the pool\n   grows — proving the apparent \"9 round trips\" was queue wait; the real work is\n   ~2 round trips (existence-check + create). **Fix:** size the pool for the\n  expected parallelism. horizon-facts now defaults `poolMax` to **16** (was 3),\n   overridable via `HORIZON_POOL_MAX` — bounded by the cluster's\n   `max_connections`.\n\n### Migration locking: keep the global lock narrow\n\nThe Horizon facts migrator uses a per-schema advisory lock for ordinary schema\nmigrations. Only database-global DDL (for example `CREATE EXTENSION` and AGE\n`ag_catalog.create_graph`) should take the global Horizon DDL lock, and it\nshould be transaction-scoped (`pg_try_advisory_xact_lock`) so an idle pooled\nconnection cannot retain it after the protected transaction ends. Do not wrap the\nentire per-schema migration run in a session-level global lock; concurrent SDK\n`--with-horizondb` tests create many isolated `ps_test_facts_*` schemas and a\nbroad global lock becomes a suite-wide bottleneck or stale-lock failure.\n\n2. **Per-checkout session setup.** Running `LOAD 'age'` (a wasted *failed* round\n   trip when preloaded) + `SET search_path` on every graph-op checkout adds ~2\n   round trips (measured `age-prep` p50 ≈ 93 ms). **Fix:** do AGE session setup\n   **once per physical connection** — horizon-facts caches prepared connections\n   in a `WeakSet\u003Cclient>` in `GraphQueries` (a reset connection yields a new\n   client object → re-prepared automatically). Measured **~17–18% faster** per\n   op. A pg-pool `connect`-event handler is the equivalent if you don't hold a\n   client wrapper:\n\n   ```ts\n   pool.on(\"connect\", (client) => {\n     client.query(\"LOAD 'age'\").catch(() => {});              \u002F\u002F tolerate preloaded\n     client.query(`SET search_path = ag_catalog, \"$user\", public`).catch(() => {});\n   });\n   ```\n\n3. **Multi-statement upserts.** Collapse existence-check + write into a single\n   `MERGE … ON CREATE SET … ON MATCH SET …` where it's race-safe, and batch\n   independent upserts. Fewer statements = fewer round trips.\n\n> **Ask of AGE:** the `cypher()` SRF wrapper carries per-call overhead; a way to\n> issue multiple graph mutations per round trip (or a lighter write path) would\n> materially help write-heavy workloads.\n\n## 4. AI \u002F embeddings — two paths\n\nHorizonDB offers **two** ways to generate embeddings in-database. Pick based on\nwhat your cluster allows and where the model lives.\n\n### Path A — `pg_durable` `df.http()` (external endpoint) ✅ verified working\n\n`pg_durable` exposes `df.http(url, method, body, headers jsonb, timeout_seconds)`\nfor durable HTTP calls from inside the database. This is the supported in-DB HTTP\nprimitive on HorizonDB — **`pgsql-http` (the `http` extension) is NOT available**;\nonly `azure_ai` and `pg_durable` ship.\n\n`incubator\u002Fhorizon-facts\u002Fsql\u002F006_embeddings_http.sql` + `src\u002Fhttp-embedding.ts`\nimplement this end-to-end (verified against the live cluster, embedding real\n1536-dim vectors). The hard-won mechanics:\n\n**1. `df.http()` is a durable FUTURE, not a synchronous call.** It returns a\nnode descriptor (`{\"node_type\":\"HTTP\",...}`), not the response. You run it via\n`df.start(fut, label, database)` → instance id, then poll\n`df.wait_for_completion(iid, timeout)` and read `df.result(iid)`:\n\n```sql\nv_iid := df.start(df.http(url,'POST',body,headers,30), 'hz-embed', NULL);\nCOMMIT;                                  -- ⚠️ see (2)\nPERFORM df.wait_for_completion(v_iid, 40);\nv_res := df.result(v_iid);               -- text JSON, see (3)\n```\n\n**2. Must COMMIT between start and wait → use a PROCEDURE, not a function.** The\n`pg_durable` worker runs the instance in its OWN connection and can't see the\ninstance row until the enqueuing transaction commits. So you cannot\n`df.start` + `df.wait_for_completion` inside one SQL function (functions can't\ncommit and would deadlock until timeout). Drive it from a **plpgsql PROCEDURE**\nthat `COMMIT`s after `df.start`. A `FOR row IN SELECT … LOOP … COMMIT … END LOOP`\nwith commits inside works on HorizonDB's PG17.\n\n**3. `df.result()` shape:** text JSON with keys\n`{ok, body, status, headers, duration_ms}`. `body` is the raw response string.\nFor an AOAI embeddings response:\n`(((df.result(iid)::jsonb->>'body')::jsonb->'data'->0->'embedding')::text)::vector`.\nCheck `(res::jsonb->>'ok')::boolean` first.\n\n**4. `df.http()` enforces an Azure egress ALLOW-LIST.** Only approved Azure\nservice domains are permitted. The Azure AI Foundry **unified** host\n`*.services.ai.azure.com` is **BLOCKED** — the instance fails with\n`\"... is not in the allowed endpoint list. Only requests to approved Azure\nservice domains are permitted.\"` The **classic Azure OpenAI host\n`*.openai.azure.com`** points at the same deployment and **IS allowed**.\n`setupHttpEmbedding` auto-rewrites the host (`toAllowlistedAzureHost`). The\n`cognitiveservices.azure.com` host also works. (The Node fallback uses Node\nfetch and works with either host.)\n\n**5. Grant HTTP usage:** `SELECT df.grant_usage(current_user, true, false);`\n(the `true` = include_http). Idempotent.\n\n**6. Recurring \u002F cron embedder via `df.loop` (sub-minute cadence).** pg_durable\nexposes futures combinators — `df.seq(a,b)` (THEN), `df.loop(body)`,\n`df.sleep(seconds)`, `df.sql(query)`, `df.race`, `df.if*`, plus `df.cancel`,\n`df.signal`, `df.wait_for_schedule(cron_expr)`. They serialize to a node tree\n(`{\"node_type\":\"LOOP\",\"left_node\":{...}}`) and you launch with `df.start`. For a\n**self-perpetuating recurring job** at a fixed interval, wrap a sleep+work\nsequence in a loop:\n\n```sql\n-- every N seconds, embed any changed facts (the loop is pure scheduling; the\n-- per-fact df.http embedding lives in the CALLed procedure → \"nested\" durability)\nSELECT df.start(\n  df.loop(df.seq(df.sleep(5::bigint), df.sql('CALL \"schema\".embed_new_facts_durable(128, NULL)'))),\n  'hz-embed-cron:schema', NULL);\n```\n\n- `df.wait_for_schedule` takes a real cron expression but only **minute**\n  granularity — for sub-minute ticks (e.g. every 5s) you MUST use `df.sleep`.\n- A loop calling a procedure that itself starts `df.http` instances works fine\n  (verified): the loop ticks, the proc runs nested durable HTTP per fact, the\n  pg_durable worker handles both. The loop instance stays `pending`\u002F`running`.\n- Track\u002Fstop by a **stable label** (e.g. `hz-embed-cron:\u003Cschema>`): look it up in\n  `df.instances` (PK column is `id`, plus `label`, `status`, `created_at`;\n  terminal statuses are `completed`\u002F`cancelled`\u002F`failed`, active are\n  `pending`\u002F`running`). Make `start` idempotent by reusing any non-terminal\n  instance with that label; `stop` = `df.cancel(id, reason)`.\n\n**7. Embedding is a PROVIDER-INTERNAL lifecycle, not a contract method.**\nPilotSwarm only knows the `EnhancedFactStore` interface; its sole embedding\nresponsibility is passing the endpoint config. *How\u002Fwhen* embeddings are produced\nis the provider's private business. The HorizonDB provider exposes only a\nlifecycle on `HorizonFactStore` (`src\u002Fhorizon-store.ts`):\n- `configureEmbedder(endpoint)` — write\u002Freplace the `embedding_config` row (with\n  the df.http allow-list host rewrite).\n- `startEmbedder({ intervalSeconds = 5, batch = 128 })` — launch the durable\n  df.loop cron; idempotent; returns `EmbedderStatus { running, instanceId?, status? }`.\n- `stopEmbedder()` — `df.cancel` the loop.\n- `embedderStatus()` — derived `{ running }` (no df leakage in the shape).\n\nCallers **never** trigger embedding or wait on a df instance — they write facts\nand observe the **outcome** (vector present \u002F semantic search returns the fact).\n\nThe two `@internal` methods `_embedPendingNode()` and `_embedNewFactsInDbOnce()`\nare **NOT production paths** — they are sanity checks for the df.http path:\n`_embedPendingNode` posts the *identical* request df.http builds (same headers\u002F\nbody, read from `embedding_config`) via Node fetch, so it validates the request\nshape against a Node-reachable stub; `_embedNewFactsInDbOnce` is a one-shot\nsynchronous trigger of the same procedure the cron CALLs. Both are exercised only\nby the **provider's own** integration tests (`test\u002Fintegration\u002Fhttp-embeddings.test.mjs`),\nwhich legitimately assert on df internals because they test the *mechanism*.\nPilotSwarm-level tests must stay outcome-only and never reference df.\n\nOther constraints:\n- Store the source-content hash alongside the vector so re-embeds only happen\n  when content changes (`last_embedded_hash IS DISTINCT FROM content_hash`).\n- `df.instances` (with your `label`) is the audit trail that a durable HTTP call\n  actually ran; it's global, not schema-scoped.\n- Inspect failures via `df.instance_nodes(iid, 1)` → the node `status`\u002F`result`.\n\n### Path B — `azure_ai` (Azure-managed inference)\n\n`azure_ai` is HorizonDB's native model-management\u002Finference extension. It wires\nembeddings\u002Fcompletions to Azure-managed model endpoints from inside the DB\n(no external HTTP plumbing). Cluster-side feature gating (`aiModelManagement`)\nmay need to be enabled before it works. Prefer this when you want managed,\nin-region inference and don't want to operate your own endpoint.\n\n### Path C — Node-side fallback (`embedPending()`)\n\nFor bootstrapping, clusters without a working in-DB HTTP path, or local tests,\nembed from the application: read pending facts, call the embeddings endpoint\nfrom Node, write `vector(dim)` back. Reference: `embedPending()` \u002F\n`http-embedding.ts` in horizon-facts. Still requires `vector` to be allow-listed\nso the `embedding vector(dim)` column and HNSW index exist.\n\n## 5. pgvector notes\n\n- `CREATE EXTENSION vector` after allow-listing; `vector` 0.8.0 supports `hnsw`\n  and `ivfflat` AMs out of the box.\n- HNSW index: `USING hnsw (embedding vector_cosine_ops)`.\n- **DiskANN is a SEPARATE extension (`pg_diskann`), not pgvector core.** On the\n  cluster it shows in `pg_available_extensions` (0.7.1). It is **NOT installed by\n  default** and must be allow-listed in `azure.extensions`. **IMPORTANT: unlike\n  Azure Flexible Server, HorizonDB does NOT require (and REJECTS) `pg_diskann` in\n  `shared_preload_libraries`** — the allowed preload set is fixed\n  (`age, auto_explain, azure_storage, pg_cron, pg_durable, pg_partman_bgw,\n  pg_prewarm, pg_stat_statements, pg_textsearch, pgaudit, wal2json`); adding\n  `pg_diskann` there fails the parameter group with `ParameterValueInvalid`. Put\n  `pg_diskann` in `azure.extensions` ONLY — it works without preload (verified\n  2026-06 on `waldemort-cms-2`: `CREATE EXTENSION pg_diskann` + `USING diskann\n  (embedding vector_cosine_ops)` both succeed). It shares the `vector_cosine_ops`\n  opclass and the `\u003C=>` operator with HNSW, so query code is identical.\n  horizon-facts selects the AM via `annIndex: \"diskann\"|\"hnsw\"|\"auto\"` (env\n  `HORIZON_ANN_INDEX`); `auto` (default) tries diskann and falls back to hnsw\n  when it isn't allow-listed (`ensureAnnIndex` in `migrations.ts`).\n- A jsonb array text `\"[...]\"` casts directly to `vector` — handy when parsing\n  an embeddings HTTP response: `(emb_json::text)::vector`.\n- Embedding dimension must match the endpoint's model exactly, or inserts fail.\n\n## 6. Networking \u002F firewall\n\n- HorizonDB firewall rules live under\n  `clusters\u002F{cluster}\u002Fpools\u002F{pool}\u002FfirewallRules`. With API\n  `2026-10-01-preview`, `GET clusters\u002F{cluster}\u002Fpools` lists the pools (the\n  default one is `DefaultPool`) and the firewall rule collection can be listed.\n  Add one rule per client IPv4; never open a broad range.\n- Connections still require the TLS handling from §1 once the firewall is open.\n\n## 7. Working checklist for a fresh cluster\n\n1. Add a firewall rule for your IP on the pool (§6).\n2. Connect with `?sslmode=require&uselibpqcompat=true`; confirm `select version()`.\n3. Create a settings group with `azure.extensions` and\n   `shared_preload_libraries` for the extensions you need, attach it to the\n   pool, and wait until the pool GET shows it as `InSync` (§2).\n4. `CREATE EXTENSION` for `vector`, `age`, `pg_durable`, `pg_textsearch` as needed.\n5. For AGE: tolerant `LOAD 'age'`, set `search_path`, distinct graph vs schema\n   names, avoid `any(... WHERE ...)`.\n6. For embeddings: choose `df.http()` (external endpoint reachable from cluster),\n   `azure_ai` (managed), or Node-side `embedPending()`; run generation as a\n   `pg_durable` activity; hash-guard re-embeds.\n\n## See also\n\n- `incubator\u002Fhorizon-facts\u002FREADME.md` — capability overview + design rules\n- `incubator\u002Fhorizon-facts\u002FCRAWLER-SPEC.md` — embedding pipeline + AGE graph contract\n- `incubator\u002Fhorizon-facts\u002Ftest\u002Fintegration\u002F` — live HorizonDB tests for all of the above\n- repo memory `horizondb-incubator-2026-06-02.md` — the original bring-up notes\n",{"name":5,"description":7},"main","a11767899d01721b3086859bdcb13d53810464cd",".github\u002Fskills\u002Fhorizondb-idiosyncrasies",10,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-15 00:36:04",{"source":9,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add microsoft\u002FPilotSwarm --skill horizondb-idiosyncrasies",{"tool":73,"command":74},"bunx","bunx skills add microsoft\u002FPilotSwarm --skill horizondb-idiosyncrasies",{"tool":76,"command":77},"pnpm","pnpm dlx skills add microsoft\u002FPilotSwarm --skill horizondb-idiosyncrasies","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fhorizondb-idiosyncrasies\u002FSKILL.md",true,[],[82,90,97,104,111,118],{"skillNo":83,"name":84,"nameZh":17,"description":85,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":89},"01M760N7TCZBTY635MYZQ8YAB0","workflow-testing","Load before you test a Workflow with mocked effects — the test, test_respond and test_advance operations, fixtures, interception ids, valid answers, the virtual clock, test evidence and what a test run does not prove.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002Fpackages\u002Fsdk\u002Fplugins\u002Fworkflow\u002Ftest-mode-skills\u002Fworkflow-testing\u002FSKILL.md",[],[],"2026-11-12 13:55:43",{"skillNo":91,"name":92,"nameZh":17,"description":93,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":89},"01M760N4RKD6BMYPGHD490SNN2","workflow-tools","Every argument of the Workflow tools, testing a revision, package definitions and the refusals you can fix. Load when a Workflow tool's short description is not enough.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002Fpackages\u002Fsdk\u002Fplugins\u002Fworkflow\u002Fskills\u002Fworkflow-tools\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":17,"description":100,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":89},"01M760N1P2VTGVE6C4N5WF3FVR","workflow-reference","Field reference for Workflow YAML (root keys, every state type, bindings, outputs, runtime error codes), what the engine guarantees, and a review fan-out example. For design, call load_skill with name workflow-authoring.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002Fpackages\u002Fsdk\u002Fplugins\u002Fworkflow\u002Fskills\u002Fworkflow-reference\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":17,"description":107,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":89},"01M760MZ5CFSAX4FYMEXZJBGM2","workflow-patterns","Load when one Workflow must run different nodes in its branches at the same time (a different prompt or model for each branch), or loops back to a state (a polling loop). Named branches, the router pattern, examples that compile.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002Fpackages\u002Fsdk\u002Fplugins\u002Fworkflow\u002Fskills\u002Fworkflow-patterns\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":17,"description":114,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":89},"01M760MWKBDJFEECRFAF3BAVQ2","workflow-authoring","Load before you create, edit, publish or run a Workflow (pilotswarm.dev\u002Fv1) — choosing states, bounded graphs, bindings, typed contracts, agent and parallel states, the lifecycle and failure diagnosis.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002Fpackages\u002Fsdk\u002Fplugins\u002Fworkflow\u002Fskills\u002Fworkflow-authoring\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":17,"description":121,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":89},"01M760MN4Y9199ARAY85DWD08X","tla-formal-validation","Required for any change to the core orchestrations (the durable session orchestration, session hydration and dehydration, and the Workflow controller and store). Teaches how to model the change in TLA+, update the existing models, run TLC with the repo runner, read the results, turn a counterexample into a fix and a regression test, and record the binding to the code.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FPilotSwarm\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftla-formal-validation\u002FSKILL.md",[],[]]