File size: 13,349 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read source-bound appearance observations from a native attribute release.

Standard library only. No prepared-pool filtering, filename inference, asset
reads, image hashing or native certification. ``deadline`` is an absolute
``time.monotonic()`` timestamp, shared with the retrieval worker. SQLite work
and Python processing check it cooperatively; callers must retain their outer
process timeout for an uninterruptible filesystem/NFS operation.

Pass the native release path explicitly; no implicit fallback is used.
"""
from __future__ import annotations

import hashlib
import json
import math
from pathlib import Path
import re
import sqlite3
import time


_DIMENSIONS = ('style_tags', 'colors', 'materials', 'shapes')
_FACETS = dict(zip(_DIMENSIONS, ('style', 'colors', 'materials', 'shape')))
_USABLE = frozenset(('inferred', 'measured', 'verified'))
_EMPTY = frozenset(('unknown', 'unspecified', 'none', 'n/a', 'pending', 'conflict'))
_SHAPE_TERMS = {
    'round': r'round|circular',
    'rectangle': r'rectangle|rectangular',
    'oval': r'oval',
    'l_shape': r'l[- _]+shap(?:e|ed)',
    'three_seater': r'(?:three|3)[- ]+(?:seaters?|seats?|seat[- ]+cushions?)',
}
_SHAPE_PATTERNS = {name: re.compile(r'(?<![\w])(?:' + term + r')(?![\w])', re.I)
                   for name, term in _SHAPE_TERMS.items()}
_NEGATION = re.compile(r'\b(?:not|no|without|non)[ -]+(?:(?:a|an)[ -]+)?$', re.I)
_SHAPE_CLAUSE_END = re.compile(
    r'[,;:.!?\n]|\b(?:with|featuring|having|including|containing|contains?|'
    r'equipped|decorated|adorned|supported|has|have)\b', re.I)
# Deliberately finite: an unrecognized subject description stays unknown.
_SHAPE_ADJECTIVES = (
    r'a|an|the|long|short|low|high|tall|large|small|wide|narrow|simple|'
    r'wooden|wood|metal|metallic|glass|upholstered|modern|minimalist|contemporary')
_SHAPE_PREFIX = re.compile(r'\s*(?:(?:' + _SHAPE_ADJECTIVES + r')\s+)*', re.I)
_SHAPE_COMPONENT = re.compile(
    r'\s+(?:(?:wooden|wood|metal|metallic|glass|decorative)\s+)*'
    r'(?:legs?|pillows?|cushions?|insets?|ornaments?|decorations?|'
    r'braces?|handles?|armrests?|feet|foot|edges?|accents?)\b', re.I)


def _check_deadline(deadline):
    if time.monotonic() >= deadline:
        raise TimeoutError('appearance_index_timeout: observations incomplete')


def _object(value):
    return value if isinstance(value, dict) else {}


def _list(value):
    return value if isinstance(value, list) else []


def _text(value):
    if isinstance(value, str):
        value = value.strip()
        if value and value.casefold() not in _EMPTY:
            return value
    return None


def _usable(value):
    return isinstance(value, dict) and value.get('status') in _USABLE


def _entry_usable(value):
    return isinstance(value, dict) and ('status' not in value or _usable(value))


def _empty(asset_id, status):
    return dict(asset_id=asset_id, features={d: [] for d in _DIMENSIONS},
                basis={d: [] for d in _DIMENSIONS}, shape_text={},
                source_sha256=None, runtime_sha256=None, record_id=None,
                record_sha256=None, evidence_refs={}, facet_metadata={},
                evidence_content_verified=False, status=status)


def _normalize(row):
    aid, rid, sql_source, raw = row
    try:
        record = json.loads(raw)
    except (TypeError, ValueError, UnicodeDecodeError) as exc:
        raise ValueError(f'appearance_index invalid record_json for {rid!r}') from exc
    if not isinstance(record, dict):
        raise ValueError(f'appearance_index record_json must be an object for {rid!r}')
    raw_bytes = raw.encode('utf-8') if isinstance(raw, str) else raw
    result = _empty(aid, 'inferred_metadata_not_certified')
    result.update(record_id=rid, record_sha256=hashlib.sha256(raw_bytes).hexdigest())
    identity = _object(record.get('identity'))
    source = _object(identity.get('source'))
    runtime = _object(identity.get('runtime'))
    source_value, runtime_value = _object(source.get('value')), _object(runtime.get('value'))
    result.update(source_sha256=source_value.get('sha256'),
                  runtime_sha256=runtime_value.get('sha256'),
                  source_identity=source, runtime_identity=runtime,
                  declared_sql_source_sha256=sql_source)
    registry = _object(record.get('evidence_registry'))
    result['evidence_refs'] = registry
    # Appearance inference cannot establish which source/runtime it describes.
    # Require explicit verified identities; retain all declarations for audit.
    identity_errors = []
    for name, declaration in (('source', source), ('runtime', runtime)):
        if declaration.get('status') != 'verified':
            identity_errors.append(f'$.identity.{name}.status')
        sha = result[name + '_sha256']
        if not isinstance(sha, str) or re.fullmatch(r'[0-9a-fA-F]{64}', sha) is None:
            identity_errors.append(f'$.identity.{name}.value.sha256')
    if identity_errors:
        result['status'] = 'source_identity_unverified'
        result['identity_validation_errors'] = identity_errors
        return result
    # Preserve differing declarations, but never use a conflicting binding to
    # satisfy an entity's hard appearance requirement.
    if (sql_source and result['source_sha256'] and sql_source != result['source_sha256']):
        result['status'] = 'source_identity_conflict'
        return result
    if ((record.get('asset_id') is not None and record['asset_id'] != aid) or
            (record.get('record_id') is not None and record['record_id'] != rid)):
        result['status'] = 'record_identity_conflict'
        return result

    attributes = _object(record.get('attributes'))
    for dimension, facet_name in _FACETS.items():
        facet = _object(attributes.get(facet_name))
        result['facet_metadata'][dimension] = {
            key: facet[key] for key in ('status', 'confidence', 'provenance', 'evidence') if key in facet}
        if not _usable(facet):
            continue
        value = _object(facet.get('value'))
        prefix = '$.attributes.' + facet_name + '.value'
        if not _entry_usable(value):
            continue
        if 'appearance_status' in value and value['appearance_status'] not in _USABLE:
            continue

        def add(label, path):
            label = _text(label)
            if label is not None:
                result['features'][dimension].append(label)
                result['basis'][dimension].append(path)

        if dimension == 'style_tags':
            for i, label in enumerate(_list(value.get('labels'))):
                if not _entry_usable(label):
                    continue
                score = label.get('score')
                if type(score) in (int, float) and math.isfinite(score) and score >= .4:
                    add(label.get('name'), f'{prefix}.labels[{i}].name')
        elif dimension == 'colors':
            appearance = _object(value.get('rendered_appearance'))
            if not _entry_usable(appearance):
                continue
            for i, entry in enumerate(_list(appearance.get('palette'))):
                if _entry_usable(entry):
                    add(entry.get('color_name'), f'{prefix}.rendered_appearance.palette[{i}].color_name')
        elif dimension == 'materials':
            appearance = _object(value.get('appearance'))
            if not _entry_usable(appearance):
                continue
            for i, entry in enumerate(_list(appearance.get('appearance'))):
                if _entry_usable(entry):
                    add(entry.get('material_appearance'), f'{prefix}.appearance.appearance[{i}].material_appearance')
        else:
            description = value.get('description')
            if _text(description):
                result['shape_text']['description'] = description
                head = _SHAPE_CLAUSE_END.split(description, maxsplit=1)[0]
                for label, pattern in _SHAPE_PATTERNS.items():
                    if label == 'three_seater':
                        # Explicit seating count can occur after "with";
                        # component counts such as legs/pillows never match.
                        matches = (not _NEGATION.search(description[:m.start()])
                                   for m in pattern.finditer(description))
                    else:
                        # Only the initial subject's adjective is evidence of
                        # overall form. Parts and later clauses are audit only.
                        matches = (_SHAPE_PREFIX.fullmatch(head[:m.start()]) is not None
                                   and not _SHAPE_COMPONENT.match(head[m.end():])
                                   for m in pattern.finditer(head))
                    if any(matches):
                        add(label, prefix + '.description')
            if 'parts' in value:
                result['shape_text']['parts'] = value['parts']
        result['features'][dimension] = sorted(set(result['features'][dimension]))
        result['basis'][dimension] = sorted(set(result['basis'][dimension]))
    evidence_keys = {key for facet in result['facet_metadata'].values()
                     for key in _list(facet.get('evidence')) if isinstance(key, str)}
    result['unresolved_evidence_refs'] = sorted(evidence_keys - registry.keys())
    return result


def load_observations(path, asset_ids, deadline=None) -> dict:
    """Return normalized records keyed by requested asset ID (missing IDs omitted).

    ``path`` must be the native release's records SQLite, not annotation_index.
    Each query uses at most 400 bound IDs. Pool/processing status never limits
    discovery. Duplicate IDs in the request are deduplicated; duplicate *rows*
    return an ``ambiguous`` entry with empty features and compact ``records``
    identities, never an arbitrarily selected source variant. Malformed JSON,
    schema/IO errors and expired deadlines raise without a partial result.

    Hashes and evidence URIs are release declarations; only record_sha256 is
    freshly computed here, over the exact stored record_json UTF-8 bytes.
    Both identity declarations must have status verified and a 64-hex SHA;
    otherwise features stay empty with status source_identity_unverified.
    """
    if deadline is None:
        deadline = time.monotonic() + 30.0
    if type(deadline) not in (int, float) or not math.isfinite(deadline):
        raise ValueError('deadline must be a finite absolute monotonic timestamp')
    _check_deadline(deadline)
    if isinstance(asset_ids, (str, bytes)):
        raise TypeError('asset_ids must be an iterable of asset ID strings')
    ids = []
    seen = set()
    for aid in asset_ids:
        _check_deadline(deadline)
        if not isinstance(aid, str):
            raise TypeError('asset_ids must contain strings')
        if aid not in seen:
            seen.add(aid)
            ids.append(aid)
    if not ids:
        return {}
    # absolute() does not resolve a symlink or add a separate filesystem stat.
    uri = Path(path).absolute().as_uri() + '?mode=ro'
    db = None
    try:
        db = sqlite3.connect(uri, uri=True, timeout=min(1.0, max(0.0, deadline-time.monotonic())))
        db.execute('PRAGMA query_only=ON')
        db.execute('PRAGMA trusted_schema=OFF')
        db.set_progress_handler(lambda: int(time.monotonic() >= deadline), 1000)
        db.execute('BEGIN')
        columns = {r[1] for r in db.execute('PRAGMA table_info(records)')}
        if not {'asset_id', 'record_id', 'source_sha256', 'record_json'} <= columns:
            raise ValueError('appearance_index schema: expected native records(asset_id, record_id, source_sha256, record_json)')
        result = {}
        for offset in range(0, len(ids), 400):
            _check_deadline(deadline)
            chunk = ids[offset:offset+400]
            marks = ','.join('?' for _ in chunk)
            query = f'SELECT asset_id, record_id, source_sha256, record_json FROM records WHERE asset_id IN ({marks})'
            for row in db.execute(query, chunk):
                _check_deadline(deadline)
                observation = _normalize(row)
                aid = row[0]
                if aid not in result:
                    result[aid] = observation
                else:
                    previous = result[aid]
                    keys = ('record_id', 'record_sha256', 'source_sha256', 'runtime_sha256')
                    if previous['status'] != 'ambiguous':
                        previous = _empty(aid, 'ambiguous')
                        previous['records'] = [{key: result[aid][key] for key in keys}]
                        result[aid] = previous
                    previous['records'].append({key: observation[key] for key in keys})
                _check_deadline(deadline)
        for observation in result.values():
            if observation['status'] == 'ambiguous':
                observation['records'].sort(key=lambda r: str(r['record_id']))
        _check_deadline(deadline)
        return result
    except sqlite3.Error as exc:
        if time.monotonic() >= deadline:
            raise TimeoutError('appearance_index_timeout: observations incomplete') from exc
        raise ValueError(f'appearance_index read/schema error: {exc}') from exc
    finally:
        if db is not None:
            db.close()