Differential Privacy — Spike-Level DP
Spike-level differential privacy: add privacy noise at the spike domain instead of the gradient domain. Exploits the binary nature of spikes for more natural DP mechanisms.
Why Spike-Level DP?
Standard DP-SGD adds Gaussian noise to gradients (continuous, high-dimensional). For SNNs, spikes are already binary — we can use mechanisms designed for binary data:
| Mechanism |
How It Works |
Privacy Cost |
| Randomized Response |
Flip each bit with probability p = 1/(1+e^ε) |
ε per bit |
| Poisson Subsampling |
Keep each spike with probability q = e^ε/(1+e^ε) |
ε per step |
Components
SpikeLevelDP — Main DP mechanism.
| Parameter |
Default |
Meaning |
epsilon |
1.0 |
Per-step privacy budget |
mechanism |
"randomized_response" |
DP mechanism |
Methods: privatize(spikes) — apply DP noise to a spike tensor.
PrivacyAccountant — Track cumulative privacy budget.
| Parameter |
Default |
Meaning |
target_epsilon |
1.0 |
Total privacy budget |
target_delta |
1e-5 |
Failure probability |
Properties: spent_epsilon, remaining_epsilon, budget_exhausted. Methods: record_step(step_epsilon), summary().
MembershipAudit — Audit SNN for membership inference vulnerability. Compares model confidence on training vs non-training samples. Returns accuracy (0.5 = no leakage, 1.0 = full leak), vulnerable flag if accuracy > 0.6.
Governance Contracts
The sc_neurocore.privacy.governance module defines the deterministic manifest
surface for neural and BCI deployments that need privacy evidence before data or
model artefacts leave a controlled environment.
| Contract |
Purpose |
ConsentBoundary |
Participant identity, legal basis, telemetry consent, allowed purposes, consent token, and issue timestamp. |
RetentionPolicy |
Raw-stream, model-artifact, and audit-log retention windows bounded by one maximum horizon. |
RedactionPolicy |
Field-level redaction activation, protected fields, and replacement marker. |
TelemetryPolicy |
Telemetry enablement, sink name, and sampling interval. |
ProvenanceRecord |
Artefact URI, hash algorithm, hash value, artefact type, and source system. |
IntegratorResponsibility |
Integrator contact, operational responsibilities, and release approval requirement. |
PrivacyFeatureFlags |
Differential-privacy, federated-learning, telemetry logging, and audit-flag activation. |
GovernanceContract |
Cross-section contract that fails closed when telemetry lacks consent/redaction or sensitive features lack audit flags. |
Pythonfrom sc_neurocore.privacy import GovernanceContract
contract = GovernanceContract.from_dict(manifest)
assert contract.active_features() == ("telemetry_logging",)
signed_manifest = contract.to_dict()
The governance surface is intentionally dependency-free and does not have a
polyglot compute counterpart. It is covered by tests/test_privacy_governance.py
with 100% isolated module coverage and strict type checking.
Usage
Pythonfrom sc_neurocore.privacy.dp_snn import SpikeLevelDP, PrivacyAccountant, MembershipAudit
import numpy as np
# Apply DP to spike outputs
dp = SpikeLevelDP(epsilon=1.0, mechanism="randomized_response")
spikes = np.random.randint(0, 2, (100, 64)).astype(np.int8)
private_spikes = dp.privatize(spikes)
# Track privacy budget
accountant = PrivacyAccountant(target_epsilon=10.0)
for step in range(100):
accountant.record_step(dp.per_step_epsilon)
if accountant.budget_exhausted:
print(f"Budget exhausted at step {step}")
break
print(accountant.summary())
# Membership inference audit
def model_fn(x):
return np.random.randn(10) # your model here
auditor = MembershipAudit(run_fn=model_fn)
result = auditor.audit(member_samples, non_member_samples)
print(f"MI accuracy: {result['accuracy']:.2f}, vulnerable: {result['vulnerable']}")
See Tutorial 62: Differential Privacy.
sc_neurocore.privacy
Spike-level differential privacy: training and inference with privacy guarantees.
PrivacyAccountant
dataclass
Track cumulative privacy budget across training steps.
Uses simple composition theorem: total epsilon = sum of per-step epsilons.
For tighter bounds, use Renyi DP (future extension).
Parameters
target_epsilon : float
Privacy budget limit.
target_delta : float
Failure probability.
Source code in src/sc_neurocore/privacy/dp_snn.py
| Python |
|---|
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69 | @dataclass
class PrivacyAccountant:
"""Track cumulative privacy budget across training steps.
Uses simple composition theorem: total epsilon = sum of per-step epsilons.
For tighter bounds, use Renyi DP (future extension).
Parameters
----------
target_epsilon : float
Privacy budget limit.
target_delta : float
Failure probability.
"""
target_epsilon: float = 1.0
target_delta: float = 1e-5
_spent_epsilon: float = 0.0
_steps: int = 0
def record_step(self, step_epsilon: float) -> None:
"""Record privacy cost of one training step."""
self._spent_epsilon += step_epsilon
self._steps += 1
@property
def spent_epsilon(self) -> float:
return self._spent_epsilon
@property
def remaining_epsilon(self) -> float:
return max(0.0, self.target_epsilon - self._spent_epsilon)
@property
def budget_exhausted(self) -> bool:
return self._spent_epsilon >= self.target_epsilon
def summary(self) -> str:
return (
f"Privacy: epsilon={self._spent_epsilon:.4f}/{self.target_epsilon} "
f"({self._steps} steps), delta={self.target_delta}"
)
|
record_step(step_epsilon)
Record privacy cost of one training step.
Source code in src/sc_neurocore/privacy/dp_snn.py
| Python |
|---|
| def record_step(self, step_epsilon: float) -> None:
"""Record privacy cost of one training step."""
self._spent_epsilon += step_epsilon
self._steps += 1
|
MembershipAudit
Audit SNN for membership inference vulnerability.
Given a trained model (as a callable), test whether it leaks
information about training data membership. Uses shadow model
methodology: compare model confidence on training vs non-training
samples.
Parameters
run_fn : callable
Model function: takes spikes (T, N) → output (N_out,).
Source code in src/sc_neurocore/privacy/dp_snn.py
| Python |
|---|
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198 | class MembershipAudit:
"""Audit SNN for membership inference vulnerability.
Given a trained model (as a callable), test whether it leaks
information about training data membership. Uses shadow model
methodology: compare model confidence on training vs non-training
samples.
Parameters
----------
run_fn : callable
Model function: takes spikes (T, N) → output (N_out,).
"""
def __init__(self, run_fn: Callable[..., Any]) -> None:
self.run_fn = run_fn
def audit(
self,
member_samples: list[np.ndarray[Any, Any]],
non_member_samples: list[np.ndarray[Any, Any]],
) -> dict[str, Any]:
"""Run membership inference audit.
Parameters
----------
member_samples : list of ndarray
Samples known to be in the training set.
non_member_samples : list of ndarray
Samples known to NOT be in the training set.
Returns
-------
dict with:
- accuracy: membership inference accuracy (0.5 = no leakage, 1.0 = full leak)
- member_confidence: mean output magnitude for members
- non_member_confidence: mean output magnitude for non-members
- vulnerable: bool, True if accuracy > 0.6
"""
member_scores = [float(np.abs(self.run_fn(s)).mean()) for s in member_samples]
non_member_scores = [float(np.abs(self.run_fn(s)).mean()) for s in non_member_samples]
mean_member = float(np.mean(member_scores))
mean_non = float(np.mean(non_member_scores))
# Threshold-based inference: predict member if score > midpoint
threshold = (mean_member + mean_non) / 2
correct = 0
total = len(member_scores) + len(non_member_scores)
for s in member_scores:
if s >= threshold:
correct += 1
for s in non_member_scores:
if s < threshold:
correct += 1
accuracy = correct / max(total, 1)
return {
"accuracy": accuracy,
"member_confidence": mean_member,
"non_member_confidence": mean_non,
"vulnerable": accuracy > 0.6,
}
|
audit(member_samples, non_member_samples)
Run membership inference audit.
Parameters
member_samples : list of ndarray
Samples known to be in the training set.
non_member_samples : list of ndarray
Samples known to NOT be in the training set.
Returns
dict with:
- accuracy: membership inference accuracy (0.5 = no leakage, 1.0 = full leak)
- member_confidence: mean output magnitude for members
- non_member_confidence: mean output magnitude for non-members
- vulnerable: bool, True if accuracy > 0.6
Source code in src/sc_neurocore/privacy/dp_snn.py
| Python |
|---|
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198 | def audit(
self,
member_samples: list[np.ndarray[Any, Any]],
non_member_samples: list[np.ndarray[Any, Any]],
) -> dict[str, Any]:
"""Run membership inference audit.
Parameters
----------
member_samples : list of ndarray
Samples known to be in the training set.
non_member_samples : list of ndarray
Samples known to NOT be in the training set.
Returns
-------
dict with:
- accuracy: membership inference accuracy (0.5 = no leakage, 1.0 = full leak)
- member_confidence: mean output magnitude for members
- non_member_confidence: mean output magnitude for non-members
- vulnerable: bool, True if accuracy > 0.6
"""
member_scores = [float(np.abs(self.run_fn(s)).mean()) for s in member_samples]
non_member_scores = [float(np.abs(self.run_fn(s)).mean()) for s in non_member_samples]
mean_member = float(np.mean(member_scores))
mean_non = float(np.mean(non_member_scores))
# Threshold-based inference: predict member if score > midpoint
threshold = (mean_member + mean_non) / 2
correct = 0
total = len(member_scores) + len(non_member_scores)
for s in member_scores:
if s >= threshold:
correct += 1
for s in non_member_scores:
if s < threshold:
correct += 1
accuracy = correct / max(total, 1)
return {
"accuracy": accuracy,
"member_confidence": mean_member,
"non_member_confidence": mean_non,
"vulnerable": accuracy > 0.6,
}
|
SpikeLevelDP
Spike-level differential privacy mechanism.
Adds stochastic spike noise to provide (epsilon, delta)-DP.
Two mechanisms:
- Spike randomized response: each spike independently flipped with probability p
- Spike subsampling: randomly drop spikes with probability 1-q
Parameters
epsilon : float
Per-step privacy budget.
mechanism : str
'randomized_response' or 'subsampling'.
seed : int
Source code in src/sc_neurocore/privacy/dp_snn.py
| Python |
|---|
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131 | class SpikeLevelDP:
"""Spike-level differential privacy mechanism.
Adds stochastic spike noise to provide (epsilon, delta)-DP.
Two mechanisms:
- Spike randomized response: each spike independently flipped with probability p
- Spike subsampling: randomly drop spikes with probability 1-q
Parameters
----------
epsilon : float
Per-step privacy budget.
mechanism : str
'randomized_response' or 'subsampling'.
seed : int
"""
def __init__(
self, epsilon: float = 1.0, mechanism: str = "randomized_response", seed: int = 42
) -> None:
self.epsilon = epsilon
self.mechanism = mechanism
self._rng = np.random.RandomState(seed)
# Compute noise parameter from epsilon
if mechanism == "randomized_response":
# Randomized response: flip each bit with probability p = 1/(1+e^epsilon)
self.flip_prob = 1.0 / (1.0 + np.exp(epsilon))
elif mechanism == "subsampling":
# Poisson subsampling: keep each spike with probability q = e^epsilon / (1+e^epsilon)
self.keep_prob = np.exp(epsilon) / (1.0 + np.exp(epsilon))
else:
raise ValueError(f"Unknown mechanism '{mechanism}'")
def privatize(self, spikes: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
"""Apply DP mechanism to a spike tensor.
Parameters
----------
spikes : ndarray of shape (T, N) or (N,)
Binary spike tensor.
Returns
-------
ndarray, same shape
Privatized spikes.
"""
if self.mechanism == "randomized_response":
flip_mask = self._rng.random(spikes.shape) < self.flip_prob
privatized = spikes.copy().astype(np.int8)
privatized[flip_mask] = 1 - privatized[flip_mask]
return privatized
else:
keep_mask = self._rng.random(spikes.shape) < self.keep_prob
masked_spikes: np.ndarray[Any, Any] = (spikes * keep_mask).astype(spikes.dtype)
return masked_spikes
@property
def per_step_epsilon(self) -> float:
return self.epsilon
|
privatize(spikes)
Apply DP mechanism to a spike tensor.
Parameters
spikes : ndarray of shape (T, N) or (N,)
Binary spike tensor.
Returns
ndarray, same shape
Privatized spikes.
Source code in src/sc_neurocore/privacy/dp_snn.py
| Python |
|---|
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127 | def privatize(self, spikes: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
"""Apply DP mechanism to a spike tensor.
Parameters
----------
spikes : ndarray of shape (T, N) or (N,)
Binary spike tensor.
Returns
-------
ndarray, same shape
Privatized spikes.
"""
if self.mechanism == "randomized_response":
flip_mask = self._rng.random(spikes.shape) < self.flip_prob
privatized = spikes.copy().astype(np.int8)
privatized[flip_mask] = 1 - privatized[flip_mask]
return privatized
else:
keep_mask = self._rng.random(spikes.shape) < self.keep_prob
masked_spikes: np.ndarray[Any, Any] = (spikes * keep_mask).astype(spikes.dtype)
return masked_spikes
|
ConsentBoundary
dataclass
Participant-level legal basis and telemetry permissions.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166 | @dataclass(frozen=True)
class ConsentBoundary:
"""Participant-level legal basis and telemetry permissions."""
participant_id: str
consent_basis: str
allow_telemetry: bool
allowed_purposes: Tuple[str, ...]
consent_token: str
issued_at_unix: int
def __post_init__(self) -> None:
"""Validate consent identity, legal basis, telemetry flag, and token fields."""
object.__setattr__(
self, "participant_id", _ensure_non_empty_str(self.participant_id, "participant_id")
)
object.__setattr__(
self, "consent_basis", _ensure_non_empty_str(self.consent_basis, "consent_basis")
)
if self.consent_basis not in _ALLOWED_CONSENT_BASES:
allowed = ", ".join(_ALLOWED_CONSENT_BASES)
raise ValueError(f"consent_basis must be one of: {allowed}")
object.__setattr__(
self,
"allow_telemetry",
_ensure_bool(self.allow_telemetry, "allow_telemetry"),
)
if not isinstance(self.issued_at_unix, int) or self.issued_at_unix <= 0:
raise ValueError("issued_at_unix must be a positive int")
object.__setattr__(
self, "allowed_purposes", _to_str_tuple(self.allowed_purposes, "allowed_purposes")
)
object.__setattr__(
self, "consent_token", _ensure_non_empty_str(self.consent_token, "consent_token")
)
def to_dict(self) -> Dict[str, Any]:
"""Return this consent boundary as a deterministic mapping."""
return {
"participant_id": self.participant_id,
"consent_basis": self.consent_basis,
"allow_telemetry": self.allow_telemetry,
"allowed_purposes": list(self.allowed_purposes),
"consent_token": self.consent_token,
"issued_at_unix": self.issued_at_unix,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ConsentBoundary":
"""Build a consent boundary from a manifest section."""
payload = _expect_mapping(data, field="consent_boundary")
_require_fields(
payload,
"consent_boundary",
(
"participant_id",
"consent_basis",
"allow_telemetry",
"allowed_purposes",
"consent_token",
"issued_at_unix",
),
)
return cls(
participant_id=payload["participant_id"],
consent_basis=payload["consent_basis"],
allow_telemetry=payload["allow_telemetry"],
allowed_purposes=payload.get("allowed_purposes", ()),
consent_token=payload["consent_token"],
issued_at_unix=payload["issued_at_unix"],
)
|
__post_init__()
Validate consent identity, legal basis, telemetry flag, and token fields.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130 | def __post_init__(self) -> None:
"""Validate consent identity, legal basis, telemetry flag, and token fields."""
object.__setattr__(
self, "participant_id", _ensure_non_empty_str(self.participant_id, "participant_id")
)
object.__setattr__(
self, "consent_basis", _ensure_non_empty_str(self.consent_basis, "consent_basis")
)
if self.consent_basis not in _ALLOWED_CONSENT_BASES:
allowed = ", ".join(_ALLOWED_CONSENT_BASES)
raise ValueError(f"consent_basis must be one of: {allowed}")
object.__setattr__(
self,
"allow_telemetry",
_ensure_bool(self.allow_telemetry, "allow_telemetry"),
)
if not isinstance(self.issued_at_unix, int) or self.issued_at_unix <= 0:
raise ValueError("issued_at_unix must be a positive int")
object.__setattr__(
self, "allowed_purposes", _to_str_tuple(self.allowed_purposes, "allowed_purposes")
)
object.__setattr__(
self, "consent_token", _ensure_non_empty_str(self.consent_token, "consent_token")
)
|
to_dict()
Return this consent boundary as a deterministic mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
132
133
134
135
136
137
138
139
140
141 | def to_dict(self) -> Dict[str, Any]:
"""Return this consent boundary as a deterministic mapping."""
return {
"participant_id": self.participant_id,
"consent_basis": self.consent_basis,
"allow_telemetry": self.allow_telemetry,
"allowed_purposes": list(self.allowed_purposes),
"consent_token": self.consent_token,
"issued_at_unix": self.issued_at_unix,
}
|
from_dict(data)
classmethod
Build a consent boundary from a manifest section.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ConsentBoundary":
"""Build a consent boundary from a manifest section."""
payload = _expect_mapping(data, field="consent_boundary")
_require_fields(
payload,
"consent_boundary",
(
"participant_id",
"consent_basis",
"allow_telemetry",
"allowed_purposes",
"consent_token",
"issued_at_unix",
),
)
return cls(
participant_id=payload["participant_id"],
consent_basis=payload["consent_basis"],
allow_telemetry=payload["allow_telemetry"],
allowed_purposes=payload.get("allowed_purposes", ()),
consent_token=payload["consent_token"],
issued_at_unix=payload["issued_at_unix"],
)
|
GovernanceContract
dataclass
Full privacy governance contract for BCI/neural workflows.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586 | @dataclass(frozen=True)
class GovernanceContract:
"""Full privacy governance contract for BCI/neural workflows."""
consent_boundary: ConsentBoundary
retention_policy: RetentionPolicy
redaction_policy: RedactionPolicy
telemetry: TelemetryPolicy
provenance: Tuple[ProvenanceRecord, ...]
integrator: IntegratorResponsibility
features: PrivacyFeatureFlags
schema_version: str = "1.0"
def __post_init__(self) -> None:
"""Enforce cross-section privacy governance invariants."""
if self.features.enable_telemetry_logging:
if not self.telemetry.enabled:
raise ValueError("telemetry_logging requires telemetry enabled")
if not self.redaction_policy.enabled:
raise ValueError("telemetry_logging requires redaction")
if not self.consent_boundary.allow_telemetry:
raise ValueError("telemetry_logging requires telemetry consent")
if self.features.enable_differential_privacy and (
"differential_privacy" not in self.features.audit_flags
):
raise ValueError("differential_privacy requires audit flag 'differential_privacy'")
if self.features.enable_federated_learning and (
"federated_learning" not in self.features.audit_flags
):
raise ValueError("federated_learning requires audit flag 'federated_learning'")
if self.features.enable_telemetry_logging and "telemetry" not in self.features.audit_flags:
raise ValueError("telemetry_logging requires audit flag 'telemetry'")
@property
def audit_required_features(self) -> Tuple[str, ...]:
"""Return sorted feature keys that require audit flags."""
return tuple(sorted(_FEATURE_AUDIT_FLAG.keys()))
def active_features(self) -> Tuple[str, ...]:
"""Return names of enabled privacy features in deterministic order."""
enabled = []
if self.features.enable_differential_privacy:
enabled.append("differential_privacy")
if self.features.enable_federated_learning:
enabled.append("federated_learning")
if self.features.enable_telemetry_logging:
enabled.append("telemetry_logging")
return tuple(sorted(enabled))
def to_dict(self) -> Dict[str, Any]:
"""Return a deterministic JSON-serialisable representation."""
return {
"consent_boundary": self.consent_boundary.to_dict(),
"retention_policy": self.retention_policy.to_dict(),
"redaction_policy": self.redaction_policy.to_dict(),
"telemetry": self.telemetry.to_dict(),
"provenance": [record.to_dict() for record in self.provenance],
"integrator": self.integrator.to_dict(),
"features": self.features.to_dict(),
"schema_version": self.schema_version,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "GovernanceContract":
"""Build a full governance contract from a manifest mapping."""
payload = _expect_mapping(data, field="governance_contract")
for required in _ROOT_REQUIRED_FIELDS:
if required not in payload:
raise ValueError(f"Missing required field: {required}")
provenance = payload["provenance"]
if not isinstance(provenance, list):
raise ValueError("provenance must be a list")
return cls(
consent_boundary=ConsentBoundary.from_dict(payload["consent_boundary"]),
retention_policy=RetentionPolicy.from_dict(payload["retention_policy"]),
redaction_policy=RedactionPolicy.from_dict(payload["redaction_policy"]),
telemetry=TelemetryPolicy.from_dict(payload["telemetry"]),
provenance=tuple(ProvenanceRecord.from_dict(item) for item in provenance),
integrator=IntegratorResponsibility.from_dict(payload["integrator"]),
features=PrivacyFeatureFlags.from_dict(payload["features"]),
schema_version=payload.get("schema_version", "1.0"),
)
|
audit_required_features
property
Return sorted feature keys that require audit flags.
__post_init__()
Enforce cross-section privacy governance invariants.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533 | def __post_init__(self) -> None:
"""Enforce cross-section privacy governance invariants."""
if self.features.enable_telemetry_logging:
if not self.telemetry.enabled:
raise ValueError("telemetry_logging requires telemetry enabled")
if not self.redaction_policy.enabled:
raise ValueError("telemetry_logging requires redaction")
if not self.consent_boundary.allow_telemetry:
raise ValueError("telemetry_logging requires telemetry consent")
if self.features.enable_differential_privacy and (
"differential_privacy" not in self.features.audit_flags
):
raise ValueError("differential_privacy requires audit flag 'differential_privacy'")
if self.features.enable_federated_learning and (
"federated_learning" not in self.features.audit_flags
):
raise ValueError("federated_learning requires audit flag 'federated_learning'")
if self.features.enable_telemetry_logging and "telemetry" not in self.features.audit_flags:
raise ValueError("telemetry_logging requires audit flag 'telemetry'")
|
active_features()
Return names of enabled privacy features in deterministic order.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
540
541
542
543
544
545
546
547
548
549 | def active_features(self) -> Tuple[str, ...]:
"""Return names of enabled privacy features in deterministic order."""
enabled = []
if self.features.enable_differential_privacy:
enabled.append("differential_privacy")
if self.features.enable_federated_learning:
enabled.append("federated_learning")
if self.features.enable_telemetry_logging:
enabled.append("telemetry_logging")
return tuple(sorted(enabled))
|
to_dict()
Return a deterministic JSON-serialisable representation.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
551
552
553
554
555
556
557
558
559
560
561
562 | def to_dict(self) -> Dict[str, Any]:
"""Return a deterministic JSON-serialisable representation."""
return {
"consent_boundary": self.consent_boundary.to_dict(),
"retention_policy": self.retention_policy.to_dict(),
"redaction_policy": self.redaction_policy.to_dict(),
"telemetry": self.telemetry.to_dict(),
"provenance": [record.to_dict() for record in self.provenance],
"integrator": self.integrator.to_dict(),
"features": self.features.to_dict(),
"schema_version": self.schema_version,
}
|
from_dict(data)
classmethod
Build a full governance contract from a manifest mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "GovernanceContract":
"""Build a full governance contract from a manifest mapping."""
payload = _expect_mapping(data, field="governance_contract")
for required in _ROOT_REQUIRED_FIELDS:
if required not in payload:
raise ValueError(f"Missing required field: {required}")
provenance = payload["provenance"]
if not isinstance(provenance, list):
raise ValueError("provenance must be a list")
return cls(
consent_boundary=ConsentBoundary.from_dict(payload["consent_boundary"]),
retention_policy=RetentionPolicy.from_dict(payload["retention_policy"]),
redaction_policy=RedactionPolicy.from_dict(payload["redaction_policy"]),
telemetry=TelemetryPolicy.from_dict(payload["telemetry"]),
provenance=tuple(ProvenanceRecord.from_dict(item) for item in provenance),
integrator=IntegratorResponsibility.from_dict(payload["integrator"]),
features=PrivacyFeatureFlags.from_dict(payload["features"]),
schema_version=payload.get("schema_version", "1.0"),
)
|
IntegratorResponsibility
dataclass
Operational responsibilities for an integrator in a deployment pipeline.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430 | @dataclass(frozen=True)
class IntegratorResponsibility:
"""Operational responsibilities for an integrator in a deployment pipeline."""
name: str
contact: str
responsibilities: Tuple[str, ...]
release_approval_required: bool
def __post_init__(self) -> None:
"""Validate integrator contact details and approval responsibility fields."""
object.__setattr__(self, "name", _ensure_non_empty_str(self.name, "name"))
object.__setattr__(self, "contact", _ensure_non_empty_str(self.contact, "contact"))
object.__setattr__(
self, "responsibilities", _to_str_tuple(self.responsibilities, "responsibilities")
)
object.__setattr__(
self,
"release_approval_required",
_ensure_bool(self.release_approval_required, "release_approval_required"),
)
def to_dict(self) -> Dict[str, Any]:
"""Return this integrator responsibility record as a deterministic mapping."""
return {
"name": self.name,
"contact": self.contact,
"responsibilities": list(self.responsibilities),
"release_approval_required": self.release_approval_required,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "IntegratorResponsibility":
"""Build an integrator responsibility record from a manifest section."""
payload = _expect_mapping(data, field="integrator")
_require_fields(
payload,
"integrator",
("name", "contact", "responsibilities", "release_approval_required"),
)
return cls(
name=payload["name"],
contact=payload["contact"],
responsibilities=payload.get("responsibilities", ()),
release_approval_required=payload["release_approval_required"],
)
|
__post_init__()
Validate integrator contact details and approval responsibility fields.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
394
395
396
397
398
399
400
401
402
403
404
405 | def __post_init__(self) -> None:
"""Validate integrator contact details and approval responsibility fields."""
object.__setattr__(self, "name", _ensure_non_empty_str(self.name, "name"))
object.__setattr__(self, "contact", _ensure_non_empty_str(self.contact, "contact"))
object.__setattr__(
self, "responsibilities", _to_str_tuple(self.responsibilities, "responsibilities")
)
object.__setattr__(
self,
"release_approval_required",
_ensure_bool(self.release_approval_required, "release_approval_required"),
)
|
to_dict()
Return this integrator responsibility record as a deterministic mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
407
408
409
410
411
412
413
414 | def to_dict(self) -> Dict[str, Any]:
"""Return this integrator responsibility record as a deterministic mapping."""
return {
"name": self.name,
"contact": self.contact,
"responsibilities": list(self.responsibilities),
"release_approval_required": self.release_approval_required,
}
|
from_dict(data)
classmethod
Build an integrator responsibility record from a manifest section.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "IntegratorResponsibility":
"""Build an integrator responsibility record from a manifest section."""
payload = _expect_mapping(data, field="integrator")
_require_fields(
payload,
"integrator",
("name", "contact", "responsibilities", "release_approval_required"),
)
return cls(
name=payload["name"],
contact=payload["contact"],
responsibilities=payload.get("responsibilities", ()),
release_approval_required=payload["release_approval_required"],
)
|
PrivacyFeatureFlags
dataclass
Feature activation and audit flags for a governed workflow.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497 | @dataclass(frozen=True)
class PrivacyFeatureFlags:
"""Feature activation and audit flags for a governed workflow."""
enable_differential_privacy: bool
enable_federated_learning: bool
enable_telemetry_logging: bool
audit_enabled: bool
audit_flags: Tuple[str, ...]
def __post_init__(self) -> None:
"""Validate feature toggles and the audit-flag activation contract."""
object.__setattr__(
self,
"enable_differential_privacy",
_ensure_bool(self.enable_differential_privacy, "enable_differential_privacy"),
)
object.__setattr__(
self,
"enable_federated_learning",
_ensure_bool(self.enable_federated_learning, "enable_federated_learning"),
)
object.__setattr__(
self,
"enable_telemetry_logging",
_ensure_bool(self.enable_telemetry_logging, "enable_telemetry_logging"),
)
object.__setattr__(self, "audit_enabled", _ensure_bool(self.audit_enabled, "audit_enabled"))
object.__setattr__(self, "audit_flags", _to_str_tuple(self.audit_flags, "audit_flags"))
if self.audit_enabled and not self.audit_flags:
raise ValueError("audit_enabled requires audit_flags")
def to_dict(self) -> Dict[str, Any]:
"""Return this privacy feature flag set as a deterministic mapping."""
return {
"enable_differential_privacy": self.enable_differential_privacy,
"enable_federated_learning": self.enable_federated_learning,
"enable_telemetry_logging": self.enable_telemetry_logging,
"audit_enabled": self.audit_enabled,
"audit_flags": list(self.audit_flags),
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "PrivacyFeatureFlags":
"""Build privacy feature flags from a manifest section."""
payload = _expect_mapping(data, field="features")
_require_fields(
payload,
"features",
(
"enable_differential_privacy",
"enable_federated_learning",
"enable_telemetry_logging",
"audit_enabled",
"audit_flags",
),
)
return cls(
enable_differential_privacy=payload["enable_differential_privacy"],
enable_federated_learning=payload["enable_federated_learning"],
enable_telemetry_logging=payload["enable_telemetry_logging"],
audit_enabled=payload["audit_enabled"],
audit_flags=payload.get("audit_flags", ()),
)
|
__post_init__()
Validate feature toggles and the audit-flag activation contract.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464 | def __post_init__(self) -> None:
"""Validate feature toggles and the audit-flag activation contract."""
object.__setattr__(
self,
"enable_differential_privacy",
_ensure_bool(self.enable_differential_privacy, "enable_differential_privacy"),
)
object.__setattr__(
self,
"enable_federated_learning",
_ensure_bool(self.enable_federated_learning, "enable_federated_learning"),
)
object.__setattr__(
self,
"enable_telemetry_logging",
_ensure_bool(self.enable_telemetry_logging, "enable_telemetry_logging"),
)
object.__setattr__(self, "audit_enabled", _ensure_bool(self.audit_enabled, "audit_enabled"))
object.__setattr__(self, "audit_flags", _to_str_tuple(self.audit_flags, "audit_flags"))
if self.audit_enabled and not self.audit_flags:
raise ValueError("audit_enabled requires audit_flags")
|
to_dict()
Return this privacy feature flag set as a deterministic mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
466
467
468
469
470
471
472
473
474 | def to_dict(self) -> Dict[str, Any]:
"""Return this privacy feature flag set as a deterministic mapping."""
return {
"enable_differential_privacy": self.enable_differential_privacy,
"enable_federated_learning": self.enable_federated_learning,
"enable_telemetry_logging": self.enable_telemetry_logging,
"audit_enabled": self.audit_enabled,
"audit_flags": list(self.audit_flags),
}
|
from_dict(data)
classmethod
Build privacy feature flags from a manifest section.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "PrivacyFeatureFlags":
"""Build privacy feature flags from a manifest section."""
payload = _expect_mapping(data, field="features")
_require_fields(
payload,
"features",
(
"enable_differential_privacy",
"enable_federated_learning",
"enable_telemetry_logging",
"audit_enabled",
"audit_flags",
),
)
return cls(
enable_differential_privacy=payload["enable_differential_privacy"],
enable_federated_learning=payload["enable_federated_learning"],
enable_telemetry_logging=payload["enable_telemetry_logging"],
audit_enabled=payload["audit_enabled"],
audit_flags=payload.get("audit_flags", ()),
)
|
ProvenanceRecord
dataclass
Cryptographic provenance record for model and dataset artefacts.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382 | @dataclass(frozen=True)
class ProvenanceRecord:
"""Cryptographic provenance record for model and dataset artefacts."""
artifact_type: str
artifact_uri: str
hash_algorithm: str
artifact_hash: str
source_system: str
def __post_init__(self) -> None:
"""Validate provenance artefact identity, hash, and source-system fields."""
object.__setattr__(
self, "artifact_type", _ensure_non_empty_str(self.artifact_type, "artifact_type")
)
object.__setattr__(
self, "artifact_uri", _ensure_non_empty_str(self.artifact_uri, "artifact_uri")
)
object.__setattr__(
self, "hash_algorithm", _ensure_non_empty_str(self.hash_algorithm, "hash_algorithm")
)
object.__setattr__(
self, "artifact_hash", _ensure_non_empty_str(self.artifact_hash, "artifact_hash")
)
object.__setattr__(
self,
"source_system",
_ensure_non_empty_str(self.source_system, "source_system"),
)
def to_dict(self) -> Dict[str, Any]:
"""Return this provenance record as a deterministic mapping."""
return {
"artifact_type": self.artifact_type,
"artifact_uri": self.artifact_uri,
"hash_algorithm": self.hash_algorithm,
"artifact_hash": self.artifact_hash,
"source_system": self.source_system,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ProvenanceRecord":
"""Build a provenance record from one manifest list item."""
payload = _expect_mapping(data, field="provenance entry")
_require_fields(
payload,
"provenance entry",
(
"artifact_type",
"artifact_uri",
"hash_algorithm",
"artifact_hash",
"source_system",
),
)
if not payload.get("artifact_uri", ""):
raise ValueError("Provenance entry requires artifact_uri")
if not payload.get("artifact_hash", ""):
raise ValueError("Provenance entry requires artifact_hash")
if not payload.get("hash_algorithm", ""):
raise ValueError("Provenance entry requires hash_algorithm")
return cls(
artifact_type=payload["artifact_type"],
artifact_uri=payload["artifact_uri"],
hash_algorithm=payload["hash_algorithm"],
artifact_hash=payload["artifact_hash"],
source_system=payload["source_system"],
)
|
__post_init__()
Validate provenance artefact identity, hash, and source-system fields.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343 | def __post_init__(self) -> None:
"""Validate provenance artefact identity, hash, and source-system fields."""
object.__setattr__(
self, "artifact_type", _ensure_non_empty_str(self.artifact_type, "artifact_type")
)
object.__setattr__(
self, "artifact_uri", _ensure_non_empty_str(self.artifact_uri, "artifact_uri")
)
object.__setattr__(
self, "hash_algorithm", _ensure_non_empty_str(self.hash_algorithm, "hash_algorithm")
)
object.__setattr__(
self, "artifact_hash", _ensure_non_empty_str(self.artifact_hash, "artifact_hash")
)
object.__setattr__(
self,
"source_system",
_ensure_non_empty_str(self.source_system, "source_system"),
)
|
to_dict()
Return this provenance record as a deterministic mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
345
346
347
348
349
350
351
352
353 | def to_dict(self) -> Dict[str, Any]:
"""Return this provenance record as a deterministic mapping."""
return {
"artifact_type": self.artifact_type,
"artifact_uri": self.artifact_uri,
"hash_algorithm": self.hash_algorithm,
"artifact_hash": self.artifact_hash,
"source_system": self.source_system,
}
|
from_dict(data)
classmethod
Build a provenance record from one manifest list item.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ProvenanceRecord":
"""Build a provenance record from one manifest list item."""
payload = _expect_mapping(data, field="provenance entry")
_require_fields(
payload,
"provenance entry",
(
"artifact_type",
"artifact_uri",
"hash_algorithm",
"artifact_hash",
"source_system",
),
)
if not payload.get("artifact_uri", ""):
raise ValueError("Provenance entry requires artifact_uri")
if not payload.get("artifact_hash", ""):
raise ValueError("Provenance entry requires artifact_hash")
if not payload.get("hash_algorithm", ""):
raise ValueError("Provenance entry requires hash_algorithm")
return cls(
artifact_type=payload["artifact_type"],
artifact_uri=payload["artifact_uri"],
hash_algorithm=payload["hash_algorithm"],
artifact_hash=payload["artifact_hash"],
source_system=payload["source_system"],
)
|
RedactionPolicy
dataclass
Field-level redaction policy for protected telemetry and logs.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273 | @dataclass(frozen=True)
class RedactionPolicy:
"""Field-level redaction policy for protected telemetry and logs."""
enabled: bool
fields: Tuple[str, ...]
replacement: str
def __post_init__(self) -> None:
"""Validate redaction activation, field list, and replacement marker."""
object.__setattr__(self, "enabled", _ensure_bool(self.enabled, "enabled"))
object.__setattr__(self, "fields", _to_str_tuple(self.fields, "fields"))
if self.enabled and not self.fields:
raise ValueError("redaction enabled requires at least one field")
if self.replacement is None:
raise ValueError("replacement must not be None")
def to_dict(self) -> Dict[str, Any]:
"""Return this redaction policy as a deterministic mapping."""
return {
"enabled": self.enabled,
"fields": list(self.fields),
"replacement": self.replacement,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "RedactionPolicy":
"""Build a redaction policy from a manifest section."""
payload = _expect_mapping(data, field="redaction_policy")
_require_fields(
payload,
"redaction_policy",
("enabled", "fields", "replacement"),
)
return cls(
enabled=payload["enabled"],
fields=payload.get("fields", ()),
replacement=payload.get("replacement", ""),
)
|
__post_init__()
Validate redaction activation, field list, and replacement marker.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
243
244
245
246
247
248
249
250 | def __post_init__(self) -> None:
"""Validate redaction activation, field list, and replacement marker."""
object.__setattr__(self, "enabled", _ensure_bool(self.enabled, "enabled"))
object.__setattr__(self, "fields", _to_str_tuple(self.fields, "fields"))
if self.enabled and not self.fields:
raise ValueError("redaction enabled requires at least one field")
if self.replacement is None:
raise ValueError("replacement must not be None")
|
to_dict()
Return this redaction policy as a deterministic mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
252
253
254
255
256
257
258 | def to_dict(self) -> Dict[str, Any]:
"""Return this redaction policy as a deterministic mapping."""
return {
"enabled": self.enabled,
"fields": list(self.fields),
"replacement": self.replacement,
}
|
from_dict(data)
classmethod
Build a redaction policy from a manifest section.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
260
261
262
263
264
265
266
267
268
269
270
271
272
273 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "RedactionPolicy":
"""Build a redaction policy from a manifest section."""
payload = _expect_mapping(data, field="redaction_policy")
_require_fields(
payload,
"redaction_policy",
("enabled", "fields", "replacement"),
)
return cls(
enabled=payload["enabled"],
fields=payload.get("fields", ()),
replacement=payload.get("replacement", ""),
)
|
RetentionPolicy
dataclass
Retention windows for neural telemetry and artefacts.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232 | @dataclass(frozen=True)
class RetentionPolicy:
"""Retention windows for neural telemetry and artefacts."""
raw_stream_days: int
model_artifacts_days: int
audit_log_days: int
max_days: int
def __post_init__(self) -> None:
"""Validate retention windows and enforce the maximum retention horizon."""
object.__setattr__(
self,
"raw_stream_days",
_ensure_positive_days(self.raw_stream_days, "raw_stream_days"),
)
object.__setattr__(
self,
"model_artifacts_days",
_ensure_positive_days(self.model_artifacts_days, "model_artifacts_days"),
)
object.__setattr__(
self,
"audit_log_days",
_ensure_positive_days(self.audit_log_days, "audit_log_days"),
)
object.__setattr__(self, "max_days", _ensure_positive_days(self.max_days, "max_days"))
if (
self.raw_stream_days > self.max_days
or self.model_artifacts_days > self.max_days
or self.audit_log_days > self.max_days
):
raise ValueError("all retention windows must be <= max_days")
def to_dict(self) -> Dict[str, Any]:
"""Return this retention policy as a deterministic mapping."""
return {
"raw_stream_days": self.raw_stream_days,
"model_artifacts_days": self.model_artifacts_days,
"audit_log_days": self.audit_log_days,
"max_days": self.max_days,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "RetentionPolicy":
"""Build a retention policy from a manifest section."""
payload = _expect_mapping(data, field="retention_policy")
_require_fields(
payload,
"retention_policy",
(
"raw_stream_days",
"model_artifacts_days",
"audit_log_days",
"max_days",
),
)
return cls(
raw_stream_days=payload["raw_stream_days"],
model_artifacts_days=payload["model_artifacts_days"],
audit_log_days=payload["audit_log_days"],
max_days=payload["max_days"],
)
|
__post_init__()
Validate retention windows and enforce the maximum retention horizon.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202 | def __post_init__(self) -> None:
"""Validate retention windows and enforce the maximum retention horizon."""
object.__setattr__(
self,
"raw_stream_days",
_ensure_positive_days(self.raw_stream_days, "raw_stream_days"),
)
object.__setattr__(
self,
"model_artifacts_days",
_ensure_positive_days(self.model_artifacts_days, "model_artifacts_days"),
)
object.__setattr__(
self,
"audit_log_days",
_ensure_positive_days(self.audit_log_days, "audit_log_days"),
)
object.__setattr__(self, "max_days", _ensure_positive_days(self.max_days, "max_days"))
if (
self.raw_stream_days > self.max_days
or self.model_artifacts_days > self.max_days
or self.audit_log_days > self.max_days
):
raise ValueError("all retention windows must be <= max_days")
|
to_dict()
Return this retention policy as a deterministic mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
204
205
206
207
208
209
210
211 | def to_dict(self) -> Dict[str, Any]:
"""Return this retention policy as a deterministic mapping."""
return {
"raw_stream_days": self.raw_stream_days,
"model_artifacts_days": self.model_artifacts_days,
"audit_log_days": self.audit_log_days,
"max_days": self.max_days,
}
|
from_dict(data)
classmethod
Build a retention policy from a manifest section.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "RetentionPolicy":
"""Build a retention policy from a manifest section."""
payload = _expect_mapping(data, field="retention_policy")
_require_fields(
payload,
"retention_policy",
(
"raw_stream_days",
"model_artifacts_days",
"audit_log_days",
"max_days",
),
)
return cls(
raw_stream_days=payload["raw_stream_days"],
model_artifacts_days=payload["model_artifacts_days"],
audit_log_days=payload["audit_log_days"],
max_days=payload["max_days"],
)
|
TelemetryPolicy
dataclass
Telemetry sink and sampling policy.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312 | @dataclass(frozen=True)
class TelemetryPolicy:
"""Telemetry sink and sampling policy."""
enabled: bool
sink: str
sampling_interval_ms: int
def __post_init__(self) -> None:
"""Validate telemetry activation, sink name, and sampling interval."""
object.__setattr__(self, "enabled", _ensure_bool(self.enabled, "enabled"))
object.__setattr__(self, "sink", _ensure_non_empty_str(self.sink, "sink"))
if self.enabled and self.sampling_interval_ms is None:
raise ValueError("sampling_interval_ms must be set when telemetry is enabled")
if not isinstance(self.sampling_interval_ms, int):
raise ValueError("sampling_interval_ms must be an int")
if self.sampling_interval_ms <= 0:
raise ValueError("sampling_interval_ms must be positive")
def to_dict(self) -> Dict[str, Any]:
"""Return this telemetry policy as a deterministic mapping."""
return {
"enabled": self.enabled,
"sink": self.sink,
"sampling_interval_ms": self.sampling_interval_ms,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "TelemetryPolicy":
"""Build a telemetry policy from a manifest section."""
payload = _expect_mapping(data, field="telemetry")
_require_fields(payload, "telemetry", ("enabled", "sink", "sampling_interval_ms"))
return cls(
enabled=payload["enabled"],
sink=payload["sink"],
sampling_interval_ms=payload["sampling_interval_ms"],
)
|
__post_init__()
Validate telemetry activation, sink name, and sampling interval.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
284
285
286
287
288
289
290
291
292
293 | def __post_init__(self) -> None:
"""Validate telemetry activation, sink name, and sampling interval."""
object.__setattr__(self, "enabled", _ensure_bool(self.enabled, "enabled"))
object.__setattr__(self, "sink", _ensure_non_empty_str(self.sink, "sink"))
if self.enabled and self.sampling_interval_ms is None:
raise ValueError("sampling_interval_ms must be set when telemetry is enabled")
if not isinstance(self.sampling_interval_ms, int):
raise ValueError("sampling_interval_ms must be an int")
if self.sampling_interval_ms <= 0:
raise ValueError("sampling_interval_ms must be positive")
|
to_dict()
Return this telemetry policy as a deterministic mapping.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
295
296
297
298
299
300
301 | def to_dict(self) -> Dict[str, Any]:
"""Return this telemetry policy as a deterministic mapping."""
return {
"enabled": self.enabled,
"sink": self.sink,
"sampling_interval_ms": self.sampling_interval_ms,
}
|
from_dict(data)
classmethod
Build a telemetry policy from a manifest section.
Source code in src/sc_neurocore/privacy/governance.py
| Python |
|---|
303
304
305
306
307
308
309
310
311
312 | @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "TelemetryPolicy":
"""Build a telemetry policy from a manifest section."""
payload = _expect_mapping(data, field="telemetry")
_require_fields(payload, "telemetry", ("enabled", "sink", "sampling_interval_ms"))
return cls(
enabled=payload["enabled"],
sink=payload["sink"],
sampling_interval_ms=payload["sampling_interval_ms"],
)
|