Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

acdat

Compile hundreds to hundreds of thousands of literal patterns into a compact Aho–Corasick automaton and scan PostgreSQL text or bytea values in a single linear pass. Ideal for content moderation, log IOC tagging, entity extraction, and bulk redaction.

Checking a text column against thousands of keywords with LIKE ANY, ~ regex alternation, or repeated replace() calls slows down linearly as your rule list grows. acdat compiles an entire dictionary once into an Aho–Corasick automaton stored on a double-array trie (acdat.machine), then evaluates every rule simultaneously in one pass over each input value.

Why use acdat

  • Constant-cost rule scaling: Scan time scales with the length of the input string, not the number of keywords—whether your dictionary holds 20 rules or 100,000 rules.
  • Exact text and binary matching: Supports both text (reporting 1-based byte and Unicode character offsets) and bytea (arbitrary binary payloads including \x00).
  • One-pass deterministic rewriting: acdat.replace() rewrites overlapping spans according to an explicit policy (leftmost_longest or leftmost_priority) and never rescans already-replaced output.
  • Managed dictionary lifecycle: Publish immutable dictionary versions, switch active builds atomically via MVCC, or roll back instantly without taking queries offline.

When to use acdat (and when not to)

NeedBest toolWhy
Check, tag, or redact many exact literal phrases or binary signatures inside PostgreSQLacdatSingle-pass scan with stable rule IDs, priorities, and deterministic replacement
Search by stemmed natural-language words or relevance rankingPostgreSQL full-text search / vchord_bm25acdat matches exact literal bytes, not linguistic tokens or stem variants
Match variable patterns (\d{4}-\d{2}, lookaheads, wildcards)Regular expressions (~ / regexp_replace)acdat handles literal strings only
Filter a tiny fraction of rows out of a huge table by a few substringspg_trgm GIN/GiST index (or combine with acdat)Narrow candidate rows with an index first, then run acdat on the survivors

How acdat works

flowchart LR
    R["Application Rule Table (pattern, id, replacement, priority)"] -->|acdat.compile| M["acdat.machine (Double-Array Trie)"]
    M -->|acdat.publish + activate| CAT["acdat.active_machine (MVCC Pointer)"]
    CAT -->|acdat.contains| B["boolean (fast filter)"]
    CAT -->|acdat.matches| H["SETOF acdat.hit (id & offsets)"]
    CAT -->|acdat.replace| T["text / bytea (single-pass rewrite)"]
  1. Keep rules in your own table: Your application table owns the pattern text, business pattern_id, optional replacement text, priority, and metadata (such as risk level or category).
  2. Compile once: acdat.compile() turns arrays or table rows into an immutable acdat.machine value. A 1,114-rule real-world dictionary compiles in ~1.2 ms and caches in ~227 KiB per backend.
  3. Publish or pass directly: Store the compiled machine in your own table or publish it to acdat’s built-in catalog (acdat.publish + acdat.activate) for atomic rollouts and rollbacks.
  4. Scan in one pass: Pass the machine to acdat.contains() to filter rows, acdat.matches() to extract rule IDs and offsets, or acdat.replace() to redact or rewrite values.

1 - Getting started with acdat

Install acdat and build a complete comment moderation and redaction pipeline in PostgreSQL in three minutes.

1. Install acdat

Install from Pigsty packages

CI covers PostgreSQL 14–18, and Pigsty ships packages for PostgreSQL 15–19 across Linux distributions. Check Downloads for OS and architecture availability.

pig repo add pgsql -u
pig ext add acdat

Or build from the release tag

Point PG_CONFIG to your target PostgreSQL installation:

git clone --branch v0.1.1 --depth 1 https://github.com/pgsty/acdat.git
cd acdat
make PG_CONFIG=pg_config
sudo make install PG_CONFIG=pg_config

2. Enable the extension

Connect to a UTF8 database as a superuser and create the extension. All functions and types live in the fixed acdat schema:

CREATE EXTENSION IF NOT EXISTS acdat;

3. Build and run a moderation pipeline

Instead of scanning rows one keyword at a time, keep rules in a table, compile them into one acdat.machine, and run filtering, annotation, and redaction in a single pass.

  1. Create a rule table and sample comments:

    CREATE TEMP TABLE moderation_rules (
        pattern_id  bigint PRIMARY KEY,
        pattern     text NOT NULL,
        replacement text NOT NULL,
        priority    integer NOT NULL DEFAULT 0,
        category    text NOT NULL
    );
    
    INSERT INTO moderation_rules (pattern_id, pattern, replacement, priority, category) VALUES
        (101, 'insider tip',       '[BLOCKED]', 10, 'compliance'),
        (102, 'guaranteed return', '[BLOCKED]', 10, 'compliance'),
        (103, 'DM on Telegram',    '[CONTACT]',  5, 'spam');
    
    CREATE TEMP TABLE comments (
        comment_id bigint PRIMARY KEY,
        body       text NOT NULL
    );
    
    INSERT INTO comments VALUES
        (1, 'DM on Telegram for a guaranteed return today'),
        (2, 'PostgreSQL 18 release notes'),
        (3, 'Never act on an insider tip');
  2. Compile the rule table into a single acdat.machine:

    CREATE TEMP TABLE compiled_dict AS
    SELECT acdat.compile(pattern, pattern_id, replacement, priority) AS machine
    FROM moderation_rules;
  3. Filter only the comments that match at least one rule (acdat.contains stops on the first hit):

    SELECT comment_id, body
    FROM comments
    WHERE acdat.contains(body, (SELECT machine FROM compiled_dict))
    ORDER BY comment_id;
     comment_id |                     body
    ------------+----------------------------------------------
              1 | DM on Telegram for a guaranteed return today
              3 | Never act on an insider tip
  4. Extract every match with its position and join back to your rule table for business labels:

    SELECT c.comment_id,
           h.pattern_id,
           r.category,
           h.start_char,
           h.char_length,
           substring(c.body FROM h.start_char FOR h.char_length) AS matched_text
    FROM comments AS c
    CROSS JOIN LATERAL acdat.matches(c.body, (SELECT machine FROM compiled_dict)) AS h
    JOIN moderation_rules AS r USING (pattern_id)
    ORDER BY c.comment_id, h.start_byte, h.pattern_id;
     comment_id | pattern_id |  category  | start_char | char_length |   matched_text
    ------------+------------+------------+------------+-------------+-------------------
              1 |        103 | spam       |          1 |          14 | DM on Telegram
              1 |        102 | compliance |         22 |          17 | guaranteed return
              3 |        101 | compliance |         17 |          11 | insider tip
  5. Redact all matched spans in one non-recursive pass:

    SELECT comment_id,
           acdat.replace(body, (SELECT machine FROM compiled_dict)) AS sanitized
    FROM comments
    ORDER BY comment_id;
     comment_id |            sanitized
    ------------+----------------------------------
              1 | [CONTACT] for a [BLOCKED] today
              2 | PostgreSQL 18 release notes
              3 | Never act on an [BLOCKED]
Tip

Notice the scalar subquery (SELECT machine FROM compiled_dict) above. Writing the machine lookup as an uncorrelated subquery lets PostgreSQL load the automaton once in an InitPlan rather than re-reading it per row during parallel scans.

For one-off ad-hoc checks without a rule table, you can also compile an inline array directly:

SELECT acdat.contains('PostgreSQL timeout error', acdat.compile(ARRAY['timeout', 'deadlock'])) AS matched;
-- t

Next steps

  • Examples and workflows — Explore overlap policies, log IOC extraction, managed dictionary publishing & rollback, binary matching, and cross-database export/import.
  • Performance and tuning — Benchmark charts, avoiding the 22x parallel-plan trap, and per-worker memory budgets.
  • Operations — Separate dictionary admin privileges, backups, and error troubleshooting.
  • Run the tagged end-to-end SQL script examples/demo.sql inside a single rolled-back psql transaction.

2 - Examples and workflows

Five practical acdat recipes: resolving overlapping phrases, extracting log IOCs with a reverse-lookup index, rolling out versioned dictionaries atomically, scanning binary payloads, and shipping compiled artifacts across databases.

Every example below is self-contained and runs inside PostgreSQL using acdat v0.1.1.

1. Overlapping rules and redaction policies

Real dictionaries almost always contain overlapping phrases—for instance, "credit card", "credit card fraud", and "fraud". acdat resolves overlaps deterministically using three policies:

  • all_overlapping (default for matches): reports every candidate hit, including prefixes, suffixes, and duplicate text with distinct IDs.
  • leftmost_longest (default for replace): consumes the leftmost match; at the same start offset, prefers the longer pattern, then lower priority number, then lower ID.
  • leftmost_priority: consumes the leftmost match; at the same start offset, prefers the lower priority number first (e.g., priority 10 beats priority 20), then longer pattern, then lower ID.
WITH dict AS (
    SELECT acdat.compile(
        ARRAY['credit card', 'credit card fraud', 'fraud'],
        ARRAY[1, 2, 3]::bigint[],
        ARRAY['[PAYMENT]', '[HIGH-RISK]', '[RISK]'],
        ARRAY[10, 20, 5]::integer[]
    ) AS m
)
SELECT
    acdat.replace('report credit card fraud now', m, 'leftmost_longest')  AS longest,
    acdat.replace('report credit card fraud now', m, 'leftmost_priority') AS by_priority,
    (SELECT count(*) FROM acdat.matches('report credit card fraud now', m, 'all_overlapping')) AS total_hits
FROM dict;
         longest         |         by_priority         | total_hits
-------------------------+-----------------------------+------------
 report [HIGH-RISK] now  | report [PAYMENT] [RISK] now |          3

Why the two results differ:

  • Under leftmost_longest, "credit card fraud" (17 bytes) beats "credit card" (11 bytes) at byte 8 and consumes the entire span.
  • Under leftmost_priority, "credit card" (priority 10) beats "credit card fraud" (priority 20) at byte 8; scanning then resumes after byte 18 and also matches "fraud".

Practical rules for acdat.replace():

  • Delete spans with '': An empty replacement string deletes the matched span; selecting a rule whose replacement is NULL raises an error (acdat pattern ID <n> has no replacement).
  • Single non-recursive pass: Replacement output is never rescanned, so replacing "foo" with "foobar" cannot loop.
  • Guard against expansion: Pass explicit max_replacements (default 10000) and max_output_bytes (default 256 MiB) when short inputs could expand into large outputs. The candidate limit counts raw overlaps before policy resolution, and an outer SQL LIMIT does not cap it.

2. Extract log IOCs and build a reverse-lookup table

When auditing security logs or tagging documents against a large IOC (Indicator of Compromise) list, you often need two answers: “which indicators hit this log?” and later “which logs matched indicator #402?”

CREATE TEMP TABLE ioc_rules (
    pattern_id bigint PRIMARY KEY,
    pattern    text NOT NULL,
    severity   text NOT NULL
);

INSERT INTO ioc_rules VALUES
    (401, 'malicious.example', 'critical'),
    (402, '198.51.100.77',     'high'),
    (403, 'powershell -enc',   'critical');

CREATE TEMP TABLE ioc_machine AS
SELECT acdat.compile(pattern, pattern_id) AS machine
FROM ioc_rules;

CREATE TEMP TABLE access_logs (
    log_id bigint PRIMARY KEY,
    line   text NOT NULL
);

INSERT INTO access_logs VALUES
    (1, 'GET https://malicious.example/payload from 198.51.100.77'),
    (2, 'GET https://docs.example.org/index.html from 203.0.113.5'),
    (3, 'exec: PowerShell -Enc SQBFAFgA');

Notice log #3 has mixed casing (PowerShell -Enc). Because acdat compares exact UTF-8 bytes without case folding or Unicode normalization, normalize both rules and input identically (for example with lower()) when case-insensitive matching is required:

-- Materialize every hit along with position offsets for auditing and reverse lookup
CREATE TEMP TABLE log_ioc_hits AS
SELECT l.log_id,
       h.pattern_id,
       r.severity,
       h.start_byte,
       h.byte_length,
       h.start_char,
       h.char_length,
       substring(lower(l.line) FROM h.start_char FOR h.char_length) AS matched_token
FROM access_logs AS l
CROSS JOIN LATERAL acdat.matches(
    lower(l.line),
    (SELECT machine FROM ioc_machine),
    'all_overlapping',
    1000
) AS h
JOIN ioc_rules AS r USING (pattern_id);

CREATE INDEX ON log_ioc_hits (pattern_id, log_id);

SELECT log_id, pattern_id, severity, start_char, char_length, matched_token
FROM log_ioc_hits
ORDER BY log_id, start_byte;
 log_id | pattern_id | severity | start_char | char_length |   matched_token
--------+------------+----------+------------+-------------+-------------------
      1 |        401 | critical |         13 |          17 | malicious.example
      1 |        402 | high     |         44 |          13 | 198.51.100.77
      3 |        403 | critical |          7 |          15 | powershell -enc

With the index on (pattern_id, log_id), reverse lookups (WHERE pattern_id = 402) are instant. In production, store dictionary_version and build_id alongside each materialized hit so you know which rule build produced it and can rebuild cleanly when rules change.

Note

Offsets are 1-based. For UTF-8 text, start_byte/byte_length measure UTF-8 bytes while start_char/char_length measure Unicode code points (which plug directly into PostgreSQL substring(... FROM start_char FOR char_length)). Always add ORDER BY if you need stable output order.

3. Publish, atomically switch, and roll back dictionaries

For production dictionaries that change over time, use acdat’s built-in catalog instead of overwriting a single row. Publishing stores an immutable semantic version and returns a 32-byte build_id; activating flips a pointer in acdat.active_dictionary atomically under MVCC so concurrent readers switch cleanly without locks.

-- 1. Compile and publish version 1 from your rule table
CREATE TEMP TABLE dict_releases (version bigint PRIMARY KEY, build_id bytea NOT NULL);

INSERT INTO dict_releases (version, build_id)
SELECT 1,
       acdat.publish(
           'security_ioc',
           1,
           acdat.compile(pattern, pattern_id),
           '{"ticket":"SEC-101"}'::jsonb
       )
FROM ioc_rules;

-- 2. Activate version 1
SELECT acdat.activate('security_ioc', build_id)
FROM dict_releases WHERE version = 1;

-- 3. Add a new rule, publish version 2, and switch traffic atomically
INSERT INTO ioc_rules VALUES (404, 'credential-dump', 'critical');

INSERT INTO dict_releases (version, build_id)
SELECT 2,
       acdat.publish(
           'security_ioc',
           2,
           acdat.compile(pattern, pattern_id),
           '{"ticket":"SEC-102"}'::jsonb
       )
FROM ioc_rules;

SELECT acdat.activate('security_ioc', build_id)
FROM dict_releases WHERE version = 2;

-- Readers always query acdat.active_machine
SELECT name, version, acdat.contains('detected credential-dump', machine) AS hit
FROM acdat.active_machine
WHERE name = 'security_ioc';
     name     | version | hit
--------------+---------+-----
 security_ioc |       2 | t

If version 2 triggers false positives, roll back immediately by reactivating version 1, then retire version 2:

SELECT acdat.activate('security_ioc', build_id)     FROM dict_releases WHERE version = 1;
SELECT acdat.retire_build('security_ioc', build_id) FROM dict_releases WHERE version = 2;

Keep these compilation rules in mind:

  • Parallel arrays passed to acdat.compile() must be 1D and equal in length; patterns must be non-empty; explicit IDs must be non-NULL and unique (duplicate literal strings with distinct IDs are allowed); NULL priorities default to 0.
  • An aggregate over zero rows returns NULL; an explicitly typed empty array (ARRAY[]::text[]) builds an empty machine.
  • Canonical sorting makes source_fingerprint() independent of input row order when rule IDs are stable.

4. Scan and patch binary payloads (bytea)

Use the bytea overloads to match protocol headers, file magic bytes, or raw signatures containing \x00 or non-UTF-8 octets. Binary hits always return NULL for start_char and char_length.

WITH sigs AS (
    SELECT acdat.compile(
        ARRAY[decode('00ff', 'hex'), decode('beef', 'hex')],
        ARRAY[20, 21]::bigint[],
        ARRAY[decode('1122', 'hex'), decode('dead', 'hex')]
    ) AS m
)
SELECT
    (SELECT array_agg(pattern_id ORDER BY start_byte)
     FROM acdat.matches(decode('aa00ffbeef', 'hex'), m)) AS hit_ids,
    encode(acdat.replace(decode('aa00ffbeef', 'hex'), m), 'hex') AS patched
FROM sigs;
 hit_ids |  patched
---------+------------
 {20,21} | aa1122dead

Text machines reject bytea inputs and vice versa (acdat machine input kind does not match function input). On databases using encodings other than UTF8 or single-byte encodings, use bytea.

5. Inspect and ship compiled machines across databases

If you compile a 100,000-pattern dictionary in CI or on a build server, you can inspect its metadata and ship the compiled bytea artifact to production databases without recompiling there.

WITH d AS (
    SELECT acdat.compile(ARRAY['virus', 'signature'], ARRAY[1, 2]::bigint[]) AS m
)
SELECT acdat.info(m)->>'engine'                         AS engine,
       acdat.info(m)->>'pattern_count'                  AS patterns,
       encode(acdat.source_fingerprint(m), 'hex')       AS source_sha256,
       encode(acdat.artifact_checksum(m),  'hex')       AS artifact_sha256
FROM d;

Export on the build database, validate and import on the target database:

WITH exported AS (
    SELECT acdat.export(acdat.compile(ARRAY['virus', 'signature'])) AS blob
)
SELECT acdat.validate(blob) AS valid,
       acdat.contains('virus detected', acdat.import(blob)) AS works
FROM exported;
 valid | works
-------+-------
 t     | t
  • source_fingerprint() hashes the canonical rule set; build_fingerprint() also includes engine, compiler, and format version; artifact_checksum() hashes the serialized payload.
  • validate() returns false on corrupted bytes while import() raises an error.
  • Transfer text machines only between databases with compatible server encodings; bytea machines are encoding-independent.

3 - Performance and tuning

Reference throughput and memory measurements for acdat v0.1.1, how to avoid the 22x parallel-scan planning trap, and sizing rules for production rule sets.

acdat compiles fast and scans near memory bandwidth. In production, query latency is usually governed by PostgreSQL’s execution plan, row width, and parallel worker count rather than the automaton itself.

All benchmark figures below were measured on acdat v0.1.1 (Apple M5 Max, PostgreSQL 18.6, hot buffers, in-database aggregation without client transfer). Full methodology and raw logs: PERFORMANCE.md · BENCHMARK.md.

1. Real corpus throughput (10.3M rows, 1,114 rules)

Dataset: 10,318,163 short video titles (306.9 MiB total, ~31 bytes/row) scanned against a 1,114-rule real dictionary (compiled in 1.16 ms, 227 KiB runtime cache per process).

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["contains", "replace", "matches"]
yAxis:
  type: value
  name: "MiB/s"
series:
  - name: "1 backend"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [202, 153, 83]
  - name: "4 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#3b82f6"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [772, 602, 376]
  - name: "8 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#10b981"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [1346, 1055, 645]
Operation1 backend4 workers8 workers8-worker speedup
contains1.522 s0.398 s0.228 s6.67x
replace (leftmost_longest)2.007 s0.510 s0.291 s6.89x
matches (all_overlapping)3.678 s0.816 s0.476 s7.73x

contains stops on the first match and allocates no output text or hit tuples, making it ~2.4x faster than matches on short rows.

2. Scaling to 100,000 rules across row widths

Dataset: 100,000 shared-prefix patterns (compiled in 36.9 ms, 5.51 MiB runtime cache) scanning 256–314 MiB of root-miss text across three row sizes.

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["33 B / row (10M rows)", "1 KiB / row (262k rows)", "64 KiB / row (4k rows)"]
yAxis:
  type: value
  name: "GiB/s"
series:
  - name: "1 backend"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [0.51, 0.89, 0.89]
  - name: "4 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#3b82f6"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [2.19, 3.41, 3.55]
  - name: "8 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#10b981"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [2.94, 5.01, 5.13]
Row widthRows1 backend4 workers8 workers
33 B10,000,000600.6 ms140.1 ms104.0 ms
1 KiB262,144281.6 ms73.3 ms49.9 ms
64 KiB4,096280.4 ms70.5 ms48.8 ms

At 1 KiB and 64 KiB per row, a single PostgreSQL backend reaches ~94% of the standalone C core’s throughput (965 MiB/s). On 33-byte rows, executor per-row call overhead accounts for roughly half of runtime.

3. Avoid the 22x parallel matches trap

Joining a single-row machine table directly with CROSS JOIN can cause the parallel planner to place the machine scan inside the document loop—re-reading the machine row once per document:

-- SLOW: parallel Gather can rescan active_dict once per document row (10.43 s on 8 workers)
SELECT count(*)
FROM documents AS d
CROSS JOIN active_dict AS m
CROSS JOIN LATERAL acdat.matches(d.body, m.machine, 'all_overlapping') AS h;

Wrapping the lookup in an uncorrelated scalar subquery turns it into a once-per-query InitPlan. On the 10.3M-row corpus with 8 workers, runtime dropped from 10.43 s to 0.476 s (22x faster):

-- FAST: uncorrelated scalar subquery loads the machine once via InitPlan (0.476 s)
SELECT count(*)
FROM documents AS d
CROSS JOIN LATERAL acdat.matches(
    d.body,
    (SELECT machine FROM acdat.active_machine WHERE name = 'security_ioc'),
    'all_overlapping'
) AS h;

Always check EXPLAIN (ANALYZE, BUFFERS) before rolling out a large scan and verify that the machine scan runs with loops=1.

4. Memory budget and tuning rules

Each backend and parallel worker keeps its own materialized runtime cache. Budget (1 + max_parallel_workers_per_gather) copies for large dictionaries:

Dictionary profileStored artifactCache / process9 processes (leader + 8 workers)
Real corpus (1,114 rules)269 KiB227 KiB~2.0 MiB
100k shared-prefix rules5.94 MiB5.51 MiB~49.6 MiB
100k random ASCII rules28.96 MiB23.93 MiB~215.4 MiB

Four practical rules for fast scans:

  • Compile once outside the row loop: Never put acdat.compile() inside a per-row WHERE or SELECT expression.
  • Filter before scanning: Narrow candidate rows with B-tree, GIN, or time-range indexes first, and choose acdat.contains() over acdat.matches() when you only need a boolean match.
  • Benchmark your own dictionary: Root-miss workloads run much faster than dense-fallback ASCII workloads; rule count alone does not predict throughput.
  • Stream large exports: Use COPY or a server-side cursor when exporting millions of matches or rewritten rows instead of buffering a giant SELECT in client memory.

4 - Operations

Configure least-privilege roles for scanning vs. publishing dictionaries, plan logical and physical backups, diagnose common errors, and uninstall safely.

For throughput measurements, parallel execution plans, and per-worker cache sizing, see Performance and tuning.

1. Least-privilege permissions

A superuser installs acdat. By default, PUBLIC receives USAGE on the acdat schema and EXECUTE on scanning/compilation functions, while managed catalog tables and publish / activate / retire_build are revoked from PUBLIC.

Separate read-only scanning roles from dictionary administrators:

-- Scan-only role: reads currently active published machines
CREATE ROLE app_scanner;
GRANT SELECT ON acdat.active_machine TO app_scanner;

-- Dictionary admin role: publishes, activates, and retires managed builds
-- (management functions run SECURITY INVOKER, so both table and function grants are required)
CREATE ROLE dict_admin;
GRANT SELECT, INSERT, UPDATE, DELETE ON
    acdat.dictionary,
    acdat.dictionary_version,
    acdat.dictionary_build,
    acdat.dictionary_build_data,
    acdat.active_dictionary
TO dict_admin;

GRANT EXECUTE ON FUNCTION
    acdat.publish(text, bigint, acdat.machine, jsonb),
    acdat.activate(text, bytea),
    acdat.retire_build(text, bytea)
TO dict_admin;

2. Backup, restore, and replication

  • Logical dumps (pg_dump): acdat registers its catalog tables via pg_extension_config_dump(), dumping all dictionary, version, and build metadata, active pointers, and active machine payloads. Inactive historical payloads are excluded to keep dumps compact—back up your application rule tables so inactive versions can be recompiled on demand.
  • Physical backups and PITR: Include all logged active and inactive payloads automatically. Install a compatible acdat shared library on the recovery host before starting PostgreSQL.
  • Logical replication: Install acdat on subscribers beforehand, then either replicate metadata, payload, and activation atomically in one transaction or recompile dictionaries independently on subscribers from replicated source rules.

3. Common errors

Error messageCause and fix
acdat compile failed: pattern ID 1 is duplicatedEvery rule in one dictionary must have a unique pattern_id. Deduplicate or assign distinct IDs.
acdat scan failed: match count exceeds limit 2Raw overlapping hits exceeded max_matches (or max_replacements) before overlap resolution. Prune overlapping rules or raise the measured cap.
acdat pattern ID 1 has no replacementacdat.replace() selected a rule whose replacement was NULL. Supply a literal replacement (or '' to delete).
cannot retire the active acdat buildActivate another ready build first, then retire the previous build.
acdat machine input kind does not match function inputA text machine was passed to a bytea function (or vice versa). Keep machine and input types paired.
acdat build is absent, retired, or has no artifact payloadPublish or recompile the target build before calling acdat.activate().

Other quick checks: cast empty arrays explicitly (ARRAY[]::text[]), note that an aggregate over zero rows returns NULL, and on permission errors verify both table and function grants for SECURITY INVOKER management functions.

4. Uninstall

Warning

DROP EXTENSION acdat removes all managed catalog tables and compiled machines. Adding CASCADE also drops dependent application tables, views, or functions. Back up your source rules and inspect dependencies before removing the extension.

5 - acdat SQL reference

Complete SQL API lookup for acdat v0.1.1. All types, functions, and catalog tables live in the fixed acdat schema; always pair text or bytea inputs with a matching machine.

Compile a dictionary

acdat.compile(patterns text[], pattern_ids bigint[], replacements text[], priorities integer[], options jsonb) , acdat.machine , defaultNULL, NULL, NULL, '{}'¹
Compile parallel 1D text arrays into a machine. Omitted IDs default to 1..N; NULL priorities default to 0.
acdat.compile(patterns bytea[], pattern_ids bigint[], replacements bytea[], priorities integer[], options jsonb) , acdat.machine , defaultNULL, NULL, NULL, '{}'¹
Binary array overload preserving arbitrary bytes (including \x00).
acdat.compile(text, bigint) , aggregate → acdat.machine , default—
Compile rows of (pattern, pattern_id). Returns NULL for zero rows.
acdat.compile(text, bigint, text, integer) , aggregate → acdat.machine , default—
Compile rows of (pattern, pattern_id, replacement, priority). Returns NULL for zero rows.
acdat.compile(bytea, bigint) , aggregate → acdat.machine , default—
Binary aggregate over (pattern, pattern_id). Returns NULL for zero rows.
acdat.compile(bytea, bigint, bytea, integer) , aggregate → acdat.machine , default—
Binary aggregate over (pattern, pattern_id, replacement, priority). Returns NULL for zero rows.

¹ Defaults apply starting at pattern_ids; patterns is required. options accepts NULL or {}.

Scan and replace

acdat.contains(text, acdat.machine) , boolean , default—
Return true on the first literal match and stop scanning immediately.
acdat.contains(bytea, acdat.machine) , boolean , default—
Binary overload of contains.
acdat.matches(input text, machine acdat.machine, policy text, max_matches integer) , setof acdat.hit , default'all_overlapping', 10000
Return 1-based byte and character offsets for each hit. Candidate limit is checked before overlap resolution.
acdat.matches(input bytea, machine acdat.machine, policy text, max_matches integer) , setof acdat.hit , default'all_overlapping', 10000
Binary overload; start_char and char_length are always NULL.
acdat.replace(input text, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint) , text , default'leftmost_longest', 10000, 268435456
Single non-recursive pass rewrite. Errors if a selected match has a NULL replacement or exceeds a limit.
acdat.replace(input bytea, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint) , bytea , default'leftmost_longest', 10000, 268435456
Binary overload of replace.

Overlap policies

all_overlapping , matches , defaultdefault for matches
Emit every candidate hit, including prefixes, suffixes, and duplicate literals with distinct IDs.
leftmost_longest , matches / replace , defaultdefault for replace
Leftmost start offset → longer pattern → lower priority integer → lower pattern_id → lower canonical ordinal.
leftmost_priority , matches / replace , default—
Leftmost start offset → lower priority integer → longer pattern → lower pattern_id → lower canonical ordinal.

Inspect and transport

acdat.info(acdat.machine) , jsonb , default—
Metadata JSON: engine, compiler/format versions, input kind, encoding, pattern/state/slot counts, and sizes.
acdat.export(acdat.machine) , bytea , default—
Serialize a compiled machine into a portable binary image.
acdat.validate(bytea) , boolean , default—
Verify a serialized image without raising an error on corruption.
acdat.import(bytea) , acdat.machine , default—
Validate and decode a serialized image; raises an error if malformed.
acdat.source_fingerprint(acdat.machine) , bytea , default—
32-byte SHA-256 digest of the canonical rule set and input kind.
acdat.build_fingerprint(acdat.machine) , bytea , default—
32-byte digest identifying rules plus compiler, engine, and format version.
acdat.artifact_checksum(acdat.machine) , bytea , default—
32-byte checksum of the serialized artifact payload.

Managed dictionary catalog

acdat.publish(p_dictionary_name text, p_semantic_version bigint, p_compiled_machine acdat.machine, p_source_reference jsonb) , bytea , defaultp_source_reference = NULL
Store an immutable ready build and return its 32-byte dictionary-scoped build_id.
acdat.activate(p_dictionary_name text, p_build_id bytea) , void , default—
Atomically point acdat.active_dictionary to a ready build.
acdat.retire_build(p_dictionary_name text, p_build_id bytea) , void , default—
Mark an inactive build as retired.
acdat.active_machine , view , default—
Active ready machines: name, input_kind, version, build_id, machine, info.
acdat.dictionary , table , default—
Dictionary name and fixed input_kind (text or bytea).
acdat.dictionary_version , table , default—
Semantic version, source_fingerprint, and optional source_ref JSON.
acdat.dictionary_build , table , default—
Build metadata, compiler/format/engine info, status (ready / retired), and checksum.
acdat.dictionary_build_data , table , default—
Compiled acdat.machine payload (STORAGE EXTERNAL) keyed by build_id.
acdat.active_dictionary , table , default—
Current active build_id pointer per dictionary.

Types and internal functions

acdat.machine , base type , default—
Variable-length compiled automaton (STORAGE = external).
acdat.hit , composite type , default—
(pattern_id bigint, start_byte integer, byte_length integer, start_char integer, char_length integer, priority integer).
machine_in / machine_out / machine_recv / machine_send , internal I/O , default—
Type I/O functions revoked from PUBLIC; invoked by PostgreSQL.
_compile_*_trans / _compile_final / _catalog_build_id , internal helpers , default—
Aggregate state transition/final and catalog digest helpers revoked from PUBLIC.