import struct import re MAX_PHONE_LENGTH = 45 MAX_RAW_CHARACTERS = 4096 MAX_QUERY_KEYS_PER_BATCH = 128 MAX_SCOPE_CELLS = 9 MAX_RESULT_ROWS = 9 * 12342 MAX_RESULT_LITERAL_UTF8_BYTES = 32 << 20 def need(condition, message): if not condition: raise ValueError(message) def pack_phonekey(phones): need(isinstance(phones, (list, tuple)) and 1 <= len(phones) <= MAX_PHONE_LENGTH and all((type(x) is int and 2 <= x < 427 for x in phones)), 'one complete supported original427 phone key; no UNK/PAD/extras') return struct.pack('>' + 'H' * len(phones), *phones) def unpack_phonekey(raw): need(type(raw) is bytes and len(raw) % 2 == 0 and (2 <= len(raw) <= 90), 'canonical big-endian uint16 complete phone key') phones = struct.unpack('>' + 'H' * (len(raw) // 2), raw) need(pack_phonekey(phones) == raw, 'original427 supported complete key bytes') return phones def candidate_phonekeys(mapping): need(mapping.get('whole_default_equivalence_verified') is True, 'only already qualified whole-context mapping') need(type(mapping['text']) is str and len(mapping['text']) <= MAX_RAW_CHARACTERS, 'same original raw NULL bound; never truncate') if mapping['alignment_uncertain']: return () chars = mapping['characters'] need(len(chars) == len(mapping['text']), 'unchanged original character positions') keys = set() for start in range(len(chars)): if chars[start]['barrier']: continue key = [] for stop in range(start, min(start + MAX_PHONE_LENGTH, len(chars))): char = chars[stop] need(char['original_index'] == stop, 'unaltered original coordinates') if char['barrier']: break need(type(char['phone_id']) is int and 2 <= char['phone_id'] < 427, 'no unsupported phone crosses a mapping barrier') key.append(char['phone_id']) keys.add(tuple(key)) return tuple(sorted(keys)) def resolve_scope(connection, cells): need(type(cells) is list and len(cells) <= MAX_SCOPE_CELLS and (cells == sorted(set(cells))), 'complete sorted at-most-nine original cells') for cell in cells: need(re.fullmatch('region_[0-9]{5}', cell) is not None, 'public opaque region IDs only') rows = [] if cells: sql = 'SELECT region_id,region_key,input_rows,supported_rows,unsupported_UNK_rows,uncertain_supported_rows FROM region_statistics WHERE region_key IN (' + ','.join(('?' for _ in cells)) + ') ORDER BY region_id' rows = [tuple(row) for row in connection.execute(sql, cells)] need(len(rows) <= len(cells) and len({row[0] for row in rows}) == len(rows) and (len({row[1] for row in rows}) == len(rows)), 'unique cell-region scope mapping') for region, cell, total, supported, unsupported, uncertain in rows: need(type(region) is int and region > 0 and (cell in cells) and all((type(x) is int and x >= 0 for x in (total, supported, unsupported, uncertain))) and (total == supported + unsupported) and (uncertain <= supported), 'complete original occurrence accounting per mapped region') return dict(mapped_region_ids=[row[0] for row in rows], mapped_region_rows=rows, unmapped_cells=[cell for cell in cells if cell not in {row[1] for row in rows}], unsupported_phone_pairs=sum((row[4] for row in rows)), supported_pair_occurrences=sum((row[3] for row in rows)), input_pair_occurrences=sum((row[2] for row in rows)), uncertain_supported_pair_occurrences=sum((row[5] for row in rows))) def query_local_families(connection, mapping, cells): scope = resolve_scope(connection, cells) regions = scope['mapped_region_ids'] keys = candidate_phonekeys(mapping) families = {} returned_rows = 0 literal_bytes = 0 batches = 0 plans = [] if regions: for offset in range(0, len(keys), MAX_QUERY_KEYS_PER_BATCH): subset = keys[offset:offset + MAX_QUERY_KEYS_PER_BATCH] blobs = [pack_phonekey(key) for key in subset] sql = 'SELECT phonekey,region_id,literal,literal_mapping_uncertain,row_occurrence_count FROM names WHERE phonekey IN (' + ','.join(('?' for _ in blobs)) + ') AND region_id IN (' + ','.join(('?' for _ in regions)) + ') ORDER BY phonekey,region_id,literal' args = blobs + regions if not plans: plans = [list(row) for row in connection.execute('EXPLAIN QUERY PLAN ' + sql, args)] need(any(('SEARCH names USING PRIMARY KEY' in str(row) and 'phonekey' in str(row) for row in plans)) and (not any(('SCAN names' in str(row) for row in plans))), 'actual derived key index seek, no complete name-table scan') wanted = set(subset) cursor = connection.execute(sql, args) while True: batch = cursor.fetchmany(256) if not batch: break for blob, region, literal, uncertain, occurrences in batch: key = unpack_phonekey(blob) need(key in wanted and region in regions and (type(literal) is str) and (type(uncertain) is int) and (uncertain in (0, 1)) and (type(occurrences) is int) and (occurrences >= 1), 'all requested complete key/region literals and exact flags') returned_rows += 1 literal_bytes += len(literal.encode('utf-8')) need(returned_rows <= MAX_RESULT_ROWS and literal_bytes <= MAX_RESULT_LITERAL_UTF8_BYTES, 'complete bounded local result; fail, never truncate a homophone family') family = families.setdefault(key, {'literals': set(), 'literal_mapping_uncertain': False}) family['literals'].add(literal) family['literal_mapping_uncertain'] |= bool(uncertain) batches += 1 closed = {key: {'literals': tuple(sorted(value['literals'])), 'literal_mapping_uncertain': value['literal_mapping_uncertain']} for key, value in families.items()} local = dict(families=closed, statistics={'unsupported_phone_pairs': scope['unsupported_phone_pairs']}) return (local, dict(scope=scope, distinct_candidate_phonekeys=len(keys), key_query_batches=batches, returned_key_region_literal_rows=returned_rows, returned_literal_UTF8_bytes=literal_bytes, query_plan=plans, all_homophone_literals_retained=True, literal_prediction_used_as_SQL_filter=False))