This is the multi-page printable view of this section.
acdat
- 1: Getting started with acdat
- 2: Examples and workflows
- 3: Performance and tuning
- 4: Operations
- 5: acdat SQL reference
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) andbytea(arbitrary binary payloads including\x00). - One-pass deterministic rewriting:
acdat.replace()rewrites overlapping spans according to an explicit policy (leftmost_longestorleftmost_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)
| Need | Best tool | Why |
|---|---|---|
| Check, tag, or redact many exact literal phrases or binary signatures inside PostgreSQL | acdat | Single-pass scan with stable rule IDs, priorities, and deterministic replacement |
| Search by stemmed natural-language words or relevance ranking | PostgreSQL full-text search / vchord_bm25 | acdat 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 substrings | pg_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)"]- 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). - Compile once:
acdat.compile()turns arrays or table rows into an immutableacdat.machinevalue. A 1,114-rule real-world dictionary compiles in ~1.2 ms and caches in ~227 KiB per backend. - 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. - Scan in one pass: Pass the machine to
acdat.contains()to filter rows,acdat.matches()to extract rule IDs and offsets, oracdat.replace()to redact or rewrite values.
1 - Getting started with acdat
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.
Or build from the release tag
Point PG_CONFIG to your target PostgreSQL installation:
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:
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.
Create a rule table and sample comments:
Compile the rule table into a single
acdat.machine:Filter only the comments that match at least one rule (
acdat.containsstops on the first hit):Extract every match with its position and join back to your rule table for business labels:
Redact all matched spans in one non-recursive pass:
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:
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
psqltransaction.
2 - Examples and workflows
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 formatches): reports every candidate hit, including prefixes, suffixes, and duplicate text with distinct IDs.leftmost_longest(default forreplace): 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., priority10beats priority20), then longer pattern, then lower ID.
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"(priority10) beats"credit card fraud"(priority20) 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 isNULLraises 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(default10000) andmax_output_bytes(default256 MiB) when short inputs could expand into large outputs. The candidate limit counts raw overlaps before policy resolution, and an outer SQLLIMITdoes 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?”
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:
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.
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.
If version 2 triggers false positives, roll back immediately by reactivating version 1, then retire 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 to0. - 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.
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.
Export on the build database, validate and import on the target database:
source_fingerprint()hashes the canonical rule set;build_fingerprint()also includes engine, compiler, and format version;artifact_checksum()hashes the serialized payload.validate()returnsfalseon corrupted bytes whileimport()raises an error.- Transfer
textmachines only between databases with compatible server encodings;byteamachines are encoding-independent.
3 - Performance and tuning
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]| Operation | 1 backend | 4 workers | 8 workers | 8-worker speedup |
|---|---|---|---|---|
contains | 1.522 s | 0.398 s | 0.228 s | 6.67x |
replace (leftmost_longest) | 2.007 s | 0.510 s | 0.291 s | 6.89x |
matches (all_overlapping) | 3.678 s | 0.816 s | 0.476 s | 7.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 width | Rows | 1 backend | 4 workers | 8 workers |
|---|---|---|---|---|
| 33 B | 10,000,000 | 600.6 ms | 140.1 ms | 104.0 ms |
| 1 KiB | 262,144 | 281.6 ms | 73.3 ms | 49.9 ms |
| 64 KiB | 4,096 | 280.4 ms | 70.5 ms | 48.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:
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):
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 profile | Stored artifact | Cache / process | 9 processes (leader + 8 workers) |
|---|---|---|---|
| Real corpus (1,114 rules) | 269 KiB | 227 KiB | ~2.0 MiB |
| 100k shared-prefix rules | 5.94 MiB | 5.51 MiB | ~49.6 MiB |
| 100k random ASCII rules | 28.96 MiB | 23.93 MiB | ~215.4 MiB |
Four practical rules for fast scans:
- Compile once outside the row loop: Never put
acdat.compile()inside a per-rowWHEREorSELECTexpression. - Filter before scanning: Narrow candidate rows with B-tree, GIN, or time-range indexes first, and choose
acdat.contains()overacdat.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
COPYor a server-side cursor when exporting millions of matches or rewritten rows instead of buffering a giantSELECTin client memory.
4 - Operations
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:
2. Backup, restore, and replication
- Logical dumps (
pg_dump):acdatregisters its catalog tables viapg_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
acdatshared library on the recovery host before starting PostgreSQL. - Logical replication: Install
acdaton 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 message | Cause and fix |
|---|---|
acdat compile failed: pattern ID 1 is duplicated | Every rule in one dictionary must have a unique pattern_id. Deduplicate or assign distinct IDs. |
acdat scan failed: match count exceeds limit 2 | Raw 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 replacement | acdat.replace() selected a rule whose replacement was NULL. Supply a literal replacement (or '' to delete). |
cannot retire the active acdat build | Activate another ready build first, then retire the previous build. |
acdat machine input kind does not match function input | A 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 payload | Publish 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
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
Compile a dictionary
acdat.compile(patterns text[], pattern_ids bigint[], replacements text[], priorities integer[], options jsonb), ,- Compile parallel 1D text arrays into a machine. Omitted IDs default to
1..N;NULLpriorities default to0. acdat.compile(patterns bytea[], pattern_ids bigint[], replacements bytea[], priorities integer[], options jsonb), ,- Binary array overload preserving arbitrary bytes (including
\x00). acdat.compile(text, bigint), ,- Compile rows of
(pattern, pattern_id). ReturnsNULLfor zero rows. acdat.compile(text, bigint, text, integer), ,- Compile rows of
(pattern, pattern_id, replacement, priority). ReturnsNULLfor zero rows. acdat.compile(bytea, bigint), ,- Binary aggregate over
(pattern, pattern_id). ReturnsNULLfor zero rows. acdat.compile(bytea, bigint, bytea, integer), ,- Binary aggregate over
(pattern, pattern_id, replacement, priority). ReturnsNULLfor zero rows.
¹ Defaults apply starting at pattern_ids; patterns is required. options accepts NULL or {}.
Scan and replace
acdat.contains(text, acdat.machine), ,- Return
trueon the first literal match and stop scanning immediately. acdat.contains(bytea, acdat.machine), ,- Binary overload of
contains. acdat.matches(input text, machine acdat.machine, policy text, max_matches integer), ,- 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), ,- Binary overload;
start_charandchar_lengthare alwaysNULL. acdat.replace(input text, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint), ,- Single non-recursive pass rewrite. Errors if a selected match has a
NULLreplacement or exceeds a limit. acdat.replace(input bytea, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint), ,- Binary overload of
replace.
Overlap policies
all_overlapping, ,- Emit every candidate hit, including prefixes, suffixes, and duplicate literals with distinct IDs.
leftmost_longest, ,- Leftmost start offset → longer pattern → lower
priorityinteger → lowerpattern_id→ lower canonical ordinal. leftmost_priority, ,- Leftmost start offset → lower
priorityinteger → longer pattern → lowerpattern_id→ lower canonical ordinal.
Inspect and transport
acdat.info(acdat.machine), ,- Metadata JSON: engine, compiler/format versions, input kind, encoding, pattern/state/slot counts, and sizes.
acdat.export(acdat.machine), ,- Serialize a compiled machine into a portable binary image.
acdat.validate(bytea), ,- Verify a serialized image without raising an error on corruption.
acdat.import(bytea), ,- Validate and decode a serialized image; raises an error if malformed.
acdat.source_fingerprint(acdat.machine), ,- 32-byte SHA-256 digest of the canonical rule set and input kind.
acdat.build_fingerprint(acdat.machine), ,- 32-byte digest identifying rules plus compiler, engine, and format version.
acdat.artifact_checksum(acdat.machine), ,- 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), ,- Store an immutable
readybuild and return its 32-byte dictionary-scopedbuild_id. acdat.activate(p_dictionary_name text, p_build_id bytea), ,- Atomically point
acdat.active_dictionaryto areadybuild. acdat.retire_build(p_dictionary_name text, p_build_id bytea), ,- Mark an inactive build as
retired. acdat.active_machine, ,- Active ready machines:
name,input_kind,version,build_id,machine,info. acdat.dictionary, ,- Dictionary name and fixed
input_kind(textorbytea). acdat.dictionary_version, ,- Semantic version,
source_fingerprint, and optionalsource_refJSON. acdat.dictionary_build, ,- Build metadata, compiler/format/engine info, status (
ready/retired), and checksum. acdat.dictionary_build_data, ,- Compiled
acdat.machinepayload (STORAGE EXTERNAL) keyed bybuild_id. acdat.active_dictionary, ,- Current active
build_idpointer per dictionary.
Types and internal functions
acdat.machine, ,- Variable-length compiled automaton (
STORAGE = external). acdat.hit, ,(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, ,- Type I/O functions revoked from
PUBLIC; invoked by PostgreSQL. _compile_*_trans/_compile_final/_catalog_build_id, ,- Aggregate state transition/final and catalog digest helpers revoked from
PUBLIC.