The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): keep structured summaries valid; honour opt-out for parent copy
Teknium24dfa8a19e8b
diff --git a/tests/tools/test_delegated_output_redaction.py b/tests/tools/test_delegated_output_redaction.pyindex 18a9c3cc9ea..e90ab8e8aa1 100644--- a/tests/tools/test_delegated_output_redaction.py+++ b/tests/tools/test_delegated_output_redaction.py@@ -70,7 +70,7 @@ def test_child_result_events_memory_hooks_and_spill_use_redacted_output(assert text not in stop["child_summary"]spills = list((tmp_path / "cache" / "delegation").glob("subagent-summary-*.txt"))assert spills- assert text not in spills[0].read_text(encoding="utf-8")+ assert text not in spills[0].read_text(encoding="utf-8-sig")def _record():@@ -406,12 +406,47 @@ def test_batch_failure_notice_scrubs_entry_without_finishing_batch(monkeypatch):assert ad._records[record["delegation_id"]]["status"] == "running"-def test_forced_redaction_does_not_follow_optional_display_setting(monkeypatch):- from agent.redact import redact_sensitive_text+def test_structured_summary_is_redacted_per_value_and_stays_valid_json():+ """A text pass over JSON lets ``KEY=***`` swallow the closing quote and comma."""+ from tools.delegation_redaction import redact_child_result- monkeypatch.setattr("agent.redact._redact_enabled", lambda: False)- assert redact_sensitive_text(SECRET) == SECRET- entry = delegate._run_single_child(- 0, "finish the task", _StubChild([SECRET]), _Parent()+ answer = {"env": "OPENAI_API_KEY=sk-proj-" + "a" * 40, "n": 2}+ entry = redact_child_result(+ {"summary": json.dumps(answer), "schema_valid": True}, {"type": "object"})- assert entry["status"] == "completed" and SECRET not in entry["summary"]++ parsed = json.loads(entry["summary"])+ assert parsed["n"] == 2 and "sk-proj-" + "a" * 40 not in parsed["env"]+ assert entry["schema_valid"] is True+++def test_parent_copy_honours_opt_out_while_persisted_copies_stay_forced(+ tmp_path, monkeypatch+):+ """security.redact_secrets=false: the parent model reads the child's text as-is;+ spill file, memory provider, lifecycle hook and the durable row are still masked."""+ import hermes_cli.plugins++ monkeypatch.setattr("agent.redact._redact_enabled", lambda: False)+ hooks = Mock()+ monkeypatch.setattr(hermes_cli.plugins, "invoke_hook", hooks)+ monkeypatch.setattr(delegate, "_load_config", lambda: {"max_summary_chars": 2000})+ summary = SECRET + "\n" + "ordinary explanation\n" * 180+ parent = _Parent()++ entry = results._run_child_lifecycle(0, "summarize", _StubChild([summary]), parent)++ assert SECRET in entry["summary"]+ assert SECRET not in parent._memory_manager.on_delegation.call_args.kwargs["result"]+ stop = next(c.kwargs for c in hooks.call_args_list if c.args[0] == "subagent_stop")+ assert SECRET not in stop["child_summary"]+ spill = next((tmp_path / "cache" / "delegation").glob("subagent-summary-*.txt"))+ assert SECRET not in spill.read_text(encoding="utf-8-sig")++ record, target = _record(), queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", target)+ ad._push_completion_event(record, {"status": "completed", "summary": SECRET}, "completed")+ assert SECRET in target.get_nowait()["summary"]+ with ad._transaction() as conn:+ row = conn.execute("SELECT event_json,result_json FROM async_delegations").fetchone()+ assert SECRET not in "".join(row)diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 55be32d3d6a..b3746bb23f0 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -972,8 +972,11 @@ def _push_completion_event(record: dict[str, Any], result: dict[str, Any], statu"""Push a type='async_delegation' event onto the shared completion queue. Batch records(``is_batch``) carry the per-task ``results`` list (plus live transcript paths, thefull-fidelity record of each child's run) instead of a single summary. Best-effort: failure- must not crash the worker, but it WOULD mean a silently-lost result, so we log loudly."""- result = redact_child_result(result)+ must not crash the worker, but it WOULD mean a silently-lost result, so we log loudly.++ The queued event is the parent's in-process copy and honours ``security.redact_secrets: false``;+ ``_persist_completion`` re-scrubs with force for the durable row (and the worker IPC)."""+ result = redact_child_result(result, force=False)is_batch = bool(record.get("is_batch"))label = " batch" if is_batch else ""try:@@ -1027,8 +1030,9 @@ def push_task_failure_notice(delegation_id: str, entry: dict[str, Any], *, n_tasarrived: 66 minutes of a dead wave with nothing running. The notice rides the same``type="async_delegation"`` event shape as the batch result (so every drain/route/format pathtreats it identically) with ``task_failure_notice=True`` and a single-entry ``results`` list; the- batch record is NOT finalized and its consolidated result still arrives as before."""- entry = redact_child_result(entry)+ batch record is NOT finalized and its consolidated result still arrives as before. In-process+ queue only (never persisted), so the parent's copy honours ``security.redact_secrets: false``."""+ entry = redact_child_result(entry, force=False)with _records_lock:record = _records.get(delegation_id)if record is None or record.get("status") not in _ACTIVE_STATES:diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex ac33918c283..4ee0b12bc33 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -9,8 +9,7 @@ import jsonimport osimport threadingimport time-from agent.redact import redact_for_egress-from tools.delegation_redaction import redact_child_result+from tools.delegation_redaction import redact_child_result, redact_child_textfrom concurrent.futures import TimeoutError as FuturesTimeoutErrorfrom typing import Any, Dict, List, Optionalfrom agent.compression_marker import elide@@ -735,7 +734,7 @@ class _ChildRun:"""Inspect + prune the child worktree, reporting into the entry (no-op without isolation)."""info = self.worktree_infoif info is None:- return redact_child_result(entry_dict, getattr(self.child, "_delegate_output_schema", None))+ return redact_child_result(entry_dict, getattr(self.child, "_delegate_output_schema", None), force=False)from tools import subagent_worktreetry:entry_dict["worktree"] = subagent_worktree.finalize_subagent_worktree(info)@@ -744,7 +743,7 @@ class _ChildRun:# via the shared factory so the two producers never drift.logger.warning("worktree finalize failed: %s", e)entry_dict["worktree"] = subagent_worktree.unproven_worktree_payload(info, f"finalize raised: {e}")- return redact_child_result(entry_dict, getattr(self.child, "_delegate_output_schema", None))+ return redact_child_result(entry_dict, getattr(self.child, "_delegate_output_schema", None), force=False)def seed_workspace(self) -> None:"""Seed cwd/container aliases and optional worktree isolation for the child;@@ -778,8 +777,9 @@ class _ChildRun:"""Shared tail of every failure path: emit ``subagent.complete`` (``status`` defaults to the entry's), notethe steer text that won the race with the failure, report the worktree."""_safe_progress(- self.child_progress_cb, "subagent.complete", preview=redact_for_egress(preview), status=status or entry["status"],- duration_seconds=entry["duration_seconds"], summary=redact_for_egress(summary) if summary is not None else None,+ self.child_progress_cb, "subagent.complete", preview=redact_child_text(preview, force=False), status=status or entry["status"],+ duration_seconds=entry["duration_seconds"],+ summary=redact_child_text(summary, force=False) if summary is not None else None,)_append_missed_steer(entry, late_steer)return self.attach_worktree(entry)@@ -1001,13 +1001,13 @@ class _ChildRun:leftover = process_registry.running_owned_by(self.child_task_id)if leftover:entry["orphaned_processes"] = [- {"session_id": s.id, "command": redact_for_egress(s.command)[:200], "runtime_seconds": round(time.time() - s.started_at)}+ {"session_id": s.id, "command": redact_child_text(s.command, force=False)[:200], "runtime_seconds": round(time.time() - s.started_at)}for s in leftover]unread = process_registry.unread_completions_owned_by(self.child_task_id)if unread:entry["unread_completions"] = [- {"session_id": s.id, "command": redact_for_egress(s.command)[:200], "exit_code": s.exit_code,- "output_tail": redact_for_egress(_output_tail(s, len(s.output_buffer)))[-600:]} for s in unread]+ {"session_id": s.id, "command": redact_child_text(s.command, force=False)[:200], "exit_code": s.exit_code,+ "output_tail": redact_child_text(_output_tail(s, len(s.output_buffer)), force=False)[-600:]} for s in unread]def emit_complete(self, result: dict[str, Any], entry: dict[str, Any], duration: float) -> None:"""Fire ``subagent.complete`` with the per-branch observability payload (tokens, cost, files touched,@@ -1015,7 +1015,8 @@ class _ChildRun:if not self.child_progress_cb:returnchild = self.child- entry.update(redact_child_result(entry, getattr(child, "_delegate_output_schema", None)))+ # Parent copy + live progress: honour security.redact_secrets=false (persistence boundaries force).+ entry.update(redact_child_result(entry, getattr(child, "_delegate_output_schema", None), force=False))summary = entry["summary"]_files_read: list = []with _quiet(None):@@ -1043,7 +1044,7 @@ class _ChildRun:if _cost_usd is not None:with _quiet(None):complete_kwargs["cost_usd"] = float(_cost_usd)- _safe_progress(self.child_progress_cb, "subagent.complete", **redact_child_result(complete_kwargs))+ _safe_progress(self.child_progress_cb, "subagent.complete", **redact_child_result(complete_kwargs, force=False))def cleanup(self, *, heartbeat: _Heartbeat, child_pool: Any, leased_cred_id: Any, close_deferred: bool) -> None:"""Finally-path teardown (idempotent, never raises). Order matters: stop heartbeat → drop registry entry →diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.pyindex 476057ca636..7e171a1c546 100644--- a/tools/delegate_tool_progress.py+++ b/tools/delegate_tool_progress.py@@ -38,8 +38,8 @@ def _safe_progress(cb: Any, event_type: Any, *args: Any, **kwargs: Any) -> None:def _clean_error_text(error: Any, max_chars: int = 200) -> str:"""Reduce an error payload (traceback / JSON wall) to one clean line: the exception message (last line of atraceback) or the first non-empty line, hard-capped in length."""- from agent.redact import redact_for_egress- lines = [ln.strip() for ln in redact_for_egress(str(error or "")).strip().splitlines() if ln.strip()]+ from tools.delegation_redaction import redact_child_text+ lines = [ln.strip() for ln in redact_child_text(str(error or ""), force=False).strip().splitlines() if ln.strip()]if not lines:return ""line = lines[-1] if lines[0].startswith("Traceback") else lines[0]diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.pyindex 947880ef73b..b9de015592c 100644--- a/tools/delegate_tool_results.py+++ b/tools/delegate_tool_results.py@@ -8,7 +8,7 @@ import threadingfrom typing import Any, Dict, List, Optionalfrom urllib.parse import urlsplit, urlunsplitfrom agent.redact import redact_for_egress-from tools.delegation_redaction import redact_child_result+from tools.delegation_redaction import redact_child_result, redact_child_text, redact_child_valuelogger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module@@ -68,7 +68,8 @@ def _extract_output_tail(result: dict[str, Any], *, max_entries: int = 12, max_cbreakif not isinstance(msg, dict) or msg.get("role") != "tool":continue- content = redact_for_egress(_stringify_tool_content(msg.get("content") or ""))+ # Live progress (subagent.complete overlay): honours security.redact_secrets=false.+ content = redact_child_text(_stringify_tool_content(msg.get("content") or ""), force=False)tool_name = name_by_call_id.get(msg.get("tool_call_id") or "", "tool")tail.append({"tool": tool_name, "preview": content[:max_chars], "is_error": _looks_like_error_output(content)})tail.reverse()@@ -80,14 +81,14 @@ _TOOL_INPUT_TARGET_KEYS = frozenset({})_TOOL_INPUT_URL_KEYS = frozenset({"endpoint", "url", "urls"})-def _sanitize_tool_target(key: str, value: Any) -> Any:+def _sanitize_tool_target(key: str, value: Any, force: bool = True) -> Any:"""Keep bounded side-effect targets while dropping URL secrets."""if isinstance(value, list):- cleaned = [item for item in (_sanitize_tool_target(key, item) for item in value[:16]) if item is not None]+ cleaned = [item for item in (_sanitize_tool_target(key, item, force) for item in value[:16]) if item is not None]return cleaned or Noneif not isinstance(value, str) or not value:return None- bounded = redact_for_egress(value)[:1024]+ bounded = redact_child_text(value, force=force)[:1024]if key in _TOOL_INPUT_URL_KEYS:try:parsed = urlsplit(bounded)@@ -105,22 +106,23 @@ def _sanitize_tool_target(key: str, value: Any) -> Any:return Nonereturn bounded-def _sanitize_targets(mapping: dict[str, Any]) -> dict[str, Any]:+def _sanitize_targets(mapping: dict[str, Any], force: bool = True) -> dict[str, Any]:"""Keep only known side-effect target keys, each sanitized (URL secrets dropped)."""targets: dict[str, Any] = {}for raw_key, value in mapping.items():key = str(raw_key).lower()if key in _TOOL_INPUT_TARGET_KEYS:- cleaned = _sanitize_tool_target(key, value)+ cleaned = _sanitize_tool_target(key, value, force)if cleaned is not None:targets[key] = cleanedreturn targets-def _input_summary(keys: Any, targets: Any) -> dict[str, Any]:- """``{argument_keys, targets}`` with bounded, sanitized contents (empty on bad shapes)."""+def _input_summary(keys: Any, targets: Any, force: bool = True) -> dict[str, Any]:+ """``{argument_keys, targets}`` with bounded, sanitized contents (empty on bad shapes). ``force=False`` for the+ parent's own tool_trace copy (honours the opt-out); lifecycle hooks re-sanitize with ``force=True``."""return {- "argument_keys": [redact_for_egress(str(key))[:128] for key in keys[:64]] if isinstance(keys, list) else [],- "targets": _sanitize_targets(targets) if isinstance(targets, dict) else {},+ "argument_keys": [redact_child_text(str(key), force=force)[:128] for key in keys[:64]] if isinstance(keys, list) else [],+ "targets": _sanitize_targets(targets, force) if isinstance(targets, dict) else {},}def _summarize_tool_arguments(arguments: Any) -> dict[str, Any]:@@ -131,7 +133,7 @@ def _summarize_tool_arguments(arguments: Any) -> dict[str, Any]:parsed = Noneif not isinstance(parsed, dict):return _input_summary([], {})- return _input_summary(sorted(str(key) for key in parsed), parsed)+ return _input_summary(sorted(str(key) for key in parsed), parsed, force=False)def _subagent_stop_tool_call_history(tool_trace: Any) -> list[dict[str, Any]]:"""Detached, metadata-only tool history for lifecycle hooks (input summaries re-sanitized)."""@@ -180,6 +182,7 @@ def _spill_summary_to_file(task_index: int, summary: str) -> Optional[str]:from tools.spill_safety import write_text_exclusive# Exclusive symlink-refusing create; not private because cache/delegation is bind-mounted read-only into# remote backends whose container UID must be able to read it.+ # Forced: the spill file persists and is bind-mounted into remote backends.write_text_exclusive(path, redact_for_egress(summary), private=False)return str(path)except Exception as exc:@@ -190,7 +193,8 @@ def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple["""``(model_text, spill_path)`` for one over-budget summary: a ~75% head / ~25% tail window snapped to lineboundaries (so the opening AND the closing outcomes/files-changed/issues both survive), the full text spilledto disk, and a footer giving the exact ``read_file offset=`` for the omitted middle."""- summary = redact_for_egress(summary)+ # ``summary`` is the parent's copy (already scrubbed per the user's setting in _finalize_child_results);+ # the spill write below is forced regardless.original_len = len(summary)head_budget = int(cap * 0.75)tail_budget = cap - head_budget@@ -339,7 +343,8 @@ def _notify_memory_manager(results, task_list, child_by_index, parent_agent) ->task_index = entry.get("task_index", -1)in_range = isinstance(task_index, int) and 0 <= task_index < len(task_list)memory.on_delegation(- task=task_list[task_index]["goal"] if in_range else "", result=entry.get("summary", "") or "",+ task=task_list[task_index]["goal"] if in_range else "",+ result=redact_child_text(entry.get("summary", "") or "", force=True), # memory providers persistchild_session_id=getattr(child_by_index.get(task_index), "session_id", ""),)except Exception:@@ -369,7 +374,8 @@ def _fire_subagent_stop_hooks(results, child_by_index, parent_agent) -> float:"subagent_stop", parent_session_id=getattr(parent_agent, "session_id", None),parent_turn_id=getattr(parent_agent, "_current_turn_id", "") or "",child_session_id=getattr(child, "session_id", None), child_role=child_role,- child_summary=entry.get("summary"), child_status=entry.get("status"),+ child_summary=redact_child_value(entry.get("summary")), # forced: plugins leave the process+ child_status=entry.get("status"),tool_call_history=_subagent_stop_tool_call_history(entry.get("tool_trace")),duration_ms=int((entry.get("duration_seconds") or 0) * 1000),)@@ -401,7 +407,8 @@ def _finalize_child_results(child_by_index = {index: child for index, _task, child in children}for entry in results:child = child_by_index.get(entry.get("task_index"))- entry.update(redact_child_result(entry, getattr(child, "_delegate_output_schema", None)))+ # The parent's own copy honours security.redact_secrets=false; spill/memory/hooks force their own scrub.+ entry.update(redact_child_result(entry, getattr(child, "_delegate_output_schema", None), force=False))_apply_summary_budget(results, parent_agent)_notify_memory_manager(results, task_list, child_by_index, parent_agent)_rollup_children_cost(parent_agent, _fire_subagent_stop_hooks(results, child_by_index, parent_agent))diff --git a/tools/delegation_redaction.py b/tools/delegation_redaction.pyindex 53122ff6880..cfe13f74aa8 100644--- a/tools/delegation_redaction.py+++ b/tools/delegation_redaction.py@@ -1,15 +1,29 @@-"""Delegation-owned output projections, using the existing forced text redactor.+"""Delegation-owned output projections, using the existing text redactor.Child output is scrubbed before it is shortened or handed to another consumer.Parent-authored instructions and delivery coordinates retain their exact values.Live streamed text needs its own buffering policy and does not pass through here.++Policy (``force``): copies that leave the process or persist (spill files, the+async_delegations rows and their replay/recovery, worker IPC, memory providers,+lifecycle hooks) are always scrubbed (``force=True``, the default). The parent+model's own in-process copy and live progress honour ``security.redact_secrets:+false`` (``force=False``), the same as any other tool result the parent reads.+Registered vault values are scrubbed in both modes."""from __future__ import annotations+import jsonfrom typing import Any-from agent.redact import REDACTION_UNAVAILABLE, redact_for_egress+import agent.redact as _redact+from agent.redact import (+ REDACTION_UNAVAILABLE,+ is_secret_field_name,+ redact_for_egress,+ redact_sensitive_text,+)_PARENT_EVENT_FIELDS = frozenset({@@ -38,25 +52,74 @@ _RESULT_METADATA = frozenset()-def redact_child_value(value: Any, *, _depth: int = 0) -> Any:+def redact_child_text(text: Any, *, force: bool = True) -> str:+ """Scrub one child-produced string. ``force=False`` honours the user's opt-out."""+ if force or _redact._redact_enabled():+ return redact_for_egress(text)+ try: # opted out: vault values only (still a hard boundary)+ return redact_sensitive_text(str(text or ""))+ except Exception: # health: allow BLE001 -- fail closed, never return raw text on redactor faults+ return REDACTION_UNAVAILABLE+++def _redact_field(key: str, value: str, force: bool) -> str:+ """Redact a string value with its key as context: once a JSON summary is parsed apart, the+ key-gated ``"api_key": "<opaque>"`` rule no longer sees the key, so credential-named fields+ get that pass on a one-field document. Fails closed for those fields only."""+ cleaned = redact_child_text(value, force=force)+ if cleaned != value or not is_secret_field_name(key):+ return cleaned+ raw = json.dumps({key: value})+ scrubbed = redact_child_text(raw, force=force)+ if scrubbed == raw:+ return cleaned+ try:+ probe = json.loads(scrubbed)+ except ValueError:+ return REDACTION_UNAVAILABLE+ only = next(iter(probe.values()), None) if isinstance(probe, dict) and len(probe) == 1 else None+ return only if isinstance(only, str) else REDACTION_UNAVAILABLE+++def redact_child_value(value: Any, *, force: bool = True, _depth: int = 0) -> Any:"""Copy JSON-shaped child data; unsupported or excessively deep values are withheld."""if _depth > 64:return REDACTION_UNAVAILABLEif isinstance(value, str):- return redact_for_egress(value)+ return redact_child_text(value, force=force)if isinstance(value, dict):return {- redact_for_egress(str(key)): redact_child_value(item, _depth=_depth + 1)+ redact_child_text(str(key), force=force): (+ _redact_field(str(key), item, force)+ if isinstance(item, str)+ else redact_child_value(item, force=force, _depth=_depth + 1)+ )for key, item in value.items()}if isinstance(value, (list, tuple)):- return [redact_child_value(item, _depth=_depth + 1) for item in value]+ return [redact_child_value(item, force=force, _depth=_depth + 1) for item in value]if value is None or isinstance(value, (bool, int, float)):return valuereturn REDACTION_UNAVAILABLE-def redact_child_result(result: dict[str, Any], output_schema=None) -> dict[str, Any]:+def _redact_summary(summary: Any, structured: bool, force: bool) -> Any:+ """Structured (schema) summaries that parse as JSON are redacted per value and+ re-serialized: a text pass can eat JSON delimiters (``KEY=***`` swallowing the+ closing quote and comma) and break an answer that was valid. Unchanged JSON keeps+ its original formatting; anything that does not parse gets the text pass."""+ if structured and isinstance(summary, str):+ try:+ parsed = json.loads(summary)+ except ValueError:+ parsed = None+ if isinstance(parsed, (dict, list)):+ cleaned = redact_child_value(parsed, force=force)+ return summary if cleaned == parsed else json.dumps(cleaned, ensure_ascii=False)+ return redact_child_value(summary, force=force)+++def redact_child_result(result: dict[str, Any], output_schema=None, *, force: bool = True) -> dict[str, Any]:"""Project a result or batch, preserving accounting and host-owned model/task identity.Revalidation here is only for a summary changed by redaction. General schema@@ -64,18 +127,21 @@ def redact_child_result(result: dict[str, Any], output_schema=None) -> dict[str,Old durable entries do not retain the schema, so their previous positive verdictcannot certify a newly redacted summary."""+ structured = isinstance(output_schema, dict) or "schema_valid" in resultcleaned = {}for key, value in result.items():if key == "results" and isinstance(value, list):cleaned[key] = [- redact_child_result(entry)+ redact_child_result(entry, force=force)if isinstance(entry, dict)- else redact_child_value(entry)+ else redact_child_value(entry, force=force)for entry in value]+ elif key == "summary":+ cleaned[key] = _redact_summary(value, structured, force)else:cleaned[key] = (- value if key in _RESULT_METADATA else redact_child_value(value)+ value if key in _RESULT_METADATA else redact_child_value(value, force=force))if "schema_valid" in result and cleaned.get("summary") != result.get("summary"):valid, errors = (@@ -98,17 +164,17 @@ def redact_child_result(result: dict[str, Any], output_schema=None) -> dict[str,cleaned.pop("schema_errors", None)cleaned.pop("schema_note", None)if not valid:- cleaned["schema_errors"] = redact_child_value(errors)+ cleaned["schema_errors"] = redact_child_value(errors, force=force)cleaned["schema_note"] = ("Secret redaction changed the delivered summary; do not treat it as validated output.")return cleaned-def redact_completion_event(event: dict[str, Any]) -> dict[str, Any]:+def redact_completion_event(event: dict[str, Any], *, force: bool = True) -> dict[str, Any]:"""Scrub output while leaving parent instructions and routing outside the projection."""cleaned = redact_child_result(- {key: value for key, value in event.items() if key not in _PARENT_EVENT_FIELDS}+ {key: value for key, value in event.items() if key not in _PARENT_EVENT_FIELDS}, force=force)cleaned.update({key: value for key, value in event.items() if key in _PARENT_EVENT_FIELDS}