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 viewFS_V_GLOSSARY), one row per(TERM, DATA_DOMAIN);DATA_DOMAINis''for the whole store and a domain entry wins over the store one. Created atsetup()/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_blockgives 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_textflags 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_acronymslists 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')
_IMPORT_COLUMNS
module-attribute
¶
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'}
_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)
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
¶
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.
_view_missing
¶
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 the public view of an existing table; a refusal is a warning (a read-only user).
glossary_creation
¶
Create the table and its view when missing. Never raises; returns whether it is usable.
available
¶
Whether the table exists in the primary store (checked once per store).
parse_synonyms
¶
Synonyms from a JSON list, a list, or text separated by | ; , (order kept, no repeat).
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.
read_sql
¶
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).
read_frame
¶
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
¶
{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.
resolve_entries_multi
¶
{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
¶
Sorted DATA_DOMAINs of the registered process views among lineage node ids ('DB.VIEW').
Pure; names compared unquoted, upper-cased.
object_domains
¶
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
¶
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
¶
The glossary in force for data_domain (default: tdfs4ds.DATA_DOMAIN), cached 60 s.
{} when the store has none. Never raises.
store_clock_first_date
¶
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
¶
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
¶
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
¶
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
¶
Domains of a sheet cell ('CLAIMS, PHARMACY'; separators , ; |), normalised and
without repeats; an empty cell is the whole store (['']).
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
¶
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
¶
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
¶
The primary store's current row for exactly (term, data_domain), or None. Fail-open.
read_glossary_sheet
¶
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
¶
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
¶
Write the glossary to .xlsx (or .csv) in the import layout; returns the path.
tokens
¶
Words of text: split on anything that is not a letter or digit, and camelCase
(HCFLength -> HCF, Length). Original case kept.
terms_in
¶
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
¶
Prompt block listing found terms (fixed English text); '' for none.
documentation_block
¶
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).
contradictions
¶
[(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
¶
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
¶
:func:correct_text over a {part: text} dict: (corrected dict, [(part, term, wrong)]).
report_contradictions
¶
Log each corrected expansion as a WARNING (never raises).
status_suffix
¶
Text for a documentation log status; '' when nothing was flagged.
check_process_info
¶
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
¶
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
¶
Same pass over a dataset's generated sections; in place.
_acronym_candidates
¶
Acronym-like tokens of one object / column name (upper-cased, 2-6 letters, no digit).
missing_acronyms
¶
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.
terms_in_question
¶
Glossary entries named in a question (whole words, case-insensitive).
is_meaning_question
¶
what does ABC mean? / que veut dire ABC ? / what is ABC shape (no store lookup).
explain_terms
¶
The fixed answer giving the meaning of found terms.
agent_context_block
¶
Small block for a skill's LLM context: the glossary terms named in the question. ''
without a glossary or a match.
object_terms_line
¶
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
¶
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
¶
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
¶
Rows of one store's glossary (None = the primary store), fail-open to an empty frame.
coverage_gaps
¶
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 version of each term: (TERM, DATA_DOMAIN, MIN(ValidStart)), whole history.
read_first_versions
¶
[(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
¶
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
¶
I/O wrapper of :func:future_terms for the store (name kept). Never raises.
late_term_findings
¶
Sanity findings (pure): one per term valid in the future, glossary_valid_in_future, warning.
backdate_sql
¶
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}.