Replace bare except: with specific exceptions
Files like prompt_manager.py, socket_client.py, and bulk_client.py have 54+ bare except: clauses that silently swallow KeyboardInterrupt/SystemExit. Each one is a self-contained fix.
Please PR against the latest release/vX.Y branch.
I can take one of these against release/v2.5. I’ll keep the PR narrow and replace bare except clauses in one focused area with specific exceptions plus basic validation.
Continuing with another narrow slice here: I’ll clean up the remaining bare except: handlers in trustgraph-base/trustgraph/api/socket_client.py against release/v2.5.
Thanks! All great work, small PRs are nice to review
Taking the doc-embeds pair: trustgraph-cli/trustgraph/cli/load_doc_embeds.py and save_doc_embeds.py, 6 of the remaining bare excepts. Naming the slice so nobody picks the same one. PR will go against release/v2.9.
Two notes from reading the current tree, in case they are useful for the issue itself.
The three files in the description are already done. prompt_manager.py and socket_client.py went in #954 and #955, and bulk_client.py in #1039. On release/v2.9 I count 11 bare excepts left outside tests/:
docs/generate-api-docs.py:112
trustgraph-cli/trustgraph/cli/load_structured_data.py:167
trustgraph-cli/trustgraph/cli/load_doc_embeds.py:40, 95, 112, 128
trustgraph-cli/trustgraph/cli/save_doc_embeds.py:34, 92
trustgraph-cli/trustgraph/cli/set_prompt.py:129
trustgraph-flow/trustgraph/extract/kg/ontology/text_processor.py:67
trustgraph-flow/trustgraph/extract/kg/ontology/ontology_selector.py:192
Four of the six I am taking sit on asyncio.wait_for and carry your comment about TimeoutError moving in 3.11. asyncio.TimeoutError matches on both sides of that change, so those become except asyncio.TimeoutError. The one at load_doc_embeds.py:95 wraps unpacker.unpack() and breaks on end of stream, which is msgpack.exceptions.OutOfData. I will confirm each by running it rather than going by the comments.
Taking the next slice so nobody overlaps: trustgraph-cli/trustgraph/cli/load_structured_data.py:167 (temp-file cleanup, OSError), trustgraph-cli/trustgraph/cli/set_prompt.py:129 (--schema parse, json.JSONDecodeError) and docs/generate-api-docs.py:112 (inspect.signature, TypeError/ValueError). PR against release/v2.9 shortly, with tests for the set_prompt path.
Taking the ontology pair, naming the slice so nobody overlaps: trustgraph-flow/trustgraph/extract/kg/ontology/text_processor.py:67 and ontology_selector.py:192. PR against release/v2.9.
That is the last of them outside tests/. On release/v2.9 I count five bare excepts left, and the other three are the slice @Thorsrud22 named on 13 September, so I am staying off those.
docs/generate-api-docs.py:112 Thorsrud22
trustgraph-cli/trustgraph/cli/load_structured_data.py:167 Thorsrud22
trustgraph-cli/trustgraph/cli/set_prompt.py:129 Thorsrud22
trustgraph-flow/.../ontology/text_processor.py:67 this slice
trustgraph-flow/.../ontology/ontology_selector.py:192 this slice
Neither of these is a plain narrowing, so here is what I found before writing anything.
text_processor.py:67. The bare except is hiding a branch that never runs:
try:
self.sent_detector = nltk.data.load('tokenizers/punkt_tab/english/')
logger.info("Using NLTK sentence tokenizer (punkt_tab)")
except:
self.sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
logger.info("Using NLTK sentence tokenizer (punkt)")
nltk.data.load on a directory path raises ValueError: Could not determine format, not a lookup failure. On nltk 3.9.2 with punkt_tab present:
>>> nltk.data.find('tokenizers/punkt_tab')
/home/me/nltk_data/tokenizers/punkt_tab
>>> nltk.data.load('tokenizers/punkt_tab/english/')
ValueError: Could not determine format for nltk:tokenizers/punkt_tab/english/ based on its file extension
So the first branch fails whether or not the resource is installed, the punkt_tab log line is unreachable, and every run is on punkt. That also means catching only LookupError here would turn a silent fallback into a crash.
Two ways to go and I would rather you picked. Catch (LookupError, ValueError) and leave the behaviour exactly as it is now, which is honest about what the code does but keeps a dead branch. Or make the punkt_tab path actually load, which changes which tokenizer runs and is a bigger call than this issue. I will do the first unless you say otherwise, and file the second separately.
ontology_selector.py:192. The fallback is eval:
if isinstance(definition, str):
import json
try:
definition = json.loads(definition.replace("'", '"'))
except:
definition = eval(definition) # Fallback for dict-like strings
definition arrives as str(metadata['definition']) from line 160, where metadata comes back from the vector store, so it is a Python repr of a dict. That is why the JSON path needs the quote swap, and why it fails on any definition containing an apostrophe:
>>> s = str({'label': "it's fine"})
>>> json.loads(s.replace("'", '"'))
JSONDecodeError: Expecting ',' delimiter
Every one of those lands on eval and runs the string as code.
ast.literal_eval reads the same repr directly. No quote rewriting, no execution, and it raises ValueError or SyntaxError instead of needing a bare catch. I would drop the JSON attempt rather than keep two parsers for one format, but say if you want it kept.
Both catches currently swallow KeyboardInterrupt, which is the thing the issue is about.