-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweb_app.py
More file actions
1688 lines (1551 loc) · 79.2 KB
/
web_app.py
File metadata and controls
1688 lines (1551 loc) · 79.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Web Interface for Natural Language KQL Agent
A Flask web application that provides a user-friendly interface for the KQL agent
"""
from flask import Flask, render_template, request, jsonify, send_from_directory
import asyncio
import time # needed for docs enrichment timing budget
import os
import sys
import traceback
from datetime import datetime, timedelta, timezone
import threading
import re
from urllib import request as urlrequest
from urllib.error import URLError, HTTPError
# Add the project root to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Import the KQL agent
from logs_agent import KQLAgent
try:
from azure.identity import DefaultAzureCredential # type: ignore
from azure.monitor.query import LogsQueryClient # type: ignore
except Exception: # Library might not be installed yet; schema fetch will be skipped
DefaultAzureCredential = None # type: ignore
LogsQueryClient = None # type: ignore
from example_catalog import load_example_catalog
from schema_manager import get_workspace_schema
from examples_loader import load_capsule_csv_queries # CSV capsule queries
app = Flask(__name__)
# Ensure workspace_id is defined before any early cache load attempts to avoid NameError
workspace_id = None
# Legacy compatibility globals (removed caching logic, retained empty structures for tests/UI expecting them)
_workspace_schema_cache = {}
_workspace_schema_refresh_flags = {}
_workspace_schema_refresh_errors = {}
# Workspace schema cache removed; all schema requests now perform a fresh fetch via get_workspace_schema().
# Optional simple persistence for workspace schema across debug reloads.
SCHEMA_CACHE_FILE = None # caching disabled
def _persist_workspace_cache():
return # no-op (caching disabled)
def _load_workspace_cache():
return # no-op (caching disabled)
# Attempt load at module import (only effective on debug reloads)
_load_workspace_cache()
# Docs enrichment tuning (env configurable to avoid UI stalls from slow/blocked Microsoft Docs fetches)
DOCS_ENRICH_DISABLE = bool(os.environ.get("DOCS_ENRICH_DISABLE")) # "1" or any non-empty string disables
WORKSPACE_SCHEMA_SYNC_FETCH = os.environ.get("WORKSPACE_SCHEMA_SYNC_FETCH", "0") == "1" # allow reverting to old synchronous behavior
DOCS_META_MAX_SECONDS = float(os.environ.get("DOCS_META_MAX_SECONDS", "10")) # cumulative time budget for metadata enrichment (raised from 4s to 10s)
# Removed legacy refresh flags and lock (stateless schema fetch)
DOCS_ENRICH_MAX_TABLES = int(os.environ.get("DOCS_ENRICH_MAX_TABLES", "8")) # cap number of unmatched tables to enrich per request
DOCS_ENRICH_MAX_SECONDS = float(os.environ.get("DOCS_ENRICH_MAX_SECONDS", "5")) # cumulative time budget per request
DOCS_ENRICH_COLUMN_FETCH = bool(os.environ.get("DOCS_ENRICH_COLUMN_FETCH", "1")) # allow disabling column scraping (heavier)
# Generic examples fallback
GENERIC_EXAMPLES = {
'Application Insights': [
'Show me failed requests from the last hour',
'Show me recent exceptions',
'Show me recent trace logs',
'Show me dependency failures',
'Show me page views from the last hour',
'Show me performance counters',
],
'Usage Analytics': [
'Show me user activity patterns',
'Get daily active users',
'Show me usage statistics by region',
'Show me usage trends over time',
],
}
# New endpoint: Suggest example queries based on resource type (dynamic mapping)
@app.route('/api/resource-examples', methods=['POST'])
def resource_examples():
"""Suggest example queries for a given resource type.
Strategy:
1. Attempt to locate an *_kql_examples.md file matching the resource_type inside NGSchema.
2. Fallback to app_insights_capsule/kql_examples directory.
3. If none found, return generic examples if available.
"""
try:
import glob
data = request.get_json(silent=True) or {}
resource_type = data.get('resource_type', '').strip()
if not resource_type:
return jsonify({'success': False, 'error': 'Resource type is required'})
def _normalize(s: str) -> str:
return s.replace(' ', '').lower()
example_file = None
ngschema_dir = os.path.join(os.path.dirname(__file__), 'NGSchema')
if os.path.exists(ngschema_dir):
for root, dirs, _ in os.walk(ngschema_dir):
for d in dirs:
if _normalize(d) == _normalize(resource_type):
kql_files = glob.glob(os.path.join(root, d, '*_kql_examples.md'))
if kql_files:
example_file = kql_files[0]
break
if example_file:
break
if not example_file:
capsule_dir = os.path.join(os.path.dirname(__file__), 'app_insights_capsule', 'kql_examples')
if os.path.exists(capsule_dir):
kql_files = glob.glob(os.path.join(capsule_dir, '*_kql_examples.md'))
for f in kql_files:
base = os.path.basename(f).lower()
if _normalize(resource_type) in base:
example_file = f
break
examples = []
if example_file:
try:
with open(example_file, 'r', encoding='utf-8') as ef:
content = ef.read()
# Simple heuristic: lines starting with "#" are titles, code blocks are fenced ``` lines
current_title = None
current_code = []
for line in content.splitlines():
if line.startswith('#'):
if current_title and current_code:
examples.append({'title': current_title.strip('# ').strip(), 'query': '\n'.join(current_code).strip()})
current_title = line
current_code = []
elif line.startswith('```'):
# Toggle collection; naive approach: start capturing after opening fence until closing
if current_code and current_code[-1] == '__END_FENCE__':
current_code.pop() # remove marker
else:
current_code.append('__END_FENCE__')
else:
if current_title:
current_code.append(line)
if current_title and current_code:
if current_code and current_code[-1] == '__END_FENCE__':
current_code.pop()
examples.append({'title': current_title.strip('# ').strip(), 'query': '\n'.join(current_code).strip()})
except Exception as ex: # noqa: BLE001
print(f"[Examples] Failed parsing examples file {example_file}: {ex}")
# Fallback generic examples
if not examples:
generic = GENERIC_EXAMPLES.get(resource_type) or GENERIC_EXAMPLES.get('Application Insights') or []
examples = [{'title': f'Example {i+1}', 'query': q} for i, q in enumerate(generic)]
return jsonify({'success': True, 'resource_type': resource_type, 'example_file': example_file, 'examples': examples})
except Exception as e: # noqa: BLE001
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/fetch-workspace-schema', methods=['GET', 'POST'])
def fetch_workspace_schema():
"""Direct, stateless workspace schema retrieval (lightweight summary).
Returns JSON:
success, workspace_id, table_count, retrieved_at, source, error (optional)
"""
global workspace_id
if not workspace_id:
return jsonify({'success': False, 'workspace_id': None, 'table_count': 0, 'error': 'Workspace not initialized'}), 200
try:
result = get_workspace_schema(workspace_id)
if result.get('error'):
return jsonify({'success': False, 'workspace_id': workspace_id, 'table_count': 0, 'error': result.get('error')}), 200
return jsonify({
'success': True,
'workspace_id': workspace_id,
'table_count': len(result.get('tables', [])),
'retrieved_at': result.get('retrieved_at'),
'source': result.get('source')
})
except Exception as e: # noqa: BLE001
return jsonify({'success': False, 'workspace_id': workspace_id, 'table_count': 0, 'error': str(e)}), 200
# Global agent instance
agent = None
_workspace_resource_types_cache = {} # deprecated: manifest data now supplied via SchemaManager
_workspace_queries_cache = {}
_ms_docs_table_resource_type_cache = {} # table_name -> resource_type | 'unknown resource type'
_ms_docs_table_full_cache = {} # table_name -> { description, columns:[{name,type,description}], fetched_at }
_ms_docs_table_queries_cache = {} # table_name -> [ { name, description } ]
# Shared Azure credential (created once to avoid multiple az login prompts)
_azure_credential = None
_credential_creation_lock = threading.Lock()
# Static fallback map for common Application Insights (Azure Monitor 'classic' AI) derived tables
_STATIC_FALLBACK_TABLE_RESOURCE_TYPES = {
# App Insights standard tables
'AppRequests': 'microsoft.insights/components',
'AppDependencies': 'microsoft.insights/components',
'AppTraces': 'microsoft.insights/components',
'AppExceptions': 'microsoft.insights/components',
'AppAvailabilityResults': 'microsoft.insights/components',
'AppPageViews': 'microsoft.insights/components',
'AppPerformanceCounters': 'microsoft.insights/components',
'AppBrowserTimings': 'microsoft.insights/components',
'AppCustomEvents': 'microsoft.insights/components',
'AppCustomMetrics': 'microsoft.insights/components',
'AppMetric': 'microsoft.insights/components',
'AppMetrics': 'microsoft.insights/components',
'AppSessions': 'microsoft.insights/components',
'AppEvents': 'microsoft.insights/components',
'AppPageViewPerformance': 'microsoft.insights/components'
}
def _lookup_table_resource_type_doc(table_name: str, timeout: float = 4.0) -> str:
"""Best-effort lookup of resource type for a given table via public Microsoft Docs.
Tries https://learn.microsoft.com/en-us/azure/azure-monitor/reference/tables/{table}
Table pages typically include a "Resource type:" label followed by a provider/resourceType value.
Returns discovered resource type string or 'unknown resource type'.
Caches results per process. Keeps failures cached to avoid repeated outbound calls.
"""
if DOCS_ENRICH_DISABLE:
return 'unknown resource type'
if not table_name:
return 'unknown resource type'
cache_key = table_name
# Static fallback first (case-insensitive)
for k, v in _STATIC_FALLBACK_TABLE_RESOURCE_TYPES.items():
if k.lower() == table_name.lower():
return v
if cache_key in _ms_docs_table_resource_type_cache:
return _ms_docs_table_resource_type_cache[cache_key]
slug = table_name.lower()
url = f"https://learn.microsoft.com/en-us/azure/azure-monitor/reference/tables/{slug}"
try:
req = urlrequest.Request(url, headers={
'User-Agent': 'AzMonLogsAgent/1.0 (+https://github.com/noakup)'
})
with urlrequest.urlopen(req, timeout=timeout) as resp:
if resp.status != 200:
_ms_docs_table_resource_type_cache[cache_key] = 'unknown resource type'
return 'unknown resource type'
content = resp.read().decode('utf-8', errors='ignore')
# Heuristic: look for 'Resource type' line then capture next provider/resourceType token
# Common patterns: <strong>Resource type:</strong> Microsoft.Insights/components
# or visible text 'Resource type: microsoft.operationalinsights/workspaces'
m = re.search(r'Resource\s*type:?\s*</?strong>[^A-Za-z0-9/]*([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)', content, re.IGNORECASE)
if not m:
# Fallback: search anywhere for microsoft.<provider>/<resourcetype> preceded by 'Resource type'
m = re.search(r'Resource\s*type:?[^\n]{0,120}?([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)', content, re.IGNORECASE)
if m:
rtype = m.group(1)
# Normalize provider casing (Microsoft.*) if missing capital M
if rtype.lower().startswith('microsoft.') and not rtype.startswith('Microsoft.'):
rtype = 'Microsoft.' + rtype.split('.', 1)[1]
_ms_docs_table_resource_type_cache[cache_key] = rtype
return rtype
except (HTTPError, URLError, TimeoutError, ValueError) as e: # noqa: PERF203 - broad acceptable for network
print(f"[Docs Enrichment] Failed to fetch {url}: {e}")
except Exception as e: # noqa: BLE001
print(f"[Docs Enrichment] Unexpected error for {url}: {e}")
_ms_docs_table_resource_type_cache[cache_key] = 'unknown resource type'
return 'unknown resource type'
def _fetch_table_docs_full(table_name: str, timeout: float = 6.0) -> dict:
"""Fetch table description and columns from Microsoft Docs table reference page.
Caches results in _ms_docs_table_full_cache. Returns a dict:
{ description:str, columns:[{name,type,description}], fetched_at:str }
"""
if DOCS_ENRICH_DISABLE:
return {}
if not table_name:
return {}
if table_name in _ms_docs_table_full_cache:
return _ms_docs_table_full_cache[table_name]
slug = table_name.lower()
url = f"https://learn.microsoft.com/azure/azure-monitor/reference/tables/{slug}"
try:
req = urlrequest.Request(url, headers={'User-Agent': 'AzMonLogsAgent/1.0 (+https://github.com/noakup)'})
with urlrequest.urlopen(req, timeout=timeout) as resp:
if resp.status != 200:
return {}
html = resp.read().decode('utf-8', errors='ignore')
# Very lightweight parsing heuristics (avoid full HTML parser to keep deps minimal)
# Description: first <p> after <h1> or meta description
desc_match = re.search(r'<h1[^>]*>.*?</h1>\s*<p>(.*?)</p>', html, re.IGNORECASE | re.DOTALL)
description = ''
if desc_match:
description = re.sub(r'<[^>]+>', '', desc_match.group(1)).strip()
# Columns: look for markdown-like table rendered as HTML <table> with column headers Name, Type
columns = []
table_sections = re.findall(r'<table.*?>.*?</table>', html, re.IGNORECASE | re.DOTALL)
if DOCS_ENRICH_COLUMN_FETCH:
for sect in table_sections:
if re.search(r'<th[^>]*>\s*Name\s*</th>', sect, re.IGNORECASE) and re.search(r'<th[^>]*>\s*Type\s*</th>', sect, re.IGNORECASE):
# Extract rows
rows = re.findall(r'<tr>(.*?)</tr>', sect, re.IGNORECASE | re.DOTALL)
for r in rows[1:]: # skip header
cols = re.findall(r'<t[dh][^>]*>(.*?)</t[dh]>', r, re.IGNORECASE | re.DOTALL)
if len(cols) >= 2:
cname = re.sub(r'<[^>]+>', '', cols[0]).strip()
ctype = re.sub(r'<[^>]+>', '', cols[1]).strip()
cdesc = ''
if len(cols) >= 3:
cdesc = re.sub(r'<[^>]+>', '', cols[2]).strip()
if cname:
columns.append({'name': cname, 'type': ctype, 'description': cdesc})
if columns:
break
record = {
'description': description,
'columns': columns,
'fetched_at': datetime.now(timezone.utc).isoformat()
}
_ms_docs_table_full_cache[table_name] = record
return record
except Exception as e: # noqa: BLE001
print(f"[Docs Enrichment] Failed full table fetch for {table_name}: {e}")
return {}
def _fetch_table_docs_queries(table_name: str, timeout: float = 6.0) -> list:
"""Fetch example queries for a table from Microsoft Docs queries page.
Heuristic extraction pattern:
<h3>Query Title</h3> (sometimes h2)
<p>Short description sentence.</p>
<pre><code class="lang-kusto">KQL HERE</code></pre>
Returns list of { name, description, code, source='docs' }.
Caches results per table.
"""
if DOCS_ENRICH_DISABLE:
return []
if not table_name:
return []
if table_name in _ms_docs_table_queries_cache:
return _ms_docs_table_queries_cache[table_name]
slug = table_name.lower()
url = f"https://learn.microsoft.com/azure/azure-monitor/reference/queries/{slug}"
try:
req = urlrequest.Request(url, headers={'User-Agent': 'AzMonLogsAgent/1.0 (+https://github.com/noakup)'})
with urlrequest.urlopen(req, timeout=timeout) as resp:
if resp.status != 200:
return []
html_text = resp.read().decode('utf-8', errors='ignore')
import html as html_lib # local import to avoid global namespace clutter
queries = []
# Find all h2/h3 headings as potential query titles
heading_iter = list(re.finditer(r'<h[23][^>]*>(.*?)</h[23]>', html_text, re.IGNORECASE | re.DOTALL))
for idx, match in enumerate(heading_iter):
raw_title = match.group(1)
title_clean = re.sub(r'<[^>]+>', '', raw_title).strip()
if not title_clean:
continue
# Slice segment until next heading or limited length
start = match.end()
end = heading_iter[idx + 1].start() if idx + 1 < len(heading_iter) else len(html_text)
segment = html_text[start:end]
# Description: first <p>...</p>
desc_match = re.search(r'<p>(.*?)</p>', segment, re.IGNORECASE | re.DOTALL)
desc_clean = ''
if desc_match:
desc_clean = re.sub(r'<[^>]+>', '', desc_match.group(1)).strip()
# Code: prefer <pre><code ...>...</code></pre>
code_match = re.search(r'<pre[^>]*>\s*<code[^>]*>([\s\S]*?)</code>\s*</pre>', segment, re.IGNORECASE)
if not code_match:
# fallback single code tag
code_match = re.search(r'<code[^>]*>([\s\S]*?)</code>', segment, re.IGNORECASE)
code_text = ''
if code_match:
code_text = code_match.group(1)
# Remove HTML tags inside code (rare) and unescape entities
code_text = re.sub(r'<[^>]+>', '', code_text)
code_text = html_lib.unescape(code_text).strip()
# Only record if we have at least a code block (to ensure it's an actual query example)
if code_text:
queries.append({
'name': title_clean,
'description': desc_clean,
'code': code_text,
'source': 'docs'
})
_ms_docs_table_queries_cache[table_name] = queries
return queries
except Exception as e: # noqa: BLE001
print(f"[Docs Enrichment] Failed table queries fetch for {table_name}: {e}")
return []
# Legacy cache-based workspace schema block removed.
for entry in workspace_tables:
tname = entry.get('name')
ws_rt = entry.get('resource_type') or 'Unknown'
manifest_rts = manifest_tables_index.get(tname, [])
in_manifest = bool(manifest_rts)
if in_manifest:
matched += 1
# Build subset mapping: include table under each manifest resource type it appears in
for mrt in manifest_rts:
resource_type_subset.setdefault(mrt, []).append(tname)
provider = mrt.split('/')[0]
provider_summary.setdefault(provider, {'tables': 0, 'resource_types': set()})
provider_summary[provider]['tables'] += 1
provider_summary[provider]['resource_types'].add(mrt)
else:
unmatched.append(tname)
enriched.append({
'name': tname,
'workspace_resource_type': ws_rt,
'in_manifest': in_manifest,
'manifest_resource_type': manifest_rts[0] if manifest_rts else None,
'manifest_resource_types': manifest_rts,
'provider': (manifest_rts[0].split('/')[0] if manifest_rts else None)
})
# NOTE: Synthetic fallback grouping for unmatched tables removed per user request.
# Unmatched tables will no longer be assigned to a synthetic resource type; they remain
# visible only in the 'unmatched_tables' list. This keeps the UI honest about mapping
# completeness and allows the frontend to surface an explicit error state when
# workspace tables exist but no resource types are mapped.
# Enrich unmatched tables using Microsoft Docs table pages (best-effort)
doc_enriched = 0
# if unmatched and not DOCS_ENRICH_DISABLE:
# # Bound number of tables & cumulative time to keep endpoint responsive
# t_docs_start = time.time()
# for table in unmatched[:DOCS_ENRICH_MAX_TABLES]:
# doc_rtype = _lookup_table_resource_type_doc(table)
# # Normalize to lowercase provider/resource type to be consistent (as per docs examples)
# if doc_rtype != 'unknown resource type':
# doc_rtype = doc_rtype.strip()
# # Ensure pattern provider/resourceType; if uppercase Microsoft.* keep as-is else lowercase
# if '/' in doc_rtype:
# parts = doc_rtype.split('/')
# if len(parts) == 2:
# # Keep original provider case if startswith Microsoft., else lowercase both
# if not parts[0].startswith('Microsoft.'):
# doc_rtype = f"{parts[0].lower()}/{parts[1].lower()}"
# else:
# # Not a recognized pattern, mark unknown
# doc_rtype = 'unknown resource type'
# # Update enriched list entry
# for e in enriched:
# if e['name'] == table:
# e['doc_resource_type'] = doc_rtype
# if doc_rtype != 'unknown resource type' and not e.get('provider'):
# e['provider'] = doc_rtype.split('/')[0]
# break
# # If a resource type was found (not unknown), include in subset; otherwise bucket under 'unknown resource type'
# target_rtype = doc_rtype if doc_rtype != 'unknown resource type' else 'unknown resource type'
# if target_rtype not in resource_type_subset:
# resource_type_subset[target_rtype] = []
# resource_type_subset[target_rtype].append(table)
# if target_rtype != 'unknown resource type':
# provider = target_rtype.split('/')[0]
# else:
# provider = 'unknown'
# provider_summary.setdefault(provider, {'tables': 0, 'resource_types': set()})
# provider_summary[provider]['tables'] += 1
# if target_rtype != 'unknown resource type':
# provider_summary[provider]['resource_types'].add(target_rtype)
# doc_enriched += 1
# if (time.time() - t_docs_start) > DOCS_ENRICH_MAX_SECONDS:
# print(f"[Docs Enrichment] Cumulative time budget exceeded ({DOCS_ENRICH_MAX_SECONDS}s); skipping remaining tables.")
# break
# Normalize provider summary sets to counts (after enrichment)
provider_summary_out = {
prov: {'tables': info['tables'], 'resource_types': len(info['resource_types']) if isinstance(info['resource_types'], set) else info['resource_types']}
for prov, info in provider_summary.items()
}
# Build per-table queries mapping (manifest first, docs fallback)
manifest_table_queries = manifest_data.get('table_queries', {}) or {}
capsule_csv_queries = {}
try:
capsule_csv_queries = load_capsule_csv_queries()
# Debug summary of capsule CSV ingestion
total_capsule_query_count = sum(len(v) for v in capsule_csv_queries.values())
print(f"[Capsule CSV] tables={list(capsule_csv_queries.keys())} total_queries={total_capsule_query_count}")
for tbl, qlist in capsule_csv_queries.items():
preview = [q.get('name','<noname>')[:60] for q in qlist[:5]]
print(f"[Capsule CSV] table={tbl} count={len(qlist)} preview={preview}")
except Exception as e: # noqa: BLE001
print(f"[Workspace Schema] Capsule CSV ingestion error: {e}")
def _normalize_code(code: str) -> str:
if not isinstance(code, str):
return ''
c = code.replace('\r\n', '\n').replace('\r', '\n').strip()
while '\n\n' in c:
c = c.replace('\n\n', '\n')
return c
workspace_table_queries = {}
tables_with_manifest_queries = 0
tables_with_capsule_queries = 0
tables_with_docs_queries = 0
for tinfo in enriched:
tname = tinfo['name']
combined: list[dict] = []
# 1. Manifest queries (highest precedence)
m_list = manifest_table_queries.get(tname) or []
if m_list:
for q in m_list:
# Ensure uniform shape; manifest queries already include name/description
if q.get('name'):
combined.append({
'name': q.get('name'),
'description': q.get('description'),
'code': q.get('code') if q.get('code') else None,
'source': 'manifest'
})
tables_with_manifest_queries += 1
# 2. Capsule CSV queries (second precedence)
c_list = capsule_csv_queries.get(tname) or []
if c_list:
for q in c_list:
if q.get('name') and q.get('code'):
norm_code = _normalize_code(q.get('code'))
if not any(_normalize_code(existing.get('code')) == norm_code for existing in combined if existing.get('code')):
combined.append({
'name': q.get('name'),
'description': q.get('description') or '',
'code': q.get('code'),
'source': q.get('source') or 'capsule-csv',
'file': q.get('file')
})
tables_with_capsule_queries += 1
# 3. Docs queries (fallback only adds if new code)
if not DOCS_ENRICH_DISABLE:
docs_q = _fetch_table_docs_queries(tname)
if docs_q:
added_docs = 0
for q in docs_q:
if q.get('name') and q.get('code'):
norm_code = _normalize_code(q.get('code'))
if not any(_normalize_code(existing.get('code')) == norm_code for existing in combined if existing.get('code')):
combined.append({
'name': q.get('name'),
'description': q.get('description'),
'code': q.get('code'),
'source': 'docs'
})
added_docs += 1
if added_docs:
tables_with_docs_queries += 1
if combined:
workspace_table_queries[tname] = combined
# Debug per-table merged result
src_counts = {
'manifest': sum(1 for q in combined if q.get('source') == 'manifest'),
'capsule-csv': sum(1 for q in combined if q.get('source') == 'capsule-csv'),
'docs': sum(1 for q in combined if q.get('source') == 'docs')
}
print(f"[QueryMerge] table={tname} total={len(combined)} breakdown={src_counts}")
else:
print(f"[QueryMerge] table={tname} no queries merged (manifest={len(m_list)} capsule={len(capsule_csv_queries.get(tname, []))})")
# Final debug: any query objects missing required fields
missing_fields_total = 0
for tbl, qlist in workspace_table_queries.items():
for q in qlist:
if not q.get('name') or not q.get('code'):
print(f"[QueryMerge][WARN] table={tbl} query missing name/code -> {q}")
missing_fields_total += 1
if missing_fields_total:
print(f"[QueryMerge][WARN] total_incomplete_queries={missing_fields_total}")
else:
print("[QueryMerge] all merged queries have name & code")
response = {
'success': True,
'status': 'ready',
'workspace_id': workspace_id,
'counts': {
'workspace_tables': len(workspace_tables),
'manifest_tables': sum(len(v) for v in manifest_data.get('resource_type_tables', {}).values()),
'matched_tables': matched,
'unmatched_tables': len(unmatched),
'resource_types_with_data': len(resource_type_subset)
},
'tables': enriched,
'resource_type_tables': resource_type_subset,
'providers': provider_summary_out,
'unmatched_tables': unmatched,
'retrieved_at': ws_cache.get('retrieved_at'),
'doc_enrichment': {
'performed': bool(unmatched) and not DOCS_ENRICH_DISABLE,
'enriched_tables': doc_enriched,
'cache_size': len(_ms_docs_table_resource_type_cache),
'disabled': DOCS_ENRICH_DISABLE,
'limits': {
'max_tables': DOCS_ENRICH_MAX_TABLES,
'max_seconds': DOCS_ENRICH_MAX_SECONDS,
'column_fetch': DOCS_ENRICH_COLUMN_FETCH
}
},
# Workspace scoped table metadata (manifest first, docs fallback)
'table_metadata': {},
'table_queries': workspace_table_queries,
'query_enrichment': {
'tables_with_manifest_queries': tables_with_manifest_queries,
'tables_with_capsule_csv_queries': tables_with_capsule_queries,
'tables_with_docs_queries': tables_with_docs_queries
}
}
try:
manifest_meta = manifest_data.get('table_metadata', {}) or {}
t_meta_start = time.time()
for tinfo in enriched:
if (time.time() - t_meta_start) > DOCS_META_MAX_SECONDS:
print(f"[Workspace Schema] Metadata enrichment time budget exceeded ({DOCS_META_MAX_SECONDS}s); truncating.")
break
tname = tinfo['name']
meta = manifest_meta.get(tname, {}).copy()
if not DOCS_ENRICH_DISABLE and (not meta.get('description') or not meta.get('columns')):
docs_meta = _fetch_table_docs_full(tname)
if docs_meta:
if not meta.get('description') and docs_meta.get('description'):
meta['description'] = docs_meta['description']
if not meta.get('columns') and docs_meta.get('columns'):
meta['columns'] = docs_meta['columns']
response['table_metadata'][tname] = meta
except Exception as e: # noqa: BLE001
print(f"[Workspace Schema] Metadata enrichment error: {e}")
# Verbose schema dump removed per request to reduce console noise.
# Persist enriched response back into cache (exclude success/status to keep shape stable for early return)
# Caching disabled: do not persist enriched workspace schema response.
print(f"[Workspace Schema] Enrichment complete (no persistence) tables={len(response.get('tables', []))} table_queries_total={sum(len(v) for v in response.get('table_queries', {}).values())}")
return jsonify(response)
@app.route('/api/workspace-schema-status', methods=['GET'])
def workspace_schema_status():
"""Stateless status endpoint (cache removed).
Returns JSON:
success: bool
status: 'uninitialized' | 'ready' | 'empty'
workspace_id: str|None
table_count: int
retrieved_at: str|None
source: str|None
"""
global workspace_id
if not workspace_id:
return jsonify({'success': False, 'status': 'uninitialized', 'workspace_id': None, 'table_count': 0, 'retrieved_at': None, 'source': None})
result = get_workspace_schema(workspace_id)
if result.get('error'):
return jsonify({'success': False, 'status': 'error', 'workspace_id': workspace_id, 'error': result.get('error'), 'table_count': 0, 'retrieved_at': None, 'source': None})
tables = result.get('tables', [])
status = 'ready' if tables else 'empty'
return jsonify({
'success': True,
'status': status,
'workspace_id': workspace_id,
'table_count': len(tables),
'retrieved_at': result.get('retrieved_at'),
'source': result.get('source')
})
# ---------------------------------------------------------------------------
# Compatibility workspace schema endpoint (previously removed). Front-end and
# tests poll this path; we now serve immediate ready state with stateless fetch.
# ---------------------------------------------------------------------------
@app.route('/api/workspace-schema', methods=['GET'])
def workspace_schema():
"""Enriched workspace schema (stateless) with merged query suggestions.
Returns:
success: bool
status: ready|empty|uninitialized|error
workspace_id: str|None
tables: [ { name, resource_type, manifest_resource_types? } ]
counts: { workspace_tables, tables_with_manifest_queries, tables_with_capsule_csv_queries, tables_with_docs_queries }
table_queries: { tableName: [ { name, description, code, source, file? } ] }
table_metadata: { tableName: { description, columns:[{name,type,description}] } }
doc_enrichment: { disabled: bool }
"""
global workspace_id
if not workspace_id:
return jsonify({'success': False, 'status': 'uninitialized', 'workspace_id': None, 'tables': [], 'counts': {}, 'table_queries': {}, 'table_metadata': {}, 'error': 'Workspace not initialized'}), 400
try:
# Fetch workspace tables
ws_result = get_workspace_schema(workspace_id)
if ws_result.get('error'):
return jsonify({'success': False, 'status': 'error', 'workspace_id': workspace_id, 'error': ws_result.get('error'), 'tables': [], 'table_queries': {}, 'table_metadata': {}}), 500
workspace_tables = ws_result.get('tables', [])
# Load manifest (resource types + manifest queries)
manifest_tables_index = {}
manifest_table_queries = {}
manifest_table_metadata = {}
try:
from schema_manager import SchemaManager
mgr = SchemaManager.get()
mgr.load_manifest(force=False)
manifest_cache = mgr._manifest_cache or {}
manifest_tables_index = manifest_cache.get('resource_type_tables', {}) or {}
# Build reverse index for resource types per table
reverse_index = {}
for rt, tbls in manifest_tables_index.items():
for t in tbls:
reverse_index.setdefault(t, []).append(rt)
manifest_table_queries = manifest_cache.get('table_queries', {}) or {}
manifest_table_metadata = manifest_cache.get('table_metadata', {}) or {}
except Exception as me: # noqa: BLE001
print(f"[WorkspaceSchema] Manifest load error: {me}")
reverse_index = {}
# Capsule CSV queries
try:
from examples_loader import load_capsule_csv_queries
capsule_csv_queries = load_capsule_csv_queries()
except Exception as ce: # noqa: BLE001
print(f"[WorkspaceSchema] Capsule CSV ingestion error: {ce}")
capsule_csv_queries = {}
# Docs queries (optional, only if not disabled)
tables_with_docs_queries = 0
def _normalize_code(code: str) -> str:
if not isinstance(code, str):
return ''
c = code.replace('\r\n', '\n').replace('\r', '\n').strip()
while '\n\n' in c:
c = c.replace('\n\n', '\n')
return c
table_queries = {}
tables_with_manifest_queries = 0
tables_with_capsule_queries = 0
for entry in workspace_tables:
tname = entry.get('name')
combined = []
# Manifest queries first
m_list = manifest_table_queries.get(tname) or []
if m_list:
for q in m_list:
if q.get('name'):
combined.append({
'name': q.get('name'),
'description': q.get('description'),
'code': q.get('code') if q.get('code') else None,
'source': 'manifest'
})
tables_with_manifest_queries += 1
# Capsule CSV queries second
c_list = capsule_csv_queries.get(tname) or []
if c_list:
for q in c_list:
if q.get('name') and q.get('code'):
norm_code = _normalize_code(q.get('code'))
if not any(_normalize_code(existing.get('code')) == norm_code for existing in combined if existing.get('code')):
combined.append({
'name': q.get('name'),
'description': q.get('description') or '',
'code': q.get('code'),
'source': q.get('source') or 'capsule-csv',
'file': q.get('file')
})
tables_with_capsule_queries += 1
# Docs queries third (only if enabled)
if not DOCS_ENRICH_DISABLE:
docs_q = _fetch_table_docs_queries(tname)
if docs_q:
added_docs = 0
for q in docs_q:
if q.get('name') and q.get('code'):
norm_code = _normalize_code(q.get('code'))
if not any(_normalize_code(existing.get('code')) == norm_code for existing in combined if existing.get('code')):
combined.append({
'name': q.get('name'),
'description': q.get('description'),
'code': q.get('code'),
'source': 'docs'
})
added_docs += 1
if added_docs:
tables_with_docs_queries += 1
if combined:
table_queries[tname] = combined
# Attach manifest resource type info to tables
reverse_index = {}
for rt, tbls in manifest_tables_index.items():
for t in tbls:
reverse_index.setdefault(t, []).append(rt)
enriched_tables = []
for entry in workspace_tables:
tname = entry.get('name')
enriched_tables.append({
'name': tname,
'resource_type': entry.get('resource_type') or 'Unknown',
'manifest_resource_types': reverse_index.get(tname, [])
})
# Build minimal table metadata (manifest first, docs fallback if enabled)
table_metadata_out = {}
for tname in [e['name'] for e in enriched_tables]:
meta = manifest_table_metadata.get(tname, {}).copy()
if not DOCS_ENRICH_DISABLE and (not meta.get('description') or not meta.get('columns')):
docs_meta = _fetch_table_docs_full(tname)
if docs_meta:
if not meta.get('description') and docs_meta.get('description'):
meta['description'] = docs_meta['description']
if not meta.get('columns') and docs_meta.get('columns'):
meta['columns'] = docs_meta['columns']
table_metadata_out[tname] = meta
status = 'ready' if enriched_tables else 'empty'
return jsonify({
'success': True,
'status': status,
'workspace_id': workspace_id,
'tables': enriched_tables,
'counts': {
'workspace_tables': len(enriched_tables),
'tables_with_manifest_queries': tables_with_manifest_queries,
'tables_with_capsule_csv_queries': tables_with_capsule_queries,
'tables_with_docs_queries': tables_with_docs_queries
},
'table_queries': table_queries,
'table_metadata': table_metadata_out,
'retrieved_at': ws_result.get('retrieved_at'),
'source': ws_result.get('source'),
'doc_enrichment': {
'disabled': DOCS_ENRICH_DISABLE
},
'error': None
})
except Exception as e: # noqa: BLE001
return jsonify({'success': False, 'status': 'error', 'workspace_id': workspace_id, 'error': str(e)}), 500
@app.route('/api/refresh-manifest', methods=['POST'])
def refresh_manifest():
"""Force a rescan of NGSchema manifests and update persisted manifest cache.
This endpoint is explicit and not part of normal UI flow. Returns summary counts.
"""
try:
from schema_manager import SchemaManager
mgr = SchemaManager.get()
mgr.load_manifest(force=True)
manifest = mgr._manifest_cache
return jsonify({
'success': True,
'forced': True,
'resource_type_count': len(manifest.get('resource_type_tables', {})),
'total_table_mappings': sum(len(v) for v in manifest.get('resource_type_tables', {}).values()),
'fetched_at': manifest.get('fetched_at'),
'manifests_scanned': manifest.get('manifests_scanned')
})
except Exception as e: # noqa: BLE001
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/resource-schema', methods=['GET'])
def resource_schema():
"""Return manifest-derived resource schema merged with any cached workspace tables.
This endpoint restores the previous /api/resource-schema functionality (now missing) so
UI callers expecting it no longer receive a 404. It focuses on resource types and
manifest metadata while optionally enriching with currently cached workspace tables.
Response JSON includes:
success: bool
status: 'uninitialized' | 'pending' | 'ready'
workspace_id: str|None
manifest: {
resource_types: [str],
providers: [str],
counts: { resource_types:int, providers:int, tables:int },
resource_type_tables: { resource_type: [tableName] },
table_metadata: { tableName: { description:str, columns:[{name,type,descriptions:[str]}], resource_types:[str] } },
queries: [ { name, description, resource_type, provider, table, manifest_file, related_tables:[...] } ]
}
workspace: {
tables: [ { name, resource_type } ],
retrieved_at: str|None,
count: int,
source: str|None
}
table_join: [ { name, workspace_resource_type, manifest_resource_types:[str] } ]
"""
global workspace_id
# Persistent manifest load via SchemaManager (decoupled from workspace fetch)
try:
from schema_manager import SchemaManager
mgr = SchemaManager.get()
mgr.load_manifest(force=False)
manifest_data = mgr._manifest_cache
except Exception as e: # pragma: no cover
print(f"[ResourceSchema] Manifest load error: {e}")
manifest_data = {}
# If no workspace selected yet, return manifest-only payload (no error)
if not workspace_id:
# Provide explicit top-level lists for frontend convenience (resource_types/providers)
_rt_tables = manifest_data.get('resource_type_tables', {}) or {}
_resource_types_list = sorted(_rt_tables.keys())
_providers_list = sorted({rt.split('/')[0] for rt in _rt_tables})
return jsonify({
'success': True,
'status': 'manifest-only',
'workspace_id': None,
'manifest': {
'resource_type_tables': _rt_tables,
'table_resource_types': manifest_data.get('table_resource_types', {}),
'resource_types': _resource_types_list,
'providers': _providers_list,
'fetched_at': manifest_data.get('fetched_at'),
'manifests_scanned': manifest_data.get('manifests_scanned'),
'counts': {
'resource_types': len(_resource_types_list),
'providers': len(_providers_list),
'tables': sum(len(v) for v in _rt_tables.values())
}
},
'workspace': {
'tables': [], 'retrieved_at': None, 'count': 0, 'source': None
},
'table_join': []
})
# Workspace tables (may be absent if not yet fetched)
# Fresh fetch of workspace tables (cache removed)
ws_result = get_workspace_schema(workspace_id)
if ws_result.get('error'):
print(f"[ResourceSchema] workspace fetch error: {ws_result.get('error')}")
workspace_tables = []
ws_retrieved = None
ws_source = None
else:
workspace_tables = ws_result.get('tables', [])
ws_retrieved = ws_result.get('retrieved_at')
ws_source = ws_result.get('source')
# workspace_tables already set above
join = []
manifest_tables_index = manifest_data.get('resource_type_tables', {})
# Build reverse index table -> list(resource_types)
reverse_index = {}
for rt, tbls in manifest_tables_index.items():
for t in tbls:
reverse_index.setdefault(t, []).append(rt)
for entry in workspace_tables:
tname = entry.get('name')
w_rt = entry.get('resource_type') or 'Unknown'
m_rts = reverse_index.get(tname, [])
join.append({'name': tname, 'workspace_resource_type': w_rt, 'manifest_resource_types': m_rts})
_rt_tables = manifest_data.get('resource_type_tables', {}) or {}
_resource_types_list = sorted(_rt_tables.keys())
_providers_list = sorted({rt.split('/')[0] for rt in _rt_tables})
return jsonify({
'success': True,
'status': 'ready',
'workspace_id': workspace_id,
'manifest': {
'resource_type_tables': _rt_tables,
'table_resource_types': manifest_data.get('table_resource_types', {}),
'resource_types': _resource_types_list,
'providers': _providers_list,
'fetched_at': manifest_data.get('fetched_at'),
'manifests_scanned': manifest_data.get('manifests_scanned'),
'counts': {
'resource_types': len(_resource_types_list),
'providers': len(_providers_list),
'tables': sum(len(v) for v in _rt_tables.values())
}
},
'workspace': {
'tables': [{'name': e.get('name'), 'resource_type': e.get('resource_type') or 'Unknown', 'manifest_resource_types': e.get('manifest_resource_types', [])} for e in workspace_tables],
'retrieved_at': ws_retrieved,
'count': len(workspace_tables),
'source': ws_source
},
'table_join': join
})
def _scan_manifest_resource_types() -> dict:
"""Scan NGSchema manifest files to enumerate resource types/providers, map tables, and pick up query definitions.
Returns a dict with keys: