Skip to content

tdfs4ds.genai.glossary

tdfs4ds.genai.glossary

Glossary of company terms and acronyms (0.3.7.34).

Documentation written by a model expands an acronym it does not know with a plausible wrong meaning, and differently from one object to the next. No column dictionary can fix that: acronyms are company knowledge that no single table carries. This module keeps a glossary per store, optionally per data domain, and puts it to work:

  • Storage: the optional valid-time table FS_GLOSSARY (public view FS_V_GLOSSARY), one row per (TERM, DATA_DOMAIN); DATA_DOMAIN is '' for the whole store and a domain entry wins over the store one. Created at setup() / connect() and by the first write; no table = no glossary (fail-open: every prompt and answer is then byte-identical to what it was).
  • Documentation: :func:documentation_block gives the terms found in an object's names, columns and SQL to the model, with the rule "never expand an acronym that is not in the glossary"; :func:correct_text flags a generated text that expands a glossary acronym differently and replaces the wrong expansion by the glossary meaning (deterministic).
  • Agent: :func:terms_in_question / :func:explain_terms (answered by code).
  • Reports: :func:missing_acronyms lists acronym-like tokens of object and column names the glossary does not know.

Everything that looks at text is pure and unit-tested without a database.

COLUMNS module-attribute

COLUMNS = ('TERM', 'DATA_DOMAIN', 'MEANING', 'SYNONYMS', 'NOTES', 'DOC_SOURCE', 'AUTHOR', 'DB_USER')

SOURCES module-attribute

SOURCES = ('MANUAL', 'IMPORTED')

_STATE module-attribute

_STATE: dict = {}

_WARNED module-attribute

_WARNED: set = set()

_CACHE module-attribute

_CACHE: dict = {}

_CACHE_TTL module-attribute

_CACHE_TTL = 60.0

_IMPORT_COLUMNS module-attribute

_IMPORT_COLUMNS = ('TERM', 'MEANING', 'SYNONYMS', 'DATA_DOMAIN', 'NOTES')

_WORD_RE module-attribute

_WORD_RE = re.compile('[A-Za-z][A-Za-z0-9]*')

_CAMEL_RE module-attribute

_CAMEL_RE = re.compile('[A-Z]+(?![a-z])|[A-Z]?[a-z]+[0-9]*|[0-9]+')

RULE_ONLY module-attribute

RULE_ONLY = '\n\n-- GLOSSARY RULE: this company keeps a glossary of its terms and acronyms. Never expand an acronym you were not given the meaning of; write it as it is.\n'

_STOP module-attribute

_STOP = {'of', 'the', 'and', 'for', 'de', 'des', 'du', 'la', 'le', 'les', 'et', 'a', 'an', 'to', 'in', 'on', 'd', 'l'}

_VERBS module-attribute

_VERBS = '(?:stands?\\s+for|means?|is\\s+short\\s+for|is\\s+an?\\s+abbreviation\\s+of|refers?\\s+to|signifie|veut\\s+dire|d[ée]signe)'

_IGNORED_ACRONYMS module-attribute

_IGNORED_ACRONYMS = {'ID', 'IDS', 'UTC', 'GMT', 'DATE', 'NR', 'NO', 'NBR', 'NUM', 'AMT', 'QTY', 'DT', 'TS', 'TM', 'CD', 'DESC', 'FLG', 'PCT', 'AVG', 'MIN', 'MAX', 'SUM', 'CNT', 'TOT', 'YR', 'MTH', 'SQL', 'TD', 'FS', 'VT', 'KEY', 'SEQ', 'TYPE', 'NAME', 'TEXT', 'LIST', 'TIME', 'YEAR', 'DAY', 'WEEK', 'LAST', 'NEXT', 'FLAG', 'RATE', 'SIZE', 'LEVEL', 'SCORE', 'COUNT', 'VALUE', 'TOTAL', 'ROW', 'COL', 'TAB', 'VIEW', 'DATA', 'LOG', 'RUN', 'START', 'END', 'FROM', 'THIS', 'THAT', 'WITH', 'ONLY', 'ALL', 'ANY', 'NEW', 'OLD', 'CURR', 'PREV', 'BASE', 'MAIN', 'TEMP', 'TMP', 'STG', 'RAW', 'DIM', 'FACT', 'HIST', 'DAILY', 'ASOF', 'AS', 'OF', 'IN', 'ON', 'BY', 'OR', 'AND', 'NOT', 'IS', 'TO', 'AT', 'IF', 'PK', 'FK', 'UUID', 'URL', 'CSV', 'JSON', 'XML', 'NULL', 'NA', 'CODE', 'DESCR', 'STATE', 'STATUS', 'GROUP', 'ORDER', 'SORT', 'RANK', 'PART', 'PERIOD', 'FIRST', 'MONTH', 'WEEKLY', 'ROLL', 'LAG', 'LEAD', 'ZERO', 'ONE', 'TWO', 'TEN', 'SEC', 'MS', 'HR', 'HRS', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN', 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'}

_VOWELS module-attribute

_VOWELS = set('AEIOU')

_MEANING_RE module-attribute

_MEANING_RE = re.compile("(?:what\\s+(?:does|do|is|are|'s)|what's|whats|define|meaning\\s+of|what\\s+is\\s+the\\s+meaning\\s+of|que\\s+(?:veut|signifie|signifient|veulent)|qu['e]\\s*est[- ]ce\\s+que|c['e]\\s*est\\s+quoi|que\\s+signifie|signification\\s+de|d[ée]finition\\s+de|what\\s+does\\s+the\\s+acronym)", re.IGNORECASE)

_FRENCH_RE module-attribute

_FRENCH_RE = re.compile("\\b(?:que|qu'|quoi|signifie|signifient|veut|veulent|dire|signification|d[ée]finition)\\b", re.IGNORECASE)

_RAW_WORD_RE module-attribute

_RAW_WORD_RE = re.compile('[A-Za-z0-9_$#@]+(?:\\.[A-Za-z0-9_$#@]+)*')

LATE_FIX module-attribute

LATE_FIX = 'Re-declare the term without valid_from= (set_glossary_term); tdfs4ds.backdate_glossary(valid_from=<past date>) moves a first version back'

sql_literal

sql_literal(value)

Escape value for use inside a single-quoted SQL string literal.

For the DBC probes and catalog predicates that compare a name as data (WHERE DatabaseName = '…'). The caller supplies the surrounding quotes.

_table_name

_table_name() -> str

_view_name

_view_name() -> str

_qualified_table

_qualified_table() -> str

_key

_key() -> Optional[str]

reset_state

reset_state() -> None

invalidate

invalidate() -> None

_warn_once

_warn_once(key: str, message: str, *args) -> None

_execute

_execute(sql: str)

glossary_ddl

glossary_ddl() -> str

glossary_view_sql

glossary_view_sql() -> str

_view_missing

_view_missing(existing: Optional[Iterable[str]] = None) -> bool

Whether the public view is absent. existing (connect's DBC read of the table database) answers when views live in the table database; otherwise one DBC read. A failed read counts as absent: the REPLACE VIEW that follows is harmless when the view exists (0.3.7.34 field report: a store whose first connect failed on the view never got it, since the table existed).

_create_view

_create_view(label: str) -> None

Create the public view of an existing table; a refusal is a warning (a read-only user).

glossary_creation

glossary_creation(existing: Optional[Iterable[str]] = None) -> bool

Create the table and its view when missing. Never raises; returns whether it is usable.

available

available() -> bool

Whether the table exists in the primary store (checked once per store).

norm_term

norm_term(term) -> str

_norm_domain

_norm_domain(domain) -> str

_lit

_lit(v) -> str

parse_synonyms

parse_synonyms(value) -> List[str]

Synonyms from a JSON list, a list, or text separated by | ; , (order kept, no repeat).

_qualifier

_qualifier(valid_from) -> str

set_term_sql

set_term_sql(term, meaning, *, synonyms=None, data_domain=None, notes=None, source='MANUAL', author=None, valid_from=None, first_version: bool = False) -> str

The valid-time statement recording one term; every column named, every value escaped.

first_version with valid_from (the term has no row at all): a NONSEQUENCED VALIDTIME INSERT with ValidStart = valid_from and ValidEnd = UNTIL_CHANGED. A sequenced MERGE cannot do it: its INSERT branch leaves the period columns empty (Error 3811, checked live). Otherwise a MERGE: valid_from opens it with VALIDTIME PERIOD '(t, UNTIL_CHANGED)', None = CURRENT VALIDTIME.

remove_term_sql

remove_term_sql(term, data_domain=None) -> str

read_sql

read_sql(source: Optional[str] = None, as_of: Optional[str] = None) -> str

SELECT of every row. source None = the primary base table (current valid time, or VALIDTIME AS OF as_of); a string = that store's public view (already current).

_rows_to_frame

_rows_to_frame(rows: Sequence[Sequence[Any]], store: Optional[str])

_primary_store_name

_primary_store_name() -> str

read_frame

read_frame(as_of: Optional[str] = None)

All rows of the primary store plus the read-only stores attached (first store wins per (TERM, DATA_DOMAIN)). Fail-open: an unreadable store contributes nothing; with no glossary anywhere, an empty frame.

resolve_entries

resolve_entries(frame, data_domain: Optional[str] = None) -> Dict[str, Dict[str, Any]]

{TERM: entry} applying to data_domain: store-wide rows, a row of that domain winning over the store one. Pure. data_domain None keeps the store-wide rows only.

_entry_key

_entry_key(e: Dict[str, Any])

resolve_entries_multi

resolve_entries_multi(frame, domains: Sequence[str]) -> Dict[str, Dict[str, Any]]

{TERM: entry} for an object read by the processes of domains. Pure.

No domain: the store-wide terms. One domain: that domain's terms. Several: a term every domain reads the same way keeps that entry; a term the domains read differently (a domain row, or a domain without its own row falling back to the store one) takes the store-wide meaning, with a note naming the domains (the first domain's entry when the store has no store-wide row).

domains_of_nodes

domains_of_nodes(nodes: Iterable[str], proc_df) -> List[str]

Sorted DATA_DOMAINs of the registered process views among lineage node ids ('DB.VIEW'). Pure; names compared unquoted, upper-cased.

object_domains

object_domains(db: str, name: str) -> List[str]

Data domains whose processes read db.name, from the persisted lineage (the processes downstream of the object, then their DATA_DOMAIN in the process catalog). [] when the lineage is empty or unreadable, the object is absent, or no process reads it. Never raises.

effective_glossary_for_object

effective_glossary_for_object(db: str, name: str) -> Dict[str, Dict[str, Any]]

The glossary in force for one object that has no data domain of its own (an intermediate view, a source table, data outside the store): the terms of the domain(s) whose processes read it in the persisted lineage (see resolve_entries_multi for several). Without lineage, or with no reader: the store-wide terms. Cached 60 s. Never raises.

effective_glossary

effective_glossary(data_domain: Optional[str] = 'default') -> Dict[str, Dict[str, Any]]

The glossary in force for data_domain (default: tdfs4ds.DATA_DOMAIN), cached 60 s. {} when the store has none. Never raises.

_author_default

_author_default(author)

_ts

_ts(text)

store_clock_first_date

store_clock_first_date() -> Optional[str]

The earliest first date over the calendars of every data domain's clock (valid-from text), or None without a clock. Never raises.

earliest_business_date

earliest_business_date(data_domain: Optional[str] = None) -> Optional[str]

First business date of the store (a domain when given): the first date of the clock's calendar, else the earliest VALIDTIME_DATE of a COMPLETED follow-up row. Valid-from text or None. Never raises.

term_valid_from

term_valid_from(first_load: bool, data_domain: Optional[str] = None, explicit=None) -> Optional[str]

Valid start of a glossary write: a date the caller gives (explicit, else the documentation_valid_from context), else None = CURRENT VALIDTIME (real time), first load included. first_load and data_domain are kept for compatibility and ignored.

_has_history

_has_history(term, data_domain) -> bool

Whether the term has any row, current or closed (a removed term re-added must not be inserted over its own history). Unreadable = no history (fail-open towards the first load).

domain_list

domain_list(data_domain) -> Optional[List[str]]

The normalised, de-duplicated domains of a list argument ('' = the whole store, kept), in the given order; None for the historical scalar forms (None or one string), which keep their single-row behaviour byte for byte. A string is never split here (use split_domains).

split_domains

split_domains(cell) -> List[str]

Domains of a sheet cell ('CLAIMS, PHARMACY'; separators , ; |), normalised and without repeats; an empty cell is the whole store (['']).

_plan_term

_plan_term(t, meaning, synonyms, domain, notes, source, author, valid_from)

set_glossary_term

set_glossary_term(term: str, meaning: str, *, synonyms=None, data_domain=None, author: Optional[str] = None, notes: Optional[str] = None, dry_run: bool = False, source: str = 'MANUAL', valid_from=None) -> Dict[str, Any]

Declare (or change) a term of the glossary, valid from now (history kept).

tdfs4ds.set_glossary_term('ABC', 'alpha beam coupler', synonyms=['alpha coupler']). data_domain None = the whole store; a domain entry wins over the store one. A list of domains (['CLAIMS', 'PHARMACY'], '' = the whole store) writes one row per domain in ONE multi-statement request; the report then carries rows (one report per domain) and data_domain as the list. Returns {'term', 'data_domain', 'meaning', 'status', 'previous', 'sql', 'applied'}; dry_run=True executes nothing. Raises ValueError for an empty term or meaning and RuntimeError when the table cannot be created.

valid_from: an explicit date the term is valid from (opt-in, for a store read AS OF a past date). Without it the term is valid from now (real time), first load included.

remove_glossary_term

remove_glossary_term(term: str, data_domain=None, *, dry_run: bool = False) -> Dict[str, Any]

End the validity of a term (its history stays readable with get_glossary(as_of=)). data_domain may be a list: one DELETE per domain in one request (report rows).

get_glossary

get_glossary(data_domain: Optional[str] = None, as_of: Optional[str] = None)

The glossary as a DataFrame (TERM, DATA_DOMAIN, MEANING, SYNONYMS, NOTES, DOC_SOURCE, AUTHOR, DB_USER, FEATURE_STORE). data_domain None = every row; a name = the terms in force for that domain (store-wide rows, a domain row winning). Read-only stores attached by connect(databases_readonly=...) are read too (first store wins); as_of reads the primary store at a past valid time.

effective_entry_exact

effective_entry_exact(term, data_domain=None) -> Optional[Dict[str, Any]]

The primary store's current row for exactly (term, data_domain), or None. Fail-open.

_same_entry

_same_entry(prev: Dict[str, Any], meaning, synonyms, notes) -> bool

read_glossary_sheet

read_glossary_sheet(path_or_df, sheet=None)

A DataFrame with the columns TERM, MEANING, SYNONYMS, DATA_DOMAIN, NOTES (upper-cased headers; the last three optional) from a path (.xlsx, .xls, .csv) or a DataFrame.

expand_domain_cells

expand_domain_cells(frame)

One row per domain: a DATA_DOMAIN cell such as CLAIMS, PHARMACY becomes two rows (the other columns repeated). A frame with no such cell is returned unchanged.

plan_import

plan_import(frame, current: Dict[Tuple[str, str], Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]

Pure: classify the rows of a sheet against {(TERM, DOMAIN): entry}: added / changed / unchanged / skipped (empty term or meaning).

import_glossary

import_glossary(path_or_df, *, sheet=None, author: Optional[str] = None, dry_run: bool = True, valid_from=None) -> Dict[str, Any]

Load a sheet of terms (columns TERM, MEANING, SYNONYMS, DATA_DOMAIN, NOTES) into the glossary as IMPORTED. A dry run (the default) only reports what would be added / changed / unchanged; a term already declared by hand is replaced when its meaning differs (the report lists it under changed). Never deletes.

export_glossary

export_glossary(path: str, data_domain: Optional[str] = None) -> str

Write the glossary to .xlsx (or .csv) in the import layout; returns the path.

tokens

tokens(text: str) -> List[str]

Words of text: split on anything that is not a letter or digit, and camelCase (ABCLength -> ABC, Length). Original case kept.

_as_texts

_as_texts(text_or_names) -> List[str]

_token_set

_token_set(texts: Iterable[str]) -> List[List[str]]

_contains_seq

_contains_seq(seq: List[str], pat: List[str]) -> bool

terms_in

terms_in(text_or_names, glossary: Dict[str, Dict[str, Any]]) -> List[Dict[str, Any]]

The glossary entries whose term (or a synonym) appears as whole words in text_or_names (a text, or names of objects / columns, split on _ and camelCase). Case-insensitive. Sorted by term.

glossary_context

glossary_context(found: Sequence[Dict[str, Any]]) -> str

Prompt block listing found terms (fixed English text); '' for none.

documentation_block

documentation_block(texts, data_domain: Optional[str] = 'default', obj=None) -> str

What to append to a documentation prompt for the object described by texts (its name, column names, SQL): the glossary terms found in them with the rule, or just the rule when the store has a glossary and none applies, or '' when the store has no glossary (the prompt is then unchanged).

_norm_text

_norm_text(s: str) -> str

_initials

_initials(expansion: str) -> str

_equivalent

_equivalent(expansion: str, entry: Dict[str, Any]) -> bool

_acronym_re

_acronym_re(term: str) -> str

contradictions

contradictions(generated_text: str, glossary: Dict[str, Dict[str, Any]]) -> List[Tuple[str, str]]

[(term, wrong expansion)] for each glossary acronym the text expands differently.

Conservative: an expansion counts only when clearly attached to the acronym, ABC (words) or words (ABC) when the initials of the words spell the acronym, ABC, the words likewise, or ABC stands for / means words; and only when it is neither the meaning nor a synonym. A correct expansion, a synonym, a parenthesis that is no expansion, and an acronym not in the glossary never flag.

correct_text

correct_text(text: str, glossary: Dict[str, Dict[str, Any]]) -> Tuple[str, List[Tuple[str, str]]]

Replace each wrong expansion found by :func:contradictions with the glossary meaning.

Returns (text, contradictions); the text is unchanged when there is none. The replacement is the captured expansion only, so ABC (High Carbon Fiber) becomes ABC (hollow-core fiber) and High Carbon Fiber (ABC) becomes hollow-core fiber (ABC).

correct_mapping

correct_mapping(texts: Dict[str, str], glossary: Dict[str, Dict[str, Any]])

:func:correct_text over a {part: text} dict: (corrected dict, [(part, term, wrong)]).

report_contradictions

report_contradictions(flagged: Sequence[Tuple[str, str, str]], object_label: str) -> None

Log each corrected expansion as a WARNING (never raises).

status_suffix

status_suffix(flagged: Sequence[Tuple[str, str, str]]) -> str

Text for a documentation log status; '' when nothing was flagged.

check_process_info

check_process_info(process_info: Dict[str, Any], sql: str = '') -> None

Glossary pass over a process's generated documentation (process_info keys of document_process_incremental): wrong expansions are replaced and logged. In place; never raises; nothing happens without a glossary.

check_view_docs

check_view_docs(docs: Dict[str, Any], label: str, obj=None) -> List[Tuple[str, str, str]]

Same pass over document_sql_query_columns output (an intermediate view); in place. obj = (db, name): the glossary of the domain(s) reading the view.

check_sections

check_sections(sections: Dict[str, str], label: str) -> List[Tuple[str, str, str]]

Same pass over a dataset's generated sections; in place.

_acronym_candidates

_acronym_candidates(name: str) -> List[str]

Acronym-like tokens of one object / column name (upper-cased, 2-6 letters, no digit).

missing_acronyms

missing_acronyms(names: Iterable[str], glossary: Dict[str, Dict[str, Any]]) -> List[Dict[str, Any]]

Acronym-like tokens of names (objects, columns) absent from the glossary, with their count and a few of the names carrying them, most frequent first. A heuristic: an all-capital token of 2-6 letters with at most one vowel, or an all-capital token inside a mixed-case name; common SQL, time and abbreviation words (ID, UTC, DATE, NR...) are never listed. A glossary term or synonym is known.

standalone_terms

standalone_terms(question: str, found: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]

The entries of found whose term (or a synonym) is a word of its own in question, not a part of a longer name: ABC in "what does ABC mean?", not in "what is the ABC_ARP_VW table?" (_, db.name and camelCase names are kept whole here; :func:terms_in splits them on purpose, to explain an object's name). A term spelled like an identifier matches that identifier exactly. Pure.

terms_in_question

terms_in_question(question: str, glossary: Dict[str, Dict[str, Any]]) -> List[Dict[str, Any]]

Glossary entries named in a question (whole words, case-insensitive).

is_meaning_question

is_meaning_question(question: str) -> bool

what does ABC mean? / que veut dire ABC ? / what is ABC shape (no store lookup).

explain_terms

explain_terms(found: Sequence[Dict[str, Any]], french: bool = False) -> str

The fixed answer giving the meaning of found terms.

agent_context_block

agent_context_block(question: str) -> str

Small block for a skill's LLM context: the glossary terms named in the question. '' without a glossary or a match.

object_terms_line

object_terms_line(db: str, name: str, texts, french: bool = False) -> str

One line for an answer about an object outside the store: the glossary terms (of the domain(s) reading it) found in its name, description and columns. '' without a glossary or a match. Never raises.

answer_meaning_question

answer_meaning_question(question: str) -> Optional[Dict[str, Any]]

Deterministic answer for a "what does ABC mean?" question when the term is in the glossary.

Returns {'answer', 'terms'} or None (not a meaning question, no glossary, or no glossary term in the question). Never raises.

migration_entries

migration_entries(source_frame, target_frame) -> Dict[str, List[Dict[str, Any]]]

Pure: {'new': [...], 'same': [...], 'differing': [...]} of the source terms against the target's, per (TERM, DATA_DOMAIN). A differing term is reported, never overwritten.

read_store_frame

read_store_frame(store: Optional[str])

Rows of one store's glossary (None = the primary store), fail-open to an empty frame.

coverage_gaps

coverage_gaps(names: Iterable[str]) -> List[Dict[str, Any]]

Acronyms found in object and column names that the glossary lacks, for the documentation coverage report. [] when the store keeps no glossary (nothing to compare with) or on any failure; every domain's terms count as known.

first_versions_sql

first_versions_sql() -> str

First version of each term: (TERM, DATA_DOMAIN, MIN(ValidStart)), whole history.

read_first_versions

read_first_versions() -> List[Tuple[str, str, str]]

[(TERM, DATA_DOMAIN, first valid start)] of the primary store; [] without table. Fail-open.

late_terms

late_terms(first_versions: Sequence[Tuple[str, str, str]], business_dates: Dict[str, Optional[str]]) -> List[Dict[str, Any]]

Pure: the terms whose first version starts after the earliest business date of their scope.

business_dates: {DATA_DOMAIN upper: date} with the key '' for the store-wide date (a domain term uses its domain's date, else the store's). A term with no known date is not listed.

future_terms

future_terms(first_versions: Sequence[Tuple[str, str, str]], now=None) -> List[Dict[str, Any]]

Pure: the terms whose first version starts in the FUTURE (after now, default the current UTC time): a row dated forward by mistake is not valid yet, so nothing reads it.

collect_late_terms

collect_late_terms() -> List[Dict[str, Any]]

I/O wrapper of :func:future_terms for the store (name kept). Never raises.

late_term_findings

late_term_findings(late: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]

Sanity findings (pure): one per term valid in the future, glossary_valid_in_future, warning.

backdate_sql

backdate_sql(term, data_domain, valid_from: str) -> str

NONSEQUENCED UPDATE of the first version of one term (the row starting at its earliest ValidStart).

backdate_glossary

backdate_glossary(valid_from=None, data_domain: Optional[str] = None, *, dry_run: bool = True) -> Dict[str, Any]

Repair for an explicit wish to show glossary terms at past dates (a store read AS OF a past date, an audit); not needed by the agent, which reads at the current time. Moves the first version of each glossary term back to valid_from. Without it: the first date of the data domain's clock (store-wide terms: the earliest over the clocks), else 1900-01-01. Only a first version that starts later is touched; every later version is left as it is. data_domain None = every term. Dry run by default: lists the statements. Returns {'moved': [...], 'sql': [...], 'applied': bool}.