From 0a1dd2d1eac37d7878cf78dab5ce1647d58545b8 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Wed, 18 Nov 2026 14:58:26 +0800 Subject: [PATCH 1/6] feat(logging): add JSON and human runtime presentations Refs https://github.com/teaql/teaql-python/issues/73 Coordinated release: https://github.com/teaql/teaql-conformance/issues/248 Signed-off-by: Philip Z --- src/teaql/runtime/__init__.py | 2 + src/teaql/runtime/context.py | 57 +++- src/teaql/runtime/logging.py | 368 ++++++++++++++++++++++++ src/teaql/runtime/object_storage.py | 3 +- src/teaql/runtime/query_list.py | 3 +- src/teaql/runtime/query_stream.py | 3 +- src/teaql/sql/executor.py | 11 +- tests/runtime/test_log_presentations.py | 298 +++++++++++++++++++ tests/runtime/test_runtime_logging.py | 304 ++++++++++++++++++++ 9 files changed, 1033 insertions(+), 16 deletions(-) create mode 100644 src/teaql/runtime/logging.py create mode 100644 tests/runtime/test_log_presentations.py create mode 100644 tests/runtime/test_runtime_logging.py diff --git a/src/teaql/runtime/__init__.py b/src/teaql/runtime/__init__.py index 02fd1530..5a17534e 100644 --- a/src/teaql/runtime/__init__.py +++ b/src/teaql/runtime/__init__.py @@ -8,6 +8,7 @@ Tools, ToolToken, ToolUnavailableError, ) from .module import RuntimeModule, DefaultEntityDataServiceBehavior +from .logging import RuntimeLogger, RuntimeLoggingError from .context_fix import ContextFix, ContextFixInput from .graph_session import GraphMutationSession, GraphCommittedError from .store import DataStore @@ -72,6 +73,7 @@ __all__ = ["WireFieldMetadata", "WireEntityMetadata", "NormalizedWireInput", "WireInputError", "create_wire_entity_metadata", "normalize_wire_input", "encode_wire_output", "retain_submitted_paths", "EntityKey", "EntityChangeSet", "EntityRoot", "ContextEntityRef", "ContextRootError", "CheckException", "CheckResult", "I18nCatalog", "JsonFieldNamingProfile", "Locale", "ObjectLocation", "UnsupportedLocaleError", "UserContext", "TeaqlRuntime", "SqlLogEntry", "SqlLogOperation", "DiagnosticSqlLogSink", "TextDiagnosticSqlLogSink", "ServiceRuntimeFromEnv", "RuntimeModule", "DataStore", "RawAuditEvent", "SafeAuditEvent", "MutationAuditKind", "BusinessClock", "FixedBusinessClock", "SystemBusinessClock", "InternalIdAllocator", "AeadEntityReferenceCodec", "EntityReferenceClaims", "EntityReferenceCodec", "EntityReferenceTokenError", "ENTITY_REFERENCE_AAD", "UNSAFE_RAW_ENTITY_REFERENCES_ACKNOWLEDGEMENT", "UNSAFE_RAW_ENTITY_REFERENCES_ENVIRONMENT", "BUSINESS_ID_PERMUTATION_V1_ALPHABET", "BUSINESS_ID_PERMUTATION_V1_DOMAIN_SIZE", "BUSINESS_ID_PERMUTATION_V1_MAX_SEQUENCE", "BUSINESS_ID_PERMUTATION_V1_WIDTH", "DefaultBusinessIdProfileFactory", "DefaultBusinessIdService", "InMemoryBusinessIdAllocator", "PermutedDailyBusinessIdProfile", "StaticBusinessIdKeyProvider", "encode_business_id_permutation_v1", "ContextTools", "ExecutableHttpTool", "HTTP_TOOL", "HttpIntentPhase", "HttpTool", "HttpToolProvider", "ToolDeniedError", "ToolError", "ToolPolicy", "ToolRisk", "Tools", "ToolToken", "ToolUnavailableError"] __all__ += [ + "RuntimeLogger", "RuntimeLoggingError", "CheckerMessageCatalog", "CheckerPresentationModel", "CheckerPresentation", "CheckerMessageOutput", "CheckerMessageRequest", "standard_checker_message_renderer", "EntityJSONError", "EntityJSONField", "EntityJSONSchema", diff --git a/src/teaql/runtime/context.py b/src/teaql/runtime/context.py index 8820ef76..82914eac 100644 --- a/src/teaql/runtime/context.py +++ b/src/teaql/runtime/context.py @@ -99,10 +99,14 @@ def invalidate(self, query_key: str) -> None: class UserContext: - def __init__(self): + def __init__(self, *, runtime_logger=None, log_name=None, model_names=()): + from .logging import RuntimeLogger, default_runtime_logger + self._runtime_logger = runtime_logger if runtime_logger is not None else ( + RuntimeLogger(log_name, model_names=model_names) + if log_name is not None or model_names else default_runtime_logger()) self._resources: Dict[str, Any] = {} self._resources["sql_log_options"] = SqlLogOptions.all() - self._resources["diagnostic_sql_log_sink"] = TextDiagnosticSqlLogSink() + self._resources["diagnostic_sql_log_sink"] = RuntimeDiagnosticSqlLogSink(self._runtime_logger) self._metadata: Optional[Any] = None self._user_identifier: str = "" self._entities: List[Any] = [] @@ -166,8 +170,8 @@ def last_fix_evidence(self): return tuple(self._fix_evidence_last) @classmethod - def new(cls) -> 'UserContext': - return cls() + def new(cls, **logging_configuration) -> 'UserContext': + return cls(**logging_configuration) def with_active_root(self, root: ContextEntityRef) -> 'UserContext': if not isinstance(root, ContextEntityRef): @@ -242,7 +246,7 @@ async def execute_graph_save(self, work, *, comment=None, prepare=None): # cleanup. It starts only after admission to the existing save gate; # generated entities do not initialize SDKs or create manual spans. return await observe_runtime_operation( - self._runtime_telemetry, RuntimeOperation('mutation', 'graph.save'), + self.operation_telemetry(), RuntimeOperation('mutation', 'graph.save'), lambda: self._execute_graph_transaction(work, intent, GraphMutationSession, prepare)) async def _execute_graph_transaction(self, work, intent, session_type, prepare=None): @@ -374,6 +378,11 @@ def set_runtime_telemetry(self, telemetry: RuntimeTelemetryInput) -> None: def runtime_telemetry(self) -> RuntimeTelemetryAdapter: return self._runtime_telemetry + def operation_telemetry(self): + """Observe local runtime operations without replacing the installed SPI.""" + from .logging import RuntimeLogTelemetry + return RuntimeLogTelemetry(self._runtime_telemetry, self._runtime_logger) + def set_id_set_store(self, store: Any) -> None: if store is None: raise ValueError("ID set store must not be None") @@ -1054,7 +1063,7 @@ async def send_audit_event(self, event: Any): async def _deliver_audit_event(self, event: Any, safe_event: Any): from .audit import deliver from .telemetry import RuntimeOperation, start_runtime_operation - scope = start_runtime_operation(self._runtime_telemetry, RuntimeOperation( + scope = start_runtime_operation(self.operation_telemetry(), RuntimeOperation( "audit", f"{event.entity}.audit", { "teaql.entity.type": event.entity, "teaql.mutation.kind": event.kind.value, @@ -1075,6 +1084,16 @@ async def _deliver_audit_event(self, event: Any, safe_event: Any): failures.append(error) if failures: raise failures[0] + try: + self._runtime_logger.write('INFO', 'audit.' + safe_event.kind.value, 'TeaQL audit event', + category='AUDIT', outcome='success', entity=safe_event.entity, + entity_id=str(safe_event.entity_id), + fields=[{'field': item.field, 'value': item.value, 'masked': item.masked, + 'truncated': item.truncated} for item in safe_event.fields], + trace_chain=[str(node) for node in safe_event.trace_chain]) + except Exception: + from .logging import _failure + _failure('log_write_failed', self._runtime_logger.log_name) scope.success() except BaseException as error: scope.failure(error) @@ -1250,6 +1269,7 @@ def _record_metadata_log(self, metadata: Any, *, intent_source=None, intent_valu parameter_log_policies=getattr(metadata, 'parameter_log_policies', None), sql_origin=getattr(metadata, 'sql_origin', None), execution_outcome=getattr(metadata, 'execution_outcome', None), + telemetry_correlation=correlation, started_at=started_at, ended_at=ended_at, elapsed=ended_at - started_at, @@ -1465,7 +1485,7 @@ def _observe_cache(self, name: str, operation: str, work: Callable, completion: from .telemetry import RuntimeOperation, observe_runtime_operation_sync return observe_runtime_operation_sync( - self.runtime_telemetry(), + self.operation_telemetry(), RuntimeOperation("cache", name, {"teaql.cache.operation": operation}), work, completion, @@ -1604,12 +1624,33 @@ class SqlLogEntry: execution_outcome: Optional[str] = None mutation_lineage: tuple[Any, ...] = () trace_chain: tuple[Any, ...] = () + telemetry_correlation: Any = field(default=None, repr=False, compare=False) class DiagnosticSqlLogSink: - """Policy-projected SQL destination; the text sink is installed by default.""" + """Policy-projected SQL destination; the structured runtime sink is the default.""" def write(self, entry: SqlLogEntry) -> None: raise NotImplementedError +class RuntimeDiagnosticSqlLogSink(DiagnosticSqlLogSink): + def __init__(self, logger): + self._logger = logger + + def write(self, entry: SqlLogEntry) -> None: + from .log_privacy import sql_log_projection + entry = sql_log_projection(entry) + outcome = entry.execution_outcome or 'success' + level = 'ERROR' if outcome in ('failure', 'error') else 'WARN' if outcome == 'retrying' else 'INFO' + identity = getattr(entry.telemetry_correlation, 'trace_id', None) + correlation_fields = {'trace_id': identity} if identity else {} + self._logger.write(level, 'sql.' + entry.operation.name.lower(), 'TeaQL SQL execution', + category='SQL', outcome=outcome, sql=entry.debug_sql, + log_mode=entry.log_mode, omission_reason=entry.omission_reason, + comment=entry.comment, purpose=entry.purpose, audit_reason=entry.audit_reason, + duration_ms=entry.elapsed.total_seconds() * 1000 if entry.elapsed else 0, + result_count=entry.result_count, affected_rows=entry.affected_rows, + trace_chain=[str(node) for node in entry.trace_chain], + trace_path=[str(node) for node in entry.trace_path], **correlation_fields) + class TextDiagnosticSqlLogSink(DiagnosticSqlLogSink): def __init__(self, writer=print): self._writer = writer diff --git a/src/teaql/runtime/logging.py b/src/teaql/runtime/logging.py new file mode 100644 index 00000000..baf2d15a --- /dev/null +++ b/src/teaql/runtime/logging.py @@ -0,0 +1,368 @@ +"""Application-owned structured runtime logging and shared file rotation. + +Call ``RuntimeLogger`` once during application composition and pass it to +request contexts. The implicit default is shared by contexts in the process. +Only already-projected diagnostic fields reach this destination. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import re +import stat +import sys +import threading +import time +from time import monotonic as _lock_clock +from typing import Mapping, Sequence +from urllib.parse import unquote, urlsplit + + +class RuntimeLoggingError(RuntimeError): + """A value-free failure to initialize a required logging destination.""" + + +_locks_guard = threading.Lock() +_locks: dict[str, threading.RLock] = {} +_default_guard = threading.Lock() +_defaults: dict[tuple, RuntimeLogger] = {} + + +def _failure(code: str, log_name: str = 'teaql') -> None: + try: + print(json.dumps({'timestamp': datetime.now(timezone.utc).isoformat(), 'level': 'ERROR', + 'log_name': log_name, 'runtime': 'python', 'event': 'logging.failure', 'message': 'Runtime logging failed', + 'error_code': code}, separators=(',', ':')), file=sys.stderr) + except Exception: + pass + + +def _name(explicit: str | None, models: Sequence[str], environment: Mapping[str, str]) -> str: + value = explicit if explicit is not None else environment.get('TEAQL_DOMAIN') or ( + models[0] if len(models) == 1 else 'teaql') + if (not isinstance(value, str) or not value or value in ('.', '..') or value[-1] in ' .' + or any(ord(c) < 32 or ord(c) == 127 or c in '<>:"/\\|?*' for c in value) + or re.fullmatch(r'(?i)(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])', value.split('.')[0])): + raise RuntimeLoggingError('invalid_log_name') + value.encode('utf-8', errors='strict') + return value + + +def _size(value: str) -> int: + matched = re.fullmatch(r'([0-9]+)\s*(K|KB|M|MB|G|GB)?', value.strip().upper()) + if not matched: + raise RuntimeLoggingError('invalid_log_max_size') + multiplier = {'K': 1024, 'KB': 1024, 'M': 1024 ** 2, 'MB': 1024 ** 2, + 'G': 1024 ** 3, 'GB': 1024 ** 3}.get(matched[2], 1) + result = int(matched[1]) * multiplier + if not 0 < result <= 2 ** 63 - 1: + raise RuntimeLoggingError('invalid_log_max_size') + return result + + +_event_fields = frozenset(('timestamp', 'level', 'log_name', 'runtime', 'event', 'message')) +_human_header = re.compile(r'^\d{4}-\d\d-\d\dT\S+(?:Z|\+00:00) \[TeaQL\]\[.*\]\[(INFO|WARN|ERROR)\] .+ runtime=\S+$') + + +def _human_controls(value: str) -> str: + # Escape controls even when JSON permits them literally (C1 and Unicode + # line separators). A payload can never create a header or terminal escape. + return ''.join('\\u%04x' % ord(c) if ord(c) < 32 or 127 <= ord(c) <= 159 + or c in '\u2028\u2029' else c for c in value) + + +def _human_scalar(value: str) -> str: + return _human_controls(value.replace('\\', '\\\\')) + + +def _human_record(record) -> str: + scalar = _human_scalar + lines = [f"{scalar(record['timestamp'])} [TeaQL][{scalar(record['log_name'])}]" + f"[{record['level']}] {scalar(record['event'])} runtime={scalar(record['runtime'])}", + ' ' + scalar(record['message'])] + for key in sorted(record.keys() - _event_fields): + value = record[key] + if key == 'sql' and isinstance(value, str): + lines.append(' sql:') + lines.extend(' ' + scalar(line) for line in value.split('\n')) + else: + # JSON detail values retain numbers, booleans, null and typed audit + # identities, rather than calling an arbitrary object's str(). + lines.append(' ' + scalar(key) + '=' + _human_controls(json.dumps(value, ensure_ascii=False, separators=(',', ':')))) + return '\n'.join(lines) + '\n' + + +class RuntimeLogger: + """A startup-initialized destination, independent of optional OTel SDKs. + + ``model_names`` contains names known by the application at initialization; + it is never inferred from a request or an entity type. + """ + + def __init__(self, log_name: str | None = None, *, model_names: Sequence[str] = (), + environment: Mapping[str, str] | None = None, working_directory=None, + log_format: str | None = None): + environment = os.environ if environment is None else environment + try: + self.log_name = _name(log_name, model_names, environment) + self.log_format = log_format if log_format is not None else environment.get('TEAQL_LOG_FORMAT', 'json') + if self.log_format not in ('json', 'human'): + raise RuntimeLoggingError('invalid_log_format') + self.max_size = _size(environment.get('TEAQL_LOG_MAX_SIZE', '50M')) + files = environment.get('TEAQL_LOG_MAX_FILES', '7') + if not re.fullmatch(r'[0-9]+', files) or int(files) > 2 ** 31 - 1: + raise RuntimeLoggingError('invalid_log_max_files') + self.max_files = int(files) + self.stream = None + endpoint = environment.get('TEAQL_LOG_ENDPOINT') or './logs/' + self.log_name + '.log' + if endpoint in ('stdout', '-', 'stderr'): + self.stream = 'stderr' if endpoint == 'stderr' else 'stdout' + self.path = None + self._lock = threading.RLock() + else: + if endpoint.startswith('file:'): + url = urlsplit(endpoint) + if url.netloc not in ('', 'localhost') or url.query or url.fragment: + raise RuntimeLoggingError('invalid_log_endpoint') + endpoint = unquote(url.path) + elif '://' in endpoint: + raise RuntimeLoggingError('invalid_log_endpoint') + if not endpoint: + raise RuntimeLoggingError('invalid_log_endpoint') + base = Path.cwd() if working_directory is None else Path(working_directory) + self.path = (base / endpoint).resolve() + self._lock_path = self.path.with_name(self.path.name + '.lock') + with _locks_guard: + self._lock = _locks.setdefault(str(self.path), threading.RLock()) + self._emit(self._record('INFO', 'runtime.start', 'TeaQL runtime started')) + except Exception as error: + code = str(error) if isinstance(error, RuntimeLoggingError) else 'log_destination_unavailable' + _failure(code, getattr(self, 'log_name', 'teaql')) + raise RuntimeLoggingError(code) from None + + def _record(self, level: str, event: str, message: str, fields=None): + record = dict(fields or {}) + record.update(timestamp=datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z'), + level=level, log_name=self.log_name, runtime='python', event=event, message=message) + return record + + def write(self, level: str, event: str, message: str, **safe_fields) -> bool: + if level not in ('INFO', 'WARN', 'ERROR'): + raise ValueError('invalid_log_level') + try: + self._emit(self._record(level, event, message, safe_fields)) + return True + except Exception: + _failure('log_write_failed', self.log_name) + return False + + @contextmanager + def _destination_lock(self): + # Exclusive creation coordinates threads and independent processes on + # every supported server platform, including other TeaQL runtimes. + # Never remove a lock owned by another writer. + with self._lock: + self.path.parent.mkdir(parents=True, exist_ok=True) + # Logging's lock timeout has its own clock reference. A business + # cache's clock adapter/mock must not be consumed by diagnostics. + deadline = _lock_clock() + 30 + while True: + try: + descriptor = os.open(self._lock_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + break + except FileExistsError: + if _lock_clock() >= deadline: + raise OSError('log_destination_locked') from None + time.sleep(0.005) + try: + yield + finally: + try: + os.close(descriptor) + finally: + self._lock_path.unlink() + + def _archives(self): + prefix = self.path.name + '.' + for file in self.path.parent.iterdir(): + suffix = file.name.removeprefix(prefix) if file.name.startswith(prefix) else '' + if re.fullmatch(r'[1-9][0-9]*', suffix): + # Numeric archive names are owned regular files. A directory + # or symlink at that name is an I/O failure, never movable data. + if not stat.S_ISREG(file.lstat().st_mode): + raise OSError('log_archive_not_file') + yield int(suffix), file + + def _rotate(self): + for number, file in sorted(self._archives(), reverse=True): + if number >= self.max_files: + file.unlink() + else: + file.replace(self.path.with_name(self.path.name + '.' + str(number + 1))) + if self.max_files: + self.path.replace(self.path.with_name(self.path.name + '.1')) + else: + self.path.unlink() + + def _emit(self, record): + encoded = json.dumps(record, ensure_ascii=False, separators=(',', ':'), allow_nan=False) + # Normalize through the same JSON event in both modes. Neither renderer + # gets execution bindings or unprojected audit/error values. + text = encoded + '\n' if self.log_format == 'json' else _human_record(json.loads(encoded)) + data = text.encode('utf-8') + if self.stream: + with self._lock: + target = sys.stderr if self.stream == 'stderr' else sys.stdout + target.write(data.decode('utf-8')) + target.flush() + return + with self._destination_lock(): + # Check before retention/rotation so an incompatible append leaves + # both the existing active file and its archives untouched. + self._check_presentation() + for number, archive in self._archives(): + if number > self.max_files: + archive.unlink() + try: + current = self.path.stat() + except FileNotFoundError: + current = None + if current is not None: + if not stat.S_ISREG(current.st_mode): + raise OSError('log_destination_not_file') + day = datetime.fromtimestamp(current.st_mtime, timezone.utc).date() + if current.st_size and (current.st_size + len(data) > self.max_size + or day != datetime.now(timezone.utc).date()): + self._rotate() + # Reopen under the shared lock: another writer may have rotated + # since this logger's preceding append. + descriptor = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + with os.fdopen(descriptor, 'ab', buffering=0) as output: + offset = 0 + while offset < len(data): + count = output.write(data[offset:]) + if not count: + raise OSError('incomplete_log_write') + offset += count + + def _check_presentation(self): + try: + current = self.path.stat() + except FileNotFoundError: + return + if not stat.S_ISREG(current.st_mode): + raise OSError('log_destination_not_file') + if not current.st_size: + return + with self.path.open('r', encoding='utf-8', errors='strict') as stream: + first = stream.readline() + if not first.endswith('\n'): + raise OSError('incompatible_log_format') + first = first[:-1] + if self.log_format == 'human' and _human_header.fullmatch(first): + return + if self.log_format == 'json': + try: + event = json.loads(first) + if (isinstance(event, dict) and _event_fields <= event.keys() + and all(isinstance(event[k], str) for k in _event_fields) + and event['level'] in ('INFO', 'WARN', 'ERROR')): + return + except (ValueError, TypeError): + pass + raise OSError('incompatible_log_format') + + +def default_runtime_logger() -> RuntimeLogger: + # Read only logging configuration; no credentials or other environment + # values are copied into this application-owned resource. + names = ('TEAQL_DOMAIN', 'TEAQL_LOG_ENDPOINT', 'TEAQL_LOG_MAX_SIZE', 'TEAQL_LOG_MAX_FILES', 'TEAQL_LOG_FORMAT') + environment = {name: os.environ[name] for name in names if name in os.environ} + key = (str(Path.cwd().resolve()), *[environment.get(name) for name in names]) + with _default_guard: + if key not in _defaults: + _defaults[key] = RuntimeLogger(environment=environment) + return _defaults[key] + + +def telemetry_for_context(context): + """Keep compatibility with lightweight application context adapters.""" + if context is None: + return None + local = getattr(context, 'operation_telemetry', None) + return local() if callable(local) else context.runtime_telemetry() + + +class RuntimeLogTelemetry: + """Local operation logging alongside the independently owned OTel adapter.""" + + def __init__(self, delegate, logger: RuntimeLogger): + self._delegate = delegate + self._logger = logger + + def __getattr__(self, name): + return getattr(self._delegate, name) + + def start(self, operation): + from .telemetry import NOOP_RUNTIME_TELEMETRY + try: + delegate = self._delegate.start(operation) + except BaseException: + delegate = NOOP_RUNTIME_TELEMETRY.start(operation) + return _LoggedScope(delegate, operation, self._logger) + + +class _LoggedScope: + def __init__(self, delegate, operation, logger): + self._delegate, self._operation, self._logger = delegate, operation, logger + self._ended = False + + def __getattr__(self, name): + return getattr(self._delegate, name) + + def _finish(self, outcome, error=None): + if self._ended: + return False + self._ended = True + try: + fields = {'category': self._operation.family.upper(), 'operation': self._operation.name, 'outcome': outcome} + level = 'INFO' + if error is not None: + from .telemetry import runtime_error_category + from .i18n import CheckException + from .mutation_policy import MutationPolicyError + from teaql.core.request_intent import RequestIntentError + category = ('validation' if isinstance(error, (CheckException, RequestIntentError)) + else 'authorization' if isinstance(error, MutationPolicyError) + else runtime_error_category(error)) + fields['error_code'] = category + level = 'WARN' if category in ('validation', 'authorization', 'conflict') else 'ERROR' + correlation = getattr(self._delegate, 'correlation', None) + trace_id = getattr(correlation, 'trace_id', None) + if trace_id: + fields['trace_id'] = trace_id + self._logger.write(level, 'operation.' + outcome, 'TeaQL operation ' + outcome, **fields) + except Exception: + _failure('log_write_failed') + return True + + def success(self, attributes=None): + if self._finish('success'): + self._delegate.success(attributes) + + def failure(self, error): + if self._finish('failure', error): + self._delegate.failure(error) + + def cancelled(self, attributes=None): + import asyncio + if self._finish('cancelled', asyncio.CancelledError()): + callback = getattr(self._delegate, 'cancelled', None) + if callback: + callback(attributes) + else: + self._delegate.failure(asyncio.CancelledError()) diff --git a/src/teaql/runtime/object_storage.py b/src/teaql/runtime/object_storage.py index c88492b6..99389e77 100644 --- a/src/teaql/runtime/object_storage.py +++ b/src/teaql/runtime/object_storage.py @@ -1,4 +1,5 @@ """Synchronous binary stream facade; async applications can use asyncio.to_thread.""" +from teaql.runtime.logging import telemetry_for_context from dataclasses import dataclass from typing import Protocol, Optional, BinaryIO, Callable from io import BytesIO @@ -39,7 +40,7 @@ class _Receipt: def __init__(self, invocation, operation): self.invocation, self.operation = invocation, operation self.started, self.ended = time.monotonic(), False - self.scope = start_runtime_operation(invocation.context.runtime_telemetry(), RuntimeOperation("object_storage", operation)) + self.scope = start_runtime_operation(telemetry_for_context(invocation.context), RuntimeOperation("object_storage", operation)) self.scope.activate() def detach(self): diff --git a/src/teaql/runtime/query_list.py b/src/teaql/runtime/query_list.py index 7aed4791..37e4fb5c 100644 --- a/src/teaql/runtime/query_list.py +++ b/src/teaql/runtime/query_list.py @@ -1,5 +1,6 @@ """Invocation-local list execution shared by generated libraries and providers.""" from __future__ import annotations +from teaql.runtime.logging import telemetry_for_context import asyncio import math @@ -31,7 +32,7 @@ async def observe_query_operation(context, service, request: QueryRequest, return await work() token = _query_owner.set(owner) try: - telemetry = context.runtime_telemetry() if context is not None else None + telemetry = telemetry_for_context(context) return await observe_runtime_operation( telemetry, RuntimeOperation('query', f'{request.root_request.query.entity}.list', { 'teaql.entity.type': request.root_request.query.entity, diff --git a/src/teaql/runtime/query_stream.py b/src/teaql/runtime/query_stream.py index 914e0c4f..d74207ca 100644 --- a/src/teaql/runtime/query_stream.py +++ b/src/teaql/runtime/query_stream.py @@ -1,4 +1,5 @@ """Lazy typed stream ownership and delivered-row accounting for generated Q.""" +from teaql.runtime.logging import telemetry_for_context import asyncio from contextvars import ContextVar @@ -48,7 +49,7 @@ def bind_scope(self, scope): def _activate(self): if self.scope is None: - self.scope = start_runtime_operation(self.context.runtime_telemetry(), RuntimeOperation( + self.scope = start_runtime_operation(telemetry_for_context(self.context), RuntimeOperation( 'query', self.request.query.entity + '.stream', {'teaql.entity.type': self.request.query.entity})) self.scopes.append(self.scope) else: diff --git a/src/teaql/sql/executor.py b/src/teaql/sql/executor.py index 5398d241..bd3981c2 100644 --- a/src/teaql/sql/executor.py +++ b/src/teaql/sql/executor.py @@ -1,3 +1,4 @@ +from teaql.runtime.logging import telemetry_for_context from abc import ABC, abstractmethod from typing import List, Dict, Any, Optional, AsyncIterator from copy import deepcopy @@ -476,7 +477,7 @@ async def _query_stream(self, context, request: QueryRequest, chunk_size: int): outcome = 'cancelled' from teaql.runtime.query_stream import stream_observation observation = stream_observation(context, self, request) - telemetry = context.runtime_telemetry() if context is not None else None + telemetry = telemetry_for_context(context) statement = start_runtime_operation(telemetry, RuntimeOperation('provider', f'{self.dialect.kind()}.stream', { 'teaql.provider.kind': str(self.dialect.kind()), 'teaql.provider.operation': 'query', 'teaql.provider.execution': 'statement'})) @@ -591,7 +592,7 @@ async def _query(self, context: 'UserContext', request: QueryRequest) -> QueryRe start = datetime.now() try: - telemetry = context.runtime_telemetry() if context is not None else None + telemetry = telemetry_for_context(context) statement = start_runtime_operation(telemetry, RuntimeOperation("provider", f"{self.dialect.kind()}.query", { "teaql.provider.kind": str(self.dialect.kind()), "teaql.provider.operation": "query", @@ -834,7 +835,7 @@ async def _enhance_relations(self, context, parents: List[Dict[str, Any]], reque if parent_desc is None: raise CompileError(SqlCompileError(f"unknown entity: {query.entity}")) for load in query.relations: - telemetry = context.runtime_telemetry() if context is not None else None + telemetry = telemetry_for_context(context) relation_scope = start_runtime_operation(telemetry, RuntimeOperation( "relation_load", f"{query.entity}.{load.name}", { "teaql.entity.type": query.entity, @@ -1030,7 +1031,7 @@ def check(data): elif not context.consume_mutation_checked(data): context.check_and_fix_mutation(data) check(request._data) - telemetry = context.runtime_telemetry() if context is not None else None + telemetry = telemetry_for_context(context) scope = ( context.mutation_policy_execution(request) if context is not None @@ -1169,7 +1170,7 @@ async def _mutate(self, context: 'UserContext', request: MutationRequest, privac operation = {'insert': DataServiceOperation.Insert, 'update': DataServiceOperation.Update, 'delete': DataServiceOperation.Delete, 'recover': DataServiceOperation.Recover}[op] try: - telemetry = context.runtime_telemetry() if context is not None else None + telemetry = telemetry_for_context(context) statement = start_runtime_operation(telemetry, RuntimeOperation("provider", f"{self.dialect.kind()}.mutation", { "teaql.provider.kind": str(self.dialect.kind()), "teaql.provider.operation": op, diff --git a/tests/runtime/test_log_presentations.py b/tests/runtime/test_log_presentations.py new file mode 100644 index 00000000..7535d5cd --- /dev/null +++ b/tests/runtime/test_log_presentations.py @@ -0,0 +1,298 @@ +"""Native acceptance of the two presentations, including whole-event files.""" +import concurrent.futures +from datetime import datetime, timedelta, timezone +import json +import os +from pathlib import Path +import re +import subprocess +import sys +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +from teaql.runtime import RuntimeLogger, RuntimeLoggingError, UserContext +from teaql.runtime.telemetry import RuntimeOperation, observe_runtime_operation + + +HEADER = re.compile(r'^(\S+) \[TeaQL\]\[(.*)\]\[(INFO|WARN|ERROR)\] (.*) runtime=(\S+)$') + + +def scalar(text): + return re.sub(r'\\(\\|u[0-9a-fA-F]{4})', + lambda match: '\\' if match[1] == '\\' else chr(int(match[1][1:], 16)), text) + + +def events(text, presentation): + if presentation == 'json': + # JSONL separates on LF, not on Unicode characters permitted in JSON strings. + return [json.loads(line) for line in text.split('\n')[:-1]] + output = [] + sql = None + for line in text.split('\n')[:-1]: + header = HEADER.fullmatch(line) + if header: + timestamp, name, level, event, runtime = header.groups() + assert datetime.fromisoformat(timestamp.replace('Z', '+00:00')).utcoffset() == timedelta(0) + output.append(dict(timestamp=timestamp, log_name=scalar(name), level=level, + event=scalar(event), runtime=scalar(runtime))) + sql = None + else: + assert output and line.startswith(' '), 'unindented human continuation: ' + repr(line) + row = output[-1] + if 'message' not in row: + row['message'] = scalar(line[2:]) + elif line == ' sql:': + row['sql'] = '' + sql = [] + elif line.startswith(' ') and sql is not None: + sql.append(scalar(line[4:])) + row['sql'] = '\n'.join(sql) + else: + key, value = line[2:].split('=', 1) + row[scalar(key)] = json.loads(value) + sql = None + assert not any(ord(c) < 32 or 127 <= ord(c) <= 159 or c in '\u2028\u2029' for c in line) + assert text.endswith('\n') and all('message' in row for row in output) + return output + + +def read(path, presentation): + return events(path.read_text(encoding='utf-8'), presentation) + + +@pytest.mark.parametrize('presentation', ['json', 'human']) +@pytest.mark.parametrize('explicit,domain,models,name', [ + ('application', 'domain', ['model'], 'application'), + (None, 'domain', ['model'], 'domain'), (None, None, ['model'], 'model'), + (None, None, [], 'teaql'), (None, None, ['one', 'two'], 'teaql'), +]) +def test_selection_paths_precedence_frozen_contexts_and_two_starts(tmp_path, presentation, explicit, domain, models, name): + env = {'TEAQL_LOG_FORMAT': presentation} + if domain: + env['TEAQL_DOMAIN'] = domain + logger = RuntimeLogger(explicit, model_names=models, environment=env, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + env['TEAQL_LOG_FORMAT'] = 'human' if presentation == 'json' else 'json' + env['TEAQL_DOMAIN'] = 'changed' + assert context._runtime_logger is logger + assert logger.log_format == presentation and logger.log_name == name + assert logger.write('INFO', 'frozen', 'Configuration is startup-owned') + RuntimeLogger(name, log_format=presentation, environment={}, working_directory=tmp_path) + path = tmp_path / ('logs/' + name + '.log') + assert [row['event'] for row in read(path, presentation)] == ['runtime.start', 'frozen', 'runtime.start'] + override = RuntimeLogger(name, log_format=presentation, + environment={'TEAQL_LOG_ENDPOINT': 'other/custom.log', 'TEAQL_LOG_FORMAT': 'invalid-unused'}, working_directory=tmp_path) + assert override.log_format == presentation + assert read(tmp_path / 'other/custom.log', presentation)[0]['log_name'] == name + + +def test_default_is_json(tmp_path): + logger = RuntimeLogger(environment={}, working_directory=tmp_path) + assert logger.log_format == 'json' + assert read(logger.path, 'json')[0]['event'] == 'runtime.start' + + +@pytest.mark.parametrize('presentation', ['json', 'human']) +def test_logging_does_not_consume_the_business_cache_clock(tmp_path, presentation): + context = UserContext.new(runtime_logger=RuntimeLogger(log_format=presentation, environment={}, working_directory=tmp_path)) + with patch('teaql.runtime.context.time.monotonic', side_effect=[100.0, 101.0]): + context.put_to_local_cache('ttl', 'temporary', 1) + assert context.get_from_local_cache('ttl') is None + + +@pytest.mark.parametrize('value', ['', 'debug', 'JSON', 'human\nFORMAT-SECRET']) +@pytest.mark.parametrize('setting', ['app', 'environment']) +def test_invalid_format_fails_without_echo(tmp_path, capsys, value, setting): + with pytest.raises(RuntimeLoggingError, match='invalid_log_format'): + RuntimeLogger(log_format=value if setting == 'app' else None, + environment={'TEAQL_LOG_FORMAT': value} if setting == 'environment' else {}, working_directory=tmp_path) + failure = json.loads(capsys.readouterr().err) + assert failure['level'] == 'ERROR' and failure['error_code'] == 'invalid_log_format' + assert 'FORMAT-SECRET' not in json.dumps(failure) and not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('presentation', ['json', 'human']) +@pytest.mark.parametrize('endpoint', ['stdout', 'stderr']) +def test_streams_share_projected_typed_events(tmp_path, capsys, presentation, endpoint): + logger = RuntimeLogger('应用', log_format=presentation, + environment={'TEAQL_LOG_ENDPOINT': endpoint}, working_directory=tmp_path) + fields = dict(category='AUDIT', trace_id='0123456789abcdef0123456789abcdef', outcome='retrying', + error_code='connection_timeout', entity_id=42, changes=[{'field': 'password', 'value': '***'}], + elapsed_us=12, result_count=0, omission_reason=None, sql='SELECT id\nFROM customer\n\x1b[31m\r\u0085\u2028header', + trace_chain=['root', 'child'], enabled=True) + message = 'Readable "SQL" \\u001b\nFORGED HEADER\x1b\r\u0085\u2029' + assert logger.write('WARN', 'unknown.kind', message, **fields) + capture = capsys.readouterr() + rows = events(capture.out if endpoint == 'stdout' else capture.err, presentation) + assert [row['level'] for row in rows] == ['INFO', 'WARN'] + assert rows[1] | {'timestamp': None} == dict(timestamp=None, level='WARN', log_name='应用', + runtime='python', event='unknown.kind', message=message, **fields) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('presentation', ['json', 'human']) +async def test_native_outcomes_and_projection_precede_rendering(monkeypatch, tmp_path, presentation): + from teaql.runtime.audit import RawAuditEvent, MutationAuditKind, AuditFieldChange + from teaql.runtime.mutation_policy import MutationPolicyError + from teaql.runtime.log_privacy import PLAINTEXT_ACK + logger = RuntimeLogger(log_format=presentation, environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + async def success(): + return 42 + assert await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), success) == 42 + for error in (MutationPolicyError('PRIVATE-POLICY-CANARY'), OSError('PRIVATE-DRIVER-CANARY')): + async def failure(): + raise error + with pytest.raises(type(error)) as caught: + await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), failure) + assert caught.value is error + for ack in ('', 'true', PLAINTEXT_ACK): + monkeypatch.setenv('TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS', ack) + secret = 'PASSWORD-RENDER-CANARY' + metadata = SimpleNamespace(operation='update', parameters=[secret], + parameterized_sql='UPDATE customer SET password = ?', debug_query=secret, + comment='change ' + secret, execution_outcome='failure', affected_rows=1, + _sql_correlation=SimpleNamespace(trace_id='0123456789abcdef0123456789abcdef')) + context.record_metadata_log(metadata) + audit = RawAuditEvent(MutationAuditKind.UPDATED, 'Customer', 42, + (AuditFieldChange('password', 'OLD-PASSWORD-CANARY', secret),), ('change ' + secret,)) + await context.send_audit_event(audit) + assert metadata.parameters == [secret] and audit.entity_id == 42 and audit.changes[0].new_value == secret + text = logger.path.read_text() + assert 'CANARY' not in text + rows = events(text, presentation) + assert [row['level'] for row in rows[:4]] == ['INFO', 'INFO', 'WARN', 'ERROR'] + sql = [row for row in rows if row.get('category') == 'SQL'] + audits = [row for row in rows if row['event'].startswith('audit.')] + assert len(sql) == 3 and all(row['trace_id'] == '0123456789abcdef0123456789abcdef' for row in sql) + assert len(audits) == 3 and all(row['entity_id'] == '42' for row in audits) + + +@pytest.mark.parametrize('presentation', ['json', 'human']) +def test_positive_archive_limit_keeps_numeric_newest_order(tmp_path, presentation): + logger = RuntimeLogger(log_format=presentation, + environment={'TEAQL_LOG_MAX_SIZE': '256', 'TEAQL_LOG_MAX_FILES': '2'}, working_directory=tmp_path) + for sequence in range(5): + assert logger.write('INFO', 'retention', '界' * 200, sequence=sequence, sql='SELECT\n' + str(sequence)) + for suffix, expected in [('', 4), ('.1', 3), ('.2', 2)]: + rows = read(Path(str(logger.path) + suffix), presentation) + assert len(rows) == 1 and rows[0]['sequence'] == expected + assert rows[0]['sql'] == 'SELECT\n' + str(expected) + assert sorted(p.name for p in logger.path.parent.iterdir()) == ['teaql.log', 'teaql.log.1', 'teaql.log.2'] + + +@pytest.mark.parametrize('presentation', ['json', 'human']) +@pytest.mark.parametrize('override', [False, True]) +def test_utf8_whole_events_day_restart_retention_and_oversize(tmp_path, presentation, override): + env = {'TEAQL_LOG_MAX_SIZE': '1K', 'TEAQL_LOG_MAX_FILES': '100'} + if override: + env['TEAQL_LOG_ENDPOINT'] = 'override/custom.log' + logger = RuntimeLogger(log_format=presentation, environment=env, working_directory=tmp_path) + for index in range(40): + assert logger.write('INFO', 'regular', '界' * 25, index=index, sql='SELECT id\nFROM customer') + paths = list(logger.path.parent.iterdir()) + assert len(paths) > 1 and all(0 < p.stat().st_size <= 1024 for p in paths) + rows = [row for p in paths for row in read(p, presentation)] + assert sorted(row['index'] for row in rows if row['event'] == 'regular') == list(range(40)) + assert all(row['sql'] == 'SELECT id\nFROM customer' for row in rows if row['event'] == 'regular') + assert logger.write('WARN', 'oversize', 'whole', sql='界' * 2000 + '\nNEXT LINE') + oversized = logger.path.read_bytes() + assert len(oversized) > 1024 and [r['event'] for r in read(logger.path, presentation)] == ['oversize'] + assert logger.write('INFO', 'after', 'next') + assert Path(str(logger.path) + '.1').read_bytes() == oversized + yesterday = (datetime.now(timezone.utc) - timedelta(days=2)).timestamp() + os.utime(logger.path, (yesterday, yesterday)) + assert logger.write('INFO', 'day', 'UTC rotation') + assert [r['event'] for r in read(Path(str(logger.path) + '.1'), presentation)] == ['after'] + os.utime(logger.path, (yesterday, yesterday)) + restarted = RuntimeLogger(log_format=presentation, environment=env, working_directory=tmp_path) + assert [r['event'] for r in read(restarted.path, presentation)] == ['runtime.start'] + assert [r['event'] for r in read(Path(str(logger.path) + '.1'), presentation)] == ['day'] + zero = RuntimeLogger(log_format=presentation, environment={**env, 'TEAQL_LOG_MAX_FILES': '0'}, working_directory=tmp_path) + assert zero.write('INFO', 'last', '界' * 2000) + assert list(zero.path.parent.iterdir()) == [zero.path] + assert [r['event'] for r in read(zero.path, presentation)] == ['last'] + + +@pytest.mark.parametrize('presentation', ['json', 'human']) +def test_threads_keep_multiline_blocks_whole(tmp_path, presentation): + loggers = [RuntimeLogger(log_format=presentation, + environment={'TEAQL_LOG_MAX_SIZE': '2K', 'TEAQL_LOG_MAX_FILES': '100'}, working_directory=tmp_path) for _ in range(4)] + def write(index): + assert loggers[index % 4].write('INFO', 'parallel', '多线程', index=index, sql='SELECT\n' + str(index)) + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(write, range(100))) + rows = [row for p in loggers[0].path.parent.iterdir() for row in read(p, presentation)] + assert sorted(row['index'] for row in rows if row['event'] == 'parallel') == list(range(100)) + assert all(row['sql'] == 'SELECT\n' + str(row['index']) for row in rows if row['event'] == 'parallel') + + +@pytest.mark.parametrize('presentation', ['json', 'human']) +def test_processes_and_subsequent_start_keep_blocks_whole(tmp_path, presentation): + script = """from teaql.runtime import RuntimeLogger +import sys +logger=RuntimeLogger(log_format=sys.argv[2],environment={'TEAQL_LOG_MAX_SIZE':'2K','TEAQL_LOG_MAX_FILES':'100'}) +for index in range(30): + assert logger.write('INFO','process.record','原生并发',worker=int(sys.argv[1]),index=index,sql='SELECT\\n'+str(index)) +""" + env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ') if key in os.environ} + env.update(PYTHONDONTWRITEBYTECODE='1', PYTHONPATH=str(Path(__file__).resolve().parents[2] / 'src')) + children = [] + try: + for worker in range(4): + children.append(subprocess.Popen([sys.executable, '-B', '-c', script, str(worker), presentation], + cwd=tmp_path, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)) + for child in children: + _, error = child.communicate(timeout=30) + assert child.returncode == 0, error.decode() + subprocess.run([sys.executable, '-B', '-c', script, '4', presentation], cwd=tmp_path, + env=env, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30) + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait() + rows = [row for p in (tmp_path / 'logs').iterdir() for row in read(p, presentation)] + assert sum(row['event'] == 'runtime.start' for row in rows) == 5 + assert sorted((r['worker'], r['index']) for r in rows if r['event'] == 'process.record') == [ + (worker, index) for worker in range(5) for index in range(30)] + assert all(r['sql'] == 'SELECT\n' + str(r['index']) for r in rows if r['event'] == 'process.record') + + +@pytest.mark.asyncio +@pytest.mark.parametrize('presentation', ['json', 'human']) +async def test_mixed_format_and_io_failures_preserve_files_and_business(tmp_path, capsys, presentation): + logger = RuntimeLogger(log_format=presentation, environment={}, working_directory=tmp_path) + other = 'human' if presentation == 'json' else 'json' + archive = Path(str(logger.path) + '.10') + archive.write_bytes(b'preserve archived bytes') + before = {p.name: p.read_bytes() for p in logger.path.parent.iterdir()} + with pytest.raises(RuntimeLoggingError): + RuntimeLogger(log_format=other, environment={'TEAQL_LOG_MAX_SIZE': '1', 'TEAQL_LOG_MAX_FILES': '0'}, working_directory=tmp_path) + assert {p.name: p.read_bytes() for p in logger.path.parent.iterdir()} == before + replacement = RuntimeLogger(log_format=other, environment={}, working_directory=tmp_path / 'replacement') + logger.path.write_bytes(replacement.path.read_bytes()) + before = {p.name: p.read_bytes() for p in logger.path.parent.iterdir()} + context = UserContext.new(runtime_logger=logger) + async def success(): + return 42 + assert await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), success) == 42 + original = OSError('SECRET-BUSINESS-ERROR') + async def failure(): + raise original + with pytest.raises(OSError) as caught: + await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), failure) + assert caught.value is original + assert {p.name: p.read_bytes() for p in logger.path.parent.iterdir()} == before + logger.path.unlink() + logger.path.mkdir() + assert not logger.write('ERROR', 'later', 'later I/O failure') + blocked = tmp_path / 'SECRET-PATH' + blocked.write_text('file') + with pytest.raises(RuntimeLoggingError): + RuntimeLogger(log_format=presentation, environment={'TEAQL_LOG_ENDPOINT': str(blocked / 'file')}) + failures = capsys.readouterr().err + assert 'SECRET' not in failures and all(json.loads(line)['level'] == 'ERROR' for line in failures.splitlines()) diff --git a/tests/runtime/test_runtime_logging.py b/tests/runtime/test_runtime_logging.py new file mode 100644 index 00000000..4b474f7f --- /dev/null +++ b/tests/runtime/test_runtime_logging.py @@ -0,0 +1,304 @@ +import concurrent.futures +from datetime import datetime, timedelta, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +from types import SimpleNamespace + +import pytest + +from teaql.runtime import RuntimeLogger, RuntimeLoggingError, UserContext +from teaql.runtime.telemetry import RuntimeOperation, observe_runtime_operation + + +def records(path): + return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] + + +def test_default_startup_and_request_context_share_destination(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + for name in ('TEAQL_DOMAIN', 'TEAQL_LOG_ENDPOINT', 'TEAQL_LOG_MAX_SIZE', 'TEAQL_LOG_MAX_FILES'): + monkeypatch.delenv(name, raising=False) + first = UserContext.new() + path = tmp_path / 'logs/teaql.log' + assert path.exists() + second = UserContext.new() + assert first._runtime_logger is second._runtime_logger + assert [row['event'] for row in records(path)] == ['runtime.start'] + row = records(path)[0] + assert row['level'] == 'INFO' and row['runtime'] == 'python' and row['log_name'] == 'teaql' + assert datetime.fromisoformat(row['timestamp'].replace('Z', '+00:00')).utcoffset() == timedelta(0) + + +@pytest.mark.parametrize('explicit,domain,models,expected', [ + ('application', 'domain', ('model',), 'application'), + (None, 'domain', ('model',), 'domain'), + (None, None, ('model',), 'model'), + (None, None, (), 'teaql'), + (None, None, ('one', 'two'), 'teaql'), + ('应用日志', None, (), '应用日志'), +]) +def test_name_precedence_and_override(tmp_path, explicit, domain, models, expected): + environment = {'TEAQL_LOG_ENDPOINT': 'different/custom.log'} + if domain is not None: + environment['TEAQL_DOMAIN'] = domain + logger = RuntimeLogger(explicit, model_names=models, environment=environment, working_directory=tmp_path) + assert logger.log_name == expected + assert records(tmp_path / 'different/custom.log')[0]['log_name'] == expected + assert not (tmp_path / 'logs').exists() + + +@pytest.mark.parametrize('name', ['', '.', '..', '../private', 'a/b', 'a\\b', 'a\nSECRET', + 'x:y', 'tail.', 'tail ', 'CON', 'nul.txt', 'LPT1', 'a?b']) +def test_invalid_filename_segment_fails_without_echo(tmp_path, capsys, name): + with pytest.raises(RuntimeLoggingError, match='invalid_log_name'): + RuntimeLogger(name, environment={}, working_directory=tmp_path) + row = json.loads(capsys.readouterr().err) + assert row['level'] == 'ERROR' and row['error_code'] == 'invalid_log_name' + assert 'SECRET' not in json.dumps(row) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('suffix,size', [('1', 1), ('2K', 2048), ('2KB', 2048), + ('3m', 3 * 1024 ** 2), ('1GB', 1024 ** 3)]) +def test_binary_size_suffixes(tmp_path, suffix, size): + logger = RuntimeLogger(environment={'TEAQL_LOG_MAX_SIZE': suffix}, working_directory=tmp_path) + assert logger.max_size == size + + +@pytest.mark.parametrize('environment', [ + {'TEAQL_LOG_MAX_SIZE': '0'}, {'TEAQL_LOG_MAX_SIZE': '-1'}, {'TEAQL_LOG_MAX_SIZE': 'wat'}, + {'TEAQL_LOG_MAX_FILES': '-1'}, {'TEAQL_LOG_MAX_FILES': '1.5'}, +]) +def test_invalid_rotation_configuration_fails_startup(tmp_path, environment): + with pytest.raises(RuntimeLoggingError): + RuntimeLogger(environment=environment, working_directory=tmp_path) + + +def test_stdout_is_structured_and_retains_application_name(tmp_path, capsys): + logger = RuntimeLogger('app', environment={'TEAQL_LOG_ENDPOINT': 'stdout'}, working_directory=tmp_path) + logger.write('WARN', 'sql.retry', 'Retry scheduled', category='SQL', outcome='retrying') + output = [json.loads(line) for line in capsys.readouterr().out.splitlines()] + assert [row['level'] for row in output] == ['INFO', 'WARN'] + assert all(row['log_name'] == 'app' for row in output) + assert not list(tmp_path.iterdir()) + + +def test_size_rotation_utf8_oversized_line_order_and_zero_retention(tmp_path): + logger = RuntimeLogger('size', environment={'TEAQL_LOG_MAX_SIZE': '400', 'TEAQL_LOG_MAX_FILES': '2'}, + working_directory=tmp_path) + logger.write('INFO', 'large', '中' * 300 + '\ninside record') + path = tmp_path / 'logs/size.log' + assert path.stat().st_size > 400 + assert len(records(path)) == 1 and records(path)[0]['event'] == 'large' + logger.write('INFO', 'after', 'After oversized record') + assert records(path)[0]['event'] == 'after' + assert records(Path(str(path) + '.1'))[0]['event'] == 'large' + assert records(Path(str(path) + '.2'))[0]['event'] == 'runtime.start' + for index in range(10): + logger.write('INFO', 'many', 'x' * 300, index=index) + assert not Path(str(path) + '.3').exists() + no_archives = RuntimeLogger('size', environment={'TEAQL_LOG_MAX_SIZE': '400', 'TEAQL_LOG_MAX_FILES': '0'}, + working_directory=tmp_path) + no_archives.write('INFO', 'last', 'x' * 500) + assert len(records(path)) == 1 and records(path)[0]['event'] == 'last' + assert not Path(str(path) + '.1').exists() and not Path(str(path) + '.2').exists() + + +def test_utc_day_change_and_restart_check_existing_file(tmp_path): + first = RuntimeLogger('day', environment={}, working_directory=tmp_path) + first.write('INFO', 'before', 'Before rotation') + path = tmp_path / 'logs/day.log' + yesterday = (datetime.now(timezone.utc) - timedelta(days=2)).timestamp() + os.utime(path, (yesterday, yesterday)) + first.write('INFO', 'after', 'After UTC date change') + assert [row['event'] for row in records(Path(str(path) + '.1'))] == ['runtime.start', 'before'] + assert [row['event'] for row in records(path)] == ['after'] + os.utime(path, (yesterday, yesterday)) + RuntimeLogger('day', environment={}, working_directory=tmp_path) + assert [row['event'] for row in records(path)] == ['runtime.start'] + assert [row['event'] for row in records(Path(str(path) + '.1'))] == ['after'] + assert [row['event'] for row in records(Path(str(path) + '.2'))] == ['runtime.start', 'before'] + + +def test_regular_utf8_records_rotate_at_whole_line_byte_limit(tmp_path): + logger = RuntimeLogger(environment={'TEAQL_LOG_MAX_SIZE': '1K', 'TEAQL_LOG_MAX_FILES': '1000'}, + working_directory=tmp_path) + for index in range(40): + assert logger.write('INFO', 'regular', '界' * 30, index=index) + files = list((tmp_path / 'logs').iterdir()) + assert len(files) > 1 + assert all(0 < file.stat().st_size <= 1024 for file in files) + output = [row for file in files for row in records(file)] + assert len(output) == 41 + assert sorted(row['index'] for row in output if row['event'] == 'regular') == list(range(40)) + + +@pytest.mark.asyncio +async def test_rotation_failure_preserves_business_and_foreign_archive_directory(tmp_path, capsys): + logger = RuntimeLogger(environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + path = tmp_path / 'logs/teaql.log' + before = path.read_bytes() + archive = Path(str(path) + '.1') + archive.mkdir() + (archive / 'marker').write_text('preserve') + yesterday = (datetime.now(timezone.utc) - timedelta(days=2)).timestamp() + os.utime(path, (yesterday, yesterday)) + async def work(): + return 42 + assert await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), work) == 42 + original = OSError('private-original-error') + async def failure(): + raise original + with pytest.raises(OSError) as caught: + await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), failure) + assert caught.value is original + assert not logger.write('INFO', 'probe', 'Completed') + assert path.read_bytes() == before and (archive / 'marker').read_text() == 'preserve' + errors = [json.loads(line) for line in capsys.readouterr().err.splitlines()] + assert all(row['level'] == 'ERROR' and row['error_code'] == 'log_write_failed' for row in errors) + assert len(errors) >= 3 + + +@pytest.mark.asyncio +async def test_native_rule_rejections_are_warnings_and_keep_original_errors(tmp_path): + from teaql.runtime.i18n import CheckException + from teaql.runtime.mutation_policy import MutationPolicyError + from teaql.core.request_intent import RequestIntentError + logger = RuntimeLogger(environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + for error in (CheckException([]), RequestIntentError('QUERY_PURPOSE_REQUIRED', 'purpose', 'query'), + MutationPolicyError('private-policy-value')): + async def failure(): + raise error + with pytest.raises(type(error)) as caught: + await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), failure) + assert caught.value is error + output = records(tmp_path / 'logs/teaql.log') + assert [row['level'] for row in output] == ['INFO', 'WARN', 'WARN', 'WARN'] + assert 'private-policy-value' not in json.dumps(output) + + +def test_initial_io_failure_is_fatal_and_value_free(tmp_path, capsys): + parent = tmp_path / 'PATH-CONTAINING-CANARY' + parent.write_text('not a directory') + with pytest.raises(RuntimeLoggingError, match='log_destination_unavailable'): + RuntimeLogger(environment={'TEAQL_LOG_ENDPOINT': str(parent / 'file')}) + output = capsys.readouterr().err + assert json.loads(output)['level'] == 'ERROR' + assert 'PATH-CONTAINING-CANARY' not in output + + +@pytest.mark.asyncio +async def test_post_startup_io_failure_does_not_change_business_result(tmp_path, capsys): + logger = RuntimeLogger('io', environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + path = tmp_path / 'logs/io.log' + path.unlink() + path.mkdir() + async def work(): + return 42 + result = await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), work) + assert result == 42 and path.is_dir() + errors = [json.loads(line) for line in capsys.readouterr().err.splitlines() if line.startswith('{')] + assert errors[-1]['error_code'] == 'log_write_failed' + + +@pytest.mark.asyncio +async def test_native_operation_severity_and_failure_redaction(tmp_path): + logger = RuntimeLogger('operations', environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + async def success(): + return 7 + assert await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('query', 'probe'), success) == 7 + for error in [ValueError('VALIDATION-CREDENTIAL-CANARY'), OSError('DRIVER-CREDENTIAL-CANARY')]: + async def failure(): + raise error + with pytest.raises(type(error)) as caught: + await observe_runtime_operation(context.operation_telemetry(), RuntimeOperation('provider', 'probe'), failure) + assert caught.value is error + output = records(tmp_path / 'logs/operations.log') + assert [row['level'] for row in output] == ['INFO', 'INFO', 'WARN', 'ERROR'] + assert 'CREDENTIAL-CANARY' not in json.dumps(output) + + +def test_concurrent_threads_share_rotation_lock(tmp_path): + loggers = [RuntimeLogger('threads', environment={'TEAQL_LOG_MAX_SIZE': '2K', 'TEAQL_LOG_MAX_FILES': '100'}, + working_directory=tmp_path) for _ in range(4)] + def write(index): + assert loggers[index % 4].write('INFO', 'parallel', '多线程', index=index) + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(write, range(100))) + output = [row for path in (tmp_path / 'logs').iterdir() if not path.name.endswith('.lock') for row in records(path)] + assert sorted(row['index'] for row in output if row['event'] == 'parallel') == list(range(100)) + + +def test_native_processes_append_across_two_starts_and_concurrent_rotation(tmp_path): + script = """from teaql.runtime import RuntimeLogger +import sys +logger=RuntimeLogger('processes',environment={'TEAQL_LOG_MAX_SIZE':'2K','TEAQL_LOG_MAX_FILES':'100'}) +for index in range(30): + assert logger.write('INFO','process.record','原生并发',worker=int(sys.argv[1]),index=index) +""" + environment = {name: os.environ[name] for name in ('PATH', 'HOME', 'LANG', 'LC_ALL', 'TZ') if name in os.environ} + environment.update(PYTHONDONTWRITEBYTECODE='1', PYTHONPATH=str(Path(__file__).resolve().parents[2] / 'src')) + children = [] + try: + for worker in range(4): + children.append(subprocess.Popen([sys.executable, '-B', '-c', script, str(worker)], cwd=tmp_path, + env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE)) + for child in children: + _, error = child.communicate(timeout=30) + assert child.returncode == 0, error.decode() + # A subsequent native start must append to the same active destination. + subprocess.run([sys.executable, '-B', '-c', script, '4'], cwd=tmp_path, env=environment, + check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30) + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait() + output = [row for path in (tmp_path / 'logs').iterdir() if not path.name.endswith('.lock') for row in records(path)] + assert sum(row['event'] == 'runtime.start' for row in output) == 5 + assert sorted((row['worker'], row['index']) for row in output if row['event'] == 'process.record') == [ + (worker, index) for worker in range(5) for index in range(30)] + + +@pytest.mark.asyncio +async def test_default_sql_and_audit_file_projects_before_serialization(monkeypatch, tmp_path): + from teaql.runtime.audit import RawAuditEvent, MutationAuditKind, AuditFieldChange + monkeypatch.delenv('TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS', raising=False) + logger = RuntimeLogger(environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + secret = 'UNIQUE-LOG-PASSWORD-CANARY' + metadata = SimpleNamespace(operation='update', parameters=[secret], + parameterized_sql='UPDATE customer SET password = ?', debug_query=secret, + comment='change ' + secret, execution_outcome='failure', affected_rows=1) + context.record_metadata_log(metadata) + event = RawAuditEvent(MutationAuditKind.UPDATED, 'Customer', 42, + (AuditFieldChange('password', 'OLD-PASSWORD-CANARY', secret),), + ('change target 42 ' + secret,)) + await context.send_audit_event(event) + path = tmp_path / 'logs/teaql.log' + output = records(path) + assert any(row.get('category') == 'SQL' and row['level'] == 'ERROR' for row in output) + audit = next(row for row in output if row.get('category') == 'AUDIT') + assert audit['level'] == 'INFO' and audit['entity_id'] == '42' + text = path.read_text() + assert secret not in text and 'OLD-PASSWORD-CANARY' not in text + assert metadata.parameters == [secret] and event.entity_id == 42 + assert event.changes[0].new_value == secret + + +def test_default_sql_file_keeps_available_trace_correlation(tmp_path): + logger = RuntimeLogger(environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + trace_id = '0123456789abcdef0123456789abcdef' + context.record_metadata_log(SimpleNamespace(operation='select', parameters=[], + parameterized_sql='SELECT id FROM customer', debug_query='SELECT id FROM customer', + execution_outcome='success', _sql_correlation=SimpleNamespace(trace_id=trace_id))) + record = next(row for row in records(tmp_path / 'logs/teaql.log') if row.get('category') == 'SQL') + assert record['trace_id'] == trace_id From a16644721485cafafd05349320fcccf9e026f767 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Wed, 18 Nov 2026 15:16:03 +0800 Subject: [PATCH 2/6] chore(release): prepare 0.6.0 runtime logging release Refs https://github.com/teaql/teaql-python/issues/73 Coordinated release: https://github.com/teaql/teaql-conformance/issues/248 Signed-off-by: Philip Z --- .github/workflows/example-gate.yml | 11 +++++++++++ docs/releases/0.6.0.md | 22 ++++++++++++++++++++++ pyproject.toml | 2 +- 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 docs/releases/0.6.0.md diff --git a/.github/workflows/example-gate.yml b/.github/workflows/example-gate.yml index c44661b1..c8b9355b 100644 --- a/.github/workflows/example-gate.yml +++ b/.github/workflows/example-gate.yml @@ -8,6 +8,7 @@ jobs: examples: runs-on: ubuntu-latest env: + TEAQL_EXAMPLES_EVIDENCE_DIR: ${{ runner.temp }}/teaql-python-examples-evidence TEAQL_S3_ENDPOINT: http://127.0.0.1:19010 TEAQL_S3_BUCKET: teaql-python-example-ci TEAQL_S3_ACCESS_KEY: teaql-python-example-ci @@ -42,6 +43,16 @@ jobs: docker logs teaql-python-example-s3 exit 1 - run: ./scripts/verify-examples.sh + - name: Retain compact example diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: python-example-evidence + path: | + ${{ runner.temp }}/teaql-python-examples-evidence/ + logs/*.log + if-no-files-found: warn + retention-days: 7 - name: Stop dedicated S3 example fixture if: always() run: docker rm -f teaql-python-example-s3 || true diff --git a/docs/releases/0.6.0.md b/docs/releases/0.6.0.md new file mode 100644 index 00000000..bc3ebcc7 --- /dev/null +++ b/docs/releases/0.6.0.md @@ -0,0 +1,22 @@ +# 0.6.0: JSON and human runtime logging + +Both `json` and `human` logging presentations are supported. JSON remains the +default. Select the presentation when composing the runtime logger; an explicit +application option takes precedence over the server `TEAQL_LOG_FORMAT` setting. +The exact accepted values are `json` and `human`. + +Both presentations use the same privacy-safe event projection. Human SQL is +readable and indented across multiple lines. File output preserves severity, +UTF-8 whole-event rotation, UTC-day rollover, retention and concurrent writers. +A non-empty file using the other presentation is rejected before archive changes. +Plaintext SQL acknowledgement and existing privacy controls retain their meaning. + +Choose a fresh destination when changing an existing file's presentation. Existing +generated APIs do not require regeneration for this logging feature. + + +Tracking: https://github.com/teaql/teaql-python/issues/73; coordinated release https://github.com/teaql/teaql-conformance/issues/248. + +Release status and the source, internal-artifact and public-delivery gates are +recorded separately in teaql/teaql-conformance, +`evidence/2026-11-18-logging-release`. These notes do not establish publication. diff --git a/pyproject.toml b/pyproject.toml index 1ee66645..8f41240b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "teaql" -version = "0.5.0" +version = "0.6.0" description = "TeaQL Runtime and Data Service for Python" readme = "README.md" requires-python = ">=3.10" From cfdbad67b7939f85d44122994a80c4e0f67474f6 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Wed, 18 Nov 2026 15:21:56 +0800 Subject: [PATCH 3/6] ci: set evidence paths in the example verification step Refs https://github.com/teaql/teaql-python/issues/73 Signed-off-by: Philip Z --- .github/workflows/example-gate.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/example-gate.yml b/.github/workflows/example-gate.yml index c8b9355b..28742bf5 100644 --- a/.github/workflows/example-gate.yml +++ b/.github/workflows/example-gate.yml @@ -8,7 +8,6 @@ jobs: examples: runs-on: ubuntu-latest env: - TEAQL_EXAMPLES_EVIDENCE_DIR: ${{ runner.temp }}/teaql-python-examples-evidence TEAQL_S3_ENDPOINT: http://127.0.0.1:19010 TEAQL_S3_BUCKET: teaql-python-example-ci TEAQL_S3_ACCESS_KEY: teaql-python-example-ci @@ -42,7 +41,10 @@ jobs: done docker logs teaql-python-example-s3 exit 1 - - run: ./scripts/verify-examples.sh + - name: Verify all retained examples + run: ./scripts/verify-examples.sh + env: + TEAQL_EXAMPLES_EVIDENCE_DIR: ${{ runner.temp }}/teaql-python-examples-evidence - name: Retain compact example diagnostics if: always() uses: actions/upload-artifact@v4 From 7d1dd66bdb7bce9f428d2307d835f29b1d601353 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Wed, 18 Nov 2026 15:32:32 +0800 Subject: [PATCH 4/6] test(logging): verify retained examples through supported presentations Retain the intent, audit, masking and idempotence assertions while observing the new structured destination. Refs https://github.com/teaql/teaql-python/issues/73 Signed-off-by: Philip Z --- examples/conformance/test_sql_log_intent.py | 13 +++++---- .../order-management/test_sql_log_intent.py | 17 +++++++----- .../school-management/test_sql_log_intent.py | 13 +++++---- examples/task_board/test_task_board.py | 27 ++++++++++--------- 4 files changed, 41 insertions(+), 29 deletions(-) diff --git a/examples/conformance/test_sql_log_intent.py b/examples/conformance/test_sql_log_intent.py index f8ffd94a..7cfa670b 100644 --- a/examples/conformance/test_sql_log_intent.py +++ b/examples/conformance/test_sql_log_intent.py @@ -1,4 +1,5 @@ """Verify generated query intent survives execution in the conformance app.""" +import json import os from pathlib import Path import subprocess @@ -12,6 +13,8 @@ def test_generated_queries_retain_intent_at_sql_sink(self): repo = Path(__file__).resolve().parents[2] env = dict(os.environ) env.pop("TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS", None) + env.pop("TEAQL_LOG_FORMAT", None) + env["TEAQL_LOG_ENDPOINT"] = "stdout" env["PYTHONPATH"] = os.pathsep.join((str(repo / "examples" / "conformance"), str(repo / "src"))) with tempfile.TemporaryDirectory(prefix="teaql-conformance-log-test-") as directory: env["TEAQL_CONFORMANCE_DB"] = str(Path(directory) / "conformance.sqlite") @@ -20,12 +23,12 @@ def test_generated_queries_retain_intent_at_sql_sink(self): output = result.stdout + result.stderr self.assertEqual(0, result.returncode, output) generated_flow = output.split("PASS Mutation ledger identity", 1)[-1] - queries = [line for line in generated_flow.splitlines() - if line.startswith("[TeaQL SQL]") and "[select]" in line] + records = [json.loads(line) for line in generated_flow.splitlines() if line.startswith("{")] + queries = [row for row in records if row.get("event") == "sql.select"] self.assertGreater(len(queries), 0, output) - for line in queries: - self.assertNotIn("comment=None", line) - self.assertNotIn("purpose=None", line) + for row in queries: + self.assertTrue(row.get("comment") and row["comment"].strip(), row) + self.assertTrue(row.get("purpose") and row["purpose"].strip(), row) self.assertIn("PASS Python minimum runtime conformance: 8/8", output) diff --git a/examples/order-management/test_sql_log_intent.py b/examples/order-management/test_sql_log_intent.py index b5f9ed95..0eefaefc 100644 --- a/examples/order-management/test_sql_log_intent.py +++ b/examples/order-management/test_sql_log_intent.py @@ -1,4 +1,5 @@ """Check the regenerated order library's SQL intent through its real app.""" +import json import os from pathlib import Path import subprocess @@ -12,6 +13,8 @@ def test_generated_queries_retain_intent_at_sql_sink(self): repo = Path(__file__).resolve().parents[2] env = dict(os.environ) env.pop("TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS", None) + env.pop("TEAQL_LOG_FORMAT", None) + env["TEAQL_LOG_ENDPOINT"] = "stdout" env["PYTHONPATH"] = os.pathsep.join((str(repo / "examples" / "order-management" / "python-lib-core"), str(repo / "src"))) with tempfile.TemporaryDirectory(prefix="teaql-order-log-test-") as directory: env["TEAQL_ORDER_MANAGEMENT_DB"] = str(Path(directory) / "order.sqlite") @@ -19,15 +22,15 @@ def test_generated_queries_retain_intent_at_sql_sink(self): cwd=repo, env=env, capture_output=True, text=True, timeout=90) output = result.stdout + result.stderr self.assertEqual(0, result.returncode, output) - queries = [line for line in output.splitlines() - if line.startswith("[TeaQL SQL]") and "[select]" in line] + records = [json.loads(line) for line in output.splitlines() if line.startswith("{")] + queries = [row for row in records if row.get("event") == "sql.select"] self.assertGreater(len(queries), 0, output) - for line in queries: - self.assertNotIn("comment=None", line) - self.assertNotIn("purpose=None", line) + for row in queries: + self.assertTrue(row.get("comment") and row["comment"].strip(), row) + self.assertTrue(row.get("purpose") and row["purpose"].strip(), row) self.assertNotIn("masked-in-quick-start", output) - customer_sql = next((line for line in output.splitlines() - if "INSERT INTO customer_data" in line), "") + customer_sql = next((row.get("sql", "") for row in records + if "INSERT INTO customer_data" in row.get("sql", "")), "") self.assertIn("/* masked */", customer_sql) self.assertIn("'Acme Retail'", customer_sql) self.assertIn("[schema] ensured 7 generated entity tables", output) diff --git a/examples/school-management/test_sql_log_intent.py b/examples/school-management/test_sql_log_intent.py index 2db1a09c..206ad0b8 100644 --- a/examples/school-management/test_sql_log_intent.py +++ b/examples/school-management/test_sql_log_intent.py @@ -1,4 +1,5 @@ """Exercise the regenerated School library through its real application flow.""" +import json import os from pathlib import Path import subprocess @@ -12,6 +13,8 @@ def test_generated_queries_retain_intent_at_sql_sink(self): repo = Path(__file__).resolve().parents[2] env = dict(os.environ) env.pop("TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS", None) + env.pop("TEAQL_LOG_FORMAT", None) + env["TEAQL_LOG_ENDPOINT"] = "stdout" env["PYTHONPATH"] = os.pathsep.join((str(repo / "examples" / "school-management"), str(repo / "src"))) with tempfile.TemporaryDirectory(prefix="teaql-school-log-test-") as directory: env["TEAQL_SCHOOL_MANAGEMENT_DB"] = str(Path(directory) / "school.sqlite") @@ -19,12 +22,12 @@ def test_generated_queries_retain_intent_at_sql_sink(self): env=env, capture_output=True, text=True, timeout=90) output = result.stdout + result.stderr self.assertEqual(0, result.returncode, output) - queries = [line for line in output.splitlines() - if line.startswith("[TeaQL SQL]") and "[select]" in line] + records = [json.loads(line) for line in output.splitlines() if line.startswith("{")] + queries = [row for row in records if row.get("event") == "sql.select"] self.assertGreater(len(queries), 0, output) - for line in queries: - self.assertNotIn("comment=None", line) - self.assertNotIn("purpose=None", line) + for row in queries: + self.assertTrue(row.get("comment") and row["comment"].strip(), row) + self.assertTrue(row.get("purpose") and row["purpose"].strip(), row) self.assertIn("PASS Python School Management", output) diff --git a/examples/task_board/test_task_board.py b/examples/task_board/test_task_board.py index 4b1dec46..429b8cd0 100644 --- a/examples/task_board/test_task_board.py +++ b/examples/task_board/test_task_board.py @@ -1,4 +1,5 @@ """Run the real example; do not infer governance from process exit zero alone.""" +import json import os from pathlib import Path import subprocess @@ -12,6 +13,8 @@ def test_default_logs_have_intent_and_mask_business_values(self): repo = Path(__file__).resolve().parents[2] env = dict(os.environ) env.pop("TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS", None) + env.pop("TEAQL_LOG_FORMAT", None) + env["TEAQL_LOG_ENDPOINT"] = "stdout" env["PYTHONPATH"] = str(repo / "src") with tempfile.TemporaryDirectory(prefix="teaql-task-board-test-") as temporary: env["TEAQL_TASK_BOARD_DB"] = str(Path(temporary) / "task-board.db") @@ -19,28 +22,28 @@ def test_default_logs_have_intent_and_mask_business_values(self): env=env, capture_output=True, text=True, timeout=90) output = result.stdout + result.stderr self.assertEqual(0, result.returncode, output) + records = [json.loads(line) for line in output.splitlines() if line.startswith("{")] queries = writes = 0 - for line in output.splitlines(): - if not line.startswith("[TeaQL SQL]"): + for row in records: + if row.get("category") != "SQL": continue - if "[select]" in line or "[query]" in line: + if row.get("event") in ("sql.select", "sql.query"): queries += 1 - self.assertNotIn("comment=None", line) - self.assertNotIn("purpose=None", line) - self.assertNotIn("comment= purpose=", line) - self.assertNotIn("purpose= auditReason=", line) - elif any(f"[{kind}]" in line for kind in ("insert", "update", "delete")): + self.assertTrue(row.get("comment") and row["comment"].strip(), row) + self.assertTrue(row.get("purpose") and row["purpose"].strip(), row) + elif row.get("event") in ("sql.insert", "sql.update", "sql.delete"): writes += 1 - self.assertNotIn("auditReason=None", line) - self.assertNotIn("auditReason= tracePath=", line) + self.assertTrue(row.get("audit_reason") and row["audit_reason"].strip(), row) self.assertGreater(queries, 0, output) self.assertGreater(writes, 0, output) self.assertIn("PASS task board: governed Q/E/mutation and masked detail", output) self.assertNotIn("PRIVATE-TASK-DETAIL", output) self.assertIn("'PR***************IL' /* masked */", output) self.assertIn("'RENAME'", output) - self.assertIn("comment='page renamed task' purpose='verify paginated task intent'", output) - self.assertIn("comment='stream renamed task' purpose='verify streamed task intent'", output) + self.assertTrue(any(row.get("comment") == "page renamed task" and + row.get("purpose") == "verify paginated task intent" for row in records)) + self.assertTrue(any(row.get("comment") == "stream renamed task" and + row.get("purpose") == "verify streamed task intent" for row in records)) if __name__ == "__main__": From 631fc8f3a26df3599dba5b03478ab8f01fcfd1b9 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Wed, 18 Nov 2026 16:49:55 +0800 Subject: [PATCH 5/6] ci: promote the exact internally qualified packages (#73) Signed-off-by: Philip Z --- .github/release-signing-key.asc | 52 ++++++++++++++++++++++ .github/workflows/release.yml | 67 ++++++++++++++--------------- scripts/verify-qualified-release.py | 62 ++++++++++++++++++++++++++ 3 files changed, 147 insertions(+), 34 deletions(-) create mode 100644 .github/release-signing-key.asc create mode 100644 scripts/verify-qualified-release.py diff --git a/.github/release-signing-key.asc b/.github/release-signing-key.asc new file mode 100644 index 00000000..a0213ccc --- /dev/null +++ b/.github/release-signing-key.asc @@ -0,0 +1,52 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGpsF40BEAC+Olumai3qpCWXV6QYFufotbsG2TK+mIvFfHxOjX0qq24PsGW7 +D3iXxAYxG1Ohu3dNIM7Rj2lvLpxL1si6pJCvuD8vSnuhuubcpOJJIhGeG4S+r3sy +CFbgYw5Wde0t9MG4Gr5+p6OB0o3yeOeLB8Xeyk+jTZ/O9ukGgpGANNu8wMpEKE5t +06mjYPcajUdpPCs0FIC9WhyyPBQw4CLywMuJ1amnrs+yWDyaJogkw39m1/VZtnHE +FEg9PLg3SKq60DydI2kiOL2ozum/nj9y0Oe+wxNH+k+ACokZsoGV5PMG+PcDsOO/ +dPQ1v1Jm7aKAl6pyyV/jCq9tU43toKXD5MHm8Rffsb1nfgRHERzbqcl9bxsxmk1/ +62ePdc3RWiqlMS0YdqXYkd7yFtrZmJUL5xrRB0bI5tEbH0i4yema73WeSMV4PSlq +xU71TdA41Tq9OgmKKpVfWAThunKg50Dt1JXApTnCVMuEG+ejdvzXDwqlH+T9fXnp +knVgMpusZhhk4S9rP4QTmBmwNJZMIOMYNoKja0K/VAjKTfYmSHSrhpdWCkD71tqF +vD3RfTG/QohuhUz34EzN9pIpZpBAAQ6LHfISVLp9R8wdDRlOm0ICK6eVWooxtdLP +x6dQA/C4MApbuRj1pKgfwCk1X0k6HkZJA8KOqDWdmthHuFS6l1//LCVzeQARAQAB +tChQaGlsaXAgWiAoZ3BnIGZvciB0ZWFxbCkgPGluZm9AdGVhcWwuaW8+iQJUBBMB +CgA+FiEE0ZXN0QKIVz1lAZPaa58fi+AL1ZUFAmpsF40CGwMFCQHhM4AFCwkIBwIG +FQoJCAsCBBYCAwECHgECF4AACgkQa58fi+AL1ZUBdw//Qd9RBSgaxtJcSV4SnYDh +0Q2g8rWjA9WqREQAaMJJkwSHw3WsuvDi1At/zUDOy1DOjN0BrS/1tj5UneOqC4AF +jg/tuHFxTcfUPUFpPp/0Nj/jA7QPbGC2Ih2wVO8guO4JqUGbNsU0d59scwHRxSlI +l4PndTKVANi6l/cgdWXuejfLr/uPvMUji0lsODFBI4YOSvAG0RH1Ut2HHNMiNejZ +acstCPSKut01YSTDYce74RMZlBu3N+I1jW5ivOFabjkpnP2gMrYSzDzF+TsZLZAr +QYWi4pYdepf0/4LoBCUO7PqU2secg5rZ7r74E6xnBIntpTc2EG4zO4LfV4xDkavH +0Ar/I+L1VySx2QN9DiMywFJBau7Ajbc62gQacEzUzpBzPu2IW76XICLP0b5ZOltm +oBZg7xW1kvY/fFbfYT7K0K9L03K/fhIYzRRyhryZUAzv474zr9E7Tb96lsgubul6 +8s43GmQOadgHG3ZElX8XE8vGJ/ARm2FsIL99Iyw1AsSH7e2ri4diLktuVGKv7xSc +Jzywf+iTlTABPMlHJ/VDJ4KbzS5qlI/uwpdNlmCYfizXZncWIXAGpTJwoJgb0KC5 +wasDtFBNgX0cI/70Q0uDkligIQCLnqpu+LBmOynzJfwos2fzDGcsssf4ZMyL44gV +wQ0oEO5pocdEBLtGLlc4wuO5Ag0EamwXjQEQAJeD4iIKzNhQ1eJZSYmHMOcXh4pR +1rxISk0Pnu3u0raUeCKCj5iIUQTTD7b49O9j1HIxwCbjnjSeiIjE+4n/K88v/bIk +oa4yT8e+pwxs260KivtikltePAR3aNr3yr/XJEO1qCOIBaz2tW3AZlTDEOUli3Rt +unIwBwf9BC7CC9IbSDapSnWEp54XrV/uP/I1xtBB6hKla5IJNyaJzgUljb9aRXdD +nPXh7eTBsErY3io+x/EQXhmgS2qtnfC7nqDXreLohC2WrllqvyWVto1apYzS/g42 +onm3yvdMadt6FhX1oBZcktLQjY/fat7OCsAHvmluCwRpOQDw+zfMpLuWw6fbWSHl +6i1hE/1iKfW0a4NHtNleH+ClFJPyW3U5a5cWOv8mTC8xXVT+bAxdcEOxpDVzFkgl ++zgRFPB++kJAjyHqAqcFZOlQSfY0wHRT+DJKoWDGziNc5ae0U7e5oF+1kYUqOe00 +EAZajSDQj5BpF+dCrA8F08i48fVbb7WqYHRivARhkh/+z6qcbqjzJP799BCOYetB +0wehG5q9EZCgi0FqSjq+Ze0C+aGB0wuehOqgXqGG3C3xOpgduUNPucdIR8et27Pa +ij0zmKciYbs3VsvlcDxkx/7No3xh5oIk9If2ThE+A2/nbIC3rLjjo7dVOqvvrRxR +x030Qy7h2/NmycPZABEBAAGJAjwEGAEKACYWIQTRlc3RAohXPWUBk9prnx+L4AvV +lQUCamwXjQIbDAUJAeEzgAAKCRBrnx+L4AvVldZfD/9EMaDjuUXDFzVrCa4/03Wz +1HStHRLL8U9q+tc7GQDFeQELE7HH45MqA1j2ayRBOdhCcNlq0hRA371T3khqwxZ7 +PsU0TFYxosfDfuZ0nneJtFjI9yeABPhaXc+vcJZRTSn0qtvsSQeA+xJxfeNYLjK9 +0RCxd6qipVQjNnZgmpAvZNbqGO1RSLH8kdQcU21iXSL6EEawZmvYqHWX4pXVYI07 +YRbLUMUlXFSoTQTi20LORgOfk/gHNQxgRed82RGhtv7Fx8wm2jXOFOrlGDYjJ6f3 +RwxDC3GPX+DR3HWYk8tGxYiCxvVa/aP+ezamBDs+wzVJ+GtzTkeP/jYTRSBUFfCS +R9e1XyRqt+SsvutxkeMA89QlV9TkBGG1P+66Ibjf3pb6BG+3EBH77OXlMMmn1Q/q +rT0woJQXF4q3ZndunaIPYoIVlqajdIL7qJ9HMvpXN6cuD8F9J27DJGuZwTUYA7ps +0f6n4ylfO8UK0aEYQ4aoWGcgHONxYU7mXLwkUCcMhAd44HWUQwKr44XPalZtwGka +5MCfgdv2DQAWisuLZO6kYXeaallxRhfwO6Qr+7v4qBGogb4iBNtRrM8R+UYv9RTa +dsuUUWeDko0TFNxYFsCmFRtX3nN/eSn6E2DW3GS2+05PISd9f5Aun6AOCjwQNneZ +QCad98Aov4EvyhTT7opivw== +=gHhI +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 53066951..c8bd2390 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,63 +1,62 @@ -name: Publish Python package +name: Promote qualified python packages on: workflow_dispatch: inputs: release_tag: - description: Existing immutable signed Python release tag + description: Existing signed tag whose exact packages passed internal qualification + required: true + type: string + qualification_sha256: + description: SHA-256 of logging-qualification.json retained with the release evidence required: true type: string - push: - tags: - - "python-v*" -env: - TEAQL_RELEASE_TAG: ${{ inputs.release_tag || github.ref_name }} +concurrency: + group: python-public-promotion + cancel-in-progress: false jobs: - build: + verify: runs-on: ubuntu-latest permissions: contents: read steps: - - name: Validate immutable release tag input - shell: bash - run: '[[ "$TEAQL_RELEASE_TAG" =~ ^python-v[0-9]+\.[0-9]+\.[0-9]+$ ]]' - uses: actions/checkout@v4 with: - ref: ${{ inputs.release_tag || github.ref }} - - name: Verify checked out tag source - shell: bash - run: | - test "$(git cat-file -t "$TEAQL_RELEASE_TAG")" = tag - test "$(git rev-parse "$TEAQL_RELEASE_TAG^{commit}")" = "$(git rev-parse HEAD)" - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - run: python -m pip install --upgrade build - - run: python -m pip install --editable ".[test,telemetry,object-storage-s3]" - - name: Verify tag matches package version + ref: ${{ inputs.release_tag }} + fetch-depth: 0 + - name: Verify signed source and qualified package bytes + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ inputs.release_tag }} + QUALIFICATION_SHA256: ${{ inputs.qualification_sha256 }} shell: bash run: | - test "${TEAQL_RELEASE_TAG#python-v}" = "$(python -c 'import importlib.metadata; print(importlib.metadata.version("teaql"))')" - - run: python -m pytest - - run: python -m build + export GNUPGHOME="$RUNNER_TEMP/teaql-release-signatures" + mkdir -m 700 "$GNUPGHOME" + gpg --batch --import .github/release-signing-key.asc + python3 scripts/verify-qualified-release.py \ + --tag "$RELEASE_TAG" --manifest-sha256 "$QUALIFICATION_SHA256" \ + --language python --repository "$GITHUB_REPOSITORY" - uses: actions/upload-artifact@v4 with: - name: python-distributions - path: dist/ + name: qualified-python-packages + path: qualified-packages/ + if-no-files-found: error publish: - needs: build + needs: verify runs-on: ubuntu-latest - environment: - name: pypi - url: https://pypi.org/project/teaql/ + environment: pypi permissions: + contents: read id-token: write steps: - uses: actions/download-artifact@v4 with: - name: python-distributions - path: dist/ + name: qualified-python-packages + path: qualified-packages/ - uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: qualified-packages/ diff --git a/scripts/verify-qualified-release.py b/scripts/verify-qualified-release.py new file mode 100644 index 00000000..97dfc4e1 --- /dev/null +++ b/scripts/verify-qualified-release.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Download and verify exactly the packages qualified before public promotion.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--tag', required=True) + parser.add_argument('--manifest-sha256', required=True) + parser.add_argument('--language', choices=['python', 'typescript', 'dotnet'], required=True) + parser.add_argument('--repository', required=True) + args = parser.parse_args() + assert re.fullmatch(r'[a-z0-9.-]+', args.tag) + assert re.fullmatch(r'[a-f0-9]{64}', args.manifest_sha256) + assert subprocess.check_output(['git', 'cat-file', '-t', args.tag], text=True).strip() == 'tag' + signature = subprocess.run(['git', 'verify-tag', '--raw', args.tag], capture_output=True, text=True) + assert signature.returncode == 0 + assert '[GNUPG:] VALIDSIG D195CDD10288573D650193DA6B9F1F8BE00BD595 ' in signature.stderr + commit = subprocess.check_output(['git', 'rev-parse', args.tag + '^{commit}'], text=True).strip() + assert commit == subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip() + subprocess.run(['git', 'merge-base', '--is-ancestor', commit, 'refs/remotes/origin/main'], check=True) + metadata = Path('qualification-metadata') + metadata.mkdir() + subprocess.run(['gh', 'release', 'download', args.tag, '--repo', args.repository, + '--pattern', 'logging-qualification.json', '--dir', str(metadata)], check=True) + raw = (metadata / 'logging-qualification.json').read_bytes() + assert hashlib.sha256(raw).hexdigest() == args.manifest_sha256 + manifest = json.loads(raw) + assert manifest['schema'] == 'teaql.logging-release.qualified-packages/v1' + assert manifest['repository'] == args.repository and manifest['language'] == args.language + assert manifest['sourceCommit'] == commit + qualification = manifest['internalQualification'] + assert qualification['passed'] is True and qualification['rounds'] == 2 + assert re.fullmatch(r'[a-f0-9]{64}', qualification['modelSHA256']) + assert re.fullmatch(r'[a-f0-9]{40}', qualification['generatorCommit']) + assert re.fullmatch(r'[a-f0-9]{64}', qualification['receiptSHA256']) + packages = Path('qualified-packages') + packages.mkdir() + expected = set() + suffix = {'python': '.whl', 'typescript': '.tgz', 'dotnet': '.nupkg'}[args.language] + for artifact in manifest['artifacts']: + name = artifact['file'] + assert re.fullmatch(r'[A-Za-z0-9_.-]+', name) and name.endswith(suffix) + assert name not in expected + expected.add(name) + subprocess.run(['gh', 'release', 'download', args.tag, '--repo', args.repository, + '--pattern', name, '--dir', str(packages)], check=True) + path = packages / name + assert path.is_file() and not path.is_symlink() + data = path.read_bytes() + assert len(data) == artifact['bytes'] and hashlib.sha256(data).hexdigest() == artifact['sha256'] + assert expected and {p.name for p in packages.iterdir()} == expected + print('Verified signed source tag and', len(expected), 'internally qualified package(s); no rebuild performed') + + +if __name__ == '__main__': + main() From 630c14e393a340c717e26cbcd9efc43714cfcdae Mon Sep 17 00:00:00 2001 From: Philip Z Date: Wed, 18 Nov 2026 17:37:54 +0800 Subject: [PATCH 6/6] fix(logging): keep ordinary audit files masked under debug opt-in (#73) Signed-off-by: Philip Z --- docs/releases/0.6.0.md | 2 ++ src/teaql/runtime/audit.py | 10 ++++++-- src/teaql/runtime/context.py | 14 +++++++---- tests/runtime/test_log_presentations.py | 33 +++++++++++++++++++++++++ 4 files changed, 52 insertions(+), 7 deletions(-) diff --git a/docs/releases/0.6.0.md b/docs/releases/0.6.0.md index bc3ebcc7..183eafb9 100644 --- a/docs/releases/0.6.0.md +++ b/docs/releases/0.6.0.md @@ -20,3 +20,5 @@ Tracking: https://github.com/teaql/teaql-python/issues/73; coordinated release h Release status and the source, internal-artifact and public-delivery gates are recorded separately in teaql/teaql-conformance, `evidence/2026-11-18-logging-release`. These notes do not establish publication. + +Ordinary audit files keep model-marked values masked when the separate plaintext debug acknowledgement is enabled. Existing explicit custom audit projections retain their opt-in behavior. diff --git a/src/teaql/runtime/audit.py b/src/teaql/runtime/audit.py index 7e90bce1..6aa4b700 100644 --- a/src/teaql/runtime/audit.py +++ b/src/teaql/runtime/audit.py @@ -31,8 +31,14 @@ class RawAuditEvent: _intent_privacy: Any = field(default=None, repr=False, compare=False) def safe(self, mask_fields: List[str], max_length: Optional[int]) -> "SafeAuditEvent": - from .log_privacy import REDACTED, credential_name, payload_has_credentials, plaintext_enabled, scrub, value_strings - allow = plaintext_enabled() + from .log_privacy import plaintext_enabled + return self._project(mask_fields, max_length, plaintext_enabled()) + + def _runtime_log_safe(self, mask_fields: List[str], max_length: Optional[int]) -> "SafeAuditEvent": + return self._project(mask_fields, max_length, False) + + def _project(self, mask_fields: List[str], max_length: Optional[int], allow: bool) -> "SafeAuditEvent": + from .log_privacy import REDACTED, credential_name, payload_has_credentials, scrub, value_strings secrets = [] fields = [] for change in self.changes: diff --git a/src/teaql/runtime/context.py b/src/teaql/runtime/context.py index 82914eac..deb8e935 100644 --- a/src/teaql/runtime/context.py +++ b/src/teaql/runtime/context.py @@ -1063,6 +1063,10 @@ async def send_audit_event(self, event: Any): async def _deliver_audit_event(self, event: Any, safe_event: Any): from .audit import deliver from .telemetry import RuntimeOperation, start_runtime_operation + descriptor = self.entity(event.entity) + logging_event = event._runtime_log_safe( + getattr(descriptor, "audit_mask_fields_val", []) if descriptor else [], + getattr(descriptor, "audit_value_max_len_val", None) if descriptor else None) scope = start_runtime_operation(self.operation_telemetry(), RuntimeOperation( "audit", f"{event.entity}.audit", { "teaql.entity.type": event.entity, @@ -1085,12 +1089,12 @@ async def _deliver_audit_event(self, event: Any, safe_event: Any): if failures: raise failures[0] try: - self._runtime_logger.write('INFO', 'audit.' + safe_event.kind.value, 'TeaQL audit event', - category='AUDIT', outcome='success', entity=safe_event.entity, - entity_id=str(safe_event.entity_id), + self._runtime_logger.write('INFO', 'audit.' + logging_event.kind.value, 'TeaQL audit event', + category='AUDIT', outcome='success', entity=logging_event.entity, + entity_id=str(logging_event.entity_id), fields=[{'field': item.field, 'value': item.value, 'masked': item.masked, - 'truncated': item.truncated} for item in safe_event.fields], - trace_chain=[str(node) for node in safe_event.trace_chain]) + 'truncated': item.truncated} for item in logging_event.fields], + trace_chain=[str(node) for node in logging_event.trace_chain]) except Exception: from .logging import _failure _failure('log_write_failed', self._runtime_logger.log_name) diff --git a/tests/runtime/test_log_presentations.py b/tests/runtime/test_log_presentations.py index 7535d5cd..44e37b1f 100644 --- a/tests/runtime/test_log_presentations.py +++ b/tests/runtime/test_log_presentations.py @@ -62,6 +62,39 @@ def read(path, presentation): return events(path.read_text(encoding='utf-8'), presentation) +@pytest.mark.asyncio +@pytest.mark.parametrize('presentation', ['json', 'human']) +@pytest.mark.parametrize('acknowledged', [False, True]) +async def test_ordinary_audit_stays_masked_with_plaintext_debug_ack(tmp_path, monkeypatch, presentation, acknowledged): + from teaql.runtime.audit import AuditFieldChange, MutationAuditKind, RawAuditEvent + monkeypatch.setenv('TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS', + 'I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK' if acknowledged else '') + logger = RuntimeLogger(log_format=presentation, environment={}, working_directory=tmp_path) + context = UserContext.new(runtime_logger=logger) + collected = [] + class Collector: + async def on_safe_event(self, _context, event): + collected.append(event) + context.with_app_audit_event_sink(Collector()) + raw = RawAuditEvent(MutationAuditKind.CREATED, 'Customer', 42, ( + AuditFieldChange('name', new_value='PRIVATE-AUDIT-BUSINESS'), + AuditFieldChange('address', new_value='1 Runtime Road'), + AuditFieldChange('password', new_value='PASSWORD-CANARY'), + )) + descriptor = SimpleNamespace(audit_mask_fields_val=['name'], audit_value_max_len_val=None) + with patch.object(context, 'entity', return_value=descriptor): + await context.send_audit_event(raw) + data = logger.path.read_text() + assert 'PRIVATE-AUDIT-BUSINESS' not in data and 'PASSWORD-CANARY' not in data + audit = next(row for row in read(logger.path, presentation) if row.get('category') == 'AUDIT') + fields = {item['field']: item for item in audit['fields']} + assert fields['name']['masked'] is True + assert fields['address']['value'] == '1 Runtime Road' and fields['address']['masked'] is False + assert raw.changes[0].new_value == 'PRIVATE-AUDIT-BUSINESS' + assert len(collected) == 1 + assert next(field for field in collected[0].fields if field.field == 'name').masked is not acknowledged + + @pytest.mark.parametrize('presentation', ['json', 'human']) @pytest.mark.parametrize('explicit,domain,models,name', [ ('application', 'domain', ['model'], 'application'),